Display randomly picked image from Wordpress's page? - php

I would like to display one image at a time on my page, that is picked randomly from the images loaded in this page (from wordpress admin).
I am working with my own theme and I have a "front-page.php" file where I have my function to load the content of my page.
I don't know how to add the random image function to this code.
my PHP code:
<?php get_header(); ?>
<div class="container">
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$images = [];
$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>

Create an array of available images and then choose one at random.
$images = array(
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
);
$image_url = $images[array_rand( $images, 1 )];
echo $image_url;
If you want to include alt text, use a multidimensional array:
$images = array(
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
);
$image = $images[array_rand( $images, 1 )];
echo $image['url'];
echo $image['alt'];
From your response it sounds like you're trying to pull the images from the post content, if so, you'll need to loop through the post's attachments to create the images array. However, there are a number of potential pitfalls with this method. If I were you, I would create a gallery field using Advanced Custom Fields and use that as the source of the image group.
<?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 ) {
// get url from Plugin: WP Gallery Custom Links
$image_href = ( !empty( get_post_meta( $attachment->ID, '_gallery_link_url', true) ) ) ? get_post_meta( $attachment->ID, '_gallery_link_url', true) : '';
// get 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,
'href' => $image_href // url from WP Gallery Custom Links
);
}
}
}
$image = $images[array_rand( $images, 1 )];
?>
<a href="<?php echo $image['href']; ?>" title="<?php echo $image['alt']; ?>">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
<?php
}
?>

Related

How to return the SRC attribute of my secondary image via php

I'm using the following code in wordpress functions.php file in order to retrieve my secondary image (the non-featured one).
function haruki($post_id) {
global $post;
$thumbnail_ID = get_post_thumbnail_id();
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
if ($images) :
foreach ($images as $attachment_id => $image) :
if ( $image->ID != $thumbnail_ID ) :
$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
if ($img_alt == '') : $img_alt = $image->post_title; endif;
$big_array = image_downsize( $image->ID, 'large' );
$img_url = $big_array[0];
echo $img_url;
endif; endforeach; endif; }
Then when I want to output the html for the image I do:
<?php haruki("$post->ID"); ?>
Now I would like to just return the src attribute, but I'm failing by doing this:
$myvariable = haruki( $post_id, false );
How am I supposed to fix this last one in order to make it work correctly?

Get wordpress attachments ID's separated by commas of current post

i have created custom post type named "Person" and i need to get all attachments ID's separated by commas of current post in loop.
Here i have a code that loops the "person" post type posts and code that shows every posts attachments ID's, but thing is that that those ID returns like this "2713271227112710" i need it to return seperated by commas like this "2713,2712,2711,2710"
Here is my code:
<?php
$args = array(
'post_type' => 'person',
'post_status' => 'publish',
'posts_per_page' => 24,
'order' => 'ASC'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-md-4">
<div class="person">
<?php if ( $post->post_type == 'person' && $post->post_status == 'publish' ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) ); ?>
<?php
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$thumbimg = wp_get_attachment_url( $attachment->ID, 'full', false );
$attachment_id = attachment_url_to_postid( $thumbimg );
echo $attachment_id; //here outputs the attachemnts ID's of current post
}
}
}
?>
<?php echo do_shortcode( '[vc_images_carousel images="'.$attachment_id.'" img_size="large" speed="3000" autoplay="yes" hide_pagination_control="yes" hide_prev_next_buttons="yes" wrap="yes"]' ); ?>
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
</div>
<?php endwhile;
wp_reset_postdata(); ?>
Use implode in combination with an array_map, to return an array of IDs, and then convert it to a string of IDs, separated by a comma.
So instead of this:
foreach ( $attachments as $attachment ) {
$thumbimg = wp_get_attachment_url( $attachment->ID, 'full', false );
$attachment_id = attachment_url_to_postid( $thumbimg );
echo $attachment_id; //here outputs the attachemnts ID's of current post
}
Try this:
$attachment_ids = implode(',', array_map(function($attachment){
return $attachment->ID;
}, $attachments));
echo $attachment_ids;

Fetch all woocommerce categories with wp query?

I want to fetch all woocommerce categories with title and images. and after that, I wanted to display them on a front-page. Avoiding foreach loop becuase my front-page design is something like this one.
[enter image description here][1]
<?php
$termSlug = array();
$tax_terms = get_terms('product_cat', array('hide_empty' => '0'));
foreach ( $tax_terms as $tax_term ):
$termSlug[] = $tax_term->slug;
endforeach;
$args = array(
'post_type' => 'product', //Post type event
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $termSlug
)
)
);
// The Query
$the_query = new WP_Query( $args );
//echo '<pre>';print_r($the_query);echo "</pre>";
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#fff'>Nothing Found</h2>
</div>
<?php } echo '</div>';?>
[1]: https://i.stack.imgur.com/A98em.jpg
Following snippet will fetch product categories in WooCommerce. After fetching categories, it will display category name with link and category image in loop.
$product_categories = get_terms( 'product_cat', 'hide_empty=0' );
if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
foreach ( $product_categories as $category ) {
?>
<div class="category-item">
<h4><?php echo esc_html( $category->name ); ?></h4>
<?php
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
?>
<?php if ( $image ) : ?>
<img src="<?php echo esc_url( $image ); ?>" alt="" />
<?php endif; ?>
</div>
<?php
}
}

How can I get the image url in WordPress?

I'm using this code to get all images uploaded to a page and it's working fine but I'd like to use the image urls for a lightbox function and currently I'm getting an img object. Is there any way I can get the image url specifically? I'd like to think it's part of an array. Here's the code I'm using:
<?php
$images = get_children( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 999 ) );
if ( $images ) {
//looping through the images
foreach ( $images as $attachment_id => $attachment ) {
?>
<li>
<a href="*the_img_url*" data-lightbox="lightbox-1" data-title="<?php echo $attachment->post_excerpt; ?>" ><?php echo wp_get_attachment_image( $attachment_id, 'full' ); ?>
</a>
</li>
<?php
}
}
?>
Thank you.
Have you tried
<?php echo wp_get_attachment_url( $attachment_id ); ?>
// $attachment_id is The ID of the desired attachment

Can't change default thumbnail size

I'm making gallery in wordpress and I want to change default thumbnail size but it doesn't work properly. When I set photo as post thumbnail natural size is 150x150 in wordpress media options I changed thumbnail size to 215 143.
in functions I have
add_theme_support( 'post-thumbnails' );
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 1240, 1240 );
}
My gallery query:
<ul id="stage">
<?php
// The Query
$the_query = new WP_Query( array( 'post_type' => 'flota', 'orderby' => 'title', 'order' => 'ASC' ) );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id ( $the_query->ID ), 'thumbnail' );
$full = wp_get_attachment_image_src( get_post_thumbnail_id ( $the_query->ID ), 'full' );
$cats = wp_get_object_terms( $post->ID, 'flota_category' );
$items = array();
foreach ( $cats as $cat ){
$slug = $cat->slug;
$items[] = $slug;
}
$counter = count($cats);
$i = 0;
?>
<li data-tags="<?php
foreach ( $items as $tag ){
if (++$i === $counter ){
$tags = $tag;
}
else{
$tags = $tag . ', ';
}
echo $tags;
}
?>"><img src="<?php echo $thumbnail[0] ?>" width="215" height="143" style="background:#ffffff;"></li>
<?php
endwhile;
?>
</ul>
In functions.php use:
add_theme_support( 'post-thumbnails' );
add_image_size( 'gallery-thumb', 215, 143 );
Your default posts per page will be 10 which is why you can only see 10 images. Override this by changing your query to:
$the_query = new WP_Query( array( 'post_type' => 'flota', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1, ) );
In your query replace $thumbnail and $full with:
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id(), 'gallery-thumb' );
$full = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
Then use a plugin like http://wordpress.org/plugins/regenerate-thumbnails/ to regenerate your thumbnails.
In a loop get_post_thumbnail_id doesn't require the ID to be set but if you do decide to set it elsewhere you were looking for $post->ID rather than $the_query->ID. Set $global $post; as well when using it.

Categories