2012-03-08 61 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。