-1

I know the PHP part of this code is wrong but I can't figure out how to write it correctly. Can someone give me a hand?

function add_last_nav_item($items) {
  return $items .= '<li><a class="cart-button" href="/cart">View cart (<?php echo WC()->cart->get_cart_contents_count(); ?>)</a></li>';
}
add_filter('wp_nav_menu_items','add_last_nav_item');
brombeer
  • 8,716
  • 5
  • 21
  • 27
J82
  • 8,267
  • 23
  • 58
  • 87
  • 1
    Hm, don't ` – brombeer Sep 25 '19 at 09:05
  • I'm not sure how to write that. I've tried already and it always crashes the site. – J82 Sep 25 '19 at 09:05
  • Don't tell us that it is wrong. Tell us what you want to achieve with this piece of code. We can then tell you what is wrong or right. – Dharman Sep 25 '19 at 09:06
  • Well, currently, it crashes the site and I don't know why. I want it to not crash the site. – J82 Sep 25 '19 at 09:06
  • Crashes how? The PHP in PHP is definitely wrong. Please edit the question and tell us what you want to do here. – Dharman Sep 25 '19 at 09:07
  • Yeah, the PHP in PHP is the issue I have. Not sure how to write that part correctly. – J82 Sep 25 '19 at 09:08
  • 1
    Possible duplicate of [PHP - concatenate or directly insert variables in string](https://stackoverflow.com/questions/5605965/php-concatenate-or-directly-insert-variables-in-string) – Dharman Sep 25 '19 at 09:19

1 Answers1

2

No need to <?php echo from PHP, concatenate the value you need (WC()->cart->get_cart_contents_count()). Change to:

function add_last_nav_item($items) {
  return $items .= '<li><a class="cart-button" href="/cart">View cart ('. WC()->cart->get_cart_contents_count() .')</a></li>';
}
add_filter('wp_nav_menu_items','add_last_nav_item');

https://www.php.net/manual/en/language.operators.string.php

brombeer
  • 8,716
  • 5
  • 21
  • 27