首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在WordPress中使用自定义帖子类型存档作为首页?

在WordPress中使用自定义帖子类型存档作为首页,可以通过以下步骤实现:

  1. 创建自定义帖子类型

首先,需要创建一个自定义帖子类型,例如“文章”。可以使用插件或者自定义代码来实现。以下是使用代码的方法:

代码语言:php
复制
// 创建自定义帖子类型
function create_custom_post_type() {
    register_post_type( 'custom_post_type',
        array(
            'labels' => array(
                'name' => __( '文章' ),
                'singular_name' => __( '文章' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => '文章'),
            'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'comments')
        )
    );
}
add_action( 'init', 'create_custom_post_type' );
  1. 修改主题文件

接下来,需要修改主题文件,以便将自定义帖子类型的存档页面作为首页。可以通过以下代码实现:

代码语言:php
复制
// 修改主页
function custom_home_page() {
    $args = array(
        'post_type' => 'custom_post_type',
        'posts_per_page' => 10,
        'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1
    );
    $custom_query = new WP_Query($args);
    if ($custom_query->have_posts()) :
        while ($custom_query->have_posts()) : $custom_query->the_post();
            // 在这里添加文章的显示代码
        endwhile;
        // 添加分页代码
        the_posts_pagination(array(
            'mid_size' => 2,
            'prev_text' => __('«'),
            'next_text' => __('»'),
        ));
    else:
        // 没有文章时显示的代码
    endif;
    wp_reset_postdata();
}
add_action('homepage', 'custom_home_page');
  1. 更新主题设置

最后,需要更新主题设置,以便将自定义帖子类型的存档页面作为首页。可以通过以下代码实现:

代码语言:php
复制
// 更新主题设置
function custom_theme_settings($wp_customize) {
    $wp_customize->remove_section('static_front_page');
    $wp_customize->add_section('custom_home_page_section', array(
        'title' => __('首页设置'),
        'description' => __('设置首页内容'),
        'priority' => 1
    ));
    $wp_customize->add_setting('custom_home_page_setting', array(
        'default' => 'homepage',
        'transport' => 'refresh'
    ));
    $wp_customize->add_control('custom_home_page_control', array(
        'label' => __('首页类型'),
        'section' => 'custom_home_page_section',
        'settings' => 'custom_home_page_setting',
        'type' => 'radio',
        'choices' => array(
            'homepage' => __('自定义帖子类型存档页面'),
            'posts' => __('最新文章页面')
        )
    ));
}
add_action('customize_register', 'custom_theme_settings');

这样,就可以将自定义帖子类型的存档页面作为WordPress网站的首页了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

10分30秒

053.go的error入门

8分51秒

2025如何选择适合自己的ai

1.7K
领券