How to use Mailgun with MyMail the newsletter plugin for WordPress?

Like most of you I use MailChimp to publish newsletters and for the management of my mailing list. If the number of subscribers becomes bigger it’s often more lucrative to use a WordPress plugin like MyMail together with a transactional mail service provider. In the past was MyMail and Mandrill an inexpensive combination, but since Mandrill has become a premium add-on for MailChimp, many MyMail users are looking for alternatives.

Setup Mailgun for MyMail

Selecting a new transactional mail service for MyMail

Currently you can choose from the add-on section the following SMTP providers for your MyMail application: Mandrill, Amazon SES and Sendgrid. According the product support there should be an option for Mailgun too, but it’s not done until now. There is also a Mailgun add-on for MyMail on Github, but this doesn’t work with current version of MyMail.

How to install Mailgun for MyMail?

First of all you need a Mailgun account. Get one here (it’s free for the first 10.000 mails/month) and add your sending domain name to that account. The whole process is well documented in your Mailgun account, so I don’t repeat it here. If your ready, you will have the SMTP server information including your credentials on the domain’s settings page. Use this information for the MyMail settings: Dashboard > Newsletter > Settings > Delivery. Choose the tab “SMTP” and enter “” on port “587” and enter also your SMTP credentials. After saving this settings your screen should look like this:

Mailgun SMTP settings

Above the form named “Delivery Method” is an option to test your SMTP connection.

How about mail bounces?

Handling mail bounces is important because every time you send an email that can’t be delivered, that message is counted for account and a high bounce ratio is bad for your accounts authority. It’s like sending the mail delivery guy to a non existing address over and over again. You can find a list of bounces in your Suppressions list.

List of mail bounces

With the Mandrill add-on it wasn’t necessary to configure the MyMail plugin for mail bounces, because all bounces are reported back to MyMail via Mandrill. Since we use SMTP as the delivery method now, mail bounces need some configuration. You can do this with the mail bounce feature from MyMail (tab “Bouncing”). For this function it’s necessary to forward all bounces to a mailbox where MyMail will “read” these message for further processing. In my personal opinion is this not the best way to handle bounces. Mailgun will collect all bounced email addresses and we need only a simple way to tell MyMail that these addresses need to get off the active subscriber list.

A simple script to process the bounces also in MyMail

The following simple script is maybe a quick and dirty method to handle the mail bounces, but you can use it until the Mailgun add-on for MyMail is released (I’ve read in the comments that the developer has this for more than 1 year on his list!).

The script has two functions: 1) Get the list of all (max. 100 at a time) bounced email address to them to update the status of the subscribers in your MyMail list. 2) Remove the bounced email address from the Mailgun Suppressions list right after the subscriber is updated. The last function is necessary, because otherwise the list will become bigger an bigger.

Place this script on your website and protect the directory with a password. Change the path for the wp-load.php script and the values for the variables $apikey$domain and $mymail_table. You can find your API key on the Mailgun settings page. The value for the variable $mymail_table is a combination of your WordPress table prefix plus “mymail_subscribers”. If you prefix is “wp123_” the table name would be “wp123_mymail_subscribers”. You can run the script in your browser (every time before you like to issue a new newsletter) or you can run a daily CRON job. The script is using functions from the WordPress HTTP API and the new Mailgun Surpression API. 

I will transform this PHP script into a WordPress plugin if the MyMail add-on for Mailgun isn’t released over a couple of weeks. If you have any questions please post them using the comment form.

Parse html with preg_match and preg_match_all

PHP preg_match_allFor the most of the web developer which are using the function preg_match, is the function preg_match_all a smaller advantage, but for all others it’s maybe hard to understand. The biggest difference between preg_match_all and the regular preg_match is that all matched values are stored inside a multi-dimensional array to store an unlimited number of matches. The first part of this preg_match_all. tutorial is about how to “collect” the image source values inside a web page. For many other  parts in a HTML document is the preg_match function more useful, that’s why I added two other examples: A PHP backlink checker and a example that extracts the title and META description from a webpage.

preg_match_all tutorial

Live Chat Software

Let’s take a closer look on the regular expression pattern:


The first part and the last part are searching for everything that starts with src and ends with a optional quote or double quote. This could be a long string because the outer rule is very global. Next I check the rule starts within the first bracket:


Now I will test inside the long string from the outer rule for strings starting with an optional quote or double quote followed by any characters. The last part inside the inner brackets is the magic:


Next I will test for a string that is followed by a file extension and if there is a match I will retrieve all the paths from the HTML file.

I need all the rules to isolate the string parts (image paths) from the rest of the HTML. The result looks like this (access the array $images with these indexes, or just use print_r($images)):

$images[0][0] -> src="/images/english.gif"
$images[1][0] -> /images/english.gif
$images[2][0] -> gif

The index [1] is the information I need, try this preg_match_all example with other parts of HTML code and experiment for a better understanding. 

A PHP link checker “powered” by preg_match

This function is useful for people with a link directory website where the links are stored inside a (MySQL) database. The PHP script below is used to check if a reciprocal (external) link still exists on a specific webpage. The script takes care about the trailing slash in URLs and can be used with (almost) every URL. Inside the function preg_match is used to check for a link against the a regular expression.

You can try this PHP link checker here.

Extract Page title and META description from a webpage

With this script it’s possible to obtain the first part of a remote file to parse the html elements in local script. The title element and the meta description are parsed while using preg_match() function. Additional HTML head elements are possible, by adding some extra rules and regex patterns. The script reads only the first part (the head) of a remote file for a better performance. 

DEMO: Get page title and META

Create a CSS navigation bar showing the current state

These days it’s almost a standard to use an un-ordered list element for your page navigation. While a vertical list in some sidebar is some easy piece of work, is the horizontal CSS navigation bar a little bit more complicated.

Preview and example navigation

We need to float the list elements to get them in the horizontal order. There are many great examples on this CSS resource site and also our example here is based on one of the tutorials listed on the suggested site. Notice the active state in the preview above, this is not easy without any scripting language.

Generating the HTML snippet

The next snippet has for the first list item the attribute id “current”. To create some intelligent function to have one code snippet for all of our pages we need some tiny PHP function to get some dynamic navigation:

First we create an array for the links and link labels we want to use in our navigation. You can use also some database result, but you need to change the code a little bit (using a while loop in place of a foreach). Next we loop through all array elements (or the result set) and test every link value against the current URL. If there is a match we add the ID attribute the code. At the end we return the whole HTML snippet.

Some CSS style for our navigation

While the navigation is very simple (just using one level) we need only some style sheet for the unordered list elements. We need to disable the list-style-type and we float the list nodes inside the unordered list container.

Don’t forget that we are working with a block type element and all those elements are having a 100% width by default. While using a float we change that behavior and the list nodes are ordered in a horizontal direction. Next we like to have some more design elements and also a different style if we hover the mouse above a link item. We add some other style definition for the link/hover elements. At last but not least we need some extra style for the current state in our navigation bar:

You can use this PHP/HTML code example for all your navigation menus, just use different style sheets. If you need more ideas just check the CSS resource site link at the begin from this tutorial.

Customizing the Yet Another Related Posts Plugin

I love WordPress. I really do. Maybe not as much as Olaf, but he’s made a convert out of me. I’m using it more and more for my sites but am getting increasingly frustrated at how many of the “˜standard’ plugins and widgets don’t seem to be as complete as they could be. So many of them don’t seem to implement SEO best practices or take advantage of all of the great related posts most blogs have.

Google’s Panda update has caused me to rethink all of my sites, how they cross-link internally and how I can position my content to gain more visitors. When I’m writing content for static pages or blog sites, I always look for opportunities to link to old posts or future posts that could help support the one I’m writing.

While there’s more to be gained SEO-wise from cross-linking within the paragraphs, adding suggestions for further reading are great for the user experience and SEO. Providing a list of related posts does that perfectly.

One of the most popular WordPress related posts plugin is Yet Another Related Posts Plugin (YARPP). While I sometimes cringe at the choices it makes and wish I could tell it which posts to related to each other, users of the plugin can add their own formatting and customizations to make the output match their theme.

Olaf and I were discussing this the other day and he thought our ideas would make a great tutorial and something that would work great on a new project of mine…

