John Davidson

php - Function to display Images based on category on WordPress

0 comments
Message:


Hi There I am writing some PHP code to get some images assigned a custom category given to them via a WordPress Plugin which allows me to assign category's to individual images. The code is below is what I have at the moment


function showFooterImages() {

$footerImagesArray = array(
'post_type' => 'attachment',
'post_status' => 'published',
'posts_per_page' => 4,
'orderby' => 'rand',
'category' => 'footer-images',
);


// Query to get footer images
$footerImagesQuery = new WP_Query( $footerImagesArray );

// The Loop
if ( $the_query-> have_posts() ) {
echo '<ul>';
while ( $footerImagesQuery->have_posts() ) {
$footerImagesQuery->the_post();
echo '<li>' . get_the_post() . '</li>';
}
echo '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();
}

If I replace the


echo '<li>' . get_the_post() . '</li>';

with the following


echo "<p> this is a test </p>"; 

I do get 4 lines of text from the echo showing it is working and if i change the posts_per_page to 6 for example I then get 6 however I am struggling to get the images even displaying and any assistance would be greatly appreciated.



My Answer:
'attachment',
'category_name' => 'footer-images',
'posts_per_page' => 5
);

$footerImagesQuery = new WP_Query($footerImagesArray);

if ($footerImagesQuery->have_posts()) {
while ($footerImagesQuery->have_posts()) {
$footerImagesQuery->the_post();
$image = wp_get_attachment_image(get_the_ID(), 'full');
echo $image;
}
}

wp_reset_postdata();
}

add_shortcode('footer_images', 'showFooterImages');

?>

This code defines a function called showFooterImages that queries the WordPress database for images with the category 'footer-images' assigned to them. It then loops through the results and displays the images using the wp_get_attachment_image function. Finally, it registers a shortcode [footer_images] that can be used in WordPress posts or pages to display the images.

Rate this post

4 of 5 based on 3106 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us