php 基本WP_Query模板,用于显示每个类别的自定义帖子选择

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 基本WP_Query模板,用于显示每个类别的自定义帖子选择相关的知识,希望对你有一定的参考价值。

<?php 
get_header();

$cat_id = get_queried_object_id();
$is_category = is_category($cat_id);
$query_cat_id = $is_category ? $cat_id : null;
$cat_data = get_category($cat_id);

$post_id = $is_category ? $cat_id : get_option('page_for_posts');
//means-- if it's a category, set the ID to that category page so we can get its title etc. 
//otherwise, get the id of the 'blog' page that displays all the posts

    $query_args =
        array(
            'post_type' => 'post',
            'posts_per_page' => 6, //get 6 posts 
            'paged' => 1, //get the 6 most recent posts (aka. the first page full of posts)
            'cat' => $query_cat_id, //from the current category 
            
            //there are like a million filtering options that you can add here
            //see https://developer.wordpress.org/reference/classes/wp_query/
        );

    $query = new WP_Query($query_args);
?>

<div class="posts-archive" >	  

    <div class="posts-archive__content">
        
        <h1 class="page-title">
            <?php
            $page_title = get_the_title($post_id);
            echo $page_title;
            ?> 
        </h1>

        <div class="posts-archive__articles">
            <?php
            //check to see if there are any posts in Wordpress that match our $query_args
            if ($query->have_posts()) :

                $while_index = 0;
                //Loop through the posts that were found by WP_Query, and get crucial info (title, ID, date, url, etc.)
                while ($query->have_posts()) : $query->the_post();
                    
                    $article_id = $post->ID;
                    $title = get_the_title($article_id);
                    $excerpt = get_the_excerpt();
                    $date = get_the_date();
                    $url = get_the_permalink();
                    
                    //now write your 'related posts markup' and echo these variables where you want. 

                endwhile;
            endif;
            ?>
        </div>
    </div>    
</div>

<?php 
    get_footer();
?>

以上是关于php 基本WP_Query模板,用于显示每个类别的自定义帖子选择的主要内容,如果未能解决你的问题,请参考以下文章

WordPress:如何使用 $wp_query 按类别过滤帖子?

查询ACF在自定义分类模板中的WP_Query期间发布对象

Wordpress 类别模板显示来自所有类别的帖子,而不是特定类别的帖子

WP_Query Woocommerce 产品仅属于不同的多个类别 tax_query

自定义 wp_query 上的 Wordpress 分页(next_posts_link)未显示

一次显示一个类别的 Wordpress 档案?