How to get the wordpress posts parent page information out

In many cases when your working with WordPress you’ll want to assign a specific page template to become the static page. Usually replacing the homepage with a static page as well.

You can do this in WordPress -> settings -> reading.

When you set say ‘Latest News’ to be your posts page you may want to get that out at the top of the loop.

Unfortunately in some cases, you might also just settle with the default template for your Latest News page (index.php) which can make things a little more annoying.

WordPress will fill the loop with your posts rather than information about your page. Making the title of the page unavailable. This little useful snippet of code will help you overwrite that.

<div id="title">
<?php $your_title = get_the_title( get_option('page_for_posts', true) ); ?>
<h1><?= $your_title; ?></h1>
</div>

How to change the default from wordpress email from address

Sometimes you might want to stop WordPress sending emails with the default WordPress email from address.

Usually something like wordpress@domain.com

Often displayed like so: WordPress wordpress@domain.com

There are a few plugins available to achieve this, but personally I don’t relying heavily on WordPress plugins – mainly because dependencies on too many third parties can be annoying.

Particularly when there is not much code needed to achieve the change.

Add the following code to your functions.php file.

add_filter('wp_mail_from', 'replacement_mail_from');
add_filter('wp_mail_from_name', 'replacement_mail_from_name');
function replacement_mail_from($old) {
 return 'your email address';
}
function replacement_mail_from_name($old) {
 return 'your name or your website';
}

Setting Default WordPress FTP, SSH & SFTP Details

Sometimes hosts are really un-helpful and don’t set up your WordPress ftp details for you, or maybe you set your WordPress install up yourself and WordPress is asking you for FTP details.

Either way, what you’ll quite quickly find, or have already found (hence your now here reading this post) is that downloading plugins is slick when WordPress just WORKS. When it asks you for FTP credentials everytime, well…that’s just annoying.

So how can we stop this? Well it’s pretty easy actually.

What you’ll need

  • Access to editing your wp-config.php file
  • Your host’s FTP or SFTP details

Get cracking

Open up your wp-config.php file, found in the root of your WordPress install.

Add the following if you just want standard FTP connection.

define('FS_METHOD', 'ftpext');
define('FTP_BASE', '/home/site-name/www/');
define('FTP_CONTENT_DIR', 'wp-content');
define('FTP_PLUGIN_DIR ', 'wp-content/plugins/');
define('FTP_USER', 'yourFTPUsername');
define('FTP_PASS', 'yourFTPpassword');
define('FTP_HOST', 'yourFTPhost');
define('FTP_SSL', false);

To connect with SFTP then all you’ll need to do is add to the above, the following definitions and add your credentials paths.

define('FTP_PUBKEY', '/home/username/.ssh/id_rsa.pub');
define('FTP_PRIKEY', '/home/username/.ssh/id_rsa');

wordpressFTP1 Setting Default Wordpress FTP, SSH & SFTP Details

Trust me when I say this, when Wordpres just WORKS. It is a great experience!

Enqueue WordPress script on certain theme template pages only

Enqueuing scripts the proper way in WordPress can help avoid annoying javascript problems and allows us to specify dependancies of our scripts I.E. jQuery, so that WordPress may load the specified scripts before our script, thus eliminating problems.

I quite often find myself wanting to enqueue scripts into one particular page template rather than loosely across my entire site, in a vein attempt to try and keep the site as efficient as I possibly can.

So I thought I’d share with you how to achieve that.

Firstly open up your functions.php file.

if(!function_exists('register_my_scripts')):
    function register_my_scripts(){
    }
endif;

Add the above function. This function will control enqueueing scripts for your theme.
Now we must tell WordPress through registering an action that we want it to check this function when it enqueues scripts in the wp_head(); function called in the header.php file.

We can do this by adding this line of code to our functions.php file.

add_action('wp_enqueue_scripts', 'register_my_scripts');

And wollah, now WordPress will call our function when it attempts to register scripts. Now hopefully you may already be familiar with the WordPress functions wp_register_script and wp_enqueue_script

If not heres a rundown.

wp_register_script
A safe way of registring javascripts in WordPress for later use with wp_enqueue_script().

<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to problems.

For further details see the wordpress wp_register_script page »

wp_enqueue_script
A safe way of adding javascripts to a WordPress generated page. Basically, include the script if it hasn’t already been included, and load the one that WordPress ships.

usage:

wp_enqueue_script(
     $handle
    ,$src
    ,$deps
    ,$ver
    ,$in_footer
);

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to problems.

For further details see the wordpress wp_enqueue_script page »

Given that you now have a reasonable grasp of whats going on lets move this forward, first we want to register our script name with WordPress and then we want to enqueue it.

This can be quite easily done with the following.

//Register our script
wp_register_script('my-script',
get_template_directory_uri() . '/assets/js/my-script.js',
array('jquery'),
'1.0' );
//Enqueue the script
wp_enqueue_script('my-script');

Put this inside our earlier defined function of register_my_scripts. First of all I register my-script and then I enqueue it in the load schedule with wp_enqueue_script.

How to do this only on a particular page?

The answer is very easily. Inside the function we can simply wrap the register and enqueue script actions with the following.

if(is_page_template('about.php')):
// code
endif;

Sweet as a nut. See below for the full finished code example.

The full thing

if(!function_exists('register_my_scripts')):
    function register_my_scripts(){
        if(is_page_template('about.php')):
            //Register our script
            wp_register_script('my-script',
            get_template_directory_uri() . '/assets/js/my-script.js',
            array('jquery'),
            '1.0' );
            //Enqueue the script
            wp_enqueue_script('my-script');
	endif;
    }
endif;

Some points

You will notice that in my wp_register_script I have used jquery as a dependancy this means that it will now be loaded by WordPress after jquery, neat huh?

You’ll also notice that I have put a version of 1.0 into the register, this is handy for upgrading the scripts to prevent caching problems, as the version is appended to the end of the file name like so:

http://localhost:8888/my-site/wp-content/themes/my-theme/assets/js/my-script.js?ver=1.0

If you make some changes and want to avoid any caching issues, simply upgrade the version to 1.1 in your code.

How to add custom meta boxes to WordPress

Many of us want to add custom meta boxes to WordPress post types and doing so is a relevantly easy jaunt, in this tutorial i’m going to show you how from start to finish to add a Custom meta box to your admin pages.

I’m going to run through a very simple example of adding your own custom-meta to a page called ‘homepage’ from start to finish.

First of all pull up your functions.php file.

Now add the following

add_action('add_meta_boxes',array(&$my_custom_meta,'home_create'));

Notice how we are passing an array with reference to the variable $my_custom_meta here. $mss_custom_meta is a class we are now going to define which will handle our custom meta handling.

Create a folder called includes/ and within create a file called custom-meta.php

Within custom-meta.php enter the following.

if(!class_exists('MY_Custom_Meta_Handler')):
    class MY_Custom_Meta_Handler{
        function __construct(){}
        function home_create(){}
    }
endif;

Save this and head back to your functions.php file.

You’ll hopefully remember from earlier that we were passing a reference of $my_custom_meta around. Now we need to define it.

require_once(dirname(__FILE__)."/includes/custom-meta.php");
$my_custom_meta = new MY_Custom_Meta_Handler;

Now we have our class in the $my_custom_meta variable ready to be passed in our add_action call already defined.

We’ve now done the very basis setup and we’ve got ourselves an action calling a class. Now we need to define what we want our extra custom fields to look like and what we want them to do. We’ll start by defining another action, where we want it to apply to and the function designated to control the looks of it.

add_meta_box('my_homepage_meta','Home Page Info',array(&$this,'home_display'),'page','normal','high');

As defined by WordPress:

add_meta_box( $id, $title, $callback, $page, $context, $priority, $callback_args );

Here we have said we want to give this meta_box the id of my_homepage_meta, the display title of Home Page Info, passed this class by reference using this and home_display function. We’ve then defined the page which in this case we’ve left as a ‘page’. Although it could be a post, page or any other custom post type you define.

$page
(string) (required) The type of Write screen on which to show the edit screen section (‘post’, ‘page’, ‘link’, or ‘custom_post_type’ where custom_post_type is the custom post type slug)
Default: None

$context
(string) (optional) The part of the page where the edit screen section should be shown (‘normal’, ‘advanced’, or ‘side’). (Note that ‘side’ doesn’t exist before 2.7)
Default: ‘advanced’

$priority
(string) (optional) The priority within the context where the boxes should show (‘high’, ‘core’, ‘default’ or ‘low’)
Default: ‘default’

Now that, that’s in we need to focus on the home_create function within our class. The home_create function is going to be repsonsible for outputting our form to the WordPress backend.

function home_create($post){
$my_home_meta_some_text = get_post_meta($post->ID, '_my_home_meta_some_text', TRUE);
?>
<table class="form-table">
<tr>
<th scope="row"><label for="my_home_meta_some_text">Some text:</label></th><td><input type="text" name="my_home_meta_some_text" id="my_home_meta_some_text" value="<?php echo esc_attr($my_home_meta_some_text); ?>">
</td>
</tr>
</table>
<?php
}

So here i've created a form input and got the current value out of the database for this value using the get_post_meta() function.

To finish up we now need a function which is responsible for saving out this new meta data. Head into the class once more and locate the __construct() function and add the following line.

function __construct(){
    add_action('save_post',array(&$this,'home_save'));
}

This adds an action to the action save_post which means everytime a post is saved it will be fired. Now lets define our home_save function.

function home_save($post_id){
if(isset($_POST['my_home_meta_some_text'])):
update_post_meta($post_id, '_my_home_meta_some_text', esc_attr($_POST['my_home_meta_some_text']) );
endif;
}

And wallah! We now have some custom meta saved to this page! With minimal effort. Here's the finished file and code to add to the functions.php file.

Functions.php

require_once(dirname(__FILE__)."/includes/custom-meta.php");
$my_custom_meta = new MY_Custom_Meta_Handler;
add_action('add_meta_boxes',array(&$my_custom_meta,'home_create'));

includes/custom-meta.php

if(!class_exists('MY_Custom_Meta_Handler')):
    class MY_Custom_Meta_Handler{
        function __construct(){
            add_action('save_post',array(&$this,'home_save'));
        }
        function home_create($post){
        $my_home_meta_some_text = get_post_meta($post->ID, '_my_home_meta_some_text', TRUE);
        ?>
        <table class="form-table">
        <tr>
        <th scope="row"><label for="my_home_meta_some_text">Some text:</label></th><td><input type="text" name="my_home_meta_some_text" id="my_home_meta_some_text" value="<?php echo esc_attr($my_home_meta_some_text); ?>">
        </td>
        </tr>
        </table>
        <?php
        }
        function home_save($post_id){
            if(isset($_POST['my_home_meta_some_text'])):
                update_post_meta($post_id, '_my_home_meta_some_text', esc_attr($_POST['my_home_meta_some_text']) );
            endif;
        }
    }
endif;

And there we have it, how to create custom meta boxes in WordPress.

Custom URL structure in WordPress using filters and hooks

WordPress, as we all know is one of the greatest open source website platforms available right now and what with it being open source and all that pretty much anything is possible with it.

You just need to dig deep enough and most of the time you’ll find the answer. I was looking for a simple way to rewrite a custom url to a page within wordpress.

I wanted to recreate a url like this dashboard/authorise/2/ with the 2 being an id for the object I am trying to authorise.

My page called ‘authorise’ with a page parent of dashboard would look out for the presence of the passed parameter and use it within the page to attempt an authorisation request for that object.

After alot of digging I found the answer within WordPress.

In the end I needed to use a combination of 3 hooks although one is not necessarily 100% necessary. All of the below snippets should reside in your functions.php wordpress theme file.

function flush_rewrite(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}
add_action('init', 'flush_rewrite');

This function simply flushes the WordPress re-write rules to the database. The second hook adds the expected parameter to the WordPress query vars filter and is required so that our page can pull the variable out later.

function add_wp_query_vars($public_query_vars){
    $public_query_vars[] = 'auth_id';
    return $public_query_vars;
}
add_filter('query_vars', 'add_wp_query_vars');

The third and final hook is to the “generate_rewrite_rules” hook, and it allow us to add a custom WordPress re-write rule for our new URL structure.

function authorise_rewrite_rules($wp_rewrite){
    $wp_rewrite->rules = array(
        'dashboard/authorise/(.*)/?' => 'index.php?pagename=authorise&auth_id='.$wp_rewrite->preg_index(1)
    ) + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'authorise_rewrite_rules');

As you can see i’ve included the full url including the parent of the page and re-written the arguments to auth_id. The final bit of information you now need to know is how to get this variable for usage on your page, its quite simple really.

global $wp_query;
echo 'Auth_id: '.$wp_query->get('auth_id');

Note: You do not have to use pagename like I have in my rewrite rule you could be using the “page_id” method instead, I just prefer pagename as it’s a bit more universal across installs. There you have it a simple way to keep nice URL’s within WordPress.

How to create WordPress pages with just pure PHP

I’ve seen alot of people ask how to create pages within WordPress with some simple PHP code so I thought i’d give answering it a go.

You’ll be pleased to know that the solution is pretty straight forward and nothing to strenuous.

We’ll start off by defining a function to handle creating pages in WordPress, you could use this function in your themes function file or indeed in any custom WordPress Plugin.

if(!function_exists('daves_create_page')):
    function daves_create_page( $slug, $option, $page_title = '', $page_content = '', $post_parent = 0){
        global $wpdb;
        $option_value = get_option($option);
        if ($option_value>0) :
            if (get_post( $option_value )) :
	        // Page exists
	        return;
	    endif;
	endif;
	$page_found = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '$slug' LIMIT 1;");
	if ($page_found) :
	    // Page exists
	    return;
	endif;
	$page_data = array(
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_author' => 1,
            'post_name' => $slug,
            'post_title' => $page_title,
            'post_content' => $page_content,
            'post_parent' => $post_parent,
            'comment_status' => 'closed'
        );
        $page_id = wp_insert_post($page_data);
        update_option($option, $page_id);
    }
endif;

After defining this function we can call it into play very simply with the following.

daves_create_page(
    esc_sql( _x('example_page', 'page_slug', 'davespage') ),
    'daves_page_id',
    __('Example Page', 'davespage'),
    'Some example content.'
);

Hope this helps some people out, as you can see, pretty straight forward and unobtrusive.

Correct way to add CSS to WordPress Plugin Backend

Many of us have dabbled with making our own WordPress plugins, but what alot of people forget is we need to make sure we’re as compatible with WordPress going forward as can be.

Over the last 3-5 months I’ve really started to discover the hidden power of WordPress and today i’m blogging about another find.

It’s quite a simple topic really. Many of you will want to include your own custom stylesheets with your plugins, but what’s important is keeping the integrity of your WordPress plugin intact.

So whats the correct way to Enqueue your css stylesheet?

There is a couple of ways in which you could achieve it, but being prudent is best.
Include the stylesheet only in the admin pages that you absolutely need to, in the case of the backend, only on the submenu pages you need to.

I am of course assuming here that your pretty familiar with the plugin backend and that you know how to create sub menu pages for your WordPress plugin.

$page = add_submenu_page(
    'edit.php',
    __( 'My Plugin', 'myPlugin' ),
    __( 'My Plugin', 'myPlugin' ),
    'administrator',
    __FILE__,
    'my_plugin_manage_menu' );
    /* Using registered $page handle to hook stylesheet loading */
   add_action( 'admin_print_styles-' . $page, 'your_plugin_styles' );

This would of course normally be wrapped in a function or class, whichever your coding style prefers.

We are telling WordPress in the above example to add an action to call our custom function ‘your_plugin_styles’ on printing styles for the page WordPress object reference now contained within $page.

// Hook somethings up in our plugins init function
add_action( 'admin_init', 'your_plugin_admin_init' );

Next, I have added an action to be fired on ‘admin_init’ to call ‘your_plugin_admin_init’.

And what i’ll do inside this is call a custom_forms.css file that I need to use for some styling on the backend of this plugin. I’ve also housed it in a css/ folder within my plugin directory for convenience.

function your_plugin_admin_init(){
    wp_register_style( 'yourCustomFormCss', plugins_url('css/custom_forms.css', __FILE__) );
}

And finally we enqueue our script using wp_enqueue_style

function your_plugin_styles(){
    wp_enqueue_style( 'yourCustomFormCss');
}

And this is our working procedure.

Bringing it altogether.

We first fire our plugins init function called ‘your_plugin_admin_init’ inside this we register our css style with WordPress. Ready to be called later. Then whilst registering our menus, we tell WordPress on this admin page ONLY, to fire our custom css calling function ‘your_plugin_styles’ and from within that we enqueue our previously registered script ‘yourCustomFormCss’ using ‘wp_enqueue_style’.

Some useful links