For this I suggest you to use the modified code in the given steps:
Step 1: You need to replace your code given in step 1 with this code.
function jpb_custom_meta_permalink( $link, $post ) {
$post_meta = get_post_meta( $post->ID, '<insert your meta key here>', true );
if ( empty( $post_meta ) || !is_string( $post_meta ) ) {
$post_meta="<insert your default value (could be an empty string) here>";
}
$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 ) ) {
// Here we are removing '#' and appending SKU before the product title.
$link = str_replace('/product/', "/{$post_meta}/product/", $link);
return $link;
}
}
add_filter( 'post_type_link', 'append_sku_string', 10, 2 );
Step 2: In this step you need to use the given code in .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# This is the rewrite rule for SKU before the product title.
RewriteRule ^([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ index.php?sku=$1&product=$2 [NC,L]
</IfModule>
Step 3: We need additional code to confirm that WooCommerce recognizes the SKU correctly.
add_action('pre_get_posts', 'custom_rewrite_product_query');
function custom_rewrite_product_query($query) {
if (!is_admin() && $query->is_main_query() && $query->is_product()) {
if (isset($_GET['sku'])) {
// We are using this SKU to find the product.
$sku = sanitize_text_field($_GET['sku']);
$query->set('meta_query', array(
array(
'key' => '_sku',
'value' => $sku,
'compare' => '='
)
));
}
}
}