特定帖子的特色图像中的自定义字段

时间:2016-12-27 作者:Prifulnath

我已经在我的特色图片中添加了一个自定义文本区域,仅用于发布,使用以下代码。

function add_featured_description( $content ) {
    global $post;
    $small_description = get_post_meta( $post->ID,\'thumbnail_description\', true ) !== \'0\' ? get_post_meta( $post->ID,\'thumbnail_description\', true ) : \'\';
    global $pagenow;
    if (is_admin() && ($pagenow == \'post-new.php\' || $pagenow == \'post.php\') && ( get_post_type()==\'post\' ) ) {
      return $content .= \'<div id="thumb_desc_container">
                            <textarea name="thumbnail_description" id="thumbnail_description" rows="4" style="width:100%;">\'.$small_description.\'</textarea>
                            <p class="hide-if-no-js howto" id="set-post-thumbnail-desc">Enter the image description.</p>
                          </div>\';
    } else{
      return $content;
    }
}
add_filter( \'admin_post_thumbnail_html\', \'add_featured_description\');
它工作得很好!!!此代码仅在POST中显示额外的文本区域。但是当我选择了一张特色图片else 执行部件(仅返回特征图像)。添加图像时$pagenow 包含admin-ajax.phpget_post_type() 为空。全局变量$post 生成空值。我现在该怎么办?

1 个回复
最合适的回答,由SO网友:birgire 整理而成

请注意,还有其他输入参数可用于admin_post_thumbnail_html 过滤器回调,即$post->ID$thumbnail_id:

/**
 * Filters the admin post thumbnail HTML markup to return.
 *
 * @since 2.9.0
 * @since 3.5.0 Added the `$post_id` parameter.
 * @since 4.6.0 Added the `$thumbnail_id` parameter.
 *
 * @param string $content      Admin post thumbnail HTML markup.
 * @param int    $post_id      Post ID.
 * @param int    $thumbnail_id Thumbnail ID.
 */
 return apply_filters( \'admin_post_thumbnail_html\', $content, $post->ID, $thumbnail_id );
适用于_wp_post_thumbnail_html() 作用

下面是一个示例,通过使用$post->ID 改为输入参数:

function wpse250432_add_featured_description( $content, $post_id, $thumbnail_id ) {

    $small_description = get_post_meta( $post_id, \'thumbnail_description\', true );

    // Target only the \'post\' post type
    if ( \'post\' === get_post_type( $post_id ) ) 
      $content .= \'<div id="thumb_desc_container">...</div>\'; // Edit

    return $content;
}
add_filter( \'admin_post_thumbnail_html\', \'wpse250432_add_featured_description\', 10, 3 );
如果确实需要将此筛选限制为post.phppost-new.php 屏幕和get-post-thumbnail-html ajax调用,然后可以添加如下检查:

if( 
       ! did_action( \'load-post.php\' ) 
    && ! did_action( \'load-post-new.php\' ) 
    && ! did_action( \'wp_ajax_get-post-thumbnail-html\' )
)
    return $content;
但我假设你打电话给“私人”_wp_post_thumbnail_html() 其他核心功能?但这些(下划线)private functions are not intended for use by plugin and theme developers, but only by other core functions.

相关推荐

WooCommerce:Pre_Get_Posts中的复杂查询

我想在获取产品时添加一个复杂的过滤。我有一些产品,其中一些链接到自定义帖子类型</此自定义帖子类型有一个转发器字段根据cookie的不同,我应该只获取在此转发器字段中具有该值的产品,我知道我可以使用:add_filter( \'pre_get_posts\', \'fwp_archive_per_page\' ); 我知道我可以像这样设置额外的元查询:$query->set( \'meta_query\', array( \'relation\' => \'