【问题标题】:How to make a shortcode attribute pass into a seperate loop using get_template_part如何使用 get_template_part 将短代码属性传递到单独的循环中
【发布时间】:2013-02-12 17:57:45
【问题描述】:

我正在尝试使用 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 使用短代码属性中的 $category。有谁知道为什么循环不使用短代码属性?

它显然没有传递价值,这意味着我可以将其设为全局,但这是一个讨厌的解决方案,必须有一个干净的方法来做到这一点?

(我有一个帖子试图以[test category=random-category-name] 执行短代码)

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    变量$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; 添加到模板文件的顶部。

    【讨论】:

    • 感谢 Mitchell,但设置的变量不是像这种全球性的坏习惯吗?加载简码的页面将运行大约 3-5 个简码,它们传递不同的类别信息和不同的循环,这让我想避免全局变量,你不同意吗?
    • 我同意,但是因为你把事情放在一起的方式是没有办法避免的。也许考虑使用短代码的替代品,这是一个非常有限的功能。
    • 啊,我明白了,我使用简码的唯一原因是让使用我网站的人可以轻松地在任何页面上运行多个循环,以加载不同类别的最新帖子。你知道我应该研究的其他方法吗?
    【解决方案2】:

    我遇到了同样的问题,但我很难找到一个好的答案。

    显然,像这样设置一个全局变量并不是唯一的解决方案。相反,您可以在设置变量后将模板“包含”到 php 中,并且它可以按预期工作。

    在这里查看更好的描述和示例:

    http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多