programing

php에서 쿠키와 만료 날짜로 알림바를 닫는 방법?

bestprogram 2023. 9. 24. 13:03

php에서 쿠키와 만료 날짜로 알림바를 닫는 방법?

이전 질문에서 저는 워드프레스 사이트에 새로운 게시물이 게시되었을 때 알림 메시지를 만드는 방법을 찾고 있었습니다.훌륭한 답변 후에, 이것은 매우 잘 작동하고 있습니다.게시물이 게시된 시간 이후에 이 메시지를 표시할 기간의 설정을 변경할 수 있습니다.시간이 만료되면 메시지가 사라집니다.

따라서 Pieter Goosen에게 특별히 감사드립니다. 하지만 사용자가 메시지를 한 번이라도 본 적이 있다면 알림 표시줄을 닫고 사용자에게 더 이상 나타나지 않도록 할 수 있는 기능을 부여하고 싶습니다. 물론 다시 게시된 새로운 게시물이 제공되는 한 페이지 not talksens는 메시지를 반환합니다.

질문.

어떻게 해야 이런 일이 생길 수 있을까요?자바스크립트에 대해 생각하고 있었습니다.그 기능을 위해서는 당연히 닫기 버튼을 제어하는 기능이 하나 있어야 하는데, 사용자가 메시지를 닫았는지 아닌지를 확인하고 타이머 만료 시간 내에 확인하여 둘 다 서로 동기화되도록 하는 쿠키 기능도 있어야 한다고 생각합니다.

여기에서 확인할 수 있는 알림에 대한 이전 질문:

선택한 게시물 유형에서 총 게시물 수를 세는 방법은 무엇입니까?

[업데이트] 저는 그냥 앉아서 알림바의 구조를 명확히 하려고 해서 간단히 말해서 효과가 있는지 확인하려고 PieterGoosen 코드에서 워드프레스에서 사용할 수 있는 새로운 게시물이 있는지 확인하고 알림바를 보여줍니다.그러면 시간이 지난 후 또는 사용자가 닫기 버튼을 클릭한 후 바를 닫아야 합니다.그래서 코드도 그것을 확인해야 합니다.사용자가 닫기 버튼 == YES를 클릭하면 쿠키가 설정되어야 합니다(cookie는 PHP에 설정된 시간과 동기화되어야 함), 새로운 게시물이 있을 때마다 쿠키가 삭제됩니다.사용자가 닫기 버튼을 클릭하지 않으면 메모를 하고 시간이 만료되면 쿠키도 삭제합니다.

나는 해결책을 가지고 있다.최대한 많은 시나리오로 코드를 테스트했습니다.

저는 이 질문에 대한 답변에서 사용했던 것과 동일한 코드를 사용했습니다.그래서 다시는 그 부분에 도전하지 않겠습니다.

워크플로우 파트 1

우리는 jquery를 사용하여 알림바를 숨기고 쿠키를 사용하여 최신 게시물 ID를 저장하고 새로운 게시물이 게시되거나 만료 시간이 만료될 때까지 알림을 숨길 것입니다.

이를 위해 jquery의 기능을 사용하여 사용자가 숨김 버튼을 클릭하면 알림바를 숨길 것입니다.필요에 따라 이 단추를 사용자 지정하거나 다른 유형의 기호를 사용할 수 있습니다.

우리는 이제 새로운 게시물이 게시될 때까지 버튼을 숨겨둘 방법을 사용해야 합니다.숨김 버튼을 클릭하면 쿠키를 설정할 수 있습니다.쿠키가 2일 후에 만료되도록 설정되어 있으므로, 2일 이내에 새로운 게시물이 게시되지 않으면 쿠키는 자동으로 만료됩니다.쿠키를 설정하려면 jquery-cookie 플러그인을 다운로드해야 합니다.또한 이 플러그인은 쿠키가 설정되어 있을 때 새 게시물이 게시될 때 쿠키를 강제로 삭제합니다.

은 ID 합니다에 합니다.new_post_notification. 문제는 php 변수를 jquery에 직접 전달할 수 없다는 것입니다.다행히 워드프레스에는 포스트 ID를 jquery 스크립트에 전달하기 위해 사용할 수 있는 기능이 있습니다. 여기서 쿠키 값으로 사용할 것입니다.

1절은 여기까지, 코딩을 시작합니다.

LETS 코드 섹션 1

합니다.jquery.cookie.js테마의 js 폴더에 파일을 저장합니다. 다음 새으로 js다로 지정합니다.hide.notification.bar.js 이 에 다음 합니다. 새로 만든 이 파일을 열고 거기에 다음 코드를 붙여넣고 저장합니다.

jQuery(document).ready(function($) {

    $("#notification_hide_button").click(function(){
        $(this).hide();
        $(".notifications_bar").hide();

        if ($.cookie( 'hide_post_cookie' ) ) { 
            $.cookie( 'hide_post_cookie', null ) 
        }
        var post_id = parseInt( cookie_Data.post_id, 10 );

        $.cookie( 'hide_post_cookie', post_id, { expires: 2, path: '/' } );

    });

});

알림 표시줄을 숨기기 위해 사용되는 코드로 쿠키를 설정합니다.var post_id = parseInt( cookie_Data.post_id, 10 );트 입니다 여기서 합니다.

이두를 js .wp_localize_script기능. .기능을 엽니다. php에 다음 php하고 거기에 다음 내용을 붙여넣습니다.만약 당신이 이미 가지고 있다면.wp_enqueue_scripts 코드를 의 기능면에 됩니다,다.

function enqueue_cookie_scripts() {

    wp_enqueue_script( 'jquery-cookie', get_template_directory_uri() . '/js/jquery.cookie.js', array( 'jquery' ), '' , true );
    wp_register_script( 'set-cookie-option', get_template_directory_uri() . '/js/hide.notification.bar.js', array( 'jquery', 'jquery-cookie'), '' , true );

    $cookie_data = array(
        'post_id' => get_option( 'new_post_notification' )->ID
    );
    wp_localize_script( 'set-cookie-option', 'cookie_Data', $cookie_data ); // this one do the magic

    wp_enqueue_script( 'set-cookie-option' );

}

add_action( 'wp_enqueue_scripts', 'enqueue_cookie_scripts' );

다음을 설정하는 함수를 복사하여 붙여넣을 수도 있습니다.new_post_notification새 게시물이 게시될 때 선택할 수 있습니다.이 코드가 어떻게 작동하는지에 대한 참고 자료는 여기에서 확인하세요.이 코드는 기능을 합니다.php

add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
    //Check if our post status then execute our code
    if ( $new_status == 'publish' && $old_status != 'publish' ) {
        if ( get_option( 'new_post_notification' ) !== false ) {

            // The option already exists, so we just update it.
            update_option( 'new_post_notification', $post );

        } else {

            add_option( 'new_post_notification', $post );

        }
    }

}, 10, 3 );

워크플로우 파트 2

이제 jquery가 작동할 수 있는 모든 것을 마련했고, 알림바를 표시하는 기능을 설정하고, 쿠키의 유효기간이 지나지 않은 경우에는 hide 버튼을 표시하고 새로운 게시물을 설정하면 쿠키를 삭제해야 합니다.

이 코드는 잘 설명되어 있으므로 이제 따라하기가 어려울 것입니다.여기서 가장 중요한 부분은 전역 변수에 저장되어 다음과 같이 검색할 수 있는 쿠키의 값을 구하는 것입니다.$_COOKIE['hide_post_cookie']. 이 ID는 실제로 게시물 ID이며, 이 ID는 에 저장된 게시물과 비교하여 확인됩니다.get_option( 'new_post_notification' )->ID

숨김 버튼은 그 안에 있는 모든 것을 숨길 것입니다.<div class="notifications_bar"></div>, 그러면 그 디브 안에 알림바를 추가하게 됩니다.필요에 따라 사용자 지정합니다.

다음과 같이 헤더에 호출할 수 있는 함수 안에 모든 코드를 추가했습니다.

echo get_new_post_notification_bar(); 

섹션 2 코드

이 코드는 당신의 기능에도 들어갑니다.php

function get_new_post_notification_bar() {

    // Get the new_post_notification which holds the newest post
    $notification   = get_option( 'new_post_notification' );

    // Get the post ID saved in the cookie
    $cookie_post_ID = isset( $_COOKIE['hide_post_cookie'] ) ? (int) $_COOKIE['hide_post_cookie'] : false; 

    $output = '';
    if( false != $notification ) {

        //First check if we have a cookie, if not, show the notification bar
        // If a cookie is set, do not display the notification bar
        if( false === $cookie_post_ID ) {

            //Get the post's gmt date. This can be changed to post_date
            $post_date = strtotime( $notification->post_date_gmt );

            //Get the current gmt time
            $todays_date = current_time( 'timestamp', true );

            //Set the expiry time to two days after the posts is published
            $expiry_date = strtotime( '+2 day', $post_date );

            //Show the notification bar if the expiry date is not yet reached
            if( $expiry_date > $todays_date ) { 

                $output .= '<div class="notifications_bar">';
                $output .= 'If you click on the "Hide" button, I will disappear.';
                $output .= '</div>';
                $output .= '<button id="notification_hide_button">';
                $output .= 'Hide';
                $output .= '</button>';

            }

        }else{

            /**
             * If a cookie is set, check the cookie value against the post id set as last post
             * If the two don't match, delete the cookie and show the notification bar if a new post is published
             * This code only run once, that is when a cookie is still set, and new post is published within the time
             * in which the cookie is still set
            */ 
            if( (int) $notification->ID !== $cookie_post_ID ) {

                ?>
                    <script>
                        jQuery(document).ready(function($) {

                            $.removeCookie('hide_post_cookie', { path: '/' });

                        });
                    </script>
                <?php

                $output .= '<div class="notifications_bar">';
                $output .= 'If you click on the "Hide" button, I will disappear.';
                $output .= '</div>';
                $output .= '<button id="notification_hide_button">';
                $output .= 'Hide';
                $output .= '</button>';

            }

        }   

    }

    return $output;

}

언급URL : https://stackoverflow.com/questions/27335088/how-to-close-a-notification-bar-with-cookies-and-expiry-date-from-php