Blog

Inside the Minds of the Machine

WordPress Tips and Tricks

Replacing the default WordPress gallery shortcode

The built-in WordPress gallery view isn’t all that exciting. There are limited features and no way to customize the setup of the photos beyond how many columns you want. With a little know how you can completely replace the front-end view for your photo galleries.

The first step is to remove the current gallery short code and replace it with your own.

remove_shortcode('gallery');
add_shortcode('gallery', 'my_new_gallery_function');

Now you can register a new function to handle the gallery short code. Here’s some starter code to get you started:

function my_new_gallery_function($atts) {
	
	global $post;
	$pid = $post->ID;
	$gallery = "";

	if (empty($pid)) {$pid = $post['ID'];}

	if (!empty( $atts['ids'] ) ) {
	   	$atts['orderby'] = 'post__in';
	   	$atts['include'] = $atts['ids'];
	}

	extract(shortcode_atts(array('orderby' => 'menu_order ASC, ID ASC', 'include' => '', 'id' => $pid, 'itemtag' => 'dl', 'icontag' => 'dt', 'captiontag' => 'dd', 'columns' => 3, 'size' => 'large', 'link' => 'file'), $atts));
		
	$args = array('post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'orderby' => $orderby);

	if (!empty($include)) {$args['include'] = $include;}
	else {
	   	$args['post_parent'] = $id;
		$args['numberposts'] = -1;
	}

	if ($args['include'] == "") { $args['orderby'] = 'date'; $args['order'] = 'asc';}

	$images = get_posts($args);
		
	foreach ( $images as $image ) {
		//print_r($image); /*see available fields*/
		$thumbnail = wp_get_attachment_image_src($image->ID, 'large');
		$thumbnail = $thumbnail[0];
		$gallery .= "
			<figure>
				<img src='".$thumbnail."'>
				<figcaption>
					<div class='img-title'>".$image->post_title."</div>
					".$image->post_excerpt."
				</figcaption>
			</figure>";
	}
	
	return $gallery;
}

From here you should be able to structure the HTML output of your gallery short code in whatever layout you need. Here’s an example of a fully styled gallery I created by re-registering the gallery short code.


IEG and WNET are not responsible for your or any third party’s use of code from this tutorial. All the information on this website is published in good faith “as is” and for general information purposes only; WNET and IEG make no representation or warranty regarding reliability, accuracy, or completeness of the content on this website, and any use you make of this code is strictly at your own risk.