Can I return and include file in a function for cr

2019-06-07 23:29发布

I am creating a shortcode that will return an bunch of HTML elements. In the beginning it was fine to do it this way:

add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
    return "<div>Some content here.</div>";
}

But now I have to add a lot of content, which I think wouldn't look good as my functions.php will be filled with a lot of this. I was wondering if I can just put it in an external file and include it.

I hoped something like this would work:

add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
    return include 'about-us.php';
}

But of course, it didn't. Any ideas on how to do this properly? Thanks

标签: php wordpress
2条回答
冷血范
2楼-- · 2019-06-07 23:42

Use this

add_shortcode( 'about_us', 'shortcode_about' );
function add_shortcode()
{

    ob_start();
        include( dirname ( __FILE__ ) . '/include.php' );
    return ob_get_clean();
}

and in include.php

<h1>Test Content</h1>
<p>This is the data</p>
查看更多
叛逆
3楼-- · 2019-06-08 00:01

Try below code :

add_shortcode( 'about_us', 'shortcode_about' );

function shortcode_about()
{
   ob_start();
    require_once('about-us.php');
    $data = ob_get_contents();
   ob_end_clean();
   return $data;
}

code in about-us.php

<div>Some content here.</div>
查看更多
登录 后发表回答