繁体   English   中英

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

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

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

您可以使用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
}

在您的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的类别

在wordpress WP_query中, category__in参数用于选择带有帖子的类别。

<?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查询的更多信息, 请单击此处 ,您可以阅读更多信息。

   <?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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM