php - How to call plugin function per site in a multisite?

admin2025-06-03  2

My goal is to be able to call a plugin function per site and of course it has different result based on the site data.

e.g.

I have a plugin called: sample-plugin.php

Inside it has a function called:

function sp_echo_site()
{
   echo get_site_url();
}

I have a multisite inside has 3 sites: e.g. animals, fruits and people

And in a network level, I wanted to call the sp_echo_site() function.

I wanted to do the following loop, however of course it doesn't work, How can I make this work?

foreach (get_sites() as $site)
{
   $site->sp_echo_site();
}

How can i achieve the following result?:

animals
fruits
people

Is this possible? Or do I have to go to database? Or any other alternative methods?

My goal is to be able to call a plugin function per site and of course it has different result based on the site data.

e.g.

I have a plugin called: sample-plugin.php

Inside it has a function called:

function sp_echo_site()
{
   echo get_site_url();
}

I have a multisite inside has 3 sites: e.g. animals, fruits and people

And in a network level, I wanted to call the sp_echo_site() function.

I wanted to do the following loop, however of course it doesn't work, How can I make this work?

foreach (get_sites() as $site)
{
   $site->sp_echo_site();
}

How can i achieve the following result?:

animals
fruits
people

Is this possible? Or do I have to go to database? Or any other alternative methods?

Share Improve this question edited Feb 18, 2019 at 6:31 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 18, 2019 at 5:17 MarkMark 132 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 2

You're almost there...

If you have this in your plugin:

function sp_echo_site() {
   echo get_site_url();
}

Then you call this function as this:

sp_echo_site();

And this line will run this function in the context of current site.

So you'll have to do something like this:

if ( function_exists( 'get_sites' ) ) {
    foreach ( get_sites() as $site ) {
        switch_to_blog( $site->blog_id );

        sp_echo_site();

        restore_current_blog();
    }
}

Mark, to achieve the following result, you have to change your foreach loop. Try this code:

foreach (get_sites() as $site) {
  echo $site->__get('siteurl');
}

EDIT: Wordpress reference

Yes, that's an option OR you can do this exmaple/?trigger_my_func sub1.exmaple/?trigger_my_func or exmaple/sub1/?trigger_my_func by triggering a method when accessing a subsite within a network it should run in the context of that site and output site specific information.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748894589a314611.html

最新回复(0)