0

I've written up a simple function that's output into header.php, which displays the login/register modal upon so many views in this case I've set it at 4, however its firing on the first view of my listings CPT. Any insight would be greatly appreciated!

Here's the function:

function ct_display_login_register_after_x_views() {

    session_start();

    if(isset($_SESSION['views'])) {
        $_SESSION['views'] = $_SESSION['views'] + 1;
    } else {
        $_SESSION['views'] = 1;
    }

    if($_SESSION['views'] >= 4 && !is_user_logged_in() && is_singular('listings') ) {
        $output = '<script>';
            $output .= 'jQuery(window).load(function() {';
                $output .= "jQuery('#overlay').addClass('open');";
                $output .= "jQuery('html, body').animate({scrollTop : 0},800);";
                $output .= 'return false;';
            $output .= '});';
        $output .= '</script>';

        $output .= '<style>';
            $output .= '#modal .close { display: none;}';
        $output .= '</style>';

        echo $output;

    }
}

Then the output in header.php

<?php ct_display_login_register_after_x_views(); ?>
  • Keep in mind this system will never work with caching, your site will never be capable of high traffic situations, it'll also fail on some hosts, e.g. a site running on WP Engine will never work with this code. Also note that your session counting code runs on every page, not just listings. Would it not be better to do this 100% on the client side in JS? – Tom J Nowell Dec 10 '17 at 20:50
  • Gotcha, what would be the best way to do this with pure JS? Any examples that sounds like a much better way to accomplish it. – contempoinc Dec 10 '17 at 20:53
  • Use local storage in JS or equivalent to store the number of times a listing has been viewed. This way you only need to figure out if you're on a listings page in JS, which is trivial if you've built your theme correctly ( and a very good question to ask as a new question ) – Tom J Nowell Dec 10 '17 at 20:55
  • 1
    Opened another thread for a JS based version wordpress.stackexchange.com/questions/288286/… again any help is greatly appreciated! – contempoinc Dec 10 '17 at 23:24

Your Answer

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

Browse other questions tagged or ask your own question.