Configuration of Domains and Logo Sources through the WP Admin
The last step is to implement configurations through WP Admin, to eliminate the necessity to change plugin implementation whenever domains or logo images change. To achieve that, we defined two domains and two logo URLs as WordPress options.
So, to intercept default WordPress behavior, first, we register the function to be executed on the admin_init hook. This action is executed whenever the WP Admin area is initialized.
add_action('admin_init', 'set_domains_settings_inputs');
Function set_domains_settings_inputs implementation (together with utility functions used) is implemented as follows:
function set_domains_settings_inputs()
{
create_settings_field('domainA', 'Domain A');
create_settings_field('logoA', 'Logo A');
create_settings_field('domainB', 'Domain B');
create_settings_field('logoB', 'Logo B');
}
function create_settings_field($fieldId, $title) {
add_settings_field($fieldId, $title, function () use ($fieldId) {
render_settings_input($fieldId);
}, 'general');
register_setting(
'general',
$fieldId
);
}
function render_settings_input($optionName)
{
$value = '';
$option = get_option($optionName);
if ($option !== false) {
$value = $option;
}
echo '<input type="text" name="' . $optionName . '" id=' . $optionName .'" value="' . $value . '" />';
}
So, to demystify this part:
Function create_settings_field actually registers the option with the name $fieldId and defines its $title (presented on the interface). It is defined that inputs should be presented on the general page in the WordPress site settings. Function render_settings_input actually renders input on the interface. More details on Add Settings Field and Register Setting.
After these steps, when one navigates to settings -> general page of WP Admin, it should get an interface like this:
At this point, saving values for Domain A, Logo A, Domain B, and Logo B should work properly.
The final action to do is to extend get_logo_image() function to actually read these options. To read options from the database, we use get_option() function. Function get_logo_image() after this change looks like this:
function get_logo_image() {
$domain = sanitize_url($_SERVER['SERVER_NAME']);
$domainA = get_option('domainA');
$domainB = get_option('domainB');
$logo = null;
if ($domain === $domainA) {
$logoA = get_option('logoA');
if ($logoA !== false) {
$logo = $logoA;
}
} else if ($domain === $domainB) {
$logoB = get_option('logoB');
if ($logoB !== false) {
$logo = $logoB;
}
}
return $logo;
}
At this point, WordPress page logo should be changed based on configuration from settings.