Development

Embed an RSS/ATOM Feed into your WordPress Website

By michael  |  April 26th, 2010  |  Published in Development, WordPress  |  Comments Off

One of our clients needs to pull an RSS feed from a real estate virtual tour provider and display it on one of their pages. I looked into a few plugins and could not find one that was easily customizable. After a quick google search I discovered that WordPress has some built-in functions based off of SimplePie‘s easy to use RSS API.

We also needed to customize the output a little bit, which required me to rely on PHP’s preg_match and preg_replace functions. Here is some simple example for embedding a feed into your WordPess website:

<?php
include_once(ABSPATH.WPINC.'/rss.php'); // path to include script
$feed = fetch_feed('http://url.to.feed/'); // specify feed url
?>

<?php
if (!is_wp_error($feed)) : 
	$rss_items = $feed->get_items(); 
?>

    // Loop through each feed item and display each item as a hyperlink. <?php foreach ( $rss_items as $item ) : ?>
  • <?php echo $item->get_title(); ?>
  • <?php endforeach; ?>

Check out the codex for more information about WordPress’ function feed_fetch()… and with a little extra coding you can format the feed any way you like, see our example at NC Capital Homes.

Easily Extended Contact Info in WordPress

By michael  |  April 22nd, 2010  |  Published in Development, WordPress, WordPress Plugins  |  Comments Off

I’m working on a project where I need the ability to add “Phone”, “Building”, and “Room” as information a user could add in their profile. I also wanted to remove “AIM”, “Yahoo”, and “Jabber” — none of the users are going to need to fill in that info.

You can easily add this code into your functions.php. I was writing it for a WordPress MU site with multiple themes and needed to make sure it was enforced, so I stuck it in the mu-plugins directory, in a file named “extended-contact-info.php”.

This is the simple code block you need:

function extended_contact_info($user_contactmethods) {
	//Use this if you want to append to the default 
	//contact methods (AIM, Yahoo, Jabber)
	//$user_contactmethods += array(
	//	'building' => __('Building'),
	//	'room' => __('Room'),
	//	'phone' => __('Phone')
	//);

	//Use this if you want to ignore the default 
	//contact methods (AIM, Yahoo, Jabber)
	$user_contactmethods = array(
		'building' => __('Building'),
		'room' => __('Room'),
		'phone' => __('Phone')
	);
	
	return $user_contactmethods;
}

add_filter('user_contactmethods', 'extended_contact_info');

Saving ‘meta data’ for WordPress categories

By michael  |  February 7th, 2010  |  Published in Development, WordPress  |  15 Comments

[updated 2010-06-08]

WordPress has some great hooks for adding extra fields to the Add Category page (as well as the edit category and the table listing the categories). Where / how do you save that data though. I ran accross a couple other devs on Twitter this evening that were asking this question. This post is primarily for them and it doesn’t provide all the code you need to get finish, but it should get most dev on their way. For instance, you will need another action for adding to the edit page, another action for adding to the table, and another action for editing the data. You will need to replace the type of fields. The below code assumes a custom taxonomy called ‘manufacturers’.

Additionally, the code below saves every field for every category or taxonomy in a different line in the options table. If I were going to put this into production I’d serialize the data so that all fields for a single category were stored in a single row of the options table.

Finally, as this is not in production yet (though it has been tested) there may be some errors or bugs. Please let me know if you find any and I will update (code would be nice too).

This following code, placed in your theme’s functions.php file:

