wordpress文章頁添加判斷是否有圖片功能,如果有圖片并調用顯示出來。在functions.php添加以下代碼就可以輕松實現:

/**
* Check if there are any images in the article wodepress.com
*/
function is_has_image(){
   if ( is_single () || is_page()) {
    global $post;
    if( has_post_thumbnail() ) return true;
    $content = $post->post_content;
 
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
 
    if(!empty($strResult[1])) return true;
    return false;
}
}

在需要調用的位置添加

<?php if( is_has_image() ) :?>
   ......//function code
<?php endif;?>

即可調用出圖片來