Alternative to WordPress's get_site_url()

2019-08-22 08:10发布

问题:

I'm trying to get the value similar to the WordPress site url to identify a certain WordPress installation.

Since the get_site_url can get altered (with a plugin or directly) I came up with this:

untrailingslashit('http://'.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'],'', ABSPATH));

This gives me good result to identify the WordPress based on it address but I'm curios if this may cause troubles on some server installations?

回答1:

Here's my answer based on the information you've provided.

Create a function. First check if the home url is defined as a constant in wp-config. If so there's the URL. It overrides any DB value so if not set correctly the site won't function.

If that's not set then run a manual DB query to get the value of home from the options table. By running it manually instead of using get_option there's no way this value can be changed by a plugin before you use it.

function wpse_get_license_url() {
     global $wpdb;

     if ( defined( 'WP_HOME' ) ) {
         return WP_HOME;
     } else {
         $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", 'home' ) );
         return $row->option_value;
     } 
}


回答2:

I hope this link might help you to better understand the implications of using

home_url() vs site_url()

home_url() will only return the mapped domain on or after the init has fired. Calling it before then will return the .wordpress.com domain.

If you accidentally use site_url() in your templates, theme-side links will still redirect correctly to the home_url() equivalent.

home_url() is the preferred method, as it avoids the above redirect.


回答3:

blogininfo('siteurl');
get_option('home');

home_url();
site_url();


标签: php wordpress