url中的Woocommerce产品ID

时间:2014-05-20 20:12:51

标签: wordpress woocommerce

我正在寻找一种将Woocommerce产品ID放入网址的方法,例如:

domain.com/product-category/id/product-title

ID是产品的帖子ID,例如“12092”。由WooCommerce中的Wordpress自动创建。

这可以通过某种方式完成吗?可以轻松地通过Wordpress固定链接设置,也可以通过黑客攻击文件的方式进行不同的操作。

这几乎有效:

<?php

add_filter('post_type_link', 'wpse33551_post_type_link', 1, 3);

function wpse33551_post_type_link( $link, $post = 0 ){
if ( $post->post_type == 'product' ){
    return home_url( 'p/' . $post->ID );
} else {
    return $link;
}
}

add_action( 'init', 'wpse33551_rewrites_init' );

function wpse33551_rewrites_init(){
add_rewrite_rule(
    'product/([0-9]+)?$',
    'index.php?post_type=product&p=$matches[1]',
    'top' );
}

?>

但输出是:

 domain.com/p/45

我希望它是:

 domain.com/p/45/title-of-the-post

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用$post->post_name来获取slu ..

使用更宽松的正则表达式来接受以/p/[id][anything]

结尾的任何网址
<?php

add_filter('post_type_link', 'wpse33551_post_type_link', 1, 3);
function wpse33551_post_type_link( $link, $post = 0 ){
    if ( $post->post_type != 'product' )
      return $link;

    return home_url( 'p/' . $post->ID . '/' . $post->post_name );
}

add_action( 'init', 'wpse33551_rewrites_init' );
function wpse33551_rewrites_init(){
    add_rewrite_rule(
        'p/([0-9]+)?.*?$',
        'index.php?post_type=product&p=$matches[1]',
        'top'
    );
}

?>

您可能需要重置&#39;您在WordPress设置菜单中的固定链接以接受新规则。

答案 1 :(得分:0)

为什么这么复杂?转到设置->永久链接,然后点击“基于商店的网址”并保存。现在,您可以在“自定义结构”中看到永久链接结构。现在应该看起来像这样:

10-9

现在将post_id添加到永久链接设置中,如下所示:

/shop/%product_cat%/

保存并继续。

相关问题