1. Trang chủ
  2. » Công Nghệ Thông Tin

Tìm Hiểu về Wordpress - part 13 pdf

10 353 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 1,41 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

A simple function like this will display linked titles to recent posts: 4.4.4.. If you want to accommodate all the above, try the WordPress Popular Posts plugin, which is available at

Trang 1

<a href="<?php echo get_permalink(

$comment->comment_post_ID ) '#comment-' $comment->comment_ID; ?>">< ?php echo

dp_get_author($comment); ?>:</a>

< ?php echo strip_tags(substr(apply_filters('get_

comment_text', $comment->comment_content), 0, $comment_len)); ?>

</li>

ob_end_flush();

}

} else {

echo '<li>No Comments</li>';

}

}

function dp_get_author($comment) {

$author = "";

if ( empty($comment->comment_author) )

$author = 'Anonymous';

else

$author = $comment->comment_author;

return $author;

} ?>

To use this function, simply call it from anywhere in your theme:

<?php dp_recent_comments(6); ?>

4.4.3 Displaying Recent Posts

Lets do this again from easiest to hardest

• Widget - The easiest possible way to do this is through a widgetized sidebar

Trang 2

Just like recent comments, there is a built-in “Recent Posts” widget which will

do the trick Just drag it into your sidebar zone and save it

• Function - We don’t have to write a custom function this time, we can just

use the wp_get_archives function, which we already looked at a little A simple function like this will display linked titles to recent posts:

<?php wp_get_archives('type=postbypost&limit=5');

• Custom Loop - Finally we could go totally home-brew and just write a custom

loop to display recent posts This offers by far the most control as we can do anything inside this loop, including accessing the full content or custom fields

<?php query_posts("posts_per_page=10&what_to_show=posts&orderby=date");

if (have_posts()) : while (have_posts()) : the_post();

// output custom stuff here! Post title, content, custom fields endwhile; else:

// message if nothing found endif;

wp_reset_query();

?>

4.4.4 Listing Popular Posts Popularity is more loosely defined than something like “recent.” How do you define popularity? Page views? Number of comments? Back links? If you want

to accommodate all the above, try the WordPress Popular Posts plugin, which is

available at http://digwp.com/u/117 This plugin logs relevant data and then makes outputting a list of popular posts as

Resetting

The query string is set when

any page in WordPress is

loaded You can override it by

doing you own query_posts,

but then that original query

string is destroyed You can

restore it with this:

wp_reset_query();

Trang 3

<?php if (function_exists('get_mostpopular')) get_mostpopular(); ?>

If you wanted to gauge popularity only based on the number of comments, you

could achieve this with your own database query (thanks to the Bin Blog for the

idea – http://digwp.com/u/118 ):

<ul class="popular-posts">

<?php $popular_posts = $wpdb->get_results("SELECT id,post_title FROM

{$wpdb->prefix}posts ORDER BY comment_count DESC LIMIT 0,10");

foreach($popular_posts as $post) {

print "<li><a href='" get_permalink($post->id) "'>".

$post->post_title."</a></li>\n";

} ?>

</ul>

4.4.5 Listing Recently Modified Posts

You might think we’d have to go database fishing or use a plugin for this We

certainly could, but the query_posts function supports an orderby parameter which

can get the job done for us easily:

<?php query_posts("posts_per_page=5&what_to_show=posts&orderby=modified");

if (have_posts()) : while (have_posts()) : the_post();

// output custom stuff here! Post title, content, custom fields

endwhile; else:

// message if nothing found

endif;

wp_reset_query(); ?>

Function exists?

Before using a function that was created via a plugin,

it is best practice to use the function_exists() function before calling it If the function doesn’t exist (i.e., the plugin isn’t installed or is deactivated), the function won’t

be called That is far better than calling a nonexistent function since PHP will halt rendering and will likely destroy your theme.

Trang 4

4.4.6 Listing Random Posts Again the query_posts function has our back, allowing the orderby parameter to accept “rand" to display a series of random posts:

<?php query_posts("posts_per_page=3&what_to_show=posts&orderby=rand");

if (have_posts()) : while (have_posts()) : the_post();

// output custom stuff here! Post title, content, custom fields

endwhile; else:

// message if nothing found endif;

wp_reset_query(); ?>

4.4.7 Import and Display Twitter Integrating your recent tweets from Twitter can be a fun way to communicate with your web visitors and keep content on your site fresh Twitter has a robust API system for getting at and using that data But Twitter is not an infallible service, and in fact, slowness and downtime is a pretty common occurrence for them

Because of this, when using their API to get stuff and display it on your own pages,

it should be done in such a way that won’t affect the loading of the page, and won’t look awful in the case of API failure

This Twitter API communication can be done entirely through JavaScript, which is our preferred and recommended way for a few reasons:

• Connection to the Twitter API happens on the client side and keeps server load down

• If done right, doesn’t affect page load time

• Data can be processed and appended to the page only upon success

With Ajax

A neat idea with this technique

is to make a page template

that displays just one post and

nothing else Then use Ajax to

call that URL and display it

(for example, in the sidebar)

We cover (and use) this

technique on the Digging Into

WordPress website, including

a “Get Another!” button:

http://digwp.com/u/411

Trang 5

So let’s get it done We are using jQuery in this book

(because it’s awesome) so let’s keep going down

that route

Step 1: Enqueue jQuery

Put this PHP code into your functions.php file

This will load the jQuery library onto your page by

inserting a link in the <head> section where you call

the wp_head function

if(!is_admin()) {

wp_deregister_script('jquery');

wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/

jquery/1.3.2/jquery.min.js"), false, '1.3.2');

wp_enqueue_script('jquery');

}

Step 2: Load your custom script

You’ll need to load a JavaScript file for this, so if you have one already going for

your site, you can use that, otherwise load in a new one

<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/

twitter.js"></script>

Step 3: The jQuery plugin

Next, we want to create a jQuery plugin:

(function($){

$.fn.lastTwitterMessage = function(username){

In the footer of CSS-Tricks,

a speech bubble is displayed above Chris showing his latest tweet With this jQuery method, should the Twitter service be unavailable, the speech bubble just doesn’t show.

Trang 6

var $base = this;

if(!username || username == "") return this; // username required var url = "http://twitter.com/statuses/user_timeline.json?callback=?"; $.getJSON( url, { count: 10, screen_name: username },

function(data){

if(data && data.length >= 1){

try{

var item = null;

for(var i = 0; i < data.length; i++){

if(/^@/i.test(data[i].text)) continue;

item = data[i]; break;

} if(!item) return;

var $tweet = $("<p></p> ").text(item.text);

$tweet.html(

$tweet.html() .replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+) (:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>') .replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/ search?q=%23$2">#$2</a>')

replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.

com/$2">@$2</a>') )

$tweet.append(" &nbsp;<a href='http://twitter.com/" + username +

"'>(&#8734;)</a>&nbsp; ").wrapInner("<span>");

$base.empty().append($tweet).show();

Trang 7

};

});

return this; // Don't break the chain

};

})(jQuery);

That plugin, when we call it, does all the heavy lifting of communicating with

Twitter and pulling the latest tweet It even does fancy stuff like turning URLs into

real links, hash tags into search links, and @replies into profile links

Step 4: Calling the plugin

You could load in another JavaScript file just for this, or just append this beneath

the code you just added We need a DOM-ready statement and then create an

element to load the plugin on

$(function() {

$("<div id='tweet'></div>").hide().appendTo("#footer")

.lastTwitterMessage('chriscoyier');

});

That code is the magic It waits for the page to be ready to be manipulated

(DOM-ready), creates a new (hidden) element, appends it to the page (into the footer),

and then calls the plugin on it Should the plugin be successful in its duty, the new

element will show up on the page, if not, it will remain hidden

4.4.8 Import and Display Delicious

There is, unsurprisingly, a number of ways to get this done Delicious has APIs we

could wrangle with (JSON or XML) Delicious serves up RSS feeds we could parse

(see the next section) Delicious has JavaScript widgets that we could harness –

Trang 8

http://digwp.com/u/228 There are also quite a number of plugins for WordPress that specially deal with Delicious – http://digwp.com/u/229

There is one technique that stands out above the rest though, and that is a plugin which imports data from your Delicious account and creates Posts from it It’s

called Postalicious – http://digwp.com/u/230 It’s been a few years since it has been updated but it still works swimmingly with the current version of WordPress Postalicious is able to check Delicious every hour and pull in new links You can set

it to create drafts (recommended) or auto-publish posts Simply choose a category, and Postalicious will automatically create the posts, the title, and all of the HTML formatting!

It should be noted that Delicious actually has some built-in (albeit rather hidden) functionality right in the web app for communicating with a WordPress blog It isn’t very user-friendly and is difficult to customize, so we don’t recommend it

4.4.9 Import and Display Other Content

An interesting fact about WordPress that you may not know is that it includes a built-in RSS feed parser This makes the job of fetching recent content from other sites for display on your own pretty darn easy You’ll need to include the feed.php

file that ships with WordPress on any page you want to do feed parsing, but after that you are free to set up new SimplePie objects and do all the feed parsin’ you desire! Check it out:

<h2>Recent News from Digging Into WordPress</h2>

<?php // Get RSS Feed(s) include_once(ABSPATH WPINC '/feed.php');

// Get a SimplePie feed object from the specified feed source.

$rss = fetch_feed('http://digwp.com/feed/');

Wha?

What the heck is Delicious

you ask? Delicious is a very

popular social bookmarking

site You save links with

annotation to your account

online (so you’ll never lose

them) And because others do

the same, Delicious is able

to know and share what are

the most popular links going

around at any

given moment.

http://delicious.com

Trang 9

// 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);

?>

<ul>

<?php if ($maxitems == 0) echo '<li>No items.</li>';

else

// Loop through each feed item and display each item as a hyperlink.

foreach ( $rss_items as $item ) : ?>

<li>

<a href='<?php echo $item->get_permalink(); ?>' title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>

<?php echo $item->get_title(); ?></a>

</li>

<?php endforeach; ?>

</ul>

SimplePie is a very robust feed parser, so you are in no way bound by the code

above for what you are able to accomplish For a complete list of functions, check

out the SimplePie wiki at http://digwp.com/u/140, but to get the juices flowing, here

are some examples

At the “feed level” (outside the feed loop), get the title, description, and

permalink of the feed:

Quick Backstory

WordPress used to use MagpieRSS to do its feed- parsing The project was discontinued and one of its competitors SimplePie was gaining traction in a big way WordPress switched over to SimplePie, and now SimplePie development has ended.

Someone may pick up SimplePie and run with it, but it seems like inclusion into WordPress is the kiss of death for any feed parser.

Trang 10

• get_title()

• get_description()

• get_author()

At the “item level” (inside the feed loop), get the date, content, and link:

• get_date()

• get_content()

• get_link()

The SimplePie Plugin http://digwp.com/u/141

SimplePie has a plugin for WordPress as well It was probably more useful back when WordPress didn’t ship with SimplePie, but the user-friendliness of it still makes it a pretty cool plugin Once installed and activated, you can spit out external content as easy as calling the plugin function:

<?php echo SimplePieWP('http://digwp.org', array(

'items' => 5, 'cache_duration' => 1800, 'date_format' => 'j M Y, g:i a' ));

?>

Notice that the URL parameter isn’t a feed but rather just a regular website SimplePie is cool like that, with automatic feed detection The plugin uses

“themes” to then output the content it finds It ships with a number of themes, which you can select and modify through the admin itself Anything you can do with SimplePie you can do with this plugin as well, the big advantage being the

Importing Feeds

For an in-depth article

explaining everything you need

to know about importing and

displaying feeds in WordPress,

check out this post from

Perishable Press:

http://digwp.com/u/405

Ngày đăng: 04/07/2014, 21:20

w