php - WordPress 如何检查查询是否有帖子

标签 php wordpress woocommerce wordpress-theming custom-wordpress-pages

此代码允许我向连接的用户显示他撰写的文章的列表。但是,我想选择在未编写文章时(列表为空时)显示的消息。

我知道我需要一个 IF 语句,但我真的不知道该把它放在哪里以及使用哪些数据。

我希望没有文章的用户看到“没有文章”。

提前致谢,

这是我的代码:

add_action( 'woocommerce_account_dashboard' , 'recent_posts', 3 );
function recent_posts() {
    if ( is_user_logged_in() ):

    global $current_user;
    wp_get_current_user();
    $author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
    $author_posts = new WP_Query($author_query);
    ?><div id="recentposts">
            
    <ul class="liststylenone">
        
    <?php
    while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
            <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
    <?php           
    endwhile;
    ?></ul><?php
else :
    echo "not logged in";
endif;

?>

最佳答案

当您使用wp_query时,它有一个名为found_posts的属性。在您的 ul 标记之前,我们将检查您的查询中是否有任何帖子。如果没有找到帖子,那么我们将用消息回显 p 标签。就像这样:

add_action('woocommerce_account_dashboard', 'recent_posts', 3);

function recent_posts()
{
  if (is_user_logged_in()) :

    global $current_user;

    $author_query = array('posts_per_page' => '-1', 'author' => $current_user->ID);

    $author_posts = new WP_Query($author_query);

?>
    <div id="recentposts">
      <?php
      if ($author_posts->found_posts) {
      ?>
        <ul class="liststylenone">
          <?php
          while ($author_posts->have_posts()) : $author_posts->the_post();
          ?>
            <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
          <?php
          endwhile;
          ?>
        </ul>
  <?php
      } else {
        echo '<p class="author-no-post-yet">No Articles</p>';
      }
    else :
      echo "not logged in";
    endif;
}

关于php - WordPress 如何检查查询是否有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69247160/

相关文章:

php - woocommerce 中有条件地未设置结帐字段

php - Wordpress SQL查询不同的结果

mysql - 帐单地址 WooCommerce 数据库表

php - 在 WooCommerce 订阅续订订单中设置送货方式

php - 用 php 交换数组值

PHP 将类对象数组绑定(bind)到列表

php - 有条件地删除单个页面的 Storefront 手持菜单

WooCommerce:购物车总数与小计有什么区别?

php - 在 wordpress 的 CSS 中更改选定页面的最有效方法是什么?

php - 依赖下拉列表