Write Custom Wordpress Shortcode to use Parameters

So recently I needed to write a Wordpress Shortcode in my Child Theme's functions.php file which allows me to specify certain parameters or variables for a Gallery.

If the post did not have any photos for a gallery section it would show a standard set of photos I saved on the server.

If the post did have photos for the Gallery I would declare the shortcode with two additional parameters, one for total number of photos (because this runs in a PHP While Loop) and the other for the directory name where the photos are saved.

In your functions.php file in your Wordpress Child Theme add this Function (change the names to your preference)

function ListingGallery($atts) {

  $atts = shortcode_atts( array(
        'totalpics' => '10',
'imgdir' => 'general',
  ), $atts );
  
  ob_start();
  
  $output_string = '
<h1 class="entry-title">Gallery</h1>
<div align="center">
<ul>
  ';

  $counter = 1; //Starting pic
  $totalpics = $atts['totalpics'];
  $imgdir = $atts['imgdir'];
  while ($counter <= $totalpics) { 
$output_string .= "
<li><img src=\"/homes/$imgdir/$counter.jpg\" /></li>
";
$counter ++;
  }
  
  $output_string .= '
</ul>
</div>
  ';
  
  ob_end_clean();
  return $output_string;

}

add_shortcode('listing_gallery', 'ListingGallery');

In this function I declare the shortcode by typing [listing_gallery] in post. 

To specify the total number of photos and directory I change that shortcode to [listing_gallery totalpics="15" imgdir="custom-post-photos-folder-name"]

Comments

Popular posts from this blog

How to Display Custom Wordpress Header with Google Analytics Site Tage and Adwords Site Tag