Forked from vovadocent/woo_remove_product_category_slug_from_link.php
Created
June 1, 2017 12:33
-
-
Save moskalukigor/ae90e5e71410db9835bbc05eb807880d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* block remove "product_cat" from product category URL */ | |
function filter_term_link( $termlink, $term, $taxonomy ) { | |
if ( 'product_cat' != $taxonomy ) { | |
return $termlink; | |
} | |
$termlink = str_replace( '/product_category/', '/', $termlink ); | |
return $termlink; | |
}; | |
add_filter( 'term_link', 'filter_term_link', 10, 3 ); | |
/* end of block */ | |
/* Fix request when removed products_cat slug */ | |
add_filter('request', function( $vars ) { | |
global $wpdb; | |
if( !empty( $vars['pagename'] ) || !empty( $vars['category_name'] ) || !empty( $vars['name'] ) || !empty( $vars['attachment'] ) ) { | |
$slug = !empty( $vars['pagename'] ) ? $vars['pagename'] : ( ! empty( $vars['name'] ) ? $vars['name'] : ( !empty( $vars['category_name'] ) ? $vars['category_name'] : $vars['attachment'] ) ); | |
$exists = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms t LEFT JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s" ,array( $slug ))); | |
if( $exists ){ | |
$old_vars = $vars; | |
$vars = array('product_cat' => $slug ); | |
if ( !empty( $old_vars['paged'] ) || !empty( $old_vars['page'] ) ) | |
$vars['paged'] = ! empty( $old_vars['paged'] ) ? $old_vars['paged'] : $old_vars['page']; | |
} | |
} | |
return $vars; | |
}); | |
/* end of block */ | |
/* block remove "product" from product URL */ | |
function custom_remove_cpt_slug( $post_link, $post, $leavename ) { | |
if ( 'product' != $post->post_type || 'publish' != $post->post_status ) { | |
return $post_link; | |
} | |
$post_link = str_replace( '/product/', '/', $post_link ); | |
return $post_link; | |
} | |
add_filter( 'post_type_link', 'custom_remove_cpt_slug', 10, 3 ); | |
function custom_parse_request_tricksy( $query ) { | |
// Only noop the main query | |
if ( ! $query->is_main_query() ) | |
return; | |
// Only noop our very specific rewrite rule match | |
if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { | |
return; | |
} | |
global $wp_query; | |
// 'name' will be set if post permalinks are just post_name, otherwise the page rule will match | |
if ( ! empty( $query->query['name'] ) ) { | |
$query->set( 'post_type', array( 'post', 'product', 'page' ) ); | |
} | |
} | |
add_action( 'pre_get_posts', 'custom_parse_request_tricksy' ); | |
/* end of block */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment