简体   繁体   中英

Wordpress: How to implement a for-each loop?

I am trying to get all the images attached to a post. According to the original author of this code , this can be achieved by using a "for-each loop to loop through each of the values in $arrKeys". Does anyone know how to implement this?

PHP

function bdw_get_images() {

$iPostID = $post->ID;
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );

    if($arrImages) {

        $arrKeys = array_keys($arrImages);

        foreach($arrImages as $oImage) {
            $arrNewImages[] = $oImage;
        }

        for($i = 0; $i < sizeof($arrNewImages) - 1; $i++) {
            for($j = 0; $j < sizeof($arrNewImages) - 1; $j++) {
                if((int)$arrNewImages[$j]->menu_order > (int)$arrNewImages[$j + 1]->menu_order) {
                    $oTemp = $arrNewImages[$j];
                    $arrNewImages[$j] = $arrNewImages[$j + 1];
                    $arrNewImages[$j + 1] = $oTemp;
                }
            }
        }

        $arrKeys = array();

        foreach($arrNewImages as $oNewImage) {
            $arrKeys[] = $oNewImage->ID;
        }

        $iNum = $arrKeys[0];

        $sImageUrl = wp_get_attachment_url($iNum);

        $sImgString = '<img src="' . $sImageUrl . '" alt="Thumbnail Image" title="Thumbnail Image" />';

        echo $sImgString;
    }
}

Then I can call the function with bdw_get_images(); .

Try this.

After this line:

foreach($arrNewImages as $oNewImage) {
   $arrKeys[] = $oNewImage->ID;
}

Add this:

$return = array();
foreach( $arrKeys as $key) {
    $sImageUrl = wp_get_attachment_url($key);
    $sImgString = '<img src="' . $sImageUrl . '" alt="Thumbnail Image" title="Thumbnail Image" />';
    $return[] = $sImgString;
}
return $return;

OR , if you want to print out all the images, just add this (and not what's above):

foreach( $arrKeys as $key) {
    $sImageUrl = wp_get_attachment_url($key);
    $sImgString = '<img src="' . $sImageUrl . '" alt="Thumbnail Image" title="Thumbnail Image" />';
    echo $sImgString;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM