Tải bản đầy đủ (.pdf) (10 trang)

Hướng dẫn tạo themes cho wordpress part 19 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.08 MB, 10 trang )

Chapter 9
185
Getting started
You need to have a basic theme containing a functions.php le, and a sidebar le such as
sidebar.php created for this recipe. You also need to know where you would like to place
the listing of the most discussed authors. In this example, we will be displaying the data in
a sidebar.
How to do it
First, we need to create a custom template tag. We'll call the template tag get_most_
discussed_authors
, and have it accept a single parameter that determines the number
of results to return. Open or create your theme's functions.php le, and dene the function
as follows:
function get_most_discussed_authors($limit = 3) {
global $wpdb;
return $wpdb->get_results( $wpdb->prepare(
"SELECT COUNT({$wpdb->comments}.comment_ID) as
number_comments,
{$wpdb->users}.ID as user_ID
FROM {$wpdb->comments}, {$wpdb->users}, {$wpdb->posts}
WHERE {$wpdb->users}.ID = {$wpdb->posts}.post_author
AND {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID
GROUP BY {$wpdb->users}.ID
ORDER BY number_comments DESC
LIMIT %d", $limit));
}
Now we need to use this function to display information to visitors. Borrowing from the recipe
Listing all published authors on a site, we put the following code in one of our sidebars:
<ul>
<li>Most Discussed Authors
<ul>


<?php
$discussed = get_most_discussed_authors();
foreach($discussed as $item) {
$user_ID = $item->user_ID;
$num_comments = $item->number_comments;
$url = get_author_posts_url($user_ID);
?>
<li>
<a href="<?php echo $url; ?>">
<?php echo get_the_author_meta
('display_name',$user_ID); ?>
Showing Author Information
186
<?php printf( _n
( '%d comment', '%d comments', $num_comments ),
$num_comments ); ?>
</a>
</li>
<?php
}
?>
</ul>
</li>
</ul>
Save the le, and then upload it to the current theme folder on your server.
If you've done everything correctly, you should have an output that looks something like the
following screenshot of the sidebar:
How it works
As with the previous two recipes, we've created a template tag that basically acts as a
delegate for a raw SQL call, by using the $wpdb object that WordPress provides. In this

recipe, the get_most_discussed_authors function calls the wpdb class's get_results
method. This method returns an array of objects, including the authors, their related
posts, and the comments attached to those posts, formed from the rows returned from
a database call.
In our custom function, each item returned in the array has two properties:
user_ID and
number_comments. When iterating over the results from our call to get_most_discussed_
authors
, we use these two properties when displaying the nice list of author names and the
amount of comments that their posts have received.
See also
Listing all published authors on a site.
Chapter 9
187
Adding a custom user eld to display an
author's Twitter link
We can use the data that describes the author, their "metadata", to display a variety of
information, in most cases, the same as that retrieved by using $authordata or user_
data
, as seen in previous examples in this chapter. However, sometimes a plugin gathers
additional custom metadata such as an IM username or a Twitter name. In that situation,
applying a special template tag called the_author_metadata to an author page is
very useful.
In this example, we will create a custom user eld for the user prole page in the WordPress
control panel, and then use the Twitter metadata that it provides to display the author's Twitter
username on the author page.
Getting started
You will need an author.php le in a modern 2.9 compatible WordPress theme, and a
Twitter account (www.twitter.com).
How to do it

Open up your functions.php le and insert the following code, in order to create the
custom eld:
add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );
function my_show_extra_profile_fields( $user ) { ?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr><th><label for="twitter">Twitter</label></th>
<td>
<input type="text" name="twitter" id="twitter" value=
"<?php echo esc_attr( get_the_author_meta
( 'twitter', $user->ID ) ); ?>" class="regular-text" />
<br />
<span class="description">Twitter username</span>
</td>
</tr>
</table>
<?php }
Showing Author Information
188
Now we need to insert code into functions.php so that the data entered into the custom
eld will be saved. Enter the following code directly below the code in step 1:
//save the custom field
add_action( 'personal_options_update', 'my_save_extra_profile_fields'
);
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields'
);
function my_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;

update_usermeta( $user_id, 'twitter', $_POST['twitter'] );}
Save the functions.php le, and then upload it to your server. You can now see the custom
eld area within your author prole, and can use it. It should look like the example shown in
the screenshot below:
Next, a function to get the Twitter ID from the user prole needs to be created. Insert the
following code into functions.php:
//author box function
function my_author_box() { ?>
<div class="author-profile vcard">
<?php if ( get_the_author_meta( 'twitter' ) ) { ?>
<p class="twitter clear">
<a href=" the_author_meta
( 'twitter' ); ?>"
title="Follow <?php the_author_meta
( 'display_name' ); ?> on Twitter">
Follow <?php the_author_meta
( 'display_name' ); ?> on Twitter
</a>
</p>
<?php } // End check for twitter ?></div><?php
}
Chapter 9
189
Finally, we need to place a tag in author.php to call the my_author_box() function and
display the Follow on Twitter link:
<div id="authorinfo">
<strong>Author Email:</strong>
<a href="mailto:<?php echo antispambot($curauth->user_email);
?>">Contact Author</a>
<?php my_author_box(); ?>

</div>
Save the functions.php le and the author.php le, and then upload them to your server.
View the author page in your browser, and you should see a Follow link similar to the one
shown in the screenshot below:
How it works
First, the add_action( 'show_user_profile', 'my_show_extra_profile_
fields' );
and add_action( 'edit_user_profile', 'my_show_extra_
profile_fields' );
code was added to functions.php to allow a new custom user
eld to be created and edited as a part of the user prole form. Next, the form eld and labels
were created within the function my_show_extra_profile_fields( $user ). This
added an input box label and description to the WordPress control panel's user prole screen.
We then added code to functions.php le, in order to save any data entered into the
custom eld. We then created a function called my_author_box() that used the metadata
function get_author_meta() to retrieve data stored in the WordPress database. The
metadata function the_author_meta() displayed the display name and Twitter username
meta information retrieved from the user prole. Finally, we added a tag to author.php, in
order to call the my_author_box function and print the Follow on Twitter link on the screen.
Showing Author Information
190
There's more…
You can use the previous example to create custom elds to display other information,
including linking to podcasts, bookseller sites, and more.
Displaying an image next to the 'Follow' link
If you want to create a custom image, or use the default Twitter follow icon, you can add it to
the above code by adding a link to the image in the author box function:
function my_author_box() { ?>
<div class="author-profile vcard">
<?php if ( get_the_author_meta( 'twitter' ) ) { ?>

<p class="twitter clear">
<img src="/images/twitter-link-logo.png"alt="twitter logo"/>
<a href=" the_author_meta
( 'twitter' ); ?>" title="Follow
<?php the_author_meta( 'display_name' ); ?>
on Twitter">Follow <?php the_author_meta
( 'display_name' ); ?> on Twitter</a>
</p><?php } // End check for twitter ?>
</div><?php
}
10
Adding JavaScript
Effects
In this chapter, we will cover:
Linking to your theme's JavaScript les directly
Adding JavaScript les to your theme programmatically
Adding a bundled library to your theme programmatically
Creating a featured post slider
Making sidebar widgets toggle-able
Adding a font-size toggle
Introduction
In the last couple of years, web users have become quite a bit more sophisticated. As this
happened, many came to expect a certain level of dynamic interaction with a web page.
The dynamic element can be many things, the most popular being animating elements
and dynamic content loads.
Luckily for developers, this rise in interest in dynamic elements coincided with the maturation
of JavaScript libraries and techniques. This makes creating fun and useful interactions on your
site simpler.
To make things even easier for a WordPress developer, the WordPress package comes
bundled with many popular JavaScript libraries built-in and ready-to-use. In this chapter, we'll

look at how to use those libraries, where they live, and some interesting things that you can
do with them in the context of your theme.






Adding JavaScript Effects
192
Linking to your theme's JavaScript les
directly
The easiest way to include JavaScript functionality in your theme is to link directly to the le
from the <head> element of your theme. In this recipe, we'll examine how you determine the
URL to link to and where to, put the linking element.
Getting started
You need to have created a WordPress theme that contains at least a style.css le and an
index.php le.
How to do it
First, you're going to create a JavaScript le to link to. Open the folder that your theme lives in,
and create a new folder called js. This folder exists for the purposes of organization of your
JavaScript les.
Inside of the js folder, create a new le called my-theme.js. Open this le for editing, and
insert the following test script:
/*
* Created for test purposes.
*/
alert('This is a test.');
Now you need to link to the JavaScript le from your theme, to ensure that the script is loaded
and run. To do so, open up the theme le where your <head> element is located. This will

most likely be header.php.
Between the <head> and </head> tags, insert a new line with the following content:
<script type="text/javascript" src="<?php bloginfo('stylesheet_
directory'); ?>/js/my-theme.js"></script>
After doing this, load your WordPress site with your theme active, and you'll be greeted by a
dialog box similar to the one pictured in the screenshot below:
Chapter 10
193
How it works
There are two possible uses of an HTML script tag. The rst is to add JavaScript directly to a
page. This would look something like the following:
<script type="text/javascript">
alert('This is a test.');
</script>
In this example, the visitor's browser of choice interprets the script as it parses the page,
taking whatever action is called for. If you followed along in the example, you noticed that the
alert appeared before the rest of the page loaded in the browser, and once the visitor clicked
on OK, the alert box disappeared and the page resumed loading.
However, in most instances, it is desirable to put JavaScript that is used throughout a site in
a separate le that can be used again and again. There are many reasons for this, including
smaller overall page size, and the fact that most browsers can—and wil —cache the external
le so that it doesn't have to be fetched multiple times for a single site.
To specify an external le, we use a <script> tag without any content, and add the src
attribute to tell the browser where to nd the le. The browser reads the src attribute and
attempts to fetch and parse the le located at the specied URL.
In this particular case, the src attribute is dynamically-generated by using the bloginfo
function. As reviewed in the recipe Displaying the blog name from Chapter 1, the bloginfo
function has a variety of different parameter values that you can use to get different
information. Passing stylesheet_directory returns a URL that points to the directory
containing your theme's style.css le. The URL will often be something in the form

mysite.com/wp-content/themes/my-theme. Please note that no trailing slash is
included, so you need to include it yourself if necessary.
See also
Displaying the blog name
Adding JavaScript les to your theme
programmatically
Although you can certainly link to your JavaScript les directly (and in some cases, you may
need to, for one reason or another), the preferred method of generating script tags for your
theme is to add references programmatically. This allows for the reuse of popular scripts, and
ensures that a script is not linked to twice within the same page.

Adding JavaScript Effects
194
Getting started
You need to have created a WordPress theme that contains at least a style.css le and
an index.php le. Inside the template le containing your theme's <head> tag, you need
to call the wp_head function. If you have also completed the previous example, open up the
header.php le (or whichever le you placed the <script> tag code in) and remove the
code added in the last recipe.
How to do it
First, you must create a JavaScript le to link to. This le will reside within your theme.
Open your theme's folder and create a js folder. Inside the js folder, create a le called
my-theme.js.
Open the my-theme.js le, and insert the following JavaScript, which will produce an alert
dialog box on page load:
/*
* Created for test purposes.
*/
alert('This is an enqueue script test.');
Now, open or create your theme's functions.php le. In functions.php, add the

following code inside a PHP block:
if( !is_admin() ) {
wp_enqueue_script(
'my-theme',
get_bloginfo('stylesheet_directory') . '/js/my-theme.js'
);
}
Upload the updated my-theme.js le and functions.php le. Go to your WordPress site
with your theme enabled, and you'll be greeted with something like the following screenshot,
in your browser:

×