Boolean

WordPress ‘hacks’

Wordpress Logo

Been doing a bit of WordPress customisation work recently, – here are a few ways to delve into your content. There are plugins available for a lot of these techniques; however sometimes you may wish to trim your plugins for speed or other considerations. Enjoy.

1) Displaying Related Posts
Related posts can retain your readers by offering them easy to click, context related links. To execute this ‘hack’ you will need to edit your single.php file (in your current theme)

<?php
//Place in the loop to list 5 posts related to the first tag in the current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5, 'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php endwhile;
}
}
?>

2) Displaying Recent Comments
Recent comments can be very helpful to build awareness of what topics readers are finding value in. To display recent comments you will need to modify your functions.php file (in your current theme)
If this file is not present, you will need to create it.

<?php
function recent_comments($src_count=10, $src_length=60, $pre_HTML='<ul>', $post_HTML='') {
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,
SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC
LIMIT $src_count";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
foreach ($comments as $comment) {
$output .= "<li><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"on " . $comment->post_title . "\">" . strip_tags($comment->com_excerpt) ."...</a></li>";
}
$output .= $post_HTML;
echo $output;
}
?>

Wherever you would like to place comments simply include the following line:
<?php recent_comments(); ?>

3) Adding A Print Button To Blog Posts
Of course there are keyboard shortcuts and other ways to perform this task, but it is nice little feature to offer.
Edit your single.php file (in your current theme) and add the following code:

<a href="javascript:window.print()" rel="nofollow">Print this Article</a>

4) Excluding Categories From Your RSS Feed
Perhaps your have a category which has little to do with the rest of your blog, – sometimes it can be useful to exclude certain categories from your feed. Simple.

You will need to know the Category ID (cat_id= seen in your URLs)

Edit your function.php file (for your current theme, or create one if it doesnt exist)

function myFilter($query) {
if ($query->is_feed) {
$query->set('cat','-5'); //Don't forget to change the category ID =^o^=
}
return $query;
}

add_filter('pre_get_posts','myFilter');

WordPress ‘hacks’ Read More »

Everything about UTF-8

Filed under PHP, but obviously much more than that.

In an update to this post, it is time for a revisit of UTF-8.

In a post entitled “Everything you always wanted to know about UTF-8 (but never dared to ask)” the good folk at the iBuildings TechPortal have Juliette Reinders Folmer speak on a variety of topics.

“…In this talk I will cover UTF-8 from basic linguistics, through client-side aspects to all the steps you need to take to tackle the most common (and some more obscure) issues when using UTF-8 in a database driven PHP application…”

Check it out here.

Everything about UTF-8 Read More »

Simple PHP Best Practices

This post is intended to make you think a little bit more about some of the habits you may have formed whilst programming. It is not the nirvana of programming, nor best practice, just a few little ideas to help you along the way.

1. Use descriptive variable names
Arguably this is the hallmark of the inexperienced or just plain poor programmer. Using variables names such as $x or $y makes a major sacrifice in readability for a negligible performance improvement.
Remember, variable names are cheap whilst programmer time is not.

2. No commented out code
Sure, commenting out code makes sense if you do not use a revision control system (like CVS/SVN/Git/etc) however – why on earth are you not using a revision control system?
Leaving commented code behind tends to clutter files and reduces readability, – especially in those hard times on a console and don’t have the luxury of an editor with syntax highlighting and large resolution.

3. Write control structures as you would say them
It is all too easy to make control structures (if, switch, while, etc…) unreadable. An easy trick to improve readability is to read it to yourself, from start to finish; this forces you to read it anew and clears up strange comparisons such as: ‘!$security_check===false’.

4. Use single quotes (‘) by default and double quotes only when you want to put variables in your string
It’s the little things…

Simple PHP Best Practices Read More »

Exporting a MySQL Database Schema as XML

Dumping a database schema is a an often required quick task. This script will read the schema from a MySQL database, and output it XML to describe it.


<?php
// Define a few constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");
define("DB_NAME", "example");

// Lets connect to the db
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");

// Choose a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select examples");
// Return all of the available tables
$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );

$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}

$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";

// Now iterate through each table and return the fields
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );

while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}

$output .= "</table>";
}

$output .= "</schema>";

// Notify the browser the type of file being dealt with
header("Content-type: text/xml");
// Display the XML to describe the schema
echo $output;

// Dont forget to close the connection
mysql_close($dbhandle);
?>

Remember, this is an example, and real world code should escape characters, follow best security practices etc. Proof of concept code here, – not a snippet to put live.

Exporting a MySQL Database Schema as XML Read More »

WordPress Custom RSS feeds

Wordpress Logo

Adding custom content to your RSS feed is actually a fairly simple process. You may wish to do this to add a copyright notice, a link to social media profile, twitter account, or perhaps even sell advertising.
Basic usage looks like this:

function rssModification ($contentToFilter) {
// Manipulate the content as required
return $contentToFilter;
}add_filter('filterName', 'rssModification ');

There are lots of filters available and obviously an extensive list here. In this example we are going to use the the_excerpt_rss and the_content_rss filters.

When the filter is executed the data to be modified is passed to the specified function. The content can then be altered and then returned.


function rssContent($content) {
$content = $content . '<a href="http://twitter.com/booleanvalue/">Follow me on Twitter!</a>';
return $content;
}
add_filter('the_excerpt_rss', 'rssContent');
add_filter('the_content_rss', 'rssContent');

WordPress Custom RSS feeds Read More »

Building scalable web applications

Scalability is a desirable property of a system, a network, or a process, which indicates its ability to either handle growing amounts of work in a graceful manner or to be readily enlarged. (Wikipedia)

In order to achieve good scalability an application has to be designed with scalability in mind. Every application requires its own level of scalability and performance, and this should ideally be addressed during functional and technical design specification.

During this design phase there are a number of things to consider, – especially performance. Higher performance generally means more requests per second and less intensive operations; good caching is vital (think Smarty, ZendPlatform, memcached etc)

Where possible try to build software that is ‘loosely coupled’, – that way if it is required in the future it will be possible to serve different components from different servers. Often application bottlenecks occur in a small part of the application so with loosely coupled software it is easier to relocate that component to dedicated hardware.

Infrastructure architecture must support the application architecture. PHP web server clusters require a solution for sharing sessions between servers. These servers can have their own local cache or they could use a shared caching mechanism. Building on a SOA architecture can help spread load across multiple servers.

Designing a database includes thinking about scalability and performance. While replication is a good way to spread read queries across multiple servers it doesn’t help when you have lots of writes. Data partitioning is a valuable consideration; for example each group of database servers can serve part of your database. This allows you to spread writes to different groups of servers, however obviously adds to the complexity of partitioning and fetching data.

During the development process ensure that you develop with a database that reflects the real thing. Try to populate your database with content before you start developing as a database with just a couple of rows behaves different to one with millions of rows.

Building scalable web applications Read More »

Useful Run Commands

Many tools, utilities, and control panel options can be run directly from the command line. 156 of them in fact according to this list. After the popularity of this post I realised this was something that people can use.

The original list is here however I wanted to include them here as a reference and in case the link stops working.

