What I have:
A custom post type. A front end posting form which creates new posts with post_status = pending
until they are manually reviewed and status changed to published.
What I need:
While I can go to the listing of posts and see if there are any with “Pending” to authorize; what I want is to add a round icon with a number inside just like what WordPress does when there are new comments. I can write the code to extract the number of pending posts but I have no idea how to insert it in the admin menu.
This is the code created by wp when a new comment is added:
<span class="awaiting-mod count-6"><span class="pending-count">1</span></span>
A screenshot which shows one new comment, i need the same at Items.
I have been looking for a solution to this for a while now and cannot find it anywhere; my next stop if no one can answer me here is to take apart the WP core and see how they do it there.
Normally everything is contained in
$labels['menu_name']
argument on cpt registration is printed in the menu, so the right place where put the countspan
is there, but there are 2 problems:$labels['menu_name']
option or registration, the span is stripped out, because before printing the menu the value of the param is wrapped inesc_attr
The second ‘problem’, is not a real problem, it’s the solution!
In fact, the
esc_attr
function fires a filter hookattribute_escape
, that we can use to calculate the pending posts count and then output the right html unescaped.We we must be very careful if we remove the sanitize functionality from
esc_attr
because this is a function used a lot times in WP and is a function related to secutirity.So, we have to isolate the behaviour only to admin menu and only in specific case.
Moreover we can add filter again when it has done its work, in this way it’s removed only once.
The only problem now is how to understand which is the right menu item for which remove the filter and add the count.
The only chance we have, it’s insert a sort of placeholder that let us recognize the menu item. In other words, when you register your cpt you have to add an
uncommon
string to$labels['menu_name']
:Once the
%%PENDING_COUNT%%
is added, when theesc_attr
is called for a string containing that text, we run our work:That’s all, and it works!
There is only a little issue: if a pending post is published via the quick edit the pending count is not updated, because quick edit use ajax, and to update the numebr you need to use some js.
Work on it, if you want.