I have a created a custom post type say actor and created one actor "Tom Cruise" and URL is like /actors/tom-cruise in custom post type.
And I have created 3 posts (type is WordPress default post) slug is like /tom-cruise-mission-impossible1, /tom-cruise-mission-impossible2, /tom-cruise-mission-impossible3. Each slug is starting with tom-cruise pattern.
Now I want to display all 3 posts(similar posts in this case 3 mission impossible posts ) in custom post type (actors post) /actors/tom-cruise
I am trying to find similar posts but can't find from WordPress documentation with similar type of pattern used in slug. Any help appreciated. Please keep in mind don't want to create any additional category or is there any other way to do it without similar pattern slug query.
$args = array(
'post_type' => 'actors',
'post_status' => 'publish',
);
$loop = new WP_Query( $args );
I have a created a custom post type say actor and created one actor "Tom Cruise" and URL is like /actors/tom-cruise in custom post type.
And I have created 3 posts (type is WordPress default post) slug is like /tom-cruise-mission-impossible1, /tom-cruise-mission-impossible2, /tom-cruise-mission-impossible3. Each slug is starting with tom-cruise pattern.
Now I want to display all 3 posts(similar posts in this case 3 mission impossible posts ) in custom post type (actors post) /actors/tom-cruise
I am trying to find similar posts but can't find from WordPress documentation with similar type of pattern used in slug. Any help appreciated. Please keep in mind don't want to create any additional category or is there any other way to do it without similar pattern slug query.
$args = array(
'post_type' => 'actors',
'post_status' => 'publish',
);
$loop = new WP_Query( $args );
Share
Improve this question
asked Jan 10, 2021 at 15:31
DevDev
1012 bronze badges
1 Answer
Reset to default 1WP_Query
does not have a built-in arg for querying posts by part of the post slug — and normally, one would search for similar posts by the post tag or category; however, you can use a custom arg along with the posts_where
hook to query for similar posts by part of the slug.
I.e. Use a custom SQL query, then use a hook to add that query to the SQL query generated by WP_Query
.
So for example, in the theme functions.php
file, add this:
add_filter( 'posts_where', 'my_posts_where', 10, 2 );
function my_posts_where( $where, $query ) {
if ( $value = $query->get( 'slug_starts_with' ) ) {
global $wpdb;
$where .= $wpdb->prepare(
" AND {$wpdb->posts}.post_name LIKE %s",
$wpdb->esc_like( $value ) . '%'
);
}
return $where;
}
Then in your $args
, add the custom query arg (which is named slug_starts_with
in the above example):
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'slug_starts_with' => get_queried_object()->post_name,
);