Skip to content
Advertisement

WordPress add_filter to element after hook

Is it possible add a filter to a hook after an HTML element thats after the hook?

Example Template file:

do_action('hook_before_logo'); ?>

<a id="logo></a>

** location i want add content **

Or is it possible to add an element around the <a id='logo'></a> ? Like: <div class="logo_container"><a id='logo'></a></div>

Advertisement

Answer

The short answer is “no”. Hooks run at the place that the developer decided to place them. Any code before them, unless “someone somehow” stashed things in global scope, is not available to the hook, and anything after will not have happened yet.

If you have access to the theme, however, you can just move the hook or create a new one.

You could also do this with JS:

document
    .querySelectorAll('#logo')
    .forEach(
        (thing) => {
            const wrapper = document.createElement('div');
            wrapper.classList.add('logo_container');
            thing.parentNode.appendChild(wrapper);
            wrapper.appendChild(thing);
        }
    );

(Pedantic note, I’m using QSA with an ID in order to simplify the code.)

Depending on your theme, you could also just do display: none on the logo and write your own HTML in the hook_before_logo hook.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement