Limit the number of gallery items WordPress outputs - wordpress

<?php echo do_shortcode('[gallery id="25"]'); ?>
That's the code I'm using, I need a way to limit it to 2 items instead of all items. I know there is no native way to do it with the gallery shortcode, but is there a plugin or alternative method I could use?

you can rewrite the gallery shortcode function in your template's functions.php and do something like this
remove_shortcode('gallery');
add_shortcode('gallery', 'parse_gallery_shortcode');
function parse_gallery_shortcode($atts) {
global $post;
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'ids' => '',
'size' => 'medium',
'link' => 'file'
), $atts));
$ids = explode(',', $atts[ids]);
$i = 0;
foreach( $ids as $id ) {
$i++;
if ( $i > 2 ) { break; }
// or replace 2 with how many images you want
$image = get_post($id);
$img = wp_get_attachment_image_src($image->ID, 'post-onephoto');
$largeimg = wp_get_attachment_image_src($image->ID, 'large');
// this is where you output your images the way you want it
$return .= '<img width="400" height="400" src="'.$img[0].'" />';
}
return $return;
}

Related

display Random product thumbnails for specific categories

I am trying to create a dynamic trending category box to be look like below:
// Creating a shortcode that displays a random product image/thumbail
if( !function_exists('custom_shortcode_random_thumbnail') ) {
function custom_shortcode_random_thumbnail( $atts ) {
// Shortcode attributes
$atts = shortcode_atts(
array(
'cat' => '', // product category shortcode attribute
'size' => 'shop_thumbnail', // Default image size
),
$atts, 'random_thumbnail'
);
// Get products randomly (from a specific product category)
$random_post = get_posts( array(
'posts_per_page' => 1,
'post_type' => 'product',
'orderby' => 'rand',
'post_status' => 'published',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['cat'],
) )
) );
// Get an instance of the WC_Product object
$product = wc_get_product($random_post[0]->ID);
// The Product permalink
$product_permalink = $product->get_permalink();
// The Product image. Size can be: 1. 'shop_thumbnail', 2. 'shop_catalog' or 3. 'shop_single'
$product_image = $product->get_image( $atts['size'] );
// The output
return '<div id="random-pic">' . $product_image . '</div>';
}
add_shortcode( 'random_thumbnail', 'custom_shortcode_random_thumbnail' );
}
// Using the shortcode to display a random product image
function get_random_thumbnails_for_reg(){
// Only for page ID 381
if( ! is_page( 381 ) ) return;
echo do_shortcode( "[random_thumbnail cat='clothing']" );
}
add_action('wp_footer', 'get_random_thumbnails_for_reg', 50);
Original Source: random product thumbnail
unfortunately above code is only for one category, what I need is to add 8 Categories box 4 columns in each row, and show random images x 3 for the same category.
I have tried but did not found a better plugin or code for this purpose.
You have to loop your categories and build query for your products in this category.
Here is my solution - [random_thumbnail cat_ids='1,2,3,4,5,6,7,8']
if( !function_exists('custom_shortcode_random_thumbnail') ) {
function custom_shortcode_random_thumbnail( $atts ) {
// Shortcode attributes
$atts = shortcode_atts(
array(
'cat_ids' => '', // category ids
'size' => 'shop_thumbnail', // Default image size
),
$atts, 'random_thumbnail'
);
$args = array(
'orderby' => 'rand',
'hide_empty' => true,
'include' => $atts['cat_ids']
);
$product_categories = get_terms( 'product_cat', $args );
if($product_categories) {
echo '<div class="category-boxes-wrap">';
foreach($product_categories as $cat) {
$args = array(
'posts_per_page' => 3,
'post_type' => 'product',
'orderby' => 'rand,',
'suppress_filters' => true,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $cat->slug,
)
),
);
$product_list = get_posts( $args );
shuffle($product_list); // extra shuffle if you need
if($product_list):
echo '<div class="category-box">';
echo '<div class="category-title">'.$cat->name.'</div>';
echo '<div class="cat-prod-count">'.$cat->count.' '.__('products','textdomain').'</div>';
echo '<div class="product-images">';
foreach ( $product_list as $list ) : setup_postdata( $list );
global $product;
echo '<a href="'.get_permalink( $product->get_id() ).'">';
echo $product->get_image();
echo '</a>';
endforeach;
echo '</div>';
echo '</div>';
endif;
wp_reset_postdata();
}
echo '</div>';
}
}
add_shortcode( 'random_thumbnail', 'custom_shortcode_random_thumbnail' );
}
The css i have used for the result - https://prnt.sc/1yb239g
.category-boxes-wrap {
display: grid;
grid-template-columns: repeat(4,1fr);
}
.category-box {
border: 1px solid rgb(153, 153, 153);
padding:30px;
}
.category-title,
.cat-prod-count {
text-align: center;
}
.product-images {
display: grid;
grid-template-columns: repeat(3,1fr);
grid-column-gap: 10px;
}
.product-images img {
width: 100%;
height: auto;
}

Displaying Image Caption at Functions.php in Wordpress

in our wordpress site we modified image gallery style with using theme functions. We changed div classes, ids to use jquery image slider.
To make this we used this codes on functions.php
add_filter('post_gallery', 'ct_post_gallery', 10, 2);
function ct_post_gallery($output, $attr) {
global $post;
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby'])
unset($attr['orderby']);
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ('RAND' == $order) $orderby = 'none';
if (!empty($include)) {
$include = preg_replace('/[^0-9,]+/', '', $include);
$_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if (empty($attachments)) return '';
// Here's your actual output, you may customize it to your need
$output = "<div id=\"icmimarlikreferans\">\n";
$output .= "<ul id=\"icmimarlikreferansimg\">\n";
// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch the thumbnail (or full image, it's up to you)
// $img = wp_get_attachment_image_src($id, 'medium');
// $img = wp_get_attachment_image_src($id, 'my-custom-image-size');
$img = wp_get_attachment_image_src($id, 'full');
$output .= "<li class=\"item\">\n";
$output .= "<img src=\"{$img[0]}\" width=\"{$img[1]}\" height=\"{$img[2]}\" alt=\"\" />\n";
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
return $output;
}
When we use it without making edits WordPress displaying image captions in single post pages at bottom of images in galleries . But when we use this code at functions.php captions are not displaying. We know the caption codes are missing, in this code block what we are using...
We tried to add caption functions in this codes but we have failed.
We need to display image captions at bottom of images in galleries.
We will love you if you help.

Include excerpt with shortcode

Working with a plugin that provides a shortcode with only a couple of parameters. https://wordpress.org/plugins/radio-station I'm using the [list-shows] shortcode. I would like to also pull in an excerpt of the content, I imagine that would be applicable to a lot of situations and improve my understanding of shortcodes.
I was able to add in the thumbnail to the output, but not the content, which seems to be referred to in the atts of the other shortcodes as 'show_desc'. You can see the output on this page: http://www.kzmuradio.org/kzmu-programs/
Here is the code for the shortcode. Apologies for my ignorance. Learning curve.
/* Shortcode for displaying a list of all shows * Since 2.0.0*/
function station_shortcode_list_shows($atts) {
extract( shortcode_atts( array(
'genre' => '',
'show_desc' => 1
), $atts ) );
//grab the published shows
$args = array(
'numberposts' => -1,
'offset' => 0,
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'show',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'show_active',
'value' => 'on',
)
)
);
if($genre != '') {
$args['genres'] = $genre;
}
$shows = get_posts($args);
//if there are no shows saved, return nothing
if(!$shows) {
return false;
}
$output = '';
$output .= '<div id="station-show-list">';
$output .= '<ul>';
foreach($shows as $show) {
$output .= '<li>' . get_the_post_thumbnail($show->ID, 'thumbnail') . ''.get_the_title($show->ID).'</li>';
$output .= '</li>';
}
$output .= '</ul>';
$output .= '</div>';
return $output;
You can access all the data through $show in your foreach-loop. To see what they contain, you can use print_r():
print_r( $show );
For excerpt and content you can use this:
echo $show->post_excerpt;
echo wpautop( $show->post_content );
See also: https://codex.wordpress.org/Function_Reference/$post

Change Wordpress default gallery output

I am looking to use the Wordpress gallery shortcut but I want to tie the output into the Foundation Orbit plugin (to make a slider). This is the HTML I am looking to output:
<div class="slideshow-wrapper">
<div class="preloader"></div>
<ul data-orbit>
<li>
<img src="img1.png" alt="bla bla bla" />
</li>
<li>
<img src="img2.png" alt="bla bla bla" />
</li>
<li>
<img src="img3.png" alt="bla bla bla" />
</li>
<li>
<img src="img4.png" alt="bla bla bla" />
</li>
</ul>
</div>
Is it possible to put something in functions.php (or similar) to achieve this?
Yes, indeed. Quite a while ago I've found this code and have been using it ever since. It's great to customize WP's default gallery to whatever you want.
There's a filter to post_gallery which you can use to customize all default WP galleries. Here's a sample of the code I use adapted to the template you provided. I've cleared it up as much as possible.
The first part of the function is pretty much gallery attachments handling, so you'll probably just want to change the latter half, the one that determines the output of your gallery template (follow the comments):
add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr) {
global $post;
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby'])
unset($attr['orderby']);
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ('RAND' == $order) $orderby = 'none';
if (!empty($include)) {
$include = preg_replace('/[^0-9,]+/', '', $include);
$_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if (empty($attachments)) return '';
// Here's your actual output, you may customize it to your need
$output = "<div class=\"slideshow-wrapper\">\n";
$output .= "<div class=\"preloader\"></div>\n";
$output .= "<ul data-orbit>\n";
// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch the thumbnail (or full image, it's up to you)
// $img = wp_get_attachment_image_src($id, 'medium');
// $img = wp_get_attachment_image_src($id, 'my-custom-image-size');
$img = wp_get_attachment_image_src($id, 'full');
$output .= "<li>\n";
$output .= "<img src=\"{$img[0]}\" width=\"{$img[1]}\" height=\"{$img[2]}\" alt=\"\" />\n";
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
return $output;
}
Just paste it to your functions.php file and modify to adapt it to your need. I'm pretty sure it'll work for you as it have worked for me :)
Super answer Mathielo.
However, I needed the option of including a caption, so I've modified your code to use the wp_prepare_attachment_for_js() function as that seems to provide the necessary data.
add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr) {
global $post;
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby'])
unset($attr['orderby']);
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ('RAND' == $order) $orderby = 'none';
if (!empty($include)) {
$include = preg_replace('/[^0-9,]+/', '', $include);
$_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if (empty($attachments)) return '';
// Here's your actual output, you may customize it to your need
$output = "<div class=\"slideshow-wrapper\">\n";
$output .= "<div class=\"preloader\"></div>\n";
$output .= "<ul data-orbit>\n";
// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch all data related to attachment
$img = wp_prepare_attachment_for_js($id);
// If you want a different size change 'large' to eg. 'medium'
$url = $img['sizes']['large']['url'];
$height = $img['sizes']['large']['height'];
$width = $img['sizes']['large']['width'];
$alt = $img['alt'];
// Store the caption
$caption = $img['caption'];
$output .= "<li>\n";
$output .= "<img src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"{$alt}\" />\n";
// Output the caption if it exists
if ($caption) {
$output .= "<div class=\"orbit-caption\">{$caption}</div>\n";
}
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
return $output;
}
I know the original question has been answered but I just wanted to share what I've done with the filter snippet in case it helps anyone else. I've enabled Miro Mannino's 'Justified Gallery' jquery plugin http://miromannino.com/projects/justified-gallery/ to work with Wordpress galleries in Wordpress 3.9 ... Here's the code with the changes I made to get it to work... (img size light thumb is my custom thumbnail to preserve image dimensions but keep page load times down.)
// Custom Gallery
add_filter( 'post_gallery', 'my_post_gallery', 10, 2 );
function my_post_gallery( $output, $attr) {
global $post, $wp_locale;
static $instance = 0;
$instance++;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'light-thumb',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$output = apply_filters('gallery_style', "
<style type='text/css'>
#{$selector} {
margin: auto;
}
#{$selector} .gallery-item {
float: {$float};
margin-top: 0px;
text-align: center;
width: {$itemwidth}%; }
#{$selector} img {
border: 0;
}
#{$selector} .gallery-caption {
margin-left: 0;
}
</style>
<!-- see gallery_shortcode() in wp-includes/media.php -->
<div id='$selector' class='gallery galleryid-{$id}'>");
$output = "<div id=\"mygallery\">\n";
$i = 0;
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$output .= "
<{$captiontag} class='gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
}
$output .= "
<br style='clear: both;' />
</div>\n";
return $output;
}
It works a treat. Thanks for sharing the filter - it was just what I was looking for.
So if you want output another string like img title or img desc just use this construction
$title = $img['title'];
This is comment to Super answer Mathielo (second answer), and this universal solution, not only zubr foundation
Little note! If not disabled in admin area, this filter will cause gallery not to be visible in admin area. To avoid this, we can run filters main part inside if statement
add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr)
{
// Disable function in admina area.
if (is_admin()) {
return;
} else {
// put main code in here
}
}

Wordpress 3.5: own gallery with included images doesn't work

I just updated to Wordpress 3.5, but this crashed a little part of my code:
There is a php file, which loads a specific post with its gallery via AJAX.
The code looks like:
<?php
// Include WordPress
define('WP_USE_THEMES', false);
require('../../../../wp-load.php');
$id = $_POST['id'];
// query post with this identifier
query_posts('meta_key=identifier&meta_value='.$id);
if (have_posts()) :
while (have_posts()) : the_post();
// add content
$content = apply_filters('the_content', get_the_content());
echo '<div class="content-inner">'.$content.'</div>';
endwhile;
endif;
?>
The post contains a [gallery] shortcode. I've build my own Wordpress gallery with this code:
remove_shortcode('gallery');
add_shortcode('gallery', 'parse_gallery_shortcode');
function parse_gallery_shortcode($atts) {
global $post;
extract(shortcode_atts(array(
'orderby' => 'menu_order ASC, ID ASC',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'full',
'link' => 'file'
), $atts));
$args = array(
'post_type' => 'attachment',
'post_parent' => $id,
'numberposts' => -1,
'orderby' => $orderby
);
$images = get_posts($args);
print_r($images);
}
This works with all other galleries on my site, but not with the ajax-loaded ones. And it has worked with Wordpress 3.4.
Are there changes in Wordpress 3.5 that I've overlooked?
I figured it out: If you use a gallery with images, which are already uploaded to the media library, the gallery shortcode looks like [gallery ids=1,2,3], what means, that images are only linked (and not attached) to the gallery, so post_type=attachment doesn't work.
Now i'm using regular expressions to get the image IDs:
$post_content = $post->post_content;
preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
$array_id = explode(",", $ids[1]);
It's now possible to pull all the galleries or even a single gallery using the $post->ID and get_post_galleries(). Each gallery will contain the image id list in ids as well as a list of the image urls in src. The gallery object is basically the shortcode arguments so you have access to those as well.
if ( $galleries = get_post_galleries( $post->ID, false ) ) {
$defaults = array (
'orderby' => 'menu_order ASC, ID ASC',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'full',
'link' => 'file',
'ids' => "",
'src' => array (),
);
foreach ( $galleries as $gallery ) {
// defaults
$args = wp_parse_args( $gallery, $defaults );
// image ids
$args[ 'ids' ] = explode( ',', $args[ 'ids' ] );
// image urls
$images = $args[ 'src' ];
}
}

Resources