<?php
### CUSTOM FIELDS FOR MANUFACTURERS

	// Manufacturer fields
	function ft_add_manufacturer_fields(){
		?>
		<!-- Web Site -->
		<div class="form-field">
			<label for="man_web_site"><?php _e('Manufacturer Web Site') ?></label>
			<input type='text' name="man_web_site" id="man_web_site" />
			<p><?php _e('The manufacturer\'s web site.'); ?></p>
		</div>

		<!-- Logo -->
		<div class="form-field">
			<label for="man_logo_url"><?php _e('Manufacturer Logo URL') ?></label>
			<input type='text' name="man_logo_url" id="man_logo_url" />
			<p><?php _e('The web address of the manufacturer\'s logo.'); ?></p>
		</div>

		<!-- Status -->
		<div class="form-field">
			<label for="man_status"><?php _e('Manufacturer Status') ?></label>
			<select name="man_status" id="man_status"><option value='standard' selected="selected">Standard</option><option value='premium'>Premium</option></select>
			<p><?php _e('Only manufacturer\'s with a premium status will have their logos linked to their web site.'); ?></p>
		</div>

		<?php
	}
	add_action('manufacturers_add_form_fields','ft_add_manufacturer_fields');

	// Add field to edit category screen
	function ft_edit_manufacturers_form(){	

		// clear values.
		$man_web_site = $man_logo_url = $man_status = '';

		// Clean tag id
		$id = sanitize_text_field($_GET['tag_ID']);

		if ( $opt_array = get_option('man_'.$id.'_meta') ){
			$man_web_site 	= sanitize_text_field($opt_array['man_web_site']);
			$man_logo_url 	= sanitize_text_field($opt_array['man_logo_url']);
			$man_status 	= sanitize_text_field($opt_array['man_status']);
		}
		?>
		<!-- Web Site -->
		<tr class="form-field">
			<th scope="row" valign="top"><label for="man_web_site"><?php _e('Manufacturer Web Site') ?></label></th>
			<td><input type='text' name="man_web_site" id="man_web_site" value="<?php echo $man_web_site; ?>" /><br />
			<span class="man_web_site"><?php _e('The manufacturer\'s web site.'); ?></span></td>
		</tr>

		<!-- Logo -->
		<tr class="form-field">
			<th scope="row" valign="top"><label for="man_logo_url"><?php _e('Manufacturer Logo URL') ?></label></th>
			<td><input type='text' name="man_logo_url" id="man_logo_url" value="<?php echo $man_logo_url; ?>" /><br />
			<span class="man_logo_url"><?php _e('The URL for the manufacturer\'s logo.'); ?></span></td>
		</tr>

		<!-- Status -->
		<tr class="form-field">
			<th scope="row" valign="top"><label for="man_status"><?php _e('Manufacturer Status') ?></label></th>
			<td><select name="man_status" id="man_status"><option value='standard' selected="selected">Standard</option><option value='premium' <?php if ( $man_status == 'premium' ){ echo 'selected="selected" '; } ?>>Premium</option></select>
			<br /><span class="man_status"><?php _e('Only manufacturer\'s with a premium status will have their logos linked to their web site.'); ?></span></td>
		</tr>

		<?php
	}
	add_action('manufacturers_edit_form_fields','ft_edit_manufacturers_form');

	// Add Manufacturer fields to table head
	function ft_manage_manufacturers_columns($columns){
		if ( !isset($_GET['taxonomy']) || $_GET['taxonomy'] != 'manufacturers' )
			return $columns;

		if ( $posts = $columns['posts'] ){ unset($columns['posts']); }
		$columns['man_status'] = 'Status';
		if ( isset($posts) ){ $columns['posts'] = 'Machines'; }
		return $columns;
	}
	add_filter('manage_edit-tags_columns','ft_manage_manufacturers_columns');

	// Add fields to table for each manufacturer
	function ft_manage_manufacturers_custom_fields($deprecated,$column_name,$term_id){
		if ( $opt_array = get_option('man_'.$term_id.'_meta') ){
			return esc_html($opt_array[$column_name]);
		}
	}
	add_filter('manage_manufacturers_custom_column','ft_manage_manufacturers_custom_fields',10,3);

	// Insert or Update the Manufacturer
	function ft_create_update_manufacturer($term_id,$tt_id){
		// Grab your field names in $_POST, sanatize and put wherever you want
		if ( isset($_POST['man_web_site']) )
			$update['man_web_site'] = sanitize_text_field($_POST['man_web_site']);
		if ( isset($_POST['man_logo_url']) )
			$update['man_logo_url'] = sanitize_text_field($_POST['man_logo_url']);
		if ( isset($_POST['man_status']) )
			$update['man_status'] = sanitize_text_field($_POST['man_status']);

		if ( isset($update) )
			update_option( 'man_'.$term_id.'_meta' , $update );

	}
	add_action('created_manufacturers','ft_create_update_manufacturer',10,2);
	add_action('edit_manufacturers','ft_create_update_manufacturer',10,2);

	// On Delete Manufacturer
	function ft_delete_manufacturer($term_id,$tt_id){
		delete_option('man_'.$term_id.'_meta');
	}
	add_action('delete_manufacturers','ft_delete_manufacturer',10,2);
>

Download a text file with the above code: here

WPMU – Add ALL New Users to Main Site

By michael  |  August 12th, 2009  |  Published in Blogging, Development, WordPress  |  Comments Off

In WordPress MU there are two levels of users. There are users who have a blog and users who do not have a blog. This option is usually chosen when the user creates their account. If they choose to have just a username only (no blog), then the user is added as a subscriber to the main site (default setting). If they chose to have a blog, WPMU adds a subsite for them with an administrator user for that subsite. However, it does not give them subscriber permissions to the main site.

