WordPress: Conditional PHP code to check if page is set as the website home page

Here is the code I use in my WordPress template files to add a conditional statement which checks to see if a page is set in the dashboard as the site home page:

<?php 
$front_page = get_option('page_on_front');
if (!is_page($front_page) ) { ?>
Show this text on the front page of the website.
<?php } ?>

How to add an incrementing number counter inside the WordPress “while” loop

This morning I spent some time figuring out how to add an incrementing number counter inside a WordPress “while” loop and here is how I finally accomplished it:

I defined the first number (in this case, the variable $postnum) before the “while” loop started, like so:

<?php $the_query = new WP_Query( $query_string.'showposts=4' ); ?>
<?php $postnum = 0; ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

Then I added my div with the incrementing number class within the “while” loop, like so:

 
<?php $postnum++;
	echo "<div class='homepagepost-";
	echo $postnum;
	echo "'></div>";
?>

Now my output for each post includes my custom-numbered div:

<div class="homepagepost-1"></div>
<div class="homepagepost-2"></div>
<div class="homepagepost-3"></div>

Resolved: Updating the server PHP version to 5.4 broke my Genesis Simple Sidebars plugin

I had to resolve an issue recently where a client’s hosting company had updated the PHP version of the server to 5.4 and this “broke” the plugin Genesis Simple Sidebars that was being used on their site, therefore causing the whole site to be down. The PHP error message being displayed in a browser when you tried to visit a site is what told me it was the Genesis Simple Sidebars plugin that was causing the site to be down.

I found this extremely useful thread which ultimately helped me to fix the issue – http://wordpress.org/support/topic/error-after-updating-to-php-54 – but want to outline what I did here to save others from having to scroll through the entire thread.

Step 1: Log into PHPMyAdmin or whichever interface you use to edit the database.

Step 2: Navigate to the wp_options table on the database (note: this may not be the exact name of the table, your table could be named differently depending on the $table_prefix defined in your WordPress site’s wp-config.php file)

Step 3: Navigate to the “ss_settings” field in the options table and open it to edit it.

Step 4: Remove this line of code from the beginning of the “ss_settings” content:

i:0;s:20:"__return_empty_array";

Step 5: Find the number listed right after “a:” at the beginning of the “ss_settings” content and subtract 1 from that number. So, for example, if the beginning of your “ss_settings” field looked like this:

a:37:

You will want to change it to read:

a:36:

Step 6: Save your changes to the “ss_settings” field and navigate to your website in a browser. Hopefully your site will be back up and running now!

 

WordPress Tricks: Customizing the output of “wp_nav_menu()”

There are times when I need to output a menu in WordPress with very custom settings – for example, with no containing UL, with a specific class on the wrapping UL, with the links wrapped in specific tags (spans, for example), etc. Here is the call to a WordPress menu that I use and customize to output the menu exactly as I need it:

<?php wp_nav_menu( 
array ( 
'menu' => 'Main Menu', //the name of the menu you are trying to output
'container' =>false, //set to UL or DIV, or 'false' for no wrapper
'container_class' => '',//the class that is applied to the container
'container_id'    => '',//the id that is applied to the container
'before' => '<div>', //what the a tags themselves are wrapped in
'after' => '</div>', //what the a tags themselves are wrapped in 
'link_before' => '<span>', //what the words within the link are wrapped in 
'link_after' => '</span>', //what the words within the link are wrapped in
'items_wrap' => '%3$s', //what the LI elements are wrapped in - "%3$s" is the LI list itself. To wrap the LI list in a div, you would use "<div class="YOURCLASS">%3$s</div>"
'depth' => 0, ) ); ?>

An article which explains the “items_wrap” argument excellently is http://wordpress.stackexchange.com/questions/19245/any-docs-for-wp-nav-menus-items-wrap-argument so be sure to check that out if you are looking for more information.

And of course, for information on all of the parameters that you can use in wp_nav_menu, you will want to check out the official documentation on WordPress – http://codex.wordpress.org/Function_Reference/wp_nav_menu

WordPress Tricks: How to add the name of parent category to the body class of a child category archive page

Here is the snippet of code I use to add a specific body class to the child category archive pages on a WordPress site. Paste this into the header.php file of your site’s theme:

<?php $this_category = get_category($cat);
if ($this_category->category_parent == 0) {
$this_category->category_parent = $cat;
} else {
$parent_category = get_category($this_category->category_parent);
$ParentCatId = $parent_category->cat_ID;
$ParentCatName = $parent_category->slug;
}
$childcategories = array();
$catx = $ParentCatId;
$cats = get_categories('parent='.$catx);
foreach($cats as $cat) {
$childcategories[] = $cat->term_id; } ;
if( is_category( $childcategories ) ) {
$class = 'child-category-of-'.$ParentCatName;
}
?> 

Next, make sure the body tag in the header.php file looks like this:

<body <?php body_class($class); ?>>

What this code will do is add the class “child-category-of-cooking-tips” to any archive page for subcategories of the category Cooking Tips.

