dtrgqjcd877528 2013-02-12 17:57
浏览 53

如何使用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

$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])

  • 写回答

2条回答 默认 最新

  • dqaq59269 2013-02-12 18:14
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法