Jeremiah Sturgill

code etc.

Abusing WordPress Action Hooks to Modify Blocks of Code

Most popular themes for WordPress come equipped with hooks that allow you to insert code in certain places. But what do you do if you want to modify something that doesn’t have a hook in just the right place?

Pretend the following registration form code is located in a file called registration.php in your theme:

<?php do_action( 'before_account_details_fields' ); ?> 
    <div class="register-section" >
        <label for="signup_username">Username</label>
        <input type="text" name="signup_username" id="signup_username" value="" />

        <label for="signup_email">Email Address</label>
        <input type="text" name="signup_email" id="signup_email" value="" />

        <label for="signup_password">Choose a Password</label>
        <input type="password" name="signup_password" id="signup_password" value="" />
        <label for="signup_password_confirm">Confirm Password</label>
        <input type="password" name="signup_password_confirm" id="signup_password_confirm" value="" />
<?php do_action( 'after_account_details_fields' ); ?>

If you want to add the class “registration” to each label, change one of the label texts, or rearrange the order of the fields server-side without modifying registration.php, you have to get creative. One simple and robust solution is to use output buffering to capture the HTML generated between two hooks. For example, this entire block of code can be replaced without touching the theme by using the following code in a plugin or functions.php:

function modify_captured_form()
    $form_html = ob_get_clean();
    include ( 'path/to/new/form.php' );
    // You could also modify the $form_html variable using preg_replace()
    // or any number of other string manipulation functions provided by PHP
    // and then echo the new value.
add_action( 'before_account_details_fields', 'ob_start' );
add_action( 'after_account_details_fields', 'modify_captured_form' );

As long as the code or HTML you’re interested in lies between two hooks, you can capture and modify the output.

Use sparingly.