Category Archives: Wordpress Theme & Plugin

烦人的wordpress自动半角转全角符号问题

WordPress半角引号自动转换为全角引号问题:

一、通过修改主题functions.php实现:

在主题functions.php文件中加入以下代码:

/*禁用半角引号自动转换为全角引号*/
remove_filter('the_content','wptexturize');

二、通过修改WP源文件实现:
注释掉 wp-includes\formatting.php文件的下列两行代码即可

$curl = str_replace($static_characters, $static_replacements, $curl);
$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
不过两种方法都试了,但是没有用两个--连在一块仍然会被显示为一个-

PS:或者给需要保留半角的段落加上code标签也可以。

WordPress直接获取数据库blogs列表

利用前一篇单行滚动的js效果,在Wordpress首页滚动最新的几篇Blog的标题链接。首先要解决如果获取最新的5条新闻标题以及permalink的问题:

<h3 class="widget-title">Blog Lists</h3>
<ul>
<?php $bloglists = $wpdb->get_results('select * from wp_posts where post_type = "post" and post_status="publish" order by ID DESC limit 0,5');
if ( $bloglists ){
foreach( $bloglists as $post ){
setup_postdata( $post );
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
}
}
?>
</ul>

上面的代码能够获得标题以及permalink的列表。

参考:http://codex.wordpress.org/Function_Reference/wpdb_Class#SELECT_a_Column

升级WordPress至3.3

今天登录Blog发现有提醒要升级至Wordpress3.3,然后就点击自动升级了。不过升级一半报错”quicktag.js”无法安装,想起来前几天为了删除添加blockquote的时候自动生成的前后两个换行符就手工修改了quicktag.js,估计是因为用的是root权限修改的,所以www权限的php无法替换这个js文件。只有ssh登录后,手工下载Wordpress3.3,解压缩后覆盖www目录后,一切OK。不过不过我把备份的quicktag.js覆盖过去后发现编辑器的按钮无法显示,只有重新使用3.3的quicktag.js,然后在vim中把四个换行符手工删除了才OK。

修改wordpress编辑器

一般习惯在Wordpress的HTML模式下来编辑,不过在添加b-quote的时候,编辑器喜欢在上下各添加两个回车符,我还要手工来删除这回车符,如果想禁用这一项功能,必须修改wordpress的js文件,这个文件是wp-incldes\js\quicktag.js,把js文件中的“”\n\n<blockquote>”,”</blockquote>\n\n””替换为“”<blockquote>”,”</blockquote>””

原创WordPress插件中的问题和解决方法

1. 如何在admin中显示我想要的菜单的问题

我希望自己的plugin在admin中有个top-level menu,参考了内容后一下代码实现:

add_action('admin_menu', 'mt_add_pages');
function mt_add_pages() {


    // 添加top-level菜单
    add_menu_page('待审核名单','待审核名单', 'manage_options', 'mt-top-level-handle', 'mt_toplevel_page' );

    //添加二级菜单
    add_submenu_page('mt-top-level-handle', __('已审核申请','menu-test'), __('已审核申请','menu-test'), 'manage_options', 'sub-page', 'mt_sublevel_page');

    add_submenu_page('mt-top-level-handle', __('未通过申请','menu-test'), __('未通过申请','menu-test'), 'manage_options', 'sub-page2', 'mt_sublevel_page2');
}

function mt_toplevel_page() {
	global $wpdb;
        echo "<h2>" . '已提交信息' . "</h2>";
	$qry = "SELECT * FROM trials";
	$states = $wpdb->get_results( $qry );
	echo "<table style='width:800px'>";
	echo "<td><strong>目前blog类型</strong></td><td><strong>姓名</strong></td><td><strong>电话</strong></td><td><strong>QQ</strong></td><td><strong>email</strong></td><td><strong>Blog</strong></td><td><strong>地址</strong></td>";
	foreach( $states as $row ) {
		$plan = $row->plan;
		$name = $row->name;
		$phone = $row->phone;
		$qq = $row->QQ;
		$email = $row->email;
		$blogUrl = $row->blogUrl;
		$address = $row->address;
		echo "<tr>";

		echo "<td>".$plan."</td>";
		echo "<td>".$name."</td>";
		echo "<td>".$phone."</td>";
		echo "<td>".$qq."</td>";
		echo "<td>".$email."</td>";
		echo "<td><a href=$blogUrl>".$blogUrl."</a></td>";
		echo "<td>".$address."</td>";
	
		echo "</tr>";
	}
	echo "</table>";
}


function mt_sublevel_page() {
    echo "<h2>" . __( '已审核申请', 'menu-test' ) . "</h2>";
}


function mt_sublevel_page2() {
    echo "<h2>" . __( '未通过申请', 'menu-test' ) . "</h2>";
}

我的plugin要实现的功能是在wordpress中有个page可以让网站用户提交信息,管理员可以在wordpress的后台看到所有人提交的信息,并对某些人提交的进行审核.

2. plugin在admin中如何接受更新信息

在plugin的开始输入以下信息来接受更新options信息:

if ( isset($_POST['action']) ){
	
	$value = $_POST['checkedbox'];
	$action = $_POST['action'];
	
	if ($action == 'binggo' && !empty($value)){
		echo "binggo".implode(",",$value);
		$ids = implode(",",$value);
		$wpdb->query("
			UPDATE trials SET checked='Y' , bingo='Y' WHERE id in ($ids)");
	}
	else if ($action == 'noBinggo' && !empty($value)) {
		echo "noBinggo".implode(",",$value);
		$ids = implode(",",$value);
		$wpdb->query("
			UPDATE trials SET checked='Y' , bingo='N' WHERE id in ($ids)");
	}
}

3. 如何在plugin的admin中使用js

我想在plugin中使用jquery js来控制一些信息,比如说有很多checkbox,需要有一个能看全选其他的checkbox,但是在plugin中无法直接写js,需要用wp_enqueue_script()导入js文件。

wp_enqueue_script('gatherInfo', home_url()  . '/wp-content/plugins/gatherInfo/gatherInfo.js',array('jquery'));

js文件:

jQuery(document).ready(function(){
	jQuery("#checkall").click(
	function(){
		if(this.checked){
			jQuery("input[name='checkedbox[]']").each(function(){this.checked=true;});
		}else{
			jQuery("input[name='checkedbox[]']").each(function(){this.checked=false;});
		}
	}
);
	
});

4. 用户如何提交信息

做法就是在theme中创建一个新的page template,在这个page template中添加from和各种需要输入的field。然后在wordpress中添加一个以刚才创建的page template为基础的page。

5. 如何接收到用户输入的信息

这个比较难办,参考其他的plugin都是需要在wp-admin/目录接受POST信息,参考wordpress中的wp-comments-post.php,同样复制了一个wp-userinput.php来接受用户输入信息,保存数据库,效果也很好。

if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
	header('Allow: POST');
	header('HTTP/1.1 405 Method Not Allowed');
	header('Content-Type: text/plain');
	exit;
}

/** Sets up the WordPress Environment. */
require( dirname(__FILE__) . '/wp-load.php' );

nocache_headers();

global $wpdb;

$plan = filter_input(INPUT_POST, 'plan');

$name = filter_input(INPUT_POST, 'Name');

$qq = filter_input(INPUT_POST, 'QQ');

$phone = filter_input(INPUT_POST, 'phone');

$email = filter_input(INPUT_POST, 'email');

$blogUrl = filter_input(INPUT_POST, 'blogUrl');

$address = filter_input(INPUT_POST, 'address');

$user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"]; 

if(empty($plan) || empty($name) || empty($email) || empty($phone) || empty($blogUrl) || empty($address) || empty($user_IP)){
	echo "内容不能为空!";
	die();
}


//$qry_IP = "SELECT count( * ) as num FROM trials WHERE submitIP = '$user_IP'";
//$states = $wpdb->get_results( $qry_IP );
//$wpdb->show_errors();

$sql = $wpdb->prepare("SELECT count( * ) as num FROM trials WHERE submitIP = '%s'",array($user_IP));

$states = $wpdb->get_results( $sql);

if(!empty($states)){
	$num_ip = $states[0]->num;
	if($num_ip > 20){
		echo "你申请的次数太多了^_^";
		die();
	}
}

$qry_email = $wpdb->prepare("SELECT * FROM trials where email ='%s' or blogUrl ='%s'",array($email,$blogUrl));

$states = $wpdb->get_results( $qry_email );

if(!empty($states)){
	
	echo "你已经注册过了^_^";
	die();
}
else{
		
	$rows_affected  = $wpdb->insert('trials',array( 'plan' => $plan, 'name' => $name, 'qq' => $qq,'phone' => $phone,'email' => $email,'blogUrl' => $blogUrl,'address' => $address, 'submitIP' => $user_IP));
	
	echo "注册成功!,请耐心等待我们的邮件通知.";
}

主要注意:数据库查询需要防范sql注入攻击,SQL语句最好先用$wpdb->prepare函数生成,查询的时候更加保险一些;同理,插入的时候也最好用$wpdb->insert函数而别直接用sql语句插入。

4. 用户输入表单验证问题

表单js验证使用Jquery validationEngine来实现,效果很好,并且验证规则只要在input后面写上即可,不用单独在js中写明:

input class="phone validate[required,custom[phone],maxSize[11]]" maxlength="20" id="phone" name="phone" type="text"
input class="email validate[required,custom[email]]" maxlength="50" id="email" name="email" type="text"

然后使用jquery form来ajax提交用户输入信息:

jQuery(document).ready(function(){
	
	//jQuery("#submit_button").attr("disabled", true); 可以用来是按钮功能不可用
	//jQuery("#submit_button").css("display", "none"); 可以用来使按钮不可见

	jQuery("#trials_signup").validationEngine();
	
	var options = { 
        success:       showResponse  // post-submit callback 
	}
	
	jQuery('#trials_signup').submit(function() { 
		//如果验证field没有问题就ajax提交信息
		if(jQuery("#trials_signup").validationEngine('validate')){
			jQuery("#trials_signup").ajaxSubmit(options);
			return false; 			
		}
        return false; 
    }); 
	function showResponse(responseText, statusText, xhr, $form)  {  
		alert(responseText); 
	} 
});

WordPress+Nginx +WP Super Cache加速你的Blog

WordPress+Nginx +WP Super Cache

首先要在nginx的配置中开启对rewrite的支持:

location /
{
autoindex off;
gzip_static on;

set $wp_super_cache_file ”;
set $wp_super_cache_uri $request_uri;

if ( $request_method = POST )
{
set $wp_super_cache_uri ”;
}

if ( $query_string )
{
set $wp_super_cache_uri ”;
}

if ( $http_cookie ~* “comment_author_|wordpress|wp-postpass_” )
{
set $wp_super_cache_uri ”;
}

if ( $wp_super_cache_uri ~ ^(.+)$ )
{
set $wp_super_cache_file /wp-content/cache/wp_super_cache/$http_host/$1index.html;
}

if ( -f $document_root$wp_super_cache_file )
{
rewrite ^(.*)$ $wp_super_cache_file break;
}

if (-f $request_filename)
{
expires 30d;
break;
}

if (!-e $request_filename)
{
rewrite ^(.+)$ /index.php?q=$1 last;
}
}

然后在WordPress中开启permalink,其中注意一项WordPress如果发现web服务器不是Apache的话开启permalink会自作主张在permalink最前面加上index.php,例如/index.php/$postname$/之类的,所以要补permal的定义文件中的index.php删除,否则wp-supercache会认为url中包含_GET信息而不缓存除了index之外的任何页面。接下来就是安装wp-cache,这个很简单,安装后只要浏览页面源码发现最下面有如下信息,就证明wp-supercache已经缓存这个页面了:


关于Nginx添加permalink的问题

WordPress和很多web app都需要permalink的支持来完成uri优化和SEO,在Apache下面只要开启rewrite mod和在目录下面放一个.htaccess文件就可以了,但是在Nginx或者lighttpd下面就只能在配置文件下更改才能完成。比如在Nginx下面,需要导入一个rewrite文件:

# WordPress pretty URLs
if (-f $request_filename) {
expires max;
break;
}
if (-d $request_filename) {
break;
}
rewrite ^(.+)$ /index.php?q=$1 last;

# Enable nice permalinks for WordPress
error_page  404  = //index.php?q=$uri;

然后在

 location / {
            root   /usr/share/nginx/html;
            index  index.php index.html index.htm;
            include /etc/nginx/wordpress_params_regular;
            
        }

网上有些说明把引用文件放在了

location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
            include        fastcgi_params;
            include /etc/nginx/wordpress_params_regular;
            
        }

