Code Snippets

Bits and pieces of code I've written or found online and were super useful. Feel free to use anything you find here as you wish.


Check if a remote file exists

If you are using S3 or some other similar service, where your images and assets are not within your local file system you might want to check if a file exists remotely and if not, take action, like displaying a fallback image.

    /**
     * Check if a remove file exists
     *
     * @param  string $url
     * @return Bool
     */
    function remoteFileExists($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);

        // don't download content
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if(curl_exec($ch)!==FALSE) {
            return true;
        }  else {
            return false;
        }
    }


Javascipt URL Path Info

If you had a URL in PHP, you could use pathinfo() to get all the different sections without much hassle. Javascript however, has no baked in alternative.


    /**
     * create a link and return it so we can access different aspects of the url in an object context
     *
     * object.protocol; // => "http:"
     * object.host;     // => "example.com:3000"
     * object.hostname; // => "example.com"
     * object.port;     // => "3000"
     * object.pathname; // => "/pathname/"
     * object.hash;     // => "#hash"
     * object.search;   // => "?search=test"
     *
     * @param  {String} href The url
     * @return {Object}
     */
    var pathInfo = function(href) {
        var l = document.createElement("a");
        l.href = href;
        return l;
    };


Which Wordpress template are you looking at?

When working with WordPress’s default template hierarchy, it can be a little hard to know which file you should be editing.

Add this to your header.php and it will be printed for you:


<?php global $template; var_dump($template); ?>


Remove query string from URL and 301 redirect

Changing URL’s to remove your Query strings can hinder your SEO score. I recently tried to pass a page title from one set of dynamically created links to the list page via a “title” param within the query string. The why’s and wherefores are irrelevant right now, but the title of the page couldn’t be created from the data being passed within the URL as it included town names and locations, which cannot simply be unslugified for displaying. The problem was that Google indexed all the pages with the title param and when we thought of a better solution and removed the query string, the page rank fell through the floor as we had removed thousands of pages. To create mitigate this problem, we created a 301 redirect from one page with the query string to the same page without it appended.

#turn on the rewrite engine
RewriteEngine On

#look for any URL with title= in the query string so http://www.domain.com/?title=1
#this could be any query string param such as id, slug etc
RewriteCond %{QUERY_STRING} title=

#redirect to its self without the query string appended to the end
#telling apache to set the status as 301 and stop looking for other matching rewrites (exit now)
RewriteRule (.*) http://%{HTTP_HOST}/$1? [R=301,L]


Maximum function nesting level of '100' reached, aborting!

To increase the number of nested arrays that xdebug will allow, enter the commands below to increase the limit from its default of 100, to 250 and prevent PHP from aborting some operations.


# login to the super user

su

#update the xdebug ini file with the new setting

echo 'xdebug.max_nesting_level = 250' >> /etc/php5/conf.d/xdebug.ini


Check Wordpress menu has items before displaying it

WordPress menu’s seem a little bit like they were added in a hurry. They originally came from a plugin that was then rolled into the core and use a method of items within the Posts table with a custom post type of ‘nav_menu_item’. The problem is that there are a bunch of functions related to their use and as far as I can see, none of them do one important thing… check that a menu isn’t empty before trying to display it – at which point the function spews out seemingly random links.

To get round this you can add this function to your functions.php and wrap it around any menu function calls.


/**
* check the navigtion has entries
*
* @param Mixed String|Int name/id/slug of the menu
* @return String
*/
*/
function check_nav($menu) {
	global $wpdb;

	$sql = "SELECT count(tr.object_id) AS count 
		FROM ss_terms t
		LEFT JOIN ss_term_taxonomy tt ON t.term_id = tt.term_id
		LEFT JOIN ss_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
		WHERE (t.term_id = '{$menu}' OR t.name = '{$menu}' OR t.slug = '{$menu}')
		AND tt.taxonomy = 'nav_menu'";		

	$count = $wpdb->get_var($sql); 
	if ($count > 0) {
		return true;
	}

	return false;
}


Just list all the Wordpress Menu's

After about an hour of looking at an array of different and equally convoluted functions for obtaining the names of WordPress menu’s I decided that this was actually Bull Sh*t and so wrote one. I don’t understand why WordPress cant just have a function to list all the menu’s… or maybe I missed it in the confusion caused by ‘wp_nav_menu()’, ‘wp_get_nav_menu_items()’, ‘wp_page_menu()’, ‘get_nav_menu_locations()’, ‘wp_get_nav_menu_object()’, ‘get_registered_nav_menus(), ‘get_terms(“nav_menu”)’, ‘wp_get_nav_menus()’… I just wanted a list of Menu’s…

$sql = "SELECT t.name
        FROM $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON (t.term_id = tt.term_id)
        WHERE tt.taxonomy = 'nav_menu'
        ORDER BY t.name";

$list = $wpdb->get_results($sql);

var_dump($list);


Silex and Twig debug mode

Getting debug functionality to output used to be pretty hard to do, or if not hard, then just convoluted. Whilst trying to get this working I found a few Stack Overflow entries that mentioned registering Twig extensions and setting Twig options when the object is initialised, but those are all out of date.

This is how you get Twig debug mode within a Silex application:

//add these files to your composer.json file and run 'composer update'
"twig/twig": ">=1.8,<2.0-dev",
 "symfony/twig-bridge": "~2.3",
 "twig/extensions": "*"

Now you can add in the single setting that will allow debug functionality within your Twig templates:

//after you instantiate the Silex Application object add this line</span>
$app['debug'] = true;


Vagrant Root user

Most of the time you can happily work within your Vagrant box using ‘sudo’ to perform restricted actions, however from time to time you might want to actually become the root user, for instance when you want to set a system timezone like so:

echo "Europe/London" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata

Linux will not let you do this without being root and ‘sudo’ doesn’t get you any further either. So you can try and log into the root user as you normally would with the ‘su’ command, at which point, the box will require a password, which you don’t have. To access the root user, instead enter the following:

sudo su