wc_product_post_type_link() WC 1.0
Filter to allow product_cat in the permalinks for products.
Hooks from the function
Return
String.
Usage
wc_product_post_type_link( $permalink, $post );
- $permalink(string) (required)
- The existing permalink URL.
- $post(WP_Post) (required)
- WP_Post object.
Code of wc_product_post_type_link() wc product post type link WC 5.0.0
function wc_product_post_type_link( $permalink, $post ) {
// Abort if post is not a product.
if ( 'product' !== $post->post_type ) {
return $permalink;
}
// Abort early if the placeholder rewrite tag isn't in the generated URL.
if ( false === strpos( $permalink, '%' ) ) {
return $permalink;
}
// Get the custom taxonomy terms in use by this post.
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( ! empty( $terms ) ) {
$terms = wp_list_sort(
$terms,
array(
'parent' => 'DESC',
'term_id' => 'ASC',
)
);
$category_object = apply_filters( 'wc_product_post_type_link_product_cat', $terms[0], $terms, $post );
$product_cat = $category_object->slug;
if ( $category_object->parent ) {
$ancestors = get_ancestors( $category_object->term_id, 'product_cat' );
foreach ( $ancestors as $ancestor ) {
$ancestor_object = get_term( $ancestor, 'product_cat' );
if ( apply_filters( 'woocommerce_product_post_type_link_parent_category_only', false ) ) {
$product_cat = $ancestor_object->slug;
} else {
$product_cat = $ancestor_object->slug . '/' . $product_cat;
}
}
}
} else {
// If no terms are assigned to this post, use a string instead (can't leave the placeholder there).
$product_cat = _x( 'uncategorized', 'slug', 'woocommerce' );
}
$find = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
'%post_id%',
'%category%',
'%product_cat%',
);
$replace = array(
date_i18n( 'Y', strtotime( $post->post_date ) ),
date_i18n( 'm', strtotime( $post->post_date ) ),
date_i18n( 'd', strtotime( $post->post_date ) ),
date_i18n( 'H', strtotime( $post->post_date ) ),
date_i18n( 'i', strtotime( $post->post_date ) ),
date_i18n( 's', strtotime( $post->post_date ) ),
$post->ID,
$product_cat,
$product_cat,
);
$permalink = str_replace( $find, $replace, $permalink );
return $permalink;
}