Hello Folks, ever need to change the Elementor header via custom code. Or need extra conditions, that elementor-pro do not provide?
Assuming, you are using Elementor and Elementor-Pro
First, we hook into ‘elementor/theme/before_do_{$locations}’
$location is our ‘header’
add_action( 'elementor/theme/before_do_header', 'custom_maybe_change_elementor_header' );
Then in our callback function, we first remove the default location header.
This location seems like an array where the chosen header is going to be printed.
Here
- $obj is ElementorPro\Modules\ThemeBuilder\Classes\Locations_Manager Object
- 10 is the header ID we want to replace. You can either inspect the header element in the front end or edit the header in Theme Builder and find the desired header ID.
$obj->remove_doc_from_location( 'header', '10');
Then, we add our preferred header ID e.g. 12
$obj->add_doc_to_location( 'header', '12');
Note, if you do not remove the applied header first, then both headers will show up, Maybe this is not what you want.
Overall our custom_maybe_change_elementor_header() function will look likes this
function custom_maybe_change_elementor_header( $obj ): void {
// ElementorPro\Modules\ThemeBuilder\Classes\Locations_Manager Object
$obj->remove_doc_from_location( 'header', 232816 ); // Global Header - pages with banner
$obj->add_doc_to_location( 'header', 250048 ); // Global Header - pages without banner
}
You can have your various conditions based on your situation, to hook the before_do_header
Lets say, there is a query string (www.example.com/?activate=yes, in the home page, where the header is applied to entire site. But you can check that condition to to apply other header, only when there is a query string in URL.
add_action('init', function() {
$is_activate = isset( $_GET['activate'] ) && $_GET['activate'] === 'yes';
if( $is_activate ) {
add_action( 'elementor/theme/before_do_header', 'custom_maybe_change_elementor_header' );
}
});
As always, you can place this code in your child theme functions.php file at the end.
Hope, this helps to someone. Good bye.