【问题标题】:Change wp query depending on year selection根据年份选择更改 wp 查询
【发布时间】:2020-07-07 14:26:52
【问题描述】:

简介

我有一个博客,其中显示了过去 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 可能会更好>?

【问题讨论】:

    标签: php wordpress loops wordpress-theming blogs


    【解决方案1】:

    这将为您提供 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

    【讨论】:

    • 是的,没错。但是如何动态更改年份变量
    • 我更新了我的答案,向您展示如何更改它的一个示例
    • 好的,但是如何在我的选择部分设置 url 查询
    猜你喜欢
    • 2018-01-23
    • 2018-06-07
    • 1970-01-01
    • 2017-01-08
    • 2012-02-24
    • 2018-03-02
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多