有两种方法可以做到这一点,手动或编程。
手动调整永久链接:
在您的示例中,您只是调整产品 URL 以包含属性。这可以通过编辑产品本身的永久链接来手动实现。
添加/保存产品后,您将看到永久链接直接显示在标题字段下方,如下所示:
只需单击它旁边的 编辑 按钮,然后将其从 abram-widana-629 更改为 abram-widana-meta-blue-round-629
以编程方式向永久链接添加属性:
如果您想尝试为所有产品永久实现此目的,则必须通过“save_post”过滤器/挂钩将所有属性添加到永久链接。唯一的缺点是您将无法再为您的产品调整您的个人永久链接,因为一旦您点击保存,它们就会恢复原状。
下面是一个如何实现的代码示例:
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 );
}