Reputation: 104
I would like to echo a shortcode for a cart dropdown inside my header php file. I figured out how to append a menu item to the primary menu with a function and would like to have the shortcode for the cart dropdown inside the list.
My function is;
add_filter( 'wp_nav_menu_items', 'append_menu_item', 10, 2 );
function append_menu_item( $items, $args )
{
$items .= '<li class="menu-item nav-item" id="menu-item"></li>';
return $items;
}
The shortcode for the cart dropdown is;
<?php echo do_shortcode( '[nc_ajax_cart]' );?>
Which outputs this HTML (link and div which has dropdown);
<a id="nc_ajax_cart_snippet" href="javascript:void(0)"></a>
<div id="nc_ajax_cart_mini_cart" style="display:none">
<! Snipped for reading purposes -->
</div><!-- end cart-->
My php is very poor and I keep getting errors when trying to insert the echo shortcode. I am not sure if that is even the best approach.
Any help, pointers or links greatly appreciated!
Edit;
As I said my PHP is very very basic and I think I have confused myself. I the thought about it and tried this;
add_filter( 'wp_nav_menu_items', 'append_menu_item', 10, 2 );
function append_menu_item( $items, $args )
{
$shortcode = '[nc_ajax_cart]';
$items .= '<li class="menu-item nav-item" id="menu-item"> echo 'do_shortcode( $shortcode)'; <a title="Cart" href="./cart" class="nav-link"></a></li>';
return $items;
}
I thought passing the shortcode as a string and then echoing the shortcode within the list item would work but it just outputs the text "echo do_shortcode( $shortcode);" instead of the actual shortcode. Pretty embarrassing really!
Upvotes: 1
Views: 1631
Reputation: 2588
Try changing this line
$items .= '<li class="menu-item nav-item" id="menu-item"> echo 'do_shortcode( $shortcode)'; <a title="Cart" href="./cart" class="nav-link"></a></li>';
to
$items .= '<li class="menu-item nav-item" id="menu-item">'.do_shortcode( $shortcode).'<a title="Cart" href="./cart" class="nav-link"></a></li>';
You do not want to echo out the shortcode as you are returning a string, you want to append the value to the string, hence the use of '. and .' which break out of the string, add your shortcode then add back the rest of the string.
Upvotes: 1