regex to find valid URLS and make clickable HTML link

The following PHP preg_replace function will looking for valid URL’s in a string and turn them into clickable links.

For example, if you have a block of text and need to find all URL’s and turn into clickable links.

Note: replace target=”_blank”) to have links open in the same window.

$value = preg_replace( '!(((f|ht)tp(s)?://)[-a-zA-Z?-??-?()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1" target="_blank">$1</a>', $value );

WordPress – How to use IN in WPDB PREPARE SQL statements

In an SQL statement, the IN operator allows you to multiple values in a WHERE clause, for example:

SELECT * FROM 'table' WHERE 'field_id' = 1 AND 'field' IN ( 'value1', 'value2' )

When it comes to using this in WordPress things get a little more complicated when you need to pass it through the WPDB PREPARE method.

If the values for IN are known you can write them literally (as shown above), or if the number and type (string/digit) are known you can simply add them in as normal, for example:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'field_id' = %d AND 'field' IN ( %s, %s )", $field_id, 'value1', 'value2' );

But this is not often the case. Normally IN will be used to cross check against another set of data where the length is unknown.

The examples below show how to use the IN operator when using WPDB PREPARE.

Using the IN operator with digits (numbers)

Using the IN operator with numbers is a lot simplier because numbers are written without quotes.

For example ‘field’ IN ( 1, 2, 3 )

This means you can nest a second SQL statement and let SQL do it’s magic. For example:

$sql = $wpdb->prepare(
            " SELECT * FROM 'table'
                                WHERE 'field_id' = %d AND 'field' IN (
                                    SELECT 'field' FROM 'table_2'
                                )", $field_id
        );

Using the IN operator with strings (text)

Text is a little more complicated because each value needs quotes to show the start and end of the string.

For example, field IN ( ‘value1’, ‘value2’, ‘value 3’ )

To do this you need to start with your values in an array, for example

$values = array( 'value1', 'value2', 'value 3' );

then create a string with an %s for each value

$in_str_arr = array_fill( 0, count( $values ), '%s' );

and then use join to turn each %s into a comma separated string, for example

$in_str = join( ',', $in_str_arr );

This will make $in_str literally “%s, %s, %s”

And finally, add $in_str and your values into the WPDB PREPARE statement.

$sql = $wpdb->prepare(
            " SELECT * FROM 'table'
                                WHERE 'field_id' = %d AND 'field' IN (
                                   $in_str
                                )", $field_id, $values
        );

 

Full example:

$values = array( 'value1', 'value2', 'value 3' ); // start with the values in an array
$in_str_arr = array_fill( 0, count( $values ), '%s' ); // create a string of %s - one for each array value. This creates array( '%s', '%s', '%s' )
$in_str = join( ',', $in_str_arr ); // now turn it into a comma separated string. This creates "%s,%s,%s"
// now add into the SQL statement - BOTH where the each %s is meant to be an as a parameter to PREPARE
$sql = $wpdb->prepare(
            " SELECT * FROM 'table'
                                WHERE 'field_id' = %d AND 'field' IN (
                                   $in_str
                                )", $field_id, $values
        );

 

WordPress – How to use LIKE in WPDB PREPARE SQL statements

In WordPress the WPDB class is available for interacting with the database, for example reading or writing data.

The PREPARE method is almost always used along with the WPDB.

PREPARE helps protects from SQL injection vunerabilities by ensuring variables are what they’re meant to be (strings or digits).

It requires you to write the SQL statements with %s (for a string) or %d (for a digit) in place of a variable, then providing the variable as a parameter.

For example:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' = %s AND 'field' = %d", 'something', 1337 );

The problem with wildcard characters

By using the % character in PREPARE it takes on a completely different meaning which can cause problems when it comes to using it as a wild card in SQL LIKE statements.

For example, this would not work:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' like '%something' AND 'field' = %d", 1337 );

Because PREPARE will try to replace %s in the SQL statement.

There are two ways to get around this –

Escape %s with a second %

Note: with this method you need to add quotes around the condition.

For example:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' like '%%something' AND 'field' = %d", 1337 );

Pass the like condition as a parameter

For example:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' like %s AND 'field' = %d", '%something', 1337 );

This is my prefered method as it allows you to add in variables, for example:

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' like %s AND 'field' = %d", '%something' . $var, 1337 );

Escaping like conditions

As an added level of protection, WPDB also has a method called ESC_LIKE that will escape characters that will break a SQL LIKE statement.

