Redirecting domains to a WordPress Multisite

Redirecting domains to a WordPress Multisite

Redirecting domains to a WordPress Multisite is slightly more complicated that I would have expected. WordPress checks what referrer you’re coming from when using WPMU (which totally makes sense, so it can know what multisite blog you’re wanting), but when it finds a URL that it doesn’t recognize, things go down the tube, quick..

WordPress is fantastic, but there are some things hidden under rocks that you rarely know about until you need it. Today I needed to point an clients’ old domain to their new website! The problem was, WordPress was using it’s logic of “That domain doesn’t exist here, they must want to register it as a new blog!”, which is totally wrong. (Good thinking though, WordPress!)

We have new blog registration disabled. When I was looking at this setting, I noticed a small note below.

If registration is disabled, please set NOBLOGREDIRECT in wp-config.php to a URL you will redirect visitors to if they visit a non-existent site.

Good to know! This means we can actually stop that pesky “Registration is disabled” page from coming up without using any plugins! Just go into your wp-config.php file and direct any non-recognized URLs to any URL (in most cases, the new site’s URL).

1
define( 'NOBLOGREDIRECT', 'http://ericholmes.ca/' );

Now we can start redirecting domains to a WordPress Multisite with no more interference!

WP on!

Custom Post Type date archive links in WordPress

Custom Post Type date archive links are not supported out-of-box within WordPress (as of 3.6 beta). Nor are CPT date archives, but that’s another post (coming soon). The built-in date archive link functions (get_year_link, get_month_link, get_day_link) only work for Post archives.

Here is a function that will create your date archive links for you. I had a fallback of giving you get_post_type_archive{}, but took it out. If there is ever the case of not having the year, you should just use get_post_type_archive{} directly.

This function also automatically handles any rewrites you have for custom post types. I often use prefixes at work as best practice, and nobody wants eh-events in their URL string!

Let me know if you find a more efficient way of doing this. I’d love to direct to your source, or at least update mine! :)

The Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * This allows us to generate any archive link - plain, yearly, monthly, daily
 * 
 * @param string $post_type
 * @param int $year
 * @param int $month (optional)
 * @param int $day (optional)
 * @return string
 */
function EH_get_post_type_date_link( $post_type, $year, $month = 0, $day = 0 ) {
    global $wp_rewrite;
    $post_type_obj = get_post_type_object( $post_type );
    $post_type_slug = $post_type_obj->rewrite['slug'] ? $post_type_obj->rewrite['slug'] : $post_type_obj->name;
    if( $day ) { // day archive link
        // set to today's values if not provided
        if ( !$year )
            $year = gmdate('Y', current_time('timestamp'));
        if ( !$month )
            $month = gmdate('m', current_time('timestamp'));
        $link = $wp_rewrite->get_day_permastruct();
    } else if ( $month ) { // month archive link
        if ( !$year )
            $year = gmdate('Y', current_time('timestamp'));
        $link = $wp_rewrite->get_month_permastruct();
    } else { // year archive link
        $link = $wp_rewrite->get_year_permastruct();
    }
    if ( !empty($link) ) {
        $link = str_replace('%year%', $year, $link);
        $link = str_replace('%monthnum%', zeroise(intval($month), 2), $link );
        $link = str_replace('%day%', zeroise(intval($day), 2), $link );
        return home_url( "$post_type_slug$link" );
    }
    return home_url( "$post_type_slug" );
}

Subdomain Multisites for WordPress – and sub-subdomain multisites

Subdomain multisites are a great way to break up a WordPress multisite. I personally think it looks much cleaner, and separate.

books.ericholmes.ca vs ericholmes.ca/books

The former(subdomain multisite) looks like a section or portion of the ericholmes.ca domain, while the latter(subfolder multisite) looks as though you are just sitting within a folder – not as professional!

The setup is actually quite simple to accomplish this. All you need to do is log into your hosting cPanel (or hosting provider equivalent) and locate where you can manage your subdomains. I use JustHost and have never regretted choosing them! Anyways, they use cPanel, so the image below is a screenshot from within cPanel.

Wildcard subdomains for subdomain multisites

It’s a pretty painless process. Once you locate your Subdomains, add the * subdomain. Then set the Home folder to the proper location (most likely /public_html/).

Wildcard Subdomain

Sub-Subdomains

This wildcard process also works for sub-subdomains as well! It’s a pretty edge-case scenario, but I ran into it (today in fact) when setting up a WP multi-site on a development server (where we use subdomains for each project).

From what I can tell (referenced in this post) wildcard subdomains on a domain level (domain.com) will also support sub-subdomain wildcards (blog.books.ericholmes.ca). Thanks to Andrea Rennick for providing this answer!

Encoding jump anchors for Facebook shares – via sharer.php

Encoding jump anchors for Facebook shares proved to be an annoying, but simple task! Try it out for yourself.

https://www.facebook.com/sharer/sharer.php?u=http://example.com#jumplink 

Post to “Only Me” publicity if you wish (quite handy for developing). You will see when you take a look at facebook, he actually keeps the #jumplink anchor when you get redirected back to your facebook.com. It’s pretty silly.

