This article mainly introduces the methods used in WordPress to obtain the author and category information. they are all from the WP_Query class of WordPress. For more information, see
Author
You can use four parameters to query articles related to some authors (users:
- Author (integer): User ID
- Author_name (string): User's nickname ("user_nicename" field)
- Author _ in (array): User ID
- Author _ not_in (array): User ID
Get an author's article
Get by user ID:
$query = new WP_Query( 'author=123' );
Obtain the following information based on the user's nickname ("user_nicename" field:
$query = new WP_Query( 'author_name=rami' );
Obtain articles from multiple authors
Obtain the articles of multiple authors based on the user ID:
$query = new WP_Query( 'author=2,6,17,38' );
Exclude the author's article
To exclude an author, add "-" to the front of the user ID:
$query = new WP_Query( 'author=-12' );
Multi-Author Query
Get articles from multiple authors:
$query = new WP_Query( array( 'author__in' => array( 2, 6 ) ) );
Exclude articles from multiple authors:
$query = new WP_Query( array( 'author__not_in' => array( 2, 6 ) ) );
Category
There are five available parameters for classification:
- Cat (integer): Category ID
- Category_name (string): Category alias
- Category _ and (array): category ID
- Category _ in (array): category ID
- Category _ not_in (array): category ID
Get an article by category
Obtain an article by Category ID (including the subcategory of this category ):
$query = new WP_Query( 'cat=4' );
Obtain an article by category alias (including the subcategory of this category ):
$query = new WP_Query( 'category_name=staff' );
Obtain an article by Category ID (excluding the subcategory of this category ):
$query = new WP_Query( 'category__in=4' );
Get articles of multiple categories
Get articles of multiple categories based on the Category ID:
$query = new WP_Query( 'cat=2,6,17,38' );
Obtain articles of multiple categories based on the category alias:
$query = new WP_Query( 'category_name=staff,news' );
Get articles with several categories based on the category alias:
$query = new WP_Query( 'category_name=staff+news' );
Exclude Category
To exclude some categories, you only need to add the "-" before the Category ID:
$query = new WP_Query( 'cat=-12,-34,-56' );
Multi-category query
Obtain an article with multiple categories at the same time. the code below will obtain an article with both IDs 2 and 6:
$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );
An article that retrieves multiple categories does not contain its subcategories. the following code obtains an article with a classification of ID 2 or ID 6:
$query = new WP_Query( array( 'category__in' => array( 2, 6 ) ) );
Exclude some classified articles:
$query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) );