本帖最后由 易西 于 2023-10-12 16:18 编辑
Querying by Post Type
You can query posts of a specific type by passing the post_type key in the arguments array of the WP_Query class constructor.
Copy
- <?php
- $args = array(
- 'post_type' => 'product',
- 'posts_per_page' => 10,
- );
- $loop = new WP_Query($args);
- while ( $loop->have_posts() ) {
- $loop->the_post();
- ?>
- <div class="entry-content">
- <?php the_title(); ?>
- <?php the_content(); ?>
- </div>
- <?php
- }
复制代码
This loops through the latest ten product posts and displays the title and content of them one by one.
Top ↑
Altering the Main Query
Registering a custom post type does not mean it gets added to the main query automatically.
If you want your custom post type posts to show up on standard archives or include them on your home page mixed up with other post types, use the pre_get_posts action hook.
The next example will show posts from post, page and movie post types on the home page:
Copy
- function wporg_add_custom_post_types($query) {
- if ( is_home() && $query->is_main_query() ) {
- $query->set( 'post_type', array( 'post', 'page', 'movie' ) );
- }
- return $query;
- }
- add_action('pre_get_posts', 'wporg_add_custom_post_types');
复制代码
|