dinsdag 24 juli 2012

Creating a popup-bar in Wordpress using jQuery


This is how I made a non-intrusive pop-up-bar with jQuery that I used in Wordpress to notify users when they logged in.

First we should make sure that to load jQuery in a proper way. A common mistake here is to add it hardcoded in the header.php like this:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

The above line will load the jQuery library on all our pages. We do not want that The dashboard pages could have their own libraries that might come into conflict with our jQuery library. The correct way to solve this in Wordpress is to add:

// Load the google API jQuery in.
function load_google_jquery() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' );
    wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts' , 'load_google_jquery' );

To your functions.php file. This will make sure your jQuery library is only loaded on the user pages it was originally intended for.

Building our actual popup-bar. In the <head> we will place our CSS with an if statement to check if we have a 'popup_message' to display.

<?php if ( $popup_message = $_GET['popup_message'] ) : ?> 
  
       <style type="text/css">
        #popup-message {
            display:none;
            text-align:center;
            background-color:#ccccff;
            color:#5c518d;
            font-weight:bold;
            font-size:20px;
        }
        </style>
<?php endif; // END CSS popup message ?>   

We are putting the html for our popup message in our <body> tag right above our other html code containers. Again we check if an actual '$popup_message' exists to begin with. Otherwise this code is not generated. The /*

<?php if ( isset( $popup_message ) ) : // popup ?>
       <script type="text/javascript">
            /* <![CDATA[ */
            $(document).ready(function() {
                // DOM loaded & ready              
                $('#popup-melding').slideDown('slow', function(){ });            
            });
            /* ]]> */
          </script>
        <div id="popup-message">
           <span><?php echo $popup_message; ?></span>
        </div>
       
<?php endif; //END non-intrusive popup message  ?>

A possible use this popup-bar is to notify our user he just logged in after we redirected him back to the home page.
wp_redirect( home_url() . "?popup_message=". urlencode( __( "You are succesfully logged in." ) ) );
exit;

If you’d like to redirect the user to the same page you could use $_SERVER['HTTP_REFERER'] variable to find the URL of the original redirecting page. The __() function is handy to later automate translation of your theme. It is worth reading about internationalisation in wordpress.