标签: WP判断图片

  • WordPress判断是否有图片并调用出来

    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;?>

    即可调用出图片来