Posts Tagged ‘WordPress’

Tip: Exclude Categories From Archive In WordPress

August 20th, 2009

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.

Adding Facebook Connect to your WordPress Blog

August 9th, 2009

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!

Include WordPress Author Biographical Info In Posts

July 29th, 2009

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.

Guest Posts And the_author() In Your WordPress Blog

August 18th, 2008

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).

WordPress, My Gravatar and the Mystery Man

August 9th, 2008
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…

Desktop Blogging Tools Reviewed

August 2nd, 2008

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

Wordpress Themes and the functions.php file

July 30th, 2008

Loads of good free WordPress Themes are out there. And the most of them don’t make use (or at least no good use) of the ‘functions.php‘ file. This is how the WordPress Codex describes the file:

A theme can optionally use a functions file, which resides in the theme subdirectory and is named functions.php. This file basically acts like a plugin, and if it is present in the theme you are using, it is automatically loaded during WordPress initialization (both for admin pages and external pages). Suggested uses for this file:

* Define functions used in several template files of your theme
* Set up an admin screen, giving users options for colors, styles, and other aspects of your theme

The “Default” WordPress theme contains a functions.php file that defines functions and an admin screen, so you might want to use it as a model. Since functions.php basically functions as a plugin, the Function_Reference list is the best place to go for more information on what you can do with this file.

Ok, there’s a load stuff you can read into about the WordPress functions, but not much is written about this mysterious file or exactly how to use it. Here’s some info:

Open the functions.php file in your theme folder (create the file if it’s not there). Add a function to it between <?php and ?> :

1
2
3
4
// Function example. Returns the actual date
function show_date() {
    echo date('Y-m-d');
}

To use the function in your theme, place this code somewhere (i.e. page.php) inside :

1
<?php show_date(); ?>

The date should be shown on your page where you inserted the code. Pretty easy, huh. More? Read on…

Including stuff in the template header

For my part I always need to load some stuff in the header, sometimes under certain conditions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (! is_admin() ) { // If we are not in the admin, load stuff
    add_action('init', 'load_my_script'); // on initialization, execute the function load_my_scripts
    add_action('wp_head', 'load_my_css');
}
 
function load_my_script() {
    // load myscript.js version 1.0, which is dependent on 'jquery' and refer to it as 'MyScript'
    wp_enqueue_script('MyScript', get_template_directory_uri().'/js/myscript.js', array('jquery'), '1.0');
}
 
function load_my_css() {
    // load myscript.js version 1.0, which is dependent on 'jquery' and refer to it as 'MyScript'
    echo '<link rel="stylesheet" href="' . bloginfo('template_url') . '/css/style.css" type="text/css" media="screen" />'."\n";
}

You can check for certain conditions i.e. is_page(), is_home() and so on and add stuff to the header respectively. It makes more sense and saves you bandwidth if you load your JavaScript library which checks the contact form fields for errors only on the page on which the form appears.

Adding custom stuff

Personally I don’t like it when I work on a theme and while testing the theme locally, it needs to load stuff from the internet like the Google analytics code, sponsor banners and other things. I like it quick. The following code is a simple solution. If the page loads local, don’t load external stuff, if it’s on the server in the internet, then load everything. Sometimes, this speeds up things drastically.

In the functions.php add:

1
2
3
4
5
6
7
// Function to stop external things from being loaded while on localhost
function is_local() {
  $is_devbox = false;
  $this_host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
  $this_host == 'localhost' ? $is_devbox = true : $is_devbox = false;
  return $is_devbox;
}

and in the template add:

1
2
3
4
5
6
7
<?php if(! isLocal() ) { ?>
 
// Add all your stuff here you don't want to load while on localhost i.e.
// your google analytics code.
 
 
<?php } ?>

Query the WordPress Database

There’s a widget for the recent posts. What if we don’t want to use widgets in our sidebar? We create the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function get_recent_posts($number) {
// code taken and stripped from wp-includes/widgets.php
if ( !$number || $number <= 5 )
	$number = 5;
else if ( $number < 1 )
	$number = 1;
else if ( $number > 15 )
	$number = 15;
else
	$number = $number;
 
$q = new WP_Query(array('showposts' => $number, 'what_to_show' => 'posts', 'post_status' => 'publish'));
if ($q->have_posts()) :
?>
<ul>
<?php  while ($r->have_posts()) : $r->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?> </a></li>
<?php endwhile; ?>
</ul>
<?php
wp_reset_query();  // Restore global post data stomped by the_post().
endif;
}

Place the following code in the template where you want to show the links to your latest posts:

1
<?php get_recent_posts(8); // latest 8 posts ?>

Or you could include a RSS Feed:

1
2
3
4
5
6
7
8
9
// Retrieving a RSS feed
function getRSS($uri) {
// http://codex.wordpress.org/Function_Reference/get_rss
$xAbspath = str_replace("\\","/",ABSPATH);  // Win/XAMPP compatibility
require_once($xAbspath.'/wp-includes/rss-functions.php');
echo '<ul>';
get_rss($uri);
echo '</ul>';
}

And on your page:

1
<?php getRSS('http://www.flowdrops.com/feed') ?>

There’s really a lot of functionality you can add to your WordPress theme just by adding php functions to the functions.php file. A good start is the functions.php in the ‘default’ theme folder. It shows also how you can add a theme admin page. Go, modify your theme and add some functionality. But keep in mind: less is often more.