Static Page, slider and Quote on Homepage Wordpress

With this tweak it is possible to show the slider and the quote on your homepage using a static page in fontpage settings.
For this purpose I created a new homepage template
(home2.php), which you can use to design a static homepage with slider and quote; just choose "Homepage Version 2" as the template for your new homepage.

How to?

  1. copy the pink code below to a new text-file, save it and rename it to home2.php
  2. copy home2.php using ftp into your themes/chameleon folder of your Wordpress installation) if you're using a child theme copy it into your child theme's folder
  3. Create a new page, name it "Static Homepage" (the name does not matter since it will not be shown on the homepage), design it and for the page template select "Homepage Version 2" in the drop-down menu
  4. In Chameleon options select the images for your slider and fill in the text for the quote which actually will be used as the main header (h1) of the homepage
  5. In Wordpress - Settings - Reading select your new page as a static frontpage
  6. Add the css-code (at the end of this post) to your custom-css field in the Chameleon options panel or to your child theme's style.css.

<?php
/*
Template Name: Homepage Version 2
*/
?>
<?php get_header(); ?>

<?php if ( get_option('chameleon_featured') == 'on' ) get_template_part('includes/featured'); ?>

<?php if ( get_option('chameleon_quote') == 'on' ) { ?>
    <div id="fronthead">
        <div id="fronthead-inner">
        <?php if ( get_option('chameleon_quote_one') <> '' ) { ?>
            <h1><?php echo (get_option('chameleon_quote_one')); ?></h1>
        <?php } ?>
        <?php if ( get_option('chameleon_quote_two') <> '' ) { ?>
            <p><?php echo (get_option('chameleon_quote_two')); ?></p>
        <?php } ?>
        </div>
    </div> <!-- end .category-name -->
<?php } ?>

<div id="content" class="clearfix">
    <div id="left-area">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div class="entry post clearfix">
            <?php if (get_option('chameleon_page_thumbnails') == 'on') { ?>
                <?php
                    $thumb = '';
                    $width = 186;
                    $height = 186;
                    $classtext = 'post-thumb';
                    $titletext = get_the_title();
                    $thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Entry');
                    $thumb = $thumbnail["thumb"];
                ?>

                <?php if($thumb <> '') { ?>
                    <div class="post-thumbnail">
                        <?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>
                        <span class="post-overlay"></span>
                    </div>     <!-- end .post-thumbnail -->
                <?php } ?>
            <?php } ?>

            <?php the_content(); ?>
            <?php wp_link_pages(array('before' => '<p><strong>'.esc_html__('Pages','Chameleon').':</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>
            <?php edit_post_link(esc_html__('Edit this page','Chameleon')); ?>
        </div> <!-- end .entry -->

        <?php if (get_option('chameleon_show_pagescomments') == 'on') comments_template('', true); ?>
    <?php endwhile; endif; ?>
    </div>     <!-- end #left-area -->

    <?php get_sidebar(); ?>
</div> <!-- end #content -->

<?php get_footer(); ?>


css-code to add:  

#fronthead {text-align: left; width: 890px; margin: 0 auto; padding-top:10px; background: url(images/top-category-bg.png) no-repeat;}
#fronthead-inner {background: url(images/bottom-category-bg.png) no-repeat bottom left; padding-bottom: 0px; }
Continue Reading

Custom Page Template in Genesis Child Theme - Page Layouts

Page template is one which are created in WordPress template when you publish a new page there is an option on the left hand side to select the page template. Few page templates are applied by default. for example if you create an home.php it will automatically be applied when Home Page of the site is loaded. similarly single.php is applied when a page is viewed. in this tutorial we will create a Home Page Template for our Genesis Child theme.


HOW TO CREATE GENESIS PAGE TEMPLATE :

Creating a page template for the Genesis Child Theme is same as we create in other frameworks or custom WordPress Template but a little few changes to call the header,footer and footer widgets.

Creating Custom Page template :

<?php
/*
Template Name: Template Name Here
*/
?>
you can see a new page template has been created. all the code that we will enter in this template will be applied on the page which will use this template.

at the end we will call a function from Genesis to call the rest of the page elements (title, header, menu, footer widgets, footer)

<?php genesis(); ?>
Complete code :
<?php
/*
template name: Template Name Here
*/
?>

<!-- Start Custom Loop -->

<!-- End Custom Loop -->

<?php genesis(); ?>

Force Layout for Page Template :

if you want a full width, sidebar content, content sidebar or any other Genesis Layout for a Page Template you can use the following filter to force the layout of the page.
add_filter('genesis_pre_get_option_site_layout', 'name_of_the_layout');
Replace the second perameter with the name of the layout

List of Genesis Layout for Page Template :

// Force Full Width Layout

'__genesis_return_full_width_content'

// Force Content-Sidebar Layout

'__genesis_return_content_sidebar'

// Force Sidebar-Content Layout

'__genesis_return_sidebar_content'

// Force Content-Sidebar-Sidebar Layout

'__genesis_return_content_sidebar_sidebar'

// Force Sidebar-Sidebar-Content Layout

'__genesis_return_sidebar_sidebar_content'

// Force Sidebar-Content-Sidebar Layout

'__genesis_return_sidebar_content_sidebar'

Creating Full Width Home Page in Genesis Child Theme :

<?php

// GENESIS HOMEPAGE TEMPLATE //


// FORCE FULL WIDTH LAYOUT
add_filter ( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );

// Homepage CUSTOM LOOP
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'my_custom_loop' );
function my_custom_loop () {
?>
 <div id="main_container">
  <div id="single-post" class="entry-content">
  
  // Add WP Query or Custom Columns for Home page Here
  
  </div> <!-- end single post -->
 </div> <!-- end main container -->
<?php } ?>


<?php genesis(); ?>
Continue Reading

Force Full width and add custom content in Genesis Page Template

Recently I have published a post Custom Page Template in Genesis Child Theme and figured some people still have the problem to work with custom page templates.


Make sure to do every thing in steps so that if a piece of snippet does not work then you can figure out the problem with the code
<?php

/**
*
* Template Name: Agents
*
*/


genesis();

this will create a page template in "pages" post types. now add the page template in the menu and view it. This will show a simple page with title and sidebar. If you add content it will also be show. see the image below.

Return Full width


now we will add a filter that will return a full width page template.

  
// RTURNS A FULL WITH FOT THE PAGE TEMPLATE
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );

Note : If you select another page layout from the "Layout Setting" metabox then it will overwrite the above layout. (if you add full width filter to the page template, and select sidebar/content while publishing the page then sidebar/content layout will be applied to the page template)

There are other layout too that you can use in page template. See other Genesis Layout Filters You remove default layout from the Genesis Child Theme Remove Genesis Laout - Unregister Layouts in Genesis

Remove Default loop.

// remove default loop
remove_action( 'genesis_loop', 'genesis_do_loop' );

Now you will only see header and footer, all the content will be removed.

Custom Content on Custom Page Template :

this is the tricky part of the tutorial, to add custom content we need to hook into the action hook and will add the markup and content over there. If you add content without any action hook then content will be displayed on the top of the header.

to add content we need to know about Action Hooks and Filters that are available in Genesis Framework. We also need a simple Genesis Visula Hooks plugin to see the action hooks and filters. Please read this post to know how to see action hooks with Genesis Visual hooks plugin and use hooks to add and filter content.

to add three columns / Custom Content :

add_action( 'genesis_before_content', 'homepge_content' );
function homepge_content() { ?>

<div class="one-third first">
Lorem ipsum dolor sam.....</div>
<div class="one-third">
Lorem ipsum dolor sit amet......</div>
<div class="one-third">
Lorem ipsum dolor sit amet......</div>
<?php }



Continue Reading

