【问题标题】:Wordpress Foreach, Pass Category ID variable to Display Posts?Wordpress Foreach,将类别 ID 变量传递给显示帖子?
【发布时间】:2014-05-26 09:17:55
【问题描述】:

我正在尝试显示:

  1. 链接的类别标题
  2. 类别说明(修剪为自定义长度)
  3. 类别“阅读更多样式链接
  4. 该类别中的帖子标题列表,链接到帖子

我已经使用 Foreach 循环完成了任务 1-3,但我似乎无法通过我过去使用的方法在每个类别中显示帖子标题。主要是我不知道如何运行 get_posts();或类似的函数,在 $args 数组中有一个变量。

我觉得这确实需要使用 foreach 循环来完成,因为我正在使用 20 多个类别。我已经尝试与第 3 方简码插件混合/匹配,但由于“wp 操作的顺序”,这个想法也失败了:(任何帮助都将非常感谢,因为我在过去 3 年一直在旋转我的轮子-4 小时。

源代码→ http://pastebin.com/Mm9u27dF

代码输出:

<p class="topic-link-heading"><a href="http://localhost:81/wordpress/?cat=3" id="topic-link">Understanding Democratic Governance and Market Economy</a></p><p class="topic-list">There is an ongoing debate in academic circles and among practitioners on the linkages between democratic governance and market economies. It has intensified in light of transitions taking place after the fall of the Berlin Wall. Amidst expectations that all … <a href="http://localhost:81/wordpress/?cat=3" > Topic Overview →</a></p>3

请注意

显示“3”只是为了表明类别 ID 变量输出正确

【问题讨论】:

    标签: php wordpress foreach wordpress-theming


    【解决方案1】:

    据我了解,您希望显示特定类别的帖子,但您在执行此操作时遇到了问题。

    您正在遍历类别,我认为您只需要使用query_posts 函数来查询具有特定类别的相关帖子(我已从官方文档中获取代码):

    <?php
     $post_args = array(
    'posts_per_page'   => 5,
    'offset'           => 0,
    'category'         => $category->term_id, //in your case.
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'include'          => '',
    'exclude'          => '',
    'meta_key'         => '',
    'meta_value'       => '',
    'post_type'        => 'post',
    'post_mime_type'   => '',
    'post_parent'      => '',
    'post_status'      => 'publish',
    'suppress_filters' => true );
    
    // The Query
    query_posts( $post_args );
    
    // The Loop
    while ( have_posts() ) : the_post();
        echo '<li>';
        the_title();
        echo '</li>';
    endwhile;
    
    // Reset Query
    wp_reset_query();
    ?>
    

    要检查帖子是否被查询,请执行以下操作:

     $relevant_posts = query_posts( $post_args );
     print_r($relevant_posts); //Should print an associated array with the posts.
    

    因此,您可以使用您在for 循环中获取的特定类别填充args 变量,然后只查询帖子。获得帖子后,您可以轻松地参考链接。这个documentation 在循环浏览帖子时也可能会派上用场。

    【讨论】:

    • 传入 $post_args 数组 'category' => '$category' 只显示每个类别的所有帖子,这让我相信它没有被评估。如果有特殊的语法,我猜你会说在将变量放入数组之前渲染它?
    • @MichaelRoach,它只是一个模板。变量 category 将设置为您要获取的类别的 id。
    • 我已使用您获取的变量中更新的类别 ID 编辑了我的答案。您不必用单引号括起来。它将被视为一个字符串,因此尝试获取类别为'$category' 的帖子。还可以尝试将查询到的帖子放入变量中并打印出来,以调试您遇到的任何错误。
    • 我试过带/不带引号,但我仍然得到相同的结果,这真的难倒我。正在查询这些帖子,但我认为该数组正在发生一些时髦的事情。打印数组最后列出了每个类别中所有已发布的帖子信息。
    • 解决方法:query_posts(array('category__and'=>$test));完整代码:pastebin.com/Xr4rWJT3 我也引用了wordpress.org/support/topic/…。我当时想,这个“__and”运算符是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多