2012-03-08 34 views
0

伊夫拼凑下面的代码和它的作品,但感觉太哈克:试图从WordPress的帖子抢影像

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>';} 
    } 
} 

我敢肯定有一个更简单的方式做到这一点,我完全忽略了。

在本质上,当该功能被称为内时,它在它的介质尺寸包裹在一个链接到其大小输出在当前后的最后的图像(附后)。

任何见识将不胜感激。

回答

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>'; 
} 
} 
1

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