Showing posts with label WordPress. Show all posts
Showing posts with label WordPress. Show all posts

Create a Custom Action Hook Wordpress

The Codex says:
Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:
  1. Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.
  2. Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.
Action hooks are triggered by events in WordPress and are providedby scores – and every time a hook is triggered all functions (callbacks) you or anybody else attached to it are executed automagically.
There’s no magic really. All available hooks are stored in a global variable called $wp_filter, a PHP associative array that has hook names for keys.
You hook your functions to an action using add_action()  - add_action() adds your function name to the $wp_filter element with the key that is equal to the hook name you specified. If such an element does not exist it is created – added to $wp_filter.
Your functions attached to a hook are executed when you call do_action(‘action_name_here’). do_action() checks $wp_filter for ‘action_name_here’ and executes all functions attached to it, if any.
This allows you to create your own custom action hooks in two and a half easy steps, as seen below (somewhere in my theme’s functions.php):
<?php

/* a custom action hook */

/*
 * 1. Create your own custom action hook named 'the_action_hook'
 *    with just a line of code. Yes, it's that simple.
 *    
 *    The first argument to add_action() is your action hook name
 *    and the second argument is the name of the function that actually gets
 *    executed (that's 'callback function' in geek).
 *
 *    In this case you create an action hook named 'the_action_hook'
 *    and the callback function is 'the_action_callback'.
 */

add_action('the_action_hook', 'the_action_callback');

/*
 * 2. Declare the callback function. It prints a sentence.
 *    Note that there is no return value.
 */

function the_action_callback()
{
echo '<p>WordPress is nice!</p>';
}

/*
 * 3. When you call do_action() with your action hook name
 *    as the argument, all functions hooked to it with add_action()
 *    (see step 1. above) get are executed - in this case there is
 *    only one, the_action_callback(), but you can attach as many functions
 *    to your hook as you like.
 *
 *    In this step we wrap our do_action() in yet another
 *    function, the_action(). You can actually skip this step and just
 *    call do_action() from your code.
 */

function the_action()
{
do_action('the_action_hook');
}

?>
and execute them (my theme’s index.php):
<!DOCTYPE html>

<html>
<head>
<title><?php bloginfo('name'); ?></title>
<link rel="stylesheet" type="text/css" media="all"
href="&lt;?php bloginfo( 'stylesheet_url' ); ?>" />
<?php wp_head(); ?>
</head>
<body>
<div>
<div>
<h1><a href="&lt;?php echo esc_url( home_url( '/' ) ); ?>">
<?php blogInfo( 'name' ); ?></a></h1>
</div>
<div>
<?php if(have_posts()): while(have_posts()): the_post();?>
<h2><a href="&lt;?php the_permalink() ?>"><?php the_title() ?></a></h2>
<div>
<?php the_content(); ?>
<!-- Yay! this line should print 'WordPress is nice!'
                             after all your posts. -->
<?php the_action(); ?>
<!-- This line should also print 'WordPress is nice!'.
                             This time no wrapper function for do_action(). -->
<?php do_action('the_action_hook'); ?>
</div>
<?php endwhile; endif; ?>
<?php wp_footer(); ?>
</div>
<div>
<?php get_sidebar(); ?>
</div>
</div>
</body>
</html>
Continue Reading

Right Way Of Using WordPress Homepage Conditionals

WordPress is a terrific CMS. You can do whatever you want with it. But sometimes, you may find an issue with some basic functions. For example, you are probably using the is_front_page and is_home WordPress Homepage conditional in your themes and plugins (you can learn more about conditional functions in our Conditional Tags post). But you’re doing it wrong !

Homepage Settings

With those conditional functions, you can check if the homepage is being displayed (is_home), or if the homepage is using a static page (is_front_page). You can define such behaviour in Settings=> Reading.

In your plugin or theme, you may use this functions to display or change contents depending on user settings. But you are doing a huge mistake : you are not taking into account the static blog page. When you define a static page for your homepage, you can also define a blog page : it will replace the default WordPress homepage in order to list every post.
Long story made short : is_front_page should always be tested with and before is_home. And here’s why.

How It Works

1. Normal settings:
The default WordPress homepage lists your latest posts.
  • Here is the URL : website.com
  • is_home returns TRUE
  • is_front_page returns TRUE
Here, there isn’t any issue.
2. Static homepage:
The homepage is using one of your static pages.
  • The URL is still website.com
  • is_home returns FALSE
  • is_front_page returns TRUE
There is no issue with your static homepage : is_front_page returns true.
3. Static blog page
One of your page is listing all your post.
  • The URL is website.com/pagename
  • is_home : TRUE
  • is_front_page : FALSE
Here, you may have some problems : is_home is returning TRUE, but this is not your homepage : it’s a WordPress page that lists every post, like a main category archive would do.

Use Conditional Tags

When you create a plugin or a theme, you have to consider that users may use those page settings. So, every time you use is_home, you should always test is_front_page before, and you always should use conditional parameters to do so.
If you don’t, you may have problems with some users. For example, if you only test is_home to display your homepage content, there will be issues with the static homepage that will not display the right content.
Here is how to do it right :
if ( is_front_page() && is_home() ){
	// Default homepage
} elseif ( is_front_page()){
	//Static homepage
} elseif ( is_home()){
	//Blog page
} else {
	//everything else
}
This is the only (right) way to display or alter content with your homepage and your blog page.

How About You?

Did you already encounter this problem? What was your solution? I want to hear about it!
Continue Reading

List Of All WordPress Conditional Tags

We all use conditional statements in our developments under WordPress, right? But do you know all built-in WordPress conditional tags? They are simply great because thanks to these tags it’s very easy to create conditional statements. You can for example display content only for some users, or load scripts only if a page is using a specific custom template, or even styling a post if this post is sticky.
Conditional tags can be used in your themes or in your plugins, it doesn’t matter, but note that in some plugins it will be sometimes a bit tricky to use some tags (in fact all themes specific tags).

Available conditional tags

Here is the list of available conditional functions:
You probably know some of them, but do you really know the difference between is_single_() and is_singular() ? Or between id_day() and is_date() ? Did you know is_preview() ? To understand how each function works, simply click on the tag name, and read carefully the instructions in the codex.

All conditional tags return TRUE or FALSE

Conditional tags are one of my favorite WordPress built-in feature and i really encourage you to use them widely in your codes. All functions always return TRUE or FALSE, never IDs or array().

A close relation with templates hierarchy

As you might know, WordPress uses a really powerful template hierarchy system. Well, the use of conditional tags are closely related to this hierarchy. This is the principle used to select the template page to use depending on the URL you are visiting.

Conditional tags accept many arguments

When using these conditional tags you have to know that you can pass them different variables such as IDs, slug, or arrays. Here is is an example taken from the codex with the is_author() function:
is_author() 
When any Author page is being displayed.
is_author( '4' ) 
When the archive page for Author number (ID) 4 is being displayed.
is_author( 'Vivian' ) 
When the archive page for the Author with Nickname “Vivian” is being displayed.
is_author( 'john-jones' ) 
When the archive page for the Author with Nicename “john-jones” is being displayed.
is_author( array( 4, 'john-jones', 'Vivian' ) ) 
When the archive page for the author is either user ID 4, or user_nicename “john-jones”, or nickname “Vivian”.

Examples

This is how nearly all conditional functions work but you can of course combine many conditions:
if ( is_home() && in_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) ) ) {
   the_content();
}
else {
   the_excerpt();
}
or you can do an action if a situation or another occurs:
if ( is_home() || in_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) ) ) {
   the_content();
}
else {
   the_excerpt();
}
And if you want to do a negative condition, use ” ! “:
$paged = $wp_query->get( 'page' );

