Search code examples
phpwordpressshortcode

How to use a template or partial inside a loop in a shortcode WordPress?


To organize better my code, I would like to split some of my HTML in templates. I have a loop inside a shortcode to get the posts:

function nh_shortcode_func($atts) {
    $posts = get_posts_by_category(.......);
    $html .= '';
    foreach ($posts as $post) {
       $post_id = $post->ID;
       $post_title = $post->post_title;
       $post_image = get_field('image', $post_id);

       $html .= **HERE THE CODE OF HTML WITH DIVS AND CLASSES**
    }
    return $html
}

add_shortcode('nh-content', 'nh_shortcode_func');

Instead, put my HTML code inside a variable, I would like to use another file with the HTML structure that I'm going to use to build the posts. Also, I would like to pass the dynamic data to it.

Any ideas?

Thanks.


Solution

  • Just use an include file and it will have access to the variables. Something like:

    function nh_shortcode_func($atts) {
        ob_start();
        include dirname( __FILE__ ) . '/templates/nh_shortcode.php';
        return ob_get_clean();
    }
    
    add_shortcode('nh-content', 'nh_shortcode_func');