In my WordPress v6.0.2, I have a custom taxonomy country
and a custom post_type interest
.
With post_type_link
filter (another working function) and with the below function, I am rewriting custom post_type URLs as https://www.example.com/country_name/interest_term
:
add_filter('generate_rewrite_rules', 'country_cpt_generating_rule');
function country_cpt_generating_rule($wp_rewrite) {
$rules = array();
$terms = get_terms(array(
'taxonomy' => 'country',
'hide_empty' => false,
));
$post_type = 'interest';
foreach ($terms as $term) {
$rules[$term->slug . '/interest/([^/]*)$'] = 'index.php?interest=$matches[1]&post_type=' . $post_type . 'name=$matches[1]';
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
While I have single-interest.php
custom post_type template to show custom content, single posts are redirecting to home page with error404
class added to the body.
A var_dump(get_queried_object());
returning null
.
I have flushed permalinks and also tried checking is_singular()
to template redirecting, that did not worked.
How can I have a custom page template for single-interest
with above custom URL?
3
Answers
I have taken cue from this SO answer and below code worked for me:
It seems you are wanting to access the CPT single page. In order to do that please follow the code below
Now inside the "single-interest.php". you can var_dump( get_queried_object() ). Which should give you the values of the WP_Post Object data. Since this template is directly coming from a plugin the custom template file should be placed inside a plugin or the custom single-interest file should be placed inside the theme file in this format "single-interest.php". Also, I would like to add the following points, since you are using a custom post type, you do not have to regenerate custom slugs. Because WordPress does regenerate the custom slugs for you. I would recommend you not use ‘generate_rewrite_rules’ because WordPress did create those slugs for you while creating the custom post type. What you can do is pass the slug value inside the ‘parse_request’ filter hook. For reference please refer to this page here
here is the complete solution for your requirement. Please note that you do not have to regenerate new rewrite rules to be able to work with custom post-type URLs. instead, I have used filters to modify URLs based on your need. Let me know if this solves your issue. Please do not forget to flush your permalinks. There might be some edge cases that I did not put my focus on because mainly I was focusing on achieving your requirements.