WordPress删除重复的自定义字段(Custom Fields)

文章目录

自定义字段(Custom Fields)为WordPress提供了非常有用的扩展功能。倡萌在本地测试主题调用最近浏览量最多的文章的时候,发现居然存在重复的文章,查看后发现,该文章存在两个同样的字段 views,如下图所示:

duplicate-custom-fields-wpdaxue_com

出现这种情况,可能是由于网站搬家的导出导入文章造成的,下面分享两种方法删除重复的自定义字段(只保留一个)。

重要提示:请先备份和下载网站的数据库文件,然后再使用下文的方法!

方法1:通过phpMyAdmin删除

登录的 phpMyAdmin 面板(不会的请先自己阅读 phpMyAdmin 相关文章),然后使用下面的 SQL 语句进行删除即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
delete from wp_postmeta
where meta_id in (
select *
from (
select meta_id
from wp_postmeta a
where a.meta_key = 'views'
and meta_id not in (
select min(meta_id)
from wp_postmeta b
where b.post_id = a.post_id
and b.meta_key = 'views'
)
) as x
);

delete from wp_postmeta where meta_id in ( select * from ( select meta_id from wp_postmeta a where a.meta_key = 'views' and meta_id not in ( select min(meta_id) from wp_postmeta b where b.post_id = a.post_id and b.meta_key = 'views' ) ) as x );

请根据自己的实际,修改第 1、6、10 行的 wp_postmeta 的前缀 wp_(如果你的数据库前缀不是wp_ 的话);本例的第 7 、12 行 的 views 就是要删除的自定义字段,请自行修改。

方法2:通过PHP代码删除

如果你没办法通过phpMyAdmin操作数据库,那你可以使用下面的方法。

1.在网站的根目录新建一个名为 remove-duplicate-custom-fields.php 文件,复制下面的代码到该文件,保存:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
define('WP_USE_THEMES', false);
require('wp-blog-header.php');
 
define( 'WP_DEBUG_DISPLAY', true );
ini_set( 'display_errors', true );
$allposts = get_posts('numberposts=-1&post_type=post&post_status=any');
$keys = array('views','test_meta');//要检索的自定义字段
foreach ( $keys as $key ) {
foreach( $allposts as $postinfo) {
// 获取(上面所填写的)自定义字段的值
$postmeta = get_post_meta($postinfo->ID, $key);
 
if (!empty($postmeta) ) {
// 删除这篇文章的(上面所填写的)自定义字段
delete_post_meta($postinfo->ID, $key);
 
// 插入一个且只有一个(上面所填写的)自定义字段
update_post_meta($postinfo->ID, $key, $postmeta[0]);
}
}
}
?>

<?php define('WP_USE_THEMES', false); require('wp-blog-header.php'); define( 'WP_DEBUG_DISPLAY', true ); ini_set( 'display_errors', true ); $allposts = get_posts('numberposts=-1&post_type=post&post_status=any'); $keys = array('views','test_meta');//要检索的自定义字段 foreach ( $keys as $key ) { foreach( $allposts as $postinfo) { // 获取(上面所填写的)自定义字段的值 $postmeta = get_post_meta($postinfo->ID, $key); if (!empty($postmeta) ) { // 删除这篇文章的(上面所填写的)自定义字段 delete_post_meta($postinfo->ID, $key); // 插入一个且只有一个(上面所填写的)自定义字段 update_post_meta($postinfo->ID, $key, $postmeta[0]); } } } ?>

注意修改第 8 行的字段,本例删除的是 'views'和'test_meta' 两个字段,请自行修改(多个字段使用半角英文逗号隔开)。

2.通过浏览器访问 http://你的域名/remove-duplicate-custom-fields.php,稍等片刻,即可删除多余的重复字段啦!

参考资料:http://wordpress.stackexchange.com/questions/15209

全部为采集文章,文中的 联系方式 均不是 本人 的!

发表评论