0

I have created this searchfunction that looks like this:

function search_data_fetch() {
    $search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'visitor' ) );
    if ( $search_query->have_posts() ) {
        while( $search_query->have_posts() ) {
          $search_query->the_post();
          ?>

              <div class="module">
                    <span class="infos-name"><?php the_title(); ?></span>
                    <span class="infos-nick"><?php echo the_content(); ?></span>
              </div>

        <?php
        }
        wp_reset_postdata();
    }
    else {
        ?>
              <div id="nothing_found">
                <p>Nothing found</p>
              </div>
    <?php
    }
  die();
}
add_action('wp_ajax_data_fetch', 'search_data_fetch');
add_action('wp_ajax_nopriv_data_fetch', 'search_data_fetch');

And the posts I search for with the custom post type visitor all have a custom meta data field that is called visitor-hide and when it is set to yes I want it to not be visible in the search at all. So how do I exclude posts which have the meta data visitor-hide set to yes from the search results while showing every other post with this post type.

Thank you!

2

You need an additional parameter meta_query in the WP_Query arguments.

$query_args = [
    'posts_per_page' => -1, 
    's' => esc_attr( $_POST['keyword'] ),
    'post_type'  => 'visitor',

    'meta_query' => [
        'key'     => 'visitor-hide',
        'value'   => 'yes',
        'compare' => '!=',
    ]
]

or in cases like yours (query by single custom field):

$query_args = [
    'posts_per_page' => -1, 
    's' => esc_attr( $_POST['keyword'] ),
    'post_type'  => 'visitor',

    'key'     => 'visitor-hide',
    'value'   => 'yes',
    'compare' => '!=',
]

You can find more about custom field parameters in WP_Query here.

  • Thanks, works great with a little modification! – jockebq Apr 12 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.