Owais Alam, Author at WPblog A Trusted Resource for WordPress Tips, Tutorials and News Fri, 24 Jul 2020 09:26:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.1 https://wpblog.com/wp-content/uploads/2017/05/favico.png Owais Alam, Author at WPblog 32 32 How to get WordPress post featured image URL & Post Thumbnail https://wpblog.com/get-wordpress-post-featured-image-url/ https://wpblog.com/get-wordpress-post-featured-image-url/#respond Wed, 20 Nov 2019 15:00:23 +0000 https://wpblog.com/?p=30917 In many cases, developers need the direct URL of a featured image. This is because the featured image of a post, also known as a post thumbnail, is used in individual posts, pages, and custom posts and plays a vital role in WordPress. It’s just...

The post How to get WordPress post featured image URL & Post Thumbnail appeared first on WPblog.

]]>
In many cases, developers need the direct URL of a featured image. This is because the featured image of a post, also known as a post thumbnail, is used in individual posts, pages, and custom posts and plays a vital role in WordPress. It’s just like other media files that help grab the attention of the visitors, but the featured image is the most important of them all. 

When your visitors land on your WordPress blog, the featured image acts as a visual cue to what the article is about and makes the post more interesting. In fact, when you share the blog on social media, it acts as a banner as well.

Let’s find out how to get WordPress post featured image URL and post thumbnail.

How to Get WordPress Post Featured Image URL

You can display the featured images in your custom theme by adding the following code in templete.php:

<?php the_post_thumbnail(); ?>  

In many cases, though, developers need the direct URL of a featured image and want to use and display it in different ways. For example, when the featured image is used in a header, in an archive page, in a recent post page, or as the post background image, etc. 

In these cases, the requirement is more than just displaying the featured image in the post. You can use the featured image URL to fulfill any requirements related to the above scenarios. 

Also Read: How to Add WordPress Favicon to Your WordPress Website

First, I defined a wpblog-featured-image class in the CSS file in order to style the featured image. You can choose your own styling formats for this class but I would suggest that you use the following CSS style because it’s one of the most recommended styles by experts:

. wpblog-featured-image {
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
}

For the post ID (for $post->ID), you can check the URL of your post. As shown in the image below, my post ID is 12.

Get Featured Image URL and Post Thumbnail

Get Featured Image URL

To get featured image URL, place the following code in the file single.php, post.php and template.php:

Also Read: How to Change PHP Version in Xampp

<?php
$wpblog_fetrdimg = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); 
?>
<div class="wpblog-featured-image"
    <?php if( $wpblog_fetrdimg ) : ?>
 	style="wpblog-featured-background-image: url(<?php echo $wpblog_fetrdimg; ?>);"
    <?php endif; ?>
        >
  </div>

The get_post_thumbnail_id is used to retrieve the post thumbnail ID.

The wp_get_attachment_url returns a full URI for an attachment file or false on failure.

Get Single Post Thumbnail

In many cases, the post thumbnail is the feature of the theme and not part of the core WordPress capabilities. To enable support for the featured image on post and pages, use the following snippet:

<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" class="wpblog-featured-image" style="background-image: url('<?php echo $image[0]; ?>')">

</div>
<?php endif; ?>

The wp_get_attachment_image_src returns the value of the image attribute that contains different values: URL, width, height, and size of the image.

While you are at it, don’t forget to optimize your images using these best WordPress image compression plugins.

Conclusion

So there you have it. I hope you’ve now learned how to get WordPress post featured image URL and post thumbnail. Do let me know in the comments below if you found the tutorial useful and if you’d like me to cover some other topics related to coding.

Also Read: Simple Methods To Optimize Images On WordPress Websites

The post How to get WordPress post featured image URL & Post Thumbnail appeared first on WPblog.

]]>
https://wpblog.com/get-wordpress-post-featured-image-url/feed/ 0
How to Use WordPress do_shortcode https://wpblog.com/wordpress-do-shortcode/ https://wpblog.com/wordpress-do-shortcode/#respond Tue, 27 Aug 2019 12:34:15 +0000 https://wpblog.com/?p=37422 For many WordPress developers, shortcodes are a great way of extending the core functionalities of the WordPress core. In fact, all popular plugins now use shortcodes to integrate their features and options within posts and pages of the site. Table of Content Custom Message do_shortcode...

