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
$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]
)
The variable
$category
is only within the scope of the function and isn’t being passed toget_template_part()
.Try making
$category
global.Also, add
global $category;
to the top of your template file.I had the same problem and I had trouble finding a good answer.
Apparently, setting a variable global like that is not the only solution. Instead, you could just ‘include’ the template into the php after the variables have been set and it works just as intended.
Check here for a better description and an example:
http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/