douyoupingji7238 2019-04-26 19:52
浏览 88

如何在Wordpress PHP中动态添加子菜单?

I'm trying to add a login/logout feature on my new website at dernier.com. How do I add login/logout as a submenu under My Account?

I've looked up every document for the Wordpress menu, tried looking up solutions. But nothing so far.

function add_loginout_link( $items, $args ) {
    $parent_title = get_the_title($post->post_parent);
    //echo $parent_title;
    //var_dump($items); 

    $menu_items = wp_get_nav_menu_items("Main Menu 2");
    foreach ($menu_items as $value) {
        //echo $value->title;  
        //echo $value->slug;
        if($value->title == "My Account"){
            //echo var_dump($value);
            $x = get_post( wc_get_page_id( 'myaccount' ) ); 
            $x->menu_item_parent = "1377";
            $test = new WP_POST($x);
            //echo var_dump($test);
            $items[] = $test; 

        }
    }
  return $items;

}

> I get the following error:  Your PHP code changes were rolled back due
> to an error on line 443 of file wp-content/themes/rosa/functions.php.
> Please fix and try saving again.   Uncaught Error: [] operator not
> supported for strings in wp-content/themes/rosa/functions.php:443 
> Stack trace:
> #0 wp-includes/class-wp-hook.php(286): add_loginout_link('<li id="menu-it...', Object(stdClass))
> #1 wp-includes/plugin.php(208): WP_Hook->apply_filters('<li id="menu-it...', Array)
> #2 wp-includes/nav-menu-template.php(243): apply_filters('wp_nav_menu_ite...', '<li id="menu-it...',
> Object(stdClass))
> #3 wp-content/themes/rosa/header.php(138): wp_nav_menu(Object(stdClass))
> #4 wp-includes/template.php(704): require_once('/var/www/UshaFo...')
> #5 wp-includes/template.php(653): load_template('/var/www/UshaFo...', true)enter code here
> #6 wp-includes/general-template.php(41): locate_template(Array, true)
> #7 wp-content/themes/rosa/page.php(9): get_header()
> #8 wp-includes/template-loader.php(77): include('/var/www/UshaFo...')
> #9 /var/www/U
  • 写回答

1条回答 默认 最新

  • dongxie2613 2019-04-27 08:16
    关注

    Try this script.

    You have replace this secondary-menu with your menu id.

    add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );
    function add_loginout_link( $items, $args ) {
    
        if (is_user_logged_in() && $args->theme_location == 'secondary-menu') {
    
            $items .= '<li><a href="'. wp_logout_url( home_url() ) .'">Log out</a></li>';
        }elseif (!is_user_logged_in() && $args->theme_location == 'secondary-menu') {
            $items .= '<li><a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">My Account</a></li>';
        }
        return $items;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办