Create your own related posts theme

The perfect situation would be to get a list of related posts where you can choose the 2 or 3 articles which get placed below your article. But, what happens if you change or delete an article? Your related list may end up without posts or if you add the links right into your article you could create dead links. The best solution is a system that can choose those articles for you and will update the list after a new, more relevant article becomes available.

How-to create a stunning related article list

1. Install, 2. enable the YARPP plugin and 3. copy one of the example templates from the plugin directory into your theme directory (f.e. example.php). Enter the settings page and enable the following option:
Automatically display related posts?
Display using a custom template file (choose the template name from the file in your theme directory)

Now visit a recent post and notice the list of comments below the content. We will optimize this list now! Open the your new custom template file in your text editor and replace the code with:

Save the file (upload if needed) and refresh the blog post you looked at earlier. You should notice a slightly changed result (we will put some style later).

Since WordPress version 2.9 there is a function called “post_thumbnail”. We would like to have one before each related list item. If your theme does not already utilize thumbnails, you will need to enable them before proceeding. For each theme there is a file called “functions.php”, open this file and add the following code:

This will enable the thumbnail function in your theme and will set the image size to 50 pixel.

Edit one of the articles in your list and look for the box called “Featured Image”. Click the link, upload or select an image and choose “Use as featured image”. It’s not required to use the same image as in your post. Save your article and add this code to your related post template (right before the link/title)

You need to upload the default image to your theme’s image directory as well. Save the script (and upload) and check your post with the related posts again. You will notice some image together with your list items. Let’s add some additional text to each item. We’ll use the function “the_excerpt” for this. This WordPress function will add the first 55 words from your article or the text which is entered in the field “Excerpt” from your article. Safe (upload) and revisit the page an notice the changes. Use this complete code for your theme to include also the “Excerpt” snippet. In our example we’re using a default image for posts where a featured image is not included, if you like download it here.

Further optimizations

We like to have the post link for each thumbnail and the we like to use only 15 words for the Excerpt. Add the following filters to your theme functions file:

We used the following CSS style for the related posts on Tutorial Depot:

Hopefully, you will find this upgrade to the Yet Another Related Posts Plugin useful. We suspect that you’ll have folks asking you how did you do it and we hope that you’ll tell them that you found it right hear on the Web Development Blog.

404 Error Page: Report, Monetize and Analyse

After your websites getting more pages and links, the chance that a visitor will follow a broken link to your site exists. If a visitor is trying to access a page on your site, your 404 error page should provide the visitor a “Not found” error. The response is by default some unfriendly page with spare information about the error which let most visitors stop visiting your website. By using these 404 errors the right way, it’s possible to collect important information like:

  • Of course the broken link or URL
  • The HTTP_REFERER information where the dead link is available
  • How often people try to access the bad URL

Using the right tools you’re able to turn 404 error page into a powerful resource:

  • Provide a site search feature and let people search what they are looking
  • Add advertisements to your error page and start earning money
  • Learn about what people like to see on your site

In this tutorial we will show you how-to:

  • Create a dynamic error page using the Google Site search and Google Adsense content ads
  • Setup Google Analytics to track 404 errors using a filter
  • Set the site search feature with Google Analytics to collect the search queries from your visitor

Error reporting page

With the Apache webserver it’s possible to use custom directives for your error script, place this code into your .htaccess file (place the file into the site root):

ErrorDocument 400 /error.php?err=400
ErrorDocument 401 /error.php?err=401
ErrorDocument 403 /error.php?err=403
ErrorDocument 404 /error.php?err=404
ErrorDocument 500 /error.php?err=500

We use for the custom error script the most common HTTP errors.
Next we need to create a PHP script called error.php which can handle the different errors:

This script will show the different errors and also some advertisement if you add the ad code. Don’t forget to add the GA code snippet.

Track broken links in Google Analytics

In case of a 404 error the page title on this custom 404 error page will be “Not Found”. We use the page title as a filter in Google Analytics to track the page views. Create a new profile for the site you’re working on and add this filter:

404 Error Page

Adding Google Site Search to your 404 error page

If you haven’t done yet, create a Google site search for your website. Add only your own website to the list of searched sites and don’t search the entire web. Add your Google Adsense ID (section “Make Money”) and head to the section “Look and feel” and select the option Iframe. Choose a style for the search form / result and maybe you like to customize the style. Push now the button “Get code” (or enter the section “Get code” from the sidebar) and enter there the URL from your error page.
Copy / paste the code for the search form and the results into the body section from your error page. Your completed 404 error page will look like:

We placed the add code also into some IF clause, because there should not be another Google Adsense advertisement beside the Google ads from the result page.

Enable site search tracking in Google Analytics

The code for the 404 error page is complete and we move to the last step: Tracking the site search queries from the error page. To do this we need to go in Google Analytics to the profile we created for the error page and click Edit (twice), check the setting Do Track Site Search, enter a “q” as the “Query Parameter” and click Safe Changes.

This 404 error page is very basic and you need to integrate your sites web template to make it complete. If you like this tutorial and you have used the code on your own site please share the URL to your new or updated error page. Even if you don’t like to use the code from this page, we advice to track the errors and also the site search queries from your visitors. If you have questions or comments please post them below.

Create PDF documents Online with TCPDF

Many web applications output documents like invoices, contracts or just web pages in the PDF format. There are a few PHP classes which can be used for creating PDF files online, one of them is TCPDF. This tutorial is about how-to use the TCPDF class while creating a simple invoice document. A function that creates invoices online, is very common for a website that sells goods or services. 

Why TCPDF and not some other PHP class?

TCPDF is based on the FPDF class, a very stable project written originally for PHP4. Since several years has TCPDF much more features than FPDF and is written for PHP5. The TCPDF has also some great documentation and of course examples for all important PDF jobs like:
WriteHTML and RTL support, Multiple columns, JavaScript and Forms, Bookmarks (Table of Content), Multicell complex alignment, Barcodes, Set PDF viewer display preferences, EPS/AI vectorial images and many more.

Codecanyon PHP 2 PDF Scripts

The Zend Framework has some PDF class too…

Yes right, the first plan was to write this tutorial about the Zend Framework, but after writing a few rows of code I’ve noticed that the PDF Class is missing some important functions, like the MultiCell, which is used to wrap multiple rows of text. It’s a required function which was suggested as the Zend_Pdf_Cell 2 years ago and didn’t find the way to the core version until now. I like the Zend Framework a lot but not for creating PDF documents, the PDF class is much too limited. :(

Okay let’s start the tutorial:

In this tutorial we create a PDF invoice including header logo, the invoice rows, an information box and some footer row.
In our code we include some PHP files, next we’ve created a small class extension to have a custom header/footer and some handy method which creates a text box.

The header method has only two functions, one sets the image quality and the second will place an image (including hyperlink) on a defined place (x=120, Y=10, width=75). All coordinates are measured in Millimeters and the height for the image is calculated by the script. Inside the footer method we’re using some basic TCPDF methods to define the position, the font/style and the cell with the footer text. The third method (CreateTextBox) is just a group of TCPDF functions which makes it easier to place some text box into the PDF document. Note, the constant variable PDF_FONT_NAME_MAIN is defined inside the TCPDF config file, which is located inside the config directory.

The invoice header

The following code will create a TCPDF object with default values, the PDF meta data gets defined (author, title, etc.), a page is added and the invoice header with information is created using our custom text box method.

Invoice Rows

Now we create the information about the products we like put into the PDF invoice. First we create some headers and than we use a foreach loop to output our $orders array.

After the headers and after the list of invoice items we create a line. Inside the loop, we use the variable $currY to raise the Y coordinate by 5 for each new row. The row amount is calculated by PHP and also the total amount is raised inside the foreach loop.

Invoice footer and information

First we create a total row using the value from the variable $total we created before. After that row we have a MultiCell which can hold the payment conditions or just some other information. You can use HTML code in this cell as well, for example a link to your terms and conditions.

At the end we call the output method which will safe the created PDF under the name test.pdf and sends the document to the browser.

This is just an example to show how easy it is to create PDF files online. Before you start your own PDF scripts, check all the TCPDF examples to get an idea how-to use the different methods.