Home » Php » php – How to create a query that return custom post type by Advanced Custom Field(ACF) Taxonony?

php – How to create a query that return custom post type by Advanced Custom Field(ACF) Taxonony?

Posted by: admin February 25, 2020 Leave a comment

Questions:

you all!

I have categories of Author

  • 1 – Freelancer
  • 2 – Contract
  • 3 – Half-time

I have categories of Books

  • 1 – Novel
  • 2 – Fiction

I have a custom post type Author. Author has custom fields:

  • Name: Text
  • Type: Category

I have a custom post type Book. Book has custom fields:

  • Title: Text
  • Author: Taxonomy
  • Type: Category
  • Pages: Number

I need a query that return ALL BOOKs with Authors that have Contract ID = 1

And

I need a query that return ALL BOOKs with Type = Fiction

Thanks!!!

How to&Answers:

You should use meta_query to get the desired results:

I need a query that return ALL BOOKs with Authors that have Contract ID = 1

$freelance_books = get_posts(array(
    'numberposts'   => -1,
    'post_type'     => 'books',
    'meta_key'      => 'book_contract', // Adjust here with your field name
    'meta_value'    => 1
));

I need a query that return ALL BOOKs with Type = Fiction

$fiction_books = get_posts(array(
    'numberposts'   => -1,
    'post_type'     => 'books',
    'meta_key'      => 'book_type', // Adjust here with your field name
    'meta_value'    => 2
));