Make WordPress WP-API faster by not loading theme and plugins

前端 未结 4 532
广开言路
广开言路 2021-02-04 19:14

I would like to make requests to the WordPress API much faster. My API is implemented in a plugin (using register_rest_route to register my routes). However, since this is a plu

4条回答
  •  礼貌的吻别
    2021-02-04 19:37

    Sorry for my poor english if this is helpful for you.

    Put the plugin folder in root wordpress install.

    /public_html/my-plugin/my-plugin.php
    
    and include wordpress main file.
    
        require dirname( dirname( __FILE__ ) ).'/wp-load.php';
    

    Or in plugin folder directly access

    /public_html/wp-content/plugins/my-plugin/my-plugin.php
    require_once dirname(__FILE__) . '/../../../wp-load.php';
    

    Before check wp-load.php file included properly and working.

    wp-settings.php file load whole core, plugins and themes files. wordpress is load first mu-plugins files (wp-content/mu-plugins/) and provide after action hook muplugins_loaded. Trigger this action to exit whole other files loaded. You can also find which action hook is provide before muplugins_loaded and stop other files and script execution.

    if define constant SHORTINIT before include wp-load.php its includes some files provide DB,plugin or basic functions. When we want more load core files and not just want load plugins and theme files in this way found a solution.

    // file my-plugin.php
    //call before include file wp-load.php
    global $wp_filter;
    $wp_filter = array( 
        // pass wp hook where to want exit extra wp loaded
        'muplugins_loaded' => array(
         // prority
             1 => array(
                // callback function register
                'wp_extra_loaded_exit' => array( 
    
                  'function' => 'wp_extra_loaded_exit',
    
                  'accepted_args' => 1
    
                  )
             ) 
       )
    );
    
    
    
    function wp_extra_loaded_exit(){
      exit; 
    
    }
    require dirname( dirname( __FILE__ ) ).'/wp-load.php';
    // plugin code here.
    

    We check muplugins_loaded hook is define wordpress early you can also find which hook is define before muplugins_loaded then stop this point to after load more wordpress files. -

    When you want to test your script open file wp-settings.php and find string muplugins_loaded then echo statement to check.

    echo "Wordpress loaded in this point before"; 
    
    do_action( 'muplugins_loaded' );
    
    echo "After this wordpress not loading"; // Output fail bcz we exit 
    

提交回复
热议问题