To Access Command
Accessibility Controls access.cpl
Accessibility Wizard accwiz
Add Hardware Wizard hdwwiz.cpl
Add/Remove Programs appwiz.cpl
Administrative Tools control admintools
Adobe Acrobat (if installed) acrobat
Adobe Designer (if installed) formdesigner
Adobe Distiller (if installed) acrodist
Adobe ImageReady (if installed) imageready
Adobe Photoshop (if installed) photoshop
Automatic Updates wuaucpl.cpl
Bluetooth Transfer Wizard fsquirt
Calculator calc
Certificate Manager certmgr.msc
Character Map charmap
Check Disk Utility chkdsk
Clipboard Viewer clipbrd
Command Prompt cmd
Component Services dcomcnfg
Computer Management compmgmt.msc
Control Panel control
Date and Time Properties timedate.cpl
DDE Shares ddeshare
Device Manager devmgmt.msc
Direct X Control Panel (if installed)* directx.cpl
Direct X Troubleshooter dxdiag
Disk Cleanup Utility cleanmgr
Disk Defragment dfrg.msc
Disk Management diskmgmt.msc
Disk Partition Manager diskpart
Display Properties control desktop
Display Properties desk.cpl
Display Properties (w/Appearance Tab Preselected) control color
Dr. Watson System Troubleshooting Utility drwtsn32
Driver Verifier Utility verifier
Event Viewer eventvwr.msc
Files and Settings Transfer Tool migwiz
File Signature Verification Tool sigverif
Findfast findfast.cpl
Firefox (if installed) firefox
Folders Properties folders
Fonts control fonts
Fonts Folder fonts
Free Cell Card Game freecell
Game Controllers joy.cpl
Group Policy Editor (XP Prof) gpedit.msc
Hearts Card Game mshearts
Help and Support helpctr
HyperTerminal hypertrm
Iexpress Wizard iexpress
Indexing Service ciadv.msc
Internet Connection Wizard icwconn1
Internet Explorer iexplore
Internet Properties inetcpl.cpl
Internet Setup Wizard inetwiz
IP Configuration (Display Connection Configuration) ipconfig /all
IP Configuration (Display DNS Cache Contents) ipconfig /displaydns
IP Configuration (Delete DNS Cache Contents) ipconfig /flushdns
IP Configuration (Release All Connections) ipconfig /release
IP Configuration (Renew All Connections) ipconfig /renew
IP Configuration (Refreshes DHCP & Re-Registers DNS) ipconfig /registerdns
IP Configuration (Display DHCP Class ID) ipconfig /showclassid
IP Configuration (Modifies DHCP Class ID) ipconfig /setclassid
Java Control Panel (if installed) jpicpl32.cpl
Java Control Panel (if installed) javaws
Keyboard Properties control keyboard
Local Security Settings secpol.msc
Local Users and Groups lusrmgr.msc
Logs You Out Of Windows logoff
Malicious Software Removal Tool mrt
Microsoft Access (if installed) msaccess
Microsoft Chat winchat
Microsoft Excel (if installed) excel
Microsoft Frontpage (if installed) frontpg
Microsoft Movie Maker moviemk
Microsoft Paint mspaint
Microsoft Powerpoint (if installed) powerpnt
Microsoft Word (if installed) winword
Microsoft Syncronization Tool mobsync
Minesweeper Game winmine
Mouse Properties control mouse
Mouse Properties main.cpl
Nero (if installed) nero
Netmeeting conf
Network Connections control netconnections
Network Connections ncpa.cpl
Network Setup Wizard netsetup.cpl
Notepad notepad
Nview Desktop Manager (if installed) nvtuicpl.cpl
Object Packager packager
ODBC Data Source Administrator odbccp32.cpl
On Screen Keyboard osk
Opens AC3 Filter (if installed) ac3filter.cpl
Outlook Express msimn
Paint pbrush
Password Properties password.cpl
Performance Monitor perfmon.msc
Performance Monitor perfmon
Phone and Modem Options telephon.cpl
Phone Dialer dialer
Pinball Game pinball
Power Configuration powercfg.cpl
Printers and Faxes control printers
Printers Folder printers
Private Character Editor eudcedit
Quicktime (If Installed) QuickTime.cpl
Quicktime Player (if installed) quicktimeplayer
Real Player (if installed) realplay
Regional Settings intl.cpl
Registry Editor regedit
Registry Editor regedit32
Remote Access Phonebook rasphone
Remote Desktop mstsc
Removable Storage ntmsmgr.msc
Removable Storage Operator Requests ntmsoprq.msc
Resultant Set of Policy (XP Prof) rsop.msc
Scanners and Cameras sticpl.cpl
Scheduled Tasks control schedtasks
Security Center wscui.cpl
Services services.msc
Shared Folders fsmgmt.msc
Shuts Down Windows shutdown
Sounds and Audio mmsys.cpl
Spider Solitare Card Game spider
SQL Client Configuration cliconfg
System Configuration Editor sysedit
System Configuration Utility msconfig
System File Checker Utility (Scan Immediately) sfc /scannow
System File Checker Utility (Scan Once At The Next Boot) sfc /scanonce
System File Checker Utility (Scan On Every Boot) sfc /scanboot
System File Checker Utility (Return Scan Setting To Default) sfc /revert
System File Checker Utility (Purge File Cache) sfc /purgecache
System File Checker Utility (Sets Cache Size to size x) sfc /cachesize=x
System Information msinfo32
System Properties sysdm.cpl
Task Manager taskmgr
TCP Tester tcptest
Telnet Client telnet
Tweak UI (if installed) tweakui
User Account Management nusrmgr.cpl
Utility Manager utilman
Windows Address Book wab
Windows Address Book Import Utility wabmig
Windows Backup Utility (if installed) ntbackup
Windows Explorer explorer
Windows Firewall firewall.cpl
Windows Magnifier magnify
Windows Management Infrastructure wmimgmt.msc
Windows Media Player wmplayer
Windows Messenger msmsgs
Windows Picture Import Wizard (need camera connected) wiaacmgr
Windows System Security Tool syskey
Windows Update Launches wupdmgr
Windows Version (to show which version of windows) winver
Windows XP Tour Wizard tourstart
Wordpad write

Useful Run Commands Read More »

Scheduling mySQL backups

I’m sure there is no need to explain the virtues of regular backups. Below are three steps to peace of mind

1) Configure a backup directory on the server

mkdir /var/lib/backupfolder
cd /var/lib/backupfolder

2) Make a backup script

vi mysqlbackup.sh

#!/bin/sh
# MySQL server username goes here
USERNAME="username"
# MySQL server password goes here
PASSWORD="password"
# List of DBNAMES for Backup
DBNAME="dbname"
#date timestamp used in the log
DATE=`/bin/date +%Y-%m-%d_%Hh%Mm`
# format the output file
OUTDIR="/var/lib/backupfolder/"
OUTFILE="ip_bindass".$DATE."sql.gz"
#working directory
DIR="/var/lib/backupfolder/"
#cd $DIR
# Do the MySQL Backup
/usr/bin/mysqldump --database $DBNAME --opt --single-transaction -u$USERNAME -p$PASSWORD | /usr/bin/gzip -9 > $OUTDIR$OUTFILE

Dont forget to change permissions

chmod +x mysqlbackup.sh

3) Schedule the backup in crontab

crontab -e

Add something along the lines of:

30 23 * * * /var/lib/backupfolder/mysqlbackup.sh

To backup at 11:30PM every day. Just as important as to backup up is to test restores; – it’s no good having backups and feeling at ease if you cant recover in the event of catastrophe!

Scheduling mySQL backups Read More »