首页 > 解决方案 > 根据年份选择更改 wp 查询

问题描述

介绍

我有一个博客,我在其中显示过去 365 天内的最新帖子,并且只显示 100 个帖子。我还可以让用户选择年份(这是我目前正在做的事情)。

问题

我怎样才能拥有它,所以当用户选择不同的年份(从选择中)时,查询设置为显示该年份的帖子并删除 100 个帖子限制并显示这是我的博客页面。

我的查询

<?php
// gets info
$current_category = get_queried_object('post');
//$current_user =get_the_author_posts();

// the query
$wpb_all_query = new WP_Query(array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'cat' => $current_category->term_id,
//    'author' =>  $current_user,
//    'tag' => '',
    'posts_per_page' => 100,
    'date_query' => array(
        array(
//            'year'  => '2019',
            'after' => '-365 days',
            'column' => 'post_date',
        )
    )
));

我的选择(年)

 <select style="top: -4px;"
                class=" btn-link col-12"
                name="archive-dropdown"
                onChange='document.location.href=this.options[this.selectedIndex].value;'>
            <?php wp_get_archives('type=yearly&format=option'); ?>
        </select>

我的博客页面

<?php
require "settings.php";
if ($wpb_all_query->have_posts())
    :while ($wpb_all_query->have_posts())
    :$wpb_all_query->the_post();
    ?>
content
<?php endwhile; ?>
<?php endif; ?>

我在查询中尝试了一条语句,但看不到如何选择年份,但是如果我根据选项将年份设置为 var,那可能会更好>?

标签: phpwordpressloopswordpress-themingblogs

解决方案


这将为您提供 1999 年的所有帖子(不限于 100 个)。更改$yearToLookFor为您需要的年份。

<?php
//here is from a $_GET parameter
$yearToLookFor = $_GET['year'];

 // gets info
 $current_category = get_queried_object('post');
//$current_user =get_the_author_posts();

// the query
$wpb_all_query = new WP_Query(array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'cat' => $current_category->term_id,
//    'author' =>  $current_user,
//    'tag' => '',
    'date_query' => array(
        array(
            'year'  => $yearToLookFor,

        )
    )
));

在此示例中,年份来自 url 查询,如下所示:https://yourwebiste.zyx/?year=1999


推荐阅读