Can I return and include file in a function for creating shortcode?

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.

Read More

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

Related posts

3 comments

  1. add_shortcode( 'about_us', 'shortcode_about' );
    
    function shortcode_about()
    {
        // Get absolute path to file.
        $file = locate_template('my-file.php');
    
        // Check if file is found.
        if ($file) {
            // Return file contents.
            ob_start();
            include $file;
            return ob_get_clean();
        }
    
        return '';
    }
    
  2. 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>
    
  3. 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>
    

Comments are closed.