php - Wordpress Rewrite rule to allow dynamic custom terms for an existing taxonomy
Get the solution ↓↓↓I am new to both wordpress and php. I have a custom taxonomy job_category for which I have a permalink set (jobs), under which there are categories such as engineering, accounts etc. So I can easily visit /jobs/engineering-jobs.
However, I would also like to accept dynamic terms such as jobs/it-jobs-in-usa.
For this I have read about rewrite rules and wrote the following:
add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ){
$wp_rewrite->rules = array_merge(
['jobs/([a-zA-Z0-9]+[-]*[a-zA-Z0-9]*-in{1}-[a-zA-Z0-9]+)/?$' => 'index.php?
jobloc=$matches[1]'],
$wp_rewrite->rules
);
} );
add_filter( 'query_vars', function( $query_vars ){
$query_vars[] = 'jobloc';
return $query_vars;
} );
add_action( 'template_redirect', function(){
$jobloc = get_query_var( 'jobloc' );
if ( $jobloc ) {
include plugin_dir_path( __FILE__ ) . 'taxonomy.php';
die;
}
} );
However, this rule seems to be interjected by wordpress existing rules:
'jobs/(.+?)/?$'
And it does not find anything with that term (correctly so) so throws a 404. I have also tried to unset that rule but then it falls in another generic rule.
[^/]+/([^/]+)/?$
Is there a way for the above rule to kick in if it does not find anything instead of throwing 404. So:
jobs/it-job (taxonomy term found and it works as it does) jobs/it-jobs-in-usa (not found but matches the above custom rule and takes to the required taxonomy.php page) where i can show results appropriately.
I am also using a theme so making changes in my child functions.php page.
Thanks for your help in this. Been at it for a while with different combinations.
Answer
Solution:
Found the issue. It was a plug in (permalink customizer) that was picking up a draft page with jobs/ url overwriting the query params thus Causing this issue.
Deleted the draft page and the rules are working now.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.