Created
October 26, 2017 08:14
-
-
Save isuke01/36282f253d31e355c4f684fdb7e6abc5 to your computer and use it in GitHub Desktop.
[WooCommerce, WordPress ]This snippets contain get_product_by_slug , and redirect from single product page to somewhere when product is out f stock.
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
/** | |
* Retrieve a product given its slug. | |
*/ | |
function get_product_by_slug($page_slug) { | |
global $wpdb; | |
$product = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, 'product')); | |
if ( $product ) | |
return wc_get_product($product); | |
return null; | |
} | |
/** | |
* Redirect somewhere from page where product is out of stock | |
*/ | |
function redirect_out_of_stock_product( $query ) { | |
if( !is_admin() && $query->is_main_query() && $query->query['post_type'] === 'product' ){ | |
$product = get_product_by_slug($query->query['name']); | |
if( !$product->is_in_stock() ){ | |
wp_redirect( 'https://example.com/some/page' ); | |
} | |
} | |
} | |
add_action( 'pre_get_posts', 'redirect_out_of_stock_product' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment