Support » Fixing WordPress » Add "Category" to Custom Query Mysql

  • elia866

    (@elia866)


    Hallo forum 🙂

    I’ve this mysql query:

    $querystr = "
     SELECT DISTINCT meta_value  FROM $wpdb->postmeta WHERE post_id IN(
     SELECT DISTINCT wpostmeta.post_id
     FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
     WHERE wposts.ID = wpostmeta.post_id
     AND wpostmeta.meta_key  = 'Land'
     AND wpostmeta.meta_value  = 'Europe'
     AND wposts.post_type = 'post' )
     AND meta_key ='city'
     ORDER BY $wpdb->postmeta.meta_value ASC
     ";
     $cities = $wpdb->get_results($querystr, OBJECT);

    How can i add search for “category name or ID” ?

    Thanks!!! 😉

Viewing 1 replies (of 1 total)
  • vtxyzzy

    (@vtxyzzy)

    Try this (change the category name and meta variables to your own values):

    $cat_name = 'My Category';
    $meta_key_1 = 'Land';
    $meta_value_1 = 'Europe';
    $meta_key_2 = 'city';
    $querystr = "
     SELECT DISTINCT meta_value
      FROM $wpdb->postmeta
      WHERE post_id IN(
        SELECT DISTINCT wpostmeta.post_id
        FROM $wpdb->postmeta wpostmeta
        JOIN $wpdb->posts wposts ON wposts.ID = wpostmeta.post_id
        JOIN $wpdb->term_relationships tr ON wposts.ID = tr.object_id
        JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        JOIN $wpdb->terms t ON tt.term_id = t.term_id
        WHERE tt.taxonomy = 'category'
        AND t.name = '$cat_name'
        AND wpostmeta.meta_key  = '$meta_key_1'
        AND wpostmeta.meta_value = '$meta_value_1'
        AND wposts.post_type = 'post' )
     AND meta_key ='$meta_key_2'
     ORDER BY $wpdb->postmeta.meta_value ASC
    ";
    $cities = $wpdb->get_results($querystr, OBJECT);
Viewing 1 replies (of 1 total)
  • The topic ‘Add "Category" to Custom Query Mysql’ is closed to new replies.