php - Wordpress如何检查查询是否有帖子
问题描述
此代码允许我向连接的用户显示他的书面文章列表。但是,我想选择没有写文章时出现的消息(当列表为空时)。
我知道我需要一份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;
}
推荐阅读
- reactjs - npm run build 不起作用 - 没有生成生成,脚本停止而不打印任何内容
- button - 如何在颤动中使用 2 个按钮控制抽屉和 endDrawer
- azure - 长时间运行的 Azure 函数返回 502,但该函数实际上已经完成了工作
- firebase - 如果有firebase用户的信息,我想对passwordhash字段进行加密,我从firebase收到什么json
- php - 如何解决在 LiteSpeed 服务器上找不到 PHP 页面
- abap - 像整数数组一样声明和使用内部表
- compiler-errors - Ionic 4 Admob 集成错误:java.lang.NoClassDefFoundError:(解析失败:Lcom/google/android/gms/internal/zzur;)
- c++ - 如何打印与特定值对应的元素的总和?
- python - TypeError : "errorMessage": "参数应该是类似字节的对象或 ASCII 字符串,而不是 'Binary'",
- if-statement - 如何比较球拍中的字符串