The post How to Use WordPress do_shortcode appeared first on WPblog.

]]>
For many WordPress developers, shortcodes are a great way of extending the core functionalities of the WordPress core. In fact, all popular plugins now use shortcodes to integrate their features and options within posts and pages of the site.

Now, what if you need to use shortcodes on the website other than the posts and pages. This opens up a host of possibilities for using shortcodes almost anywhere on the website.

In this short tutorial on WordPress do_shortcode(), I will highlight several ways in which you can leverage this great idea into your website.

Custom Message do_shortcode

A very simple use case of WordPress do_shortcode() is adding a custom message “A simple do shortcode demo” at the location of your choice. The following snippet inserts the message or keyword at the location where the shortcode is placed.

function wp_do_shortcode() {
return 'A simple do shortcode demo';
}
add_shortcode('do_shortcode', 'wp_do_shortcode');

In the above code snippet, wp_do_shortcode is the name of the custom function that integrates do_shortcode() functionality into your website. The return statement contains the actual message or keyword that needs to be inserted.

Finally, in the add_shortcode(), you can see that the actual shortcode to be inserted is “do_shortcode”.

As you can see in the following screenshots, when the shortcode, do_shortcode is used:

WordPress do_shortcode

You can see that the shortcode gets replaced by the message in the return statement.

Integration of do_shortcode

Adding Parameters to the do_shortcode Function

Now that you know the basic structure of a do_shortcode() and how to use it in your code, I will present another example that allows you to use the idea more effectively. In this example, I will demonstrate how to add the dimensions of an image to the page. For this, check out the following code:

function parameter_att_do_shortcode($atts) {
extract(shortcode_atts(array(
'width' => 100,
'height' => 150,
), $atts));
return '<img src="https://abc.com/'. $width . '/'. $height . '" />';
}

add_shortcode('do_shortcode ', 'parameter_att_do_shortcode');

As you can see, the function parameter_att_do_shortcode() takes the parameters in the $atts. In order to make use of the user-provided parameters, I have used shortcode_atts() that takes in user-provided attributes and fill in the gaps with default arguments.

Build a Custom do_shortcode Plugin

If you wish to create a plugin to add do_shortcode functionality to your website, the process is pretty straightforward.

The process of creating the plugin is simple. Just create a new folder in the wp-cont/Plugins. in the new folder, create a file named plugin-name-seokeyword.php. open the file and add the following code snippet to it.

<?php
/*
Plugin Name: seo suggested do shortcode Integration Plugin 
Description: add a description with seo suggest keyword This plugin extends the default do_shortcode functunality and makes shortcodes available across all widgetized areas
Version: 1.0
Author: Muhammad Owais Alam
*/
function wp_do_shortcode() {
return 'A simple do shortcode demo';
}
add_shortcode('do_shortcode', 'wp_do_shortcode');


function parameter_att_do_shortcode($atts) {
extract(shortcode_atts(array(
'width' => 100,
'height' => 150,
), $atts));
return '<img src="https://abc.com/'. $width . '/'. $height . '" />';
}

add_shortcode('do_shortcode ', 'parameter_att_do_shortcode');

do_shortcode Integration plugin

Template to Register the Shortcode

Before using the shortcode plugin, you need to register the shortcode. For this, you need to create a separate file with the following function wordpress_do_shortcode_form().

function wordpress_do_shortcode_form() {
ob_start();
get_template_part('template-name');
return ob_get_clean();
}
add_shortcode( 'wordpress_do_shortcode_form', 'wordpress_do_shortcode_form' );

Wrapping Up

Shortcodes are a popular way of adding functionalities to the WordPress core. With the above-mentioned solution, you can extend the usability and application of shortcodes to all areas of the WordPress website. If you need help in implementing the idea at your site, do let me know in the comments.

The post How to Use WordPress do_shortcode appeared first on WPblog.

]]>
https://wpblog.com/wordpress-do-shortcode/feed/ 0
How to Display Recent Posts Widget in WordPress https://wpblog.com/wordpress-recent-posts-widget/ https://wpblog.com/wordpress-recent-posts-widget/#respond Thu, 18 Jul 2019 17:34:22 +0000 https://wpblog.com/?p=37063 Showcasing your recently published content is one of the most simple ways of improving almost every website performance metrics. The good thing to know is that you can display your recently published content in high-traffic areas such as sidebars, after the posts and the footer....

The post How to Display Recent Posts Widget in WordPress appeared first on WPblog.

]]>
Showcasing your recently published content is one of the most simple ways of improving almost every website performance metrics.

The good thing to know is that you can display your recently published content in high-traffic areas such as sidebars, after the posts and the footer. This makes sure that you give maximum visibility to your content and get all the benefits of publishing content. In this article, I will show you how you can create a recent post plugin that simplifies the process of showcasing the recent posts on your website.

Register the Plugin

I will start by registering the plugin on the website. Once registered, the plugin will show up in the Plugins section of the website.

/*
Plugin Name: Recent Posts widget extended
Description: This plugin creates a widget for displaying recent posts on the front end.
Version: 1.X
Author: WordPress Recent Posts Widget

*/
class RecentPostsWithExcerpts extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'recent_with_excerpt', 'description' => __( 'Your most recent posts, with optional excerpts', 'recent_posts_with_excerpts') );
parent::__construct('RecentPostsWithExcerpts', __('Recent Posts with Excerpts', 'recent_posts_with_excerpts'), $widget_ops);
}

In the code snippet above, RecentPostsWithExprects() function registers the plugin. As a result, this is how the plugin entry would appear in the Plugin list:

WordPress list posts by category

The Code of the Widget

Here is the code snippet that carries out multiple actions. First, it creates the widget that would appear on the frontend. Next, the snippet retrieves the latest published blogs. Once this is done, the excerpts (both the built-in ones and the Advanced Excerpts) of the blogs are displayed through a loop (see the comment within the snippet). Once this is done, the function wp_reset_query() restores the $wp_query and the global post data of the original main query.

function widget( $args, $instance ) {
    	global $before_widget,$instance;
    	extract( $args );
    	$title = apply_filters('widget_title', $instance['title']);
    	echo $before_widget,$title;
    	$ul_classes = 'recent_posts_with_excerpts';
    	$ul_classes = apply_filters('recent_posts_with_excerpts_list_classes', $ul_classes);
    	if ( !empty( $ul_classes ) )
        	$ul_classes = ' class="'.$ul_classes.'"';
    	$li_classes = '';
    	$li_classes = apply_filters('recent_posts_with_excerpts_item_classes', $li_classes);
    	if ( !empty( $li_classes ) )
        	$li_classes = ' class="'.$li_classes.'"';
    	$h2_classes = 'recent_posts_with_excerpts';
    	$h2_classes = apply_filters('recent_posts_with_excerpts_heading_classes', $h2_classes);
    	if ( !empty( $h2_classes ) )
        	$h2_classes = ' class="'.$h2_classes.'"';
        do_action('recent_posts_with_excerpts_begin');
    	echo '<ul'.$ul_classes.'>';
    	// retrieve last n blog posts
    	$q = array('posts_per_page' => $instance['numposts']);
    	if (!empty($instance['tag']))
        	$q['tag'] = $instance['tag'];
    	$q = apply_filters('recent_posts_with_excerpts_query', $q, $instance);
    	$rpwe = new wp_query($q);
    	// the Loop
    	if ($rpwe->have_posts()) :
        	while ($rpwe->have_posts()) : $rpwe->the_post();
            	echo '<li'.$li_classes.'>';
            	echo '<h2'.$h2_classes.'><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
            	if (!empty($date))
                    echo '<h3 class="date">'.get_the_time($date).'</h3>';
            	{ // show the excerpt
                    ?>
                <blockquote> <?php
  	              // the excerpt of the post
                	if (function_exists('the_excerpt_reloaded'))
                        the_excerpt_reloaded($instance['words'], $instance['tags'], 'content', FALSE, '', '', '1', '');
                    else
                        the_excerpt();  // this covers Advanced Excerpt as well as the built-in one
                	if (!empty($instance['more_text'])) { ?><p class="alignright"><small><a href="<?php the_permalink(); ?>"><?php echo $instance['more_text']; } ?></a></small></p>
                </blockquote> <?php
                }?></li>
        	<?php endwhile; endif; ?>
	</ul>
	<?php
    	do_action('recent_posts_with_excerpts_end');
        wp_reset_query();
    }

The Form for the Widget Placement

The next snippet generates the form that the user will see when placing the widget on the front end. This snippet creates a simple form that the user can fill out to place the widget on the website.

function form( $instance ) {
	if (get_option('show_on_front') == 'page')
    	$link = get_permalink(get_option('page_for_posts'));
	else
    	$link = home_url();
	//Defaults
	$instance = wp_parse_args( (array) $instance, array(
    	'title' => __('Recent Posts', 'recent_posts_with_excerpts'),
    	'numposts' => 5,
    	'numexcerpts' => 5,
    	'date' => get_option('date_format'),
    	'more_text' => __('Read More', 'recent_posts_with_excerpts'),
    	'words' => '25',
    	'tag' => '',
	));
	?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('numposts'); ?>"><?php _e('Number of posts to show:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('numposts'); ?>" name="<?php echo $this->get_field_name('numposts'); ?>" type="text" value="<?php echo $instance['numposts']; ?>" /></p>
<p>
	<label for="<?php echo $this->get_field_id('more_text'); ?>"><?php _e('"More" link text:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('more_text'); ?>" name="<?php echo $this->get_field_name('more_text'); ?>" type="text" value="<?php echo $instance['more_text']; ?>" />
	<br </p>
<?php
	if (function_exists('the_excerpt_reloaded')) { ?>
	<p>
    	<label for="<?php echo $this->get_field_id('words'); ?>"><?php _e('Limit excerpt to how many words?', 'recent_posts_with_excerpts'); ?></label>
    	<input class="widefat" id="<?php echo $this->get_field_id('words'); ?>" name="<?php echo $this->get_field_name('words'); ?>" type="text" value="<?php echo $instance['words']; ?>" />
	</p>
	<p>
    	<label for="<?php echo $this->get_field_id('tags'); ?>"><?php _e('Allowed HTML tags:', 'recent_posts_with_excerpts'); ?></label>
    	<input class="widefat" id="<?php echo $this->get_field_id('tags'); ?>" name="<?php echo $this->get_field_name('tags'); ?>" type="text" value="<?php echo htmlspecialchars($instance['tags'], ENT_QUOTES); ?>" />
    	<br /><small><?php
 printf( __('E.g.: %s', 'recent_posts_with_excerpts'));
    	?>
    </small></p>
	<?php } ?>
<?php
}

Here’s how the widget’s form would look like in action:

WordPress recent posts widget

How to Set up and Use the Recent Post plugin

First, create folder having name “recent-post-widget-extended”. In this folder create file having name “recent-post-widget-extended.php”. Activate plugin than it shows in widget area as shown in fig.

WordPress recent posts widget activate plugin

To set up and get the plugin operational, create a folder named recent-post-widget-extended in the WordPress Plugin folder. In this folder, create a file and name it recent-post-widget-extended.php. Paste the code of the plugin in this file and save it.

Next, activate the plugin and you would be able to see it on the Plugin section of the WordPress Dashboard.

When you are ready, you can insert the widget in any location on the frontend of your WordPress websites

Once deployed, here is how the widget would look on the frontend:

recent posts widget extended

The Full Code of the Plugin

<?php
/*
Plugin Name: Recent Posts widget extended
Description: Insert description with the help of content writer.
Version: 1.X
Author: WordPress Recent Posts Widget

*/
class RecentPostsWithExcerpts extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'recent_with_excerpt', 'description' => __( 'Your most recent posts, with optional excerpts', 'recent_posts_with_excerpts') );
parent::__construct('RecentPostsWithExcerpts', __('Recent Posts with Excerpts', 'recent_posts_with_excerpts'), $widget_ops);
}
function widget( $args, $instance ) {
global $before_widget,$intance;
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget,$title;
$ul_classes = 'recent_posts_with_excerpts';
$ul_classes = apply_filters('recent_posts_with_excerpts_list_classes', $ul_classes);
if ( !empty( $ul_classes ) )
$ul_classes = ' class="'.$ul_classes.'"';
$li_classes = '';
$li_classes = apply_filters('recent_posts_with_excerpts_item_classes', $li_classes);
if ( !empty( $li_classes ) )
$li_classes = ' class="'.$li_classes.'"';
$h2_classes = 'recent_posts_with_excerpts';
$h2_classes = apply_filters('recent_posts_with_excerpts_heading_classes', $h2_classes);
if ( !empty( $h2_classes ) )
$h2_classes = ' class="'.$h2_classes.'"';
do_action('recent_posts_with_excerpts_begin');
echo '<ul'.$ul_classes.'>';
// retrieve last n blog posts
$q = array('posts_per_page' => $instance['numposts']);
if (!empty($instance['tag']))
$q['tag'] = $instance['tag'];
$q = apply_filters('recent_posts_with_excerpts_query', $q, $intance);
$rpwe = new wp_query($q);
// the Loop
if ($rpwe->have_posts()) :
while ($rpwe->have_posts()) : $rpwe->the_post();
echo '<li'.$li_classes.'>';
echo '<h2'.$h2_classes.'><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
if (!empty($date))
echo '<h3 class="date">'.get_the_time($date).'</h3>';
{ // show the excerpt
?>
<blockquote> <?php

if (function_exists('the_excerpt_reloaded'))
the_excerpt_reloaded($instance['words'], $instance['tags'], 'content', FALSE, '', '', '1', '');
else
the_excerpt();
if (!empty($instance['more_text'])) { ?><p class="alignright"><small><a href="<?php the_permalink(); ?>"><?php echo $instance['more_text']; } ?></a></small></p>
</blockquote> <?php
}?></li>
<?php endwhile; endif; ?>
</ul>
<?php
do_action('recent_posts_with_excerpts_end');

wp_reset_query();
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field($new_instance['title']);
$instance['numposts'] = intval($new_instance['numposts']);
$instance['more_text'] = sanitize_text_field($new_instance['more_text']);
$instance['date'] = sanitize_text_field($new_instance['date']);
$instance['words'] = intval($new_instance['words']);
$instance['tags'] = $new_instance['tags'];
$instance['tag'] = sanitize_text_field($new_instance['tag']);
return $instance;
}
function form( $instance ) {
if (get_option('show_on_front') == 'page')
$link = get_permalink(get_option('page_for_posts'));
else
$link = home_url();
//Defaults
$instance = wp_parse_args( (array) $instance, array(
'title' => __('Recent Posts', 'recent_posts_with_excerpts'),
'numposts' => 5,
'numexcerpts' => 5,
'date' => get_option('date_format'),
'more_text' => __('Read More', 'recent_posts_with_excerpts'),
'words' => '25',
'tag' => '',
));
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('numposts'); ?>"><?php _e('Number of posts to show:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('numposts'); ?>" name="<?php echo $this->get_field_name('numposts'); ?>" type="text" value="<?php echo $instance['numposts']; ?>" /></p>
<p>
<label for="<?php echo $this->get_field_id('more_text'); ?>"><?php _e('"More" link text:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('more_text'); ?>" name="<?php echo $this->get_field_name('more_text'); ?>" type="text" value="<?php echo $instance['more_text']; ?>" />
<br />
</p>
<?php
if (function_exists('the_excerpt_reloaded')) { ?>
<p>
<label for="<?php echo $this->get_field_id('words'); ?>"><?php _e('Limit excerpt to how many words?', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('words'); ?>" name="<?php echo $this->get_field_name('words'); ?>" type="text" value="<?php echo $instance['words']; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('tags'); ?>"><?php _e('Allowed HTML tags:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('tags'); ?>" name="<?php echo $this->get_field_name('tags'); ?>" type="text" value="<?php echo htmlspecialchars($instance['tags'], ENT_QUOTES); ?>" />
<br /><small><?php
printf( __('E.g.: %s', 'recent_posts_with_excerpts'));
?>
</small></p>
<?php } ?>
<?php
}
}
function recent_posts_with_excerpts_init() {
register_widget('RecentPostsWithExcerpts');
}
add_action('widgets_init', 'recent_posts_with_excerpts_init');

Conclusion

This plugin is a great way of showcasing your recently published content on the website frontend. When placed on the location of your choice, the recent posts would attract readers into further exploring your website. All you need to do is to fil out a simple form that includes the title of the post, the number of posts to be visible in the widget and the excerpt from the post.

If you need help with this plugin, Do leave a comment and I will get back to you.

The post How to Display Recent Posts Widget in WordPress appeared first on WPblog.

]]>
https://wpblog.com/wordpress-recent-posts-widget/feed/ 0
Build Custom WordPress Registration Forms Through Plugin https://wpblog.com/custom-wordpress-registration-form/ https://wpblog.com/custom-wordpress-registration-form/#respond Tue, 21 May 2019 11:35:11 +0000 https://wpblog.com/?p=36579 Registered users are an important factor in the success of any WordPress website. Whether its a simple blog or an ecommerce store, registered users are the audience that receive your message and help you expand the brand reach. For many years, the standard WordPress registration...

The post Build Custom WordPress Registration Forms Through Plugin appeared first on WPblog.

]]>
Registered users are an important factor in the success of any WordPress website. Whether its a simple blog or an ecommerce store, registered users are the audience that receive your message and help you expand the brand reach.

For many years, the standard WordPress registration form was considered adequate for average WordPress administrators. This was why this form became an essential component of the WordPress core.
However, WordPress has become more than a simple blogging platform. It now drives almost 30% of the entire internet. Thus, what worked a couple of years ago might not fit the requirements of the current users.

The solution to the requirements associated with WordPress registration form is simple: WordPress Custom Registration Form.

Why Opt for WordPress Custom Registration Form

A custom WordPress registration form has two major advantages over the standard form.
The first is the integration with the overall look and feel of the website theme. Standard forms often don’t work well with custom themes and there is always a chance that the custom CSS files do not render well with the form. A custom form, on the other hand, can be easily set up to work with custom CSS.

The second and more popular reason of using a custom registration form is the option of custom fields that are not included on the standard form. A small custom registration form speeds up the process and collects all the necessary data from a neat interface.

Custom registration form are not limited to just WordPress blogs only. If you have a WooCommerce store, custom WooCommerce registration forms are a great way of collecting specific user information items that the standard form miss out.

Let’s start by creating a WordPress custom registration plugin that you can then use as the “boilerplate for your own registration forms

