jjw*_*dev 3 wordpress seo slug woocommerce
有没有办法根据产品属性创建自定义产品 URL,我有一个产品太阳镜,它有几个与之相关的属性:金属、蓝色和圆形,所以当前的 URL 是:
website.com/glasses/sunglasses/abram-widana-629/
Run Code Online (Sandbox Code Playgroud)
我想要获取的是包含以下属性的 URL:
website.com/glasses/sunglasses/abram-widana-meta-blue-round-629/
Run Code Online (Sandbox Code Playgroud)
如果有人能指出我如何解决这个问题的正确方向,我将非常感激。
有两种方法可以执行此操作:手动或编程。
在您的示例中,您只需调整产品 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 );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6084 次 |
| 最近记录: |