Categories
Free Tutorials PHP Code

template_include

Using the template_include function included in WordPress, paste this PHP code at the end of your child themes functions.php file and modify accordingly.

add_filter( 'template_include', 'single_page_template', 99 );
function single_page_template( $template ) {

if ( is_singular('page') ) {
        $new_template = locate_template( array( 'single.php' ) );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }

return $template;
}

The function loads the template named single.php on all single pages. The template named single.php can be placed anywhere in your child theme folder. In this case, its placed in the root directory as seen in the following image.

You can change the conditional tag is_singular('page') and/or the file name single.php to anything else.

Note : A file named single.php will automatically load on all single posts by default.

Categories
Free Tutorials PHP Code

get_body_class

This free code checks the body classes and executes your code if the body class exists.

In this case, the code executes on any page which includes custom-class in the body classes. If so, the header and header markup is removed along with the nav menus and this text is printed in the genesis_header hook position : Replace this output value with you own

To modify this code, replace the value for the $output variable, and replace the actions within the function to add or remove functionality.

You can check for an existing body class or a custom class added using code like this found in many Genesis child theme template files :


add_filter( 'body_class', 'genesis_sample_landing_body_class' );
function genesis_sample_landing_body_class( $classes ) {

    $classes[] = 'custom-class';
    return $classes;

}

If you inspect the element or source code and view the body classes, this is what you’ll find :

body-class

Categories
Free Tutorials PHP Code

if else

if …. else is used as a conditional statement or conditional expression which enables you to execute code if a specific condition returns true otherwise execute other code if the same condition is false.

Example :

if ( is_front_page() ) {
    echo 'This is your front page';
} else {
    echo 'This text prints on all pages excluding your front page';
}

You can test the above code by adding it to your child themes functions file however you’ll first need to wrap it in a action hook like this :

add_action( 'genesis_after_header', 'if_else_code_test' );

function if_else_code_test() {

    if ( is_front_page() ) {
        echo 'This is your front page';
    } else {
        echo 'This text prints on all pages excluding your front page';
    }

}

You can also use conditional tags with a ternary operator to achieve the same result.

if…elseif….else #

if …. elseif …. else enables you to execute code if specific conditions return true otherwise execute code if the conditions return false. Watch video.

Example :

if ( is_front_page() ) {
    echo 'This prints on your front page';
} elseif ( is_singular('post') ) {
    echo 'This text prints on all single posts excluding your front page';
} else {
    echo 'Print this on all pages if all other conditions return false.
}

To test, modify and use this code, you can paste this code at the end of your child themes functions file, wrapped in any hook like this.

add_action( 'genesis_after_header', 'if_elseif_else_code_test' );

function if_elseif_else_code_test() {

   if ( is_front_page() ) {
        echo 'This prints on your front page';
    } elseif ( is_singular('post') ) {
        echo 'This text prints on all single posts excluding your front page';
    } else {
        echo 'Print this on all pages if all other conditions return false';
    }

}

The above code prints unique text on the front page, unique text on all single posts and unique text on all other page/post types.

Watch Video #

The following video uses the above code snippet ( with added styling & different hook ) to demonstrate how you can use if elseif else conditional statements with conditional tags, in any Genesis child theme.

Related Tutorials

Categories
Free Tutorials PHP Code

array

There’s 3 types of functions which use array() out of the dozens of different array functions you can use in PHP.

This tutorial explains the simplest & most common type of array() function which is called a indexed array.

A indexed array uses a variable to hold more than 1 value.

You need to understand what a variable is, to understand what a array is and how to use arrays in WordPress and Genesis.

There’s also 2 ways to code indexed arrays :

  1. You can code a single variable which automatically holds all values.
  2. You can assign the index automatically starting at 0 or manually for each value.

In this 1st example, the variable named $colors stores 3 values which are red, white and blue. The index is automatic so the 1st value red = 0, white = 1 and blue = 2.

Square or Round Brackets

You can code the array using rounded brackets or square brackets.

Using round brackets :

$colors = array( 'red', 'white', 'blue' );

Using square brackets :

$colors = [ 'red', 'white', 'blue' ];

Working Code Snippets

Here’s a fully coded example which you can paste in your child themes functions file to test how a array works in Genesis child themes.

add_action( 'genesis_after_header', 'test_array_1' );

function test_array_1() {

$colors = array( 'red', 'white', 'blue' ); 

echo '<p> I like ' . $colors[2] . ', ' . $colors[0] . ' and ' . $colors[1] . '. </p>';

}

The following example shows how you can manually assign the index number to each value then print each value in any order using the index number for each value.

add_action( 'genesis_after_header', 'test_array_3' );

function test_array_3() {

$colors[0] = 'red';
$colors[1] = 'white';
$colors[2] = 'blue';

echo '<p> My favorite colors are : ' . $colors[2] . ', ' . $colors[0] . ' and ' . $colors[1] . '. </p>';

}

Using Arrays in Genesis

There’s different ways to use arrays in WordPress themes. A very common way is with a comma separated array of post i.d’s within a conditional tag like this :

is_page(array( 1, 2, 3 ) )

Test code :

add_action( 'genesis_after_header', 'test_array_4' );

function test_array_4() {

if ( is_page(array( 1, 2, 3 ) ) ) {

echo "Hello World";

    }
    
}

The above conditional tag, when used within a function, will only execute on a page with the post id of 1, 2 or 3.

Array of key => value pairs

In previous examples we used a indexed array of values without keys however you can also use comma-separated key => value pairs as arguments within the array like this.

array( 'format' => 'html', size  => 'full' );

Example usage of key => value pairs in Genesis

$image = genesis_get_image( array(
    'format'     => 'html',
    'size'	 => 'full',
    'attr'	 => array ( 'alt' => the_title_attribute( 'echo=0' ) ),
) );

Here’s a full working code example which uses the above array of key => value pairs in the genesis_get_image function for the image arguments.

Array In WordPress

Here’s a classic example of an array of arguments in WordPress :

$args = array(
    'orderby' => 'comment_count',
    'posts_per_page' => 3,
    'post__not_in' => $sticky
);

In the above case, the comma-separated key => value arguments are used with WP_Query. The parameter being the key which accepts different values. Here’s the Full working code example.

Categories
Free Tutorials PHP Code

class_exists

You can use class_exists to check if a plugin is active. ( Watch the video below which tests the code examples in this tutorial ).

You need to do this when using a PHP class from a plugin in your theme.

If you don’t use class_exists when using plugin functions in your theme, you’ll get a error when you load pages on the site if the plugin is deactivated.

Lets look at a working example using code from a very popular WordPress plugin, Advanced Custom Fields.

Using class_exists In Your Theme

The following code checks if the ACF plugin is active.

Use this code with code snippets which use ACF specific functions like get_field();

If you don’t, your code will cause errors if added to a themes file when the ACF plugin is not active.

The following code checks if the ACF plugin is active by looking for the acf class. If the acf class does not exist the return statement immediately ends execution of the current function.

See the full function which includes class_exists under the sub heading below: The Fix.

if ( ! class_exists( 'acf' ) ) 
    return;

Here’s a complete working example you can add to your child themes functions.php and test yourself which you can see done in the following video demonstration.

Video Demo

The video demonstrates the use of the class_exists function in genesis when using plugin specific functions in a theme to avoid theme errors when the plugin is deactivated.

Code Examples

The following code will work fine if you have created a field in ACF named after_header and activated the plugin.

add_action( 'genesis_before_loop', 'test_acf_function' );

function test_acf_function() {
    
    echo get_field( 'after_header' );

}

However, what happens when you deactivate the ACF plugin?

Fatal error: Call to undefined function get_field()

You get a fatal error because get_field is a function coded within the ACF files so it won’t work when used in a theme when the ACF plugin is inactive.

The Fix

Always add a check for the plugin when using plugin functions in your theme.

Here’s the updated code which include, you guessed it, class_exists.

