【问题标题】:Trying to grab an Image from a Wordpress Post尝试从 Wordpress 帖子中获取图像
【发布时间】:2012-03-08 01:51:46
【问题描述】:

我拼凑了以下代码,它可以工作,但感觉太hacky了:

function get_my_img() {
if($imgs = get_posts(array(
    'post_parent' => get_the_ID(),
    'post_type' => 'attachment',
    'numberposts' => 1,
    'post_mime_type' => 'image',
    'orderby' => 'menu_order',
    'order' => 'DESC'
    ))){
foreach($imgs as $img) {
    $img_med = wp_get_attachment_image($img->ID,'medium');
    }
foreach($imgs as $img) {
    $img_larg = wp_get_attachment_image($img->ID,'large');
    }
if (preg_match('/<img.+?src(?: )*=(?: )*[\'"](.*?)[\'"]/si', $img_larg, $img_r)){
    echo '<a class="myimage" href="' . $img_r[1] .'">' . $img_med .'</a>';} 
    }
}

我很确定有一种更简单的方法可以做到这一点,但我完全忽略了。

本质上,当在循环中调用此函数时,它会输出当前帖子中的最后一张图片(附加),其中等大小包含在一个链接中它的尺寸。

任何见解将不胜感激。

【问题讨论】:

    标签: wordpress wordpress-theming


    【解决方案1】:

    做起来更简单:

    function get_my_img() {
    if($imgs = get_posts(array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment',
        'numberposts' => 1,
        'post_mime_type' => 'image',
        'orderby' => 'menu_order',
        'order' => 'DESC'
        ))){
    
        $img_med = wp_get_attachment_image($imgs[0]->ID,'medium');
        $img_larg = wp_get_attachment_image_src($imgs[0]->ID,'large');
    
        echo '<a class="myimage" href="' . $img_larg[0] .'">' . $img_med .'</a>';
    } 
    }
    

    【讨论】:

      【解决方案2】:

      preg_match() 东西不是必需的。如果您打印 $img_med 和 $img_larg,您会看到它们是数组,包含三个元素:图像的路径、宽度和高度。所以你可以用这些输出你需要的html。

      【讨论】:

        猜你喜欢
        • 2016-05-04
        • 2013-07-27
        • 1970-01-01
        • 2015-05-10
        • 2012-08-29
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        • 2013-10-09
        相关资源
        最近更新 更多