This code allows me to display to the connected user the list of his written articles. However, I would like to choose the message that appears when no articles have been written (when the list is empty).
I know that I need an IF statement but I don’t really know where to put it and with which data.
I would like the user who has no articles to see “no articles” written.
Thanks in advance,
Here is my code:
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;
?>
Advertisement
Answer
When you use wp_query, it has a property called found_posts. Right before your ul tag we’re going to check whether there is any post in your query. If there is no post found, then we’re going to echo a p tag with a message. Like so:
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;
}