add_action( 'genesis_before_loop', 'test_acf_function' );

function test_acf_function() {

if ( ! class_exists( 'acf' ) ) 
    return;
    
    echo get_field( 'after_header' );

}

The above code checks if the class_exists for the ACF plugin otherwise returns false

Other Coding Methods

Another method using a ternary operator:

add_action( 'genesis_before_loop', 'test_acf_function' );

function test_acf_function() { 
    
$output = class_exists( 'acf' ) ? get_field( 'after_header' ) : get_post_meta( get_the_ID(), 'after_header', true );
    
echo $output;

}

The above code checks if the ‘acf’ class exists which is true when the ACF plugin is active.

If the ACF plugin is active, the $output variable uses the ACF function get_field( 'after_header' ) as its value.

Otherwise, the $output variable equals get_post_meta( get_the_ID(), 'after_header', true ); which is a WordPress function for custom fields and always works in any theme.

Other Examples

If you’re using WooCommerce functions in your theme, you’ll also want to check that the WooCommerce plugin is active like this:

if ( ! class_exists( 'WooCommerce' ) )
    return;

You can see the above code in many of the new StudioPress child themes which are coded to work with the WooCommerce plugin out of the box and include a dedicated woocommerce folder.

Categories
Free Tutorials PHP Code

foreach

The foreach construct only works with arrays.

This means you must either use an array like this: array( '1', '2', '3' );

Or functions which return an array like get_categories.

foreach is used to loop through each key/value pair in an array:

$key = array( '1', '2', '3' );

foreach( $key as $value ) 

print $value;

If you wrap the above code in opening and closing php tags and put it into a file, it will output 123.

That’s the most basic example of using foreach with an array.

Here’s several commonly used examples of using foreach with an array of key/value pairs as well as functions which return an array.

Add the following functions to your child themes functions file to see what each code snippet outputs on the front end.

Example 1 : Using array with foreach loop

The following example prints the value for each key in the array:

add_action( 'loop_start', 'for_each_example_1' );

function for_each_example_1() {

$key = array( 'Number 1', 'Number 2', 'Number 3' );

foreach( $key as $value ) 

echo $value;
    
}

Example 2 : Using array within foreach

A different way to code ( array ) when using foreach :

add_action( 'genesis_entry_header', 'for_each_example_2' );

function for_each_example_2() {

$key = ( 'note 1, note 2, note 3' );

foreach( ( array ) $key as $value ) 

echo $value;

}

Example 3 : Using foreach with functions.

This example uses the get_categories function which returns an array of categories.

add_action( 'genesis_entry_footer', 'for_each_example_3' );

function for_each_example_3() {

$key = get_categories();

foreach( $key as $value ) 

echo $value->name;

}

Example 4 : Commonly used names for variables using foreach

Generally, you’ll find the name of variables used with foreach won’t be named $key and $value but more descriptive like $categories as $category or $tags as $tag as seen in the following example:

add_action( 'genesis_after_entry', 'for_each_example_4' );

function for_each_example_4() {

$categories = get_categories();

foreach( $categories as $category ) 

echo $category->name;

}

Examples of using foreach with get_tags, get_categories and get_terms

Related Tutorials

Categories
Free Tutorials PHP Code

sprintf

sprintf is similar to printf however is used to return the result as a value for a variable to be used later rather than output immediately.

Here’s the difference you can test in your child themes functions file.

sprintf
add_action('loop_start','sprintf_example' );
function sprintf_example() {		
$output = sprintf('%s World', 'Hello' ); 
echo $output;
}
printf
add_action('loop_start','printf_test' );
function printf_test() {		
	printf('%s World', 'Hello' ); 
}

Both code snippets produce exactly the same result. The only difference is sprintf returns the value for the variable and printf outputs directly.

You can also write the code using sprintf like this:

add_action('loop_start','sprintf_example1' );
function sprintf_example1() {
$text = "Hello";		
$output = sprintf('%s World', $text ); 
echo $output;
}

And this:

add_action('genesis_after_header','sprintf_example2' );
function sprintf_example2() {
    $link = get_permalink();
    $text = "Hello";		
    $output = sprintf('%s World', $text ); 
printf( '<a href="%s">' . $output . '</a>', $link );
}

Or this:

add_action('wp_head','sprintf_example3' );
function sprintf_example3() {
    $link = get_permalink();
    $text = "sprintf";		
    $output = sprintf('%s Example', $text ); 
printf( '<a href="%s">%s</a>', $link, $output );
}

Related PHP Code

Categories
Free Tutorials PHP Code

add_action

add_action is a function which you’ll see in WordPress, Genesis & other theme files.

You’ve probably seen code in a file which looks something like this:

add_action( 'genesis_before_header', 'hook_test' );

To understand how add_action() works with different hooks in WordPress & Genesis, you’ll need to learn the basics of how to use it in code.

In the code above:

add_action is the WordPress function.
genesis_before_header is the hook name.
hook_test is the name of your function call.

Video Walk Thru

This video walks you thru this post and shows you the result of testing the example code snippets.

Available on request for registered users.

There are different types of action hooks, however the most commonly used are theme specific hooks like genesis_before_header and WordPress specific hooks like loop_start.

Theme Specific Hooks

Using a theme specific hook enables you to print text like “Hello World”

Add the following custom function to your child themes functions file.

The code will echo the text “Hello World” in the genesis_before_header hook location.

add_action( 'genesis_before_header', 'hook_test1' );
function hook_test1() {
    echo "Hello World";
}

Now change the hook in the above code to genesis_after_header to see the different location the text “Hello World” is printed.

add_action( 'genesis_after_header', 'hook_test2' );
function hook_test2() {
    echo "Hello World";
}

Here’s a visual presentation of all Genesis action hooks.

WordPress Hooks

WordPress includes over 1700 hooks.

1 of the action hooks included in WordPress is named loop_start. You can use loop_start in any WordPress theme.

Add the following PHP code to your child themes functions file to test the loop_start hook in a custom function:

add_action( 'loop_start', 'hook_test3' );
function hook_test3() {
    echo "Hello World";
}

The only difference between the above code and the code we tested previous to that is the change of hook from genesis_after_header to loop_start.

This shows you the most basic usage of a WordPress action hook used with the add_action function.

The add_action function enables you to add content or execute a function in a specific position in your theme or at a specific execution point or time.

Related

Categories
Free Tutorials PHP Code

printf

You’ve probably seen code in your files which looks like this:

printf('%s World', $var );

This code includes a function named printf() which in most cases is more efficient than using the echo or print functions.

To learn more about using PHP code in WordPress & Genesis, you’ll need to understand how the printf function works.

Video Guide

Coming Soon!

Printf generally includes a % percentage sign with an s for string like this:

%s

Printf can be used in replace of print or echo so rather than use this:

echo "Hello World";

or

print( 'Hello World' );

Instead, you can use printf like this:

printf('%s World', "Hello" );

These % percentage signs with a s work like placeholders which are converted when the code is executed. In the above case %s is replaced with the text Hello.

Here’s the full working code you can test in your child themes functions file:

add_action('loop_start','printf_example1' );
function printf_example1() {<br />
printf('%s World', 'Hello' ); 
}

You can then replace your text ‘Hello’ with a variable so the value for your $text variable is now equal to Hello:

$text = 'Hello';

The full working code you can test in your child themes functions file would be this:

add_action('loop_start','printf_example2');
function printf_example2() {<br />
$text = 'Hello';
printf('%s World', $text ); 
}

In WordPress themes, you’ll find code which uses printf which you can paste into your child themes functions.php file to see how it works:

add_action('loop_start','printf_example3');
function printf_example3() {<br />
printf( '<a href="%s">' . esc_html__( 'Your link text here', 'text-domain' ) . '</a>', 'http://example.com' ) ); 
}

The code above uses printf with one instance of %s which is replaced by the URL http://example.com when the function is executed.

The above code can also be written like this:

add_action('loop_start','printf_example4');
function printf_example4() {

$link = esc_url( get_permalink() );
$text = "Value for Your Text Variable";

printf( '<a href="%s">%s</a>', $link, $text ); 
}

In this case, we have replaced the URL with a variable named $link. We have also replaced the text with a variable named $text.

The value for the $link variable is equal to the posts permalink rather than the example.com URL and the value for the $text variable is equal to the text.

You’ll also notice each parameter in the string is separated by a comma like this:

$link, $text

When the code executes, the 1st placeholder %s is replaced with the 1st parameter which in this case is the $link variable which equals get_permalink();

After the 1st placeholder is replaced, the 2nd, 3rd and so on are replaced step by step in the order they occur in the string, separated by a comma.

Note: The order of the placeholders %s must match the order of the arguments in the code.

You can also write the code as follows:

add_action('loop_start','printf_example5');
function printf_example5() {

$text = "Value for Your Text Variable";

printf( '<a href="%s">%s</a>', esc_url( get_permalink() ), $text ); 
}

This way the 1st parameter is equal to the get_permalink function rather than the value for the $link variable as in example 4.

printf & sprintf

Printf is used to output the formatted string. Example:

add_action('loop_start','printf_example6' );
function printf_example6() {<br />
    printf('%s World', 'Hello' ); 
}

Sprintf is returned as the value for a variable to be used later then the variable can be output using echo or printf. Example:

add_action('loop_start','printf_example7' );
function printf_example7() {<br />
$output = sprintf('%s World', 'Hello' ); 
echo $output;
}

Ask Questions

Members can ask questions & get answers.

Related PHP Code

Categories
Free Tutorials PHP Code

variable

You’ve probably seen code which includes the $ dollar sign like this:

$output

This is whats called in PHP language, a variable.

WordPress & Genesis use thousands of variables in the code.

If you want to learn more about the code, you’ll need to understand variables.

Video Guide

This video walks you through this post and shows you the results of testing all the code in this post. Members can ask questions at any time.

A variable is something you can create ( declare ) and use in PHP code like this:

add_action( 'genesis_after_header', 'using_variables' );
function using_variables() {
$text = "Hello World";
echo $text;
}

When you create a variable, you always start with a $ dollar sign and then create a descriptive name for the variable like this:

$My_Name

Once you have created the variable, you can then assign a value to it like this:

$My_Name = "Brad";

Once the variable has a value, you can then output or print the value for your variable like this:

$My_Name = "Brad";
echo $My_Name;

We can now hook in the above code and output the value for the variable in a custom function, ( in a themes functions file ) like this:

add_action( 'genesis_after_header', 'using_variables' );
function using_variables() {
$My_Name = "Brad";
echo $My_Name;
}

Or

We can wrap the code in opening & closing PHP tags and use the code in a template file like this:

<?php 
$My_Name = "Brad";
echo $My_Name;
?>

The above variable only works within the function it is defined meaning you can’t take the $My_Name variable and use it in another function like this:

add_action( 'genesis_before_header', 'using_variables_in_other_functions');
function using_variables_in_other_functions() {
echo $My_Name;
}

The only way you can use the variable again in another function is if you originally declare it outside the function ( in your functions file ) to begin with like this:

$My_Name = "Brad";

Then you’ll need to use the global keyword like this:

add_action( 'genesis_after_header', 'using_variables' );
function using_variables() {
global $My_Name;
echo $My_Name;
}
Note: It’s best to use the appropriate API functions when available, instead of modifying global variables directly.

Case Sensitive Variables Names

This code won’t work:

add_action( 'genesis_after_header', 'case_sensitive_variable' );
function case_sensitive_variable() {
$My_Name = "Brad";
echo $my_name;
}

Nor will this:

add_action( 'genesis_after_header', 'uppercase_lowercase_variables' );
function uppercase_lowercase_variables() {
$My_Name = "Brad";
echo $MY_NAME;
}

Using Numbers in Variables

This won’t work:

add_action( 'genesis_after_header', 'case_sensitive_variable' );
function case_sensitive_variable() {
$1my_name = "Brad";
echo $1my_name;
}

