Skip to content

Instantly share code, notes, and snippets.

@isuke01
Created October 26, 2017 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isuke01/36282f253d31e355c4f684fdb7e6abc5 to your computer and use it in GitHub Desktop.
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.
/**
* 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