如何在 Wordpress 主页上仅显示两个类别的 post?

How to show post from just two categories on Wordpress Home page?

首页只需要显示两个类别。谁能帮忙。

在您的 functions.php 文件中粘贴以下代码:

我假设您要显示 ID 为 5 和 9 的两个类别中的类别。

function kiran_home_category( $query ) {
 if ( $query->is_home() && $query->is_main_query() ) {
 $query->set( 'cat', '5,9');
 }
}
add_action( 'pre_get_posts', 'kiran_home_category' );

解释:

kiran_home_category 只是函数的自定义名称。那可以是任何名字。它的工作方式是将一个函数附加到操作挂钩 pre_get_posts。所以在获取帖子之前,函数 kiran_home_category 将被调用。然后在函数内部,我将此处的查询更改为仅加载 ID 为 5 和 9

的类别

您可以使用 WP_Query 获取您的帖子列表,并使用循环显示它

示例:

$the_query = new WP_Query( array( 'category_name' => 'staff,news' ) );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

在 wordpress WP_query 中,category__in 参数用于 select 帖子类别。

<?php 
      $query = new WP_Query( array( 'category__in' => array( 2, 6 ),'post_status'=>'publish','orderby'=>'menu_order','order'=>'Asc' ) );
     if($query->have_posts()):
        echo '<ul>';
        while ( $query->have_posts() ) : the_post();
            echo '<li>' . get_the_title() . '</li>'; 
         endwhile;
        echo '</ul>';
     endif;
   ?>

关于wordpress查询的更多内容click here,可以阅读更多资料

   <?php 
        $args = array( 'post_type' => 'post', 'posts_per_page' => -1,'category_name' => array('Latest News','News')  );
        $loop = new WP_Query( $args );
        if($loop->have_posts()):
    ?><ul>

                <?php
                    while ( $loop->have_posts() ) : $loop->the_post();
                ?>
                    <li> <span class="date"><?php echo get_the_date( 'd F Y');?></span>
                    <h3><?php echo get_the_title();?></h3>
                    <?php echo $description = get_the_content(); ?>
                    </li>

                <?php endwhile;?>
            </ul>

    <?php endif;?>  
    <?php wp_reset_postdata(); ?>

执行以下操作,通常在page.php或single.php中或者如果你想要一个类别的自定义页面,你可以这样做,category-samplecat.php..

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
     $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'category_name' => array('samplecat', 'anothercat'),
        'paged' => $paged
    );

    $arr_posts = new WP_Query($args);

然后执行通常的 if, while 语句..

if($arr_posts->have_posts() ) :
        // Start the loop.
            while ( $arr_posts->have_posts() ) : 
                $arr_posts->the_post();?>

<?php endwhile; 
endif;