The solution is a simple one – Facebook (or possibly how they are retrieving their $_GET parameters) is removing (or ignoring) our jump link. To fix this, we need to encode the special character to it’s ASCII equivalent – %23.

1
2
3
4
$url = 'http://example.com#jumplink';
$sharer_url = 'https://www.facebook.com/sharer/sharer.php?u=' . str_replace( '#', '%23', $url );

// http://example.com%23jumplink

The Result

Opening in a new window

Encoding jump anchors to Facebook shares when using JavaScript to create a new popup window is a very similar approach. You just use JavaScript’s replace method.

1
2
3
4
var url = 'http://example.com#jumplink';
var sharer_url = 'https://www.facebook.com/sharer/sharer.php?u=' + url.replace( '#', '%23');

// http://example.com%23jumplink

Best practice for setting/checking PHP Cookies

PHP cookies are great tools, when used properly (and implemented properly). In a recent WordPress project, I created a semi-basic Poll form. Because WP uses actions, I was able to detect that my form ran, and updated my Poll Results in the database. In the SAME page load, however, you cannot check your $_COOKIE node for your cookie. PHP Globals are not altered (besides $_SESSION) except for when the page first loads. This means  your $_COOKIE value will not be set until you refresh, or go to another page. So I explored the Googlesphere for a fair chunk of time, and discovered the best practice for setting/checking PHP cookies within the same page load (no redirect).

The practice to check for your value is quite simple – when you set your cookie, set it to a global variable as well. That way you do not have to force a refresh/redirect to get your $_COOKIE value.

Setting the Cookie:

1
2
setcookie( 'my_cookie_name', $my_cookie_value, time() + 60*60*24*30, '/' );
$my_cookie = $my_cookie_value;

or

1
2
$my_cookie = $my_cookie_value;
setcookie( 'my_cookie_name', $my_cookie, time() + 60*60*24*30, '/' );

or (if you are just storing true/false)

1
$my_cookie = setcookie( 'my_cookie_name', true, time() + 60*60*24*30, '/' );

Checking for your cookie later in the page

1
2
3
if( isset( $my_cookie ) || isset( $_COOKIE['my_cookie_name'] ) ) {
// do stuff
}

There you have it, the best practice for setting/checking PHP Cookies. If anyone has other methods/practices, please comment!

Date Comparisons in PHP – using strtotime()

Date Comparisons in PHP are tricky. The best way to compare dates is by using strtotime(). My reasoning is simple – keep everything on the same level. Especially when dealing with user input, you don’t know a couple things.

  1. The formatting – dash(-) separators vs. colon(:) vs. backslash(/)
  2. The specificity – days, hours, minutes, seconds?

Now you can format these with regex, or PHP splits and joins,  to make sure that they meet PHP standards, and then use strtotime – comparing strings will not work in many cases.

1
2
3
if( strtotime( $date1) > strtotime( $date2 ) ) {
echo '$date1 is later than $date2';
}

Using WordPress core externally

Using WordPress Core externally can be quite useful when wanting to utilize WordPress functions from within another project/app. I’m setting up a cron job at server level, but I wanted to be able to leverage WordPress functionality. Because of how WP Cron works (initiated on page load, not time), I wanted to separate my cron process from the WordPress installation.

After a little digging around, I found this thread on StackExchange. It explains the setting up how to access WordPress core externally.

The following code will allow you to use all WordPress Core functionality!

1
2
<?php // All that is required to bootstrap into WordPress.
require('../wordpress/wp-load.php');

Test it

1
2
3
4
if( function_exists( 'update_option' ) )
echo 'We have WordPress support';
else
echo 'no WordPress support';

Use WordPress core externally!

Now that you have access to WordPress core functionality, the limit is the sky! (or at least the latest version of WordPress).

Fit Britt – Fitness and Nutritional information and inspiration

FitBritt.ca is a site created for anyone wanting tips on nutrition and fitness, whether it’s healthy recipes, great workouts, tips or motivation.

Brittany posts her workout routines weekly, explains hurdles she comes across in her path to fitness, and shares any tips on healthy eating that she comes upon along the way.

fitbritt

Vertical-alignment for TextFields – ActionScript 3.0

Vertical-alignment for textfields in ActionScript 3.0 is useful for aligning textfields to images, other UI elements in a flash app, and more! As many of you may know, Adobe introduced TLF Text along with Flash Player 10. If you are working with general consumer projects, however, chances are you are targeting Flash Player 9 as a minimum.
Before TLF TextFields, there was no direct way to vertically align TextFields.

That being said, you can easily accomplish this by using the TextLineMetrics object, or more directly, TextField‘s getLineMetrics().

TextLineMetrics allows us to access basic values for any typeface, such as ascent, descent, leading, width and height. Using ascent, we can determine a TextField’s baseline Y position.

see more

Conditional includes in ActionScript 3.0

This morning I have looked for a way to include another .as file depending on a variable. ActionScript 3′s include does not allow you to use variables, as it only accepts string literals.

The reasoning for this is that include is fired on compile time, so any variables are not set, determined, or even defined yet.

The Solution

Reading an article, I came across the solution — Config Constants. These are defined in your ActionScript 3.0 settings (File > ActionScript Settings > Config Constants ). Here you can define compile-time constants, and have functionality depend on them.
see more