PHP Snippets: If Statements

PHPThis post is part of the PHP Snippets series where I will be covering the basics of developing in PHP.

One of the most basic statemnts you’ll use in PHP is the if statement which is used for conditional statements which perform different actions.

The most basic form is the basic if itself which executes when one condition is true:

$time = date( "H" );

if ( $time < 12 ){
	echo "Good morning.";
}

This can be extended to supply a value if the original condition fails using an if...else:

$time = date( "H" );

if ( $time < 12 ){
	echo "Good morning.";
else
	echo "Hello."
}

And can be expanded further to check if one of multiple conditions is true using an if...elseif...else:

$time = date( "H" );

if ( $time < 12 ){
	echo "Good morning.";
}elseif ( $time < 18 ){
	echo "Good afternoon."
}else{
	echo "Good evening.";
}

PHP Snippets: Sprintf

PHPThis post is part of the PHP Snippets series where I will be covering the basics of developing in PHP.

The sprintf function provides the same functionality as the printf function, but silently.

This means you would either need to echo the output or concatenate it with a string and echo that string.

$number = 500;
$string = 'miles';

echo sprintf( 'But I would walk %d %s', $number, $string );

PHP Snippets: Printf

PHPThis post is part of the PHP Snippets series where I will be covering the basics of developing in PHP.

The printf function is similar to the echo function in that it will output text, but differs in that it outputs a formatted string.

The syntax of the printf function is:

printf( string, arg 1, arg 2, ... )

Multiple arguments can be provided to the function for each of the placeholders to be replaced.

Continue reading “PHP Snippets: Printf”

PHP Snippets: Quotes

PHPThis post is part of the PHP Snippets series where I will be covering the basics of developing in PHP.

Both single and double quotes are supported in PHP, but there is a significant difference in how they are handled.

Single quotes are output “as is” and are the quickest form of quoting. When using single quotes, you would need to concatenate variables with a string to output them:

$fruit = 'apples';

echo 'They drank some juice from ' . $fruit;

Double quotes evaluate variables and many escaped characters. This means you do not need to concatenate variables with the string, but can include them inside the double quoted string:

$fruit = 'apples';

echo "They drank some juice from $fruit";

You can also use curly braces ({} to isolate the variable within the string. When PHP evaluates a string and sees a $ it will take as much of the string as part of the variable name (ending at a space or punctuation), but you can use the curly braces to explicitly set the end of the variable name:

$fruit = 'apple';

echo "They drank some juice from ${fruit}s.";

PHP Snippets: Echo

PHPThis post is part of the PHP Snippets series where I will be covering the basics of developing in PHP.

Almost everything you write in PHP ill have an output to the user; the simplest way of doing this is to use the in-built echo function (which you can use with or without parentheses).

The below example is a simple echo to output one line of text:

echo 'Hello world!';

You can output multiple lines of text, which you would do with multiple echo function calls:

echo 'Hello world!<br />';
echo 'This is a simple PHP example.';

Notice though, there is a HTML break line tag <br /> included at the end of the first line; if this wasn’t present, then both lines would be output on the same row.

PHP Snippets: Series Index

PHPI started developing plugins for WordPress back in 2014 and switched to ClassicPress in early 2019. I’ve been writing a series of posts on ClassicPress Plugin Development and thought a companion series on developing in PHP might be useful to people looking to make a start.

Over this series of PHP snippets, I’ll be covering the basics of developing in PHP. The series index, below, will update automatically if you’re reading the original blog post otherwise check back to that post.

ClassicPress Plugin Development: Save an Options Page

ClassicPress PluginsThis post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.

Once you have an options page created, you need to create the process to save the options when the user changes them.

The example I am using in this post is from my Remove Revisions plugin which uses a PHP namespace.

namespace azurecurve\RemoveRevisions;

Continue reading “ClassicPress Plugin Development: Save an Options Page”

ClassicPress Plugin Development: Create an Options Page

ClassicPress PluginsThis post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.

Anything more than a very simple plugin will hae options which the site administrator will need to be able to change. this means an options page which is added to the settings menu. ClassicPress does have a settings API which can be used; however, I do not use this API as I’ve previously found it to be overly complex and difficult to use, so I roll my own settings pages.

The example in this post are from my Remove Revisions plugin which uses a namespace:

namespace azurecurve\RemoveRevisions;

As I am using a namespace the options page was added in a function simply called display_options; if a namespace wasn’t in use, I’d have used a vedor/plugin prefix and called the function azrcrv_rr_display_options.

The example takes advantage of the page title from the settings menu (which I covered in the last post as well as loading options, which can be done
with defaults or with with multilevel defaults.

Below is a sample of the display_options from Remove Revisions with the controls removed, leaving behind the basic framework of the page, with the header, load of options and then the form with submit button:

/**
 * Display Settings page.
 *
 * @since 1.0.0
 *
 */
function display_options(){

	if (!current_user_can('manage_options')){
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'remove-revisions'));
    }
	
	// Retrieve plugin configuration options from database
	$options = get_option_with_defaults('azrcrv-rr');	
	
	?>
	
	<div id="azrcrv-rr-general" class="wrap">
		
		<h1>
			<?php
				esc_html_e(get_admin_page_title());
			?>
		</h1>
		
		<form method="post" action="admin-post.php">
			
			<input type="hidden" name="action" value="azrcrv_rr_save_options" />
			<input name="page_options" type="hidden" value="enable-cron" />
			
			<?php
				//
				wp_nonce_field('azrcrv-rr', 'azrcrv-rr-nonce');
			?>
			
			/*
				your options here
			*/
			
			<input type="submit" name="btn_save" value="<?php esc_html_e('Save Settings', 'remove-revisions'); ?>" class="button-primary"/>
		</form>
	</div>
	<?php
	
}

