Setting home and siteurl dynamically in Wordpress

Setting home and siteurl dynamically in Wordpress

Created:10 Dec 2016 09:44:06 , in  Web development

If for some reason you have set siteurl and / or home options wrong in your WordPress installation database and as a result can't access admin panel, or perhaps have a reason not to change these options in wp_options table, you can overwrite them either in wp_config.php or functions.php file of your site easily.

Below I look how it can be achieved.

Hard-coded constants

The quickest method of overwriting the two settings is with wp-config.php. You just define two constants in it as shown below:


define('WP_SITEURL', 'http://<your.domain.here>/');
define('WP_HOME', 'http://<your.domain.here>/'); 

Once they are set, WordPress will use them bothering no more with what's in database wp_options table. It will use a pair of callbacks: _config_wp_home and _config_wp_siteurl.

They are attached to option_home and option_siteurl filters respectively with relevant code in wp-includes/default_filters.php

Multisite doesn't use this shortcut.

Custom filters

Alternatively to what was said above, you can dynamically set your home and siteurl options by attaching your own callbacks to option_home and option_site filters in functions.php of your theme. In other words you add what's not in wp-includes/default-filters.php


function my_filter_option_siteurl( $siteurl ) {
  // filter $siteurl here   
  return $siteurl; 
}; 
             
// add the filter 
add_filter( 'option_siteurl', 'my_filter_option_siteurl');

function my_filter_option_home( $home ) {
  // filter $home here 
  return $home; 
}; 
             
// add the filter 
add_filter( 'option_home', 'my_filter_option_home', 10, 1 );
 

The above code goes, as was said above, in functions.php, or perhaps even better, in a plugin

This post was updated on 27 Apr 2017 16:29:51

Tags:  php ,  wordpress 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.

Copyrights

©Copyright, 2018 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Setting home and siteurl dynamically in Wordpress." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/setting-home-and-siteurl-dynamically-in-wordpress