programing

분류법별로 사용자 지정 게시 유형에 대한 영구 링크 정의

skycolor 2023. 4. 2. 10:09
반응형

분류법별로 사용자 지정 게시 유형에 대한 영구 링크 정의

제품 및 제품 종류에 맞는 표준 퍼멀링크를 만들고 싶습니다.커스텀 포스트 타입과 커스텀 분류법은 알고 있습니다만, 퍼멀링크를 분류법으로 정의할 수 있을지는 모르겠습니다.예를 들어 제 작업 흐름은 다음과 같습니다.

  1. 상품이라고 하는 커스텀 포스트 타입을 만듭니다.
  2. 그런 다음 제품 유형에 대한 사용자 정의 분류법을 만듭니다.
  3. 그리고 '체어'라는 상품 유형을 추가하고 '레드체어'라는 상품을 이 카테고리에 추가합니다.

이 제품을 작성하면 이 제품을 표시하는 데 필요한 Permalink 구조는 다음과 같이 포맷됩니다.->

http://shop.com/products/chairs/red-chair

워드프레스 3.4에서도 가능합니까?커스텀 투고 타입의 메타 박스에서는 커스텀 분류법에 정의되어 있는 제품 타입을 선택할 수 있습니다.또한 제품마다 1가지 타입만 존재합니다.

가능하다면 선택한 상품 카테고리의 부모도 포함시키고 싶습니다(를 들어, '체어' 카테고리가 '라운지' 카테고리의 자녀라면 퍼멀링크 구조는 다음과 같습니다).

http://shop.com/products/lounge/chairs/red-chair

커스텀 투고 타입과 커스텀 분류법을 작성하는 방법은 다음과 같습니다.퍼멀링크에 제품 타입을 포함시키는 rewrite/slug 규칙을 정의하는 데 도움이 필요합니다.

/* Custom Post Type - Products ------- */
function products_init() {
    $args = array(
        'public' => true,
        'label' => 'Products'
    );
    register_post_type( 'products', $args );
}
add_action( 'init', 'products_init' );

/* Custom Taxonomy - Product Type ------- */
add_action( 'init', 'create_prodtype' );
function create_prodtype() {
    $labels = array(
        'name' => _x( 'Product Type', 'products' ),
        'singular_name' => _x( 'Product Category', 'product' ),
        'search_items' =>  __( 'Search Product Types' ),
        'all_items' => __( 'All Product Types' ),
        'parent_item' => __( 'Products' ),
        'parent_item_colon' => __( 'Products:' ),
        'edit_item' => __( 'Edit Product Type' ),
        'update_item' => __( 'Update Product Type' ),
        'add_new_item' => __( 'Add New Product Type' ),
        'new_item_name' => __( 'New Product Type' ),
    );
    register_taxonomy(
        'products',
        array('products'),
        array(
            'rewrite' => array(
                'slug' => 'products',
                'hierarchical' => true
            ), 
            'with_front' => false,
            'labels' => $labels
    ));
}

솔루션

저는 Jan Fabry의 이 투고들을 통해 그것을 알아냈습니다 ->

https://wordpress.stackexchange.com/a/5478/10350 https://wordpress.stackexchange.com/a/22490/10350

커스텀 투고 타입을 다음과 같이 설정했습니다.- >

  • 커스텀 투고 타입(register_post_type) -> "제품"
  • 분류법(register_taxonomy) -> "제품형"

백엔드 기능

백엔드에 저장되어 있는 퍼머링크 구조를 고쳐 씁니다.퍼머링크가 커스텀 분류 유형인 "product-type"을 포함하도록 저장됩니다.

add_filter('post_type_link', 'product_type_permalink', 10, 4);
function product_type_permalink($post_link, $post, $leavename, $sample) {
    //If is custom post type "product"
    if ($post->post_type == 'product') {
        // Get current post object
        global $post;
        // Get current value from custom taxonomy "product-type"
        $terms = get_the_terms($post->id, 'product-type');
        // Define category from "slug" of taxonomy object
        $term = $terms[0]->slug;
        // Re-structure permalink with string replace to include taxonomy value and post name
        $permalink = str_replace('product/', 'product/' . $term . '/', $post_link);
    }
    return $permalink;
}

permalink 설정을 'Post name'으로 설정하고 저장합니다.제품을 카테고리에 추가하고 저장하는 경우 permalink는 사용자 정의 분류법 정의(이 경우 "product-type")를 포함하도록 다시 작성해야 합니다.따라서 "Chairs" 카테고리에 "Red Chair"를 추가하면 URL 형식은 다음과 같습니다. ->

http://website.com/product/chairs/red-chair/

그러나 이 페이지로 이동하려고 하면 404 오류가 발생합니다.그 이유는 워드프레스는 아직 이 URL을 사용하여 데이터베이스를 조회하는 방법을 모르기 때문에 사용자가 작성해야 하기 때문입니다.

프런트 엔드 기능

wordpress가 url을 가져와 데이터베이스를 조회할 수 있도록 다시 쓰기 규칙을 추가해야 합니다.워드프레스 기능을 사용합니다.add_rewrite_rule지정된 permalink를 쿼리 문자열로 변환합니다.

add_rewrite_rule(
    // The regex to match the incoming URL
    'product/([^/]+)/([^/]+)/?',
    // The resulting internal URL: `index.php` because we still use WordPress
    // `pagename` because we use this WordPress page
    // `designer_slug` because we assign the first captured regex part to this variable
    'index.php?product-type=$matches[1]&product=$matches[2]',
    // This is a rather specific URL, so we add it to the top of the list
    // Otherwise, the "catch-all" rules at the bottom (for pages and attachments) will "win"
    'top'
);

이 함수에서 matchs 배열은 Wordpress가 각 슬래시에서 지정된 문자열을 분해하는 방식으로 정의됩니다.이 예에서 정규 표현은([^/]+)각 슬래시 사이에 있는 모든 것을 일치시키기 위해 사용됩니다.이 예에서는 두 가지 레벨이 있으므로 제품 유형과 일치한 다음 제품을 매치 배열에 추가합니다. 여기서 product-type = $type1 및 product = $time[2].

이 개서 규칙은 이것을 변환합니다.->

product/chairs/red-chair/

여기에 ->

index.php?product-type=chair&product=red-chair

데이터베이스를 조회하고 포맷된 permalink와 함께 올바른 제품 페이지를 반환하는 데 사용할 수 있습니다.

이렇게 하면 제품 유형 페이지가 사라집니다. URL에는 제품 유형이라는 한 수준만 있기 때문입니다.즉, 현재 rewrite 규칙은 항상 쿼리 문자열에 정의된 대로 제품 이름을 식별하려고 시도합니다.이를 위해 단일 레벨의 개서 규칙도 작성합니다.

add_rewrite_rule('^product/([^/]*)?$','index.php?product-type=$matches[1]','top');

또, 제품 타입의 페이지도 문의할 수 있기 때문에, 다양한 제품 타입을 표시하는 경우는, 정상적으로 분류법을 루프 할 수 있습니다.다양한 제품 타입에 링크를 걸 때, 404 에러가 발생하지 않습니다.

단점

이 작업은 현재 단일 수준의 분류법만 적용되므로 사용자 정의 분류법 구조가 계층적일 수 없습니다.여러 분류법을 지정하면 첫 번째 ID를 가진 분류법을 사용하여 Permalink를 정의합니다.이에 대한 잠재적인 해결 방법은 사용자 지정 게시 유형의 사이드 바에 표시되는 사용자 지정 분류 메뉴를 숨기고 선택 상자만 사용할 수 있는 분류용 메타 상자를 추가하는 것입니다.Meta Box 플러그인을 사용합니다.(nb, 이 플러그인에는 관리 메뉴가 없습니다.기능에서 커스텀 포스트 타입의 메타박스를 쓸 수 있습니다.어레이를 작성하는 것만으로 php - 강력 추천합니다!)

@reekogi 이것은 제품 커스텀 투고 타입에 대해 올바르게 동작하지만 다른 투고 타입은 모두 파손됩니다.

add_filter('post_type_link', 'product_type_permalink', 10, 4);
function product_type_permalink($post_link, $post, $leavename, $sample) {
    //If is custom post type "product"
    if ($post->post_type == 'product') {
        // Get current post object
        global $post;
        // Get current value from custom taxonomy "product-type"
        $terms = get_the_terms($post->id, 'product-type');
        // Define category from "slug" of taxonomy object
        $term = $terms[0]->slug;
        // Re-structure permalink with string replace to include taxonomy value and post name
        $permalink = str_replace('product/', 'product/' . $term . '/', $post_link);
    }
    return $permalink;
}

수정은 변수 $post_link와 $permalink를 $url로 변경하는 것입니다.

function product_type_permalink($url, $post, $leavename, $sample) {
    //If is custom post type "product"
    if ($post->post_type == 'product') {
        // Get current post object
        global $post;
        // Get current value from custom taxonomy "product-type"
        $terms = get_the_terms($post->id, 'product-type');
        // Define category from "slug" of taxonomy object
        $term = $terms[0]->slug;
        // Re-structure permalink with string replace to include taxonomy value and post name
        $url = str_replace('product/', 'product/' . $term . '/', $url);
    }
    return $url;
}
add_filter('post_type_link', 'product_type_permalink', 10, 4);

언급URL : https://stackoverflow.com/questions/13553932/define-permalinks-for-custom-post-type-by-taxonomy

반응형