![](/img/trans.png)
[英]Output a custom shortcode for a specific product category in WooCommerce
[英]WooCommerce custom slug for specific product category
我嘗試為特定產品類別中的產品創建自定義永久鏈接,但它的工作方式非常奇怪。
我嘗試實現如下 URL:
我嘗試通過使用兩步方法(1)生成正確的 URL 和(2)顯示相應的產品頁面,將 %type% 規則添加到產品永久鏈接:
function custom_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%type%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'product_cat');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) {
if ($terms[0]->slug == 'category_name') {
$taxonomy_slug = $terms[0]->slug;
} else {
$taxonomy_slug = 'default_slug';
}
}
else {
$taxonomy_slug = 'default_slug';
}
return str_replace('%type%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'custom_permalink', 10, 3);
add_filter('post_type_link', 'custom_permalink', 10, 3);
function rewrite_product_base_tag() {
add_rewrite_tag( '%type%', '([^&]+)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );
它工作正常,除了它顯示產品,即使我使用任何隨機的蛞蝓。 以下 URL 將根據產品名稱顯示產品(每個 URL 都顯示“產品名稱”產品):
我還嘗試使用不同的正則表達式來限制可用的 slug。 它只正確顯示第二個選項(category_name)。 第一個(default_slug)顯示存檔頁面。 即使它們相互更改,它的工作方式也完全相同:第一個顯示存檔頁面,第二個工作正常。
添加 rewrite_rule function 根本不起作用。
function rewrite_product_base_tag() {
add_rewrite_tag( '%type%', '(default_slug|category_name)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );
add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
function add_custom_attributes_to_permalink( $post_id, $post, $update ) {
//make sure we are only working with Products
if ($post->post_type != 'product' || $post->post_status == 'auto-draft') {
return;
}
//get the product
$_product = wc_get_product($post_id);
//get the "clean" permalink based on the post title
$clean_permalink = sanitize_title( $post->post_title, $post_id );
//next we get all of the attribute slugs, and separate them with a "-"
$attribute_slugs = array(); //we will be added all the attribute slugs to this array
foreach ($_product->get_attributes(); as $attribute_slug => $attribute_value) {
$attribute_slugs[] = $attribute_value;
}
$attribute_suffix = implode('-', $attribute_slugs);
//then add the attributes to the clean permalink
$full_permalink = $clean_permalink.$attribute_suffix;
// unhook the save post action to avoid a broken loop
remove_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
// update the post_name (which becomes the permalink)
wp_update_post( array(
'ID' => $post_id,
'post_name' => $full_permalink
));
// re-hook the save_post action
add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.