There are 3 main issues here
1. The $content
variable
This variable is first seen here:
$content .=get_the_title();
But it seems to have been plucked out of thin air! Computers need to be told explicitly what to do, and there’s no you know what I mean. You have to tell it about things before you use them, or it won’t know what you mean.
In this situation, PHP will generate a warning/notice in your error log about this, then substitute it for ""
or an empty value. This is PHP trying to be helpful, but it will fill your PHP error log very quickly, and it can lead to unexpected problems and strangeness.
2. query_posts
Purge this function from your memory and burn all traces of it with the fire of a thousand suns. There is no good or valid use of this function in day to day use, and it’s a great way to break pagination, slow down pages, and cause problems.
Instead:
- If you want to change the posts WP shows on a page, use the
pre_get_posts
filter. - If you’re happy with the posts WP shows, but want to query an additional set of posts, perhaps for a block or a widget, use
WP_Query
and a standard loop. e.g.:
$q = new WP_Query( [
'post_type' => 'page',
'posts_per_page' => 5,
]);
if ( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
// display this post
}
wp_reset_postdata(); // cleanup after ourselves
} else {
// nothing was found
}
The above query will fetch 5 pages
3. Return Statements and Order
return
means end the function and pass back this value. The code has a super important call to wp_reset_query
, but for some reason it’s been placed after the return
statement, making it impossible to reach for PHP.
As a result, the shortcode exits before the cleanup can happen. But now, the main loop that had just a single post in it, now has all the posts query_posts
dragged in instead, so instead of stopping and continuing to the comments area or the footer, it goes back and loop around.
Remember, order matters. Code is ran from top, to bottom. What the code has done is the equivalent of these shopping instructions:
- buy eggs
- buy milk
- stop reading these instructions and go home
- buy bread
Suffice to say bread will never be bought.
Miscellaneous Notes
- Indent indent! A good code editor will auto-indent for you, don’t leave code unindented, there’s a whole group of bugs and mistakes that are impossible if you indent code
- Don’t hardcode post IDs and category IDs in your code. Since you’re using a shortcode, pass them in as attributes!
- You might want to wrap your titles in tags of some sort so they don’t appear all smushed up together on a single line
- I see you capped your posts to 44, this is good! A lot of people use
-1
to show all, and this can be very bad for performance