I just try to add some content at the bottom of each posts from a specific category but the content is added in all posts. I use a hook in GeneratePress theme. I don’t understand why it is not working. I’m not a pro with PHP to be honest (maybe it’s obvious 😅). Thanks
function bottom_post_message() {
$query = new WP_Query( array( 'cat' => '3,5' ) );
if(is_single() && is_category($query)) {
echo '<p>Hello World!</p>';
}
}
add_action( 'generate_after_entry_content', 'bottom_post_message' );
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 just try to add some content at the bottom of each posts from a
specific category but the content is added in all posts.
Are you sure your “Hello World!” text is added in all posts? Because is_single() && is_category() would never be true because a query can’t be for a single post and a category archive at the same time. 🤔
So if you want to check if the current (or a specific) post is within a specific category, you would instead use in_category() like so:
function bottom_post_message() {
// Check if the current request/URL is for a single post, and that the post is
// in any of the categories passed to in_category().
if ( is_single() && in_category( array( 3, 5 ) ) ) {
// your code
}
}
And note that you incorrectly used is_category() — you should pass the category IDs and not an instance of WP_Query.
See the documentation for is_single() and is_category() for more details about the functions (what they do, correct syntax, etc.).
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