Custom sidebar for single product view in Genesis / WooCommerce

While working on a client site. He offered me to create a separate sidebar for a single product view in genesis. He wanted to load different widgets when single product is viewed. The tool used on the site for shopping cart was "WooCommerce"

First I went to the plugin and open it in editor and hard coded the sidebar which I registered in the functions.php


Later on I thought that this is not a good idea to do this. because with the newer version of Woo Commerce all the changes will be lost. Then I took use of the WooCommerce Actions Hooks in template and Hooked into the content-single-product.php

This template is responsible of showing content on the single-product.phpi took use of the hook

woocommerce_after_single_product

and did the following..

Step 1 : Register New Widget area for Custom Sidebar

add this code in functions.php to create a new widget area for product view page.

// NEW WIDGET AREA FOR SINGLE PRODUCT VIEW
if ( function_exists('register_sidebar') )
 register_sidebar(array('name'=>'Single Product Sidebar',
  'before_widget' => '<div class="widget-wrap">',
  'after_widget' => '</div>',
  'id' => 'product_sidebar',
  'description' => 'Widgets in this area will be shown on the single product view page only.',
  'before_title' => '<h4 class="widgettitle">',
  'after_title' => '</h4>',
));


Step 2 : removing default sidebar & adding Custom sidebar with Hooks.

add this code in functions.php to remove default sidebar and add the above sidebar in that place.

// content-single-product.php HOOK to get into the page to add single product sidebar.
add_action('woocommerce_after_single_product', 'single_product_sidebar_hook');
function single_product_sidebar_hook() { ?>
  <?php remove_action('genesis_sidebar', 'genesis_do_sidebar'); ?>
  <?php add_action('genesis_sidebar', 'genesis_single_product_sidebar');
            function genesis_single_product_sidebar() { ?>
                <?php // SINGLE PRODUCT VIEW SIDEBAR
                    if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Product_Sidebar') ) : ?>
                <?php endif; ?>
   <?php } ?>
<?php }

Continue Reading

Add theme support for Custom Background

Custom Background in your WordPress Theme is a theme feature that allows you to change the background color or add background image to the Theme.



add_theme_support( 'custom-background' );
 
This code simply adds a menu item under Appearance in WordPress Dashborad. This code need to be placed in functions.php or any other file linked with functions.php

// Register Theme Features
function custom_theme_features()  {
 global $wp_version;

 // Add theme support for Custom Background
 $background_args = array(
  'default-color'          => '#7a7a7a',
  'default-image'          => get_template_directory_uri() . '/images/background.jpg',
  'wp-head-callback'       => '_custom_background_cb',
  'admin-head-callback'    => '',
  'admin-preview-callback' => '',
 );
 if ( version_compare( $wp_version, '3.4', '>=' ) ) :
  add_theme_support( 'custom-background', $background_args );
 else :
  add_custom_background();
 endif;
}

// Hook into the 'after_setup_theme' action
add_action( 'after_setup_theme', 'custom_theme_features' );


How Custom Background works.
The important thing to make this feature work is to add wp_head before the closing &lt;/head> tag in your theme header.php. If this is missing the custom background theme support will not work.
This code generates a style in the Head of the theme like this.
 
<style id="custom-background-css" type="text/css">
body.custom-background body.custom-background {
 background-color: #7a7a7a;
 background-image: url('images/background.png');
 background-repeat: repeat;
 background-position: top left;
 background-attachment: scroll;
}
</style>

Same way add theme support for header works in the presence of wp_head tag.
Continue Reading

Use Twitter Bootstrap in your WordPress Theme

WordPress is great, Bootstrap is cool, I want to use them together!
For Twitter Bootstrap to work you need to include at least three files in any of your web pages:
  1. bootstrap.css (included with the Bootstrap download)
  2. bootstrap.js (included with the Bootstrap download)
  3. jquery.js
A WordPress theme needs, at a bare minimum, two files: style.css and index.php.
Download WordPress and install it. Create a new theme. Download Bootstrap and unzip it to your theme’s folder. OK.
Step one
Include bootstrap.css in your theme style.css:
@import url("bootstrap/css/bootstrap.min.css");
In fact, here’s the complete style.css:
/*
Theme Name: My New WordPress Theme
Theme URI: http://localhost
Description: WordPress Test Theme
Author: My Name Here
Author URI: http://localhost
Template:
*/

/*
 *  1. Import the Bootstrap css
 */

@import url("bootstrap/css/bootstrap.min.css");

/*
 *  Some fancy styling for Bootstrap spans
 */

.span4, .span8
{
background-color: #ade;
}
Step two
Bootstrap needs JQuery to work so link to it in your theme index.php:
<!-- 2. Bootstrap needs JQuery -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Step three
Include bootstrap.js in index.php:
<!-- 3. Import Bootstrap.js -->
<script src="bootstrap/js/bootstrap.min.js"></script>
index.php looks like this:

<! DOCTYPE html>

<html>
<head>
<title>My New WordPress Theme</title>

<!-- The theme's style.css file -->
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />

<!-- 2. Bootstrap needs JQuery -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<!-- 3 .Import Bootstrap.js -->
<script src="bootstrap/js/bootstrap.min.js"></script>

<?php wp_head(); ?>
</head>
<body>

<!-- Bootstrap in action -->
<div class="container-fluid">
<div class="row-fluid">
<div class="span4">
<p>Just to</p>
</div>
<div class="span8">
<p>see if it works</p>
</div>
</div>
<div class="row-fluid">
<div class="span4">
<ul class="nav nav-pills nav-stacked">
<li><a href="#">create</a></li>
<li><a href="#">a few</a></li>
<li><a href="#">stacked</a></li>
<li class="active"><a href="#">Bootstrap</a></li>
<li><a href="#">pills</a></li>
</ul>
</div>
<div class="span8">
<p>Random content here.</p>
</div>
</div>
</div>

<?php wp_footer(); ?>        
</body>
</html>
Continue Reading

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

Send article to a friend by email

In order to create more traffic on your blog, it can be a good idea to let your readers send your posts to their friends by email. A few month ago, I already shown you a function to do that, here is an improved version for today.

To apply this recipe to your blog, simply paste the following function into your functions.php file, and that's all. Hard to do something simpler!
function direct_email($text="Send by email"){   
       global $post;  
        $title = htmlspecialchars($post->post_title); 
         $subject = 'Sur '.htmlspecialchars(get_bloginfo('name')).' : '.$title; 
         $body = 'I recommend this page : '.$title.'. You can read it on : '.get_permalink($post->ID);  
        $link = '<a rel="nofollow"
 href="mailto:?subject='.rawurlencode($subject).'&amp;body='.rawurlencode($body).'"
 title="'.$text.' : '.$title.'">'.$text.'</a>';
          return $link;
  }  
Continue Reading

Enable TinyMCE editor for post the_excerpt

Adding this code to the functions.php of your wordpress theme will add the TinyMCE editor to the post excerpt textarea.

function tinymce_excerpt_js(){ ?>
<script type="text/javascript">
        jQuery(document).ready( tinymce_excerpt );
            function tinymce_excerpt() {
                jQuery("#excerpt").addClass("mceEditor");
                tinyMCE.execCommand("mceAddControl", false, "excerpt");
            }
</script>
<?php }
add_action( 'admin_head-post.php', 'tinymce_excerpt_js');
add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js');
function tinymce_css(){ ?>
<style type='text/css'>
            #postexcerpt .inside{margin:0;padding:0;background:#fff;}
            #postexcerpt .inside p{padding:0px 0px 5px 10px;}
            #postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; }
</style>
<?php }
add_action( 'admin_head-post.php', 'tinymce_css');
add_action( 'admin_head-post-new.php', 'tinymce_css');

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