WordPress Custom Registration Form Plugin

Start by creating a folder in the plugin folder. Name this new folder WordPress Registration Form.

Create a new .php file in this folder and name it custom-registration.php. Start by adding the following lines in this file:

<?php
/*
  Plugin Name: WordPress Registration Form
  Description: Custom registration form using shortcode and script as well
  Version: 1.x
  Author: Muhammad Owais Alam
 
 */

Since this is a custom plugin, the above information would be reflected in the WordPress Plugin page as:

WordPress Registration Form

Function for the HTML of the Registration Form
The following function contains the HTML code of the form.

function wordpress_custom_registration_form( $first_name, $last_name, $username, $password, $email) {
    global $username, $password, $email, $first_name, $last_name;
   echo '
    <form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
   First Name :
    <input type="text" name="fname" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '">
    Last Name:
    <input type="text" name="lname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '">
    Username <strong>*</strong>
    <input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">
    Password <strong>*</strong>
    <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">
    Email: <strong>*</strong>
    <input type="text" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '">
   <input type="submit" name="submit" value="Register"/>
    </form>
    ';
}

As you can see, this function has a very basic design that covers only the basic questions. You can use this function as it is or add the fields you require by adding the HTML elements.
As it stands now, when the plugin is activated, this is what the visitors would see:

WordPress signup form

WordPress Form Registration Validation

Using any form without validating user data is a sure recipe for disaster. In fact, the best case scenario is inaccurate user data. In worst cases, you are inviting every unsavory character on the internet to take a crack at your security.

Considering this, validation in an essential component of the custom WordPress user registration form plugin. It is implemented by the function wp_reg_form_valid, with the following code:

function wp_reg_form_valid( $username, $password, $email)  {
    global $customize_error_validation;
    $customize_error_validation = new WP_Error;
    if ( empty( $username ) || empty( $password ) || empty( $email ) ) {
        $customize_error_validation->add('field', ' Please Fill the field of WordPress registration form');
    }
    if ( username_exists( $username ) )
        $customize_error_validation->add('user_name', ' User Already Exist');
    if ( is_wp_error( $customize_error_validation ) ) {
        foreach ( $customize_error_validation->get_error_messages() as $error ) {
        	echo '<strong>Hold</strong>:';
        	echo $error . '<br/>';
        }
    }
}

The code snippet above uses WP_Error class to simplify the validation process.
Note that global $customize_error_validation ensures that the instance of WP_Error becomes global and accessible outside the scope of the validation function.

The first step of the validation process is about checking that the three important fields username, email and the password are NOT empty. This is accomplished by if ( empty( $username ) || empty( $password ) || empty( $email ) ) check that indicates to the user that these are required fields. Next, username_exists( $username ) verifies that the username is unique. In case of any issues, the user will see the HOLD error message (you can customize it to fit your requirements).

Form Validation

The form can also use JavaScript based validation. As you can see in the code snippet, the form action tag can also support a JavaScript tag that is triggered on the onsubmit action. For this modify the form action tag as:

<form action="' . $_SERVER['REQUEST_URI'] . '" name = "wp-custom-registration" onsubmit = "return(validate());">

The actual validation is carried out by the following validate() function:

<script type = "text/javascript">
	function validate() {
    	if( document.wp-custom-registration.fname.value == "" ) {
        	alert( "Enter your First Name" );
        	return false;
    	}
    	if( document.wp-custom-registration.lname.value == "" ) {
        	alert( "Enter your Last Name" );
        	return false;
    	}
    	return( true );
	}
</script>

In the validate() function, wp-custom-registration is the form name and fname.value is the combination of the name of the field and the value object.
The following function ensures that all fields of form are filled. Next, it adds the data from the form in the database using the wp_insert() function.

function wordpress_user_registration_form_completion() {
	global $customize_error_validation, $username, $password, $email, $first_name, $last_name;
	if ( 1 > count( $customize_error_validation->get_error_messages() ) ) {
    	$userdata = array(
        	'first_name'	=>   $first_name,
        	'last_name' 	=>   $last_name,
        	'user_login'	=>   $username,
        	'user_email'	=>   $email,
        	'user_pass' 	=>   $password,
 
    	);
    	$user = wp_insert_user( $userdata );
    	echo 'Complete WordPress Registration. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.';
	}
}

 

Shortcode Registration

This form can be inserted anywhere by using the shortcode [wp_registration_form]. Here is the code snippet for setting up the shortcode:

add_shortcode( 'wp_registration_form', 'wp_custom_shortcode_registration' );
 
function wp_custom_shortcode_registration() {
    ob_start();
    wordpress_custom_registration_form_function();
    return ob_get_clean();
}

If you wish to integrate the form within your theme, just add the following template tag:

<?php wordpress_custom_registration_form_function(); ?>

 

The Complete Code of the Plugin

Here is the complete code