This must be used when the LIKE condition involves a ‘dirty’ variable – for example one provided by a user.

The ESC_LIKE method sanitises the variable by escaping the % and _ characters inside the variable.

For example, if $var was ‘dirty’.

$wpdb->prepare( "SELECT * FROM 'table' WHERE 'column' like %s AND 'field' = %d", '%something' . $wpdb->esc_like( $var ), 1337 );

Should you use anonymous functions in WordPress actions and filters?

At their simplest, an anonymous function is an unnamed function. There are many ways they can be used to simplify your PHP – when it comes to WordPress I’ve often wondered if it’s a good or a bad thing to use anonymous functions when adding an action or filter.

For example, a WordPress filter using an anonymous function would would look like

add_filter( 'gform_default_address_type', function ( $default_address_type, $form_id ) {
return 'us';
}, 10, 2 );

The alternative, using a named function, would look like

add_filter( 'gform_default_address_type', 'default_address_type', 10, 2 );
function default_address_type ( $default_address_type, $form_id )  {
return 'us';
}

So should you use anonymous functions with your actions and filters?

No – not unless you know what you’re doing an accept the disadvantages.

Whilst the WordPress Coding Standards guide does not touch on the topic, I have not seen one anonymous function in the whole WordPress core (interestingly in the JavaScript they do, just not in the PHP section).

Consistent coding style is critical with all software, but even more so with open source projects like WordPress. If WordPress core is not using them, I don’t think they have a place in plugins, themes or customisations.

Other good reasons are …

  • you won’t be able to remove the function using remove_action() or remove_filter()
  • the functions are unnamed and are therefore missing a key bit of documentation/context – developers tend to use the name to describe the purpose of the function
  • the functions cannot be used more than once
  • you need at least PHP version 5.3.0 – there is a surprisingly high number of cheap web hosts running websites on older versions of PHP

 

 

How to install WordPress IIS local test environment the easy way

The following guide shows how to install a WordPress IIS test environment on your computer.

There are many guides that do this the hard way – installing IIS, PHP, mySQL, configuring and what not.

This guide skips all that by using Microsoft Web Platform Installer.

Step 1: Install Microsoft Web Platform

  1. Open the Microsoft Web Platform Installer website – www.microsoft.com/web/downloads/platform.aspx
  2. Download and begin the install
  3. Once loaded, click on the ‘Install’ button to begin
  4. WordPress-WebMatrix1
  5. Click ‘I Accept’
  6. WordPress-WebMatrix2
  7. The installer will now download and install any required components
  8. When done  you see see a confirmation message and list of components that have been installed.
  9. WordPress-WebMatrix3
  10. Click ‘Finish’.

Step 2: Install WordPress

  1. In the window that loads, use the search box at the top right to search for ‘WordPress’
  2. In the search results below, click on the ‘Add’ button next to WordPress then click on the ‘Install’ button at the bottom of the window.
  3. WordPress-WebMatrix4
  4. Enter a password for the database user. This is not the password you use to access WordPress – it is the password WordPress uses to access the database. In a producation install of WordPress you would make this password as complicated as possible, like a random stringe of numbers, leters and characters – but given that this will be a test install of WordPress you can choose a less secure password.
  5. Click ‘Continue’ after entering in the database password.
  6. You will now see a list of the required software to do your WordPress install.
  7. Click ‘I Accept’ to begin the install.
  8. WordPress-WebMatrix6
  9. The install will take around five minutes to complete.
  10. WordPress-WebMatrix7

Step 3: Configure WordPress

  1. When the install has finished the ‘Configure’ window will be displayed
  2. Here you can enter your unique salts that help secure WordPress passwords and communications.
  3. Since this is just a test environment, it’s fine to click ‘Continue’ – however you may choose to go to the WordPress salt generator website to get unique values for each of these fields.
  4. WordPress-WebMatrix8
  5. When WordPress has finished installing, click ‘Finish’ to close the window.

Step 4: Running your IIS WordPress install

  1. When the install has finished a browser window will open with WordPress ready to use.
  2. The WebMatrix program needs to be open for the WordPress to run
  3. WordPress-WebMatrix9
  4. From WebMatrix you can start, stop, restart the WordPress install and edit files using the built-in code editor.
  5. WordPress-WebMatrix10

How to create a WordPress plugin for your custom functions

Typically WordPress plugins are for a single purpose – such as a tool, and any custom functions you need are added to your active theme’s functions.php file.

The issue with this is that each time the theme is updated you lose the changes made to the functions.php file.

One way around this is to create a child theme – but it still has it’s own limitations, such as the plugins_loaded action hook doesnt fire because it needs to be called before the theme has loaded.

The answer to this is to create a simple custom plugin that can contain all your custom functions. This way you can update your theme without worrying about loosing any of your customisations.

WordPress-CustomPlugin1

There are other advantages to this – it’s easier to maintain as you can use the plugin version number to create your own version control, and easier to debug – if you have any issues you can just disable the plugin to see if the issues are caused by your customisations.

Here’s what you need to do.

  1. Using the sample plugin header below, copy to a new text file and save as a PHP file. For example itsg-custom-functions.php
  2. <?php
    /*
    Plugin Name: itsupportguides.com custom functions
    Description: Contains custom functions
    Version: 1.0.0
    Author: IT Support Guides
    Author URI: itsupportguides.com
    */
  3. Add your custom functions below the closing */
  4. TIP: make sure that you do not have the same functions anywhere else – such as the themes function.php file.
  5. ZIP the file up, so you have something like this sample plugin: itsg-custom-functions.zip
  6. Now open up the WordPress adminisation console
  7. Open the Plugins page and click on ‘Add Plugin’
  8. WordPress-CustomPlugin2
  9. Now click on the ‘Upload Plugin’ button and upload the ZIP’ed plugin file
  10. WordPress-CustomPlugin3
  11. The plugin will upload and activate automatically.
  12. You can now maintain all your custom functions from the plugin instead of your theme’s functions.php file.

Stuck? Have a look at my sample plugin: itsg-custom-functions.zip

[SOLVED] WordPress ‘Cannot modify Header Information’ when saving post

Problem

When attempting to save a WordPress post you recieve the following error message

Warning:  Cannot modify header information - headers already sent by ... in ... on line ...

WordPress-CannotModifyHeaderInformation1

Solution

There are many issues that may cause this error – all are code related, so you will need the ability to disable plugins, change themes and edit the websites PHP files to fix the error.

Step 1 – find the culprit

In the error message you will see ‘headers already sent by’ followed by a path and file name.

The path and the file name will tell you where the error is – but not which line. The line number mentioned is where the WordPress code conflicted.

If the path includes ‘plugins’ – use the path to work out the name of the plugin and try disabling it from the WordPress administration.

If the path includes ‘themes’ – use the path to work out the name of theme and try changing themes from the WordPress administration.

Does the error message still happen? If not you’ve found the culprit.  If it still happens you will need to continuing the process of disabling plugins and changing themes until resolved.

Step 2 – fix the code

This is the hard part. You know the path, you know the file – but you don’t know the line that cuased the error.

Open the file using your prefered method – typically this is done using FTP (best option), through your host cpanel account, or using the WordPress code editing feature (this is a little more risky – if you do it wrong WordPress may not load and you will not be able to undo the changes).

Check for the following issues:

  1. If the file has a blank line before the opening <?php you will need to delete the blank line. PHP files must start with <?php followed by a line break
  2. (only an option if using FTP) Open the file using notepad++ from the Edit -> EOL Conversion menu make sure that either Windows or UNIX is selected (UNIX is most probably the most suitable option here), from the Encoding menu make sure that ‘Encode in UTF-8’ (or Encode in UTF-8 without BOM) is selected. Save the file.
  3. Check the end of the file – if there is there a ?> you can delete this. PHP files do not need to be closed – this doesnt create issues on itself, but does when there is a space between them. E.g. ? > would create issues.
  4. Copy the code in the PHP file and run it through an automated PHP code checker, such as phpcodechecker.com

Still got the problem?

Try contacting the developer of the plugin or theme you identified in step 1.

Leave a comment below if you find or know of other solutions for this problem – others will appreciate it.

WordPress – Use one variable multiple times using $wpdb->prepare

Question

How do you use a variable multiple times when using $wpdb->prepare   ?

Answer

If your prepared SQL statement needs to refer to a variable more than once you need to include it as a parameter multiple times.

For example, the SQL query below refers to the user_id twice – both for the use_id and conrtributor_use_id column

SELECT id, title, user_id, contributor_user_id WHERE user_id = 1 OR contributor_user_id = 1

To prepare this statement you would need to do this

$wpdb->prepare( "SELECT id, title, user_id, contributor_user_id WHERE user_id = %d OR contributor_user_id = %d", $user_id, $user_id );