【问题标题】:WP_Query: Show posts in a certain order for a certain timeWP_Query:在特定时间以特定顺序显示帖子
【发布时间】:2021-04-01 12:08:39
【问题描述】:

我想在我的主页上以post__in 下指定的顺序显示每个帖子一天。这意味着首先 ID 为 3 的帖子应显示至 23:59:59,然后 ID 为 1 的帖子显示 24 小时至 23:59:59,然后是 ID 为 2 的帖子,依此类推。显示所有帖子后,它应该从头开始。有谁知道如何实现这个?

function post_of_the_day( $query_args) {
    global $post;
    
    $query_args = array(
            'post_type'      => 'example_post_type',
            'posts_per_page' => 1,
            'post__in'       => array(3, 1, 2, 4, 7, 6, 5)
        );

     return $query_args;

     }

【问题讨论】:

    标签: php wordpress posts


    【解决方案1】:

    如果您想要一周中的每一天只发布一篇文章,您可以使用 PHP 的 date() function'w' 格式字符串。它返回 0 代表星期日,1 代表星期一,6 代表星期六,等等。然后您可以使用它作为索引从您的数组中找到您想要的一个帖子 ID,并使用 'p' 参数你的WP_Query() arguments

    function post_of_the_day( $query_args ){
        $post_ids = array( 3, 1, 2, 4, 7, 6, 5 ); // List of available ID's
        $id_index = absint( date('w') );          // 0-6 based on day of the week
    
        $query_args = array(
            'p' => $post_ids[$id_index],          // 3 on Sun, 1 on Mon, 5 on Sat
            'post_type' => 'example_post_type'    // Your post type
        );
        
        return $query_args;
    }
    

    如果您只需要一个,则不需要使用 post__in 查询所有 7 个帖子。通常,您希望尽可能少地检索速度、优化和易于维护的信息。

    【讨论】:

    • 非常感谢!这对我帮助很大!这也可以应用于一个月的几周或一年的几周吗?所以显示的不是每天的帖子,而是每周的帖子? @Xhynk
    • 当然,任何你可以得到号码的东西。 date('n') 为您提供月份的 1-12 号,date('W') 为您提供一周中的 1-52 号(从星期一开始),并且涉及更多,但这里是如何获得 "current week of the month as a number" 的答案
    • 完美!非常感谢!
    猜你喜欢
    • 2014-10-09
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多