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:
  1. $option = get_option( 'option_name' );
  2. if ( ! $option )
  3. $option = $default_value;
But there is a better way to set option value if it doesn’t exists:
  1. $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():
  1. if ( ! is_page( 'about' ) && ! is_page( 'contact' ) && ! is_page( 'archives' ) )
  2. if ( function_exists( 'ADDTOANY_SHARE_SAVE_KIT' ) )
  3. 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 (IDslug, etc.). So I rewrite the code above with the following:
  1. if ( ! is_page( array( 'about', 'contact', 'archives' ) ) && function_exists( 'ADDTOANY_SHARE_SAVE_KIT' ) )
  2. 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 templatetemplate_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:
  1. $template_file = get_post_meta( get_the_ID(), '_wp_page_template', true );
  2. if ( 'custom_template.php' == $template_file ) {
  3. // Do stuff
  4. } else {
  5. // Do stuff
  6. }



No comments:

Post a Comment

NEWS