WordPress的10个殺手級技巧

3.用页码代替“上页”和“下页”
问题:WordPress有默认函数来显示上页和下页页面,虽然这比没有这个什么功能好,但是我不明白开发人员为什么不把页面写进核心代码呢。当然,我们可以用插件来生成页码,但是如果能把页码直接插入主题岂不更好?!
解决方案:这里使用WP-PageNavi插件把页码直接写入主题

首先下载WP-PageNavi插件
在硬盘驱动上解压插件存档,并把wp-pagenavi.php 和 wp-pagenavi.css文件上传到主题目录
打开要放置页码的文件(如index.php, categories.php, search.php,等),找到以下代码:
<div class=”navigation”>
<div class=”alignleft”><?php next_posts_link(‘Previous entries’) ?></div>
<div class=”alignright”><?php previous_posts_link(‘Next entries’) ?></div>
</div>
用以下代码代替以上内容:
<?php
include(‘wp-pagenavi.php’);
if(function_exists(‘wp_pagenavi’)) { wp_pagenavi(); }
?>
接着请修改插件文件。打开wp-pagenavi.php文件并找到以下代码(61行):
function wp_pagenavi($before = ”, $after = ”) {
global $wpdb, $wp_query;
修改成:
function wp_pagenavi($before = ”, $after = ”) {
global $wpdb, $wp_query;
pagenavi_init(); //Calling the pagenavi_init() function
最后,我们要把wp-pagenavi样式表添加到博客。
打开header.php 文件,把以下代码添加进去:
<linkrel=”stylesheet”href=”<?phpechoTEMPLATEPATH.’/pagenavi.css’;?>”type=”text/css”media=”screen”/>
代码说明:这个代码改进直接在主题文件中加入添加了插件代码。我们另外还调用了pagenavi_init()函数以使页码能够正常显示。

4.自动获取文章图像
问题:使用自定义字段来显示和日志相关的图像固然很好,但是许多用户想直接检索并使用文章本身嵌入的图像。

解决方案: 至今为止,还没有这样的插件。值得庆幸的是,以下循环将帮我们解决这一问题:它会搜索文章内容的图像并把它们显示出来

把以下代码粘贴到主题文件任意位置:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php
$szPostContent = $post->post_content;
$szSearchPattern = ‘~<img [^>]* />~’;
// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);
if ( $iNumberOfPics > 0 ) {
// Now here you would do whatever you need to do with the images
// For this example the images are just displayed
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
echo $aPics[0][$i];
};
};
endwhile;
endif;
?>
代码说明:以上代码实际上包含了一个WordPress循环。使用PHP和正则表达式的唯一区别就是前者会自动搜索文章内容中的图像而不是仅仅显示文章。一旦发现图像,系统就会显示。

5.创建“发送到Twitter”按钮
问题:你是Twitter用户吗?如果是,相信你一定了解和朋友在线分享有趣内容的乐趣。那么,为什么不给你的读者也提供一个机会,让他们可以直接把你的文章URL发送到Twitter以给你带来更多流量呢?

解决方案:这个代码改进非常简单。只要创建一个带有status参数的Twitter链接就可以了。而对于WordPress,直接使用the_permalink()函数就可获取文章URL了:
<a href=”http://twitter.com/home?status=Currentlyreading<?php the_permalink(); ?>” title=”ClicktosendthispagetoTwitter!” target=”_blank”>ShareonTwitter</a>
非常简单,对吧?但它同时也非常实用!

6. 使用直引号,避免弯引号
问题:如果你经常在自己的网站上发布代码片段的话,可能会经常碰上这类问题:某用户会说你发布的代码不起作用。这是为什么呢?WordPress默认情况下会将直引号转为“smart引号,”而后者会截断代码片段。

解决方案:要避免出现这些弯引号,请按以下操作:

打开主题中的functions.php文件。如果不存在该文件的话,请自行创建一个。
粘贴进如下代码:
<?php remove_filter(‘the_content’, ‘wptexturize’); ?>
保存文件。大功告成!
代码说明:wptexturize()函数会自动将直引号转为smart引号。而通过使用remove_filter()函数,我们会告知WordPress不要对日志内容使用wptexturize()函数,问题自然得到解决。

Leave a Reply

Your email address will not be published. Required fields are marked *