Wednesday, May 27, 2015

Periscope streaming app launches on Android smartphones




Twitter launched its Periscope application on Android-powered devices on Tuesday as the battle for live-streaming video spread to the world's leading smartphone platform.

A version of Periscope tailored for Android, the KitKat version or newer, debuted at the Google Play shop as Twitter stepped up its offensive on rival video-streaming application Meerkat.

"When we started Periscope, we wanted to build the closest thing to teleportation --  by providing users with the best way to start or watch a live video broadcast," the Periscope team said in an online post.

"Our initial launch was limited to just (Apple's) iOS, but we've been working really hard to craft an experience that feels special on Android, yet still unmistakably Periscope."

A version of Periscope for Apple iPhones was released in late March.

The Periscope app, like Meerkat, allows anyone to stream live video to a wide audience with their smartphone.

Meerkat became a virtual overnight sensation on its debut earlier this year. But Twitter soon blocked access to a function that allowed the video to spread further within the social network.



Monday, May 11, 2015

Getting Started with WordPress Plugin Development

Plugins are PHP scripts that alter your website – basically, bits (or even lots!) of code that can be uploaded to your WordPress install to extend and expand the functionality of your site, without having to hack the core code.
The great thing about plugins is that they allow you to add features to your site and remain intact, even if you switch themes or upgrade your WordPress install.
Creating a plugin of your own is really not that difficult and can solve a lot of problems. Copying and pasting useful code and additional features into your theme’s functions.php file is great, but these changes may be lost when you update your theme. A plugin is a safe way to try out new things and the way to go if you need to implement cross-theme functions.
This article will walk you through creating a plugin, and we’ll also look at some intermediate/advanced concepts:
  1. Creating a simple plugin integrating WordPress with Facebook Open Graph.
  2. How plugins work.
  3. Using hooks.
  4. Getting started with filters.
  5. Adding scripts and styles.
  6. Creating a plugin settings page.
  7. Enabling translations.
Note: This guide is aimed at those who are getting started with plugin development. A little knowledge of editing files and some rudimentary HTML and PHP is all you’ll need to follow along.

A Simple Plugin Project

In this article we’re going to create a plugin that integrates WordPress and Facebook Open Graph. Open Graph tags are special HTML tags, which give Facebook the information it needs to share your page and ensure it looks great.
Here’s a set of example tags, which could be used on the page you are reading right now:
1 2 3 4 5 6
<meta property="og:title" content="A Beginner's Guide To Creating A WordPress Plugin" />
<meta property="og:site_name" content="WPMU DEV Blog" />
<meta property="og:url" content="http://premium.wpmudev.org/blog/a-beginners-guide-to-creating-a-wordrdpress-plugin" />
<meta property="og:description" content="A guide for beginners to help them get started with plugin creation in WordPress" />
<meta property="og:type" content="article" />
<meta property="og:image" content="http://premium.wpmudev.org/blog/wp-content/uploads/2014/12/plugin-creation.jpg"/>
view raw og-tags.html hosted with ❤ by GitHub
You can read all about Facebook Open Graph and Facebook Content Sharing Best Practices on the Facebook site.
For this project, we need to make sure that whenever a single blog article is shown, Open Graph tags are added to the header of our website. Site heads consists mostly of metadata and other hidden bits of information, and are added between the <head> and </head> tags in an HTML document.
The next part of this article will focus on getting this done. After this example, I’ll venture more deeply into plugin development territory.

Creating a New Plugin

The first thing you need to do is create a folder to store your plugin. Go to the wp-content/plugins/ directory in your WordPress installation and create a folder called my-facebook-tags. Keep in mind that whatever you name your plugin’s folder will be your plugin’s slug.
A plugin slug should be unique throughout the WordPress Plugin Repository if you want to upload it and make it publicly available. What this means is that no other plugin created by anyone else should have this slug. You can search for existing plugin slugs easily, just use Google!
Keep in mind that the plugin’s name is not necessarily the same as its slug. Take a look at the iThemes Security plugin. The last bit of the URL is the slug: better-wp-security. The name of the plugin, however, is iThemes Security.
If you’re just making a plugin for yourself it is still important to make sure slugs don’t clash. During the lifetime of your website you will probably use a number of plugins and you don’t want one to accidentally clash with yours and cause problems on your site because of a naming conflict.
Now that you have your my-facebook-tags folder, create a new file inside and name it my-facebook-tags.php. This will be your main plugin file and its name should be the same as your plugin’s slug, with the PHP extension tacked on.
Open your plugin’s main file and paste in the following code:
1 2 3 4 5 6 7 8 9 10
<?php
/**
* Plugin Name: My Facebook Tags
* Plugin URI: http://danielpataki.com
* Description: This plugin adds some Facebook Open Graph tags to our single posts.
* Version: 1.0.0
* Author: Daniel Pataki
* Author URI: http://danielpataki.com
* License: GPL2
*/
view raw basics.php hosted with ❤ by GitHub
This code is a PHP comment, which won’t be visible directly in the WordPress admin. WordPress does use the data within it to output the plugin’s name and some other data in the Plugins section of the backend. I’ve tailored this to my own website, so be sure to modify the plugin author and other strings as you see fit.
Once you’ve saved this file, congratulation are in order because you’re just create your first plugin! It does absolutely nothing, of course, but it should be available in the plugins section and you should be able to activate it – go ahead and do that now.

How Plugins Work

Let’s pause for a moment to look at how plugins work before we continue with our Facebook Open Graph project.
Plugins provide functionality with hooks, therefore understanding how they work is crucial. Let’s look at a real world analogue for hooks. You know those little diaries where the first sentence says: I am the diary of _________. The empty line is where you put your actual name.
The company could of course go through all the names and create prints of each one but it would not be economical and a lot of people would be left out. Also, what if you want to put “The Master Of The Galaxy” instead of your own name?
That blank line is a hook. Instead of being specifically printed for a person it prompts the user to add his/her own name. Hooks work something like this in WordPress, let’s look at an example.
Themes are required to add the following function to the header file: wp_head(). Within this function is a bit of code where WordPress says: If a plugin wants to put some code here they may do so. The wp_head hook allows us to output something in the head section of the page, which is exactly what we need. Let’s test this”
1 2 3 4
add_action( 'wp_head', 'my_facebook_tags' );
function my_facebook_tags() {
echo 'I am in the head section';
}
view raw testhook.php hosted with ❤ by GitHub
The first line of the snippet above tells WordPress that we would like to attach some functionality to the wp_head hook using the my_facebook_tags() function.
The second line of code creates that function and the third line echoes a simple string.
This should now be visible at the top of any theme you activate, as long as it defines that wp_head() function (defining it is a requirement). We’ll remove that echoed string soon since you should never display text in the head section.
For the sake of correctness let me mention two things. There are two types of hooks: actions and filters. In the case above we used an action which is obvious because we used the add_action() function. Actions run whenever WordPress detects the hook that calls them.
Filters are similar but they modify a bit of data which WordPress uses. A good example is the logout message that is shown. Instead of performing an action whenever a logout message is shown, a filter allows you to modify the logout message itself. We will not go into hooks in detail here. I recommend taking a look at our article, A Quick (and in-Depth) Guide to WordPress Hooks, or the WordPress Codex if you would like to learn more.
The last thing I want to mention here is that technically a hooked function gets executed when the do_action() or apply_filters() function is executed. The wp_head() function contains calls to these other functions within it – it is not the hook itself.

Completing Our Plugin

Based on the description above it’s pretty clear we need to add our Facebook meta tags using the wp_head hook.
Here’s the rest of the code needed for our plugin, followed by an explanation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
add_action( 'wp_head', 'my_facebook_tags' );
function my_facebook_tags() {
if( is_single() ) {
?>
<meta property="og:title" content="<?php the_title() ?>" />
<meta property="og:site_name" content="<?php bloginfo( 'name' ) ?>" />
<meta property="og:url" content="<?php the_permalink() ?>" />
<meta property="og:description" content="<?php the_excerpt() ?>" />
<meta property="og:type" content="article" />
<?php
if ( has_post_thumbnail() ) :
$image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' );
?>
<meta property="og:image" content="<?php echo $image[0]; ?>"/>
<?php endif; ?>
<?php
}
}
view raw my-facebook-tags.php hosted with ❤ by GitHub
I’ve basically pasted our meta tags into the function as-is. The only things I needed to modify were the values to make sure they reflected the currently shown post. I used the is_single() conditional tag to make sure that the tags are only added when a single post is shown.
In order to use the title, excerpt, image, etc of the current post I used template tags. The only bit of trickery I used was to check if the post has a featured image before displaying the Facebook tag for it.
With this single function in place we’ve created something quite useful. All of the posts on your website should now have Facebook-friendly tags. You can make sure they’re set up properly using the Open Graph Debugger.
And now our plugin is complete. Let’s now look at some other plugin concepts.

The Right Hook For The Right Plot

Now that you know how to add things to the head section of your website, let’s look at inserting elements into other parts of your site.
Using actions is pretty easy. If you want to perform an action whenever WordPress does something, you are looking for a hook.
What about loading Google Analytics tracking on each page? This should be done in the footer. Perhaps themes define something similar to wp_head? Indeed they do. Using wp_footer you can output code at the bottom of the page. WordPress itself uses these two hooks to place scripts and styles in their correct places.
So far this has been easy because these are hooks you can kind of see in the theme. But how about more “hidden” cases? What if you would like to send a post’s author an email once their post is published. This screams “action” because you are saying: When WordPress publishes a post, then do something.
Finding these hooks has become a lot easier these past years. They are usually well named: user_register, publish_post, profile_update, etc. If you type “add user WordPress hook” into Google you will likely stumble upon “user_register” immediately. From there it’s just a matter of reading documentation. Let’s use publish_post to send authors an email when their posts are published. Here’s our code:
1 2 3 4 5 6 7
add_action( 'publish_post', 'post_published_notification', 10, 2 );
function post_published_notification( $ID, $post ) {
$email = get_the_author_meta( 'user_email', $post->post_author );
$subject = 'Published ' . $post->post_title;
$message = 'We just published your post: ' . $post->post_title . ' take a look: ' . get_permalink( $ID );
wp_mail( $email, $subject, $message );
}
view raw publish_post.php hosted with ❤ by GitHub
Note that when I used the add_action() function I specified two additional parameters. The third parameter is the priority, which dictates when the action is executed. You may want to add multiple functions into the same hook and WordPress itself might use it too internally. The higher the priority, the later the action is performed.
The fourth parameter states how many arguments are passed to your functions. This is something you need to look up since it is not obvious from the name of the action. You can either look at WordPress documentation, or look into the WordPress source code to see where it is defined – the former is definitely easier if you’re just starting out.
Inside the function I use the attributes of the post to get the authors email address and the title and link to the post. I construct a short message and use WordPress’ built in mailing function  wp_mail() to shoot a quick email.
Again, how did I know this existed? Google! While it is entirely possible to write your own mailer function, a quick search for “WordPress mail” will reveal this function in a jiffy.

Getting Started With Filters

I mentioned earlier that filters are similar to hooks, but they allow you to modify data before it is used instead of implementing an additional action. For this example, let’s change the error message you get in the login form when you type an incorrect password at www.example.com/wp-admin
Since there is an error message regardless of our plugin – we just want to modify it – chances are we’re looking at a filter. There is indeed a filter named “login_errors” so let’s leverage it and modify the message:
1 2 3 4 5 6
add_filter('login_errors','login_error_message');
function login_error_message( $error ){
$error = "Incorrect login information, stay out!";
return $error;
}
view raw filters.php hosted with ❤ by GitHub
The first parameter of every function you add to a filter will always be the filtered data. If you return this without modifying it you will end up with the original functionality. In our case let’s always show the same error message. This can be useful if you want to hide the root of the error. If you enter a correct username but incorrect password WordPress actually tells you this, giving hackers a bit of information. By having a single error message this information is hidden.
Filters and actions are used extensively for almost everything in plugins so I urge you to take a look at them in depth and familiarize yourself with their mechanism. You can find out more at the WordPress Codex.

Adding Scripts And Styles

Chances are are that at some point you will want to add your own styling or JavaScript functionality. This can be done by enqueueing the asset in question. Enqueuing uses actions to add scripts and styles modularly, taking care of any dependencies in the process. Let’s add support for a Google Font, which is actually a stylesheet:
1 2 3 4 5
add_action( 'wp_enqueue_scripts', 'my_enqueued_assets' );
function my_enqueued_assets() {
wp_enqueue_style( 'my-font', '//fonts.googleapis.com/css?family=Roboto' );
}
view raw enqueue-simple.php hosted with ❤ by GitHub
The action we use is horribly named because wp_enqueue_scripts is actually used to add both scripts and styles to the front-end. In the hooked function we use wp_enqueue_style() to add our style. The first parameter is the slug or handle of the script (this is up to you), and the second parameter is the URL of the script.
Using //url.com instead of http://url.com is a neat trick which allows browsers to grab the appropriate version of the script. If your connection uses https it will retrieve the HTTPS version, otherwise it will use the regular HTTP version.
You can, of course, load assets you’ve made and store within your plugin. Let’s load a custom script we’ve made using the enqueueing method:
1 2 3 4 5
add_action( 'wp_enqueue_scripts', 'my_enqueued_assets' );
function my_enqueued_assets() {
wp_enqueue_script( 'my-script', plugin_dir_url( __FILE__ ) . '/js/my-script.js', array( 'jquery' ), '1.0', true );
}
view raw enqueue-script.php hosted with ❤ by GitHub
The process is much the same but I’ve used more parameters in the wp_enqueue_script() function. The third parameter defines the dependencies of the script. WordPress makes sure to load all the dependencies properly so even if you enqueue a dependency later they will be loaded correctly. The fourth parameter is a version number you can choose yourself. These additional parameters are available for the wp_enqueue_style() function as well.
The fifth parameter, when set to true, instructs WordPress to load a script in the footer instead of the header. This is preferred if your scripts aren’t needed in the header specifically as it decreases loading times and optimizes JavaScript.
To learn more about enqueueing take a look at our article on Adding Scripts And Styles To WordPress The Right Way.

Creating a Plugin Settings Page

Many plugins call for some options the user can set. Perhaps you want to disable Facebook Open Graph tags on some posts, or even disable the author email when you publish posts have you written? Both of these these can be implemented using options.
There are a number of ways to go about creating options for yourself, including some options frameworks out there. For simple options its easier to do it ourselves, and we are here to learn, so lets get started.
The best method to use is an object oriented approach, but I will use a simpler approach here. Take a look at the Creating Options Pages in the WordPress Codex for both the simpler and the object oriented approaches.
The first thing we’ll do is create a menu entry in the backend where we can place our settings user interface:
1 2 3 4 5 6 7 8 9
add_action('admin_menu', 'my_plugin_menu');
function my_plugin_menu() {
add_menu_page('My Plugin Settings', 'Plugin Settings', 'administrator', 'my-plugin-settings', 'my_plugin_settings_page', 'dashicons-admin-generic');
}
function my_plugin_settings_page() {
//
}
view raw settings-menu.php hosted with ❤ by GitHub
Note that we’re using an action – of course – to do this. Whenever WordPress sees the admin_menu hook it executes all functions tied to it. We happened to add a function to it ourselves so it will take that into account when building the menu.
We use add_menu_page() to create a top-level menu entry. This function takes a number of arguments:
  1. Page title – used in the title tag of the page (shown in the browser bar) when it is displayed.
  2. Menu title – used in the menu on the left.
  3. Capability – the user level allowed to access the page.
  4. Menu slug – the slug used for the page in the URL.
  5. Function – the name of the function you will be using to output the content of the page.
  6. Icon – A url to an image or a Dashicons string.
  7. Position – The position of your item within the whole menu.
I’ve created the empty function my_plugin_settings_page() (you’ll notice I added this as the fifth parameter). I’ll also add the content of this function in just a moment. At this stage you should be able to see the new menu entry at the bottom of the menu.
Before we create the user interface for manipulating settings, let’s let WordPress know what settings we intend to use. This is called registering our settings. For this example let’s presume we want to create a place to store the contact information of some key staffers who are not a part of our web project, for example our accountant.
1 2 3 4 5 6 7
add_action( 'admin_init', 'my_plugin_settings' );
function my_plugin_settings() {
register_setting( 'my-plugin-settings-group', 'accountant_name' );
register_setting( 'my-plugin-settings-group', 'accountant_phone' );
register_setting( 'my-plugin-settings-group', 'accountant_email' );
}
As you can see, I hook a function into admin_init, inside which I use register_setting() to add our options. The first parameter should be an option group, the second the actual option. I recommend using the same option group if you only have a few options.
So how in the World did I know that I need to use admin_init here? The WordPress Codex of course! In some cases the hook you need to use is obvious. In other cases you’ll need to look it up. In some cases you can use different hooks while retaining functionality. In these cases there is usually a recommended way of doing things. Always search in the Codex before you implement a hook and you’ll be just fine.
So now that we have our admin menu entry and we’ve registered our settings, let’s create a form to display the user interface. Paste the code below inside the empty my_plugin_settings_page() function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<div class="wrap">
<h2>Staff Details</h2>
 
<form method="post" action="options.php">
<?php settings_fields( 'my-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-plugin-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Accountant Name</th>
<td><input type="text" name="accountant_name" value="<?php echo esc_attr( get_option('accountant_name') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Accountant Phone Number</th>
<td><input type="text" name="accountant_phone" value="<?php echo esc_attr( get_option('accountant_phone') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Accountant Email</th>
<td><input type="text" name="accountant_email" value="<?php echo esc_attr( get_option('accountant_email') ); ?>" /></td>
</tr>
</table>
<?php submit_button(); ?>
 
</form>
</div>
view raw form.html hosted with ❤ by GitHub
There are three things to keep in mind when building a form like this:
  • Use the settings_fields() function, adding the option group as the first parameter. This outputs some hidden fields WordPress will use to save your data.
  • Use the option names you defined while registering them in the name parameter of the inputs.
  • Grab the value of a field using the get_option() function, passing it the option name as the first parameter
Settings Form
The settings form we created.
With that, you’re all done! WordPress takes care of saving everything since you are using the built-in Options API. Well done!

Enabling Translations

This is definitely not a priority when you’re creating plugins for yourself, but it is a good idea to get in the habit of translation readiness as it is good practice for any public plugin.
The basics are really very simple. Any time you output some text, wrap it in either the __() function or the _e() function. Use the former for returning the string, the later for echoing it. For example:
1
<h2><?php _e( 'Staff Details', 'my-staff-plugin' ) ?></h2>
The first argument of the function is the string to translate, the second is the text domain. This should be the same as your plugin slug.
By using these functions you will allow others to translate your plugin into their own language. This is a simple procedure that can help so many, so why not do it? There is a little more to it than these two functions, but by knowing only the above you are 99% of the way there.
To learn more about translating plugins take a look at our article How To Create A Translatable Theme Or Plugin.

Conclusion

There are tons and tons of things you can do with plugins and almost as many ways you can create them. While I am a very strong advocate of WordPress standards and doing things just right (object oriented approach, in many cases), I urge everyone to experiment.
As long as you’re not creating a product for distribution, feel free to do whatever you like. Don’t worry about complicating your life with methodologies you don’t yet understand. Do your best to research hooks that can help you add your functionality and make things work in whatever way you can.
The knowledge to do things right always comes to you after you are able to do things wrong, so don’t be too bothered about the rules for now.
Good luck with creating your own plugins!


How To Create A WordPress Plugin


How To Create A WordPress Plugin
WordPress Plugins allow users to easily modify, customize, and enhance any WordPress website. Instead of changing the core software WordPress is built on you can rather create a plugin to extend it. Using plugins allows you to have the most optimized WordPress installation all while maximizing how you use the software to begin with.
This article will walk you through the steps in creating a WordPress plugin.

What is a WordPress Plugin?

Here is the basic definition found on the WordPress Codex.
WordPress Plugin: A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

Creating a Plugin

When creating a WordPress plugin there are some standards to uphold to when doing so. Below I’ll outline some key points to remember when creating your own.

Plugin Name

If you’re planning on making a plugin that doesn’t exist yet you will need to first determine its name. To be extra sure you will want to do a search in the WordPress Plugin repository. Some developers choose a name that describes more of what the plugin does so the end user can establish a quick connection with the name. The name itself can be multiple words.

Plugin Files

Typically a plugin lives within its own folder under wp-content/plugins/ inside your WordPress installation. There is usually at least one PHP file that is typically named after the plugin. So if your plugin was named amazing-plug then your PHP file name would most likely be amazing-plug.php. Using a unique name is crucial so no two plugins use the same name.
You can also choose to split your plugin into multiple files; similar to the way WordPress is built. Assets such as images, CSS, and JavaScript are common to see within installed plugins.

Readme File

Readme files are useful for other developers and users. Usually these files give a quick description of the plugin as well as sometimes offer change logs which indicate previous updates and maintenance announcements to users.

Home Page

If you plan to share you plugin with the WordPress community, having a dedicated home page would be wise. This page can be used as a place to download the plugin, report bugs, and announce updates to your user community.

Standard Plugin File

A plugin must contain a bit of meta information which tells WordPress what it is and how to handle it within your website. Plugins can be installed, deleted, activated, and inactivated. A standard header is introduced below to establish your plugin’s presence. The parameters shown will tell WordPress how to optimize it within your website and WordPress admin area.
<?php
/**
* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12
*/
The minimum WordPress needs to establish your file as a plugin is the line
Plugin Name: My Plugin Name
The rest of the information will be displayed within the Admin area under the Plugins section.

Programming the Plugin

Now the time comes to create our own demo plugin. I’ll be working on a local copy of WordPress using the our Divi 2.0 theme. You can follow along whichever method you prefer but to limit any downtime on your website I suggest you work locally or on a testing server. Our blog features other posts about installing WordPress locally if you are new to the concept. Find the links below depending on your platform.
Links:
For this tutorial I will be creating a plugin that creates a custom post type for our blog as well as establishes some other custom parameters. This plugin will be useful because we will be able to use it among any theme rather than just modifying one.

Plugin Scope

Our plugin will start with a simple PHP file. We will call this file custom-music-reviews.php. Within our file we will create a custom post type as well as define some new categories within that post type. The purpose of this plugin will be to write music reviews within specific genres without needing to touch code in the future. Each review will have a feature image, excerpt, rating, and genre type.

Starting Off

Assuming you have a local copy of WordPress ready to use, navigate to your wp-content folder inside of a code editor of your choice. Inside that folder you should see a folder called plugins. Inside of that folder create a new folder called custom-music-reviews.
With the folder created create a new file inside it called custom-music-reviews.php.
The path to the file should now be wp-content/plugins/custom-music-reviews/custom-music-reviews.php.
With your new file created we need to add some parameters in comment form like I explained earlier. For our plugin our parameters will look like this:
<?php
/**
* Plugin Name: Custom Music Reviews
* Plugin URI: http://elegantthemes.com/
* Description: A custom music review plugin built for example.
* Version: 1.0
* Author: Andy Leverenz
* Author URI: http://justalever.com/
**/
With this information added, save your file and navigate to your WordPress admin area. Click on Plugins on the left side navigation and you should now see our plugin available. Wasn’t that easy?
plugin-available
With our parameters in place our plugin becomes available to activate under “Installed Plugins”.
Even though our file is empty we can go ahead and activate the plugin. Go ahead and do that now. You’ll hopefully notice nothing different about your site with the plugin activate. If you do you probably typed the content above wrong or failed to close the comment.

Adding Our Plugin Code

With our file all set up and plugin active we can now add the inner workings of the plugin which we will be using for this tutorial.
Add the code below:
// Register the Custom Music Review Post Type
 
function register_cpt_music_review() {
 
    $labels = array(
        'name' => _x( 'Music Reviews', 'music_review' ),
        'singular_name' => _x( 'Music Review', 'music_review' ),
        'add_new' => _x( 'Add New', 'music_review' ),
        'add_new_item' => _x( 'Add New Music Review', 'music_review' ),
        'edit_item' => _x( 'Edit Music Review', 'music_review' ),
        'new_item' => _x( 'New Music Review', 'music_review' ),
        'view_item' => _x( 'View Music Review', 'music_review' ),
        'search_items' => _x( 'Search Music Reviews', 'music_review' ),
        'not_found' => _x( 'No music reviews found', 'music_review' ),
        'not_found_in_trash' => _x( 'No music reviews found in Trash', 'music_review' ),
        'parent_item_colon' => _x( 'Parent Music Review:', 'music_review' ),
        'menu_name' => _x( 'Music Reviews', 'music_review' ),
    );
 
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'Music reviews filterable by genre',
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ),
        'taxonomies' => array( 'genres' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-format-audio',
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );
 
    register_post_type( 'music_review', $args );
}
 
add_action( 'init', 'register_cpt_music_review' );
This code above may look like a lot and almost seem like an unknown language to you if you’re new to WordPress but if not you’ll recognize this code as a Custom Post Type. In this case our custom post type is called music_review. The code is essentially telling WordPress to establish a new type of post within your theme. The post type has parameters that go along with it such as labels, arguments, and more. I won’t go into a ton of detail on how Custom Post Types work because I’ve already covered it within another article on Elegant Themes. Be sure to read it to gain a full understanding.
With our post type set up you can already see it active within the WordPress admin area.
Our custom post type is successfully implemented.
Lets take things one set further and include a custom Taxonomy called Genre inside our plugin. Think of a Taxonomy as a type of categorizing feature that is completely custom. WordPress already includes Categories and Tag support by default but developers can create custom taxonomies to extend their themes or plugins even further.
Read more about WordPress Taxonomies here.
Add the code below under the custom post type function we just added.
function genres_taxonomy() {
    register_taxonomy(
        'genres',
        'music_review',
        array(
            'hierarchical' => true,
            'label' => 'Genres',
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'genre',
                'with_front' => false
            )
        )
    );
}
add_action( 'init', 'genres_taxonomy');
Registering a new Taxonomy is relatively easy. We have made the connection to our custom post type by using the
register_taxonomy() function which creates a new taxonomy called genres and assigns it to our post type music_review.
We need to add one more line to our custom post type to make everything sync up. Add this code just below the supports argument within the custom post type.
Here’s all our plugin code up until this point. For better legibility I’ve stripped our code of any comments we had prior to this.
function register_cpt_music_review() {
 
    $labels = array(
        'name' => _x( 'Music Reviews', 'music_review' ),
        'singular_name' => _x( 'Music Review', 'music_review' ),
        'add_new' => _x( 'Add New', 'music_review' ),
        'add_new_item' => _x( 'Add New Music Review', 'music_review' ),
        'edit_item' => _x( 'Edit Music Review', 'music_review' ),
        'new_item' => _x( 'New Music Review', 'music_review' ),
        'view_item' => _x( 'View Music Review', 'music_review' ),
        'search_items' => _x( 'Search Music Reviews', 'music_review' ),
        'not_found' => _x( 'No music reviews found', 'music_review' ),
        'not_found_in_trash' => _x( 'No music reviews found in Trash', 'music_review' ),
        'parent_item_colon' => _x( 'Parent Music Review:', 'music_review' ),
        'menu_name' => _x( 'Music Reviews', 'music_review' ),
    );
 
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'Music reviews filterable by genre',
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ),
        'taxonomies' => array( 'genres' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-format-audio',
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );
 
    register_post_type( 'music_review', $args );
}
 
add_action( 'init', 'register_cpt_music_review' );
 
function genres_taxonomy() {
    register_taxonomy(
        'genres',
        'music_review',
        array(
            'hierarchical' => true,
            'label' => 'Genres',
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'genre',
                'with_front' => false
            )
        )
    );
}
add_action( 'init', 'genres_taxonomy');
The only line that changed was the 'taxonomies' => array('genre') line within our custom post type. I added this line to tell our custom post type to connect to our new taxonomy and use it instead of the default category or tag structure WordPress comes installed with.
If you’ve made it this far you can now visit your WordPress admin area and see your new custom post type and taxonomy(Genres) present. Congrats!
custom-pt-and-tax-available
Our custom post type and taxonomy are successfully implemented. Here we can add a new Music Review which contains various types of genres decided upon by the user.

Getting Our Code To Output

Below I’ll try adding a new music review. You should see the new Genres section that we set up with our custom Taxonomy. With some data entered I’ll publish the post.
new-music-review
Create a new music review as an example.
At this point we have our functionality set up within our plugin.
In order to make things effortless we will rely on the plugin to create a new page called Music Reviews. The page will be referenced by our plugin and output any new music reviews the user posts. We are doing this so the user doesn’t have to edit a single line of code.

Tying it All Together

Our code now works but we should create a page that will use
// Function used to automatically create Music Reviews page.
function create_music_review_pages()
  {
   //post status and options
    $post = array(
          'comment_status' => 'open',
          'ping_status' =>  'closed' ,
          'post_date' => date('Y-m-d H:i:s'),
          'post_name' => 'music_review',
          'post_status' => 'publish' ,
          'post_title' => 'Music Reviews',
          'post_type' => 'page',
    );
    //insert page and save the id
    $newvalue = wp_insert_post( $post, false );
    //save the id in the database
    update_option( 'mrpage', $newvalue );
  }
And finally we need to create our Music Reviews page once the plugin is activated. Adding the code below initiates the function we just wrote above ( function create_music_review_pages(){…}).
// // Activates function if plugin is activated
register_activation_hook( __FILE__, 'create_music_review_pages');

Testing

Our plugin should be ready to test at this point. Lets create an example music review and see what outputs.
new-music-review-test
Create another music review to verify our plugin is working correctly.
If you click View Music Review once the post is published you should be taken to a screen which looks similar to the image below. Your theme and styles may vary…
the-single-review
The single page music review template
You may notice that I modified the menu to include our new Music Reviews page. Doing this gives us easy access.
adjust-menu
Adjusting primary navigation to include “Music Reviews” page
With your menu in place and saved click on Music Reviews to see all the posts we have made so far.
Based on the page template supplied by your theme the Music Review should output all together and be clickable through to the single review template. You will probably notice that the music review I posted earlier has output as well as the one we just created.
music-reviews-list
Our music reviews on the “Music Review” page
Our feature image, title, genre, and review all have posted successfully. Our plugin works!
To verify, you can deactivate the plugin and reinstall it or activate it. Upon doing so a new Page called Music Reviews should be created. You can delete or reuse the one from before if there are duplicates but there should be only one “Music Reviews” page. We could have added a function to delete and restore this page within our plugin but I wanted to keep things as simple as possible.

Finish

Our plugin is a relatively simple one. You can extend it so much further by including it’s own predefined templates, custom widgets, more taxonomies and so much more. Creating a plugin is no easy feat. You will want to plan your plugin before even moving to development. Knowing what you can an can’t do with WordPress before coding your own plugin is a crucial step to developing a quality one. The plugin create in this tutorial is meant to teach by example. There are better standards to follow and more useful practices to endure. Be sure to read the WordPress Codex and get familiar with the WordPress Plugin API. If a plugin isn’t out there and you need custom functionality for your website then I stronger encourage trying to create your own!




Como crear tarjetas Virtuales Visa o MasterCard con tu divisa y las ventajas que ofrecen

Hoy día, gracias al creciente mundo del Internet se le ha permitido a cada persona poder acceder a muchos productos o servicios. Y en estos ...