如何为所有已发布的帖子添加自定义域和递增值

时间:2016-10-15 作者:pradip

我试图为从第一篇文章开始的所有已发布和新文章添加一个自定义字段值“article”和从1开始的自动增量值。

我正在Mysql中尝试以下代码。但它不起作用

insert into wp_postmeta (post_id, meta_key, meta_value) 
select ID \'article\', \'AUTO_INCREMENT=VALUES\' from wp_posts WHERE post_type = \'post\';

1 个回复
SO网友:pradip

它起作用了。。。这是代码

function updateNumbers() {
/* numbering the published posts: preparation: create an array with the ID in sequence of publication date, /
/ save the number in custom field \'article\' of post with ID  /
/ to show in post (within the loop) use <?php echo get_post_meta($post->ID,\'article\',true); ?>
/ alchymyth 2010 */
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = \'publish\' AND $wpdb->posts.post_type = \'post\' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
add_post_meta($post->ID, \'article\', $counts, true);
update_post_meta($post->ID, \'article\', $counts);
endforeach;
endif;
}  

add_action ( \'publish_post\', \'updateNumbers\' );
add_action ( \'deleted_post\', \'updateNumbers\' );
add_action ( \'edit_post\', \'updateNumbers\' );