Hook : removing any category without any published post from the new block menu
-
I am working on a WordPress project where I want to dynamically filter the menu items (and possibly their parent items) based on whether they are associated with any published posts. Specifically, I am looking to dynamically filter out categories from the menu if they have no association to posts with a “published” state. Furthermore, if a parent category has no children with published posts, that parent category should be dynamically filtered out from the menu as well.
The updating of the WordPress navigation block should happen whenever a post is updated. I will use add_action( ‘save_post’, ‘my_save_post_function’ ); for this.
1 – I have been using PHP to query the database and determine whether a category has any published posts associated with it. I created a function to check each category and its parent category to see if there are any published posts and dynamically adjust the menu accordingly.
Here is a snippet of the PHP code I am working with to detect if a category has any published post associated with it, the basic model is :
php function has_published_posts($term_id) { global $wpdb; $post_count = $wpdb->get_var($wpdb->prepare(" SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts p JOIN {$wpdb->prefix}term_relationships tr ON p.ID = tr.object_id JOIN {$wpdb->prefix}term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.term_id = %d AND tt.taxonomy = 'product_cat' AND p.post_type = 'product' AND p.post_status = 'publish'", $term_id)); return $post_count > 0; }
So far I am able to detect if a child-category or parent-category has any published post associated with it. This part is achieved.
2- However, I am currently searching how to hook into the new WordPress Navigation Block API to perform this filtering. I have been trying to find a relevant hook to access a Navigation Block hooks that could filter out the categories without any published post associated to them.
Does anyone know of a hook or method within the Navigation Block API that can be used to dynamically filter menu items ?
I have seen there is Github and WordPress pages that could help :
- https://github.com/WordPress/wordpress-develop/blob/0cb8475c0d07d23893b1d73d755eda5f12024585/src/wp-includes/blocks/navigation.php#L512
- https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-block.php#L142
- https://make.www.ads-software.com/core/2022/01/07/the-new-navigation-block/
If someone has some experience with filtering out the new Navigation Block, thanks for sharing your experience.
Any guidance on this matter would be greatly appreciated. Thank you!
The page I need help with: [log in to see the link]
- The topic ‘Hook : removing any category without any published post from the new block menu’ is closed to new replies.