I would like to change the home_url for a custom post type that I have created.
The reason I would like to change the home_url is so that the site logo then links to a different URL when someone is viewing a custom post.
The custom post type is named 'usa', therefore I want to change the logo / home url to link to mysite/usa/
I have used the code below to achieve this, however I get errors because other links that make use of home_url, such as menu links, then have 'usa' appended to them, e.g mysite/usa/example-post/usa/
Does someone know a better implementation?
add_filter( 'home_url', 'custom_home_url' );
function custom_home_url( $url )
{
if( is_singular('us') )
return $url .'/usa';
else {
return $url;
}
}
I would like to change the home_url for a custom post type that I have created.
The reason I would like to change the home_url is so that the site logo then links to a different URL when someone is viewing a custom post.
The custom post type is named 'usa', therefore I want to change the logo / home url to link to mysite/usa/
I have used the code below to achieve this, however I get errors because other links that make use of home_url, such as menu links, then have 'usa' appended to them, e.g mysite/usa/example-post/usa/
Does someone know a better implementation?
add_filter( 'home_url', 'custom_home_url' );
function custom_home_url( $url )
{
if( is_singular('us') )
return $url .'/usa';
else {
return $url;
}
}
Share
Improve this question
asked Oct 13, 2017 at 14:13
user102297user102297
212 bronze badges
5
|
2 Answers
Reset to default 1Your filter generally seems fine.
I'd probably filter option_home
instead of home_url
, but it results in the same thing for most use cases (bloginfo("home")
will work and so will get_home_url()
, but get_option("home")
will only work correctly with option_home
).
I would suggest putting this in the file that contains your menu code, the header file usually. You can just check the page on load to see if the page your on needs the USA appending to the link.
Here is an example that could be used for any element within a page.
HEADER.PHP
<?php
if( is_singular('us') ) {
$url = site_url( '/usa/' );
} else {
$url = site_url();
}
?>
<nav>
<a href="<?php echo $url; ?>" class="logo">MY LOGO</a>
</nav>
site_url()
by default will just give you your website URL but it can also take an extra $path
parameter to append to the end of the URL. This is why I have put '/usa/'
inside site_url()
above.
home_url
in your functions.php and therefore, you can't pick which one should use the new URL instead of the original. What I would suggest is putting your code in the default header template file (where the menu code is). You can use theis_singular()
to check if you're on the right page to swap the link. Does that make sense? – Ashtmdu Commented Oct 13, 2017 at 16:06