您可以尝试以下操作:
/**
* 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\' );
希望您能将此扩展到您的需要。