[wp-trac] [WordPress Trac] #43621: Introduce `add_action_once` and `add_filter_once` sugar.
WordPress Trac
noreply at wordpress.org
Fri Mar 23 17:49:47 UTC 2018
#43621: Introduce `add_action_once` and `add_filter_once` sugar.
-----------------------------+-----------------------------
Reporter: soulseekah | Owner:
Type: feature request | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Plugins | Version:
Severity: normal | Keywords:
Focuses: |
-----------------------------+-----------------------------
It is often useful (especially when writing tests for filters, actions) to
run a callback only once, regardless of how many times the filter/action
is actually applied/done.
{{{
add_filter_once( 'test_action_once', '__return_true' );
$this->assertTrue( apply_filters( 'test_action_once', false ) );
$this->assertFalse( apply_filters( 'test_action_once', false ) );
}}}
This would allow developers to run anonymous callbacks that remove
themselves from the filter after running once. This can currently be done
with the following ugly workarounds:
{{{
add_action( 'run_many_times', function() {
// do stuff once and self-destruct
remove_filter( 'the_title', current( $GLOBALS['wp_filter'][
current_filter() ]->callbacks[ 10 ] )['function'] );
} );
}}}
or
{{{
$once = null;
add_action( 'run_many_times', $null = function() use ( &$once ) {
// do stuff once and self-destruct
remove_filter( 'the_title', $once );
} );
}}}
This is '''not''' a duplicate of #38743, the concept is different, the
naming is the same, yes.
Non-clashing names here?
- `add_self_destructing_filter()`
- `add_ephemaral_filter()`
open to other suggestions :)
--
Ticket URL: <https://core.trac.wordpress.org/ticket/43621>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list