如何获取wordpress中自定义查询的帖子计数?

问题描述 投票:0回答:2

当我尝试获取 WordPress 中自定义查询的帖子计数时,我收到以下错误作为输出。

Warning: array_map(): Argument #2 should be an array in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918

Warning: implode(): Invalid arguments passed in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918
0

以下是我的功能:

   if( !function_exists('my_likes') ){
    function my_likes() {
      global $current_user;
      $current_user = get_current_user_id();
       // The Query
      $args = array(
        'meta_key' =>'likes_count',
        'orderby' => 'date',
        'post__in' => $current_user
       );
       $obj_name = new WP_Query($args);
       $num = $obj_name->post_count;
       print $num;
       }
     add_action('my_likes', 'my_likes');
    }
php wordpress implode array-map
2个回答
0
投票
count($obj_name->posts)

这是一种计算用户帖子数量的低效方法,因为它获取了所有帖子对象。也许只使用原始 SQL 查询


0
投票

'post__in' => $current_user
行不正确,post__in应该是一个数组,所以如果你想像这样使用它,你需要这样做
'post__in' => array($current_user)

另外,从上下文来看,我不确定您是否想使用这一行,如果您想计算由 $current_user 标识的用户发布的帖子,那么您应该使用

'post__in' => $current_user
 而不是 
'author' => $current_user

顺便说一句。根本不需要

global $current_user;
行,它会过度扭曲全局 $current_user 值。

我认为完整的代码应该是这样的

function my_likes() {
  $current_user = get_current_user_id();
   // The Query
  $args = array(
    'meta_key' =>'likes_count',
    'orderby' => 'date',
    'post__in' => array($current_user),
    // or 'author' => $current_user
   );
   $obj_name = new WP_Query($args);
   $num = $obj_name->post_count;
   print $num;
 }
© www.soinside.com 2019 - 2024. All rights reserved.