This became an issue with a site I was working on recently. The main site had a calendar that any logged in user needed to be able to add an event to. To do this I had to create a custom group that allowed users to post in a specific category only, which worked great, except for blog users. Since blog users are not given any rights on the main blog, I needed to find a way to automatically create the same functionality that normal users have on the main site.

This is what I came up with:

function ft_new_user_meta($blog_id, $user_id) {
add_user_to_blog('1', $user_id, 'calendar' );
}
add_action( 'wpmu_new_blog', 'ft_new_user_meta', 10, 2 );

Basically, I hook onto the wpmu_new_blog function, so whenever it is called, it calls my ft_new_user_meta function. Which passes in the two variables $blog_id and $user_id. Then I run the function, add_user_to_blog with 1 as the blog_id for the main site, the $user_id that I’m adding, and the role that I want to give. In this case it is my custom “calendar” role.

I added that into a file named new_user.php which I placed in the mu-plugins directory. Now, whenever a user goes to the site and creates their own blog, it gives them access to the main site with rights to add events to the calendar.

Hide “Back to Top” Links

By michael  |  July 23rd, 2009  |  Published in Development  |  Comments Off

Often, web pages will include links at the top of the page which reference paragraphs or sections lower on the page. A recent client’s web page had a list of links at the top of the page. Each link would cause the page to scroll down to that particular section of the web page. The client wanted the user to be able to quickly return to the top of the page, but he did not want “Back to Top” links at the end of each section.

Usually, this type of web page does have “Back to Top” links at the end of each section. For example, click here to jump to the next section of this post.

Next Section
This is the next section. If you clicked on the link above, then you scrolled to this section. This section could have been anywhere on this page.

This is the HTML code used to create the link “click here to jump to the next section of this post”:

<a href="#nextsection">click here to jump to the next section of this post</a>

This code creates a link to a named section called “nextsection”.

The code to create the named section for “Next Section” would look like this:

<a name="nextsection"></a>

Typically, you would create a link at the end of “Next Section” to allow the user to jump back to the top of the web page, like this: Back to Top.

This is the code for creating the “Back to Top” link:

<a href="#">Back to Top</a>

Hiding “Back to Top” Links
However, it is not always aesthetically pleasing to have “Back to Top” links appear throughout your web page at the end of each paragraph or setting. This is especially true if your users want to print your web page. The process below “hides” the “Back to Top” links until a user clicks a link to that section.

For example, this link will take you to a section called “New Section“. However, before you click that link, scroll down to “New Section”, and you will see that there is no “Back to Top” link.

New Section
This is the new section. If you clicked on the link to “New Section” above, you should have jumped to this section. You will also see a “Back to Top” link here:

However, if you scrolled down the page without clicking the “New Section” link above, then you should not see a link for “Back to Top”.

This is the new HTML code used for the “New Section” link:

<a onclick="document.getElementById('newsection_back2top').style.visibility = 'visible';return true"
href="#newsection">New Section</a>

This code sets element “newsection_back2top” (defined below) to be visible when the link “New Section” is clicked.

This is the new HTML code for the “Back to Top” link:

<span id="newsection_back2top" style="visibility: hidden;">
<a onclick="document.getElementById('newsection_back2top').style.visibility = 'hidden';
return true" href="#">Back to Top</a></span>

Floating “Back to Top” Links
There is another option that works well for a web page that has several section with multiple “Back to Top” links. Instead of coding a “Back to Top” link after each section, or even coding a hiding “Back to Top” link after each section, you can create a “Back to Top” link that floats at a particular place on the web page.

For example, click this link for the “Final Section“. This link will cause the page to scroll down to the section labeled “Final Section”, and it will also make a new “Back to Top” element visible.

Final Section
If you clicked the “Final Section” link above, you should now see a floating “Back to Top” link on the left side of the page. Even if you scroll up or down on the web page, the “Back to Top” link will remain in the same position. Click the “Back to Top” link to scroll to the top of the page and to remove that floating “Back to Top” link.

The code for the “Final Section” does not change. However, this is the new code for the “Back to Top” link:

<div id="finalsection_back2top" style="position: fixed; left: 5px; top: 40px; background: #EEE; 
visibility: hidden;"><a onclick="document.getElementById('finalsection_back2top').style.visibility = 'hidden';
return true" href="#">Back to Top</a></div>

The addition of fixed positioning along with a location (left, top), causes the “Back to Top” link to “float” in the specified position on the web page.

