Skip to content

Instantly share code, notes, and snippets.

@stoffl6781
Last active April 20, 2021 19:59
Show Gist options
  • Save stoffl6781/c3d897817c625a20a72909ad6778151d to your computer and use it in GitHub Desktop.
Save stoffl6781/c3d897817c625a20a72909ad6778151d to your computer and use it in GitHub Desktop.
Random Image Shortcode - TAG list
add_action( 'init', 'wpd_attachment_taxonomy' );
function random_image($atts) {
$opn = shortcode_atts( array(
'tag' => 'tag',
'description' => 'description',
'caption' => 'caption',
'size' => 'size',
), $atts );
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'tag' => esc_attr($opn['tag']),
'posts_per_page' => 1,
'fields' => 'ids',
'orderby' => 'rand'
);
$image = new WP_Query( $args );
if( $image->have_posts() ){
$image_attributes = wp_get_attachment_image_src( $image->posts[0], esc_attr($opn['size']) );
$image_data = wp_get_attachment( $image->posts[0]);
$return = '<div class="rand-container"> <img src="'.$image_attributes[0].'" alt="'.$image_data['alt'].'" class="rand-image">';
if (esc_attr($opn['caption']) == 'yes'){
$return.='<div class="rand-caption"><p>' . $image_data['caption'] . '</div>';
}
if (esc_attr($opn['description']) == 'yes'){
$return.='<div class="rand-descprition">' . $image_data['description'] . '</div> ';
}
$return.='</div>';
return $return;
}
}
add_shortcode('randimage', 'random_image');
function wp_get_attachment( $attachment_id ) {
$attachment = get_post( $attachment_id );
return array(
'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink( $attachment->ID ),
'src' => $attachment->guid,
'title' => $attachment->post_title
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment