此任务与 WordPress woo commerce 相关。 问:当产品缺货时,用户会使用插件自动重定向到产品的相关类别吗?
应该非常简单,您可以使用
get_stock_quantity()
检索产品库存。 get_the_terms()
用于检索产品类别,get_term_link()
用于检索术语 url。
以下未经测试,但应该有效。
<?php
add_action( 'template_redirect', function () {
if ( ! is_admin() && is_product() ) {
global $product;
$product_id = $product->get_id();
if ( $product->get_stock_quantity() < 1 ) {
$terms = get_the_terms( $product_id, 'product_cat' );
if ( ! empty( $terms ) ) {
$location = get_term_link( $terms[0]->slug );
wp_safe_redirect( $location, 302 );
};
};
};
} );
// Add this code to your theme's functions.php file or a custom plugin
add_action( 'template_redirect', 'redirect_out_of_stock_products' );
function redirect_out_of_stock_products() {
// Check if it's a single product page
if ( is_product() ) {
global $post;
// Check if the product is out of stock
if ( ! $post || 'product' !== $post->post_type || ! $post->ID ) {
return;
}
$product = wc_get_product( $post->ID );
if ( ! $product || ! $product->is_in_stock() ) {
// Get the category IDs associated with the product
$product_categories = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'ids' ) );
// Check if the product has any categories
if ( ! empty( $product_categories ) ) {
// Get the first category ID
$category_id = $product_categories[0];
// Get the category URL
$category_url = get_term_link( $category_id, 'product_cat' );
// Redirect to the category page
wp_redirect( $category_url );
exit();
}
}
}
}