I'm trying to add the ability to redirect a user to a random product/page/post url similar to example.com/page/random which would redirect to example.com/page/oneofmany.
This question is not WooCommerce specific because...
A. This question is about finding a random product/page/post url
B. This question is about 302 redirection from a shortcode to the url in A.
C. It just so happens I'm looking for the product type.
My guess is that I would need to use a custom shortcode ([random_product_page]) which would be replaced with a 302 redirect.
My Questions:
1. How do I retrieve the list of published product/page/post urls and pick one randomly.
2. How should the 302 redirect work?
3. How should this work within function.php, should it even go in function.php.
So far I'm currently trying to add a function to my child theme's function.php to redirect a page with the above short code but have only been able to replace the shortcode with an arbitrary string.
If there is a better way to handle this please let me know. Wordpress development is still pretty new to me.
It has to be a full redirect, example.com/page/random can't just display a random page, the url needs to change so that page view can be tracked.
Solution:
//Custom Code for a Random Endpoints
function random_endpoint() {
add_rewrite_endpoint( 'random', EP_ROOT );
}
add_action( 'init', 'random_endpoint' );
function random_redirect() {
// If we have accessed our /random/ endpoints.
$post_type = get_query_var( 'random' );
if ( $post_type == '' ) {
$post_type = [ 'post', 'page', 'product' ];
}
if ( get_query_var( 'random', false ) !== false ) {
// Get a random post.
$random_post = get_posts( [
'numberposts' => 1,
'post_type' => $post_type,
'orderby' => 'rand',
] );
// If we found one.
if ( ! empty( $random_post ) ) {
// Get its URL.
$url = esc_url_raw( get_the_permalink( $random_post[0] ) );
// Escape it.
$url = esc_url_raw( $url );
// Redirect to it.
wp_safe_redirect( $url, 302 );
exit;
}
}
}
add_action( 'template_redirect', 'random_redirect' );