plugin development – Getting similar posts by custom field value
To compare just the first value of the “Near by” custom field for your current post with the first value of the “Near by” custom field for other posts, you can use the “SUBSTRING_INDEX” function in your meta query.
Here’s an example of how you can modify your WP_Query to only show posts that have the same first value as your current post:
$current_nearby = get_post_meta( $post->ID, 'Near by', true ); $current_nearby_first = strtok( $current_nearby, ',' ); // Get the first nearby city $postss = new WP_Query([ 'post_type' => 'post', 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'Near by', 'value' => $current_nearby_first, 'compare' => 'LIKE', 'type' => 'CHAR', // Ensure case-sensitive comparison 'where' => 'SUBSTRING_INDEX(meta_value, ",", 1) = SUBSTRING_INDEX("' . $current_nearby . '", ",", 1)', // Compare only the first nearby city ), ), ]);
Note that this solution assumes that nearby cities are separated by commas in the “Near by” custom field. If your nearby cities are separated by something else, you’ll need to adjust the where parameter accordingly.
Leave an answer