如何仅使用Post_Title检索特色图像缩略图?

时间:2014-08-19 作者:The Fourth Hamster

是否可以仅使用post\\u标题名获取文章的Wordpress特色图片?我知道这可以通过post->ID来完成,但我只有post\\u标题名称可以使用,这是循环之外的。

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

您可以尝试以下操作:

/**
 * Get the featured image by post title (Simple version)
 * 
 * @see    http://wordpress.stackexchange.com/a/158344/26350
 * @param  string $title   Post title
 * @param  mixed  $size    Featured image size
 */

function get_featured_image_by_post_title_wpse_simple( $title = \'\', $size = \'thumbnail\' )
{
    $obj  =  get_page_by_title( $title, OBJECT, \'post\' );
    return ( is_object ( $obj ) ) ? get_the_post_thumbnail( $obj->ID, $size ) : \'\';
}
或此扩展版本:

/**
 * Get the featured image by post title (Extended version)
 *
 * @see    http://wordpress.stackexchange.com/a/158344/26350
 * @param  string $title     Post title
 * @param  mixed  $size      Featured image size
 * @param  string $post_type Post type
 * @param  string $default   Default image url
 * @return string $html      Featured image HTML
 */

function get_featured_image_by_post_title_wpse_ext( $title = \'\', $size = \'thumbnail\', $post_type = \'post\', $default = \'\' )
{
    // Search by post title:
    $obj  = get_page_by_title( $title, OBJECT, $post_type );

    // Featured image:
    if( is_object( $obj ) && has_post_thumbnail( $obj->ID ) )
        $html = get_the_post_thumbnail( $obj->ID, $size );
    else     
        $html = sprintf( \'<img src="%s" alt="">\', esc_url( $default ) );

    return $html;
}
何处使用get_page_by_title() 按标题定位文章。

Usage examples:

 // Simple:
 echo get_featured_image_by_post_title_wpse_simple( \'Hello World!\', \'large\' );

 // Extended:
 echo get_featured_image_by_post_title_wpse_ext( \'My Car\', \'full\', \'post\', \'/car.jpg\' );
希望您能将此扩展到您的需要。

结束

相关推荐

Print Post Parent Title

我试图在页面上打印帖子的父标题以及该页面的帖子标题。这就是我的内容页。php模板当前呈现页面标题。the_title( \'<header class=\"entry-header\"><h1 class=\"entry-title\">\', \'</h1></header><!-- .entry-header -->\' ); 我意识到我可以通过这样做来检索帖子的父标题:$parent_title = get_the_title($