if ( ! $paged || $paged < 2 ) 
{
    // This is not a paginated page (or it's simply the first page of a paginated page/post)
} 
else 
{
   // This is a paginated page.
}
And finally, using conditional tags is like any other “else if” PHP statement:
if ( is_page( 'about' ) || '2' == $post->post_parent ) {    
    // the page is "About", or the parent of the page is "About"
    $bannerimg = 'about.jpg';

} elseif ( is_page( 'learning' ) || '56' == $post->post_parent ) {	
    $bannerimg = 'teaching.jpg';

} elseif ( is_page( 'admissions' ) || '15' == $post->post_parent ) { 
    $bannerimg = 'admissions.jpg';

} else { 
    $bannerimg = 'home.jpg'; // just in case we are at an unclassified page, perhaps the home page
}	

Creating custom conditional tags

In some cases you need to create your custom conditional functions. That’s pretty easy to do, but very often functions names aren’t following the same logic as the one used by core developers. Please use the same naming convention using prefix such as “is_“, “has_“, “in_“. This is very helpful in particular if you’re not the only person to work on a specific script.
Continue Reading

Plugin Shortcode Conflicts in WordPress

We all have experienced this: you buy a premium theme that is really great, and you also buy an amazing plugin (one of mine for example!) but putting the theme and the plugin together just doesn’t work at all. So what? Is the plugin or the theme having bugs?
Most part of the time, when this happens it’s when you are using shortcodes. Let’s imagine you just bought a plugin to handle “testimonials”. You read carefully the documentation and you know that to display the testimonials you need to include the following shortcode [testimonials]. But when you do so, nothing appears.
The reason why the shortcode isn’t replaced by testimonials, is because your theme AND the plugin define the same exact shortcode.
As plugins files are loaded before themes files they are overwritten and not fully taken into account in this case.
That’s why i wanted to show you a simple method to deregister the theme shortcode and replace it by the plugin’s one.

Step 1: Create A Simple Plugin

We need to create a simple plugin:
<?php
/*
Plugin Name: Avoid Shortcodes conflicts
Plugin URL: http://remicorson.com
Description: A little plugin to avoid conflicts bewteen shortcodes
Version: 1.0
Author: Remi Corson
Author URI: http://remicorson.com
Contributors: corsonr
Text Domain: rc_asc
Domain Path: languages
*/

Step 2: Check If The Shortcode Exists

This is the most important step. It’s where you check for the existence of a shortcode. WordPress has a “$shortcode_tags” global variable that store the list of all registered shortcodes. So, we just need to go through this variable and check if the shortcode we are looking for makes part of it.
/**
 * Check if a shortcode is already registered
 *
 * @since 1.0
 *
 * @param $shortcode string The shortcode slug to test
 *
 * @return void
 */
function rc_asc_shortcode_exists( $shortcode = false ) {
	
	global $shortcode_tags;

	//echo '<pre>'; var_dump($shortcode_tags); echo '</pre>';
 
	if ( ! $shortcode )
		return false;
 
	if ( array_key_exists( $shortcode, $shortcode_tags ) )
		return true;
 
	return false;

}
This is the generic function that we will use in a more specific function including the shortcode slug to look for. This function returns TRUE if the shortcode exists, or FALSE if it doesn’t.

Step 3: Remove The Shortcode & Register The New One

The next function is using the rc_asc_shortcode_exists() we just created. It simply check for the existence of the shortcode, replaces it if it exists, or add the shortcode if it’s not already registered.
/**
 * Check if a shortcode is already registered and replace it
 *
 * @since 1.0
 *
 * @return void
 */
function rc_asc_replace_shortcode() {

	$shortcode = 'testimonials';
	
	if( rc_asc_shortcode_exists( $shortcode ) ) {
		remove_shortcode( $shortcode );
		add_shortcode( $shortcode, 'my_testimonials_function' );
	} else {
		add_shortcode( $shortcode, 'my_testimonials_function' );
	}
}

Step 4: Define The New Shortcode Function

All you have to do is to define the content of the “my_testimonials_shortcode()” function, and you’re done!
/**
 * Creates the new shortcode
 *
 * @since 1.0
 *
 * @return void
 */
function my_testimonials_function() {

	return 'this replaces the previous shortcode!';
}
As you can see the previously declared shortcode is now replaced by the right shortcode.
Continue Reading

Override WordPress Core Functions

Have you ever heard of WordPress Pluggable Functions? If not, then this article should draw your attention. In two words pluggable functions are WordPress core functions that you can override. All these functions are located into one single file:
wp-includes/pluggable.php“. Pluggable functions were introduced in WordPress 1.5.1, but in the most recent versions of WordPress this method isn’t used anymore. Recent functions now use filters on their output. But you can still override pluggable functions, and this is what I would like to cover in this post.

Which Functions?

Pluggable functions are:
You can click on the each function’s name to access its codex page.

How to Override Pluggable Functions

Well this is pretty simple, all you have to do is to create a file within your plugins containing an “if ( !function_exists() )…” statement and then re-define the function. I strongly recommend you to copy and paste the original function when you start. This is way you’re sure that the function will work. Here is an empty example:
if ( ! function_exists('wp_notify_postauthor') ) :
/**
 * Notify an author of a comment/trackback/pingback to one of their posts.
 *
 * @since 1.0.0
 *
 * @param int $comment_id Comment ID
 * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
 * @return bool False if user email does not exist. True on completion.
 */
function wp_notify_postauthor( $comment_id, $comment_type = '' ) {

/* This is where you redefine the function */

}
endif;
I’d like to talk about the “wp_notify_postauthor()” function. This is the one responsible of sending an email to post’s authors when a new comment is added. In one of my plugin, the WordPress Issues Manager, i needed to disable this notification, but a specific custom post type only. So, i copied the whole function, and simply added this:
if ( ! function_exists('wp_notify_postauthor') ) :
/**
 * Notify an author of a comment/trackback/pingback to one of their posts.
 *
 * @since 1.0.0
 *
 * @param int $comment_id Comment ID
 * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
 * @return bool False if user email does not exist. True on completion.
 */
function wp_notify_postauthor( $comment_id, $comment_type = '' ) {

if( $post-&gt;post_type != 'issue'):

/* content of the original function */

endif;

}
endif;
That’s simple, but that works great without having to make huge changes or to create a full custom function hooked to a custom action.

wp_mail()

As you saw in the pluggable functions list, wp_mail() is a pluggable function. This function is the one used for sending emails. Anywhere in WordPress when an email is sent it uses this function. That’s why customizing it can be very interesting. For example you could use an html default template for all emails sent from your WordPress install.
You could also send an hidden copy of every message to a specific email to have a kind of backup (trust me this can be useful when someone tells you he did not receive the message!).

wp_authenticate()

You could also modify wp_authenticate() and add some extra parameters to enforce security on your site (brute force attacks for example).

auth_redirect()

This function is the one that checks if a user is logged in, and if not it redirects them to the login page. That would be pretty easy to override the function and redirect the user to a custom page, instead of the default login page (for example if you want to hide the wp-admin folder).

wp_generate_password()

This function is the one that auto-generates passwords. Honestly you don’t really need to modify it, but now that you know what brute force attacks are, you could be interested in creating stronger passwords. Well, this is the function to improve.

Conclusion

To conclude this short post about WordPress pluggable functions, I’d like to point the fact that new functions don’t work like that anymore. As I wrote above they are now using filters. But pluggable functions are important functions in particular when creating really specific plugins. But be careful when using pluggable functions. If the newly created function isn’t working perfectly it can break a part of your website (in terms of functionality), so please test them in all conditions.
Continue Reading

How To Create A WordPress Custom Dashboard Page


