j0h4nn3s
j0h4nn3s

Reputation: 2076

Get authors post in wordpress with co-author plus installed

I want to list all posts, a user is assigned as author. We are using the plugin, co-authors plus, which allows to assign multiple authors to a single post. The function <?php $user_post_count = count_user_posts( $userid ); ?> returns the correct number of posts, the user is assigned to. But when trying to list all the posts, with The loop only the post which initially were created by that user are shown.

query_posts( $args );

if (count_user_posts($user->ID) == 0) {
    echo "No posts";
}

// The Loop
while ( have_posts() ) : the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

Is there an other possibility to get all posts from an user or can we modify our existing code?

Upvotes: 1

Views: 3008

Answers (2)

Apurba Podder
Apurba Podder

Reputation: 13

/**
 * @param $user_id
 * @param int $paged (if $paged = null return all posts)
 * @return array|bool
 */
function get_coauthor_posts_by_author_id($id, $paged = 1)
{
    global $wpdb;

    $slug = 'cap-' . strtolower(get_userdata($id)->user_nicename);


    $max_post = get_option('posts_per_page');
    $post_lower_limit = 0;


    if ($paged > 1) {
        $post_upper_limit = $max_post * $paged;
        $post_lower_limit = $post_upper_limit - $max_post;

    }


    $term_id = $wpdb->get_results($wpdb->prepare("SELECT term_id FROM $wpdb->terms WHERE slug = %s ", $slug))[0]->term_id;


    $sql = "SELECT SQL_CALC_FOUND_ROWS  $wpdb->posts.id FROM $wpdb->posts  LEFT JOIN $wpdb->term_relationships AS tr1 ON ($wpdb->posts.id = tr1.object_id) LEFT JOIN $wpdb->term_taxonomy ON ( tr1.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id ) WHERE 1=1  AND (($wpdb->posts.post_author = %d OR ($wpdb->term_taxonomy.taxonomy = 'author' AND $wpdb->term_taxonomy.term_id = %d))) AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') GROUP BY $wpdb->posts.id  ORDER BY $wpdb->posts.post_date DESC";
    $sql_limit = " LIMIT %d, %d";
    if ($paged !== null) {
        $sql = $sql . $sql_limit;
    }



        $result = $wpdb->get_results($wpdb->prepare($sql, $id, $term_id, $post_lower_limit, $max_post), ARRAY_A);
        return array_column($result, 'id');


}

Upvotes: 0

Omer Farooq
Omer Farooq

Reputation: 4084

EDIT

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'author',
            'field' => 'slug',
            'terms' => $user_login
        )
    ),
);
$author_query = new WP_Query( $args );

if ( $author_query->have_posts() ) :
    while ( $author_query->have_posts() ) : $author_query->the_post();

    // Do your presentation

    endwhile;
endif;

Upvotes: 1

Related Questions