WordPress at Your Fingertips

add_filter_once() & add_action_once() WordPress functions

Suppose we want to change (supplement) the title of a post and for that we create a hook the_title on the [loop_start] hook and change the title of the post. But now the hook we added will be triggered for every call of the_title() after our changed title.

That is, we need to delete our hook immediately after using it. Our hook only needs to work once.

There is no function in WordPress that adds the hook and deletes it automatically after it runs.

To solve this problem, I wrote my add_filter_once() and add_action_once() functions.

if( ! function_exists( 'add_filter_once' ) ) :

	function add_filter_once( $hook_name, $hook_callback, $hook_priority = 10, $accepted_args = 1 ) {

		$cb = static function () use ( $hook_name, $hook_callback, $hook_priority, & $cb ) {

			remove_filter( $hook_name, $cb, $hook_priority );
			unset( $cb );

			return $hook_callback( ...func_get_args() );
		};

		return add_filter( $hook_name, $cb, $hook_priority, $accepted_args );
	}

	function add_action_once( $hook_name, $hook_callback, $hook_priority = 10, $accepted_args = 1 ){
		return add_filter_once( $hook_name, $hook_callback, $hook_priority, $accepted_args );
	}

endif;

Paste this code into the plugin or theme file functions.php. And then use these functions just like regular functions add_filter() or add_action():

add_filter_once( 'the_title', static function( $title ){

	if( my_condition ){
		return $title . ' some addition';
	}

	return $title;
} );
No comments
    Log In