如何在WordPress中实现自定义文章分类功能?

玖比肆 WordPress 50

解释如何使用WordPress代码实现自定义文章分类功能的技巧和最佳实践。

回复

共1条回复 我来回复
  • 玖比肆的头像
    玖比肆 评论

    在WordPress中实现自定义文章分类功能可以通过以下步骤来完成:

    Step 1:创建自定义文章分类
    通过编辑器或者代码编辑器添加以下代码来创建自定义文章分类:

    function create_custom_taxonomy() {
    register_taxonomy(
    'custom_category', // 分类名称
    'post', // 分类适用的文章类型
    array(
    'label' => 'Custom Categories', // 分类标签
    'rewrite' => array( 'slug' => 'custom_category' ), // 分类URL格式
    'hierarchical' => true, // 分类级别
    )
    );
    }
    add_action( 'init', 'create_custom_taxonomy' );

    Step 2:在文章编辑页面中添加分类选项
    要在文章编辑页面中添加分类选项,可以通过添加以下代码来实现:

    function add_custom_taxonomy_meta_box() {
    add_meta_box(
    'custom_taxonomy', // 分类名称
    'Custom Category', // 分类标签
    'custom_taxonomy_meta_box_callback', // 回调函数名称
    'post', // 分类适用的文章类型
    'side', // 分类显示位置
    'default' // 分类显示格式
    );
    }
    add_action( 'add_meta_boxes', 'add_custom_taxonomy_meta_box' );

    function custom_taxonomy_meta_box_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'custom_taxonomy_meta_box_nonce' );
    $taxonomy = 'custom_category'; // 分类名称
    $terms = get_terms( $taxonomy ); // 获取所有分类项

    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) { // 检查是否有分类项
    $current_term = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
    echo '';
    }
    }

    Step 3:保存文章分类选项
    当用户编辑文章并选择分类后,需要将选中的分类保存到WordPress数据库。可以通过以下代码来实现:

    function save_custom_taxonomy( $post_id ) {
    if ( ! isset( $_POST['custom_taxonomy_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['custom_taxonomy_meta_box_nonce'], basename( __FILE__ ) ) ) {
    return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
    return;
    }
    $taxonomy = 'custom_category'; // 分类名称
    if ( isset( $_POST[$taxonomy] ) ) {
    $term = sanitize_text_field( $_POST[$taxonomy] );
    wp_set_object_terms( $post_id, $term, $taxonomy );
    }
    }
    add_action( 'save_post', 'save_custom_taxonomy' );

    最佳实践:
    1. 定义唯一的自定义分类名称,以避免与其他分类名称冲突。
    2. 确保在给定文章类型中只适用特定分类。
    3. 保证分类选项的唯一性和准确性,以避免出现错误的分类数据。
    4. 将分类选项添加到文章检索和筛选功能中,以便用户更方便地搜索和查找相关主题。

    2023年 5月 10日 下午12:33 0条评论
微信客服
分享本页
返回顶部
玖比肆(9Bi4)专注于帮助企业实现数字化转型,提供全方位的网站建设、网络运营、网络推广、网络营销和SEO优化等一系列数字化营销服务。