Setting up a single login across WordPress and WordPress MU

By michael  |  July 20th, 2009  |  Published in Development, WordPress  |  7 Comments

We recently ran into a client who needed help getting his WordPress installation and his WordPress MU installation communicating together. They had WordPress installed in the root directory of their website, and WPMU installed in a sub-directory of the same website. Both WP installations were on the same DB.

Unfortunately I was unable to get a good copy of their MySQL tables, so I had to recreate this setup on my own. I did a little research and found out that many people have similar setups and many people have different solutions. I felt like it might be beneficial to share my experience with this.

First, I downloaded the latest WP and WPMU (2.8.1 at the time). I setup a new MySQL DB and extracted WP and WPMU into their respective directories (remember WordPress was in the root and WPMU in a sub-folder).

Something like this:

/wordpress/
/wordpress/wpmu/

After messing around for a while I determined it was easiest to install WPMU first. There was two reasons for my thinking, one of which was no necessary. First, if you were to install WordPress first, when you tried to install WPMU it would get confused because it would see the wp-config.php file below. Don’t ask me why this is, it just is. Second, I was thinking about changing the WP DB prefix (default: wp_) to something else. In WordPress you can do this during the install, in WPMU you have to edit the files to get this accomplished. This was the part that wasn’t really important, because I actually kept both using wp_ as the prefix.

Ok, WPMU is installed and working, now I installed WP. At the end of the install, it sees that there is already a wp_users table, with an Admin user in it. This caused me a little problem because I think it actually reset the password without telling me the new password. So I had to go into phpMySQL to reset the password to something I knew. Hardly a huge problem, but still it might make you think that everything is broken when you cannot log into either WP or WPMU!

Now, the goal is to be able to log into either WP or WPMU and then not have to log in again when you switch to the other. So, I needed to be able to log into WP and then go to WPMU without it asking me to log in again (and vice-versa). This is all about COOKIES! There are a bunch of people who have different solutions, but the easiest solution for me was to make sure that both the WP auth cookie and the WPMU auth cookie were identical. This is not as easy as it sounds, because MU handles cookies slightly different than WP. But ultimately, I just needed to edit wp-config.php in both WP and WPMU to get it to work perfectly.

Here are my setting changes:
define(‘COOKIE_DOMAIN’, false);
define(‘ADMIN_COOKIE_PATH’, ’/’);
define(‘COOKIEPATH’, false);
define(‘SITECOOKIEPATH’, false);
define(‘COOKIEHASH’, ‘vy48u9w38868t7t99jh8g137x221r5h1h8’);
define(‘AUTH_KEY’, ‘49uld4y46i3432ugvi346uv86uci53v5529jj5z265i987u43snbxwj3ps92u2lr’);
define(‘SECURE_AUTH_KEY’, ‘f2et8b6xck64m4j2vmqcuqxb57s3rk5edh5d19pq114ef7y67g35i6m682lr288z’);
define(‘LOGGED_IN_KEY’, ‘mywu969v3tcf2uer82vxisx8k6sq2neib5qs1qt4sx383slslb5t1xep12hbtcxs’);
define(‘NONCE_KEY’, ‘bde6j26r93lvwmgwydw7x3kp74r5299q8vxe832y7r616lf215142e5t4vc55j36’);
define(‘AUTH_SALT’, ‘3856m559klvidrx34fi574ct32r94x77bepr7638jmuw22d29883i82k76un2tm4’);
define(‘LOGGED_IN_SALT’, ‘jq4p67bv772nd73w4zm6286552x755v6293qpj5fbe34fxy894trdu77h38586n2’);
define(‘SECURE_AUTH_SALT’, ‘i9hlmd67n21j2u485645in9vu6v92itgfmja6bjfbc36gqc673svlis9u789316p’);
define(‘TEST_COOKIE’, ‘TEST_COOKIE’.COOKIEHASH);

I actually copied the AUTH_KEY, SECURE_AUTH_KEY, LOGGED_IN_KEY, NONCE_KEY, AUTH_SALT, LOGGED_IN_SALT, and SECURE_AUTH_SALT from the WPMU wp-config.php file. I just copied it over the normal WP wp-config.php settings. Then I added the other lines and everything worked. It didn’t require any additional plugins or work.

I sent the instructions to the client, he followed exactly what I did here and it worked fine for him. So, if you have a similar need, I’m pretty confident this will work for you.

SysAdmin, Web Developer PC Setup

By michael  |  July 15th, 2009  |  Published in Development, SysAdmin  |  1 Comment

