Last Updated: September 09, 2019
·
7.876K
· jaredhughes

Advanced WordPress Loops with Advanced Custom Fields

We recently launched a site for the Alabama Department of Commerce. One of the primary objectives of the site centers around the concept of brand journalism. This meant pushing traditional WordPress Posts further than normal in order to maximize the control and flexibility that could be provided to the PR department.

One of the key features we provided was the substantial level of control over the placement of stories throughout the site. Any given post could have primary or secondary (and sometimes, tertiary) placement on the homepage, "News Center", and/or the category page.

While it's not very difficult to throw a few custom field options into wp-admin, the Advanced Custom Fields plugin does an excellent job of providing an extremely user friendly interface for our friends in the PR Department. With a combination of checkboxes, radio buttons, and dropdowns, an author can select the pages (including categories) and placement of the post.

Picture

So what does the query look like? Here's the loop that queries secondary stories on our News Center page:

<?php 
  $news_secondary_args = array(
    'post_type' => 'post',
    // Fetch two posts to go right of Primary Featured story
    'posts_per_page' => 2,
    // Query posts' meta 
    'meta_query' => array( 
      array(
        // Require post to have Featured Image
        'key' => '_thumbnail_id'
      ),
      array(
        // Key = ACF Field Name (True/False field)
        'key' => 'feature_on_news_center',
        // Value = 1, so 'True' radio button is selected 
        'value' => '1'
      ),
      array(
        // Key = ACF Field Name (Radio Button)
        'key' => 'news_placement',
        // The value selected (other options include 'primary' & 'tertiary')
        'value' => 'secondary'
      )
    )
  );

  // The Loop
  $news_secondary_query = new WP_Query( $news_secondary_args );
  while ( $news_secondary_query->have_posts() ) :
    $news_secondary_query->the_post(); 

?>

<!-- <html> -->

<?php 
    endwhile; // End Loop
    wp_reset_postdata(); // Reset post data in order to run additional loops such as this
?>