WordPress plugins are used to add more features to our WordPress websites. These features are the add-ons that can be plugged into the core WordPress.
These changes can be made in UI aspects or to override the default behaviour using hooks. There are various ways to make the plugins to reflect the add-on feature by creating shortcodes, by calling plugin functions from the theme files and more.
I have created a WordPress plugin named as Breadcrumb Navigation Menu to show the post taxonomy breadcrumb links on the single page. I have defined a plugin function to get the complete hierarchy of the post custom taxonomy by using the post id.
I have created a shortcode and mapped it to the Breadcrumb Navigation Menu plugin function. I specified this shortcode in the post single page to display the post taxonomy breadcrumbs after post title.
This screenshot shows the changes made by using the Breadcrumb Navigation Menu plugin.
These steps are needed to create our own WordPress plugin.
This PHP code is showing the Breadcrumb Navigation Menu plugin. The plugin function getBreadCrumbNavigationMenu() gets the taxonomy id by using the current post id and recursively called another function getCategoryTree() to get taxonomy hierarchy until it reaches the root taxonomy.
I have created a shortcode in the theme’s functions.php and map the shortcode to callback plugin function. While getting the taxonomy hierarchy, the function returns output in HTML format by adding links to the taxonomy terms.
These links are printed as breadcrumbs in the single page where I specified the shortcode.
<?php
/*
Plugin Name: BreadCrumb Navigation Menu
Plugin URI: https://phppot.com
Description: Display BreadCrumb Navigation Menu in Post Single Page.
Author: Vincy
Author URI: https://phppot.com
Version: 1.0.0
*/
function getBreadCrumbNavigationMenu() {
if(is_single()) {
$postId = get_post()->ID;
$output = '<a class= "post-menu" href="' . get_permalink(get_post()->ID) . '">'. get_post()->post_title . '</a>';
$gotTerms = get_the_terms($postId,'menu');
$objTerms = reset($gotTerms);
$output = getCategoryTree($objTerms, $output);
}
return $output;
}
function getCategoryTree($terms, $output) {
if(!empty($terms)) {
$output = '<a class= "post-menu" href="' . get_term_link($terms->term_id) . '">'. $terms->name . '</a>' . " <span>⪼</span> " . $output;
if($terms->parent != 0) {
$terms = get_term( $terms->parent, "menu" );
$output = getCategoryTree($terms, $output);
}
}
return $output;
}
?>
...
/*
* to display the breadcrumb navigation menu in single page
*
*/
add_shortcode('breadcrumb-navigation-menu', 'getBreadCrumbNavigationMenu');
...
...
[breadcrumb-navigation-menu]
...