Documentation / Tutorials / Awesome Enterprise

Add term in the post URL

/ Awesome Enterprise / Add term in the post URL

If we want to add the taxonomy in the URL then need to add a rewrite rule in the site_specific.php

Reference:
Base: /aw-enterprise/
file: includes/app_setup.php
function: controller_taxonomy

This function checks multiple possibilities:
1. Checks for the meta with the key “default_taxonomy” defined in the App > Config > settings. If it is not present then it returns from the function and calls to render the post-single-layout.
2. Checks for the “default_taxonomy” with the value and it present then will check it with the wp function term_exists(). If term present in the DB will call archive-layout
3. If the term present and assigned to the post as well then it will call archive.
4. Term present in the URL and rewrite rule added then code will not check is it assigned or not with to the post. It will directly get rendered because rewrite rule is only looking for the post name. [See the rewrite to know more]

Add this code in the site-specific.php

URL: app/{postname} to app/{term}/{postname}

[Note: This will load the archive-layout instead of the post-layout if the post term and default_taxonomy term slug are same.]

/* URL rewrite: START */
add_action( 'generate_rewrite_rules', 'add_taxo_rewrites',999 );
function add_taxo_rewrites( $wp_rewrite ) {
$wp_rewrite->rules = array(
// 1. Specific taxo match
// 'products/fda-us/([^/]+)/?$' => 'index.php?post_type=product&name=$matches[1]'
// 2. Match anything
'products/([^/]+)/([^/]+)/?$' => 'index.php?post_type=product&name=$matches[2]'
) + $wp_rewrite->rules;
}
add_action( 'init', 'change_yoast_seo_og_meta');
function change_yoast_seo_og_meta() {
add_filter( 'wpseo_opengraph_url', 'change_url' );
add_filter( 'wpseo_sitemap_url', 'https_change_url',10,2 );
}
function change_url( $url ) {
return home_url() . $_SERVER['REQUEST_URI'];
}
function https_change_url( $output, $url ) {
/* This function needed if the sitemap shows http: instead of https: */
if(!empty($output)) {
if(stristr($output, 'http:')!==FALSE){
$output = str_replace('http:', 'https:', $output);
}
elseif(stristr($output, 'http:')!==FALSE){
$output = str_replace('http:', 'https:', $output);
}
elseif(stristr($output, '/')!==FALSE){
$output = str_replace('', ''. str_replace('http:', 'https:', home_url()), $output);
}
else {
$output = str_replace('http:', 'https:', $output);
}
}
return $output;
}
add_filter( 'wpseo_canonical', 'yoast_seo_canonical_change' );
function yoast_seo_canonical_change( $canonical_url ) {
global $post;
return change_url($canonical_url, $post);
}
/* URL rewrite: END */

This code will rewrite URL for the followings:
1. Post URL
2. Default permalink URL in the Yoast sitemap
3. Canonical URL
4. Filters all the http:// URLs in Yoast sitemap and changes to https://

Categories
Most Popular

Leave a Reply

Your email address will not be published. Required fields are marked *