Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adicahyaludin/e958c6e84f1556fb4538af934692c7c4 to your computer and use it in GitHub Desktop.
Save adicahyaludin/e958c6e84f1556fb4538af934692c7c4 to your computer and use it in GitHub Desktop.
wp post query where authors or category with wpdb
$cat_ids = "11,12,13";
$author_ids = "1,2,3";
$length = 8;
$offset = 0;
global $wpdb;
$sql = "SELECT *
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships as t
ON ID = t.object_id
WHERE post_type = 'post' AND post_status = 'publish'";
if ( !empty( $cat_ids ) || !empty( $author_ids ) ) :
$sql .= " AND ( ";
if ( !empty( $author_ids ) ) :
$sql .= " post_author IN (".$author_ids.")";
endif;
if ( !empty( $cat_ids ) && !empty( $author_ids ) ) :
$sql .= " OR ";
endif;
if ( !empty( $cat_ids ) ) :
$sql .= " term_taxonomy_id IN (".$cat_ids.")";
endif;
$sql .= " )";
endif;
$sql .= " ORDER BY ID DESC";
$totals = count($wpdb->get_results( $sql ));
$sql .= " LIMIT ".$length." OFFSET ".$offset."";
$results = $wpdb->get_results( $sql );
global $post;
foreach ( $results as $post ):
setup_postdata( $post );
?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php
endforeach;
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment