Skip to content

Snippet: Related Posts by Specific ID’s

Important: Instead of using a snippet like this we would highly recommend you instead create a dynamic template for your posts, then you can use the Post Cards to display related items, which supports displaying related items by custom field.

This snippet will add a new setting where you can enter the exact ID's for items to display in the related posts section of your blog.

// Add related items setting for standard posts.
add_filter( 'wpex_metabox_array', function( $array, $post_type ) {
	$array['main']['settings']['related_post_ids'] = array(
		'title'         => __( 'Related Posts', 'total' ),
		'description'   => __( 'Comma seperated ID\'s for related items', 'total' ),
		'id'            => 'related_post_ids', 
		'type'          => 'text',
	);

    return $array;
}, 10, 2 );

// Alter related items if the related_post_ids meta field is set.
// NOTE: for custom post types use the "wpex_related_{$post_type}_args" filter instead of "wpex_blog_post_related_query_args".
add_filter( 'wpex_blog_post_related_query_args', function ( $args ) {
	if ( $related = get_post_meta( get_the_ID(), 'related_post_ids', true ) ) {
		$args[ 'category__in' ] = null;
		$args[ 'post__in' ] = explode( ',', $related );
	}
	return $args; 
} );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top