A few days ago, i have been asked to create a custom WordPress dashboard to replace the orginial one. It wasn’t just displaying or hiding already custom metaboxes, it was replacing the whole dashboard. This was the first time i was asked to do something like that, so it was pretty challenging. As always, in this case, i looked over the internet to see if something similar had already been done. and once again, no result. I don’t know if i’m bad in asking Google specific stuff, or if most WordPress tutorials treat about the same subjects, but i coudn’t find anything.
Then, i remember, that since WordPress 3.x, there’s a new page once we login for the first time after an update. This is more or less what i wanted to do.
After a quick search in WordPress core files, i found really great stuff. And finally, i managed to create a whole custom dashboard in the WordPress style. To do so, once again i created a plugin.

Step 1: the plugin creation

If you read my previous posts on WPexplorer you should now know about to create a plugin, but here is a reminder.
Open the plugins folder under wp-content, and create a new repository called «sweet-custom-dashboard», and inside this folder create a new file called «sweet-custom-dashboard.php». Then open the file.
To declare the plugin, simply add this code to the file:
<?php
/*
Plugin Name: Sweet Custom Dashboard
Plugin URL: http://remicorson.com/sweet-custom-dashboard Description: A nice plugin to create your custom dashboard page
Version: 0.1
Author: Remi Corson
Author URI: http://remicorson.com Contributors: corsonr
Text Domain: rc_scd
*/
Only by adding this code, you already created a plugin, an empty plugin, but a working plugin!
Now, we need to define a constant for the plugin URL, we’ll need later. Add this code:
/*
|--------------------------------------------------------------------------
| CONSTANTS
|--------------------------------------------------------------------------
*/
// plugin folder url
if(!defined('RC_SCD_PLUGIN_URL')) {
define('RC_SCD_PLUGIN_URL', plugin_dir_url( __FILE__ ));
}
It’s now time to create the main class of our plugin:
/*
|--------------------------------------------------------------------------
| MAIN CLASS
|--------------------------------------------------------------------------
*/

class rc_sweet_custom_dashboard {

 /*--------------------------------------------*
  * Constructor
  *--------------------------------------------*/

 /**
  * Initializes the plugin
  */
 function __construct() {

 } // end constructor

}

// instantiate plugin's class
$GLOBALS['sweet_custom_dashboard'] = new rc_sweet_custom_dashboard();

Step 2: The constructor

In step two, we need to add an action that will occur only if the user is on the dashboard page. To do so, replace the constructore function by this code:
function __construct() {

 add_action('admin_menu', array( &$this,'rc_scd_register_menu') );
 add_action('load-index.php', array( &$this,'rc_scd_redirect_dashboard') );

} // end constructor
By adding this code, we’re telling WordPress that we want to load the rc_get_screen() function when index.php is loaded (index.php is the dashboard page). We are also telling WordPress to register a new dashboard page. The one we’ll use in the redirection. Next step is the construction of the rc_redirect_dashboard() function.

Step 3: the dashboard redirection

The rc_redirect_dashboard() function is pretty simple. Its aim is to redirect the user to a custom page when he wants to access the default dashboard. To do this, we have to check if we are on the right screen (read «page») using the get_current_screen() function. When this function called from the ‘admin_init’ hook it returns NULL, that’s in part why i hooked the rc_dashboard_redirection() to «load-index.php». Here is the function’s content:
function rc_scd_redirect_dashboard() {

 if( is_admin() ) {
  $screen = get_current_screen();
  
  if( $screen->base == 'dashboard' ) {

   wp_redirect( admin_url( 'index.php?page=custom-dashboard' ) );
   
  }
 }

}
This code is prtty understandable, if we are in the admin, and if the current screen is «dashboard» then we force a redirection to a file called «custom_dashboard.php».

Registering the dashboard page