根据我的测试这是不对的,最直接的结果就是在log中出现这样的问题

/var/www/index.php/2010/01/hello/index.php

在uri的尾部添加了一个index.php,Nginx无法找到文件。

PS:在Nginx中添加rewrite后,WordPress的“关于”页面无法打开,WordPress报了404错误,但是如果新建一个页面倒是能够顺利通过permalink访问,甚至把开始的“关于”删除后重新见一个同名的“关于”页面也能正常permalink访问,只在中文版的WordPress发现这样的情况,英文版没有测试。

网上有一段关于nginx设置rewrite的配置,甚至包含了bbPress(WordPress的姐妹项目,一个和WordPress兼容的小型论坛)的:

server {
listen 80;
server_name _ bandpress.org *.bandpress.org;
error_log /var/log/nginx/bandpress.org.error.log;
access_log /var/log/nginx/bandpress.org.access.log;
# Set this to off if you're hosting more than one site
server_name_in_redirect off;
#redirects 301
rewrite /togodaddy$ http://www.kqzyfj.com/click-3348421-10378406 permanent;
rewrite /towoothemes$ http://www.woothemes.com/amember/go.php?r=12635&i=b16 permanent;
# Rewrite WordPress
location /
{
gzip on;
gzip_http_version 1.0;
gzip_vary on;
gzip_comp_level 3;
gzip_proxied any;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_buffers 16 8k;
root /var/www/bandpress.org;
index index.php;
#rewrite for sitemaps
rewrite ^(.*/)?sitemap.xml /wp-content/sitemap.php last;
#rewite for anyfont
rewrite images/(.*)/(.*)\.png$ /wp-content/plugins/anyfont/img.php last;
#rewrite for blog files
rewrite ^.*/files/(.*) /wp-content/blogs.php?file=$1 last;
# WordPress pretty URLs
if (-f $request_filename)
{
expires max;
break;
}
if (-d $request_filename)
{
break;
}
# WP Super Cache
set $supercache_file '';
set $supercache_uri $request_uri;
if ($request_method = POST) {
set $supercache_uri '';
}
# Using pretty permalinks, so bypass the cache for any query string
if ($query_string) {
set $supercache_uri '';
}
if ($http_cookie ~* "comment_author_|wordpress|wp-postpass_" ) {
set $supercache_uri '';
}
# if we haven't bypassed the cache, specify our supercache file
if ($supercache_uri ~ ^(.+)$) {
set $supercache_file /wp-content/cache/supercache/$http_host/$1index.html;
}
# only rewrite to the supercache file if it actually exists
if (-f $document_root$supercache_file) {
rewrite ^(.*)$ $supercache_file break;
}
#BBPress
if (!-e $request_filename) {
rewrite ^/forums/topic/(.*)$ /forums/topic.php last;
rewrite ^/forums/forum/(.*)$ /forums/forum.php last;
rewrite ^/forums/profile/(.*)$ /forums/profile.php last;
rewrite ^/forums/view/(.*)$ /forums/view.php last;
rewrite ^/forums/tags/(.*)$ /forums/tags.php last;
rewrite ^/forums/rss/(.*)$ /forums/rss.php last;
rewrite ^/forums/bb-admin/ /forums/bb-admin/index.php last;
rewrite ^/forums/ /forums/index.php last;
}
if (!-e $request_filename) {
rewrite ^.+/?(/wp-.*) $1 last;
rewrite ^.+/?(/.*\.php)$ $1 last;
rewrite ^(.+)$ /index.php?q=$1 last;
}
error_page 404 = /index.php?q=$uri;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/bandpress.org$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}