Please let me know if you have any trouble implementing this into your site or if you are looking for customizations to this code.

A quick way to fix the broken pagination on your WordPress category or archive pages when using custom queries

Here is the useful code snippet that I use to fix the issue where using a custom query on a WordPress category or archive or even index page breaks the pagination.

Simply copy and paste this code into your theme’s functions file:

function my_post_queries( $query ) {
 // do not alter the query on wp-admin pages and only alter it if it's the main query
 if (!is_admin() && $query->is_main_query()){
// alter the query for the home page
 if(is_home()){
 $query->set('posts_per_page', 3);
 $query->set('cat', '9');
 }
}
add_action( 'pre_get_posts', 'my_post_queries' );

And then edit as necessary!

To target a specific category, you would use this code:

 // alter the query for the Apples category page 
    if(is_category('Apples')){
      $query->set('posts_per_page', 6);
    }

I have found this to be one of the easiest ways to fix the pagination issues I have run into when using custom WordPress queries. Let me know if you have a different or better way of doing so :)

Source

 

WordPress Tricks: Use a WordPress query to exclude a category from your home page without breaking pagination

Here is the code I use in a WordPress site’s index.php file to exclude a specific category from the home page withOUT breaking the pagination:

<?php if ( is_home() ) { query_posts( $query_string.'&cat=-21' ); } ?>

Of course, to include a specific category, you would use this:

<?php if ( is_home() ) { query_posts( $query_string.'&<span style="color: #ff0000;">cat=4</span>' ); } ?>

WordPress Tips: How to remove the extra space between LI elements from wp_nav_menu

Here is the snippet of code I use to remove the extra space that WordPress adds to the end of

  • elements when you use wp_nav_menu to call in a menu:

    <?php $custommenu = wp_nav_menu ( array (
    		'container_class' => 'my-menu',
    		'theme_location' => 'primary',
                    'echo'            => 0
     ) );
    $custommenu = str_replace("\n", "", $custommenu);
    $custommenu = str_replace("\r", "", $custommenu);
    echo $custommenu;
    ?>
  • WordPress Tricks: How to Show Most Recent Posts from Specific Categories with Thumbnails

    Here is the code I use to show a certain number of the most recent posts including their thumbnails from specific categories in a WordPress website.

    To show the 3 most recent posts from Category 1, you would add this code to the appropriate template file of your site:

    <?php
    //for category 1, show 3 posts
    $cat_args=array(
      'include' => '1',
      'orderby' => 'name',
      'order' => 'ASC'
       );
    $categories=get_categories($cat_args);
      foreach($categories as $category) {
        $args=array(
          'showposts' =>3,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
        );
        $posts=get_posts($args);
          if ($posts) {
            echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <p class="recent-posts"><span class="thumb"><?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?></span>
    <span class="recent-post"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></span></p>
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>

    You will want to edit the category ID(s) in this code of course so that you call the posts from the correct categories of your site, and you may also want to edit the number of posts shown from the categories as well.

    To show the 3 most recent posts from Categories 1, 2, AND 3, you would use this code:

    <?php
    //for categories 1, 2, and 3, show 3 posts
    $cat_args=array(
      'include' => '1,2,3',
      'orderby' => 'name',
      'order' => 'ASC'
       );
    $categories=get_categories($cat_args);
      foreach($categories as $category) {
        $args=array(
          'showposts' =>3,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
        );
        $posts=get_posts($args);
          if ($posts) {
            echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <p class="recent-posts"><span class="thumb"><?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?></span>
    <span class="recent-post"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></span></p>
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>

    If you want to include the excerpt of each post, you would use this code:

     

    <?php
    //for category 1, show 3 posts
    $cat_args=array(
      'include' => '1',
      'orderby' => 'name',
      'order' => 'ASC'
       );
    $categories=get_categories($cat_args);
      foreach($categories as $category) {
        $args=array(
          'showposts' =>3,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
        );
        $posts=get_posts($args);
          if ($posts) {
            echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <p class="recent-posts"><span class="thumb"><?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?></span>
    <span class="recent-post"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></span>
    <br/><span class="excerpt"><?php the_excerpt(); ?></span></p>
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>

    Let me know if you have any questions or need any further modifications to this code :)

    WordPress Tricks: Add a div or other element to one specific page or page type

     

    Here is the code I use to add a div or image or other element to just one page or category page of my WordPress sites:

    This code will add a div with the id “featured_content” only on the home page:

    <?php if ( is_home() ) { ?>
    <div id="featured_content">
    &nbsp;
    </div>
    <?php } ?>

     

    This code would add a div with the id “featured_recipe” to all posts in the category “recipes.”:

    <?php if ( is_category('recipes') ) { ?>
    <div id="featured_recipe">
    &nbsp;
    </div>
    <?php } ?>

     

    This code would exclude “myimage.jpg” only on the Contact page:

    <?php if ( !is_page('contact') ) { ?>
    <img src="myimage.jpg">
    <?php } ?>

     

    As you can see, there are many uses and ways implementations of this code. Let me know if you have any questions or need further assistance.