Programmatically Create & Delete Image Styles in Drupal

Need to programmatically create or delete an image style in Drupal? Maybe you’re creating a module that needs to define a new style or looking to use an update handler to delete one. It’s a cinch to do with just a few lines of code.

I recently needed to delete a image style that was no longer being used with a update handler. Being that Drupal’s documentation is less than informative, I did some digging and finally figured it out. Check out how to create, flush and delete image styles below. Continue reading “Programmatically Create & Delete Image Styles in Drupal”

Drupal Custom Tokens: How to Easily Create Your Own

A feature I regularly use in WordPress development are shortcodes. I needed the same functionality in Drupal. Like most things I’ve found with Drupal, it’s not as easy or clear on how to go about it. No need to fret though, I’ll walk you through how to get ahead of the learning curve and easily create custom tokens.

A feature I regularly use in WordPress development are shortcodes. I needed the same functionality in Drupal. Like most things I’ve found with Drupal, it’s not as easy or clear on how to go about it. No need to fret though, I’ll walk you through how to get ahead of the learning curve and easily create custom tokens.

Drupal’s documentation — or lack of — and a lot of posts I found on how to create tokens had conflicting information. This was mainly due to portions of the Token module getting moved into the core beginning with D7. Though, it doesn’t due much good for typical users if there’s no interface or UI for defining custom tokens.

In the examples below, I’ll show you how to easily create custom tokens within a module.

Creating Custom Tokens in Drupal 7

To create custom tokens in D7, we’re going to use two hooks:

  • hook_token_info() – This is where you’ll create the token and define what they are.
  • hook_tokens() – This is where the magic happens, you’ll tell Drupal what to replace your tokens with.

Below, we’re going to create a custom token that holds the user’s session status (Logged In, Logged Out). You could use this token in conjunction with GA’s custom dimensions to gather more detailed analytics.

Step 1: Create & define the custom token.

In your module, add the following code:

The code above will return an associative array with your custom tokens data:

  • Name: The translated human-readable short name of the token.
  • Description: A translated longer description of the token.

It’s important to note the structure of the array: $info['tokens']['user']['session-status']. Where user is the token type, and session-status is the machine-friendly name.

If you have the Devel module installed, you can use dpm(token_get_info()) to view all available tokens and types.

Step 2: Replace the token.

In your module, after the code above, add the following:

That’s it! The session status token should now be available and appear in the list of tokens wherever tokens are available.

Helpful Drupal Token Modules

Here’s some helpful modules that will make working with tokens in Drupal easier:

  • Token – Provides a UI to view currently available tokens.
  • Token Filter – A very simple module to make token values available as an input filter.
  • Custom Tokens – Gives users the ability to create custom tokens for specific replacements.
  • Token Insert – Allows you to insert tokens into a textarea.

More Information on Drupal Tokens

PHP MySQL Connect, The Right Way!

Connecting to MySQL with PHP is a common among developers. Without a proper connection, your site performance and security could suffer. Learn how to setup & run queries with a PHP MySQL connection, the right way!

Connecting to MySQL with PHP is a common among developers. Without a proper connection, your site performance and security could suffer. Learn how to setup & run queries with a PHP MySQL connection, the right way!

PHP MySQL ConnectCode is a living text. All developers should be aware and embrace this fact. No matter the type of development you do, a year from now, there will probably be a better way to accomplish what you did today. Code is constantly evolving as technology improves—a perfect example being how to connect to MySQL with PHP.

I’ll walk you through how to properly connect to your MySQL databases with PHP for better site performance and security. Learn how to connect to MySQL with PHP the right way!

Connecting to MySQL with PHP

There’s many way to connect to MySQL with PHP. Some options include:

Which one is the best? Doing a quick Google search for ‘php mysql connect‘ will yield a ton of results with one common theme—connecting to MySQL with PHP should be done using a PDO connection. In the old days, most developers used mysql_connect to talk to their database. Code has evolved and that method has been officially deprecated as of PHP 5.5.0. You could use mysqli, but PDO is more stable with better performance and database support. There’s a great in-depth article by Dejan Marjanovic detailing the differences between PDO and MySQLi.

PDO MySQLi
Database support 12 different drivers MySQL only
API OOP OOP + procedural
Connection Easy Easy
Named parameters Yes No
Object mapping Yes Yes
Prepared statements (client side) Yes No
Performance Fast Fast
Stored procedures Yes Yes

PHP MySQL Connect with PDO

PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.

There’s a ton of articles out there about PDO, how it works, why to use it, and detailed information on it’s functions (see the bottom of this post for more information). Instead of going into all the intricacies, I’m just going to show you how to use it. So, let’s start off with the basics, how to use PDO to connect to MySQL.

Connecting with PDO

Depending on the type of database you’re using, there are slightly different connection methods. The example above uses MySQL. Here’s some other types of connection methods:

What if you run into errors? You should always wrap your PDO operations in a try/catch, and use the exception mechanism:

This will output any connection errors you might run into. It’s important to note, the default error mode for PDO is PDO::ERRMODE_SILENT. If you don’t spefify the mode, you’ll need to manually fetch errors after performing a query. PDO has three error modes, in the example above, where using ERRMODE_EXCEPTION. This is the mode you’re going to want to use in most situations. It’ll fire an exception allowing you to handle errors gracefully and hide data that might help someone exploit your system. Here’s the other two modes available:

Fetching Data with PDO

There’s a couple of different ways to run queries using PDO. Generally, it’s best to use prepared statements to safeguard against SQL injection. With the prepare method we prepare the query before the user’s data gets attached. See below:

For better readable code, it’s best to use named parameters vs. ?. Notice we used :name to specify the placeholder.

You could also use the bindParam:

Now, let’s look at how to get the output. Once you’ve called the execute method, there’s a variety of different ways to get your data: an array (the default), and object, etc. In the example above, we’re using the default PDO::FETCH_ASSOC to return an array. This can easily be overridden like so:

Here, we’re returning an anonymous object with property names that correspond to the columns. Other choices include, but not limited to:

  • PDO::FETCH_BOTH: Returns an array, indexed by both column-name, and 0-indexed
  • PDO::FETCH_BOUND: Returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound
  • PDO::FETCH_CLASS: Returns a new instance of the specified class

No results? No problem.

What if no results are returned? That’s the problem with the code above, we’re not providing any feedback if nothing is returned. We can easily fix that with the following:

Taking it a step further…

One of the benefits to using the PDO extension is the ability to execute the same SQL query multiple times with different parameters. Check out the example below:

The example above shows how you can easily execute the same query multiple times using different parameters. It’ll insert two rows, one with a name of “Ben”, and the other with “Angel”.

Creating, Updating, Deleting

Now that you’re connected, you’re probably going to want to run some queries. We looked into how to insert data above a little, now I’ll show you some more examples how to create, update and delete data:

Insert

Update

Delete

PDO Object Mapping

One of the coolest aspects of using PDO (mysqli can do this as well), is the ability to may query results to a class or object. See below:

Other Helpful Methods

Here’s some other helpful methods that will make life a lot easier when running queries with PDO:

Get last insert ID

lastInsertId() should always called on the database handle, not statement handle, and will return the auto incremented id of the last inserted row by that connection.

Return number of rows affected

The rowCount() method returns an integer indicating the number of rows affected by an operation. In at least one known version of PDO, according to this bug report the method does not work with select statements. If you’re having this problem, and can’t upgrade PHP, you could get the number of rows with the following:


More On PHP MySQL PDO Connections

WordPress AJAX: Frontend & Backend Implementation

I was recently working on a WP site that required AJAX functionality on the frontend. Having implemented WordPress AJAX for my Book It! Transportation plugin on the backend, I figured it would be a cinch. Come to find out, it required a little more work to accomplish.

I was recently working on a WP site that required AJAX functionality on the frontend. Having implemented WordPress AJAX for my Book It! Transportation plugin on the backend, I figured it would be a cinch. Come to find out, it required a little more work to accomplish.

After digging around multiple blogs and the WordPress Codex, I found it a little difficult to find full working examples. Get ahead of the learning curve by learning how to implement WordPress AJAX for both the frontend and backend below.


