获取自上次访问以来每个类别中的帖子数量

时间:2016-08-30 作者:Justin W Hall

我可以想出很多方法来做这件事。我在寻找最有效的方法。菜单如下所示:

目录1[num\\u new\\u posts]目录2[num\\u new\\u posts]目录3[num\\u new\\u posts]

^^[num\\u new\\u posts]是新帖子的数量

假设我们为用户上次访问设置了cookie值$_COOKIE[\'lastvisit\'].

我可以为每个菜单/类别做如下操作

$args = array(
 \'category\' => $cat_id,
 \'posts_per_page\' => -1,
 \'date_query\'     => array( \'after\' => $_COOKIE[\'lastvisit\'] ),
 );

$new_posts = get_posts($args);
$num_posts = count($num_posts); // Number of new posts
当然,这是对每个菜单项的另一个查询。有没有办法把这些整合到一个类别中,并且仍然知道每个类别中有多少个新帖子?

2 个回复
SO网友:theodorhanu

改为使用wpdb查询:“选择不同的WPOST。*从$wpdb->posts WPOST LEFT JOIN$wpdb->post wpostmeta wpostmeta wpostmeta.ID=wpostmeta.post\\U ID LEFT JOIN$wpdb->term\\U relationships.object\\U ID)LEFT JOIN$wpdb->term\\U TANCOMY ON($wpdb->term\\U relationships.term\\U TANCOMY ID=$wpdb->term\\U TANCOMY.term\\U ID),其中post\\U date>=$lastvisit}和$wpdb->term\\u分类法。分类=\'类别\';

我没有测试这个,但应该可以工作。我还建议你使用事先准备好的声明

SO网友:Justin W Hall

最后做了一次查询,循环结果并组织。

/**
* Calculates number of posts since a users last visit.
* @return array Organized by category and total.
*/
function denverite_posts_by_cat_since_last_visit(){
session_start();
$post_counts = array();

// Set session value as the time stamp of the users last visit if not yest set.
// use this value to get "new posts" during users sessions. 
if(!isset($_SESSION[\'denveritelastvisit\'])){
    $_SESSION[\'denveritelastvisit\'] = $_COOKIE[\'denveritelastvisit\'];
}

if ($_SESSION[\'denveritelastvisit\']) {

    $lastvisit = date(\'Y-m-d G:i:s\', $_SESSION[\'denveritelastvisit\']);
    $args = array(
        \'posts_per_page\' => -1,
        \'post_type\' => \'post\',
        \'date_query\' => array(
            \'after\' => $lastvisit 
        )
    ); 
    $new_posts = get_posts( $args );

    // all posts since visitors last visit. 
    $post_counts[\'total_posts\'] = count( $new_posts );

    // Loop all posts and count posts for each category.
    foreach ( $new_posts as $new_p ) {
        $cats = get_the_category( $new_p->ID );

        if (is_array( $cats )) {

            foreach ( $cats as $cat ) {

                if ( in_array($post_counts[$cat->slug], $post_counts) ) {
                    $post_counts[$cat->slug] = $post_counts[$cat->slug] + 1;
                } else {
                    $post_counts[$cat->slug] = 1;
                }

            }

        }

    }
 }
 // Overwrites last visit cookie 
 denverite_lastvisit_set_cookie();
 return $post_counts;
}

相关推荐