[英]Creating a button with a dynamic link to a page based on data in Wordpress User Object
我想在我的主頁上添加一個“立即預訂”按鈕,根據 WP 用戶對象中的數據將登錄用戶帶到特定頁面。 例如:
如果未登錄的用戶單擊該按鈕,他們將被定向到我的登錄頁面。
如果登錄的用戶單擊按鈕,我希望他們動態重定向到正確的頁面進行預訂 - 這將基於注冊表中必填字段中的數據。
第一個問題:我可以通過什么方式實現這一目標? 我假設我會使用 PHP 腳本? 如果是這樣,我熟悉使用自定義 php 並將其添加為插件。 但我不確定如何將其鏈接到按鈕點擊。 特別是該按鈕是通過 Astra Theme 編輯器格式化的,我只能看到添加 HTML 鏈接的選項。 我可以直接鏈接到 php 腳本嗎?
第二個問題:從 WP 用戶對象中檢索數據的代碼是什么樣的?
第三個問題:一旦我有了數據 - 我會使用 php 開關來處理重定向 - 像這樣:
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();
}
}
非常感謝,
蓋伊
你可以試試這個:
<?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.
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.