Wordpress |将函数/过滤器应用于特定模板(特色图像函数过滤器)


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

我在我的插件中有以下代码:

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

作用:它在第一段之后添加了特色图像,这很好,正是我所需要的。

问题:代码适用于single.php(很好,这就是我需要它的地方),但它也适用于single-training_courses.php(自定义帖子类型的模板)。

所需的帮助:将代码应用于single.php,而不是任何子single模板,如single-training_courses.php

这是可行的吗?如果可以,我怎样才能做到呢?

您可以使用get_post_type() WordPress函数并将代码包装在if语句中,如下所示:

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

您所使用的过滤器the_content,正如您所发现的,将适用于所有内容区域。您需要添加一个条件来检查您所处的帖子类型并相应地进行调整。我的建议是使用is_singular()

add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );
function sqhse_news_featimgmove( $content ) {
    if ( is_singular( '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;
}

处理过滤器时,确保总是返回一个值。例如,如果你有一个条件语句,把返回语句放在它的外面。

https://codex.wordpress.org/Function_Reference/is_singular