source

wp_nav_메뉴 항목에 특징 이미지 추가

nicesource 2023. 10. 26. 21:15
반응형

wp_nav_메뉴 항목에 특징 이미지 추가

셀프 Q&A입니다.

wp_nav_메뉴의 출력에 나타나는 text/html을 어떻게 수정합니까?예를 들어, 페이지와 카테고리의 특징 이미지를 추가하고 싶었습니다.

사용자 지정 워커를 사용하여 이 작업을 수행하는 예를 볼 수 있지만 코드는 작은 변경 사항에 대해 매우 복잡합니다.확실히 필터로 할 수 있는 방법이 있나요?

이것은 제가 더 이상 찾을 수 없는 워드프레스 스택 오버플로우 답변의 도움 덕분에 생각해낸 코드입니다(찾으면 링크와 함께 댓글을 달아주세요).

먼저 특정 메뉴에 필터를 추가해야 합니다(필요한 경우 모든 메뉴에 추가할 수 있음 - add_filter 라인을 직접 사용하기만 하면 됨).

// Add filter to specific menus 
add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {

    // You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location']
    if( $args['theme_location'] == 'header_menu') {
        add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
    }

    return $args;
}

그러면 $item 개체에서 post 또는 category ID를 필터로 전달하기 위해 코드를 작성해야 합니다.$ 항목에는 기본 포스트/카테고리 ID가 포함되지 않고 메뉴 항목 ID만 포함되어 있기 때문에 예상보다 쉽지 않습니다.그래서 저는 URL을 사용하여 ID를 역방향 조회합니다.

메뉴에 사용되는 태그나 사용자 지정 분류법에는 적용되지 않습니다.카테고리에만 필요해서 이게 제가 만든 전부입니다.

// Filter menu
function filter_menu_items($item) {

    if( $item->type == 'taxonomy') {

        // For category menu items
        $cat_base = get_option('category_base');
        if( empty($cat_base) ) {
            $cat_base = 'category';
        }

        // Get the path to the category (excluding the home and category base parts of the URL)
        $cat_path = str_replace(home_url().'/'.$cat_base, '', $item->url);

        // Get category and image ID
        $cat = get_category_by_path($cat_path, true);
        $thumb_id = get_term_meta($cat->term_id, '_term_image_id', true); // I'm using the 'Simple Term Meta' plugin to store an attachment ID as the featured image

    } else {
        // Get post and image ID
        $post_id = url_to_postid( $item->url );
        $thumb_id = get_post_thumbnail_id( $post_id );
    }

    if( !empty($thumb_id) ) {
        // Make the title just be the featured image.
        $item->title = wp_get_attachment_image( $thumb_id, 'poster');
    }

    return $item;
}

그런 다음 처음에 적용한 필터를 제거하여 다음 처리된 메뉴에서 filter_menu_items()에 정의된 것과 동일한 HTML을 사용하지 않도록 합니다.

// Remove filters
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2);
function remove_filter_from_menus( $nav, $args ) {
    remove_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
    return $nav;
}

드루 베이커의 답변을 수정했습니다.플러그인 없이 작동하며, 현재 슬러그에 카테고리가 없는 경우 우커머스 상품 카테고리('product_cat')를 확인합니다.

기능들.php

// Add filter to specific menus 
add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {

    // You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location']
    if( $args['theme_location'] == 'menu-header') {
        add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
    }

    return $args;
}
// Filter menu
function filter_menu_items($item) {

    if( $item->type == 'taxonomy') {

        // Get category and image ID
        $slug = pathinfo( $item->url, PATHINFO_BASENAME );
        $cat = get_term_by( 'slug', $slug, 'category' );
        // If there is no standard category try getting product category
        if( !$cat ) {
            $cat = get_term_by( 'slug', $slug, 'product_cat' );
        }
        $thumb_id = get_term_meta($cat->term_id, 'thumbnail_id', true);

    } else {
        // Get post and image ID
        $post_id = url_to_postid( $item->url );
        $thumb_id = get_post_thumbnail_id( $post_id );
    }

    if( !empty($thumb_id) ) {
        // Make the title just be the featured image.
        $item->title = wp_get_attachment_image( $thumb_id, 'poster');

        // Display image + title example
        // $item->title = wp_get_attachment_image( $thumb_id, 'poster').$item->title;
    }
    return $item;
}
// Remove filters
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2);
function remove_filter_from_menus( $nav, $args ) {
    remove_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
    return $nav;
}

언급URL : https://stackoverflow.com/questions/26079190/add-featured-image-to-wp-nav-menu-items

반응형