首页 文章

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

提问于
浏览
0

当我尝试在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');
    }

2 回答

  • 0

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

    同样从上下文我不确定你是否想要使用这一行,如果你想计算由$ current_user标识的用户发布的帖子而不是 'post__in' => $current_user 你应该使用 'author' => $current_user

    BTW . 那里根本不需要 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;
     }
    
  • 0
    count($obj_name->posts)
    

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

相关问题