The hidden input action and the wp_nonce_field is used for the save of the options, which I’ll cover in the next post in this series.

Click to show/hide the ClassicPress Plugin Development Series Index

ClassicPress Plugin Development: Get Options Page Title

ClassicPress PluginsThis post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.

Over the last couple of posts in this series, I’ve discussed how options can be loaded and saved, loaded with defaults and loaded with multilevel defaults. Over the next couple of pages, I’m going to show how an options page can be created and the options saved, but first a quick post on how the options page title can be populated.

I’ve seen a lot of plugins where the options page title has been a string which has been echoed. However, when the options page is added to the settings main menu, the first parameter is the page title. So instead of echoing a new string, we can use the get_admin_page_title function to get the title set when the options page was added to the menu.

<h1>
	<?php
		esc_html_e(get_admin_page_title());
	?>
</h1>

As you can see from the example code, above, the call to get_admin_page_title has been wrapped with a esc_html_e to echo and escape the page title.

Click to show/hide the ClassicPress Plugin Development Series Index

ClassicPress Plugin Development: Load Multilevel Options with Defaults

ClassicPress PluginsThis post is part of the ClassicPress Plugin Development series in which I am going to look at both best practice for developing plugins and how I approach some requirements as well as some of the functions I commonly use.

Over the last couple of posts, I’ve taken a look at saving and loading options and how to load options with defaults. The defaults in the last post was a single dimension array, but you can also do the same with multi dimensional arrays using a ustom recursive parse of the arrays.

The below is an example of loading options with multi dimensional defaults from my Widget Announcements plugin:

/**
 * Get options including defaults.
 *
 * @since 1.1.0
 *
 */
function azrcrv_wa_get_option($option_name){
 
	$defaults = array(
						'widget' => array(
											'width' => 300,
											'height' => 300,
										),
						'to-twitter' => array(
												'integrate' => 0,
												'tweet' => 0,
												'retweet' => 0,
												'retweet-prefix' => 'ICYMI:',
												'tweet-format' => '%t %h',
												'tweet-time' => '10:00',
												'retweet-time' => '16:00',
												'use-featured-image' => 1,
											),
						'toggle-showhide' => array(
												'integrate' => 0,
											),
					);

	$options = get_option($option_name, $defaults);

	$options = azrcrv_wa_recursive_parse_args($options, $defaults);

	return $options;

}

/**
 * Recursively parse options to merge with defaults.
 *
 * @since 1.1.0
 *
 */
function azrcrv_wa_recursive_parse_args( $args, $defaults ) {
	$new_args = (array) $defaults;

	foreach ( $args as $key => $value ) {
		if ( is_array( $value ) && isset( $new_args[ $key ] ) ) {
			$new_args[ $key ] = azrcrv_wa_recursive_parse_args( $value, $new_args[ $key ] );
		}
		else {
			$new_args[ $key ] = $value;
		}
	}

	return $new_args;
}

Click to show/hide the ClassicPress Plugin Development Series Index