Can I change header.php of current theme through a plugin function?

I need to add some html into the header.php but instead of directly changing the header.php of my theme or creating a child theme, how can I do it with just actions and/or hooks?

Related posts

Leave a Reply

3 comments

  1. If you are looking to insert code into the <head></head> block, then this hook does it:

    add_action( 'wp_head', 'wpse_73900_wp_head' );
    
    function wpse_73900_wp_head()
    {
        ?>
        <!-- Custom Html --->
        <?php
    }
    

    If that’s not the case, then it’s more difficult. I think it would depend on the theme providing a hook at your desired point of insertion.

    Another option is to make DOM manipulations with jQuery.

    Other quite crazy possibilities can be extracted from this Q&A: Adding onload to body

  2. You have three options:

    • If you’re wanting to put things in the head tags, use the wp_head action.
    • If you’re wanting to add markup either override header.php or add actions/filters of your own creation.
    • Insert it using javascript

    Adding a header action

    say in header.php I have a large blue square containing a message, and I want to eb able to insert stuff afterwards via a hook, I can do:

    <div id="bigbluesquare">
        <div id="bigsquaremessage">
            <p>message</p>
        </div>
        <?php do_action('after_big_blue_box_message'); ?>
    </div>
    

    I can now put in functions.php something like this:

    add_action('after_big_blue_box_message','hello_world');
    
    function hello_world(){
        echo '<p>hello world</p>';
    }
    

    And hello world will be displayed after the big square message

    Of course you will need to add the do_action calls in the appropriate places

    Adding wp_head

    This will insert code into the <head> tags, and works the same as the above example.

    Inserting With Javascript

    This might work, but will assume you know the ID and classes

    How Do I insert header content That Will Work With Any Theme?

    You can’t.

    There is no standard hook that hooks into the header area. It wouldn’t make sense on a lot of themes as header layouts vary wildly. Some themes don’t have headers.

  3. It all depends upon the theme, what you want to change, and if WordPress and/or the theme provide filters and hooks to accomplish it. A child theme would most likely be your best (and safe) bet.

    A simple child theme is very easy to setup and code. Take a look at he CODEX docs here.