How to make a shortcode attribute pass into a seperate loop using get_template_part

I’m trying to get a shortcode to execute and pass the attribute value into a separate loop using get_template_part, the shortcode code is like this:

function test( $atts, $content = null ) {
     extract( shortcode_atts( array('category' => '', 'type' => '' ), $atts ) );
    ob_start();  
    get_template_part('loop', $type);  
    $ret = ob_get_contents();  
    ob_end_clean();  
    return $ret; 
}
add_shortcode('test', 'test');

And then in the loop-$type.php file I have

Read More
$cat_id = get_cat_ID($category);
$args=array(
  'cat' => $cat_id,
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => 4,
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
                     <li> /* post stuff */         </li>

    <?php
  endwhile;
}
wp_reset_query();  

But I can’t get the cat_id to use the $category from the shortcode attribute. Does anyone know why the loop isn’t using the shortcode attribute?

It clearly isn’t passing the value on, which means I could make it global, but that is a nasty solution, there must be a clean way to do it?

(I have a post that is trying to execute the shortcode as [test category=random-category-name])

Related posts

Leave a Reply

2 comments

  1. The variable $category is only within the scope of the function and isn’t being passed to get_template_part().
    Try making $category global.

    function test( $atts, $content = null ) {
      global $category;
      extract( shortcode_atts( array('category' => '' ), $atts ) );
      ob_start();
      get_template_part('loop', $type);  
      $ret = ob_get_contents();  
      ob_end_clean();  
      return $ret; 
    }
    add_shortcode('test', 'test');
    

    Also, add global $category; to the top of your template file.