programing

워드프레스:여러 언어를 선택할 경우 method="post" 사용

mailnote 2023. 10. 3. 11:14
반응형

워드프레스:여러 언어를 선택할 경우 method="post" 사용

두 개의 플래그가 있는 듀얼 언어를 엔트리 페이지로 하는 웹사이트를 만들고 있습니다.입니다를 <form method="post">사용자가 원하는 언어를 선택할 수 있도록 플래그 주위에 표시합니다.

다음 페이지에서는 다음과 같은 것을 사용하고자 합니다.

<?php
if( $_POST['language']=='uk' ){
    echo $uk;
}elseif( $_POST['language']=='french' ){
    echo $french;}
?>

그래서 이 깃발을 클릭하면 그들은 자신이 원하는 언어를 클릭합니다.플래그를 클릭한 후에만 다음 페이지에서 작동합니까? 아니면 다른 페이지로 계속 이동할 수 있으며 선택한 언어를 계속 선택할 수 있습니까?

만약 그것이 효과가 없다면, 어떻게 다른 방법으로 할 수 있습니까?


업데이트:

것을 것 는 요, 요를 않는 것 .$_SESSION.

저는 지역이라는 템플릿에 이것을 가지고 있습니다.언어 선택을 제출하려면 php:

    <form action="<?php the_permalink(); ?>/home" name="region" method="post">              
        <div id="uk">
            <a href="javascript:document.region.submit()" name="UK">
                <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/-uk.png" width="259" height="160" alt="UK" />
            </a>
            <h1 style="color:black!IMPORTANT;">Enter United Kingdom site</h1>
        </div>

        <div id="world">
            <a href="javascript:document.region.submit()" name="World">
                <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/
world.png" width="258" height="160" alt="
Rest of the World" />
            </a>
            <h1 style="color:black!IMPORTANT;">Enter Rest of the World site</h1>                    
            </div>  
    </form>

어떤 언어가 선택되었는지 확인하려면 다른 모든 템플릿에 무엇을 넣어야 합니까?예를 들어, UK가 선택된 경우 "UK"를 반향하면 되고, 나머지 세계가 선택된 경우 "World"를 표시하면 됩니다.

이 작업은 여러 페이지에 걸쳐 수행되어야 하므로 정보 페이지로 이동하면 언어를 확인하고, 연락처 페이지로 이동하면 언어를 다시 확인합니다(초기 언어 선택에서 시작해야 하는 모든 것).

는 그 을 입니다.$_SESSION변수. .그것은 그들이 떠날 때까지 그들과 함께 있을 것입니다.쿠키를 아주 멋지게 사용할 수도 있습니다.실제로 이 두 가지 조합이 좋을 것입니다. 방문 시 쿠키 실행을 허용하지 않는 사용자를 묶고 쿠키를 사용할 수 있는 사용자는 한 번만 선택하면 됩니다.

편집: 작동 코드의 예:

<form action="<?php the_permalink(); ?>/home" name="region" method="post">              
    <div id="uk">
    <a href="javascript:document.region.submit()" name="UK">
        <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/=uk.png" width="259" height="160" alt="UK" />
    </a>
    <h1 style="color:black!IMPORTANT;">Enter United Kingdom site</h1>
    </div>

    <div id="world">
    <a href="javascript:document.region.submit()" name="World">
        <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/world.png" width="258" height="160" alt="Rest of the World" />
    </a>
    <h1 style="color:black!IMPORTANT;">Enter Rest of the World site</h1>                    
    </div>  
</form>
// I assume that this form sends a POST request to the following page URL.

양식이 리디렉션되는 페이지:

<?php

    session_start();
    if(isset($_POST['country'])) 
    // assuming that your form returns a field called 'country'...
    {
        $_SESSION['myCountry'] = htmlspecialchars($_POST['country']);
        // Assumes that myCountry is now 'UK' or 'World'...
    }
    header('Location: http://www.example.com/yourIndexPage.php');
    // You want to use a quick snippet to process the form and 
    // then redirect them away. This makes for less stupid BACK actions
    // in the browser as well as data being resent to the code.
?>

당신의 Index page.php

<?php

    // As the $_SESSION is now set, we can use it in the page as follows:
    session_start();
    switch($_SESSION['myCountry'])
    {
        case 'UK':
            echo $UK;
            // And anything else you want to do with the UK language.
            break;
        case 'World':
            echo $world;
            // etc etc etc...
            break;
        default:
            // echo out default stuff, probably 'World' at a guess.
            break;
    }

?>

워드프레스를 사용하고 있다면 이 글을 읽어보아야 할 것입니다.

답들

첫째, 워드프레스 사이트에 지역/다국어 지원을 추가하기 위해 이 플러그인 http://wpml.org/ 보다 더 나은 대안은 없습니다.이에 관련된 비용이 발생하지만, 이를 금지하는 것은 아닙니다(엄청난 지원을 위해 비용을 지불합니다).

둘째, 기본적으로 $_SESS를 사용할 수 없습니다.WP는 설계상 상태 비저장 상태입니다.이 기능을 얻기 위한 수많은 플러그인과 자습서가 온라인에 있다고 합니다.

코드적인

원래 양식 html에 입력 사항이 없습니다.아무것도 제출하지 않은 양식이었습니다.다 을 가진 두 .location하면 . 됩니다에 됩니다.$_POST['location'].

<form action="<?php the_permalink(); ?>/home" name="region" method="post">              
    <div id="uk">
        <input type="submit" name="location" value="UK" />
        <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/uk.png" width="259" height="160" alt="UK" />
        <h1 style="color:black!IMPORTANT;">Enter United Kingdom site</h1>
    </div>

    <div id="world">
        <input type="submit" name="location" value="World" />
        <img style="margin-bottom:10px;" src="<?php bloginfo('stylesheet_directory'); ?>/images/world.png" width="258" height="160" alt="Rest of the World" />
        <h1 style="color:black!IMPORTANT;">Enter Rest of the World site</h1>                    
    </div>  
</form>

게시물 처리를 위한 워드 프레스 작업을 작성합니다.테마의 기능 파일에 추가합니다.쿠키 문서는 http://php.net/manual/en/function.setcookie.php 에서 확인할 수 있습니다.

function set_location_cookie()
{
    if(isset($_POST['location']))
    {
        setcookie('location', $_POST['location'], time()+1209600);
    }
}
add_action('init', 'set_location_cookie');

그런 다음 위치를 알고 싶은 곳이라면 어디든:

<?php echo $_COOKIE["location"]; ?>

추가 정보

저는 처음에 UK를 클릭하여 쿠키를 설정하고, 다시 돌아가서 World를 클릭했지만 쿠키 위에 world가 복사되지 않고 다시 UK를 표시했습니다.다른 선택을 할 때마다 쿠키를 지우는 것이 가능합니까?

따라서 쿠키가 기술적 수준에서 작동하는 방식에 대한 문제입니다.

브라우저가 이 작업을 [사이트 요청]하면 [사이트]가 설정한 쿠키 파일을 컴퓨터에서 찾습니다.쿠키 파일을 찾으면 브라우저가 파일의 모든 이름과 값 쌍을 URL과 함께 [the] 서버로 보냅니다. 쿠키 파일을 찾지 못하면 쿠키 데이터를 보내지 않습니다.

새로운 쿠키 데이터는 처음에 전송되지 않습니다. b/c inst는 브라우저에서 서버로 요청이 전송된 후 새로운 쿠키 데이터가 저장되고 요청과 함께 전송할 수 있습니다.

그럼 이 일을 어떻게 만드나요?쿠키 설정 이벤트가 성공한 후 리디렉션합니다.

function set_location_cookie()
{
    if(isset($_POST['location']))
    {
        // Set Cookie
        setcookie('location', $_POST['location'], time()+1209600);
        // Reload the current page so that the cookie is sent with the request
        header('Location: '.$_SERVER['REQUEST_URI']);
    }
}
add_action('init', 'set_location_cookie');

또한 깃발의 이미지를 제출 버튼으로 사용하는 것도 가능한가요?예, CSS를 사용하여 입력 버튼을 스타일화합니다.

에 ID :id="uk-button"그리고.id="world-button"

CSS:

#uk-button {
    background-image: url(uk-flag.png);
    background-size: 100%;
    background-repeat:no-repeat;
}
#world-button {
    background-image: url(world-flag.png);
    background-size: 100%;
    background-repeat:no-repeat;
}

쿠키를 사용하고 싶지 않다면 이렇게 하면 됩니다.

session_start();    
if(!isset($_SESSION['language'])){
    $_SESSION['language'] = 'English'; //default language
}

그리고 당신이 2개의 버튼을 가지고 있을 때, 하나는 영어이고 다른 하나는 독일어이거나 당신이 원하는 것입니다.

<a href="?language=English">English</a>
<a href="?language=German">German</a>

이 체크를 사용하여 페이지가 어떤 언어가 되어야 하는지 확인할 수 있습니다.

if(isset($_GET['language'])){
    if($_GET['language'] == 'English'){
        $_SESSION['language'] = 'English';
    }
    if($_GET['language'] == 'German'){
        $_SESSION['language'] = 'German';
    }
} 

$_POST 변수는 단일 요청에만 포함된 데이터(POST(HTTP))를 포함하므로 "클릭" 후에 적절한 내용을 보거나 일부 양식을 페이지에 게시하므로 요청 후에만 해당 페이지에 해당합니다.

사용자 설정을 보다 영구적으로 저장하려면 $_SESS 변수에서 사용할 수 있고 영구적이므로 방문자가 페이지를 탐색할 때까지 이 설정을 "세션" 데이터에 저장해야 합니다.보다 영구적이지만 약간 덜 순수한 솔루션은 쿠키에 설정을 저장하여 다음 방문 시에도 쿠키를 사용할 수 있도록 만료를 정의할 수 있습니다.

몇 가지 예를 참조하십시오.

<?php

session_start();
$language = $_POST['language'];
$_SESSION['language'] = $language;

...기타:

<?php

session_start();
$language = $_SESSION['language'];

또는 쿠키를 사용할 수 있습니다.

<?php

session_start();
$language = $_POST['language'];
set_cookie('language', $language, 365 * 24 * 60 * 60);   
// will live for one year

...기타:

$language = $_COOKIE['language'];

다른 페이지에서는 작동하지 않습니다.POST 변수가 항상 전송되는 것은 아닙니다.양식을 제출할 때만 발송됩니다.쿠키를 작업에 사용할 수 있습니다.거기에 변수를 저장하고 모든 페이지에서 확인합니다.

선택을 지속하거나 값을 계속 전달하려면 세션/쿠키가 정말 필요합니다.GET맘에 들다?lang=uk, 하지만 그것은 그다지 우아하지 않습니다.그런데 기본 동작이 차단되고 상위 폼이 자바스크립트와 함께 제출되는 하이퍼링크 내의 이미지는 필요 없습니다.간단히 다음과 같은 것을 사용할 수 있습니다.

<input alt="en-UK" name="lang" src="uk-flag.png" type="image" value="en-UK">

이것은 양식 제출 버튼인 이미지로도 작동합니다.

언급URL : https://stackoverflow.com/questions/11796046/wordpress-use-method-post-for-multiple-language-selection

반응형