我正在尝试使用get_template_part来执行短代码并将属性值传递到单独的循环中,短代码代码如下:
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');
然后在loop- $ type.php文件中我有
$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();
但我无法让cat_id使用shortcode属性中的$ category。有谁知道为什么循环没有使用短代码属性?
显然没有传递价值,这意味着我可以将其全局化,但这是一个令人讨厌的解决方案,必须有一个干净的方法来做到这一点?
(我有一篇文章试图将短代码作为[test category=random-category-name]
执行)
答案 0 :(得分:0)
变量$category
仅在函数范围内,不会传递给get_template_part()
。
尝试将$category
设为全球。
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');
另外,将global $category;
添加到模板文件的顶部。
答案 1 :(得分:0)
我遇到了同样的问题,但我找不到合适的答案。
显然,设置这样的变量全局不是唯一的解决方案。相反,你可以只包括&#39;变量设置完成后,模板进入php,并且按预期工作。
点击此处查看更好的说明和示例:
http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/