Wordpress Multisite - add function to functions.php to only affect 1 site
php, wordpress
Solution
In my opinion the best way to target one subsite within multisite is to use the `get_current_blog_id()` function within the function called by the filter. Here's an example of some code that would work:
<?php
function function_to_call(){
if( get_current_blog_id() === 1 ){
// Return something if the site ID matches the number one...
}
// Return something if the site ID does not match the number 1
}
add_filter( 'filter_name', 'function_to_call' );
?>
You can grab the ID of the site you want to target by going to https://example.org/wp-admin/network/sites.php where https://example.org is replaced with your domain.
There are a few benefits to this approach over others listed here.
- This will work if you have multiple versions of your multisite installation using different domains. For example, you might have http://localhost/site1, site1.example.org and site1.staging.example.org. If you checked for the domain the filter would break on every site except production. If you use the ID, it should work across the board.
- Other options like creating a child theme or a plugin do work, but they tend to be overkill when you're talking about running a function on a single hook.
Problem
I am running a wordpress multisite with 2 blogs ( site1.com and site2.com ) The entire site is sharing the same theme as well as the functions.php file. I have the following filter that I need to put into the function.php file, but I need this filter to only affect 1 blog - site2.com The filter is as follows : ``` add_filter( 'get_manager_nav', 'set_manager_nav' ); function set_manager_nav( $urls ) { unset($urls['voucher']); return $urls; } ``` Is there a way to apply this filter only to 1 site ?? What I have done instead is that I have created a new plugin, I have added the function to the plugin and activated the plugin only on site2.com. It is working great, but I suppose using a simple snippet is much better than using a plugin, so is there a way to do this using a snippet ?