简体   繁体   中英

Wordpress query_posts displayed by category custom field

Have wordpress based site, where:

  • MainCategory

    • Subcategory(custom-field value = custom1)
    • Subcategory2(custom-field value = custom2)
    • Subcategory3(custom-field value = custom3)
  • MainCategory2

    • Subcategory(custom-field value = custom1)
    • Subcategory2(custom-field value = custom2)
    • Subcategory3(custom-field value = custom3)
  • MainCategory3

    • Subcategory(custom-field value = custom1)
    • Subcategory2(custom-field value = custom2)
    • Subcategory3(custom-field value = custom3)

As you can see, all subacegories in main categories are the same. With same name (not slug), and there are custom fields with same field values.

I need to display posts that is in MainCategory2 AND subcategory has custom field with value custom2 . Is this possible?

PS I use ACF plugin for custom fields.

I'm not sure if this is the best solution, but it will hopefully solve your problem.

  1. Loop all posts of MainCategory2 (let's assume, this category has the ID 2)
  2. Check if the content of the custom-field is equal custom2.
  3. Define what should be looped (in this example it's the blogtitle and link)

The code would look like this:

<?php query_posts( 'showposts=20&cat=2&order=ASC' ); ?>
   <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

      <?php if( get_field('custom-field') == 'custom2' ): ?>
         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br />
      <?php else : ?>
      <?php endif; ?>

<?php endwhile; endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM