Category: WordPress

  • Redirect after logging in based on the user role

    Redirect after logging in based on the user role

    Not every user should be able to log in to the Dashboard, and WooCommerce already prevents this. But you may want to change it for somebody or just use a different page.

    By default WooCommerce redirects the user to the My Account page after a successful login.

    You can redirect after logging in and use a custom URL based on the user role, like the Dashboard for admins and My Account page for customers.

    Add this code at the end of the file functions.php in wp-content/themes/your-child-theme-name/:

    <?php
    /**
     * Redirect users to custom URL based on their role after login
     *
     * @param string $redirect
     * @param object $user
     * @return string
     */
    function wc_custom_user_redirect( $redirect, $user ) {
    	// Get the first of all the roles assigned to the user
    	$role = $user->roles[0];
    	$dashboard = admin_url();
    	$myaccount = get_permalink( wc_get_page_id( 'myaccount' ) );
    	if( $role == 'administrator' ) {
    		//Redirect administrators to the dashboard
    		$redirect = $dashboard;
    	} elseif ( $role == 'shop-manager' ) {
    		//Redirect shop managers to the dashboard
    		$redirect = $dashboard;
    	} elseif ( $role == 'editor' ) {
    		//Redirect editors to the dashboard
    		$redirect = $dashboard;
    	} elseif ( $role == 'author' ) {
    		//Redirect authors to the dashboard
    		$redirect = $dashboard;
    	} elseif ( $role == 'customer' || $role == 'subscriber' ) {
    		//Redirect customers and subscribers to the "My Account" page
    		$redirect = $myaccount;
    	} else {
    		//Redirect any other role to the previous visited page or, if not available, to the home
    		$redirect = wp_get_referer() ? wp_get_referer() : home_url();
    	}
    	return $redirect;
    }
    add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
    

    Delete the sign <?php on first line if you are having errors come up after saving the file.

    If you need to change the URL for a specific role you can use the function get_permalink() passing the page ID to return its URL:

    get_permalink( 150 );
    

    This code will return the URL to the page with ID 150.

  • Easily import DB using wp-cli

    Easily import DB using wp-cli

    I have been using Vagrant VVV for development on local for a long while now; havinng moved from XAMPP and PHPmyadmin for as long as I’ve been doing this stuff, moving to Vagrant presented me with a very real fear that I wouldn’t be able to easily setup local installs of live sites. With XAMPP I had always did a find & repace using the Search and Replace DB script, after importing the DB to the the local/development servers.

    It wasn’t perfect but served my needs for any db under 50MB. Sadly as I have been tasked with older installs and larger DBs that restriction has become problematic. Fortunately Vagrant once again steps in to save my butt.

    This is mostly a command line process but I promise it’s pretty basic, much faster than my previous mostly manual solution, and isn’t restricted to the PHPmyadmin file size limits. These steps while specific to Vagrant make use of the WP-CLI which is not specific to Vagrant. You could probably do this with XAMPP/MAMP and can definietly do this on your server if you set it up proper.

    WARNING

    If you are cloning a live site make sure you update your local wp-config.php file accordingly. Just copy the settings that Vagrant setup for you with the wp install.

    DB IMPORT IN VAGRANT

    This assumes you installed vagrant at the default location of vagrant-local

    1. Rename db
      Make sure that the db you will be importing is the same name as the db you will be importing into. So if your local site has a database name of EXAMPLE.sql you need to make sure that the db you will be imported also has the name of EXAMPLE.sql
    2. Move db
      Make a copy of the db you will be importing and move it to the root directory of the site you will be importing into./vagrant-local/www/EXAMPLE/
    3. ssh into vagrant
      cd vagrant-localvagrant ssh
    4. cd to site
      cd /srv/www/EXAMPLE
       
    5. Import db
      wp db import DATABASE.sql
    6. Search and Replace (optional)If you need to do a search and replace run the following command. It handles serialized data appropriately so you don’t bugger up your site.wp search-replace ‘http://example.com’ ‘http://example.dev’
    7. Celebrate 🎉
      Extra: Commands that start with wp make use of the WP-CLI which comes set up with vagrant. See http://wp-cli.org for more info and available commands.

      Vagrant does support PHPmyadmin at vvv.dev but the upload limit is actually lower than MAMP. This limit can be changed in your PHP.ini file but I really don’t think it’s worth doing with how much easier the command line method is.

      What tools do you use for your development environments? Do you have any favourites?

  • Getting the most of your WordPress Dashboard

    Getting the most of your WordPress Dashboard

    Why customize the WordPress dashboard?

    One of the things I really like about WordPress is the immense flexibility it offers to its users. Everything within WordPress is customizable, starting from themes, plugins, post types, taxonomies, widgets, page templates… literally everything!

    What is that one screen you see regularly on WordPress, but might not have customized so far? Yes, the dashboard. I have been using WordPress since long now myself, and very rarely have I seen someone spending time changing things on the dashboard. I think that is because people care more about what readers see, rather than what they see on the dashboard.

    I know there are a many admin themes out there, of course not as much as the regular themes, but there are definitely interesting options. I have tried a few admin themes myself, but I was never really impressed, as most of them generally offer just another UI. Or may be that’s just me 😛

    However, the dashboard, in generally should be one of the most productive and useful screen on your site.

    We will have a look at the methods to customize the WordPress admin area, how to introduce changes to it manually, and a number of plugins that also get the job done.

    How to customize the WordPress dashboard?

    Customize the login page

    A user experience for users begins even before thy use your dashboard, right at the login page. Lets see how we can improve it.

    For instance, to change the WordPress logo on the login form to use your logo instead. You can use the following code snippet for that:

    &lt;?php
    function my_login_logo() { ?&gt;
        &lt;style type=&quot;text/css&quot;&gt;
            #login h1 a, .login h1 a {
                background-image: url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/images/login-logo.png);
                padding-bottom: 30px;
            }
        &lt;/style&gt;
    &lt;?php }
    add_action( &#039;login_enqueue_scripts&#039;, &#039;my_login_logo&#039; );
    ?&gt;
    

    Make sure you replace the image path to match with your logo file. You can have this right into your WordPress Media library, or in a images directory within your child theme’s directory. The recommended image size to be used here is under 80×80 pixels in size.

    If you wish to, you can go beyond this and customize your login page even further using custom CSS. If you plan to make CSS changes the best practice is to enqueue the custom style sheets. Here is how to can do it.

    &lt;?php
    function my_login_stylesheet() {
        wp_enqueue_style( &#039;custom-login&#039;, get_template_directory_uri() . &#039;/style-login.css&#039; );
        wp_enqueue_script( &#039;custom-login&#039;, get_template_directory_uri() . &#039;/style-login.js&#039; );
    }
    add_action( &#039;login_enqueue_scripts&#039;, &#039;my_login_stylesheet&#039; );
    ?&gt;
    

    Here are a few suggestions from WordPress Codex for CSS operators to customize your backend:

    body.login {}
    body.login div#login {}
    body.login div#login h1 {}
    body.login div#login h1 a {}
    body.login div#login form#loginform {}
    body.login div#login form#loginform p {}
    body.login div#login form#loginform p label {}
    body.login div#login form#loginform input {}
    body.login div#login form#loginform input#user_login {}
    body.login div#login form#loginform input#user_pass {}
    body.login div#login form#loginform p.forgetmenot {}
    body.login div#login form#loginform p.forgetmenot input#rememberme {}
    body.login div#login form#loginform p.submit {}
    body.login div#login form#loginform p.submit input#wp-submit {}
    body.login div#login p#nav {}
    body.login div#login p#nav a {}
    body.login div#login p#backtoblog {}
    body.login div#login p#backtoblog a {}
    

    Do you want to go further? You can build your own login page template. Here are the instructions to do so.

    Utilize the user roles

    Though you can code everything yourself, WordPress offers a bunch of option built-in to make things easier. User roles in WordPress are one of those.

    All the users in WordPress are assigned certain roles, according to which they have pre-defined capabilities with define what the user can and cannot do.

    Obviously the administrator is the role with all the capabilities. If you are building sites for clients, you can choose to have just one administrator i.e. yourself and make other users with only the capabilities required for the client. The more options you leave open, the more chances of things going wrong, its always good practice to restrict users to only action they are expected to perform.

    For instance, if the client need to write, edit and publish post but not change the theme or update plugin, an author profile is perfectly suitable for this purpose.

    Obviously you can change roles for the users whenever you need to. Additionally if you find the pre-defined roles aren’t fitting your needs you can modify the user capabilities. There are several plugin to do so. User role editor is something I would recommend for customizing user roles.

    De-Clutter the menu items

    According to the roles, users have different menu items available for them. Sometimes you may come across a scenario where you might want to hide certain menu items.

    There are two function which can help you to do it:

    Here is an example to remove one of the pages from the admin menu, using the remove_menu_page( $menu_slug )

    &lt;?php
    function custom_menu_page_removing() {
        remove_menu_page( $menu_slug );
    }
    add_action( &#039;admin_menu&#039;, &#039;custom_menu_page_removing&#039; );
    ?&gt;
    

    With using current_user_can() function, you can go further to limit the users according to the user roles. For instace the below example show how you can hide the plugins page from the menu for any user that is not the admin:

    &lt;?php
    function remove_menus(){
         if ( !current_user_can( &#039;manage_options&#039; ) ) {
              remove_menu_page( &#039;plugins.php&#039; );
         }
    }
    add_action( &#039;admin_menu&#039;, &#039;remove_menus&#039; );
    ?&gt;
    

    You can check for slugs for the different menus in WordPress Codex. By the way, this methods just hides the menu item from the dashboard, which means the page is still accessible if the complete address is typed in the browser.

    Using the Screen options

    Another and often less used built-in feature for customizing the dashboard are Screen options. Screen options lets you to show/hide almost everything visible on the backend screen.

    For instance, if you don’t use categories on your posts, you can simply disable them. This also work for excerpts, tags, track backs, redirections, everything else you can find on the screen options.

    [wpvideo Awygo1HV]

    The screen options even allow you to determine how many comments to display in the comments menu. All you need to do is find them in the upper right corner on any screen and use the check boxes to make elements appear and disappear.

    The best thing: Screen options are saved on a user basis so you can customize screens for each person on your site.

    Adding custom widgets to WordPress dashboard

    Now that we know how we can reduce clutter from the dashboard and hide widgets, lets look into how we can create a custom widget. Here is a sample code which you can use to add custom widget to the dashboard which you can use to display any content you want:

    &lt;?php
    function add_custom_dashboard_widgets() {
    
            wp_add_dashboard_widget(
                         &#039;my_custom_dashboard_widget&#039;, // Widget slug.
                         &#039;My Custom Dashboard Widget&#039;, // Title.
                         &#039;custom_dashboard_widget_content&#039; // Display function.
                );
        }
    
        add_action( &#039;wp_dashboard_setup&#039;, &#039;add_custom_dashboard_widgets&#039; );
    
        /**
         * Create the function to output the contents of your Dashboard Widget.
         */
    
        function custom_dashboard_widget_content() {
            // Display whatever it is you want to show.
            echo &quot;Hello there, I&#039;m a Dashboard Widget. Edit me!&quot;;
        }
     ?&gt;
    

    You can change the line “Hello there, I’m a Dashboard Widget. Edit me!” to whatever you need to make your widget appear.

    For instance, you can add a custom welcome message for your client with links to documentation and support etc. Users new to WordPress often get lost and don’t know what to do next, such help widgets can be used to guide them using hyperlinks to help.

    For such case you can add information like this:

    &lt;?php
    function custom_dashboard_widget_content() {
         echo &quot;Hello Client, please remember to stay away from the plugins menu.&lt;/br&gt;If you have any need of assistance, please don&#039;t hesitate to contact us under:
         &lt;ul&gt;
             &lt;li&gt;http://yourwebsite.com&lt;/li&gt;
             &lt;li&gt;0-00-000-000&lt;/li&gt;
         &lt;/ul&gt;
         &quot;;
        }
     ?&gt;
    

    You can replace the link and the phone number to match with your contact details.

    You can customize this further to add your own help tabs to pages for more information:

    &lt;?php
    function setup_help_tab() {
    
    $screen = get_current_screen();
    
    if ( &#039;post&#039; == $screen-&gt;post_type ) {
    
    get_current_screen()-&gt;add_help_tab( array(
    &#039;id&#039; =&gt; &#039;post&#039;,
    &#039;title&#039; =&gt; ( &#039;How to Publish a Blog Post&#039; ),
    &#039;content&#039; =&gt; &#039;&lt;strong&gt;To publish a blog post, please follow the steps below.&lt;/strong&gt;
    &lt;ul&gt;
        &lt;li&gt;Locate big, blue &lt;em&gt;Publish&lt;/em&gt; button.&lt;/li&gt;
        &lt;li&gt;Click it.&lt;/li&gt;
        &lt;li&gt;Well done.&lt;/li&gt;
    &lt;/ul&gt;
    &#039;,
    ) );
    }
    }
    add_action( &#039;admin_head&#039;, &#039;setup_help_tab&#039; );
    
    ?&gt;
    

    The example above will add the information to the Help button they can find on almost any screen.

    Disable theme and plugin editor

    Personally, I am not a big fan of the theme and plugin editor within the WordPress dashboard. I know a lot, who might not feel the same about it. The primary reason I don’t like it is because it leaves the ends open to users who are not very familiar with the code, and the worst part if while editing, they go wrong, the dashboard may not be accessible any more for them to undo the changes. This not only creates a panic for the users, but also leaves the developer in a difficult situation.

    Not to mention the addition security risk involved with it; anyone who can access you dashboard (both legitimately and illegitimately), can make any changes to your site and possibily bring it down.

    Also, since mostly you will work on edits to the theme and plugin from FTP or from a dev/staging environment, you won’t need this on the dashboard.

    That being said, here is how you can disable it, by adding this to your wp-config.php:

    define( &#039;DISALLOW_FILE_EDIT&#039;, true );
    

    Edit the dashboard footer

    Since we are talking about all the aspects of customizing the WordPress Dashboard, why not change the footer too.
    It usually says “thank you for creating with WordPress”.

    It is a great place to let your client know who built their site for them. Here is how you can do it, just adding this to the function.php will do the trick:

    &lt;?php
    function change_admin_footer(){
         echo &#039;&lt;span id=&quot;footer-note&quot;&gt;From your friends at &lt;a href=&quot;http://www.yourdomain.com/&quot; target=&quot;_blank&quot;&gt;XYZ Web Studio&lt;/a&gt;.&lt;/span&gt;&#039;;
        }
    add_filter(&#039;admin_footer_text&#039;, &#039;change_admin_footer&#039;);
    ?&gt;
    

    Feeling adventurous? How about making a custom dashboard page? 

    You can build a custom dashboard page according to your choice. You will have to build a plugin for it. It is a comparatively longer discussion and I hope to share it soon. I will update a link here when I do so.

    If you are thinking about having your own WordPress backend, WP Explorer has an excellent article to get you started.

    Plugin suggestions:

    There are several plugin you can make use of to get these changes done. Here is a list of plugin I think can be helpful:

    Admin Menu Editor

    Wp Admin UI Customize

    White Label CMS

    WP Help

    Tabify Edit Screen

    Fancy Admin UI

    Dashboard themes:

    Slate Admin Theme

    First WordPress Admin Theme

    I hope you find this post useful. Let me know if you know any more hacks to customize the WordPress dashboard that I might have missed. Feel free to open a discussion below in the comments.

  • Debugging WordPress

    Debugging WordPress

    If you accidentally introduce a syntax or fatal error in one of your template files, you’ll probably see the dreaded white screen of death when you visit your home page. In some cases, even the admin screens will go blank. The best way to figure out what happened is to check your PHP error log. Look for the last error shown and try to correct it. However, if you can’t find your error log (or you don’t have one), you can turn on debugging by adding define('WP_DEBUG', true); to your wp-config.php file.

    The problem with this method, though, is that everyone who visits the site will see your errors. Fortunately there is an alternative, which lets you enter debug mode by adding a query string to any URL.


    if ( isset($_GET['debug']) && $_GET['debug'] == 'debug')
    define('WP_DEBUG', true);

    Then you can just add ?debug=debug to your URL (e.g. http://mysite.com/category/news/?debug=debug) to see the errors.

    The white screen of death usually comes up when you update a theme or plugin. If your theme has gone horribly wrong and you just want to switch back to another one, but you can’t access the admin screens to change it, don’t panic. Simply delete or rename your active theme’s directory. When WordPress can’t find it, it will revert to the default theme. You can also deactivate an error-causing plugin by deleting or renaming its directory. WordPress will automatically deactivate it.

  • Change the “Enter title here” placeholder text to make it fit your content

    Change the “Enter title here” placeholder text to make it fit your content

    When you’re working with custom post types, sometimes the post title isn’t a title. It might be a person’s name, a building number, or a course code (just to take a few examples from universities). So it’s great that WordPress has a simple filter that makes it easy to customize the “Enter title here” placeholder text to make it fit your content:

    https://gist.github.com/patilswapnilv/5cffbf8396e3d2e86b4f77a1f3f1232f

    How to use this?

    Place this code in your functions.php or in a plugin or even better if you can add it to a must-have plugin.

  • How to change WordPress admin icons

    How to change WordPress admin icons

    One of my favorite things about the admin theme with WordPress is the new Dashicons icon font. It brings a sense of standard and uniformity to dashboard icons with its distinctive look and vast array of icons for theme and plugin authors to choose from and use with ease.

    However, it seems that not all plugin and theme authors have jumped on the Dashicons bandwagon. They insist on using their own custom image icons that do not fit in with the new design at all. This includes things such as colored icons which do not adapt to the different color schemes included with WordPress. Other authors do not set an icon for their menu or post type, resulting in many of that same thumb tack post icon or generic gear icon. This leads to a messy dashboard, which I do not like.

    Fortunately, it is easier than ever to override the author’s choice for the icon with a Dashicon of your choice – all with only a few lines of CSS.

    Dashicons is the icon font used officially in WordPress admin. What’s great about it is that you can add some visual cues on your website without bloating it up. Visuals like images increase load times and don’t scale well, while SVGs require you to read up a bit to actually put it to use Today we’re going to show you how you can get these font icons installed on your WordPress project.

    Step 1: Enqueuing the script

    To get your WordPress site ready, you’ll need to open up your child theme’s functions.php file and insert the following lines of code at the end.

    add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
    function load_dashicons_front_end() {
    }

    Step 2: Using dashicons

    Head over to this site and pick an icon that you’d like to use. Click on ‘Copy HTML’ and use that snippet of code and paste it into your HTML, and with that, you are done! Simple isn’t it.

    copy-code-prompt
    Copy the code and insert it into your HTML.

    Extra Step: CSS Method

    Instead of inserting it via HTML, you can also insert dashicons using CSS.  Return to this site and pick an icon. This time, click ‘Copy CSS’ and insert that code into your own CSS file. Make sure to paste the code in the CSS before:selector.

    Here’s a sample code of how this will look like:

    .web-link:before {
    font-family: "dashicons";
    content: "\f319";
    }

    Menu icons?

    Head over to the Dashicons website and pick out an icon you want. Select it and click “Copy CSS” to copy the necessary code for using that icon in CSS.

    The next is to obtain the ID of that menu. To do so, use your browser’s Inspect Element tool. You’re looking for something like toplevel_page_{menu-slug} or menu-posts-{post_type}.

    To add the Dashicon to the menu, use this CSS. Remember to substitute toplevel_page_{menu-slug} for the menu ID and content: '\f174'; for the Dashicon CSS code.

    #adminmenu #toplevel_page_{menu-slug} div.wp-menu-image::before {
        content: '\f174';
    }
    

    If you’re just overriding another Dashicon, then the above is all that is needed. If the menu already has an image icon embedded in the HTML, you will need to add this CSS:

    #adminmenu #toplevel_page_{menu-slug} div.wp-menu-image img 
        display: none;
    }
    

    If the menu already has an image icon applied through CSS background images, use this CSS instead of the above:

    #adminmenu #toplevel_page_{menu-slug} div.wp-menu-image {
        background: none !important;
    }
    

    You can include the CSS code in a plugin, theme’s functions.php or code snippet by wrapping it with this PHP code:

    function replace_admin_menu_icons_css() {
        ?>
        <style>
            /* CSS code goes here */
        </style>
        <?php
    }
    
    add_action( 'admin_head', 'replace_admin_menu_icons_css' );

    And with that, you are now on the road to using WordPress dashicons! Do you use Dashicons or do you prefer SVGs? Let us know which method you use and why down in the comments below.

  • Call a navigation menu using a shortcode

    Today I came across a weird situation: I needed to place a navigation menu in the content of a page. A shortcode was the obvious solution, but there doesn’t appear to be one built in for menus. I created this one very quickly:

    function print_menu_shortcode($atts, $content = null) {
    extract(shortcode_atts(array( 'name' =&gt; null, ), $atts));
    return wp_nav_menu( array( 'menu' =&gt; $name, 'echo' =&gt; false ) );
    }
    add_shortcode('menu', 'print_menu_shortcode');
    

    Place this in functions.php, then use [menu name="main-menu"] to call the menu in your content (replacing "main-menu" with your menu’s slug, of course).

    You could adapt this to accept any of the other arguments available for wp_nav_menu(), but this served my purposes.

  • Have you built something interesting with WordPress?

    Have you built something interesting with WordPress?

    It is very easy to create a WordPress website. Considering that WordPress is no longer just blogging tool, it has grown into a very powerful Content Management System. You can use WordPress to build a different type of websites very easily.

    Thousands of free and premium plugins are available to turn WordPress from simple blog to powerful professional website. And this is what makes the WordPress eco-system way more interesting. You think of it, and there is a way to build it with WordPress.

    What have you built with WordPress?

    We would like to learn more if you have built an interesting website or an app with WordPress, or a plugin/ theme or might be even a SAAS platform. We would like to know more about your journey.

    Come talk to us!  The Pune Knowledge Exchange group is organising a Meetup to showcase your awesome website, blog, product to other WordPressers in Pune. We are having a Meetup discussing interesting products built on the top of WordPress.
    More about it here

    Why should you be there?

    We understand that building a product is not as easy as it is said. But we also understand that just building great products does not make it popular. It’s the community that adopts it.

    Talking about your WordPress product at the Meetup gives you a window into your users perspective. You can get first-hand reviews of your product. Suggestions regarding improving it. And who knows you might gain some customers too.

    What are we interested in listening?

    Actually everything about your journey building it. I personally would be more eager to listen to how you built it. Why have you built it? What problems does your product solve? Did you face any difficulties when doing it? How did you overcome them? Do you have suggestions for other fellow developers/users or someone who is looking forward to building something similar?

    See you there!

    WordPress Lightning Showoff

    1/13, 2:00 PM: Have a great website or product around WordPress that you’d like to show off?In 10 minutes, showcase your awesome website, blog, product to other WordPressers in Pune.5 more minutes to

     

  • Installing WP-CLI on shared hosting

    Installing WP-CLI on shared hosting

    WordPress Command-Line Utility, or WP-CLI for short, is an advanced utility for power users who wish to rapidly manage and deploy their WordPress sites using bash/SSH.

    Are you managing multiple WordPress websites

    Have ever logged in to your client’s site just for the sake of Core WordPress Update or Plugin/Theme update?

    Let us assume WordPress has released a new update and you have to update all themes and plugins of 10 different WordPress websites, every time you’ve to log in to the dashboard go to the updates page and select updates manually.

    the above process is quite time-consuming, So in order to manage multiple WordPress websites in a quick way you can use WP-CLI

    What is WP-CLI?

    WP-CLI is Command Line interface based WordPress site management tool used to manage WordPress websites via SSH.

    Using WP-CLI you can easily manage your websites without logging in, no need to remember your WordPress Login credentials. Just log in to your server via SSH and manage your WordPress installation quickly.

    Why WP-CLI?

    • Serious Time Saver: No need to wait for the page to load, No need to remember site passwords, You can just enter few commands and your work will be done in few seconds as simple as that.
    • Supported & used by top Hosting Providers: The Overall WP-CLI project is backed by Hosting Giants like BlueHost, Automattic, DreamHost, WPEngine & SiteGround. BlueHost has confirmed that they are using WP-CLI to upgrade more than 2 Million websites. According to a report out of 2 million websites, 99% of websites were upgraded successfully.
    • Easy to use: If too many options on GUI confuses you then WP-CLI is for you. As it is CLI based tool there is no huge list of drop down links or tons of buttons which helps you to navigate you from one page to other. Command line interface is pretty simple , Enter a correct command it executes properly and gives a output.
    • No Passwords: Yes no need to remember login username and password for every website you manage. Just login to your server via SSH and let WP-CLI handle rest of the things. using WP-CLI you can handle each WordPress installation hosted on your server.
    • Love for Terminal : If the geek inside you loves working with Dark terminal window then WP-CLI is for you.

    Basic Requirements of WP-CLI

    • SSH Access

    Before moving forward make sure your hosting provider has enabled SSH access for your account. If not then request your hosting provider to enable SSH for your account.

    Installing WP-CLI via SSH

    1. Login to server via SSH

    Enter your username and password to access server via SSH.

    After successful login enter “pwd” command to know your current directory.
    Output should be /home/username
    [username@server ~]$ pwd
    /home/username

    3. Download Setup file

    To install WP-CLI you must download setup file to our directory.

    WP-CLI is open source project maintained by open source community

    Latest version of wp-cli file is available as wp-cli.phar on WP-CLI GitHub repository.

    Now you have to Download wp-cli.phar file to our current directory.
    To download that file you can use “curl” command.

    (you can also use “wget” command to download files from remote server)
    curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
    hit enter key to execute command.

    4. Making file Executable

    In Linux operating system you can’t execute a file directly like the way you execute files in Windows, here you have to set permission for that particular file and make it executable so that users can use execute those files and accomplish their task

    Now you have to set permissions to wp-cli.phar file and make it executable.
    chmod +x wp-cli.phar
    chmod +x is a Unix system call which may change the access permissions to file system objects and makes that file executable.

    5. Testing Execution

    After assigning permissions lets check whether the file executes properly.

    If the command doesn’t execute properly then you should delete current .phar file and Download a new file.

    To Check whether file is Executing properly, Run “php wp-cli.phar –info” command to get PHP version details and WP-CLI version details.
    php wp-cli.phar --info
    (version details will be displayed in following manner)
    patilswapnilv@swapnil-desk:~$ php wp-cli.phar --info
    PHP binary: /opt/cpanel/ea-php56/root/usr/bin/php.cagefs
    PHP version: 7.0
    php.ini used: /opt/cpanel/ea-php56/root/etc/php.ini
    WP-CLI root dir: phar://wp-cli.phar
    WP-CLI vendor dir: phar://wp-cli.phar/vendor
    WP_CLI phar path: /home/patilswapnilv
    WP-CLI packages dir:
    WP-CLI global config:
    WP-CLI project config:
    WP-CLI version: 1.4.1
    patilswapnilv@swapnil-desk:~$

    6. Setting up Alias for commands

    Now in order to execute WP-CLI commands you have to always mention “php wp-cli.phar” before command.

    Like “php wp-cli.phar plugin list”
    (this command will display all the plugins installed in current WordPress website)

    Syntax is too long, you can trim it and make it more user-friendly by assigning alias in .bashrc file or move wp-cli.phar file to usr/bin/wp folder.

    This is final step of WP-CLI installation which can be executed in two ways

    • .bashrc file method
    • moving .phar file to bin folder

    6.1 Adding alias to .bashrc file

    Adding Bash alias for WP-CLI (.bashrc file method)

    Using alias you can trim long code “php wp-cli.phar” to a short one “wp“.
    Basically alias helps us to create a short version of long commands

    In .bashrc file you have to create an alias and assign “php wp-cli.phar” to “wp” so that whenever you run a command in short form in terminal but in backend it will run as long format.

    Example
    “wp plugin list” will run as “php wp-cli.phar plugin list”

    Run alias command to assign alias
    alias wp='~/wp-cli.phar'
    This command tells the system that every time when users enters “wp” consider it as “wp-cli.phar“, an executable file which is present in home directory.
    echo "alias wp='~/wp-cli.phar'" >> .bashrc
    using echo you can output the required statement then “>>” will append it to .bashrc file
    source .bashrc
    here you use source command to update bash initialization.

    6.2 Moving WP-CLI.Phar to Bin folder

    In shared hosting user don’t have root level permission to move file from home directory to system folders or edit system level file that is why use .bashrc file editing method.

    If you are trying to install WP-CLI on Virtual Private Server or Dedicated server then you can move wp-cli.phar file to /usr/bin/wp folder
    mv wp-cli.phar /usr/local/bin/wp

    or

    sudo mv wp-cli.phar /usr/local/bin/wp
    This will move .phar file to bin folder and help us to use WP-CLI just by typing “wp“.

    Test WP-CLI Commands

    If you have completed all the above steps then run any WP-CLI command to check whether it is working properly.

    Run “wp plugin list” command to check installed plugin status and plugin version.
    patilswapnilv@swapnil-desk:~$ wp plugin list
    +-------------------------+----------+--------+---------+
    | name | status | update | version |
    +-------------------------+----------+--------+---------+
    | akismet | active | none | 4.0.1 |
    | jetpack | active | none | 5.5.1 |
    | syntaxhighlighter | active | none | 3.2.1 |
    | wordpress-seo | active | none | 5.8 |
    +-------------------------+----------+--------+---------+
    patilswapnilv@swapnil-desk:~$

    If you can see similar output then WP-CLI is working perfectly.

    Hope you’ve understood how WP-CLI is installed on shared hosting servers. If you are facing any difficulty while installing WP-CLI let me know in comments below.

    This is a basic tutorial on WP-CLI installation. Now you’ve learned how WP-CLI makes WordPress site management easy. There are few hosting companies which provides WP-CLI by default for every WordPress installation. You can find list of Hosting providers who are supporting WP-CLI project.

    Using WP-CLI you can install WordPress, install Themes, install Plugin, Comment Moderation, Write Posts, Add users etc. For every process there is a CLI command mentioned in WP-CLI commands cheat sheet.

    WP-CLI is maintained by open source community and new commands are added with every new release.

    For more info about WP-CLI Project you can visit WP-CLI.org

  • How to submit plugin to WordPress plugin repository

    How to submit plugin to WordPress plugin repository

    So you made an interesting WordPress plugin, and you want that to be available for others to use. Though GitHub is really nice to share code, when it comes to WordPress, nothing beats the WordPress.org plugin and theme repository.

    Why Publish Your WordPress Plugin?

    The reasons people publish plugins in the WordPress Plugin Directory are obviously varied. A couple of examples are explained below:

    • You see a need for functionality that doesn’t exist in a plugin in the directory
    • You see a market opportunity
    • You want to build a community around your plugin
    • Your favorite plugin doesn’t offer additional functionality that you want
    • You’re frustrated by how much some plugins charge for extra extensions and you think you could build those features at a lower cost
    • You want to simplify functionality in a way that doesn’t exist
    • You want to contribute to the WordPress Plugin Directory in order to be a part of the community

    Today, I am trying to explain how you can submit your plugin/s to the WordPress.org repository.

    The plugin Submission process:

    I am breaking down the process into smaller steps for ease;

    The Guidelines.

    Make sure you read the guidelines before creating and submitting your plugin to the repository. Make sure that your plugin is in compliance with all the rules. Some of the rules include:

    • Your plugin must be GLP compatible
    • Requiring user consent before storing user information
    • Not spamming users
    • Not including obfuscated code
    • Not doing anything that is illegal or morally offensive
    • Not embedding external link in the public site

    Check the plugin name on the WordPress Directory

    This is a simple step to decide the name for your plugin before you start. Doing this will let you know if that name is already taken. Just like usernames, you might not get what you expected.

    Go to https://wordpress.org/plugins/ and enter your desired plugin name into the “Search plugin” search box. If you find no plugin for the name you used, there’s still a chance that a plugin has been submitted under that name and the user hasn’t submitted their first subversion commit, so don’t get too excited. Stay positive 🙂

    You will want to submit the plugin as soon as possible in order to make sure that you get the name. If the plugin name already exists, you will need to brainstorm to think of a new one.

    Create a plugin that works

    Isn’t this so obvious? Make sure you plugin does exactly what you mention in the Readme. I create several plugins using the WordPress Plugin BoilerPlate. It saves a lot of time and has a perfect structure. But this is a choice and not a necessity. You are free to use whatever structure you find comfortable working with, as far as it follows the guidelines.

    After you have made the plugin test it various times, in different environments if possible. Test all the functionalities so everything works exactly as you want it to.

    Validate the Readme file.

    The readme file plays an important role since it is used to populate the plugins page in the WordPress directory. If you want to make sure your plugin stands out here is an interesting article which talks about it in more detail.

    To give you a general overview, you should enter in your plugin name, contributors (WordPress author IDs), donate link, tags, the WordPress version that is required and the WordPress version the plugin has been tested on, license (it must be GPL) and a short description of your plugin. For the tags, I would suggest choosing tags based on those listed in a competing plugin and popular tags that are relevant to your plugin. You can find tags from competing plugins by looking at their directory page and scrolling to the bottom of their page or by checking out theirreadme.txt file.

    After adding that information, you should add the main description, installation instructions frequently asked questions and screenshots of your plugin. Make sure to include the screenshots, banner, and icon in your plugin’s assets directory. The more screenshots the better. Once you’re happy with your readme file, run it through the ReadMe Validator.

    Submit your plugin for Review

    Once you have completed all the above, you can log in to WordPress.org and add your plugin for review, by uploading your plugin at https://wordpress.org/plugins/add/

    Add your plugin name as well as a description of your plugin. For the plugin URL, you need to compress your plugin files and upload your plugin.zip file to your website or to a website that you have access to. You should be able to upload the compressed file to Dropbox or Google Drive and add a public link to the plugin zip file.

    Wait for approval 🙂

    During the review, in some cases, the plugin review team may suggest some improvements to your plugin. Once the review is done, you should receive an email from WordPress.org regarding the approval. Congrats! You may now have that little dance you were waiting for 😛

    The email will also contain the URL for your plugin page on WordPress.org, A SVN URL to upload your plugin files.

    This command adds all of your central WordPress Subversion repository’s files into your local repository. An important note, make sure to replace  https://plugins.svn.wordpress.org/your-plugin-name. with the URL that is provided in your plugin approval email; You SVN URL will also be in the similar format of https://plugins.svn.wordpress.org/your-plugin-name. And, replace your-plugin-name at the end of the command with what you would like to name the directory.

    You’ll get a response asking the following:

    (R)eject, accept (t)emporarily or accept (p)ermanently? 
    

    Type in t or p and hit Enter. Then, you’ll receive the message below. This indicates that the your-plugin-name directory was created on your computer and the tags, assets, trunk, and branches directories were added within the your-plugin-name Subversion repository directory.

    Place all of your plugin files in the trunk directory. Now that you have your plugin files in the trunk directory, you need to add those files to your Subversion repository so that they can be tracked. You can do this by running the terminal command below.

    svn2

    You then need to push the changes made to your local repository to the central WordPress repository by running the following command in your terminal window.

    svn-ci

    You’ll need to enter your computer’s logged in username and password.

    Then, you will be asked for your WordPress username and password.

    Once those are credentials are provided, your plugin’s files will be transferred to the WordPress central repository. A Transmitting File Data message will be displayed and when complete, a Committed revision message will be displayed.

    transmitting

    DONE! You should get an email from WordPress explaining the new commit. Now, you may go and check your plugin URL on WordPress.org to see the changes.

    Your plugin is now available for the public to download and use. But there are some improvements you can make to help users know your plugin a little better.

    If you have not added images for banner and screenshots etc in the /assets directory already you won’t see them on your plugin page. Now add them and run the following command.assest*

    Now, you need to commit the change to the central repository.

    adding-assets

     

    Check out your WordPress Plugin Directory page now and you should see images.

    If you are developing your plugin on multiple computers or with multiple contributors, make sure to run the update command (visible below) before committing any changes. This pulls the changes that exist in the central WordPress repository into your local plugin repository.

    update

    Question?

    Please feel free to get in touch using this contact form if you have any question regarding this, which I may have missed adding here.

    References:
    https://developer.wordpress.org/plugins/wordpress-org/
    https://developer.wordpress.org/plugins/wordpress-org/how-your-readme-txt-works/
    https://make.wordpress.org/plugins/2012/06/09/the-plugins-directory-and-readme-txt-files/
    https://www.sitepoint.com/create-awesome-wordpress-org-page-plugin/
    https://wordpress.org/plugins/developers/add/
    https://wppb.me/
    https://github.com/DevinVinson/WordPress-Plugin-Boilerplate
    https://www.slushman.com/guide-using-wordpress-plugin-boilerplate/