Author Archives: admin

Using the Data Shortcodes in Shortcode Revolution

The Data Shortcodes tab in the Shortcode Revolution plugin is simple but powerful way to build profile pages, greetings, widgets with user stats, and so on.ย  It has 3 ways to specify the user whose data we’ll be showing:

Currently Logged User

Probably the simplest and most frequent use will be to get data for the currently logged in user and do something with it. A simple example is just a greeting:

Getting a shortcode for first name

You can get this shortcode and place it in a widget like this for example:

Hello, [srevo-profile user_id=”logged_in” field=”first_name”]!

Which will produce Hello, John! or whatever the user name is. So far so good.

If you want to use it inside your theme instead of a widget you need to use do_shortcode. Like this:

<?php echo do_shortcode(‘Hello, [srevo-profile user_id=”logged_in” field=”first_name”]!’);?>

This is simple and easy.

Fixed User IDUsing the shortcode for a fixed user ID

This usage is less common inside a post or widget because you will rarely have such fixed content for each of your users in the system. It is however very useful if you are doing something with programming in your theme. In this case you can dynamically pass the user ID. Something like this:

<?php echo do_shortcode(‘[srevo-profile user_id=”specific” user_id=”‘.$current_user_id.'” field=”meta_account_status”]’);?>

* Please note that the above example assumes you have created the variable $current_user_id. If not, you can use the built-in WP function get_current_user_id().

User ID Passed by URL Parameter

This is the most powerful way to use the data shortcodes and it works great when you are creating dynamic profile pages or other pages which display data for all users.

Using the shortcode with a GET parameter

In this example we are building a profile page (obviously we have not formatted anything in the enclosed content in the shortcode. But you can nicely format a table or other user interface with colors, font formatting, etc.

The important thing here is the variable name field. You can use any variable – in our example it is called “uid”, but you can use “user_id”, “member_id” or whatever you like. You can then load the profile data by passing this variable in the URL of the page where you have published the shortcode. For example let’s assume you have published the shortcode in this URL:

https://blog.calendarscripts.info/user-profile/

Then going to https://blog.calendarscripts.info/user-profile/?uid=25 (if you have used the variable name “uid”) will show the data for user with ID 25.

Let’s create a very simple example of how you can use this in a page that lists all users in your system. The page could be created with a custom shortcode or a theme function:

<?php
// let's assume you have existing array of members in $members
foreach($members as $member) {
   echo '<p><a href="'.add_query_arg(['uid' => $member->ID], 'https://blog.calendarscripts.info/user-profile/').'">'.$member->display_name.'</a></p>';
}

That’s it. Simple and powerful.

Shortcode Revolution for WordPress

During our work on various WordPress installations I have figured out that we repeatedly create (oh well, kind of copy/paste) layout elements, dynamic stuff like lightboxes and sliders, pieces of code in custom plugins, and so on.

Some of these codes slowly turned into a library so we decided to go ahead and package them into a new free plugin called Shortcode Revolution. (You can check it at our site or directly at the WordPress repo)

This is just a very first version so there is hopefully a lot more to come. But let’s have a brief look at what’s available:

Posts, Related Posts, and Comments

UI for posts / comments shortcode

This allows you to create widgets that contain posts related to a topic, searched by ID or tag, related to the currently shown post, and so on.

There are 3 handy layout modes: simple list, default (with a thumbnail and excerpt), and a carousel / slider.

And above this paragraph you see a slider / carousel of 3 posts related to this one.

Popup / Lightbox

modal box UI

This is such a frequent task, and this plugin really makes it easy. Just enter your contents, some clickable text and probably some custom CSS classes. Voila, the popup is created.

Click me!

Columns and Grids

Columns / Grids UI

I mean, it’s typical that the content on the web normally just stays in one column. But who said it should always be that?

Do you remember newsletters? I hope our readers are not all that young. Newsletters (the paper ones!) typically have content flowing in multuple columns. That’s not typical for the web not because it’s bad but because it was hard thing to do in the past.

Now with the new CSS techniques it’s not that hard. But you don’t always want to write CSS especially when you are writing a blog post, do you? This is where the columns shortcode comes handy!

The shortcode also allows you to create a grid. In the grid the content does not flow in the columns. Instead, each piece stays in its own grid cell. Like this:

Hey, I’m the first item

And I am number two

They can all be different

And can contain images (look right)

Chart from a personality quiz

This at left is from our quiz plugin WatuPRO

Third line, item 1

And number two

The ninth item goes here

Tabs

Tabs UI

Tabs allow you to place content within, well, tabs. What does it mean? Look at this:

As I told you, you canย  arrange content in tabs ๐Ÿ™‚ Just click on one of these tabs and you’ll see the content related to each one.
just a chartLet’s just have a chart here to look smart.

Buttons

Create buttons UI

There isn’t so much to explain here. You get an easy to use UI to create all kind of buttons.

Tables

create tables from CSV

This one is super simple – it creates table from an uploaded CSV file. Technically you can use a remove or a dynamic CSV as well – just replace the uploaded file URL with the remote one.

Tables aren’t that much fascinating – I am sure you have seem some! So no demo for this shortcode.

Flashcards / Flipcards

Create flashcard shortcodes

There cards have a front and a back side and reveal the back when the user clicks on them. Simple:

Here’s a Math task:

2 + 2*3?

Of course it’s 8 because multiplication has a higher priority than addition ๐Ÿ™‚

Who is she?

Adriana Lima

You can even combine shortcodes together like I did above. I placed two flashcard shortcodes in a grid so they can be side by side.

Data Shortcodes

creating a data shortcode

They are excellent for creating profile pages in communities, author pages, widgets containing some user data, and so on.

Custom Shortcodes

Just any content that you may want in many places on your site. Custom HTML, shortcodes, media, formulas, whatever. Easily repeatable and editable in one place.

Enjoy the plugin – it’s free and can save you many hours of work. Let us know your feedback, feature requests, and bug reports (yes, even bug reports!).

Display Custom Tooltips in Chart.js 3

Chart.js is a lovely library for interactive charts. It’s probably the best free and open source library for JavaScript based charts available at the moment.

For a project that creates custom charts based on data collected with our quiz and survey WP plugin we had to create custom tooltips that appear when the mouse hovers any of a linear chart datapoints.

The Problem

The default tooltips in chart.js unfortunately allow only text. For our project we needed to include fully featured HTML code – a pop-up with an image and text had to appear when the mouse is hovered on a data point.

The Solution In Action

Here is what you will achieve after following this kind-of a tutorial:

Info about One

Content, including images can be placed here.

Close

Info about Two

Content, including images can be placed here.

Close

Info about Three

Content, including images can be placed here.

Close

Info about Four

Content, including images can be placed here.

Close

Info about Five

Content, including images can be placed here.

Close

You see how the tooltips are fully featured HTML boxes with text, image(s), and a close button.

The Solution in Code

For this post we just created a hardcoded chart with 5 data points and 5 divs with information about them. It’s of course more likely that you will use some dynamic data from a database, etc. So you will need to loop through the data and generate parts of the HTML and JS code. This however does not change the logic that we will describe here.

First, let’s create some basic HTML. You need a div with information (tooltip contents) for each data point. The important thing here is to place these divs AND your chart canvas in a wrapper with position:relative. Each of the info divs has position:absolute. This allows you to properly display the divs pretty close to each data point.

<style type="text/css">
    .pointinfo-container {
        display:none;
        padding: 7px;
        background: white;
        width: 200px;
        border: 1pt solid black;
        position: absolute;
    }
    </style>

    <div style="position: relative;"><!-- This is the wrapper -->
        <div id="pointInfo1" class="pointinfo-container">
            <h3 class="pointinfo-event-title">Info about One</h3>			  		
            <span ><a href="#" onclick="closePointInfo(1);return false;">Close</a></span>
        </div>
        
        <div id="pointInfo2" class="pointinfo-container">
            <h3 class="pointinfo-event-title">Info about Two</h3>
            <span ><a href="#" onclick="closePointInfo(2);return false;">Close</a></span>
        </div>
        
        <div id="pointInfo3" class="pointinfo-container">
            <h3 class="pointinfo-event-title">Info about Three</h3>
            <span ><a href="#" onclick="closePointInfo(3);return false;">Close</a></span>
        </div>
        
        <div id="pointInfo4" class="pointinfo-container">
            <h3 class="pointinfo-event-title">Info about Four</h3>
            <span ><a href="#" onclick="closePointInfo(4);return false;">Close</a></span>
        </div>
        
        <div id="pointInfo5" class="pointinfo-container">
            <h3 class="pointinfo-event-title">Info about Five</h3>
            <span ><a href="#" onclick="closePointInfo(5);return false;">Close</a></span>
        </div>	
        
        <div><canvas id="myChart" style="display: block; box-sizing: border-box; height: 306px; width: 612px;"></canvas></div>
    </div>

For clarity we have omitted most of the contents of the div.

And now, more important, the JavaScript.

var myChart = null;
    jQuery( document ).ready(function() {
            var ctx = document.getElementById('myChart').getContext('2d');
            myChart = new Chart(ctx, {	
            type: 'line',
            data: {
                labels: ['One', 'Two', 'Three', 'Four', 'Five'],
                datasets: [{
                    label: 'Demo Chary',			
                    data: [22, 33, 17, 67, 8],
                    fill: 'false',
                    borderColor: '#052148',
                    backgroundColor: 'white',			
                }],
            },
            options: {
                aspectRatio: 3,
                responsive: true,
                maintainAspectRatio: true,
                layout: {
                    padding: {
                        left: 30,
                        right: 40,
                        top: 70,
                        bottom: 10
                    }
                },
                legend: {
                    display: false
                },
                plugins: {
                    
                },
                tooltips: {
                    enabled: false
                },
        
                onHover: (e) => {	
                    			
                      var meta = myChart.getDatasetMeta(0);
                      datapoints = [
                      	 {'x' : Math.round(meta.data[0].x), 'y': Math.round(meta.data[0].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[1].x), 'y': Math.round(meta.data[1].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[2].x), 'y': Math.round(meta.data[2].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[3].x), 'y': Math.round(meta.data[3].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[4].x), 'y': Math.round(meta.data[4].y)},
                      ]; 
                        
                        
                       if(typeof(datapoints) === 'undefined') return false;
                    const canvasPosition = Chart.helpers.getRelativePosition(e, myChart);
                        
                   jQuery(datapoints).each(function(i, elt){
                   	   let j = i+1;
                   	  
                    	if(elt.x >= canvasPosition.x - 10 && elt.x <= canvasPosition.x + 10 && elt.y >= canvasPosition.y - 10 && elt.y <= canvasPosition.y + 10) {		            		
                    		jQuery('#pointInfo' + j).css( {position:"absolute", top: canvasPosition.y - 50, left: canvasPosition.x - 50});		            		
                    		jQuery('#pointInfo' + j).show();
                    	}
                    });
        
                },			
            } // end options
        }); // end chart		
       
        // on resize we hide all boxes to avoid messy view
       jQuery( window ).resize(function() {
         jQuery('.pointinfo-container').hide();
        }); // end resize		
        
    }); // end document ready

Most of the standard Chart.js code is pretty clear. You need to focus only on the onHover function. Let’s repeat it here with lots of comments:

onHover: (e) => {	
                    	 // this gets the meta data of the chart to figure out the coordinates of each data point
                      // This part is very important and specific to Chart.js version 3. In version 2 the syntax will not work.		
                      var meta = myChart.getDatasetMeta(0);
                      datapoints = [					  	 	 
                      	{'x' : Math.round(meta.data[0].x), 'y': Math.round(meta.data[0].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[1].x), 'y': Math.round(meta.data[1].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[2].x), 'y': Math.round(meta.data[2].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[3].x), 'y': Math.round(meta.data[3].y)},
                      	 	  	 
                      	 {'x' : Math.round(meta.data[4].x), 'y': Math.round(meta.data[4].y)},
                      ]; 
                        
                        
                       if(typeof(datapoints) === 'undefined') return false;

                           // Once we know the datapoints position, we also need to get the x/y of the canvas
                    const canvasPosition = Chart.helpers.getRelativePosition(e, myChart);
                        
                   jQuery(datapoints).each(function(i, elt){
                   	   let j = i+1;
                                  // Remember, we are hovering the mouse. Don't expect the user to be exact and give some allowance which will display the info when the user is close to any
                        // of the data points. Here we give allowance of 10 pixels around each point.
                    	if(elt.x >= canvasPosition.x - 10 && elt.x <= canvasPosition.x + 10 && elt.y >= canvasPosition.y - 10 && elt.y <= canvasPosition.y + 10) {
		            	// and the stuff here is rather straightforward: set the element position around the datapoint position	
                    		jQuery('#pointInfo' + j).css( {position:"absolute", top: canvasPosition.y - 50, left: canvasPosition.x - 50});	
                                // then show	            		
                    		jQuery('#pointInfo' + j).show();
                    	}
                    });
        
                },

The most important part above is getting the data points coordinates. You need to do this inside the onHover function. In Chart.js version 2 you could do it in a document.ready handler, but this no longer works correctly.

The data points information is retrieved through the getDatasetMeta() method of the library. The argument is the dataset number, staring at 0. (Our chart has only one dataset).

Each data point is in the resulting object property meta.data. It is an array of datapoint objects and you need the properties x and y of each of them.

Finally, you need a function to close the pop-up when the user clicks on the close()

function closePointInfo(cnt) {
        jQuery('#pointInfo' + cnt).hide();
    
        // if all point infos are hidden, make sure the show all mode is show
        let anyOpen = false;
        jQuery('.pointinfo-container').each(function(i, elt){
            if(jQuery(elt).is(":visible")) {
                anyOpen = true;
                return;
            }
        });
        
    }

That’s it. If you have used this somewhere, let us know in the comments!