简体   繁体   中英

How to fetch the records from the database with a custom field using where clause?

I have 20 posts on my page and each post has a custom field called is_feature_home . I have to fetch the post where is_feature_home checked.

I tried the below code but I am not getting the correct output

function getpagecompany(){
  global $post;
   $args = array(  
        'post_type' => 'company',
        'post_status' => 'publish',
        'posts_per_page' => 8, 
        'is_feature_home'=>1,
    );

    $loop = new WP_Query( $args ); 
        
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $tid=$loop->ID;

        print_r(the_title);
        // print_r(post_content);

    endwhile;

  wp_reset_postdata(); 
}
/* you must fetch post by meta key so please change your code with below */

function getpagecompany(){
  global $post;
   $args = array(  
        'post_type' => 'company',
        'post_status' => 'publish',
        'posts_per_page' => 8, 
        'meta_key'       => 'is_feature_home',
        'meta_value'     => '1',
        'meta_compare'   => '=' // default operator is (=) equals to 
      );

    $loop = new WP_Query( $args ); 
        
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $tid=$loop->ID;

        print_r(the_title);
        // print_r(post_content);

    endwhile;

  wp_reset_postdata(); 
}

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