在 WooCommerce 的产品网址中仅使用 ID?

Posted

技术标签:

【中文标题】在 WooCommerce 的产品网址中仅使用 ID?【英文标题】:Using only ID in product url in WooCommerce? 【发布时间】:2022-01-23 19:27:13 【问题描述】:

我想这样做的原因是非英文产品标题会自动在 slug 中使用,它会呈现带有百分号的非常长的 URL,例如/product/%e9%97%bb%e7%a8%bf%e5%8f%91%e5%b8%83/,看起来一点也不好看,尤其是作为 URL 共享时,有时冗长不方便。

因此,在诸如/product/1178/ 之类的 URL 中仅使用产品 ID 似乎要好得多

四处搜索,从未发现任何相关内容。尝试设置 > 永久链接 > 产品永久链接 > 自定义基础 = "/product/%post_id%/" 但 slug 仍附加为 /product/1178/%e9%97%bb%e7%a8%bf%e5%8f%91%e5%b8%83/

有没有办法以编程方式做到这一点?

找到this answer,是否将其修改为用于 WooCommerce 产品,以便在创建产品时将产品 ID 用于 slug?

【问题讨论】:

【参考方案1】:

这对我有用。现在,每次我创建新产品时,产品 ID 都是产品标签。

add_action( 'save_post_product', 'wpse251743_set_title', 10, 3 );
function wpse251743_set_title ( $post_id )
    //This temporarily removes action to prevent infinite loops
    remove_action( 'save_post_product', 'wpse251743_set_title' );
    //update title
    wp_update_post( array(
        'ID'        => $post_id,
        'post_name' =>  $post_id, //Wordpress would generate the slug based on the post name
    ));
    //redo action
    add_action( 'save_post_product', 'wpse251743_set_title', 10, 3 );

【讨论】:

以上是关于在 WooCommerce 的产品网址中仅使用 ID?的主要内容,如果未能解决你的问题,请参考以下文章