Categories
PHP programming

WordPress plugin: insert link to latest post (in category) on your menu

Instructions:

  1. Copy/paste this into your functions.php (TODO: convert it to a standalone php file, and make it into a plygin you can activte/deactivate)
  2. Create a new menu item of type “custom URL”
  3. Make your URL “http://#latestpost:category_name”
    • where “category_name” is the name of the category whose latest post you want to link to
  4. Make the name whatver you want to appear on the menu
  5. Profit!

Based on an idea (with some upgrading + bugfixes for latest WordPress in 2016) from http://www.viper007bond.com/2011/09/20/code-snippet-add-a-link-to-latest-post-to-wordpress-nav-menu/

[php]
/** Adam: add support for putting ‘latest post in category X’ to menu: */
// Front end only, don’t hack on the settings page
if ( ! is_admin() ) {
// Hook in early to modify the menu
// This is before the CSS "selected" classes are calculated
add_filter( ‘wp_get_nav_menu_items’, ‘replace_placeholder_nav_menu_item_with_latest_post’, 10, 3 );
}

// Replaces a custom URL placeholder with the URL to the latest post
function replace_placeholder_nav_menu_item_with_latest_post( $items, $menu, $args ) {

$key = ‘http://#latestpost:’;

// Loop through the menu items looking for placeholder(s)
foreach ( $items as $item ) {

// Is this the placeholder we’re looking for?
if ( 0 === strpos( $item->url, $key ) )
{

$catname = substr( $item->url, strlen($key) );
// Get the latest post
$latestpost = get_posts( array(
‘posts_per_page’ => 1,
‘category_name’ => $catname
) );

if ( empty( $latestpost ) )
continue;

// Replace the placeholder with the real URL
$item->url = get_permalink( $latestpost[0]->ID );
}
}

// Return the modified (or maybe unmodified) menu items array
return $items;
}
[/php]

Categories
PHP usability web 2.0

How to get an awesome tag-cloud for WordPress

There’s only a few tag-cloud plugins that still work – most of them have stopped being supported.

The best one I found has super-awesome-multi-colour mode. But by default it’s disabled, and the config-options don’t include a way to turn it on. You have to dig in the developer documentation to find out how.

Categories
PHP programming startup advice usability web 2.0

WordPress: inline “signup email” drop into post or sidebar

My blog posts are info-rich and spam-poor. Most of the “enter your email address” plugins are designed for spam – covered in bling, in-your-face animations, background music, all sorts of crap.

There’s nothing out there, so I made one, using a GPL’d existing project. Feel free to use this yourself.

note: this is an image, not a form!
Screen Shot 2013-06-13 at 13.48.14

Categories
fixing your desktop PHP programming

Fixing Suffusion: List posts from a single WordPress category

