Skip to content

Instantly share code, notes, and snippets.

@dankoch-cz
Created November 24, 2021 12:02
Show Gist options
  • Select an option

  • Save dankoch-cz/aa7cb0459f12b7eee65b6188e15a4499 to your computer and use it in GitHub Desktop.

Select an option

Save dankoch-cz/aa7cb0459f12b7eee65b6188e15a4499 to your computer and use it in GitHub Desktop.
Search DB for posts including protected files
<?php
/*
* Query that search wp_posts table for title with defined cpt, taxonomy and taxonomy term ID
*/
global $wpdb;
$table_name = "{$wpdb->prefix}posts";
//Define post type
$post_type = "cpt";
//Define taxonomy and term_ID
$taxonomy = "cpt_category";
$term_ID = 123;
//Search for title
$title = 'test';
$sql = $wpdb->prepare( 'SELECT ID FROM '.$table_name.' AS p
INNER JOIN wp_term_relationships AS tr ON (p.ID = tr.object_id)
INNER JOIN wp_term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
INNER JOIN wp_terms AS t ON (t.term_id = tt.term_id)
WHERE p.post_status = "publish"
AND p.post_type = "'.$post_type.'"
AND tt.taxonomy = "'.$taxonomy.'"
AND p.post_title LIKE "%'.esc_sql($title).'%"
AND tt.term_id = '.$term_ID.'
ORDER BY p.post_date DESC');
$records = $wpdb->get_results( $sql , ARRAY_A );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment