Easy Guide to Show User Registration Date in WordPress

In this tutorial, we will learn how to show user registration date in WordPress.

Where and How You Want to Show User Registration Date?

Some of you may just want to display a user’s registration date in the admin columns of the Users page. This will give you a quick overview of when a user joined your website and allow you to sort by registration date.

Another usage scenario is to display a user’s registration date on the ‘Edit Profile’ page. This will allow any administrator and the user themselves to see when they joined your website.

Last but probably the most popular usage scenario is when you want to display the user registration date on their public profile on the front-end of your website.

Let’s take a look at how you can do all of them.

Adding Registered Date Column on Users Page in Admin Area

First thing you need to do is install and activate the Admin Columns plugin. Upon activation, you need to visit Settings » Admin Columns to configure the plugin.

 Settings » Admin Columns to configure

Under the admin columns tab, click on users and then click on add column button.

Next select ‘Registered” in the Type drop down menu and click on store updates button.

You can now visit the users screen where you will see a new column labeled ‘Registered’ showing the date when a user registered on your WordPress site.

Users table with registration date column

See what other things you can do to add and customize admin columns in WordPress.

Showing Registration Date Field in User Profile

For showing registration date on the edit profile page, you will need to upload a custom plugin to your website.

Simply create a new file on your computer using a text editor like Notepad and save it as membersince.php on your desktop.

Next open the file and paste the following code inside it.

<?php
/*
Plugin Name: Member Since
Plugin URI:  http://www.wpbeginner.com
Description: Adds registration date on edit user profile screen. 
Version:     1.0
Author:      WPBeginner
*/
 
 
namespace ShowMemberSince;
add_action( 'plugins_loaded', 'ShowMemberSince\init' );
/**
 * Adding needed action hooks
*/
function init(){
  foreach( array( 'show_user_profile', 'edit_user_profile' ) as $hook )
        add_action( $hook, 'ShowMemberSince\add_custom_user_profile_fields', 10, 1 );
}
/**
 * Output table
 * @param object $user User object
 */
function add_custom_user_profile_fields( $user ){
    $table =
    '

 

Save your file and then upload it to your WordPress site.

Finally you can connect to your WordPress site using a FTP client and then go to /wp-content/plugins/ folder. Select the membersince.php file from your computer and then upload it.

Now you can go to your WordPress plugins page and activate this plugin on your website.

That’s all. Verify everything is working by editing a user profile on in your WordPress admin area, and you will see the user registration date.

Showing member registration date in WordPress user profile

Showing User Registration Date on Your Website

In this method, we will be using a simple shortcode to display any users registration date on the front-end of your WordPress site.

First you will need to add the following code in your theme’s functions.php file or in a site-specific plugin.

function wpb_user_registration_date($atts, $content = null ) { 
 
$userlogin = shortcode_atts( array(
'user' => FALSE,
), $atts );
 
$uname = $userlogin['user'];     
 
if ($uname!== FALSE) {             
 
$user = get_user_by( 'login', $uname );  
if ($user == false) { 
 
$message ='Sorry no such user found.'; 
 
 
} else { 
 
$udata = get_userdata( $user-ID );
$registered = $udata->user_registered;
 
$message =  'Member since: ' . date( "d F Y", strtotime( $registered ) );
 
}
     
} else { 
 
$message = 'Please provide a username.'; 
 
} 
 
return $message; 
 
} 
 
add_shortcode('membersince', 'wpb_user_registration_date');

Next, you can display a user’s registration date by simply using the shortcodelike this:

[membersince user=peter]

Replace peter with the username that you want to show.

We hope this tutorial helped you show registration date in WordPress user profiles.

Easy Guide to Restore a WordPress Site with DB Backup

In this tutorial, we will learn how to restore a WordPress site with just a database backup. It will not be a complete restore, but we will show you how you can minimize the damage.

Introduction

For the sake of this tutorial, we are assuming that you have your WordPress database backup in a zip file. If you do not have one yet, here is how to make a WordPress database backup manually.

If you are recovering from a bad experience with your web hosting provider, then it is probably the time to find a better host. We have hand picked some of the best WordPress hosting providers. These are the companies that we have worked with and trust with our own projects.

Preparing to Restore WordPress Database Backup

First, you will need to create a new database. Simply login to your cPanel account and click on MySQL Databases under the Database section.

MySQL databases in cPanel

Next, provide a name for your database and then click on create database button.

Creating new MySQL database

Now that you have created a database, you need a MySQL user who will be assigned all privileges to work on your newly created database.

On the same MySQL databases page, scroll down to MySQL users section and add a new user.

Adding a new MySQL user

Provide a username and a strong password for your database user and then click on create user button.

Next, you need to add this user to the MySQL database. Scroll down to ‘Add user to database’ section and select the user along with the database from the drop down menus and then click on the add button.

Adding a user to database

Your new database is now ready for WordPress.

Importing WordPress Database Backup

First you need to visit the cPanel dashbaord. Under the databases section, you need to click on phpMyAdmin.

Launching phpMyAdmin from cPanel

On then next step, select the database you created earlier on the phpMyAdmin page and then click on the Import button.

Now you need to click on the choose file button to upload your WordPress database backup file. Simply click on the go button at the bottom of the page to start importing.

Importdb

You will see a success message when the import job is finished.

You have successfully imported your WordPress database. Now the next step is to install WordPress using your new database.

Restoring Your WordPress Site

For a manual restore of WordPress, you will need to manually install WordPress on your server. Visit our step by step WordPress installation tutorialand jump to the section ‘how to install WordPress using FTP’ for detailed instructions.

During the installation, when you reach ‘create a configuration file’ step. Enter the database name and user you created earlier.

Creating configuration file step during WordPress installation

You will now see a message that WordPress can connect to your database, and you can run the installation now.

Clicking on the install button will now show you the ‘Already Installed’ message.

Already installed message

That’s all you can now proceed to login to your WordPress site.

Restoration Troubleshooting

Since you do not have your old WordPress files, there will be several things missing. Some of them can be easily restored while others will be a bit difficult. We will go through all of them one by one.

1. Theme

Simply install a fresh copy of your old WordPress theme. If you made direct changes to your theme files, then all those changes will be gone.

You will have to go through theme options to set it up the way it was before.

2. Widgets

Widgets play an important role in WordPress themes. Luckily, they are stored in your WordPress database and switching to your old theme will restore some of your widgets.

You can always go to Appearance » Widgets to add and rearrange widgets in your sidebars.

Some WordPress plugins come with their own widgets. In order to use those widgets, you will first need to install and activate those plugins.

3. Permalinks

Your site’s permalink structure is also stored in database, and it will be automatically restored. However, if you are seeing 404 errors on front-end of your site, then you need to refresh permalink settings.

Simply go to Settings » Permalinks and click on the save changes button without changing anything. This will refresh your WordPress url structure.

4. Plugins

WordPress stores a record of your site’s active plugins. When you visit the plugins page for the first time, WordPress will show you a list of errors for each plugin that was in the database but is not installed anymore.

Deactivated plugins

Copy all the plugin names and start installing and activating them one by one.

Recovering Lost Images for your WordPress Site

Finding and replacing lost images on your website would be the trickiest part of the recovery. Depending on how much content and images you have, this can take a long time.

Unfortunately, there is no easy way around it. You will have to use a variety of tools to extract your images from different sources. Your chances of recovering all images are fairly low.

1. Look in Your Browser Caches

If you have recently lost your website, then you can look into your browser cache.

Firefox users can download CacheViewer2 add-on to easily find images from their website stored in browser cache.

Finding cached images in Firefox

You can just right click on an image and select save as from the menu.

Google Chrome users on Windows can try Chrome Cache Viewer.

Google Chrome users on Mac will be out of luck. We were unable to find any reasonable solution to browse, preview, and save image from Google Chrome cache on Mac.

2. Look for Your Images in Web Caches

There are several web services that keep cached versions of websites. You can start by looking for your images in Google’s image search. Simply enter your site’s URL and you will be able to see images Google found on your website.

If you are restoring a much older site and can’t find images on Google or Bing, then you can try Archive.org. It is a non-profit organization that stores snapshots of websites for historical purposes.

Internet Archive Way Back Machine

Finding and Replacing Images on Your Website

If you did not have much content on your old site, then you can manually replace images in your posts. However, if you have a lot of content then finding and replacing images manually will be difficult.

Here is how you can easily locate broken images and replace them.

First, you need to install and activate the Broken Link Checker plugin. Upon activation, simply go to Tools » Broken Links Checker page. The plugin will show you a list of all broken links on your site.

Find and replace missing images in WordPress

Broken images are also considered broken links, so they will appear in the list as well. You can click on the link text column to sort the broken links list to show images first.

Now you can replace the images that you have recovered by editing posts. For the images that you were not able to recover, you can either try to recreate them or simply unlink them.

Bonus Tip

It will be hard to recover all your lost data. Your site may even show errors and affect user experience. This is why you see many experts strongly urging you to set up automatic backups.

We recommend using BackupBuddy. It is a premium WordPress backup plugin with easy restore options and the ability to automatically create and save your backups on the cloud.

That’s all, we hope this tutorial helped you restore your WordPress site from database backup.

Easy Guide to Display Code on Your WordPress Site

In this tutorial, we will learn how to easily display code on your WordPress site.

First you need to install and activate the Syntax Highlighter Evolved plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Settings » Syntax Highlighter to configure the plugin settings.

Syntax Highlighter settings page

The default plugin settings should work for most websites. However, you should review all settings and make changes if necessary.

Each option has detailed description to explain what it does. Once you are done, simply click on the save changes button to store your settings.

Syntax Highlighter Evolved uses simple shortcodes to display code. For each programming language you need wrap your code in the shortcode for that language.

For PHP you would wrap your code like this:

<?php
echo “Hello World”;
?>

It will appear in your post like this:

For CSS you will wrap your code like this:

.entry-title {
font-family:”Open Sans”, arial, sans-serif;
font-size:16px;
color:#272727;
}

It will appear on your site like this:

.entry-title { 
font-family:"Open Sans", arial, sans-serif;
font-size:16px;
color:#272727; 
}

Syntax Highlighter will automatically highlight the code for that particular language. It will also add line numbers and handle tab indent properly. Your users will be able to easily copy and paste code snippets from your WordPress site.

How to Display Code in WordPress Without Using Plugin

Many bloggers do not run a development blog, so they don’t need to add sample code snippets in their posts very often. For rare occasions, you can add code by encoding the code into HTML entities. Like this:

&gt;?php echo "Hello World"; ?&lt;

The problem with converting code into HTML entities is that it is difficult to do manually. You can use online tools like this one, to convert code into HTML entities.

By converting PHP, HTML, JavaScript code into HTML entities, you can paste them into your WordPress posts. For additional styling you can wrap code between <code> and </code> tags.

We hope this tutorial helped you find the best syntax highlighter plugin for WordPress.

Easy Guide to Disable Auto Linking of URLs in WordPress Comments

In this tutorial, we will learn how to disable auto-linking of URLs in WordPress comments.

Why WordPress Autolinks Text URLs in Comments?

WordPress automatically converts text URLs into links which makes it easier to visit the link while moderating comments.

This auto-linking is not stored in your database. WordPress makes URLs clickable when displaying them on screen in admin area as well as comments section below your articles.

Auto-linked clickable text URL in WordPress comments

Some of these comments are genuine where commenters didn’t know how to add a link in comments. But many spam comments also contain plain URLs pasted directly in the comment text.

Disabling Auto-Link in WordPress Comments

Simply add this single line of code in your theme’s functions.php file or in a site-specific plugin.

 remove_filter( 'comment_text', 'make_clickable', 9 );

WordPress does not store plain text URLs as links in the database. Instead it changes them into clickable links on the fly. This code simply disables the filter that makes URLs clickable.

This makes plain text URLs non-clickable in admin area and comments section below your posts. Removing this code will re-enable the auto linking.

If you are adding it to your theme’s functions.php file, then updating your theme will overwrite your functions file.

Also keep in mind that this code only works on plain text URLs. If a user decided to create a link by adding the proper HTML tag, then those links will appear as they should.

If you want to complete turn off any HTML in comments, then take a look at our tutorial on how to disable HTML in WordPress comments.

We hope this tutorial helped you disable auto linking of URLs in WordPress comments.

Easy Guide to Add Google Analytics Event Tracking in WordPress

In this tutorial, we will learn how to add Google Analytics event tracking in WordPress.

What is Event Tracking in Google Analytics

Event tracking allows you to measure user interactions on your website. These interactions can be things like clicking on a button, playing a video, downloading files, submitting forms, etc.

Let’s suppose you added a video to your product page, and now want to know how effective is it for your conversions. Event tracking allows you to track how many users played the video, so you can judge for yourself.

Another example is ajax based form submissions. If you are using Gravity Forms or any other contact form plugin, then form submission does not result into a new pageview.

Using event tracking you can see how users interacted with a form.

The same goes for file downloads included on a page. You can track how many users downloaded a file using event tracking and even which button on the page was clicked most.

Event tracking is different from tracking links in Google analytics. You can track links in WordPress using Google Analytics by simply adding UTM source to a link.

These measurable actions allow you to see how users behave on your site. You can then change your strategy to add content that generate more user engagement and interaction. Ultimately this means more sales and conversions on your website.

Getting Started

Before getting started, you will need to setup and install Google Analytics on your WordPress site. If you are not familiar with using Google Analytics, then you can try our beginner’s guide on how to use Google Analytics.

If you are already using Google Analytics, then you can jump right into event tracking.

Upgrade to Universal Analytics Code

There are currently two type of Google Analytics implemented on websites. Google is slowly pushing out the older code by asking webmasters to use newer ‘Universal Analytics Code’.

If your Google Analytics code looks like this:

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
  ga('create', 'UA-XXXXXX-1', 'auto');
  ga('send', 'pageview');
 

Then you are already using the newer Universal Analytics code. There is no action required, and you can move on to the next step.

If your code does not look like this, then you are probably using the older Google Analytics code. You will need to upgrade, Google has a detailed upgrade guide for that. Basically if you are not using advanced tracking features in Google Analytics, then you can just switch the old code with the new one from your account’s property settings.

Creating Your Event in Google Analytics

First you need to create your event in your Google Analytics account. Simply log into your Analytics dashboard and click on the Admin link at the top. If you have multiple websites under your analytics account, then make sure that you are viewing the dashboard for the site where you want to add the event.

Google Analytics dashboard

There are three columns under the admin page. Click on the ‘Goals’ link under the ‘View’ column.

Creating Goals in Google Analytics

Next, click on the new goal button to create a goal. From the Goal Setup options, you need to select the custom option and then click on the next button to continue.

Creating custom goal in Google Analytics

This will bring you to the Goal Description step. You need to provide a title for your custom goal, this is something that will help you identify the goal inside Google Analytics.

Under the goal type, you need to select Event. After that click on the next step button to continue.

Entering custom goal title and selecting event as the goal type

The last step is to provide goal details. You will need to enter the event conditions here.

Analytics will count a conversion when all these conditions match.

In this example, we have provided a category and action for the event. We entered a label for the event and provided a value. Depending on what kind of event you are trying to create, you can name your own category, actions, and labels.

If you feel that your event should pass on a value that can be calculated, then you can enter that value here. However, for most common event tracking using the value to be 0 works fine too.

Entering event conditions for custom goal in Google Analytics

Finally click on the create goal button to save and activate the goal. You have successfully enabled tracking for an event in Google Analytics. The next step is to track this event on your website and send data to Google Analytics.

Adding Google Analytics Event Tracking onClick

The easiest and perhaps the fastest way to add Google Analytics event tracking is by using the onclick method. This method simply sends event conditions to Google Analytics when user clicks on an element.

In this example, we are tracking users who click on eBook download link.

We will add the onClick parameter to the download link using this format.

onClick="ga('send', 'event', 'category', 'action', 'label', 'value');"

You will need to replace category, action, label, and value with your event’s conditions. Finally your download link would look like this.

Download Free Ebook

That’s all, when users click on this link, it will send an event to Google Analytics which will appear in your site’s reporting.

Adding Event Tracking Using Google Tag Manager

Google Tag Manager is an online tool which allows you to add different tracking codes as tags under one dashboard.

You can also use it to create tags to track events in your Google Analytics account. The main benefit of using Google Tag Manager is that you wouldn’t have to manually insert code into your website, and you can manage all your tags from one location.

If you have already added Google analytics tracking code to your site manually, then you will need to remove it. Use our tutorial on how to install and setup Google Tag Manager in WordPress to add Analytics code to your website.

Once you have successfully added Google Analytics tag in the tag manager, the next step is to create a new trigger. For the sake of this tutorial, we will be tracking a contact form submission as an event.

Click on Triggers in tag manager and then click on the New button.

Triggers in Google Tag Manager

This will bring you to the trigger creation wizard. This is where you would choose event select form.

Choose form as your event

Under the configure trigger section, you need to uncheck wait for tags and check validation options. Next, click on the continue button to go to the next step.

Configure trigger options

In the next step, you need to choose when to fire the trigger. If your page has only one form on it, then you can choose all forms. If your page has more than one form, then you click on some forms button.

When to fire the trigger

If your page has more than one form and you want to track a specific form, then you need to tell Google Tag Manager which form you want to track. When you click on some form buttons you will see filters.

Creating a fire on filter

A filter is simply a set of instructions like if A matches B, then fire the trigger. You need to select new variable.

Selecting new variable will bring up a popup where you can create your own variable. Select DOM element as your variable type. Next, under configure variable choose ID as your selection method.

Now you will need to find your form’s ID. Visit the form page on your WordPress site, take the mouse over to the first form field and select inspect element.

Your browser screen will split into two. You will see the HTML for your page in the bottom screen. The id attribute will either be part of your <form> tag or the div containing the form.

Finding the form element ID

Copy and paste the form ID under the element ID and attribute. Next, click on the create variable button.

You will come back to Fire on filter where you can now select your custom variable. In the matching rule select ‘contains’ and then enter your form’s ID again.

Now click on the create trigger button to continue.

The next step is to create a tag for the event we want to track. In the Google Tag Manager, click on Tags and then click on the New button.

This will bring you to tag creation wizard. Select Google Analytics as your product and then click on the continue button.

Creating an event tracking tag in Google Tag Manager

Now you need to choose Universal Analytics as your tag type. You will be asked to provide your Google Analytics tracking ID. You can obtain this from your Google Analytics account.

Under the track type you need to select event and then provide category, action, label, and value information. In this example we used Forms for category, form submission for action, contact form as label, and submitted as the value.

Click on the continue button to proceed to next step. This is where you select when to fire the tag. Click on the more button and select the trigger you created earlier.

Select your trigger

Finally you can click on the create tag button to save your tag.

Remember that saving a tag does not make it go live on your website. You will still need to click on the publish button to make it live.

Publish your container

That’s all, you can now go to your website and submit the form. Go to Real Time » Events in your Analytics account and you will see your event tracked and recorded.

Event tracked in Google Analytics

Using the tag manager you can create different kind of events and manage them all from Google Tag Manager. It also saves you from editing your WordPress themes or adding tracking code manually.

We hope this tutorial helped you add Google Analytics event tracking in your WordPress site.

Easy Guide to Add a Shortcodes User Interface in WordPress

In this tutorial, we will show you how to add a user interface for shortcodes in WordPress with Shortcake.

What is Shortcake?

WordPress offers an easier way to add executeable code inside posts and pages by using shortcodes. Many WordPress themes and plugins allow users to add additional functionality using shortcodes. However, sometimes these shortcodes can become complicated when a user needs to enter parameters for customization.

For example, in a typical WordPress theme if there is a shortcode to enter a button, then the user will probably need to add atleast two to five parameters. Like this:

[themebutton url=”http://example.com” title=”Download Now” color=”purple” target=”newwindow”]

Shortcake is a WordPress plugin and a proposed future WordPress feature. It aims to solve this problem by providing a user interface to enter these values. This will make shortcodes a lot easier to use.

Shortcake Bakery Plugin

Getting Started

This tutorial is aimed for users who are new to WordPress development. Beginner level users who like to tweak their WordPress themes would also find this tutorial helpful.

Having said that, let’s get started.

First thing you need to do is install and activate the Shortcake (Shortcode UI)plugin.

You will now need a shortcode that accepts a few parameters of user input. If you need a little refresher, here is how to add a shortcode in WordPress.

For the sake of this tutorial we will be using a simple shortcode that allows users to insert a button into their WordPress posts or pages. Here is the sample code for our shortcode, and you can use this by adding it to your theme’s functions file or in a site-specific plugin.

add_shortcode( 'cta-button', 'cta_button_shortcode' );
 
function cta_button_shortcode( $atts ) {
       extract( shortcode_atts(
               array(
                       'title' => 'Title',
                       'url' => ''
               ),
               $atts
       ));
       return '' . $title . '';
}

You will also need to add some CSS to style your button. You can use this CSS in your theme’s stylesheet.

.cta-button {
padding: 10px;
font-size: 18px;
border: 1px solid #FFF;
border-radius: 7px;
color: #FFF;
background-color: #50A7EC;
}

This is how a user will use the shortcode in their posts and pages:

[cta-button title="Download Now" url="http://example.com"]

Now that we have a shortcode that accepts parameters, let’s create a UI for it.

Registering Your Shortcode User Interface with Shortcake

Shortcake API allows you to register your shortcode’s user interface. You will need to describe what attributes your shortcode accepts, input field types, and which post types will show the shortcode UI.

Here is a sample code snippet we will use to register our shortcode’s UI. We have tried to explain each step with inline comments. You can paste this in your theme’s functions file or in a site-specific plugin.

shortcode_ui_register_for_shortcode(
 
/** Your shortcode handle */
'cta-button',
 
/** Your Shortcode label and icon */
array(
 
/** Label for your shortcode user interface. This part is required. */
'label' => 'Add Button',
 
/** Icon or an image attachment for shortcode. Optional. src or dashicons-$icon.  */
'listItemImage' => 'dashicons-lightbulb',
 
/** Shortcode Attributes */
'attrs'          => array(
 
/**
* Each attribute that accepts user input will have its own array defined like this
* Our shortcode accepts two parameters or attributes, title and URL
* Lets first define the UI for title field. 
*/
 
array(
 
/** This label will appear in user interface */
'label'        => 'Title',
 
/** This is the actual attr used in the code used for shortcode */
'attr'         => 'title',
 
/** Define input type. Supported types are text, checkbox, textarea, radio, select, email, url, number, and date. */
'type'         => 'text',
 
/** Add a helpful description for users
'description'  => 'Please enter the button text',
),
 
/** Now we will define UI for the URL field */
 
array(
'label'        => 'URL',
'attr'         => 'url',
'type'         => 'text',
'description'  => 'Full URL',
),
),
),
 
/** You can select which post types will show shortcode UI */
'post_type'     => array( 'post', 'page' ), 
)
);

That’s all, you can now see the shortcode user interface in action by editing a post. Simply click on the Add Media button above a post editor. This will bring up the media uploader where you will notice a new item ‘Insert Post Element’ in the left hand column. Clicking on it will show you a button to insert your code.

Inserting your shortcode in a post or page

Clicking on the thumbnail containing the lightbulb icon and your shortcake label will show you the shortcode UI.

User interface for a simple shortcode

Adding Shortcode With Multiple Inputs

In the first example, we used a very basic shortcode. Now lets make it a little more complicated and a lot more useful. Let’s add a shortcode that allows users to choose a button color.

First we will add the shortcode. It is nearly the same shortcode, except that it now excepts user input for color.

add_shortcode( 'mybutton', 'my_button_shortcode' );
 
function my_button_shortcode( $atts ) {
       extract( shortcode_atts(
               array(
                       'color' => 'blue',
                       'title' => 'Title',
                       'url' => ''
               ),
               $atts
       ));
       return '' . $title . '';
}

Since our shortcode will be showing buttons in different colors so we will need to update our CSS too. You can use this CSS in your theme’s stylesheet.

.mybutton {
    padding: 10px;
    font-size: 18px;
    border: 1px solid #FFF;
    border-radius: 7px;
    color: #FFF;
}
 
.blue-button  {
    background-color: #50A7EC;
}
.orange-button { 
background-color:#FF7B00;
} 
 
.green-button { 
background-color:#29B577;
}

This is how the buttons will look like:

Call to action buttons created with shortcode

Now that our shortcode is ready, the next step is to register shortcode UI. We will be using essentially the same code, except that this time we have another parameter for color and we are offering users to select from blue, orange, or green buttons.

shortcode_ui_register_for_shortcode(
 
/** Your shortcode handle */
'mybutton',
 
/** Your Shortcode label and icon */
array(
 
/** Label for your shortcode user interface. This part is required. */
'label' => 'Add a colorful button',
 
/** Icon or an image attachment for shortcode. Optional. src or dashicons-$icon.  */
'listItemImage' => 'dashicons-flag',
 
/** Shortcode Attributes */
'attrs'          => array(
 
/**
* Each attribute that accepts user input will have its own array defined like this
* Our shortcode accepts two parameters or attributes, title and URL
* Lets first define the UI for title field. 
*/
 
array(
 
/** This label will appear in user interface */
'label'        => 'Title',
 
/** This is the actual attr used in the code used for shortcode */
'attr'         => 'title',
 
/** Define input type. Supported types are text, checkbox, textarea, radio, select, email, url, number, and date. */
'type'         => 'text',
 
/** Add a helpful description for users */
'description'  => 'Please enter the button text',
),
 
/** Now we will define UI for the URL field */
 
array(
'label'        => 'URL',
'attr'         => 'url',
'type'         => 'text',
'description'  => 'Full URL',
),
 
/** Finally we will define the UI for Color Selection */
array(
'label'     => 'Color',
'attr'      => 'color',
 
/** We will use select field instead of text */
'type'      => 'select',
    'options' => array(
        'blue'      => 'Blue',
        'orange'    => 'Orange',
        'green'     => 'Green',
    ),
),
 
),
 
/** You can select which post types will show shortcode UI */
'post_type'     => array( 'post', 'page' ), 
)
);

That’s all, you can now edit a post or page and click on the Add Media button. You will notice your newly added shortcode under ‘Insert Post Elements’.

Selecting post element or shortcode to insert

Clicking on your newly created shortcode will bring up the shortcode UI, where you can simply enter the values.

Shortcode UI with a select field

You can download the code used in this tutorial as a plugin.

wpb-shortcake-tutorial

We have included the CSS, so you can use it to study or use it to add your own call to action buttons in WordPress using an easier user interface. Feel free to modify the source and play with it.

We hope this tutorial helped you learn how to add a user interface for shortcodes in WordPress with Shortcake.

Easy Guide to Display Random Posts in WordPress

In this tutorial, we will learn how to easily display random posts in WordPress.

Why and Where to Display Random Posts in WordPress

By default WordPress lists your blog posts in reverse chronological order (from newest to oldest). This allows users to see your latest posts first.

However, most users will not get to see your older articles. If you have been running your site for quite some time now, then your older articles will not be prominently displayed anywhere.

One way to overcome this is by making internal linking a habit. Linking to your older articles in new posts will help users discover them. It will also increase your pageviews and improve your SEO score.

Another way around that is by displaying random posts in your sidebar. This way your users will get to discover posts that they would not see otherwise.

Having said that, let’s see how you can easily display random posts in WordPress.

Method 1: Display Random Posts in WordPress with a Plugin

This method is easier and is recommended for most users.

First thing you need to do is install and activate the Advanced Random Posts Widget plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Appearance » Widgets page. You will notice a new widget labeled ‘Random Posts’ under the list of available widget.

You need to add this widget to a sidebar. See our guide on how to add and use widgets in WordPress.

Now, you will be able to see the widget settings. The default options will work for most websites, you can just click on the save button.

Advanced Random Posts Widget is a powerful plugin with tons of customization options. You can select different post types, show excerpt, show thumbnail, and skip posts you don’t want to show, or displays posts from specific categories or tags.

For more experienced users, the plugin also allows you to add custom before and after HTML, and your own custom CSS as well.

Don’t forget to click on the save button to store your widget settings. You can now visit your website to see random posts widget in action.

Method 2: Display Random Posts in WordPress Using Code

This method requires you to add code to your WordPress theme files. See our guide on how to copy paste code in WordPress.

First thing you need to do is add this code in your theme’s functions.php file or a site-specific plugin.

function wpb_rand_posts() { 
 
$args = array(
    'post_type' => 'post',
    'orderby'   => 'rand',
    'posts_per_page' => 5, 
    );
 
$the_query = new WP_Query( $args );
 
if ( $the_query->have_posts() ) {
 
$string .= ''; 
while ( $the_query->have_posts() ) { $the_query->the_post(); $string .= '
 	'. get_the_title() .'

'; } $string .= ' '; 
/* Restore original Post Data */ 
wp_reset_postdata(); } 
else { $string .= 'no posts found'; } return $string; } 
add_shortcode('wpb-random-posts','wpb_rand_posts'); add_filter('widget_text', 'do_shortcode');

This code simply creates a function that displays 5 random posts. It then creates a shortcode so that you can easily display random posts anywhere on your site. Lastly, it enables shortcodes to be executed inside WordPress widgets so that you can use shortcode inside a text widget.

Now you can display random posts inside a WordPress post, page, or text widget using the shortcode [wpb-random-posts].

That’s all, we hope this tutorial helped you learn how to display random posts in WordPress.