I just got a new Desktop PC, it’s a DELL 760, with two Dell 2208 WFP monitors. I thought this might be a good opportunity for me to list all the software and packages I install on my machines. I am a Systems Administrator and a Web Developer, so I use a lot of different tools.

Development Tools:

  • XAMPP – An easy to install Apache distribution containing MySQL, PHP and Perl.
  • Notepad++ – A free (as in “free speech” and also as in “free beer”) source code editor and Notepad replacement that supports several languages.
  • Tortoise SVN – Subversion client for Windows.
  • Adobe Web Premium Suite – mostly for Dreamweaver and Photoshop
    • SubWeaver - Tortoise SVN Plugin for Dreamweaver.
  • GIMP – Free GNU image manipulation program (similar to Photoshop).

Browsers:

  • Firefox – 90% of my browsing is done with Firefox.
    • Adblock Plus – Block annoying Ads.
    • Download Statusbar – I like this for my download management.
    • Firebug – Necessary tool for any web developer.
    • Firesizer – Also pretty nice tool to see how your site looks in specific resolutions.
    • Forecastfox – Nice little forecast plugin for FF.
    • Gmail Manager – Best Gmail plugin out there, reports on my 16+ gmail and gmail hosted accounts.
    • IE Tab – Two uses: 1) for sites that only work in IE – but you don’t want to open IE and 2) to test a site in IE.
    • oldbar – I don’t like the big fat URL bar with firefox, this makes it one size with all the benefits of the new bar.
    • SecurePassword Generator – Great tool for generating secure passwords.
    • TwitterFox – Twitter plugin.
    • Ubiquity – Don’t really use this much, but it’s there just in case.
    • User Agent Switcher – Testing iPhone-enabled sites and hacking airport wireless.
    • Xmarks – Bookmark syncing.
    • YammerFox – Yammer plugin.
  • IE – Comes with Windows, barely ever use it for anything except testing.
    • Xmarks – Bookmark syncing.
    • IE7Pro – Use for Ad Blocking.
  • Google Chrome – Browser compatibilty and some productivity uses.
  • Safari – Mostly to test browser compatibility.
  • IETester – For testing browser compatibility in IE6 – IE8

Utilities:

Productivity:

  • VMWare Player – Using for virtual Kubuntu and Mac OS X desktops.
  • VMware Infrastructure Client – Using for Linux and Windows Servers.
  • PuTTY – SSH client for Windows.
  • WinSCP – Easy to use SCP client for Windows; also does SFTP and FTP.
  • Microsoft Office Professional

Unproductivity:

That’s pretty much everything that I install and use on a regular basis. There are some other small utilities, and such, that I have installed for non-business related tasks, so I didn’t include them here.

If you have any questions or comments about what I use, please ask. I’d love to know what you use on a regular basis. So if you have a blog I encourage you to do a similar write-up and let me know about it.

Alternate Title – WordPress

By michael  |  July 9th, 2009  |  Published in Development, WordPress  |  2 Comments

We’ve been working on a site where the client wanted the page title to be different on the front end and the back end. They want a longer more descriptive title on the back end. On the front end, they wanted to customize the title for their customers to see. Basically something small and simple.

Immediately I knew that using WordPress Custom Tags would work perfectly for this. So we went with the meta-tag “alt_title” for their alternate titles. On my first attempt I edited the relevant .php theme files to do this for the title:

<?php
if ($p = get_post_meta($post->ID, "alt_title", true)) {
	$title = $p;
} else {
	$title = get_the_title($post->ID);
} 
?>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title='Click to read: "<?php echo $title; ?>"'>
<?php echo $title; ?></a></h2>

However, that wasn’t quite good enough. They also wanted to be able to make an alternate name for page titles in a navigation. In their current navigation, using wp_list_pages, it was displaying the actual page title, not the alternate title. This took a little extra work, but finally, with a pretty simple piece of code. I added this function to the functions.php in their theme.


function the_alt_title($title= '') {
	$page = get_page_by_title($title);

	if ($p = get_post_meta($page->ID, "alt_title", true)) {
		$title = $p;
  	}

	return $title;
}

Now, all I need to do is apply this function to the the_title filter, with:

add_filter('the_title', 'the_alt_title', 10, 1);

But, if you remember, they want to see the original titles on the backend, so I actually needed to write it like this:

if (!is_admin()) {
	add_filter('the_title', 'the_alt_title', 10, 1);
}

I don’t know if there is much need for this functionality, but this could easily be turned into a WordPress plugin. There is still a little more work that would need to be done. But it works for our client’s needs.

As always, your questions and comments are welcome.