Re-numbering With jQuery

August 20th, 2009 by Pete No comments »

I needed this to do a quick re-numbering of featured items in a slider on the homepage because I was always changing the PHP code and the numbering got messed up.

Code to do a quick re-numbering of ‘a span’ items in a unordered list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
jQuery(document).ready(function()
{
    renumber_featured_nav();
});
 
function renumber_featured_nav()
{
    var ftabscount = 1;
    jQuery("li.ftab a span").each(function()
    {
        jQuery(this).html(ftabscount);
        ftabscount++;
    });
}
Advertisement
Download 1000's of web templates. Unlimited access!

Tip: Exclude Categories From Archive In WordPress

August 20th, 2009 by Pete 3 comments »

While working on a recent project, I came across a task: exclude certain categories from the archive page. I went the usual way to the WordPress codex -> query_posts and thought the following would do it:

1
2
3
4
5
6
7
8
9
10
# Exclude categories | archive.php
if ( is_home() || is_category('one') || is_category('two') )
{
    $current_cat = get_query_var( 'cat' );
    $exclude_cat = 3;
    $current_page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    query_posts("cat=$current_cat,-$exclude_cat&paged=$current_page");
}
//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();

This, unfortunately, didn’t work. I then thought of filtering via custom queries. The problem with custom queries is that the filter is applied to each and every query on the page. If you do:

1
2
3
4
5
6
7
8
9
10
# Exclude categories | functions.php
function fd_remove_cat( $nada )
{
  global $wp_query;
  if ( is_home() || is_category('one') || is_category('two') )
  {
     $wp_query->query_vars['cat'] = '-3';
  }
}
add_action('pre_get_posts', 'fd_remove_cat' );

this will work, but it affects all other queries on the page as well. If you have some custom ‘query_posts’ in your theme, category 3 will be stripped out of all queries on the page.

I came up with this solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Exclude categories | archive.php
if ( is_category('one') || is_category('two') )
{
    global $wpdb;
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    query_posts(
        array_merge(
            array
            (
                'category__in' => array($cat),
                'category__not_in' => array(3,4),
                'paged' => $paged
            ), $wp_query->query
        )
    );
}
//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();

The above code preserves the original query and adds/alter defined query variables (also see query_posts, ‘Preserving the Original Query’).

I hope this post keeps you from wasting time while trying to alter the wp_query.

Advertisement
Download 1000's of web templates. Unlimited access!

Adding Facebook Connect to your WordPress Blog

August 9th, 2009 by Pete No comments »

Today I added ‘Facebook Connect‘ to my blog and I was running into two or three caveats. I want to share my trial-and-error experience from today with you.

First, I downloaded the WP-FBConnect plugin, installed & activated it in the wp-admin. After reading myself trough the Wiki and Adam Breckler’s tutorial I was ready to set up the required Facebook Application.

Having entered only the minimal required information to get the WP-FBConnect plugin up and running, I tried to login to my site with my Facebook account. It worked fine and I was able to post a comment.

After that I wanted to do some customizations and here’s where the problems started:

  • Infinite redirect loop when trying to log out
    Reason: http://forum.developers.facebook.com/viewtopic.php?id=32640
    Solution: Clear all your browser cookies (or at least all cookies from the affected domain). Don’t use the ‘base domain’ field in the Facebook Application settings.
  • Logged in as “Facebook User”, Username is not displaying correctly
    Reason: http://wordpress.org/support/topic/234687 (first post from ahupp). You may also want to read this post.
  • Facebook users have access to wp-admin
    This was the biggest issue as I really don’t want to expose anything from the WP back-end to ‘Subscribers’. My solution is simple: add the following code to your themes ‘functions.php’:
1
2
3
4
5
6
7
# Disable access to wp-admin for Facebook users
if ( is_admin() ) {
    global $current_user;
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    if ( !is_null($user_info->fbuid) ) die( 'No access for Facebook users!' );
}

If you want to change the appearance of the FB login button, you can do so by updating the code at line 99 of ‘common.php’ according to the attributes described here.

If you run into more issues with the plugin, please read the section ‘Troubleshooting / FAQ’ outlined in this document.

Happy Facebook-Connecting!

Advertisement
Download 1000's of web templates. Unlimited access!

Include WordPress Author Biographical Info In Posts

July 29th, 2009 by Pete No comments »

In addition to this and this post, I thought this post may be useful for you as well. It describes how you can add the ‘Biographical Info’ to your posts.

Advertisement
Download 1000's of web templates. Unlimited access!

Dynamic form elements & the jQuery validation plugin

April 15th, 2009 by Pete 6 comments »

I recently run into a problem where I had to validate a form with dynamic fields. I am impressed of the jQuery Validation plugin but I had no clue on how to achieve this as the documentation does not have any code on this included. A few searches on in the WWW didn’t bring the right results, but I eventually found some snippet in the Google Groups (I forgot where, sorry).

Now, let’s say you have a form with a few elements and depending on their selection or values one or more fields are added to the form:

View a basic sample/demo form here

Since you cannot validate a hidden element (because the user can’t make a selection or enter anything), you cannot add validation rules. You need to add/remove this rules dynamic depending on the user’s input.

Actually, the code is very simple. All you have to do is to catch the ‘change’, ‘blur’ or whatever event from the ‘other’ element and attach a simple function to add the validation rule. To go with the demo form this is it:

jQuery( jQuery("input[name='howhelp']") ).change( function()
{
  if ( jQuery("input[name='howhelp']:checked" ).val() == "help" )
  {
    jQuery("#whathelp").rules("add", "required");
    jQuery("#problems").show();
  }
  else
  {
    jQuery("#whathelp").rules("remove", "required");
    jQuery("#problems").hide();
  }
});

Simple. Let’s see what the code does line for line:

  • line 1 tells to fire a function if the radiobuttons status have changed
  • line 3 checks if the current selected radiobutton’s value is equal to ‘help’
  • line 5 adds the validation rule to the hidden select ‘whathelp’
  • line 6 shows the hidden select
  • the rest removes the validation rule and hides the select, in this case the value was not equal to ‘help’

With this code, you can validate pretty much any complex form with the validate plugin.

Further reading:

I’d like to know how you validate complex dynamic forms, so please leave your comments here.

Advertisement
Download 1000's of web templates. Unlimited access!

iF AJAX Comments For WordPress: Latest Beta Version

December 7th, 2008 by Pete 21 comments »

For those who can’t wait or want to test the upcoming version, here’s the latest beta. Tested in WP 2.7 RC1 with the default theme.

Known issues

  • The new comment threading function in WP 2.7 is not yet supported (the comment is added at the wrong location)

Download

iF AJAX Comments For WordPress 0.99.5b

Have fun!

Advertisement
Download 1000's of web templates. Unlimited access!

Guest Posts And the_author() In Your WordPress Blog

August 18th, 2008 by Pete 14 comments »

As you may have seen I have a guest post on this blog written by Matt from phuketvogue.com. Since I am the only registered writer/author on this site, all posts are marked as ‘written by Toxane’ or something similar. I thought it would be just fair for the guest writer, to mark these posts with the corresponding author name and a link back to the author’s site.

What I didn’t want was to have the guest authors as registered WordPress users on my blog, just to keep things simple (and save). I came up with the following solution:

In my theme folder I have my ‘functions.php’ file and I added the following code to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Guest Posts
function theAuthor()
{
	$guestName = get_post_custom_values("guestName");
	$guestLink = get_post_custom_values("guestLink");
 
	if ($guestName)
	{
		if ($guestLink)
		{
			echo '<a href="'.$guestLink[0].'" target="_blank">'.$guestName[0].'</a>';
		}
		else
		{
			echo $guestName[0];
		}
	}
	else
	{
		the_author();
	}
}

The code checks if the post has a custom field ‘guestName’. If the field is found, the code further checks if there’s a custom field ‘guestLink’. If that field is found as well, the code returns the name of the guest author as a hyperlink back to the guest authors website. If there’s no ‘guestLink’, only the guest author’s name is returned. If both custom fields are missing, the code returns ‘the_author()’ which is the registered WordPress user.

