此代码允许我向连接的用户显示他撰写的文章的列表。但是,我想选择在未编写文章时(列表为空时)显示的消息。
我知道我需要一个 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/