Skip to content

Snippet: Related Posts by Specific ID’s

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 ) {

	if ( 'post' == $post->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 fields
    return $array;

}, 40, 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
	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