scriptK scriptK - 1 month ago 8
PHP Question

php request for images and fill blanks with a default image

I have function that retrieves the images uploaded by each user. The limit per user is 5 images and I want to display a default image to fill the blanks upto 5 if they have less than 5 uploads. How can I achieve this?

function display_images() {
$imgs = get_images();
$html = '<div class="myImages">';

foreach($imgs as $img) {
$html .= '<div class="myImageContainer"><img src="'. $img .'"/></div>';
}
$html .= '</div>';
return $html;
}

function get_images() {
global $current_user;
get_currentuserinfo();

$args = array(
'author' => $current_user->ID,
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => 5,
'orderby' => 'date'
);
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}

Answer

You have to check for current length of total images:

function display_images() {
    $imgs = get_images();
    $html = '<div class="myImages">';

    foreach($imgs as $img) {
        $html .= '<div class="myImageContainer"><img src="'. $img .'"/></div>';
    }
    if (count($imgs)<5) {
        for($i=0; $i<(5-count($imgs)); $i++) {
            $html .= '<div class="myImageContainer"><img src="MY_BLANK_IMAGE_LINK"/></div>';
        }
    }
    $html .= '</div>';
    return $html;
}