簡體   English   中英

通過元鍵wp_query

[英]wp_query by meta key

我編寫了此循環,以獲取過去30天內獲得最多視圖的帖子(將視圖計數作為自定義元鍵記錄到數據庫中)。

但是,在仔細考慮之后,我不確定我是否會以“正確”的方式,或者至少是最合乎邏輯的方式進行操作。

<?php 

                // Create a new filtering function that will add our where clause to the query
                function filter_where( $where = '' ) {
                    // posts in the last 30 days
                    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
                    return $where;
                }

                add_filter( 'posts_where', 'filter_where' );

                    $popularpost = new WP_Query( array( 
                'posts_per_page' => 33, 
                'meta_key' => 'wpb_post_views_count', 
                'orderby' => 'meta_value_num', 
                'order' => 'DESC'  

                ) );


                remove_filter( 'posts_where', 'filter_where' ); ?>


                <?php if ( $popularpost->have_posts() ) : ?>



                <?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?>

            <article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
                        <?php the_title (); ?>
            </article> <!-- end div post -->


                <?php endwhile; wp_reset_query(); ?>

                <?php endif; ?>

因此,如您所見,我將日期范圍限制為30天,按meta_value_num排序帖子,並獲得33個帖子。

因此,從邏輯上講,最近30天內發布的任何帖子都將按照其擁有的觀看次數在此顯示。 讓我思考的是,當我創建一個頁面以拉近過去7天的33個最受歡迎的帖子時,它們是相同的。 明顯。

因此,我認為我想做的是獲取過去30天/ 7天內他們獲得的觀看次數,而不是在這些日期范圍內發布的帖子。

我在沿着正確的方向思考嗎? 如果是這樣,您能給我任何想法嗎?

如果您運行的是WordPress 3.7或更高版本,則現在可以使用date_query 未經測試,但您的查詢將類似於:

$popularpost = new WP_Query( array(
    'posts_per_page' => 33,
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'date_query' => array(
      array(
        'after' => '1 month ago',
        'column' => 'post_date_gmt', //posted within one month
      ),
    )
    )
);
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";

strtotime('30 days')=現在+ 30天

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM