Woocommerce products permalink based on SKU

To achieve the permalink structure http://example.com/product_title-sku, you need to adjust the way the SKU is appended to the product title in the permalink. The current code appends the SKU to the end of the URL. Instead, you need to modify it to include a hyphen between the product title and the SKU.

Here is the modified code:

function jpb_custom_meta_permalink( $link, $post ) {
    $post_meta = get_post_meta( $post->ID, '_sku', true );
    if ( empty( $post_meta ) || !is_string( $post_meta ) )
        $post_meta="";
    $link = str_replace( '!!custom_field_placeholder!!', $post_meta, $link );
    return $link;
}
add_filter( 'post_link', 'jpb_custom_meta_permalink', 10, 2 );

function append_sku_string( $link, $post ) {
    $post_meta = get_post_meta( $post->ID, '_sku', true );
    if ( 'product' == get_post_type( $post ) && !empty( $post_meta ) ) {
        $link = str_replace( '/product/', '/product-', $link ); // Replace the last slash before the SKU with a hyphen
        $link = str_replace( "https://wordpress.stackexchange.com/", '-' . $post_meta . "https://wordpress.stackexchange.com/", $link ); // Add the SKU with a hyphen before the last slash
        return $link;
    }
    return $link;
}
add_filter( 'post_type_link', 'append_sku_string', 1, 2 );

This code makes the following changes:

  1. In the append_sku_string function, the str_replace function is used to first replace the last slash before the SKU with a hyphen.
  2. Then it replaces the last slash with the SKU preceded by a hyphen.

This way, your product permalink will be structured as http://example.com/product_title-sku.

Make sure to flush the rewrite rules after making these changes by visiting the Permalinks settings page in your WordPress dashboard.

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino