questions

Only target posts and not pages when using the_content() PHP function with WP

Rate this post

I’m having trouble changing the posts display in my WordPress website. So far, the posts can display a title and text content, and I would like to display tags, categories and an image. I added the following code in functions.php and it actually displays the p tags, but around the content, and not in it. Also, it is displayed on all pages of my website, while I just want to add these HTML tags inside the posts.

So,

  • How can I put the tags inside the_content() and only display the custom HTML in posts?

I hope my question is clear, I starting learning PHP a few days ago, sorry!

Thank you so much in advance for you help!

The code :

// Creating a custom function that appends HTML to the content

function bts_add_html_to_content($content) {
    $html_segment = '<p>Text to be added.</p>';
    $content = $html_segment . $content . $html_segment;
    return $content;
  }
  add_filter( 'the_content', 'bts_add_html_to_content', 99);

 

✔️Solution:

// Creating a custom function that appends HTML to the content

function bts_add_html_to_content( $content ) {
    // if not a post then return the $content as is
    if ('post' !== get_post_type()) {
        return $content;
    }

    // must be a post if we get here so lets do something with it
    $html_segment = '<p>Text to be added.</p>';
    $content = $html_segment . $content . $html_segment;
    return $content;
}
add_filter( 'the_content', 'bts_add_html_to_content', 99);

Leave a Reply

Your email address will not be published.

Back to top button