Edit site_url with filter

2019-02-19 08:43发布

问题:

With WordPress, calling site_url() returns the full site URL (http://www.example.com) What I'm trying to do is adding something (add-something-here) at the end of the URL with filter.

The result I'm expecting is: http://www.example.com/add-something-here

Does someone know how to do that with filter?

I tried the following with no success:

function custom_site_url($url) {
    return get_site_url('/add-something-here');
}
add_filter('site_url', 'custom_site_url');

回答1:

The problem is that you are producing a loop with this filter. The function get_site_url is exactly where the filter site_url is being called.

You need:

add_filter( 'site_url', 'custom_site_url' );

function custom_site_url( $url )
{
    if( is_admin() ) // you probably don't want this in admin side
        return $url;

    return $url .'/something';
}

Bear in mind, that this may produce errors for scripts that rely on the real URL.



回答2:

Untested, but since it's PHP could you just try...

function custom_site_url($url) {
    return get_site_url() . '/add-something-here';
}
add_filter('site_url', 'custom_site_url');


回答3:

Untested, but this is a snippet of what I use often:

$constant = 'add-something-here';
return '<a href="'. esc_url(site_url().'/'.$constant.'/'">'. esc_html( $name ).'</a>'; 

or you might simply want to get the page ID instead and it's much better.

 $page_id = '2014';
 return  <a href="'. get_page_link ($page_id) .'">'.esc_html__( 'pagename', 'text-domain' ).'</a>