【问题标题】:Is there any way to have a menu with images and a custom navwalker?有没有办法让菜单包含图像和自定义导航器?
【发布时间】:2015-02-19 09:16:00
【问题描述】:

我正在尝试创建一个带有图像、标题和描述的菜单。

到目前为止,描述和标题都很好,所以我找到了这个插件

https://wordpress.org/plugins/menu-image/

效果很好,显示图片+标题,但不显示描述。

所以,我想我需要以某种方式在不丢失图像的情况下显示描述。

我创建了一个自定义导航行走,但似乎我不能只调用附加的图像。查看插件的代码找不到任何帮助。

有什么想法吗?以前有人做过吗?

到目前为止,我的 navwalker 看起来像这样:

<?php 
class Ext_Walker extends Walker {

    var $tree_type = array('post_type', 'taxonomy', 'custom');
    var $db_fields = array('parent' => 'menu_item_parent', 'id' => 'db_id');

    function start_el(&$output, $object, $depth = 0, $args = array(), $current_object_id = 0) {

        $classes = "";
        foreach ($object->classes as $cl){
            $classes.=" $cl";
        }

        $output .="<div class='col-lg-15 bottom-pad'>
                    <div class='vertical_item'>
                        <div class='col-lg-60'>
                            <div class='$classes'></div>
                        </div>
                        <div class='clear'></div>
                        <div class='desc_vertical'>
                            <h2 class='vertical_title'>{$object->title}</h2>";
                        if($object->post_content != ""){
                            $output .="<p class='item_description'>{$object->post_content}</p>";    
                        }else{

                        }   
        $output         .="</div>"; 
        $output .="<a href=".$object->url."><button class='btn btn-link'>View More</button></a>";
    }

    function end_el(&$output, $object, $depth = 0, $args = array()) {
        $output.='</div></div>';
    }

}
?>

【问题讨论】:

  • 标题、描述和图片从何而来?

标签: php wordpress


【解决方案1】:

当 WordPress 创建菜单时,它正在创建带有表单链接的菜单项

<a>Some Title</a>

Walker 通过“the_title”过滤器运行标题。你引用的插件做同样的事情。

因此,在不开发自己的 Walker 扩展程序的情况下,至少有两种可能实现您的目标:

1) 扩展插件

由于插件使用 the_title 过滤器,您可以添加该类型的过滤器来添加描述(插件已经在添加图像)。所以

function add_description( $title, $id ) {
    if ( 'nav_menu_item' == get_post_type( $id ) ) {
        $title = '<span class="title">' . $title . '</span>;
        $title .= '<span class="desc">' . description from wherever you get it . '</span>;
    }

    return $title;
}
add_filter( 'the_title', 'add_description', 10, 2 );

这会将内部链接的文本更改为标题和描述。您可能需要检查帖子类型,因为在其他情况下也会调用过滤器。

2) 只使用过滤器

您可以使用上述过滤器的变体来添加图像和描述,从而避免使用插件。例如:

function add_img_and_desc( $title, $id ) {
    if ( 'nav_menu_item' == get_post_type( $id ) ) {
        // Get the image for the menu item (say in $img)
        $title = $img . '<span class="title">' . $title . '</span>;
        $title .= '<span class="desc">' . description from wherever you get it . '</span>;
    }

    return $title;
}
add_filter( 'the_title', 'add_img_and_desc', 10, 2 );

如何获得图像取决于您的方法。例如,它可以像基于标题的 switch 语句一样简单。

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2020-08-26
    相关资源
    最近更新 更多