I had a request from a reader for a tutorial on how to add a message to every post, but not to archives, categories or the blogroll.
Specifically, they wanted an affiliate disclaimer to appear on every post, below the post title. They were using the Astra theme.
But they didn't want the affiliate disclaimer to appear on the post preview on category etc pages.
How to add text to every post on WordPress Astra
Create a function that hooks into the place in the post you want the text to appear. Use if( is_single() ) {} to only display the text on single posts.
Because I wanted the text to display before the content, but under the post title, the code I used is:
add_action( 'astra_entry_content_before', 'display_disclaimer' );
function display_disclaimer() {
if( is_single() ) {
echo "<p><em>This is a disclaimer</em></p>";
}
}
Add this code to the functions.php file of your child theme.
But what if you wanted to do the opposite?
How to add text on the category page for every post using WordPress Astra
Create a function that hooks into the place in the post you want the text to appear. Use if( is_archive() ) {} to only display the text on the category pages. Or use if( !is_single() ) {} to display the text everywhere that isn't a single post.
The code is almost identical to above:
add_action( 'astra_entry_content_before', 'display_disclaimer' );
function display_disclaimer() {
if( is_archive() ) {
echo "<p><em>This is a disclaimer</em></p>";
}
}
That will add the text to every post, but only on the category pages.
That's very useful thank you. Could this be used to add something like this -
Updated [post_modified_date] : First Published [post_date] [post_edit]
I tried it but couldn't get it to work
It can. The reason it may not have appeared to work is the post modified date is hidden by CSS by default in Astra.
Thank you for this! I have been searching for this answer.
I was using this code successfully for a few weeks, but it doesn't seem to be working anymore. It shows up on every page, not just the single posts.
Make sure it's wrapped in if( is_single() ) {}
I just tested it with the most recent version (3.7.10) and it's working fine. if( is_single() ) {} is a WordPress check, not specific to Astra.
If that doesn't work, feel free to paste your code for this function here and we'll see where it is going wrong.
I figured it out!
Ideally I would like to display my message under (or in) the post meta but before the featured image. (my post format is title/meta, featured image, content.)
But when I use the "astra_entry_content_before" hook, it shows up under the featured image.
Is there a way to add a custom hook location, or do this another way?
For that, hook it into "astra_single_post_meta_after".