Posts Tagged php
Rotating Twitter Tweet feed in WordPress
Posted by admin in Web design & development on June 12th, 2010
Again, this is for one my current projects: my mate Phil’s digital DJ tips site…
OK – so there’s loads of plugin’s out there that do this kind of thing but I’m not after anything fancy (or bloated), I’m happy to code this into the theme files with a bit of PHP and well – it’s something slightly new to learn …
Primary requirements:
- We want this thing to use the SimplePie feed parser and cacheing system, as already included with a standard WordPress install. This will copy the latest tweets into WordPress and avoid running-off to bother Twitter every time our WP site gets a visit. This will also make the thing more robust as Twitter does occasionally… fail.
- A raw Twitter feed will include your user name at the beginning of each tweet. This unnecessary when the blog and tweets are from the same person/identity/brand so we’ll need to remove that.
- We need the SimplePie cache to expire fairly regularly – not enough to bust Twitter’s balls with extra requests – but enough to keep the tweets fresh
- We may want to trim the tweets (yes even less than 140 characters!) so they fit on one line without having the set an explicit width or css “overflow:hidden;”. [This is a graphic design call here as I like backgrounds fills to match the variable length of text (inline) rather than be fixed-width with trailing whitespace of block level element - makes each tweet look like the unique thing it is.]
- Once this is done it goes into a simple carousel to rotate through the last x tweets.
The code comes in a couple of pieces:
The main engine: get the twitter feed – pack it up and process it.
I put the following into an include file to keep it all wrapped together for easy access. This code mostly based on the excellent WordPress codex article “Function Reference/fetch feed“. The String replace reference came from the classic tizag PHP guide and the shorten to the nearest whole word came from somewhere else
<?php
// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/feed.php');
// Get a SimplePie feed object from the specified feed source. CHANGE THE USER ID BELOW!
$rss = fetch_feed('http://twitter.com/statuses/user_timeline/126881491.rss');
if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity(5);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);
endif;
// shorten string function
function short_str( $str, $len, $cut = true ) {
if ( strlen( $str ) <= $len ) return $str;
return ( $cut ? substr( $str, 0, $len ) : substr( $str, 0, strrpos( substr( $str, 0, $len ), ' ' ) ) ) . '...';
}
?>
<div id="djt-twitter-feed"><!-- djt classes and ID to be replaced by something that is useful to you -->
<ul id="djt-tweets" class="jcarousel-skin">
<?php if ($maxitems == 0) echo '<li>No tweets!</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li class="cfn">
<span><a href='<?php echo $item->get_permalink(); //or hardcode link to Twitter homepage ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php //get tweets (but remove twitter ID before displaying)
$djt_twitter_tweet = $item->get_title();
$djt_twitter_tweet = str_replace("YourTwitterUsername: ", "", $djt_twitter_tweet) ;
echo short_str( $djt_twitter_tweet , 140, false) //OK - not actually doing any shortening with this line now ;
?></a></span>
</li>
<?php endforeach; ?>
</ul>
</div>
Set the cache expiry in functions.php
// Alter expiry lenght on feeds (set in seconds)
add_filter( 'wp_feed_cache_transient_lifetime', create_function('$a', 'return 480;') );
Finally make it pretty with jCarousel
The idea was to have one tweet visible at a time – scrolling/rotating through the list. Grab your copy of jCarousel (it’s much bigger than jCarousel lite but by the time I’d figured out the trouble with my wp_head() it was time to leave well enough alone. To be revisited when there’s some time to optimize.) I’ll not go into the CSS – that’s there online.
<!-- jCarousel -->
<script type="text/javascript">
function mycarousel_initCallback(carousel) { };
jQuery(document).ready(function() {
jQuery('#djt-tweets').jcarousel({
auto: 8,
wrap: 'last',
vertical: false,
scroll: 1,
animation: 0,
initCallback: mycarousel_initCallback
});
});
</script>
Long/short headings (or title tags) using WordPress Custom Fields
Posted by admin in CMS, Web design & development on May 19th, 2010
Problem: WP titles are too long to fit in your navigation.
Solution:
Make the title short enough to fit in the navigation and then add a Custom Field into your post (in the example bellow it is set as “heading”) then edit your template file to render the longer version (“heading”) on the page.
Example:
In the Loop of your template swap out
<h1><?php the_title(); ?></h1> <?php the_content(); ?>
for:
<h1><?php// If has a custom field of heading ; then use that:
$customField = get_post_custom_values("heading");
if (isset($customField[0])) {
echo $customField[0];
} else {
the_title();
} ; ?></h1>
<?php the_content(); ?>
Hat-tip: Smashing Magazine
Include an HTML file in a PHP variable
Posted by admin in Web design & development on May 12th, 2010
I couldn’t get PHP to accept an HTML file include as the definition of a variable without throwing my templated page into disarray. An answer came from the venerable desilva then checked with the php folk; use output buffering (see example six in that last link):
<?php
$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
?>
Also worth a look: file_get_contents
Why? Because Coda, my favourite Macintosh text editor+, doesn’t do syntax highlighting of HTML for a PHP string. The site I’ve just finished for a high-end luxury villa in Marbella I had a big block of HTML to include (and work on) for the images page…
MAMP stacked (Mac OS X 10.6)
Posted by admin in Web design & development on November 16th, 2009
When I moved over to Mac OS X 10.6 last week I found I had to fix my MAMP stack. My old MAMP install didn’t work anymore as unfortunately Marc Liyanage’s excellent PHP package fails in 10.6.
The following instructions are mostly the same as before – except it’s not quite so easy now – if you want more than a base PHP install that is. (I even had another look at the commercial MAMP Pro offering. Nah.) For a simple MAMP stack you really only need to turn on Apple’s PHP package and grab a copy of MySQL. If easy is good for you – jump to 1.5.
But I “like” to have phpMyAdmin and don’t like being warned that I’m missing the mcrypt extension for PHP. If you want mcrypt too – start at #1.
Tools & Requirements:
- You need admin access on your Mac
- Basic understanding of the filesystem and Terminal.app
- If you’ve not got it already grab the wonderful and free editor TextWrangler. The config files that need editing are hidden from normal view- but easily reached by TextWrangler which even has a menu item for that: File / Open hidden… . It also handles authentication beautifully to allow saving without having to manually change permissions to and fro.
1. [extra steps to customise things first eg add mcrypt PHP extension - if you don't need/want it skip past to 1.5.] Go and see Xeon Xai’s blog post Snow Leopard PHP Extensions Installation Tutorial or for a quicker version – go here. These first optional steps to customising your set up (adding PHP extensions and even downgrading PHP from 5.3. to 5.2) has turned out to be more “intereseting” than originally percieved and needs post of its own…
1.5 Prepare your php.ini file by duplicating the supplied stock example file and givining it the right name: In Terminal paste this:
sudo cp /private/etc/php.ini.default /private/etc/php.ini
You’ll need to edit the timezone – replace
;date.timezone = with
date.timezone = Europe/Madrid
For other timezones look to the official list here (note the lost semi colon – that’s the comment character)
1.6 Get PHP looking in the right place for MySQL (once you’ve installed it.) …Still editing php.ini find and replace all instances of /var/mysql/mysql.sock with /tmp/mysql.sock . (Why? – well as documented here it seems php.ini is configured for Mac OS X Server’s bundled version of MySQL)
1.7 Start PHP by un-commenting the LoadModule php5_module line in your /etc/apache2/http.conf file.
1.8 Turn Web Sharing (in System Preferences/Sharing) off-and-on again.
2. Get yourself virtualhost.sh from Patrick Gibson. This little shell script will make the process of setting up proper virtual domains on your development server a cinch. I use “.dev” or “.live” as the TLD to prevent any conflict with the live sites. (Although now I’ve started using Git I may just drop the separation between live and development branch domains on my development box. I still put all my sites in my ~/Sites folder though.
3. MySQL
3.1 If you’ve already got another version installed uninstal MySQL from your Mac. NB – this will delete your databases too! But you’ve got those backed up and you want a clean slate:
- sudo rm /usr/local/mysql
- sudo rm -rf /usr/local/mysql*
- sudo rm -rf /Library/StartupItems/MySQLCOM
- sudo rm -rf /Library/PreferencePanes/My*
- edit /etc/hostconfig and remove the line MYSQLCOM=-YES-
- sudo rm -rf /Library/Receipts/mysql*
- sudo rm -rf /Library/Receipts/MySQL*
3.2 Get a MySQL Community Server for the Mac and install it.
4. Give your MySQL root user a password; type the following into the Terminal:
/usr/local/mysql/bin/mysqladmin -u root password sniggle
…if you like sniggle as a passowrd that is.
5. Now you can administer your MySQL server with phpMyAdmin and the root user you’ve just defined. (There are other tools too – eg MySQL Administrator – but I’m used to phpMyAdmin from the hosting packeges I use). You may want to virtualhost phpMyAdmin to, for example, “http://mysql/”. Love virtualhost.sh.
6. Then for each [dynamic] site you’ll probably want to add a user and then associate a DB with that user. Do this in phpMyAdmin in one step using the Privileges pane fill in “Add a new User”/then select “Create database with same name and grant all privileges”. Job’s a good ‘un.
Done and not long-winded at-all at-all!
String to integer (strip all non numerics) with PHP
Posted by admin in Web design & development on June 19th, 2009
I’ve been hacking somebody else’s CMS (without access to the main engine) and needed to calculate a mathematical function on some prices. Specifically needed to display a percentage drop when given an original price as well as the current price. Here follows the journey. [Jump to The Solution.]
Easy right?
<?php
if($originalPrice > 0) {
$percentageDrop = intval(100*(($originalPrice - $currentPrice)/$originalPrice));
}
?>
There was a Problem. The prices are stored not as integers but as formatted currency; ie “€ 120,000″
OK – easy – I found a simple solution to strip non alphanumerics (and space) and adapted it slightly:
<?php
function numericFromString( $string )
{
return preg_replace('/[^0-9]/', '', $string);
}
?>
This function is then applied like so:
$currentPrice = numericFromString( ' € 120,000 ' ) ;
Worked in principle but not in practice – numbers seemed to balloon in size. [I didn't spot it all the numbers which had '8364' at the beginning...]
I had to call in Dave “tech support” Watson. “Bingo!” he said.
The problem [you've figured it out already... ] is that the euro symbol is a numeric HTML entity: €. There’s a bunch of numbers in there too. In fact – 8364.
So Dave took my adapted [and useless] function and made it work. Now it looks like this:
The Solution
<?php
function numericFromString($string) {
$string = str_replace('€','',$string);
return preg_replace('/[^0-9]/','', html_entity_decode($string));
}
?>
Why the extra line with str_replace? Because html_entity_decode doesn’t actually decode numerical html entities…
Would you believe it?
For more bullet proof results it may be worthwhile to try the following in place of that str_replace (from the comments at the official PHP manual at php.net)
$string = preg_replace('/(\d+);/me',"chr(\\1)",$string); //decimal notation
$string = preg_replace('/([a-f0-9]+);/mei',"chr(0x\\1)",$string); //hex notation
MAMP stacked (Mac OS X 10.5)
Posted by admin in Web design & development on June 5th, 2009
UPDATE: I’ve upgraded to Snow Leopard (Mac OS X 10.6) and the following instructions are no longer entirely valid as Marc Liyanage’s PHP package hasn’t been upgraded to work in the Snow.
Want to get MAMP on Mac OS X 10.6?
If you’re on 10.5 you may read on…
Want to roll a MAMP stack of your own to enable proper local web development? Try these steps to getting you own development environment:
1. Swap the Apple package of PHP for Marc Liyanage’s package of PHP for Mac OS X. Read his notes – only takes a minute. His version has useful “extras” like the mcrypt extension that Apple doesn’t include: you’ll want that for phpMyAdmin. (If you’ve already started Apple’s version – you’ll know how to stop it by re-commenting the LoadModule php5_module line in your http.conf file )
2. Get yourself virtualhost.sh from Patrick Gibson. This little shell script will make the process of setting up proper virtual domains on your development server a cinch. I use “.dev” or “.live” as the TLD to prevent any conflict with the live sites. (Although now I’ve started using Git I may just drop the separation between live and development branch domains on my development box. I still put all my sites in my ~/Sites folder though.
3. Get a Mac OS X MySQL package – (not the latest build but v5.0.x) from the good folks at MySQL. If you’ve already got another version installed – here’s how to uninstal MySQL from a Mac (NB – this will delete your databases too!).
4. Give your MySQL root user a password; type the following into the Terminal:
/usr/local/mysql/bin/mysqladmin -u root password sniggle
…if you like sniggle as a passowrd that is.
5. Now you can administer your MySQL server with phpMyAdmin and the root user you’ve just defined. (There are other tools too – eg MySQL Administrator – but I’m used to phpMyAdmin from the hosting packeges I use). You may want to virtualhost phpMyAdmin to, for example, “http://mysql/”. Love virtualhost.sh.
6. Then for each [dynamic] site you’ll probably want to add a user and then associate a DB with that user. Do this in phpMyAdmin in one step using the Privileges pane fill in “Add a new User”/then select “Create database with same name and grant all privileges”. Job’s a good ‘un.
Done and not long-winded at-all at-all!
[Originally posted as a reply in Panic's Coda forum... Lots of love for MAMP Pro - a serious contender - and for just 40€... ]
DOCUMENT_ROOT trailing slash issues?
Posted by admin in Web design & development on April 28th, 2009
Do you have a web server and a development server rendering different versions of the $_SERVER['DOCUMENT_ROOT'] superglobal?
Mmm, me too. I’d have pulled my hair out if I had any. Made me feel rather defeated after thinking I’d fixed things so that one DB connect call would work on two+ servers. Fancy that – PHP behaving unpredictably – anybody would think I was playingworking very hard with CSS.
[
I had finally got round to using substr to trim the public_htmlpart off a DocumentRoot path to get me an absolutely relative link to a safe place...
ie (substr($_SERVER['DOCUMENT_ROOT'], 0, -12). )
ie keeping the DB connect information out of the public view
]
Anyway for how to fix the trailing slash problem you should point your google at the New Zealand PHP advocates or crib directly from here:
$_SERVER['DOCUMENT_ROOT'] .=
(substr($_SERVER['DOCUMENT_ROOT'],-1)=='/')?'':'/';
We *heart* Nathan Kennedy