WordPress AJAX for the Backend

This is a cinch to do. Currently, the core of WordPress uses AJAX only in the administration screens. For instance, AJAX is used for instant updates when you are doing comment moderation, and when you are adding and deleting items from lists such as categories, blogroll, and posts; AJAX is also the technology behind the auto-save functionality on post and page editing screens. Several themes and plugins also use AJAX; for instance, some post rating plugins use AJAX to store the visitor’s rating in the database and then display an updated average rating.

Since AJAX is already built into the core WordPress administration screens, adding more administration-side AJAX functionality to your plugin or theme is fairly straightforward, check out the example below.

This should be fairly straight forwared. It uses WP’s admin_footer action (see add_action) to include some JS in the footer that makes the AJAX magic happen. Take a look at $.post if you’re not familiar with it.

With the code above, you’re defining your action, a WordPress nonce for security, and any other data you want to send. You’ll use the action you define as part of the WP function you’ll create that handles the AJAX request. See below:

We’re using WP’s wp_ajax_(action) hook to handle the AJAX request. This hook allows you to create custom handlers for your own custom AJAX requests. The wp_ajax_ hook follows the format “wp_ajax_$youraction”, where $youraction is your AJAX request’s ‘action’ property you sent in the JS above.

Also, be sure to include the check_ajax_referer to verify that the request came from the right place.

That’s it! You will need to add a few details, such as error checking, but hopefully the example above will be enough to get you started on your own administration-side AJAX plugin.

WordPress AJAX Backend Example

Here’s a full working example of WordPress AJAX in the backend. This will produce a JS alert box with the text 1044 when a page has been loaded in the administration panel. In the functions.php file:

WordPress AJAX for the Frontend

This takes a little extra work to accomplish. Since WordPress 2.8, there is a hook similar to wp_ajax_(action):

You’ll need to use this hook if you’re planning on implementing WordPress AJAX on the frontend. If you want to fire your AJAX function both both logged-in and logged-out users, you’d do this:

Something else to keep in mind when implementing WordPres AJAX on the frontend is, unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, you’ll need to declare a javascript namespace object with its own property, ajaxurl. Use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( 'admin-ajax.php' ). See below:

Another thing to keep in mind is, both front-end and back-end AJAX requests use admin-ajax.php so is_admin() will always return true in your action handling code. When selectively loading your AJAX script handlers for the frontend and backend, and using the is_admin() function, your wp_ajax_(action) and wp_ajax_nopriv_(action) hooks MUST be inside the is_admin() === true part.

AJAX requests bound to either wp_ajax_ or wp_ajax_nopriv_ actions are executed in the WP Admin context. Carefully review the actions you are performing in your code since unprivileged users or visitors will be able to trigger requests with elevated permissions that they may not be authorized for. See below:

Here the AJAX action my_frontend_action will trigger the PHP function my_frontend_action_callback() for all users. The AJAX action my_backend_action will trigger the PHP function my_backend_action_callback() for logged-in users only.

WordPress AJAX Frontend Example

Here’s a full working example of WordPress AJAX in the frontend. This will produce a JS alert box with the text 1044 when a page has been loaded in the administration panel. In the functions.php file:

In the example.js file:


Learn more about WordPress AJAX

MailChimp PHP API Class: Simple Library for MailChimp API V2

The past couple of months I’ve been working to move a little over 260,000 subscribers from Eloqua to MailChimp. The company that owns the site does heavy email marketing that differs from the typical MailChimp user. This requires some advanced functionality that MailChimp’s interface does not provide. The solution, MailChimp API which allows us to build out our own custom functionality where MailChimp falls short.

The past couple of months I’ve been working to move a little over 260,000 subscribers from Eloqua to MailChimp. The company that owns the site does heavy email marketing that differs from the typical MailChimp user. This requires some advanced functionality that MailChimp’s interface does not provide. The solution, MailChimp API which allows us to build out our own custom functionality where MailChimp falls short.

I was going to build out my own MailChimp PHP API class, but luckily after a little digging, found Drew McLellan‘s MailChimp v2 wrapper. Unlike a lot of the PHP libraries out that are complex, confusing wrappers, this one is super-simple and light-weight. It allows you to quickly access the MailChimp API and start coding your own applications.

Download the MailChimp PHP API Class

MailChimp PHP API Class

Using this MailChimp PHP API Class is as simple as the class is itself. You can either download it by clicking the button above or install the mailchimp-api using Composer. In order to install it with Composer, see the docs for more details.

Once you’ve got it installed, you’ll be ready to build out your application. Just grab your MailChimp API key and initialize the class.

Once initialized, you can begin calling out to the MailChimp API and request the data or functionality you need for your app.

MailChimp PHP API Class Examples

I’m a visual learner, so put together some examples for the MailChimp PHP API Class. I’m also interested in how others use APIs to build out applications. Be sure to comment below and let me know how you’ve integrated this API for your projects.

List Related Methods

List Related Methods

These are just a few examples using the MailChimp API. Check out their docs for a full list and details of all the methods they provide.


MailChimp List Related Methods

Get emails that complained.

MailChimp API Method:
lists/abuse-reports (string apikey, string id, int start, int limit, string since)

Access up to 180 days of aggregated activity for a list (does not include AutoResponder activity).

MailChimp API Method:
lists/activity (string apikey, string id)

Subscribe a batch of emails.

MailChimp API Method:
lists/batch-subscribe (string apikey, string id, array batch, boolean double_optin, boolean update_existing, boolean replace_interests)

Maximum batch sizes vary based on the amount of data in each record, though you should cap them at 5k – 10k records, depending on your experience. These calls are also long, so be sure you increase your timeout values.

Unsubscribe a batch of emails.

MailChimp API Method:
lists/batch-unsubscribe (string apikey, string id, array batch, boolean delete_member, boolean send_goodbye, boolean send_notify)

Retrieve the clients that the list’s subscribers have been tagged as being used.

MailChimp API Method:
lists/clients (string apikey, string id)

Access the Growth History by Month in aggregate or for a given list.

MailChimp API Method:
lists/growth-history (string apikey, string id)

Add a single Interest Group.

MailChimp API Method:
lists/interest-group-add (string apikey, string id, string group_name, int grouping_id)

If interest groups for the List are not yet enabled, adding the first group will automatically turn them on.

Delete a single Interest Group.

MailChimp API Method:
lists/interest-group-del (string apikey, string id, string group_name, int grouping_id)

If the last group for a list is deleted, this will also turn groups for the list off.

Change the name of an Interest Group.

MailChimp API Method:
lists/interest-group-del (string apikey, string id, string old_name, string new_name, int grouping_id)

Get the list of interest groupings for a given list.

MailChimp API Method:
lists/interest-groupings (string apikey, string id, bool counts)

Add a new Interest Grouping.

MailChimp API Method:
lists/interest-grouping-add (string apikey, string id, string name, string type, array groups)

If interest groups for the List are not yet enabled, adding the first grouping will automatically turn them on.

Delete an existing Interest Grouping.

MailChimp API Method:
lists/interest-grouping-del (string apikey, int grouping_id)

This will permanently delete all contained interest groups and will remove those selections from all list members.

Update an existing Interest Grouping.

MailChimp API Method:
lists/interest-grouping-update (string apikey, int grouping_id, string name, string value)

Retrieve all of the lists defined for your user account.

MailChimp API Method:
lists/list (string apikey, struct filters, int start, int limit, string sort_field, string sort_dir)

Retrieve the locations (countries) that the list’s subscribers have been tagged to.

MailChimp API Method:
lists/locations (string apikey, string id)

Get the most recent 100 activities for particular list members.

MailChimp API Method:
lists/member-activity (string apikey, string id, array emails)

Get all the information for particular members of a list.

MailChimp API Method:
lists/member-info (string apikey, string id, array emails)

Get all of the list members for a list.

MailChimp API Method:
lists/members (string apikey, string id, string status, struct opts)

MailChimp API Method:
gallery/list (string apikey, struct opts)