What's your Favorite Wordpress Hook?

[ Wordpress ] [ hook ] [ functions.php ] [ plugins ]

I recently wrote a cover letter for a job and they asked applicants to answer this question. If you're new to Wordpress on the programming side, hooks are ways you can insert code into various stages of the processing and display of pages and data. For instance, Woocommerce, a great Wordpress plugin that adds ecommerce support, has a function called woocommerce_process_product_meta. This little guy lets you alert any meta data associated with a product. I used it to set default settings for a site that strictly sells downloadables:

function my_woo_defaults( $id) {

    if ( !isset( $_POST['_regular_price'] ) ) {
        update_post_meta( $id, '_regular_price', '0' );
    }

    update_post_meta( $id, '_virtual', 'yes' );
    update_post_meta( $id, '_downloadable', 'yes' );
    update_post_meta( $id, '_download_type', 'music' );

    return true;
}
add_action( 'woocommerce_process_product_meta', 'my_woo_defaults', 30);

The top if statement after the function declaration (which takes a product id so it knows which product to alter) checks to see if a _regular_price is set. If not, it sets it to '0.' The next 3 functions within the function update default settings of the downloads. The add_action function, which you will see a lot as you continue to hack Wordpress, registers your new hook. My version says 'if woocommerce_process_product_meta happens, call my function called my_woo_defaults, too, and give it the priority if 30 (the priority is how Wordpress orders the running of the functions).

This hook makes it easy to add a product without having to click a bunch of checkboxes to set these variables. While it might not be my favorite hook, it certainly helps speed up the process.

comments powered by Disqus

This space intentionally left blank