wordpress调用自定义文章类型
时间 : 2024-01-09 12:52:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性
最佳答案
要在WordPress中调用自定义文章类型,你需要按照以下步骤进行操作:
步骤 1:创建自定义文章类型
首先,在你的主题的functions.php文件中添加以下代码来创建一个新的自定义文章类型(例如:books):
function create_custom_post_type() {
register_post_type( 'books',
array(
'labels' => array(
'name' => __( 'Books' ),
'singular_name' => __( 'Book' )
),
'public' => true,
'has_archive' => true,
)
);
}
add_action( 'init', 'create_custom_post_type' );
以上代码将创建一个名为“Books”的自定义文章类型,并为其添加了一些基本的标签和选项。
步骤 2:创建一个自定义模板(可选)
如果你希望为自定义文章类型创建一个专门的模板,可以在主题文件夹中创建一个名为single-books.php的文件。在该文件中,你可以自定义自定义文章类型的展示方式。
步骤 3:调用自定义文章类型模板
要在前端页面中调用自定义文章类型模板,可以使用以下代码:
<?php
$args = array(
'post_type' => 'books',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
// 在这里编写你想要显示的自定义文章类型内容
endwhile;
endif;
// 重置查询
wp_reset_postdata();
?>
将上面的代码插入到你想要显示自定义文章类型的位置,即可按照你在单个自定义模板中定义的方式展示自定义文章类型的内容。
希望以上步骤对你有所帮助!
其他答案
在WordPress中调用自定义文章类型非常简单。首先,你需要在functions.php文件中注册你的自定义文章类型。可以使用register_post_type函数来完成这个任务。下面是一个示例代码:
function custom_post_type() {
$labels = array(
'name' => '自定义文章类型',
'singular_name' => '自定义文章',
'add_new' => '新增文章',
'add_new_item' => '新增自定义文章',
'edit_item' => '编辑自定义文章',
'new_item' => '新的自定义文章',
'view_item' => '查看自定义文章',
'search_items' => '搜索自定义文章',
'not_found' => '没有找到相关文章',
'not_found_in_trash' => '回收站中没有找到相关文章'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'custom-post'),
'menu_icon' => 'dashicons-businessman',
'supports' => array('title', 'editor', 'thumbnail', 'excerpt'),
);
register_post_type('custom_post', $args);
}
add_action('init', 'custom_post_type');
在上面的代码中,我们定义了一个名为"custom_post"的自定义文章类型。你可以根据实际需要修改名称、标签以及支持的功能等。此外,还可以通过设置rewrite参数来自定义文章类型的URL。
完成了自定义文章类型的注册后,你可以在WordPress的后台中看到一个新的菜单选项,用于管理自定义文章类型的文章。你可以像处理普通文章一样来处理自定义文章类型的文章:创建、编辑、发布和删除。
如果你想在你的主题中调用自定义文章类型,可以使用WP_Query类或get_posts函数。以下是一个示例代码,展示了如何通过自定义文章类型获取最近发布的3篇文章:
$args = array(
'post_type' => 'custom_post',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC'
);
$custom_posts = new WP_Query($args);
if ($custom_posts->have_posts()) {
while ($custom_posts->have_posts()) {
$custom_posts->the_post();
// 输出文章的标题和内容等
the_title();
the_content();
}
} else {
echo '没有找到相关文章';
}
这样就可以在你的主题中调用自定义文章类型了。根据你的需求,你还可以使用其他参数来自定义查询,例如按照特定的分类或标签进行过滤等。
希望以上信息对你有帮助!如果还有其他问题,请随时提问。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章