Next I replaced all occurences of ‘the_author()’ in the theme files with ‘theAuthor()’

To mark any post in your WordPress Blog as a guest post, you just add a custom field ‘guestName’ and the name of the guest author as value. If you want the guest author’s name appears as a hyperlink, just add a custom field ‘guestLink’ and the web address of the guest author as value.

That’s it. Simple and fair for your guest author(s).

Advertisement
Download 1000's of web templates. Unlimited access!

WordPress, My Gravatar and the Mystery Man

August 9th, 2008 by Pete 2 comments »
Mystery Man - the default Gravatar

Mystery Man - the default Gravatar

I just had a problem with my own gravatar not showing up on my own site for the comments I wrote. First I thought that clearing the browser cache would solve everything. I was wrong. After clearing the cache, deleting cookies and checking my gravatar (http://en.gravatar.com/site/check/), I was really out of (quick) ideas. Then it suddenly hit me: a few days ago I changed a few things in my Blog’s user accounts. I added new accounts with different user rights and merged the old accounts with the new ones.

After having a look at WordPress’s gravatar code (wp-includes/pluggable.php), everything was clear: WordPress actually pulls the user id and gets the email address which is stored in the user account data for this id. This ensures that if a user changes the email address in the user account, it will always pull the new gravatar associated with the new email address. The user id – for registered users – is stored in the comments table for each and every comment.

That said, if you change user accounts and a user id changes, you need to run

UPDATE wp_comments SET user_id = new_user_id WHERE user_id = old_user_id

otherwise you’re going to have a lot comments from the mystery man…

Advertisement
Download 1000's of web templates. Unlimited access!

PayPal donation form with CSS and jQuery for WordPress

August 3rd, 2008 by Pete 38 comments »

Yesterday I got an email from Jamie asking me how I made my PayPal donation form. Here’s how I did it.

First, we need a PayPal form with the donation stuff inside:

1
2
3
4
5
6
7
8
9
10
11
12
<form id="form_paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
  <input type="hidden" name="cmd" value="_donations">
  <input type="hidden" name="business" value="paypal@email.com">
  <input type="hidden" name="item_name" value="My Donations Subject">
  <input type="hidden" name="no_shipping" value="0">
  <input type="hidden" name="no_note" value="1">
  <input type="hidden" name="currency_code" value="USD">
  <input type="hidden" name="tax" value="0">
  <input type="hidden" name="bn" value="PP-DonationsBF">
  <label for="">Amount (US$) : </label><input type="text" name="amount" id="input_amount" width="10" class="text" />
  <input type="submit" name="submit" value="Donate" class="submit" />
</form>

More information about the PayPal donation buttons and the form code behind can be found here: https://www.paypal.com/cgi-bin/webscr?cmd=_pdn_donate_techview_outside

Next, we need to add some more code to the form where we want to show the various messages displayed by jQuery. These messages are set to be hidden (display:none;):

1
2
3
4
<input type="submit" name="submit" value="Donate" class="submit" />&nbsp;&nbsp;
<span id="msg_moreamount" class="icon_warning red" style="display:none;">PayPal takes $0.35 commission for a $1 donation. Please enter at least $1.35 , thank you!</span>
<span id="msg_noamount" class="icon_warning red" style="display:none;">Please enter the amount you wish to donate and try again.</span>
<span id="msg_activity" style="display:none;"> <img src="images/loader.gif" align="absmiddle" />&nbsp;Transferring to PayPal, please wait...</span>

The jQuery script which actually checks and validates the form looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
jQuery(document).ready(function()
{
	// the minimum required value to be entered.
	// in this case PayPal takes $0.35 from a $1
	// donation, hence we ask for at least $1.35
	var minimum_value = 1.35;
 
	// attach this script to the form's submit action
	jQuery('#form_paypal').submit(function()
	{
		// check if there is an amount entered
		if (jQuery('#input_amount').val() > null)
		{
			// is the amount equal to or higher than the minimum_value?
			if (jQuery('#input_amount').val() < minimum_value)
			{
				// need more amount
				// hide messages, show more amount error
				jQuery('#msg_noamount').hide();
				jQuery('#msg_moreamount').fadeIn();
				return false; // prevent the form from submitting
			}
			else
			{
				// amount is more than minimum_value
				// hide messages, show activity
				jQuery('#msg_moreamount').hide();
				jQuery('#msg_noamount').hide();
				jQuery('#msg_activity').fadeIn();
				return true; // submit the form
			}
		}
		else
		{
			// no amount entered at all
			// hide messages, show no amount error
			jQuery('#msg_moreamount').hide();
			jQuery('#msg_noamount').fadeIn();
			return false; // prevent the form from submitting
		}
	});
});

The code is documented so it should be clear what each block does.

The final step is to add some CSS styling:

1
2
3
4
5
.red {color:#ff0000;}
.icon_warning {background:transparent url(../images/exclamation.png) left no-repeat;padding:4px;padding-left:20px;}
form#form_paypal input {padding:3px;border:1px solid #ddd;background:#fefefe;}
form#form_paypal input#input_amount {width:50px;}
form#form_paypal .submit {cursor:pointer;border-style:outset;}

If you want to integrate this form into your WordPress Blog then this is the way to go:

In your WordPress Theme folder (wp-content/themes/yourtheme/) create a new file named ‘donate.php’. To make the file available as a WordPress page template you’ll need to add the following code at the top of the file:

1
2
3
4
5
<?php
/*
Template Name: Donate
*/
?>

A donation form template for the default theme would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
/*
Template Name: Donate
*/
?>
<?php get_header(); ?>
<div id="content" class="narrowcolumn">
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <div class="post" id="post-<?php the_ID(); ?>">
    <h2>Make A Donation</h2>
    <p>If you think you have benefited or I have helped you in some way, by using any of my 
    WordPress plugins or themes, please consider making a donation. Donations support the 
    continued development of my websites and help cover the hosting costs. 
    Donations of any size are gratefully accepted. Thank you!</p>
    <form id="ppDonate" action="https://www.paypal.com/cgi-bin/webscr" method="post">
      <input type="hidden" name="cmd" value="_donations">
      <input type="hidden" name="business" value="paypal@email.com">
      <input type="hidden" name="item_name" value="My Donations Subject">
      <input type="hidden" name="no_shipping" value="0">
      <input type="hidden" name="no_note" value="1">
      <input type="hidden" name="currency_code" value="USD">
      <input type="hidden" name="tax" value="0">
      <input type="hidden" name="bn" value="PP-DonationsBF">
      <label for="">Amount (US$) : </label>
      <input type="text" name="amount" id="ppAmount" width="10" class="text" />
      <input type="submit" name="submit" value="Donate" class="submit" />
      <span id="moreAmount" class="warningIcon red" style="display:none;">PayPal takes $0.35 commission for $1 donation. 
      Please enter at least $1.35 , thank you!</span>
      <span id="noAmount" class="warningIcon red" style="display:none;">Please enter an amount to donate and try again.</span>
      <span id="ppGo" style="display:none;">
      <img src="&lt;?php bloginfo('template_url'); ?&gt;/images/loader.gif" align="absmiddle" />Transferring to PayPal, please wait...</span>
    </form>
    <p><small>Info : once you click on 'Donate', you will be transferred to PayPal where you can enter your payment information.</small></p>
  </div>
  <?php endwhile; endif; ?>
  <?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Next you need to create a page in WordPress, call it ‘Donate’, ‘Make A Donation’ or whatever you want the page title to be. You can leave the page content empty as we will use our template file. Scroll down to the ‘Page Template’ section and select your page template (‘Donate’ in our case). Save & publish the page.

Available Files

 

Hopefully this short tutorial will be of some use for you (if so, don’t forget to donate ;) ) and if you still have some questions feel free to leave a comment below.

Received Donations

Thank You!

 

Advertisement
Download 1000's of web templates. Unlimited access!

Desktop Blogging Tools Reviewed

August 2nd, 2008 by Pete No comments »

Just a quick post to let you know that Glen over at Smashing Magazine has written a cool review of 15 desktop blogging tools.

Advertisement
Download 1000's of web templates. Unlimited access!