akhila
akhila

Reputation: 53

get posts by category or author wordpress

I want to get posts from a particular category or if the post by a particular user . It seems we could only have AND condition in wordpress . I know the below code is wrong but this is what I need to get - I want all the posts written by a particular user OR all the posts from a particular category

$args = array(
    'posts_per_page'   => 10,
    'offset'           => $PageStart,
    'query' => array(
    'relation' => 'OR', /* <--                here */
    array(
        'author' => 18,
    ),
    array(
        'category' => 20,
        )
    ),
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',

);
//print_r($args);
$author_post = get_posts( $args );

Please do help. Thanks in advance .

Upvotes: 3

Views: 906

Answers (3)

akhila
akhila

Reputation: 53

I have found solution to this ,I have done it with a custom query

 SELECT DISTINCT wposts.* 
            FROM $wpdb->posts wposts
                LEFT JOIN $wpdb->postmeta wpostmeta 
                ON wposts.ID = wpostmeta.post_id 
                LEFT JOIN $wpdb->term_relationships 
                ON (wposts.ID = $wpdb->term_relationships.object_id)
                LEFT JOIN $wpdb->term_taxonomy 
                ON ($wpdb->term_relationships.term_taxonomy_id 
                  = $wpdb->term_taxonomy.term_taxonomy_id)
                AND wposts.post_status = 'publish'
                AND $wpdb->term_taxonomy.taxonomy = 'category'
                AND ( $wpdb->term_taxonomy.term_id IN($cat_list) 
                OR wposts.post_author IN ($authors) )
            ORDER BY wposts.post_date DESC

where $cat_list is an array with your category ids and $authors is an array with your author ids . Hope this would help someone in need.

Upvotes: 0

Dhinju Divakaran
Dhinju Divakaran

Reputation: 903

Try this code

$args = array(
    'posts_per_page'   => 10,
    'offset'           => $PageStart,
    'author'       => '18',
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',

);
$author_post = get_posts( $args );

$args = array(

    'posts_per_page'   => 10,
    'offset'           => $PageStart,
    'category'         => '20',
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',
);
$category_post = get_posts( $args );
$total_post = array_merge($category_post,$author_post)

Upvotes: 1

Marvin Fischer
Marvin Fischer

Reputation: 2572

If you want both do get_posts() 2 times.

  1. all posts from user
  2. all posts from the category and then merge both arrays with array_merge()

Upvotes: 0

Related Questions