I am trying to display all the post on my page but it’s not displaying. I am using the below code and I added the shortcode gridPost on my page. I am getting the only UL LI but not getting the title name.
function getAllPost(){
$postData=[];
$wpb_all_query = new WP_Query(array('post_type'=>'project', 'post_status'=>'publish', 'posts_per_page'=>-1));
if ( $wpb_all_query->have_posts() ) :
$postData[]='<ul>';
while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();
$postData[]='<li><a href="'.the_permalink().'">'.the_title().'</a></li>';
endwhile;
$postData[]='</ul>';
wp_reset_postdata();
else :
$postData[] ='<p>Sorry, no posts matched your criteria.</p>';
endif;
$postData = implode( '', $postData );
return $postData;
}
add_shortcode( 'gridPost', 'getAllPost');
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I see you’re using functions such as the_permalink that echo their values, but don’t return them, yet you’re using them as if they do return values, which they don’t.
Aside from a few exceptions, WP functions that start with the_ don’t return data, they echo it, so you have to use functions such as get_permalink etc
For example:
$foo = the_title(); // <- this is a mistake, it outputs the title
$bar = get_the_title(); // <- this correct, it returns the title
Here, $foo has no value, and the posts title was sent to the browser. $bar however behaves as expected and returns a post title which is assigned to $bar.
Think about it, if the_title prints the title of the post, and you write $title = the_title(); how does it know that you wanted to put it in the variable instead? It doesn’t. Computers do exactly what you say, not what you meant. PHP tries to be helpful and will give it an empty value to avoid a fatal error.
As an aside, you should never set posts_per_page to -1, set it to a super high number you never expect to reach, or add pagination, or you run the risk of timeouts and out of memory issues.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
