Horje
Need related post short code to display images from custom fields - Wordpress Solution
[Solved] - Need related post short code to display images from custom fields - Wordpress Solution
Try following codes
Hi I found the code that allows a current blog post to show related posts based on it's tags: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/ It works great however instead of a bulleted list with the titles I would like it to display just the thumbnails related to the post (which are pulled in via a custom field in each of these tagged posts) Can anybody help me? Thanks Steve

Solution - 1

I assume you meant to #4 on that page - " Show related posts (uses tags)" Paste this code instead, I added it inside:


function related_posts_shortcode( $atts ) {
 
	extract(shortcode_atts(array(
	    'limit' => '5',
	), $atts));
 
	global $wpdb, $post, $table_prefix;
 
	if ($post->ID) {
 
		$retval = '
<ul class="related">';
 
		// Get tags
		$tags = wp_get_post_tags($post->ID);
		$tagsarray = array();
		foreach ($tags as $tag) {
			$tagsarray[] = $tag->term_id;
		}
		$tagslist = implode(',', $tagsarray);
 
		// Do the query
		$q = "
			SELECT p.*, count(tr.object_id) as count
			FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p
			WHERE tt.taxonomy ='post_tag'
				AND tt.term_taxonomy_id = tr.term_taxonomy_id
				AND tr.object_id  = p.ID
				AND tt.term_id IN ($tagslist)
				AND p.ID != $post->ID
				AND p.post_status = 'publish'
				AND p.post_date_gmt < NOW()
			GROUP BY tr.object_id
			ORDER BY count DESC, p.post_date_gmt DESC
			LIMIT $limit;";
 
		$related = $wpdb->get_results($q);
 
		if ( $related ) {
			foreach($related as $r) {
				$meta_field = get_post_meta($r->ID, $your_custom_field_name_here, true);
				$retval .= '
	<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'"><img src="'.$meta_field.'" alt="'.wptexturize($r->post_title).'" /></a></li>
';
			}
		} else {
			$retval .= '
	<li>No related posts found</li>
';
		}
		$retval .= '</ul>
';
		return $retval;
	}
	return;
}
add_shortcode('related_posts', 'related_posts_shortcode');
Notice the line -
$meta_field = get_post_meta($r->ID, $your_custom_field_name_here, 
If your custom field key is $image for example, you will write - $image instead of - $your_custom_field_name_here Another thing, add to the bottom of youestyle.css that inside your template folder this code:

ul.related {list-style-type:none;}
ul.related li {list-style-type:none; float:left;}
or just -

ul.related {list-style-type:none;}
ul.related li {list-style-type:none;}

Date: 2022-10-21 05:20:10
Category: Wordpress
More for You