Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: Add SKU to Product Permalinks
- Plugin URI: http://maciejbis.net
- Description: A plugin that adjusts the functionality of this website
- Version: 1.0
- Author: Maciej Bis
- Author URI: http://www.maciejbis.net
- License: GPL2
- */
- define('SKU_FIELD', '_sku');
- function pm_sku_in_woo_permalinks($url, $post) {
- global $permalink_manager_uris;
- if(!empty($post->post_type) && ($post->post_type == 'product') && ($post->post_status == 'publish')) {
- $product_sku = get_post_meta($post->ID, SKU_FIELD, true);
- if(!empty($product_sku)) {
- $product_sku = sanitize_title($product_sku);
- $url = trim(get_option('home'), '/') . "/shop/{$product_sku}";
- $url = user_trailingslashit($url);
- }
- }
- return $url;
- }
- add_filter('post_type_link', 'pm_sku_in_woo_permalinks', 999, 2);
- function pm_detect_sku_woo_permalinks($query) {
- global $wpdb, $pm_query, $wp;
- // Do not run when Elementor is opened
- if((!empty($_REQUEST['action']) && strpos($_REQUEST['action'], 'elementor') !== false) || isset($_REQUEST['elementor-preview'])) {
- return $query;
- }
- if(!empty($wp->request) && strpos($wp->request, 'shop/') !== false) {
- $sku_number = basename($wp->request);
- // 2. Check if the slug is assigned to any post item
- $sql_query = $wpdb->prepare("SELECT p.* FROM {$wpdb->posts} AS p JOIN {$wpdb->postmeta} AS pm ON pm.post_id = p.ID AND pm.meta_key = %s WHERE 1=1 AND meta_value = %s AND post_type = %s AND post_status = 'publish'", array(SKU_FIELD, $sku_number, 'product'));
- $post = $wpdb->get_row($sql_query);
- // 3. Filter the query if post was found
- if(!empty($post->post_name)) {
- // $page = (!empty($query['page'])) ? $query['page'] : 1;
- $new_query = array(
- 'post_type' => $post->post_type,
- $post->post_type => $post->post_name,
- 'name' => $post->post_name,
- // 'page' => $page,
- 'do_not_redirect' => 1,
- );
- // 4. Disable canonical redirect
- remove_action('template_redirect', 'wp_old_slug_redirect');
- remove_action('template_redirect', 'redirect_canonical');
- add_filter('wpml_is_redirected', '__return_false', 99, 2);
- add_filter('pll_check_canonical_url', '__return_false', 99, 2);
- return $new_query;
- }
- }
- return $query;
- }
- add_filter('request', 'pm_detect_sku_woo_permalinks', 9999);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement