How to display unread message count badge in a custom mobile menu?

hi,
I have a technical question regarding a custom fixed mobile menu that we’ve added at the bottom of the screen, which is only visible on mobile devices.

Inside this mobile menu, we have an icon for “Messages” and we would like to display a red badge showing the number of unread messages for the logged-in user.

We tried fetching the unread count using this endpoint:

fetch(‘/wp-json/wp/v2/messages/unread-count’)

We also tested:
fetch(‘/wp-json/hivepress/v1/messages/unread-count’)

What works and what doesn’t:

  • The HTML, CSS, and JS are correct and fully functional.
  • The badge displays correctly in the user dashboard, next to “Messages”.
  • But the badge does not appear inside the custom mobile menu (even though the DOM structure and selectors are identical).
  • JavaScript runs inside window.onload, so the DOM is fully loaded.
  • Scripts are added via the Custom CSS & JS plugin, not injected by the theme.

What we need to clarify:

  1. What is the correct endpoint to retrieve the number of unread messages for the logged-in user?
  2. Does this fetch request require authentication headers or cookies to return data correctly?
  3. Could there be a contextual limitation where the fetch() call does not return data outside certain pages (like the dashboard)?
  4. Do you recommend a different method to show unread message counts in a custom area of the site, such as a mobile menu?

We can provide the full code (HTML, CSS, JS) if needed.

Thank you in advance for your help!

Kind regards,
Cristian Grosu

Hi,

Yes, you can get the unread message count anywhere using this PHP code:

echo esc_html( hivepress()->request->get_context( 'message_unread_count' ) );

There’s no REST API endpoint for this, I recommend using PHP when you render the menu HTML, this is much easier than developing a custom endpoint. This also doesn’t require authentication and the count is properly cached.

Hope this helps

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.