Inès Rose
Inès Rose

Reputation: 11

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

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,

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);

Upvotes: 1

Views: 470

Answers (1)

mikerojas
mikerojas

Reputation: 2338

Not totally sure what you want for the "in it" part but I can help with conditionally applying your code to posts only... See below:

// 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);

Upvotes: 1

Related Questions