My custom functions in “functions.php” doesn’t work.

Posted on May 11, 2021

Normally, you can add code snippets for your custom functions into functions.php which is placed in your theme or child theme folder. But in case you select “mu-plugins” (ip-location-block-mu.php) as “Validation timing” in “Validation rule settings” section, your code for this plugin in functions.php would be failed to work as you expected.

Validation timing

This restriction is originated from the excution order described in Action Reference where you can find muplugins_loaded action hook is triggered far before after_setup_theme which is the timing of your functions.php to be parsed.

Action Reference

Then what’t the solution?

Installing “drop-in.php” and “drop-in-admin.php”

To install, upload drop-in.php or drop-in-admin.php  in  /wp-content/uploads/ip-location-block/dropins/

You can find a sample for drop-in.php in /wp-content/plugins/ip-location-block/wp-content/drop-in-sample.php. Just rename it to dropi-in.php and upload in the directory mentioned above.

Both drop-in.php and drop-in-admin.php are similar but are fired on different sides. The first is used on the front-end and the second is used on the admin side.

Note that even in the case of multisite, drop-in.php and drop-in-admin.php  will be called on every site. So if you want each site to behave differently, you should add some code like follows:

<?php
/**
 * Drop-in for IP Location Block custom filters
 *
 * @package   IP_Location_Block
 * @link      https://www.ipgeoblock.com/codex/#filter-hooks
 * @example   Use `IP_Location_Block::add_filter()` instead of `add_filter()`.
 */
if ( ! class_exists( 'IP_Location_Block' ) ) {
    die;
}

$components = parse_url( site_url() );

switch ( $components['host'] ) {
    case 'example.com':
      if ( 0 === strpos( $components['path'], '/subdir1' ) ) {
          // here is code snippet for sub directory 1
      }

      elseif ( 0 === strpos( $components['path'], '/subdir2' ) ) {
          // here is code snippet for sub directory 2
      }
      break;

    case 'subdomain1.example.com':
      // here is code snippet for sub domain 1
      break;

    default:
      // here is code snippet for default
      break;
}
NOTE: All your custom functions in functions.php doesn’t need to be put together into drop-in.php but functions related to only this plugin such as Filter hooks for this plugin.