Elementor Posts Query: Related Posts From the Same Category
Adds a custom query ID "wpide_related" that shows posts sharing a category with the current post, newest first, without the current post itself.
Opens WPIDE on
Code
add_action( 'elementor/query/wpide_related', function ( $query ) {
if ( ! is_singular() ) {
return;
}
$post_id = get_queried_object_id();
$terms = wp_get_post_terms( $post_id, 'category', array( 'fields' => 'ids' ) );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return;
}
$query->set( 'category__in', $terms );
$query->set( 'post__not_in', array( $post_id ) );
$query->set( 'ignore_sticky_posts', true );
$query->set( 'no_found_rows', true );
} );
Notes
Type wpide_related in the Query ID field of a Posts or Loop Grid widget in your single post template.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.