Browsing Category

PHP

PHP WordPress

How to Customize WordPress Sidebars

If you haven’t noticed! I’ve not only migrated my domain to t.omlinson.com, but I’ve also created a child theme based off of the Redwood WordPress theme. One particular element I needed to add was different WordPress sidebars based on the category page.

Old Way of Customizing Your Sidebars

In the past, I used to buy HTML themes and convert them into WordPress themes. This avoided some of the bloat found within premium themes and required a much smaller investment. During that era, this is how I would ensure different pages could support different sidebars.

I would create a PHP file called “wordpress-sidebar.php.” Inside, I’d insert the customization that I wanted. I’d usually not use widgets because it wasn’t something I was comfortable with at the time. Afterwards, I’d just add an if statement to call on the file I just created wherever I needed to.

The code would look something like this.

<?php 
 
//if you wanted a custom sidebar for your wordpress category archive page
//you could use in_category() if you wanted to target a post within a category
 
if(is_category("wordpress"){ 
 
      //actually not sure if TEMPLATEPATH is necessary, leave a comment if you know!
 
      include(TEMPLATEPATH . '/wordpress-sidebar.php');
 
      // the else would call the default sidebar, you could use elseif to create a chain if you wanted
 
} else {
 
      // this is a command to get the default sidebar in WordPress
      // it is identical to using include 
 
      get_sidebar();
}
?>

Pretty simple, but it’s the old and wrong way to do it.

New & Better Way to Create Different WordPress Sidebars

You begin by entering into your theme or child theme’s “functions.php” file. You’ll want to add code similar to this one:

<?php 
 
// Basic was of registering new WordPress sidebars
 
if ( function_exists ('register_sidebar')) { 
    register_sidebar ('wordpress_sidebar'); 
 
    // More advanced way of adding an alternative sidebar allow you to control some of the style and CSS
    // elements. You could also use a function called register_sidebars()
    //  to create multiple WordPress sidebars but the function is not recommended. 
 
    register_sidebar( array(
        'name' => __( 'Work Sidebar', $theme_slug), //name that appears in your widget area
        'id' => 'work', //id to call your sidebar this is only variable you must specify
        'description' => __( 'Widgets in this area will be shown on all posts and pages.',  $theme_slug ),
        'before_widget' => '<li id="%1$s" class="widget %2$s">',
	'after_widget'  => '</li>',
	'before_title'  => '<h2 class="widgettitle">',
	'after_title'   => '</h2>',
    ) );
 
// Be sure to replace $theme_slug with your theme's slug! 
 
} 
?>

This will allow you to modify your sidebar using the regular widget section. Next step if similar to the previous way of adding WordPress sidebars, create a file based on the id of your newly registered sidebar. In this case, the file would be named “sidebar-work.php”.

You’ll make whatever modifications you need in that new file and make sure that your dynamic_sidebar(); function refers to your new sidebar by name. If you don’t make changes to that function, your widgets will not show up.

Now, whenever you use the get_sidebar(); function, you can call the work sidebar by doing get_sidebar(‘work’);.

If you need additional help, you should definitely do one of these three things:

  1. Read the WordPress Codex page about customizing your sidebar.
  2. Search the WordPress Development Stack Exchange.
  3. Comment below and I’ll do my best to help you out.
PHP WordPress

Modifying the WordPress Template Hierarchy to Handle Parent Categories

This is essentially plagiarism of a great post by Drew Jaynes. It took me a while to discover his post when trying to figure out how to modify the WordPress template hierarchy so I decided to share it again. Hopefully one of these pages will start to rank better.

Here’s his code with a tiny amount of additional comments:

 
//this code should be pasted into your function.php file
 
function new_subcategory_hierarchy() {  
 
    $category = get_queried_object();
 
    $parent_id = $category->category_parent;
 
    $templates = array();
 
    // preserves the classic WordPress template hierarchy for parent categories
    // or else it create a new path for sub-categories
    if ( $parent_id == 0 ) {
        // Use default values from get_category_template()
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
        $templates[] = 'category.php';      
    } else {
        // Create replacement $templates array 
        $parent = get_category( $parent_id );
 
        // Current first
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
 
        // Parent second
        $templates[] = "category-{$parent->slug}.php";
        $templates[] = "category-{$parent->term_id}.php";
        $templates[] = 'category.php';  
    }
    return locate_template( $templates );
}
 
add_filter( 'category_template', 'new_subcategory_hierarchy' );

Personally, I find the WordPress Template Hierarchy pretty good. Other than it’s issue with dealing with sub-categories, I’ve never really had a problem with its flow. In fact, I could have easily just copy pasted a template file for each sub-category based on its parent.

PHP SEO

Two scalable branded link reclamation tactics

This post is a work in progress. It requires more images and maybe a video tutorial!

There are a lot of tutorials and bloggers that state branded link reclamation is really easy. According to these SEOs, all you need to do is follow these 4 simple steps:

  1. Navigate to Google
  2. Search for your brand
  3. Find a non-linking brand mention
  4. Send an email

The four step process is a lie. Combing through your brand mentions like this takes time and isn’t scalable if your working for Toyota or any other large brand.

These types of businesses get mentioned multiple times everyday and often own a large number of other brands. By taking a look at all these mentions manually, not only will you encounter a high number of linking mentions, but a high number of unusable ones will also show in search results.

This means countless hours are wasted just to turn one mention into a link. You’ll be wasting your time for a very low return. In this post, I’ll show two branded link reclamation tactics that I have used with great success. I’ll also explain how to check for non-linking mentions as well as an easy way to find contact information in order to tell them what’s up.

Reclaiming Branded Links with Scrapebox

If you aren’t using Scrapebox because you’ve heard it’s a blackhat too, you need to wisen up. While some people like to use it for comment spam, it’s actually a great tool for uncovering guest posting opportunities, eliminating dead links from your Ahref or Majestic backlink exports, verifying DA of a huge number of domains and a lot of other everyday SEO tasks. I’m going to assume readers of this blog know their Scrapebox basics or have at least read Jacob King’s Ultimate Guide.

Setting Up Your Scrape

Personally, I don’t think you need to do much here. If you have a list of the branded terms you’re looking for it should be enough. The reason why I don’t suggest using the Scarpebox Keyword Scraper is that you might end up having to waste some time cleaning it up.

Due the fact that I work mainly with Canadian brands, I will merge a list of footprints tied to site: queries with country, province and city name mentions within my keyword list. Lastly, I’ll ensure to have -site:brand.com in my global footprint.

After that’s done, you really just need to stat harvesting. It’s really that easy to get more than a thousand URLs that have potentially mentioned your brand.

Cleaning Your Results

One of the main issues with a Scrapebox harvest is that it tends to be very dirty. If you were looking for brand mentions of a Jeep Grand Cherokee, you’ll definitely get some sites that are actually about Native Americans instead. An easy way to eliminate those sites is by cleaning your harvest into Excel.

Using Seo Tools for Excel, it’s extremely easy to check if pages mention any potential keywords that would signify a scrape error. In our example, I’d most likely run a similar but more complex regex to this =IFERROR(RegexpFindOnUrl("http://www.brandmention.com","Native"), TRUE). I’d keep all TRUE URLs and manually check the others if I have the time or motivation.

Monitoring Brand Mentions for Link Reclamation

Now if you aren’t comfortable getting your hands a bit dirty with some PHP code, you won’t be able to actually use this second link reclamation tactic. It’s a more scalable version of Moz’s Fresh Web Explorer and services like Mention.net.

Creating a Huge Number Number of Google Alerts

You’ll be wanting to set up a lot of Google Alerts. I’m talking 20 to 50 alert different types of alerts. The easiest way to do this without getting suicidal thoughts is to automate it. A easy and efficient solution is to just create a ReMouse macro using your browser and excel columns with each alert.

Setting Up SimplePie

SimplePie is a great tool for filtering out useless mentions. I’m working on getting it to do the actual link verification for me. Until then, here’s my two introductory posts on Simple Pie:

How to merge your Google Alerts RSS feeds and filtering out items

Removing duplicate items and an another method to filter out items

Once you’ve set this up. all you will need to do is hit your page up once every few days to find new brand mentions.

Finding Non-Linking Brand Mentions

After getting our leads using either Scrapebox or our custom monitoring system built with SimplePie, we need to start turning those non-linking brand mentions into links.

This is fairly easy. Just install the Link Checker add-on. You’ll need to create two text file. One will contain the list of sites you scraped using one of the two methods bellow. The other must contain the list of domains you are interested in checking.

I suggest running the link checker multiple times while cleaning out positive hits. Depending on the number of URLs on the same domain and other factors, I tend to get a few false negatives on my first link checker runs.

Scraping Emails for Mass Mailing

While I know there are some other tools that will scrape email address from sites. I haven’t had the budget to invest in any of them yet. My current technique is to just use Scrapebox. I take the list of non-linking URLs and trim to root. I move this list to excel and create a list where I concatenate “/about” and another where I concatenate “/contact”. These three lists paired with Scrapebox Email Grabber tends to give me great results.

If you can suggest a great email scraper in the comments, I’d be enormously grateful.

Remember to have “Email Grabber: Save url with emails” enable in options.

Preventing Spam Accusations

Now you got your emails, you just need to start sending out some messages. The best way to prevent spam accusations is not to mass mail the list of emails you just got and be polite…

PHP

How to remove duplicate URLs and irrelevant pages from RSS feeds with SimplePie

At the end of my last post about using SimplePie, I mentioned that I did not think I would have any issues with removing duplicate URLs. I actually did have some issues with the appearance of duplicate URLs and irrelevant pages in my results. By irrelevant articles, I mean articles where reclaiming a brand mention would not make any sense. In any case, I’ll be showcasing the modifications I have done to my last snippets of code in this post. For those who wish to see both posts combined, there will be an excellent tutorial on branded link reclamation coming up in the next month.

Using Regex To Filter Out Non Relevant Titles

Most of the irrelevant pages were created by pages trying to sell products related to the brand. While I could of still used an array to look for specific substrings in the titles, I decided to use a regex variable. Regex is not only more flexible, but also requires less code to actually filter out results. Instead of looping through each string in the array and compare it to the item in the RSS feed, only one check is needed.

<?php $titlePattern = "/(U|u)sed|(f|F)or.(S|s)ale/"; ?>

As you can see, the filter looks quite different than the one created previously for domain names. If you look bellow, you’ll see that instead of doing a check on each item using stristr, you’ll need to use pre_match and it’ll check for all the combinations in the regex variable.

<?php $filtration = 0; ?>
<!-- title check -->
<?php   if(preg_match($titlePattern, $item->get_title()) != false){
                $filtration = 1; 
		} else {
                        //if title check passes, check domain
			foreach($filter as $token){
				if(stristr($item->get_permalink(), $token) !== false){
				$filtration = 1;
				break;
}}}
?>

How to Remove Duplicate URLs & Preserve Relevant Information

You’ll notice that there’s a new variable included in this filter called $filtration. This works as a flag that tells the filter that the URL did not pass the various domain and title filters. The next step is to remove all duplicate domains while preserving only the information we want to display. Unlike the answer in this Stack Overflow question, the filtration creates items that include both the title and the permalink instead of just the title.

<?php                                      
//remove duplicates that pass filter 	
if($filtration != 1){ 
    $filteredFeed[$item->get_title()] = array('title' => $item->get_title(), 'permalink' => $item->get_permalink());
} 
endforeach; ?>

If you were wondering how this removes duplicate URLs, it’s because the items are created using the title of the RSS feed item. Whenever there’s a duplicate title, it gets removed from the list!

eCommerce PHP

How to translate a Magento theme in six easy steps

I’ve been pretty busy at work these last few weeks, but that doesn’t mean I have given up working on any of my learning projects. I’ve begun to translate a Magento theme. I was afraid at first, but translating a Magento theme is actually quite an easy process. It’s actually simpler than trying to make a WordPress theme multilingual using WPML.

Get Translation Files For Default Magento Interface

The first step is to go ahead and download the official Magento translation packages. Be sure to download the actual package and not the inline or string list. I won’t be using those translation methods in my guide.

Once that is done, decompress the file and upload the /app folder of your Magento store’s root directory. It’s easy-peasy.

magento translation root folder

Create Store Views For Every Language

how to translate magento theme configsNow that the Magento translation files have been uploaded on your serve, it’s time to create the various store views associated with each language.

First, navigate to System/Manage Stores which can be found easily by using the Magento backend’s header menu. From here, you’ll be able to create new store views as well as edit the names of the existing ones. I suggest you change the default store view’s name to English to keep your naming convention convenient.

Once, you’ve created the store the views. You will have to navigate to System/Configuration and ensure that you set the current configuration scope to your new language. Select the appropriate language from the locale dropdown on the General/General configuration page.

french-locale-magento-translation

Why Your Theme Isn’t Fully Translated

After creating the store views and associating them with the appropriate locale file, you might notice that some text portions of your Magento theme have already been translated in the front end. This is because those particular strings use the same wording that is used in the default Magento theme. Yet, most good Magento theme developers will have modified the default text and added strings of their own. In addition, you’ll most likely have created a number of static blocks and pages that will need translating as well.

Don’t worry! You’re halfway through translating your Magento theme.

Depending on how many pages and static blocks you have, that might have been a lie. This is where actual Magento translation grunt work actually begins.

Translate All Static Blocks

Navigate to CMS/Static Blocks. Go through every single block that currently exists, and set their store view to your default language. In our case, it’s English.

translating english static block

Next, you’ll want to start creating blocks that will replace them in your translated Magento theme. You’re best bet is to come up with a naming convention that will make it easier when it comes to translating your pages. In my case, I tend to append a language code such as _en or _fr to all my static blocks.

translating french static block

Once that’s done, verify that you have not forgotten to translate the actual content of any of your newly created static blocks for your new store views. If you don’t translate them, you won’t end up with a fully multilingual Magento theme.

Translate All Pages

Repeat the same process that you have just done with the pages found in CMS/Page. The only difference is that you’ll have to keep an eye open for calls to your static blocks.

Whenever you see something similar to {{block type="cms/block" block_id="static_block_1" template="cms/content.phtml"}}, you’ll have to be sure to append the appropriate language code to the store view you have selected for the page.

Verify Store View Theme Configurations

how to translate magento theme configs

If you’re lucky, you’ll be able to skip this last step. Some Magento themes reference static blocks in the System/Config and you’ll need to ensure that each store view references the right CMS static block.

You’ll want to go through each part of the config and look for mentions of static blocks. Remember to select a store view as the current configuration scope.

In addition, you may also encounter a few options that require either custom HTML or text. You’ll have to change those as well to ensure that the last step runs smoothly.

You’ve almost successfully translated your Magento theme!

The last step may be the most tedious one, but over 80% of the translation job is now done.

Complete a Magento Translate.csv For Your Theme

Now that all the text that can be customized in the backend of your Magento theme has been translated, it’s time to fix all other text. Open up Excel, or whatever spreadsheet editor you prefer, and start jotting down all the text lines lines that still do not appear translated in your theme in the first column. In the next column, write the translation as it should appear on the new store view.

Save it as CSV and name it translate. Upload translate.csv to the appropriate language folder in your Magento theme’s locale folder. In some cases, you will have to create a folder. This is often found in a similar path to ../app/design/frontend/default/theme_name/locale/language_name.

Dealing With Variables

Remember that not all information displayed in your theme is 100% static. In some cases, the code used to display the text includes a variable. Usually, you can use %s to take the place of that variable in your translate.csv. If that doesn’t work, check the actually php code that is displaying the text and use the exact same variable that you see there.

Congrats! You are finished translating your Magento theme. If you know of easier ways or spotted a mistake feel free to call me names.

I also don’t mind hearing you complain about CSV and quotation mark problems too.

PHP

How to filter multiple RSS feeds with SimplePie

As for installing SimplePie, it was a relatively painless operation. I was able to install the RSS library using Softaculous. This install comes with a working demo which I decided to modify to fit my needs, instead of starting from scratch, as it seemed like multiple people were having issues installing SimplePie 1.3.

As stated in my post about my problems starting a link reclamation campaign, I decided to learn how to use SimplePie in order to have an extremely malleable presentation as well as an easy way to filter out useless mentions in the multiple RSS feeds. For example, there is no way I don’t want to be notified about a craigslist ad mentioning my client.

In fact, I was easily able to build a code filters to deal with dirty data. In addition, it will be quite easy to add to these filters as I acquire links on more and more domains.

Limiting Number of Items from Each RSS Feed

This is quite easy to implement. All it takes is a line of code after declaring your feeds.


// Combine your chosen RSS feeds into one feed
$feed->set_feed_url(array( /*insert your feeds here*/ );

//Use this to limit the number of RSS items coming from each feed
$feed->set_item_limit(/*put your number here*/);

You can read about more about implementing the snippet here.

Filtering Out Domains, Keywords & Dates

This is where things start to get tricky. I wanted a filter that would look at each item in the feed and decide whether or not it should be included in my list of URLs on the page. I began by declaring an array which included all potential URLs that I knew where useless for link reclamation.


//Set up filter
$filter = array("youtube", "craiglist", "kijiji", "forum", "flickr", "dailymotion", "facebook");

The next step was to make sure that every item would pass through this filter and get flagged for removal if they included one of those words in the URL.

<?php  

//Let's begin looping through each individual news item in the feed.
	foreach($feed->get_items() as $item): 

//My filter variable
                $filtration = 0;

/* When the site fails to not have a substring from our filter array, it changes our filtration variable and exits the verification loop */
                foreach($filter as $token){
			if(stristr($item->get_permalink(), $token) !== false){
			$filtration = 1;
			break;
		        }
                }
?>

You could also filter out items using their titles, dates and descriptions as well using the same type of verification loop by changing $item->get_permalink() to the respective value you are looking to check.

<?php			
//If the item passed the filtering system, it will get displayed on the page 
		if($filtration != 1){ ?>
	
			<div class="chunk">

<!-- If the item has a permalink back to the original post (which 99% of them do), link the item's title to it. -->
			
<h4><?php if ($item->get_permalink()) echo '<a href="' . $item->get_permalink() . '">'; echo $item->get_title(); if ($item->get_permalink()) echo '</a>'; ?></h4>

			</div>

<!-- Stop looping through each item once we've gone through all of them. -->
	
	<?php } ?>
	<?php endforeach; ?>

Removing Duplicate URLs From Multiple Feeds

While I haven’t had to clean up duplicate listings, it’s also simple to modify this loop to remove duplicate titles from the list. You can learn more about doing this in the answer to this Stack Overflow question.

PHP SEO WordPress

Modifying the length of Yoast Breadcrumbs

If you don’t know Yoast’s WordPress SEO Plugin, you’re not a real SEO. Sure, he puts a link in your Sitemap, but it’s a small price to pay for an amazing WordPress plugin.

As a reward for finishing up two posts, I decided to spend some time making some initial design changes to Bones. Most of it was pretty simple. Yet, I did have to pause to fix a minute detail that bugged me about the SEO plugin’s auto-generated breadcrumbs: if the title of a blog post exceeded a certain number of characters, the Yoast Breadcrumbs would take two lines. I decided to take a look at how I could shorten the titles in the breadcrumbs if they went over a certain number of characters.

Getting it to fix on line wasn’t as easy as it looked.

How to Modify the Length of Yoast Breadcumbs in WordPress

The first step is as simple as getting the string that is generated by the plugin as follows.

<?php if ( function_exists('yoast_breadcrumb') ) {
	$yoast = yoast_breadcrumb("","",false);

Then, you just need to create an if statement that takes into consideration the length of the current breadcrumb string. You’ll notice that the length is remarkably long for something that is usually relatively little text. That’s because the breadcrumb string also includes some HTML markup and you’ll have to truncate it all.

You might have to test different lengths depending on the width of your content div.

	if(strlen($yoast) < 585) { ?>
		<p id="breadcrumbs">
			<?php echo $yoast; ?> 
		</p>
	<? } else { ?>
		<p id="breadcrumbs">
			<?php echo substr($yoast, 0, 585)."..."; ?>

As you might of guessed, the last piece of the puzzle is to close the tags that have been cut off by only using a sub-string of $yoast. If you did not select to bold the current page in the breadcrumb options, you can omit </strong>.

			</strong>
			</span>
		</p>
<?php } } ?>