WordPress.org

Forums

Advanced Custom Fields
Using a custom field value in WP_query (5 posts)

  1. rengland77
    Member
    Posted 3 years ago #

    So I'm displaying a few blog posts in a template, based off whatever category name the client types into the ACF box. How can I use that category value into a wp_query loop?

    <?php
    $args=array(
    'post_type' => 'post',
    'category_name' => 'blog_category',
    'posts_per_page' => '2',
    );
    
    $my_query = new WP_Query($args);
    
    if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); ?>
    
    <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
    	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    	<?php the_excerpt(); ?>
    </div>
    
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

    Thanks :)

    http://wordpress.org/extend/plugins/advanced-custom-fields/

  2. kg69design
    Member
    Posted 3 years ago #

    I wanted to install this plugin, but many important questions unanswered - that is sad. I will look for an alternative.

  3. Jason Bahl
    Member
    Posted 3 years ago #

    You would capture the field value as a variable, then use the variable in the Query args.

    For example:

    $category = get_field('category_field_name');

    Then in your args:

    <?php
    $args=array(
    'post_type' => 'post',
    'category_name' => ''.$category.'',
    'posts_per_page' => '2',
    );

    Hope this helps

  4. kg69design
    Member
    Posted 3 years ago #

    Thanks, I'll try.

  5. Xtremefaith
    Member
    Posted 3 years ago #

    Try this post, it looks to be on target with what you're attempting and it's based on a previous post on his site that asked the same question.

    http://www.advancedcustomfields.com/support/discussion/112/wp_query-orderby-field-name

    I'd be surprised if Visioniz suggest works because get_field() would be based on what post id (the one you're ABOUT to loop)? Seems like at most you could run a loop and get the ID(s) you need and run another loop but that's not efficient at all and I have little faith it would work.

    Post back how well that post helps, good luck

Topic Closed

This topic has been closed to new replies.

About this Plugin

  • Advanced Custom Fields
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic