Skip to content

Instantly share code, notes, and snippets.

@SitesByYogi
Created December 27, 2024 11:59
Show Gist options
  • Save SitesByYogi/8420a77e7864abddae9793bf3c64bde4 to your computer and use it in GitHub Desktop.
Save SitesByYogi/8420a77e7864abddae9793bf3c64bde4 to your computer and use it in GitHub Desktop.
Displays project categories in WordPress
<?php
// Add this code to your theme's functions.php file or use the Code Snippets plugin.
/**
* WooCommerce Product Categories Dropdown Shortcode with Title
*/
function custom_woocommerce_category_dropdown_shortcode($atts) {
// Ensure WooCommerce is active
if (!class_exists('WooCommerce')) {
return '<p>WooCommerce plugin is not activated.</p>';
}
// Extract attributes
$atts = shortcode_atts(array(
'placeholder' => 'Select a category', // Default placeholder text
'title' => 'Product Categories', // Default title
), $atts, 'category_dropdown');
// Get WooCommerce product categories
$categories = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => true, // Only show categories with products
));
// Build the output
ob_start();
echo '<div class="woocommerce-category-dropdown-wrapper">';
// Display the title
if (!empty($atts['title'])) {
echo '<h2 class="category-dropdown-title">' . esc_html($atts['title']) . '</h2>';
}
// Display the dropdown
if (!empty($categories) && !is_wp_error($categories)) {
?>
<form class="woocommerce-category-dropdown" method="get" action="<?php echo esc_url(home_url('/')); ?>">
<select name="product_cat" onchange="this.form.submit()">
<option value=""><?php echo esc_attr($atts['placeholder']); ?></option>
<?php foreach ($categories as $category) : ?>
<option value="<?php echo esc_attr($category->slug); ?>">
<?php echo esc_html($category->name); ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="post_type" value="product" />
</form>
<?php
} else {
echo '<p>No categories found.</p>';
}
echo '</div>';
return ob_get_clean();
}
add_shortcode('category_dropdown', 'custom_woocommerce_category_dropdown_shortcode');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment