Created
August 31, 2024 13:38
-
-
Save aliboy08/c6a3d8e0db23981068effb6617b7ef3e to your computer and use it in GitHub Desktop.
optimized db query for post_ids or posts count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function ffdb($args){ | |
global $wpdb; | |
$post_type = $args['post_type'] ?? 'post'; | |
$post_status = $args['post_status'] ?? 'publish'; | |
$term_id = $args['term_id'] ?? null; | |
$meta_key = $args['meta_key'] ?? null; | |
$meta_value = $args['meta_value'] ?? null; | |
$select = $args['select']; | |
$select_query = 'ID'; | |
if( $select == 'count' ) { | |
$select_query = 'count(ID) as count'; | |
} | |
$join = ''; | |
if( $term_id !== null ) { | |
$join .= " LEFT JOIN {$wpdb->prefix}term_relationships ON object_id = ID"; | |
} | |
if( $meta_key !== null ) { | |
$join .= " LEFT JOIN {$wpdb->prefix}postmeta ON post_id = ID"; | |
} | |
$query = "SELECT {$select_query} FROM {$wpdb->prefix}posts {$join} WHERE post_status = '{$post_status}' AND post_type = '{$post_type}'"; | |
if( $term_id !== null ) { | |
$query .= " AND term_taxonomy_id = {$term_id}"; | |
} | |
if( $meta_key !== null ) { | |
$query .= " AND meta_key = '{$meta_key}'"; | |
} | |
if( $meta_value !== null ) { | |
$query .= " AND meta_value = '{$meta_value}'"; | |
} | |
$result = $wpdb->get_results($query); | |
if( $select == 'count' ) { | |
return $result[0]->count; | |
} | |
$ids = []; | |
foreach( $result as $row ) { | |
$ids[] = $row->ID; | |
} | |
return $ids; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment