• Resolved NtreSBK

    (@ntresbk)


    I need to use functions such as wp_insert_user and wp_update_user in a plugin, but theses functions call not yet loaded functions (such as get_user_by or get_userdata).

    I don’t have any problems if I require pluggable.php where I use theses functions, but messing with WordPress load orders seems a pretty bad idea to me.

    How would you use theses functions in a plugin ?

    • This topic was modified 6 years, 2 months ago by NtreSBK.
    • This topic was modified 6 years, 2 months ago by NtreSBK.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Pluggable functions are added before plugins_loaded so your best bet is to include a file in your base plugin file with all your pluggable functions, probably toward the top of the file.

    /* wp-content/plugins/myplugin/pluggable.php */
    require_once( plugin_dir_path( __FILE__ ) . 'pluggable.php' );

    Define all your functions in that file. These above will load before pluggable. Do note to wrap them in a function_exists(). From The Codex:

    Note: A function can only be reassigned this way once, so you can’t install two plugins that plug the same function for different reasons. For safety, it is best to always wrap your functions with if ( !function_exists() ), otherwise you will produce fatal errors on plugin activation.

    What you need to do is look at when you’re calling those functions, and make sure that they’re called using an action that’s run after ‘plugins_loaded’ so that they will use the correct functions (either the core ones or any custom ones that have been added).

    The Codex on pluggable functions says:

    WordPress loads the built-in functions only if they are undefined after all plugins have been loaded.

    So if you use plugins_loaded or any action after, they will be declared duplicate and you will receive errors. They need to be defined as the plugin is loading not during a hook.

    Thread Starter NtreSBK

    (@ntresbk)

    @howdy_mcgee I don’t want to redeclare theses functions, I just want to use them.

    @catacaustic is right, I just had to move my logic to a hook where pluggable.php is already loaded.

    What I’ve done is using a main class for my plugin and in the __construct hook my logic to init and/or plugins_loaded.

    class MyPlugin {
      public function __construct() {
        add_action( 'plugins_loaded', [$this, 'plugins_loaded'] );
        add_action( 'init', [$this, 'init'] );
      }
    
      public function plugins_loaded() {
        // pluggables are available here
      }
    
      public function init() {
        // pluggables are available here
      }
    }
    new MyPlugin();
    • This reply was modified 6 years, 2 months ago by NtreSBK. Reason: mark as resolved
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Use core/pluggables functions on plugins’ is closed to new replies.