Filter home_url for custom post type

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.com/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.com/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;
    }

}

2 Answers
2

Your 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).

Leave a Comment