I am trying to properly prepare my data for $ wpdb
$region = $wpdb->get_results( $wpdb->prepare( " SELECT tr.*, count(*) AS jobs_count FROM {$wpdb->terms} tr INNER JOIN {$wpdb->term_taxonomy} tm ON ( tm.term_id = tr.term_id ) INNER JOIN {$wpdb->term_relationships} tmr ON ( tmr.term_taxonomy_id = tm.term_taxonomy_id ) INNER JOIN {$wpdb->posts} p ON ( p.ID = tmr.object_id ) WHERE (tm.parent = '%d' AND tm.taxonomy = '%s' AND p.post_type = '%s' ) GROUP BY name HAVING COUNT(name) > '%d' ", 0, 'location', 'job', 0 ));
I tried this to get the region name. It accurately returns data as expected. But here, the region is the taxonomy of parents, and the country is a children's thing. Therefore, I also wanted to prepare the data for a list of countries. But the problem here is what it is searching under the parent if it exists. Therefore, I am creating a dynamic array for a name named $ sql. The code I want to prepare is shown below as $ country_query.
In the WHERE clause, I use the php implode method to dynamically build queries. Now it works for me. But I also want to prepare the data as a region.
foreach ($region as $reg) { $sql[] = " $wpdb->term_taxonomy.parent = '$reg->term_id' "; } $country_query = "SELECT $wpdb->terms.*, count(*) AS jobs_count FROM $wpdb->terms INNER JOIN $wpdb->term_taxonomy ON ( $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id ) INNER JOIN $wpdb->term_relationships ON ( $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id ) INNER JOIN $wpdb->posts ON ( $wpdb->posts.ID = $wpdb->term_relationships.object_id ) WHERE (". implode(' OR ', $sql) ." AND $wpdb->term_taxonomy.taxonomy = 'location' ) AND $wpdb->posts.post_type = 'job' GROUP BY name HAVING COUNT(name) > 0"; $country = $wpdb->get_results($country_query);
Currently, my query returns this SQL statement after using implode ('OR', $ sql). It will be helpful if anyone knows how to do this, please let me know.
SELECT wp_terms.*, count(*) AS jobs_count FROM wp_terms INNER JOIN wp_term_taxonomy ON ( wp_term_taxonomy.term_id = wp_terms.term_id ) INNER JOIN wp_term_relationships ON ( wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id ) INNER JOIN wp_posts ON ( wp_posts.ID = wp_term_relationships.object_id ) WHERE ( wp_term_taxonomy.parent = '2' OR wp_term_taxonomy.parent = '322' OR wp_term_taxonomy.parent = '651' AND wp_term_taxonomy.taxonomy = 'location' ) AND wp_posts.post_type = 'job' GROUP BY name HAVING COUNT(name) > 0
I also try to find the answer. if I find an answer, I will also share my answer. But I do not know how to prepare implode ('OR', $ sql). If this is not possible and anyone knows, then I should ignore it or try a different approach.
Thanks in advance...
php mysql prepared-statement wordpress wpdb
Faysal haque
source share