UPDATE: So … it seems Suffusion has (buried deep inside the config) a way of displaying category pages with a higher-level workaround to the WP “missing feature”. Although so far I can’t find a way to set the settings on individual pages (which is what you generally need). So, I’ll leave this post up – it’s a good starting point for customizing Suffusion’s page-of-pages (which is also, it seems, how you would customize its Category pages.

Just to be clear, this is not a bug in Suffision, although it’s an oversight and I hope it’ll be included in a future version. The core problem is in WordPress: people have been requesting/expecting this feature for the past 5+ years, it’s pretty basic, but for now the WP folks haven’t added it.

Problem: List all the posts in a single category

This is VERY frequently requested by WP users: you want to have a Page on your site which lists the posts that are in a single Category.

WP has a very low-level way of doing this – which is very error-prone, hard to maintain (it’s hard-coded to database ID’s!), and requires you to break every single theme you own. Every time the theme is updated, you have to manually re-implement the fix!

Fortunately, there’s a minimal workaround (which is documented in the WP docs now (scroll to bottom)) which still (!) requires some theme editing.

Fortunately, Suffusion already has most of this workaround implemented, so we can make the fix without screwing around with the theme so much. The source code in Suffusion is almost identical to the sample provided by WP – but unfortunately it’s missing a key part. In Suffusion, you CAN list posts on a Page, but you CANNOT filter those posts by category.

Solution: Combine WP’s source with Suffusion, with a bit of safety improvement

So, edit the file “posts.php”, titled (in Suffusion): “Page of Posts”.

Where it has these lines:

$args = array(
	'orderby' => 'date',
	'order' => 'DESC',
	'paged' => $paged,
);

…instead copy/paste the following:

$category_exclusive = get_post_meta($posts[0]->ID, 'category', true );

if( $category_exclusive )
{
$cat = get_cat_ID($category_exclusive);
$args = array(
	'category__in' => array( $cat ),
	'orderby' => 'date',
	'order' => 'DESC',
	'paged' => $paged,
);
}
else
{
$args = array(
	'orderby' => 'date',
	'order' => 'DESC',
	'paged' => $paged,
);
}

Usage

As per WP’s official suggestion … if you want a page to filter by category:

  1. Edit the page
  2. Select the “Page of Posts” template (this is Suffusion specific; in other themes, it might not exist)
  3. Add a “custom field” (scroll down on the edit screen), called “category”, with a value of the NAME of the category you want to be included

Explanation

One major thing here: We are being SAFE and non-destructive to the Suffusion theme.

Critically important is that we ONLY do a “filter by category” if the Page itself requests it. WP’s sample code does NOT have this protection (which is why the code above is slightly different).

This means that the rest of Suffusion (which doesn’t know about our new feature) is unaffected, and works as normal

Categories
PHP programming

Now I remember why PHP is so easy to hate…

(aka “why do my include/require/include_once/require_once files not work / seem NOT to be included, even though they are?”)

PHP has a mechanism for including files inside each other. The architects of PHP didn’t really think much about what they were doing with a lot of the core language features (witness the foolishness over Register Globals), and file import/include/require is a classic example.

This is one of the most fundamental features of the language, and it’s screwed up. It “seems” to work, so long as you write simplistic enough / small enough apps. The bigger your app, the more likely it is you’ll discover how poor this part of the language is.

Categories
PHP programming security

PHP: Anti-spam CAPTCHA using photos

I’m just finishing up a quick PHP project at the moment, which allows anyone to register an account – so as the final step before launching it, I needed to add some form of CAPTCHA system. I tried a couple of 3rd party ones and source code ones and none quite worked for me. This post gives full source for a simple user-friendly photo-based CAPTCHA in PHP. Use at your own risk – but it’s short and easy to integrate.

NB: this was more a quick-and-dirty practice exercise than a serious attempt at a CAPTCHA. I don’t believe in CAPTCHAs, generally – but if you ARE going to use them, it’s best to have a lot of them in the wild, so it’s harder for crackers to do “crack once, spam everywhere”. See the section at the bottom for links to suggestions for other people’s CAPTCHAs that I reckon would be better for production use if you can get them to work :).

Categories
PHP programming

PHP: how to fetch all possible values of an ENUM from MySQL

Sadly, the code snippets on MySQL’s main website for PHP are mostly untested and buggy (try running them – half of them don’t execute because of silly mistakes).

After much trial and error, here’s one that *actually works*:

// Missing feature (?) from MySQL: find the list of valid ENUM values for a given ENUM
// (actually, returns all the value-arrays for ALL the enum fields in a given table, by name)
// ---------------------------------------------------------
function fetchEnumValuesForTable( $tablename )
{
	global $db; // assuming you're using PEAR:DB here, and throughout (I use it, or MDB, exclusively)
	
	$enumresult = $db->query("SHOW COLUMNS FROM $tablename");

	// Makes arrays out of all ENUM type fields.
	// Uses the field names as array names and skips non-ENUM fields
	while( $enumrow = $enumresult->fetchRow() )
	{
		extract($enumrow);
		if (substr($Type, 0, 4) != 'enum') continue;

		$Type = str_replace('enum', 'array', $Type);
		
		// Add to array
		eval( '$tmp = '."$Type;" ); // I'm not sure why, but I had to do this
		// intermediate step to get it to work
		
		$results[$Field] = $tmp;
	}
	
	return $results; // returns an array mapping each enum's "column name"
	// to "array of elements valid fo that ENUM"
}