It’s now time to register the new dashboard page. To do this, we need to add two functions: one to register the page in the WordPress menu and one to fill in the content page:
function rc_scd_register_menu() {
 add_dashboard_page( 'Custom Dashboard', 'Custom Dashboard', 'read', 'custom-dashboard', array( &$this,'rc_scd_create_dashboard') );
}

function rc_scd_create_dashboard() {
 include_once( 'custom_dashboard.php'  );
}
If you saved the file, activate the plugin and try to access the dashboard, you should see a blank page or a 404 message. We can create our custom dashboard.

Step 4: The custom dashboard creation

When i created this plugin, i wanted the new dashboard to be in the WordPress style, that’s why my starting point was, the page that you see when you login for the first time afte a core update. I went through the code of this page to find inspiration.
To start, create a new file called «custom_dashboard.php» in your sweet-custom-dashboard folder. Open it and add this code:
<?php
/**
 * Our custom dashboard page
 */

/** WordPress Administration Bootstrap */
require_once( ABSPATH . 'wp-load.php' );
require_once( ABSPATH . 'wp-admin/admin.php' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
The first require_once() fucntion, loads WordPress, by adding this simple line, you are now able to use any WordPress variables or any functions.
The two other require_once() load needed filed to display properly the administration.
All we have to now is to create the content of our custom dashboard. The code below is inspired by the file mentioned previously that’s why you’ll maybe need to adjust it a bit to fit your needs. In my example i just want a menu with 3 links that will be displayed as tabs, and two paragraphs, once including an image. Here is the code:
<div class="wrap about-wrap">
<h1><?php _e( 'Welcome to My Custom Dashboard Page' ); ?></h1>

 <div class="about-text">
 <?php _e('Donec id elit non mi porta gravida at eget metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.' ); ?>
 </div>

 <h2 class="nav-tab-wrapper">
 <a href="#" class="nav-tab nav-tab-active">
 <?php _e( 'Step 1' ); ?>
 </a><a href="#" class="nav-tab">
 <?php _e( 'Step 2' ); ?>
 </a><a href="#" class="nav-tab">
 <?php _e( 'Step 3' ); ?>
 </a>
 </h2>

 <div class="changelog">
 <h3><?php _e( 'Morbi leo risus, porta ac consectetur' ); ?></h3>

 <div class="feature-section images-stagger-right">
 <img src="<?php echo esc_url( admin_url( 'images/screenshots/theme-customizer.png' ) ); ?>" class="image-50" />
 <h4><?php _e( 'Risus Consectetur Elit Sollicitudin' ); ?></h4>
 <p><?php _e( 'Cras mattis consectetur purus sit amet fermentum. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Vestibulum id ligula porta felis euismod semper. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui.' ); ?></p>

 <h4><?php _e( 'Mattis Justo Purus' ); ?></h4>
 <p><?php _e( 'Aenean lacinia bibendum nulla sed consectetur. Donec id elit non mi porta gravida at eget metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id ligula porta felis euismod semper. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.
Cras mattis consectetur purus sit amet fermentum. Maecenas faucibus mollis interdum. Etiam porta sem malesuada magna mollis euismod. Maecenas faucibus mollis interdum. Curabitur blandit tempus porttitor. Cras justo odio, dapibus ac facilisis in, egestas eget quam.' ); ?></p>
 </div>
 </div>
</div>
Nothing really interesting in this code, it’s just HTML code.
And finally, we have to load the WordPress administration footer. To do so, just this line at the bottom of the file:
<?php include( ABSPATH . 'wp-admin/admin-footer.php' );
And… that’s it ! The plugin is now working great, there’s of course many many ways to make it better, for example you could add custom stylesheets and custom javascript files, or you could add some extra verification to display the custom dashboard to some user roles only…
Well, i hope you enjoyed this tutorial, and i am looking forward to read your comments in the comments section!
One more thing, there’s an already compiled version of the plugin on the official WordPress plugins repositoryn click here to download it.
Continue Reading