WordPress: Custom Field Outside Loop Plus If/Else Statement

Testimonials are an excellent way to add affirmation to a website. Some kind words here and there may be the reason a potential client reaches out to hire someone. Recently, a client of ours wanted a specific testimonial in the sidebar on a specific page. The website was already setup to pull testimonials randomly from a group of testimonials. The project is built in WordPress so we knew we had the tools needed to accomplished this dynamically. Our logic was that we could use an If/Else statement in coordination with custom fields to set things up.

Essentially, we would tell the platform that:

  • If: If the custom field exists for a specific testimonial, display that and ignore the random testimonial.
  • Else: If the custom field does not exist, display the random testimonial.

This part was pretty straight forward. The first line of PHP checks to see if the custom field “custom-quote” exists. If it does, it gets displayed using the second line of PHP code. If it does not exist, we pull the random testimonial code instead. The last line closes the statement.

<?php $key = 'custom-quote'; $themeta = get_post_meta($post->ID, $key, TRUE); if($themeta != '') { ?>
    <?php $key="custom-quote"; echo get_post_meta($post->ID, $key, true); ?>
<?php } else { ?>
    // Random Testimonials Code
<?php } ?>

Not Quite There Yet

After adding the code into the sidebar, the custom field was not displaying. Rather, the random quotes were still running. The issue was that the coding is outside of the page loop. After realizing the issue, we reset the query using the following line above our initial code:

<?php global $wp_query; $postid = $wp_query->post->ID; wp_reset_query(); ?>

Putting It All Together

Our final code looks something like this - of course, replacing “// Random Testimonials Code” with our actual coding for that dynamic.

<?php global $wp_query; $postid = $wp_query->post->ID; wp_reset_query(); ?>
<?php $key = 'custom-quote'; $themeta = get_post_meta($post->ID, $key, TRUE); if($themeta != '') { ?>
    <?php $key="custom-quote"; echo get_post_meta($post->ID, $key, true); ?>
<?php } else { ?>
    // Random Testimonials Code
<?php } ?>

Stay In The Loop

Social Gathering

Join our newsletter to get notified about the happenings here at J Taylor Design.