small-wordpress tips

3 Small But Useful WordPress Tips

Sometimes small things have great value if they’re used in right place. In this post, I’ll show you 3 small WordPress tips that can help you keep your code cleaner but still effective.

1. Check if an option is empty and assign default value

I usually use the following code to check if an option is empty and set the default value if it isn’t:

$option = get_option( 'option_name' );
if ( ! $option )
    $option = $default_value;

But there is a better way to set option value if it doesn’t exists:

$option = get_option( 'option_name', $default_value );

The function get_option() accepts 2nd parameter as default option value. Using this parameter, we don’t need to write more code to check if the $option is empty anymore. It keeps our code shorter and cleaner.

2. Conditional check for multiple posts and pages

At Deluxe Blog Tips, I don’t want to show AddToAny buttons on pages ‘About’, ‘Contact’ and ‘Archives’, so I used a conditional tag is_page():

if ( ! is_page( 'about' ) && ! is_page( 'contact' ) && ! is_page( 'archives' ) )
    if ( function_exists( 'ADDTOANY_SHARE_SAVE_KIT' ) )
        ADDTOANY_SHARE_SAVE_KIT();

But doing 3 checks is not optimal. I want a simple check statement. And I found that the is_page() function accepts an array of page parameters (ID, slug, etc.). So I rewrite the code above with the following:

if ( ! is_page( array( 'about', 'contact', 'archives' ) ) && function_exists( 'ADDTOANY_SHARE_SAVE_KIT' ) )
    ADDTOANY_SHARE_SAVE_KIT();

It’s shorter and more elegant, right?

Not only is_page(), but also is_single(), is_category(), is_tax() accept an array as their arguments. Check out the Codex for more information.

3. Get the template name of current page

We all know that in a page template, we can use is_page_template( 'template_name.php' ) to check if current page has template template_name.php. But there’s a situation like this: you’re trying to list sub-pages of the current page, and each sub-page might have its own template file. How can you get the template file of the sub-pages?

I’ve found a simple solution for that situation. The template file name is saved in page’s custom field named _wp_page_template. So, checking the template name is easy as the following:

$template_file = get_post_meta( get_the_ID(), '_wp_page_template', true );
if ( 'custom_template.php' == $template_file ) {
    // Do stuff
} else {
    // Do stuff
}

2 comments

  1. Trying to get over these tips by applying to my own blog. Keep sharing posts like this. Thanks

Comments are closed.