WordPress.org

Make WordPress Core

Opened 4 months ago

Closed 4 months ago

#49265 closed enhancement (fixed)

switch_to_blog() and restore_current_blog() reuse switch_blog action

Reported by: iandunn Owned by: SergeyBiryukov
Milestone: 5.4 Priority: normal
Severity: normal Version:
Component: Networks and Sites Keywords: has-patch commit
Focuses: Cc:

Description

Because the use the same action, it's difficult to do different things when switching to a site and restoring from a site.

For example:

function wcorg_switch_to_blog_locale() {
	$backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 5 );
	$caller    = $backtrace[4]['function'];

	switch ( $caller ) {
		case 'switch_to_blog':
			switch_to_locale( get_option( 'WPLANG', 'en_US' ) );
			break;

		case 'restore_current_blog':
			restore_previous_locale();
			break;
	}
}
add_action( 'switch_blog', 'wcorg_switch_to_blog_locale' );

See #49263 for the context of that example. It's not a fully working solution, just a minimal example to demonstrate the problem here.


One potential solution would be to introduce a new restore_blog action inside restore_current_blog().

That still leaves a problem where it may not be obvious to people that switch_blog will still also run when restoring a blog, but I'm not sure there's a back-compat way to solve that. We could at least highlight it in the switch_blog filter documentation, though.

Attachments (1)

49265.diff (2.0 KB) - added by SergeyBiryukov 4 months ago.

Download all attachments as: .zip

Change History (8)

#1 in reply to: ↑ description @SergeyBiryukov
4 months ago

Replying to iandunn:

That still leaves a problem where it may not be obvious to people that switch_blog will still also run when restoring a blog, but I'm not sure there's a back-compat way to solve that.

We could add a context as the third parameter, see 49265.diff for example.

#2 @SergeyBiryukov
4 months ago

  • Keywords has-patch added
  • Milestone changed from Awaiting Review to 5.4

#3 @johnbillion
4 months ago

I like the context parameter approach, as it solves the disambiguation problem for both switching to and switching from.

#4 @jeremyfelt
4 months ago

I also like the context parameter. 49265.diff looks good to me.

#5 @iandunn
4 months ago

Ah, yeah, that's much better!

#6 @SergeyBiryukov
4 months ago

  • Keywords commit added
  • Owner set to SergeyBiryukov
  • Status changed from new to accepted

#7 @iandunn
4 months ago

  • Resolution set to fixed
  • Status changed from accepted to closed

In 47105:

Multisite: Add $context parameter to switch_blog action.

The action is fired by both switch_to_blog() and restore_current_blog(), and previously it was difficult for callback functions to determine which function had fired it.

Props SergeyBiryukov, johnbillion, jeremyfelt.
Fixes #49265.

Note: See TracTickets for help on using tickets.