WP_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,
);