워드프레스 커스텀 필드 값을 카테고리로 지정하는 방법

워드프레스 정보를 제공하는 블로그 Avada 2024. 2. 20. 16:37 • 댓글:

워드프레스 사이트에서 커스텀 필드(사용자 정의 필드) 값을 카테고리로 지정하고 싶은 경우가 있을 수 있습니다. 그런 경우 커스텀 필드에 입력된 커스텀 카테고리가 존재하는지 여부를 체크한 다음, 존재하는 경우 해당 카테고리로 지정하고, 존재하지 않는 경우에는 커스텀 카테고리를 생성하도록 하는 방법을 생각할 수 있습니다.

워드프레스 커스텀 필드 값을 카테고리로 지정하는 방법

티스토리나 그누보드, XE 등의 데이터를 워드프레스로 이전할 때, 카테고리 매핑을 위해 카테고리를 커스텀 필드에 저장한 다음, 커스텀 필드 값을 카테고리로 지정하는 것을 생각할 수 있습니다.

예를 들어, custom-category라는 커스텀 필드 값을 워드프레스의 카테고리로 할당하고 싶은 경우 다음과 같은 코드를 사용할 수 있습니다.

<?php

// Load WordPress environment
require_once(dirname(__FILE__) . '/wp-load.php');

function update_post_categories_from_custom_field() {
    $args = array(
        'post_type' => 'post', // Adjust for custom post types if necessary
        'posts_per_page' => -1, // Consider running in batches if you have many posts
        'no_found_rows' => true, // Performance optimization
        'fields' => 'ids', // Fetch only post IDs to save memory
        'meta_query' => array(
            array(
                'key' => 'custom-category',
                'compare' => 'EXISTS',
            ),
        ),
    );

    $posts = get_posts($args);

    foreach ($posts as $post_id) {
        $custom_category_value = get_post_meta($post_id, 'custom-category', true);

        // Skip if the custom field is empty
        if (empty($custom_category_value)) continue;

        // Check if the category exists (by slug or name)
        $term = term_exists($custom_category_value, 'category');

        if ($term === 0 || $term === null) {
            // Create the category if it does not exist
            $term = wp_insert_term($custom_category_value, 'category');
        }

        // Error handling for wp_insert_term
        if (is_wp_error($term)) {
            error_log('Error inserting term: ' . $term->get_error_message());
            continue;
        }

        // Get the term ID
        $term_id = is_array($term) ? $term['term_id'] : $term;

        // Set the post's category
        wp_set_post_categories($post_id, array($term_id), true);
    }
}

// Execute the function
update_post_categories_from_custom_field();

echo 'Post categories updated based on the custom-category custom field.';

위의 코드로 테스트해 보니 잘 작동했습니다. 만약 작동하지 않는다면 다음 코드를 추가하여 커스텀 필드 값이 올바른지 체크할 수 있습니다.

function append_custom_category_to_content($content) {
    if (is_single() && is_main_query()) {
        global $post;
        $custom_category = get_post_meta($post->ID, 'custom-category', true);
        if (!empty($custom_category)) {
            // If you want to display the category name instead of ID, use the following line
            // $category = get_category($custom_category);
            // $content .= '<p>Custom Category: ' . esc_html($category->name) . '</p>';
            
            // If you're storing category IDs and want to keep it simple, use this line
            $content .= '<p>Custom Category ID: ' . esc_html($custom_category) . '</p>';
        }
    }
    return $content;
}
add_filter('the_content', 'append_custom_category_to_content');

차일드 테마를 만들어, 차일드 테마 내의 함수 파일에 위의 코드를 추가할 수 있습니다.

참고

https://avada.tistory.com/3277

 

플러그인을 사용하여 티스토리 블로그를 쉽게 워드프레스로 옮기는 방법

카카오 데이터센터 화재 사건 이후 티스토리 백업 기능이 부활했습니다. 티스토리 백업본을 사용하여 워드프레스로 이전하는 것이 가능합니다. 티스토리 백업 파일을 이용하여 워드프레스로

avada.tistory.com

https://avada.tistory.com/3046

 

해외웹호스팅: 클라우드웨이즈 vs. 블루호스트 vs. 카페24 비교 (Cloudways vs. Bluehost vs. Cafe24)

저는 오랫동안 블루호스트(Bluehost)를 이용해 왔으며 2021년부터는 클라우드웨이즈(Cloudways) 웹호스팅 서비스도 함께 이용하고 있습니다. 현재 일부 중요하지 않는 블로그는 Bluehost에서 호스팅되고

avada.tistory.com

https://avada.tistory.com/2897

 

엘리멘터 무료 버전 vs. 프로 버전 비교

엘리멘터(Elmentor)는 500만 개가 넘는 사이트에 설치되어 사용되고 있는 인기 워드프레스 페이지 빌더 플러그인입니다. 엘리멘터는 무료 버전과 프로 버전으로 제공됩니다. Elementor 프로 버전에서

avada.tistory.com

 

워드프레스 네이버 카페