【问题标题】:Wordpress: show only top 3 posts from 3 categories in order on front pageWordpress:仅在首页上按顺序显示 3 个类别中的前 3 个帖子
【发布时间】:2015-07-13 08:47:56
【问题描述】:

我想在主页上仅显示 3 个选定类别中的前 3 个帖子。所有分类页面都可以像往常一样显示默认的10个。

这是我尝试过但不起作用的查询:

$the_query= new WP_Query( 'cat=1,2,3&posts_per_page=3' );

还有循环:

if ( $paged == 1 ) {
    get_template_part( 'includes/featured' );
} else {
    $page_title = sprintf( __( 'Recent Posts - page %d', 'opti' ), $paged );
}

if ( have_posts() ) {
?>

<div id="recent-posts" class="<?php echo $recent_colwidth; ?>">
    <h3><?php echo $page_title; ?></h3>

    <ul id="recent-excerpts">
<?php

    while( have_posts() ) {
        the_post();
        if ( $post->ID != $ignore_post ) {
            get_template_part( 'content', 'home-loop' );
        }
    }
?>
    </ul>
<?php
    get_template_part( 'includes/pagination' );
?>

只需要一点帮助就可以将它们组合在一起。如果可能,我还希望帖子在作者旁边显示类别。

【问题讨论】:

  • 您将不得不使用 WP_Query 三次,每个类别一次。

标签: wordpress loops categories posts


【解决方案1】:

在循环函数中添加 $the_query,例如:

$the_query = new WP_Query( 'cat=1,2,3&posts_per_page=3' );
if ( $paged == 1 ) {
    get_template_part( 'includes/featured' );
} else {
    $page_title = sprintf( __( 'Recent Posts - page %d', 'opti' ), $paged );
}

if ( $the_query->have_posts() ) {
?>

<div id="recent-posts" class="<?php echo $recent_colwidth; ?>">
    <h3><?php echo $page_title; ?></h3>
    <author><?php the_author()?></author>
    <div><?php the_category(', '); ?></div>
    <ul id="recent-excerpts">
<?php

    while( $the_query->have_posts() ) {
        the_post();
        if ( $post->ID != $ignore_post ) {
            get_template_part( 'content', 'home-loop' );
        }
    }
?>
    </ul>
<?php
    get_template_part( 'includes/pagination' );
?>

【讨论】:

  • 谢谢,试过了 - 它默认回到所有类别中按发布顺序混合运行的前十名。
  • 可以修改这段代码吗?我可以让它显示 3 个类别并限制帖子,但不是按照我想要的顺序...// Only top 3 posts from selected 3 cats add_action('pre_get_posts', 'ad_filter_categories'); function ad_filter_categories($query) { if ($query-&gt;is_main_query() &amp;&amp; is_home()) { $query-&gt;set('cat','1,2,3'); $query-&gt;set('posts_per_page', 9); } }
  • 似乎没有插件这是不可能的,因为没有办法指定posts_per_category - 它总是使用posts_per_page,这不好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多