Home > Mobile >  Get custom post types posts using custom meta fileds value wordpress
Get custom post types posts using custom meta fileds value wordpress

Time:04-27


$posts = new WP_Query( [
        'post_type'  => 'mock_test',
        'meta_query' => array(
        'key'     => 'selectedchapter',
        'value' => 15
        ),
    ] );

 echo "<pre>";
 print_r($posts);
 echo "</pre>";

I need to get posts which have selected chapter 2 in custom meta box. This WP_Query not working for me, I'm getting all the posts. see attached screenshot (https://prnt.sc/vuzw6lhW44mR) of metabox html structure.

CodePudding user response:

What is the custom field? Whenever You need to add extra field inside the existing form it’s call custom fields. The custom field is known as a meta box in WordPress. WordPress provides a function and hook add_meta_box using it we can add custom fields inside any post type. Most of the time WordPress stored the meta box value in wp_postmeta database table except for some specific data like the post type. Don’t confuse the custom field and meta box both are same.

The met box is helpful to describe the post in a proper manner. For example, Post type and post format are meta box. In WooCommerce, The price and sales price field is a custom field.

The custom fields are very helpful when you are working site like Real Estate, Freelancing, Movie, Review etc… WordPress get post meta value WordPress provides a get_post_meta function for getting the meta field value. It works with all post types like post, page, products and custom post type etc…

You can get the post meta value, page, products and any custom post type meta field value using get_post_meta functions. It’s accept three parameters:

1-$post_id: the post ID is required. You should pass the post ID of that you want to fetch the meta field value. 2-$key: the key is not required but when you want to fetch specific meta field value of the post then you should specify the meta key. 3-$single: This parameter will works only when you specify a key. It indicates the custom field value is an array or not. Let’s see the example how we can use the WordPress get_post_meta function.enter code here

ID, '_your_meta_key_name', true );`enter code here` First of all, Let’s see how we can get the all post meta values. Lorem Ipsum text ) Now, What if you want to get the text instead of Array? Then you should pass the **true** as a **single** like.

CodePudding user response:

Try using tax_query. Something like this:

$posts = new WP_Query( array(
         'post_type' => 'mock_test',
         'tax_query' => array(
          array (
          'taxonomy' => 'taxonomy_slug',
          'field' => 'slug',
          'terms' => 'taxonomy_value', // maybe chapter2 in you case
         )
     ),
) );

echo "<pre>";
print_r($posts);
echo "</pre>";

Refer this to understand more about tax_query: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

  • Related