问题描述

我已经创建了一个自定义的 post 类型作为插件,并将其发布到存储库中。其中一个核心功能包括使用特色图像。我已经在 register_post_type()中将 thumbnail 添加到 $supports,所以在 “管理” 面板中显示了该方框。我也挂着 after_setup_theme,并调用 add_theme_support( 'post-thumbnails' ),但我不认为它会影响。

Codex 说 you have to call it from the theme’s functions.php file,但是如果是真的,那么只有用户的主题调用 add_theme_support( 'post-thumbnails' )(这将涵盖所有的帖子类型),如果主题没有调用它,或者只是在特定的类型上调用它,那么它就会有效不工作

有没有人看到这个问题的方法?

最佳解决方案

核心代码中有评论应该改进,但是已经有一段时间了。基本上没有本机功能添加或删除部分功能,仅功能完全。

主题完成后,手动执行此操作 (after_setup_theme 钩子后):

function add_thumbnails_for_cpt() {

    global $_wp_theme_features;

    if( empty($_wp_theme_features['post-thumbnails']) )
        $_wp_theme_features['post-thumbnails'] = array( array('your-cpt') );

    elseif( true === $_wp_theme_features['post-thumbnails'])
        return;

    elseif( is_array($_wp_theme_features['post-thumbnails'][0]) )
        $_wp_theme_features['post-thumbnails'][0][] = 'your-cpt';
}

次佳解决方案

这是我最后使用的,这是 Rarst 的答案的修改版本

public function addFeaturedImageSupport()
{
    $supportedTypes = get_theme_support( 'post-thumbnails' );

    if( $supportedTypes === false )
        add_theme_support( 'post-thumbnails', array( self::POST_TYPE ) );
    elseif( is_array( $supportedTypes ) )
    {
        $supportedTypes[0][] = self::POST_TYPE;
        add_theme_support( 'post-thumbnails', $supportedTypes[0] );
    }
}
add_action( 'after_setup_theme',    array( $this, 'addFeaturedImageSupport' ), 11 );

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。