เพิ่มภาพเด่นให้กับรายการ wp_nav_menu

นี่คือการถามตอบด้วยตนเอง

คุณจะแก้ไขข้อความ/html ที่ปรากฏในผลลัพธ์ของ wp_nav_menu ได้อย่างไร ตัวอย่างเช่น ฉันต้องการเพิ่มรูปภาพเด่นสำหรับเพจและหมวดหมู่

คุณเห็นตัวอย่างการดำเนินการนี้กับวอล์คเกอร์แบบกำหนดเอง แต่โค้ดนั้นซับซ้อนมากสำหรับการเปลี่ยนแปลงเล็กๆ น้อยๆ แน่นอนว่ามีวิธีทำฟิลเตอร์ด้วยเหรอ?


person Drew Baker    schedule 27.09.2014    source แหล่งที่มา


คำตอบ (1)


นี่คือรหัสที่ฉันคิดขึ้นมาด้วยความช่วยเหลือจากคำตอบ Wordpress StackOverflow ที่ฉันหาไม่ได้อีกต่อไป (โปรดแสดงความคิดเห็นพร้อมลิงก์หากคุณพบ)

ขั้นแรก คุณต้องเพิ่มตัวกรองลงในเมนูเฉพาะ (คุณสามารถเพิ่มตัวกรองลงในเมนูทั้งหมดได้หากต้องการ - เพียงใช้บรรทัด 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 ที่ส่งผ่านไปยังตัวกรอง มันไม่ง่ายอย่างที่คุณคาดหวัง เนื่องจาก $item ไม่มีรหัสโพสต์/หมวดหมู่ที่เกี่ยวข้อง มีเพียงรหัสรายการเมนูเท่านั้น ดังนั้นฉันจึงใช้ 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;
}

จากนั้นคุณต้องการลบตัวกรองที่คุณใช้ตอนเริ่มต้น เพื่อให้เมนูถัดไปที่ประมวลผลไม่ได้ใช้ HTML เดียวกันกับที่กำหนดไว้ข้างต้นใน filter_menu_items()

// 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;
}
person Drew Baker    schedule 27.09.2014