Home Forums General Issues Query posts by custom fields


Query posts by custom fields

  • Hi there,

    Looking to query a custom post-type by custom fields but want the second meta_query to vary depending on the page slug. Not sure how to go about this whether to duplicate the query or if someone knows something a smarter way to go about this.

    e.g. if page slug equals slug1, 2nd meta_query value = value1, if page slug equals slug2, 2nd meta_query value = value2.

    $args = array(
    ‘post_type’ => ‘testimonial’,
    ‘posts_per_page’ => 2,
    ‘meta_query’ => array(
    ‘key’ => ‘testimonial_type’,
    ‘value’ => ‘Video’,
    ‘compare’ => ‘=’,
    ‘key’ => ‘product’,
    ‘value’ => ‘———-here—–‘,
    ‘compare’ => ‘=’,
    $testimonial_posts = new WP_Query($args);
    <?php if($testimonial_posts->have_posts()) : ?>

    <?php endif; ?>’

  • Hi @renee

    I believe you were talking about the current page slug where it shows the custom post type, right? In this case, I think you can get the current page slug like this:

    global $post;

    After that, you need to convert the page slug to the value you want like this:

    if( $page_slug == "slug1" ){
        $value = "value1";
    }elseif( $page_slug == "slug2" ){
        $value = "value2";
        $value = "value3";

    Then you can use it like this:

        'key' => 'product',
        'value' => $value,
        'compare' => '=',

    I hope this makes sense 🙂

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.