<?php
/*
  Plugin Name: WordPress Registration Form
  Description: Custom registration form using shortcode and script as well
  Version: 1.x
  Author: Muhammad Owais Alam
*/
function wordpress_custom_registration_form( $first_name, $last_name, $username, $password, $email) {
    global $username, $password, $email, $first_name, $last_name;
   echo '
    <form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
   First Name :
    <input type="text" name="fname" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '">
    Last Name:
    <input type="text" name="lname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '">
    Username <strong>*</strong>
    <input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">
    Password <strong>*</strong>
    <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">
    Email: <strong>*</strong>
    <input type="text" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '">
   <input type="submit" name="submit" value="Register"/>
    </form>
    ';
}
function wp_reg_form_valid( $username, $password, $email)  {
    global $customize_error_validation;
    $customize_error_validation = new WP_Error;
    if ( empty( $username ) || empty( $password ) || empty( $email ) ) {
        $customize_error_validation->add('field', ' Please Fill the filed of WordPress registration form');
    }
    if ( username_exists( $username ) )
        $customize_error_validation->add('user_name', ' User Already Exist');
    if ( is_wp_error( $customize_error_validation ) ) {
        foreach ( $customize_error_validation->get_error_messages() as $error ) {
        	echo '<strong>Hold</strong>:';
        	echo $error . '<br/>';
        }
    }
}
 
function wordpress_user_registration_form_completion() {
    global $customize_error_validation, $username, $password, $email, $first_name, $last_name;
    if ( 1 > count( $customize_error_validation->get_error_messages() ) ) {
        $userdata = array(
        	'first_name'	=>   $first_name,
        	'last_name' 	=>   $last_name,
        	'user_login'	=>   $username,
        	'user_email'	=>   $email,
        	'user_pass' 	=>   $password,
 
        );
        $user = wp_insert_user( $userdata );
        echo 'Complete WordPress Registration. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.';
    }
}
function wordpress_custom_registration_form_function() {
    global $first_name, $last_name,$username, $password, $email ;
    if ( isset($_POST['submit'] ) ) {
        wp_reg_form_valid(
        	$_POST['username'],
        	$_POST['password'],
        	$_POST['email'],
        	$_POST['fname'],
        	$_POST['lname']
       );
 
        $username   =   sanitize_user( $_POST['username'] );
        $password   =   esc_attr( $_POST['password'] );
        $email  	=   sanitize_email( $_POST['email'] );
        $first_name =   sanitize_text_field( $_POST['fname'] );
        $last_name  =   sanitize_text_field( $_POST['lname'] );
       wordpress_user_registration_form_completion(
        	$username,
        	$password,
        	$email,
        	$first_name,
        	$last_name
        );
    }
    wordpress_custom_registration_form(
        $username,
        $password,
        $email,
        $first_name,
        $last_name
    );
}
 
add_shortcode( 'wp_registration_form', 'wp_custom_shortcode_registration' );
 
function wp_custom_shortcode_registration() {
    ob_start();
    wordpress_custom_registration_form_function();
    return ob_get_clean();
}

Custom Validation Field Method
add_filter( 'registration_errors', 'custom_validation_error_method', 10, 2 );
function custom_validation_error_method( $errors, $lname, $last_name ) {
 
    if ( empty( $_POST['fname'] ) || ( ! empty( $_POST['fname'] ) && trim( $_POST['fname'] ) == '' ) ) {
        $errors->add( 'fname_error', __( '<strong>Error</strong>: Enter Your First Name.' ) );
    }
 
    if ( empty( $_POST['lname'] ) || ( ! empty( $_POST['lname'] ) && trim( $_POST['lname'] ) == '' ) ) {
        $errors->add( 'lname_error', __( '<strong>Error</strong>: Enter Your Last Name.' ) );
    }
    return $errors;
}

 

Wrapping Up

I hope that by now you have a fair idea of creating a WordPress custom Registration form plugin. I have provided a basic template that you can expand and/or modify to fit your requirements. If you need to clarify a point, drop a comment below and i will get back to you.

The post Build Custom WordPress Registration Forms Through Plugin appeared first on WPblog.

]]>
https://wpblog.com/custom-wordpress-registration-form/feed/ 0