Add a filter inside an action init

Hello in the init action, I would like to add a filter to a fairly large function to modify variables in the $vars array, for example the Wordpress post ID.

That is to say:

    add_action( 'init',function(){
        //code
    
        add_filter( 'query_vars',function($vars){
            $vars[] = array('ID' = $myid);
             return $vars;
    
        });
    });

Is this possible?

EDIT: I am doing A/B/C tests of pages and with the same url I want to show a page with another ID, (i.e. edit the ID of the current post to display the complete content of another post).

Topic actions filters init Wordpress

Category Web


To alter the page ID before the query is run, hook the request filter.

If you're using pretty permalinks, pagename will be set, you can overwrite pagename with another page slug:

function wpd_265903_request( $request ) {
    if( isset( $request['pagename'] ) ){ // any page
        $request['pagename'] = 'some-other-slug';
    }
    return $request;
}
add_filter('request', 'wpd_265903_request');

or you can unset pagename and set page_id:

function wpd_265903_request( $request ) {
    if( isset( $request['pagename'] ) ){
        unset( $request['pagename'] );
        $request['page_id'] = 106;
    }
    return $request;
}
add_filter( 'request', 'wpd_265903_request' );

Yes, it's possible to do something like that. And in fact, if you want to remove actions/filters, then you will be almost certainly be required to use one hook to remove it.

For instance, plugins load before the theme. So if a theme adds a hook to the init hook from the functions.php file like so:

add_action( 'init', 'wpse_265903_init' );

Plugins would not be able to remove that action until after the theme gets setup:

add_action( 'after_setup_theme', function() {
  remove_action( 'init', 'wpse_265903_init' );
} );

Similarly, if you want some hooks to run only after the admin_init hook, then you can do something like this:

add_action( 'admin_init', function() {
  add_action( 'the_post', function() {
    do_something();
  } );
} );

The init hook fires on every request though, so I'm not sure the purpose of adding hooks from that particular hook.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.