Get posts by category or copyright wordpress

I want to receive posts from a specific category or posts defined by a specific user. It seems we can only have an AND condition in wordpress. I know the below code is wrong, but this is what I need to get - I want all posts written by a specific user or all posts from a specific 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, help. Thanks in advance.

+3


source to share


3 answers


I found a solution for this, I did it with a custom request

 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 category IDs and $ authors is an array with your author IDs. Hope this helps someone in need of this.

0


source


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)

      

+1


source


If you want both to run get_posts()

2 times.

  • all user posts
  • all posts from a category and then concatenate both arrays with array_merge()

0


source







All Articles