Sapphire BSL Sapphire BSL - 3 months ago 9
PHP Question

Wordpress | Apply function/filter to specific template (featured image function filter)

I have the following code in my tweaks plugin.

add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );

function sqhse_news_featimgmove( $content ) {
$content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "<div class='clearfix' style='margin-bottom:10px;'></div>", $content, 1 );
return $content;
}


What it does:
It adds the featured image after the first paragraph which is great and exactly what I need.

The problem: The code applies itself to single.php (great that's where I need it) but it also applies itself to single-training_courses.php (a template for a custom post type).

The help required: Apply the code to single.php and not any sub single templates such as single-training_courses.php

Is this achievable? and if so how may I achieve this?

Answer

You can use get_post_type() WordPress function and wrap your code inside an if statement as follow:

add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );

function sqhse_news_featimgmove( $content ) {
    if( get_post_type() == 'post' ) {
        $content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "<div class='clearfix' style='margin-bottom:10px;'></div>", $content, 1 );
        return $content;
    }
    return $content;
}