简体   繁体   中英

Creating a button with a dynamic link to a page based on data in Wordpress User Object

I would like to add a 'Book Now' button on my home page that takes logged in users to a specific page based on data in the WP user object. For example:

If a user that is not logged in clicks the button they are directed to my login page.

If a user that is logged in clicks the button I want them to be dynamically re-directed to the right page to book - This will be based on data from a required field from the registration form.

First question: In what ways can I achieve this? I assume that I would use a PHP script? If so, I am familiar with using custom php and adding it in like a plugin. But I am not sure how I would link this to a button click. The button in particular is formatted via the Astra Theme editor and I can only see an option to add an HTML link. Can I link direct to a php script?

Second question: What would the code look like to retrieve the data from the WP user object?

Third question: Once I have the data - Would I use a php switch to handle the re-direct - Like so:

   case 'London':
$redirect_to = 'http://example.com/my-page/london';
break;

case 'New York':
$redirect_to = 'http://example.com/my-page/new-york/';
break;

default:
$redirect_to = 'http://example.com/my-page/some-default-page';
break;

}

// the "if" check here is just in case $redirect_to is accidentally empty
if ( isset( $redirect_to ) ) {
wp_redirect( $redirect_to );
exit();
}
}

Many thanks,

Guy

You can try this:

<?php
if( is_user_logged_in() ) {
    $city = get_user_meta( get_current_user_id(), 'city', true ); // Get the prevered city from the user meta.

    // Detirmine the redirect url for the selected city
    switch ($city) {
        case 'london':
            $redirect_to = '/cities/london';
            break;
        case 'amsterdam':
            $redirect_to = '/cities/amsterdam';
            break;
        default:
            $redirect_to = '/cities'; // if no city provided.
    }

    // make a link to the selecte url.
    echo '<button onclick="window.location.href=\'' . $redirect_to . '\'">' . $city . '</button>';

} else {
    wp_redirect('/login'); // If user is not loged in, redirect to the login page.
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM