【问题标题】:How to count posts using WP_Query?如何使用 WP_Query 统计帖子?
【发布时间】:2021-07-01 00:52:03
【问题描述】:

以下代码的“if 子句”有问题。

“Echo”显示正确的数字“3”,但“if count”显示“FOUND one”,这是错误的。

它应该显示“FOUND a lot”,因为计数是 3。

我试过了:

$count_post = $about_preview_query->found_posts;

$posts = get_posts($args);  

但“if 子句”仍然显示一个。

请告诉我如何修复代码?

function profile_url(){
  $user = wp_get_current_user();

  if (!$user->ID) {
    return;
  }

  $args = array(
    'author'         => get_current_user_id(),
    'posts_per_page' => -1,
    'post_type'      => 'project',
    'post_status'    => 'publish'
  );

  $about_preview_query = new WP_Query($args);
  $count_post = $about_preview_query->post_count;

  if (count($count_post) == 0) {
    print "<h1>FOUND None</h1>";
  } elseif (count($count_post) == 1) {
    print "<h1>FOUND one</h1>";
  } else {
    print "<h1>FOUND a lot</h1>";
  }
  echo 'Your Count is: ' . $count_post;
}

谢谢。

【问题讨论】:

  • $count_post里面有什么
  • 我不确定它是否是正确的答案,但自定义帖子有标题、作者和五个 acf 字段
  • 请不要使用Word来制定问题/代码
  • 抱歉,您是什么意思?

标签: php mysql wordpress wordpress-theming


【解决方案1】:

你可以试试

function profile_url() {
    $user = wp_get_current_user();

    if( !$user->ID ){
        return;
    }    

    $args = array(
        'author'         => get_current_user_id(),
        'posts_per_page' => -1,
        'post_type'      => 'project',
        'post_status'    => 'publish'
    );
    
    $about_preview_query = new WP_Query($args);
    $count_post = $about_preview_query->found_posts;

    if ( $count_post == 0 ) {
        print "<h1>FOUND None</h1>"; } 
    elseif ( $count_post == 1 ) { 
        print "<h1>FOUND one</h1>";
    }else {
        print "<h1>FOUND a lot</h1>";
    }

    echo 'Your Count is: ' . $count_post; 
}

【讨论】:

  • 谢谢 Binh :) 我不知道怎么写 if caluse 是从你那里学来的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多