This code works:

add_action( 'genesis_after_header', 'numbers_in_variables' );
function numbers_in_variables() {
$my1_name = "Brad";
echo $my1_name;
}

Variables must always start with a $ dollar sign followed by a character or underscore.

To get access to hundreds of code snippets which include the use of variables and answers to your questions, register for membership. Here’s some of the benefits.

Usage of Variables in Genesis

The following code includes 2 variables named $link and $output.

add_action( 'genesis_after_header','variable_output' );
function variable_output() {	
$link = esc_url( 'http://example.com' );  
$output = sprintf( '<a href="%s">' . __( 'Your link text here' ) . '</a>',  $link  ); 	
echo $output;
}

The following code includes 1 variable named $link which is equal to the posts permalink.

add_action( 'genesis_after_header','variable_output' );
function variable_output() {	
$link = esc_url( get_permalink() );
printf( '<a href="%s">' . __( 'Link text' ) . '</a>',  $link  ); 
}

The code above uses printf to output the formatted string.

This code snippet enables you to modify the default value for the original variable already declared in Genesis, via your child themes functions file, using a filter function.

//* Modify comments title text in comments
add_filter( 'genesis_title_comments', 'sp_genesis_title_comments' );
function sp_genesis_title_comments() {
	$title = '<h3>Discussion</h3>';
	return $title;
}

Understanding how variables work will make it easier to understand how to read and write custom filter functions to modify the default value for a variable already included in Genesis or WordPress.

Categories
Free Tutorials PHP Code

Ternary Operator

There’s at least 3 ways to code if conditionals and else statements in WordPress using PHP.

In the first 2 examples below, we’ll use the most common methods using if and else.

In the 3rd method, we’ll use the ternary operator question mark ? and colon :

In programming language, a ternary operator is commonly referred to as a conditional operator which excepts 3 arguments.

Is the use of a ternary operator a more efficient way to code if conditionals and else statements using PHP? Test the code yourself and find out.

Here’s 3 working examples you can paste into your child themes functions file and test at the same time or individually :

if …. else conditional #

The first 2 methods use if else conditional statements.

add_action( 'loop_start', 'else_if_method_one' );
function else_if_method_one() {
if ( is_front_page() ) :
echo 'Only on the front page';
else :
echo 'Otherwise different on all others';
endif;
}

You can also use code like this:

add_action( 'loop_start', 'else_if_method_two' );
function else_if_method_two() {
if ( is_front_page() ) {
echo 'Only on the front page';
} else {
echo 'Otherwise different on all others';
   }
}

Ternary Operator #

In the 3rd example, we’ll use a conditional tag with the operator ? and : like this :

add_action( 'loop_start', 'ternary_operator_method_three' );
function ternary_operator_method_three() {
$output = is_front_page() ? 'Only on the front page' : 'Otherwise different on all others';
echo $output;
}

The above method uses the ternary operators ? and : which enable you to change the value of the $output variable.

In this case, if we’re on the front page, the 1st value is true ‘Only on the front page’

Otherwise, if we’re not on the front page, the 1st value is false and the 2nd value is true ‘Otherwise different on all others’.

Note: is_front_page() assumes your child theme contains a front-page.php file otherwise, in these examples, returns true on the home and blog page ( posts page ) in genesis.

Use With Variables

You can use variables with actions and filters like this:

add_action( 'loop_start', 'ternary_operator_variables' );
function ternary_operator_variables() {
$output = $a ? $b : $c;
echo $output;
}

This code reads, if $a is true, use the value for $b else use the value for $c.

All you need to do is define your variables.

Here’s an example from the genesis featured posts widget:

$title = get_the_title() ? get_the_title() : __( '(no title)', 'genesis' );

An example using printf

printf( genesis_html5() ? '<p class="entry-meta">%s</p>' : '<p class="byline post-info">%s</p>', do_shortcode( $post_info ) );

See here for a working example using the ternary operators with variables.

Related PHP Code