Dear Gagan,
wonderful work! Thank you so much for sharing.
I have written a small example for those who are a little lost when it comes to coding up the functionality of your very useful plugin…
Problem example
we often work on our localhost server when developing a new site. This means that our initial domain is folder based, so we access it using https://localhost/new-project
. However when we deploy live we have our client domain, so the site is accessed with something like https://new-project.com/
. Now if we want to access a custom post-type (eg: products) archive page from the main menu, we have the following links:
Localhost: https://localhost/new-project/products
Live server: https://new-project.com/products
So may times we have forgotten to change the custom link in the menu, which breaks the live site, because it points to https://new-project.com/new-project/products
which of course does not exists.
The Solution: ‘Shortcodes in Menu’ to the rescue.
First we create the shortcode logic in our functions.php
file:
function sy_get_domain_name(){
$domain_name = preg_replace('/^www\./','',$_SERVER['SERVER_NAME']);
return $domain_name;
}
function isLocalhost(){
if("localhost" == sy_get_domain_name()) return true;
else return false;
}
//menu short code test
// [syMenuLink]
add_shortcode( 'syMenuLink', 'menu_shortcode' );
function menu_shortcode( $atts ) {
$url = 'https://'.sy_get_domain_name();
switch (true){
case isLocalhost():
$url = $url.'/only/listing';
break;
default:
$url = $url.'/listing';
break;
}
return $url;
}
we have 3 functions:
sy_get_domain_name()
– returns our current domain name without the protocol, eg localhost
isLocalhost()
– make use of the above function to test if this is the localhost
add_shortcode( 'syMenuLink', 'menu_shortcode' )
– registers the shortcode [syMenuLink]
menu_shortcode( $atts )
– defines the logic of our menu short code
Then in our menu section of the Dashboard, we include a new custom menu Link. In the URL field we enter our new shortcode [syMenuLink]
created above.
You should now see your menu link being correctly constructed, regardless of the site being visited.
Hope this helps someone out there.