簡體   English   中英

WordPress菜單發布精選圖片

[英]WordPress menu post featured image

我有一個包含多個下拉列表的菜單。 我想在菜單下拉列表中顯示下方或旁邊的帖子或帖子的特色圖片。 可能嗎? 我已將圖像附加到此消息中。 我不想知道如何設計它或類似的東西。 所以,假設我有“Siguranta” ,我想在下面顯示該帖子的特色圖像,並在圖像下方顯示“閱讀更多”鏈接。 提前謝謝了。

在此輸入圖像描述

將過濾器添加到特定菜單

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' );
    }
}

過濾菜單

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。

刪除過濾器

 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;
    }

所以,我會回答我自己的問題。 我終於用這段代碼做了:

  // get featured image
  $thumbnail = get_the_post_thumbnail( $item->object_id );

  //display featured image
  $item_output .= $thumbnail;

我必須提到我在walker類中使用了這段代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM