How to display the post using a shortcode in WordPress?

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.