自定义文章类型

 火... [复制链接]  373查看
 楼主| 易西 发表于 2023-10-12 15:06:43 | 显示全部楼层
本帖最后由 易西 于 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
  1. <?php
  2. $args = array(
  3.         'post_type'      => 'product',
  4.         'posts_per_page' => 10,
  5. );
  6. $loop = new WP_Query($args);
  7. while ( $loop->have_posts() ) {
  8.         $loop->the_post();
  9.         ?>
  10.         <div class="entry-content">
  11.                 <?php the_title(); ?>
  12.                 <?php the_content(); ?>
  13.         </div>
  14.         <?php
  15. }
复制代码

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
  1. function wporg_add_custom_post_types($query) {
  2.         if ( is_home() && $query->is_main_query() ) {
  3.                 $query->set( 'post_type', array( 'post', 'page', 'movie' ) );
  4.         }
  5.         return $query;
  6. }
  7. add_action('pre_get_posts', 'wporg_add_custom_post_types');
复制代码

 楼主| 易西 发表于 2023-10-12 16:31:11 | 显示全部楼层
Custom Post Type Templates
You can create custom templates for your custom post types. In the same way posts and their archives can be displayed using and , you can create the templates:single.phparchive.php

single-{post_type}.php – for single posts of a custom post type
archive-{post_type}.php – for the archive
Where is the post type identifier, used as the argument of the function.{post_type}$post_typeregister_post_type()

Building upon what we’ve learned previously, you could create and template files for single product posts and the archive.single-wporg_product.phparchive-wporg_product.php

Alternatively, you can use the is_post_type_archive() function in any template file to check if the query shows an archive page of a given post type, and the post_type_archive_title()  function to display the post type title.
[发帖际遇]: 易西 被钱袋砸中进医院,看病花了 1 金钱. 幸运榜 / 衰神榜
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

邮箱|首页|小黑屋|吾侪 ( 蜀ICP备2020029307号-4 )

GMT+8, 2025-12-2 00:56 , Processed in 0.044331 second(s), 17 queries , APCu On.

Powered by Discuz! X3.5

Copyright © , 吾侪网

快速回复 返回顶部 返回列表