0

I'm trying to build a search query in PHP in WordPress and I need to get all posts by a specific author in a specific category including drafts.

For example, is it possible to do something like, "status=draft and author=12 and category=7"?

Also, I haven't been able to find the page that shows how to build WordPress query.

Note: I'm using the JSON-API plug-in and using it's get_search_results method. It's not clear if it's a full WP_Query like search since "cat=1" and "author=1" does not return results but "demo" and other common keywords return posts.

  • You should try and search it in the site with keywords and I am sure you will find plenty of answer related to your question. – Maruti Mohanty Dec 9 '13 at 10:07
  • 1
    you can try using WP_Query class for this. – nur Dec 9 '13 at 10:18
  • I was trying to use the JSON-API plug-in and use it's "get_search_results" API. I don't think it's the same as WP_Query which our friend linked below. I say this because it finds posts by keywords but when I enter a search like, "cat=1" or "author=1" as described on that page it does not show any results. – 1.21 gigawatts Dec 9 '13 at 10:27
1

You can also use the following query for getting the results if you have author_id, post_status and cat_id with you.

global $wpdb;

$author_id = 1;

$cat_id = 1;

$post_status = 'publish';

/*  Post Titles  */

$search_titles = $wpdb->get_col(        
                "SELECT DISTINCT post_title FROM $wpdb->posts
                LEFT JOIN $wpdb->term_relationships ON
                ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
                LEFT JOIN $wpdb->term_taxonomy ON
                ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
                WHERE $wpdb->posts.post_status = '$post_status'
                AND $wpdb->posts.post_type = 'post'
        AND $wpdb->posts.post_author = $author_id
                AND $wpdb->term_taxonomy.taxonomy = 'category'
                AND $wpdb->term_taxonomy.term_id = $cat_id"        
)
1
<?php 
$args = array(
    'posts_per_page'   => -1,
    'cat'              => 7,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => array('publish', 'draft', 'pending' ),
    'author'           => 1,
); 

$postslist = get_posts( $args );
foreach ( $postslist as $post ) :
  setup_postdata( $post ); ?> 
    <div>
        <?php the_date(); ?>
        <?php the_title(); ?>   
        <?php the_excerpt(); ?>
    </div>
<?php
endforeach; 
wp_reset_postdata();
?>

Replace the category id in 'cat', author id in 'author' and check. Refer: http://codex.wordpress.org/Class_Reference/WP_Query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.