Wordpress Multisite调用插件功能在不同的站点上

时间:2018-06-15 21:03:07

标签: php wordpress multisite

我正在使用Wordpress插件,该插件必须在Wordpress Multisite网络中的其他网站上触发某些操作。

  • 网站A
  • 网站B:更改网站A

例如,我切换网站以更改其他网站上的用户角色(网站B上的代码):

switch_to_blog(1); //to Site A
//Change the user's role
restore_current_blog();

这很好用,但现在我想调用插件的功能。 所以我想调用一个插件的功能,该插件在站点A上从站点B激活。switch_to_blog()函数只切换数据库而不是加载的插件。那么我怎样才能实现目标呢? 我试图激活网站B上的插件,但这不起作用。 我可以完全访问这两个站点。

1 个答案:

答案 0 :(得分:0)

不幸的是,它似乎不会进入Core:Trac ticket #14941(并且每个人都知道回文票号是密封的,大声笑)。

老实说,最好的办法是触发该功能通过其他方法运行,例如在目标站点上触发自定义操作。因此,继续运行您现在拥有的功能,但是向目标博客URL添加GET或POST请求(我将使用file_get_contents作为示例,但您应该使用带有nonces的POST方法如果你能够的话)

function trigger_function_on_blog( $blog_id, $user_id ){
    $blog_url = get_site_url( $blog_id );
    switch_to_blog( $blog_id );

    $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => 'new_role' ) );
    file_get_contents( $blog_url . '?auth=m50667' );

    restore_current_blog();
}

// Modify User: 2 on Blog: 1
trigger_function_on_blog( 1, 2 );

现在您的功能正常运行,但也直接请求目标站点。在您的目标网站上,您只需要确保该功能仅在$_GET['auth']等于m50667时触发(或者您的其他更好的验证方法)。

您可能希望使用MU Plugin,因为functions.php与主题相关,而多站点则允许使用不同的主题。

所以继续创建/mu-plugins/custom-functions.php并且它会一直运行,总是不需要激活,并在里面放置你想要运行的逻辑:

if ( ! defined( 'ABSPATH' ) ) exit; // Prevent direct file access

add_action( 'init', 'faux_switch_to_blog_function' );
function faux_switch_to_blog_function(){
    if( $_GET['auth'] === 'm50667' ){ // Make sure this request is authorized by us
        if( function_exists( 'some_plugin_function' ) ){
            some_plugin_function();
        }
    }
}

现在,当any-site.example.com?auth=m50667触发trigger_function_on_blog()时,faux_switch_to_blog_function()将在目标网站上运行,您应该可以访问该网站可用的任何功能和挂钩。< / p>

请注意:

我想强调的是,我不一定建议$_GET使用file_get_contents授权,特别是如果您在各个博客上运行任何准敏感内容。我会考虑使用wp_remote_poststream_context_createcURL以及WP Nonces来确保没有任何可疑事件发生并且操作已获得授权。

我纯粹使用file_get_contents来保持示例的简洁。

相关问题