Skip to content

Instantly share code, notes, and snippets.

@olex0r
Created July 16, 2023 08:32
Show Gist options
  • Save olex0r/1b69aabf6e55fe1c96453cb9b53711fe to your computer and use it in GitHub Desktop.
Save olex0r/1b69aabf6e55fe1c96453cb9b53711fe to your computer and use it in GitHub Desktop.
Fix permalink of categories matching primary category in aio seo plugin (All in One SEO Pack)
<?php
/*
* Author: https://github.com/olex0r
*
* Fix permalink of categories matching primary category in aio seo plugin (All in One SEO Pack)
* This code snippet is a WordPress filter that modifies the permalink (URL) of product categories
* in the WooCommerce plugin when the "All in One SEO Pack" (AIO SEO) plugin is active. It ensures
* that the permalink for a category matches the primary category set by the AIO SEO plugin
* for a specific product.
*
* Add this code to your theme's functions.php file.
*/
add_filter( 'wc_product_post_type_link_product_cat', function ( $term, $terms, $post ) {
// Get the primary term as saved by AIO SEO
// If AIOSEO\Plugin\Common\Models\Post doesn't exist, then we are not using AIO SEO
if ( ! class_exists( 'AIOSEO\Plugin\Common\Models\Post' ) ) {
return $term;
}
// Use native AIO SEO getPost
$aioseoPost = AIOSEO\Plugin\Common\Models\Post::getPost( $post->ID );
$primaryTerms = ! empty( $aioseoPost->primary_term ) ? $aioseoPost->primary_term : false;
$taxonomyName = 'product_cat';
// If there is no primary term, or the primary term is not set for this taxonomy
if ( ! $primaryTerms || empty( $primaryTerms->{$taxonomyName} ) ) {
return $term;
}
// Get the primary term ID
$primary_cat_id = $primaryTerms->{$taxonomyName};
// If there is a primary, and it's not currently chosen as primary
if ( $term->term_id != $primary_cat_id ) {
// Find the primary term in the term list
foreach ( $terms as $term_key => $term_object ) {
if ( $term_object->term_id == $primary_cat_id ) {
// Return this as the primary term
$term = $term_object;
break;
}
}
}
// Return the term
return $term;
}, 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment