paullacey78
12/14/2017 - 4:28 PM

Related posts shortcode

<?php 

function ('pad_related_posts_shortcode') {

  // get the custom post type's taxonomy terms
  $custom_taxterms = wp_get_object_terms( $post->ID, 'TAXONOMY_SLUG', array('fields' => 'ids') );
  
  // arguments
  $args = array(
  'post_type' => 'TAXONOMY_SLUG',
  'post_status' => 'publish',
  'posts_per_page' => 2,
  'orderby' => 'rand',
  'tax_query' => array(
      array(
          'taxonomy' => 'TAXONOMY_SLUG',
          'field' => 'id',
          'terms' => $custom_taxterms
      )
  ),
  'post__not_in' => array ($post->ID),
  );
  
  // Run the query
  $related_items = new WP_Query( $args );
  
  // loop through query
  if ($related_items->have_posts()) :
  	// open wrappers
  	$output = '<div>';
  		while ( $related_items->have_posts() ) : $related_items->the_post();
  
  			$output .= '<div class="related-featured-image">';
      		$output .= get_the_post_thumbnail();
      	$output =. '</div>';
      
        $output =. '<div class="related-title">';
        	$output =. '<a href="'.get_the_permalink().'">'.get_the_title("<h3>").'</a>';
        $output =. '</div>';
  
  		endwhile;
  	// close wrappers
  	$output =. '</div>';
  endif;
  
  return $output;
  
  // Reset Post Data
  wp_reset_postdata();
}

add_shortcode('pad_related_posts', 'pad_related_posts_shortcode');