-1

enter image description here

Right now I'm getting the id statically in my output "1778a1778" because of array_push(), but I have to send ID dynamically and get the same output.

0

If you want the ID of the current post outside of the loop, you can use get_queried_object_id(). Just make sure to check is_singular() first, or you could end up storing IDs of things other than posts. This could cause problems if there's overlap with post IDs. I'd share the amended code with those changes, but for some reason you posted a screenshot instead of code, and I'm not writing it out by hand.

  • add_action( 'wp', 'cookies_for_posts' ); function cookies_for_posts() { $viewed = array(); $viewed= get_the_ID(); $post_arr=array(); array_push($post_arr,$viewed); array_push($post_arr,$viewed); $post_str=implode( 'a' , $post_arr); var_dump($post_str); setcookie( 'cookies_for_posts', $post_str, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true, ); } – Ankush May 24 '19 at 8:25
  • You can use this and you can suggest me. – Ankush May 24 '19 at 8:27
  • as I have written " array_push($post_arr,$viewed); " twice so I'm getting the output after var_dump " 1778a1778 " but what I need is that on page refresh the ID should dynamically get add. For ex. 1st-time refresh page. Output = " 1778 " 2nd-time when I refresh the page. The output should be = " 1178a1178 " 3rd-time when I refresh. The output should be = " 1778a1778a1778 " like that – Ankush May 24 '19 at 8:34
  • Your question was about the ID, which I've answered. If you have a new question, then post a new question. Or you should clarify your original question, which at the moment doesn't make a lot of sense. – Jacob Peattie May 24 '19 at 9:04
  • I'm having a douth in the same question so. Thanks Btw. – Ankush May 24 '19 at 9:09
0
add_action( 'wp', 'Store_cookies_of_user' );
function Store_cookies_of_user() {  
$ids = isset( $_COOKIE['bsf_docs_cookies'] ) ? explode('a', $_COOKIE['bsf_docs_cookies']) : array();
if( ! in_array(get_the_ID(), $ids) ) {

        // Add to array.
        $ids[] = get_the_ID();

        // Impload with `a` stirng!
        $ids = implode('a', $ids);

        // Increase currend doc view count with 1.
        $count = (int) get_post_meta( get_the_ID(), 'views', true );
        update_post_meta( get_the_ID(), 'views', ($count+1) );

        // Set updated ids list.
        setcookie(
           'bsf_docs_cookies',
            $ids,
            time() + 86400,
            COOKIEPATH,
            COOKIE_DOMAIN,
            false,
            true,
        );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.