Skip to content

Instantly share code, notes, and snippets.

@marrisonlab
Created October 1, 2025 16:13
Show Gist options
  • Select an option

  • Save marrisonlab/0fc52a7d8eb640a69386bcfb74df28d4 to your computer and use it in GitHub Desktop.

Select an option

Save marrisonlab/0fc52a7d8eb640a69386bcfb74df28d4 to your computer and use it in GitHub Desktop.
Same Terms Cart In Prods
/**
* Shortcode to get the product categories IDs present in the cart.
* Hooked to 'wp_loaded' to ensure the cart is initialized.
* Returns a string of (numeric) IDs separated by commas.
*/
function get_cart_categories_ids_shortcode() {
// 1. Secure initialization and cart check
if ( ! function_exists( 'WC' ) || is_null( WC()->cart ) ) {
return '';
}
// 2. Check if the cart is empty
if ( WC()->cart->is_empty() ) {
return '';
}
$category_ids = array();
// 3. Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Get the product object
$_product = $cart_item['data'];
// Handle variations: ensure categories are fetched from the parent product
if ( $_product->is_type('variation') ) {
$product_id = $_product->get_parent_id();
} else {
$product_id = $_product->get_id();
}
// Get the category IDs from the product (or parent)
$product_cat_ids = wc_get_product( $product_id )->get_category_ids();
// Merge the IDs
$category_ids = array_merge( $category_ids, $product_cat_ids );
}
// 4. Remove duplicates and format into a string
$unique_ids = array_unique( $category_ids );
return implode( ',', $unique_ids );
}
// Add a filter to ensure the shortcode is processed late
add_action( 'wp_loaded', function() {
add_shortcode( 'cart_categories_ids', 'get_cart_categories_ids_shortcode' );
});
@marrisonlab
Copy link
Author

marrisonlab commented Oct 1, 2025

Query Builder Settings:

Post query (not wc product)
Post Type Product
Tax Query - prod cat - Term ID - shortcode result [cart_categories_ids]
Post not in - Wc cart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment