mardi 12 septembre 2017

Attributing links to random picked image function

I am working on Wordpress and the homepage of my site has a random image function, that picks one image at a time. It picks the images through the media gallery, from the ones that are attached to this page.

My issue is that I need to attribute link to each image, to be able to click on it when we are on the homepage. How can I do that?

I was thinking to have a function that would picks the images directly in the page, instead of having the images attached to the page from the media gallery. The idea would be to load the images directly in my homepage via the WYSIWYG editor and then be able to attribute a link to each.
(My client can't touch php or any code, the result has to be easily settable from Wordpress admin)

Here is the PHP I have:

<?php get_header(); ?>        

<div class="container">
<div class="homepage col-lg-6 col-md-9 col-sm-12 col-xs-12" >

<?php
if ( have_posts() ) {
  $images = [];
  while ( have_posts() ) {
    the_post(); 
    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); 
    $attachments = get_posts($args);
    if ($attachments) {
      foreach ( $attachments as $attachment ) {
        $image_url = ( !empty( wp_get_attachment_url( $attachment->ID ) ) ) ? wp_get_attachment_url( $attachment->ID ) : '';
        $image_alt = ( !empty( get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) ) ) ? get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) : '';
        $images[] = array( 
          'url' => $image_url,
          'alt' => $image_alt
        );
      }
    }
  }
  $image = $images[array_rand( $images, 1 )];
  ?>

    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

    <?php
}
?>

</div>            
</div>



Aucun commentaire:

Enregistrer un commentaire