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');
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');
Share
Improve this question
edited Aug 9, 2020 at 19:25
user9437856
asked Aug 9, 2020 at 17:58
user9437856user9437856
1117 bronze badges
1 Answer
Reset to default 0I 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.