1

I want to add a new custom field with a meta key and meta value to my posts.

Currently the only way it is added to a post is if I go into the post and click Update.
I have lots of posts and essentially want this custom field to be added to all posts automatically with an assigned meta value.

This meta value is different for each post.

4

2 回答 2

3

我发现这很有帮助: http: //www.catswhocode.com/blog/wordpress-how-to-insert-data-programmatically

function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
    add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');

这将为 $post_ID 中的“字段名称”添加一个“自定义值”。

于 2011-11-17T21:26:19.460 回答
0

我认为正确的方法是使用'save_post'hook,例如:

  function cwp_add_custom_post_meta($post_id, $post){
global $wpdb;
$post_cat_id=get_the_terms( $post_id, 'category' );
$post_cat_id=cwp_object_to_array($post_cat_id);
$post_cat_id=$post_cat_id['0'] ["term_id"];
$display_voting = get_tax_meta($post_cat_id,'cwp_display_voting');
if(!wp_is_post_revision($post_id))
    update_post_meta($post_id,'display_voting', $display_voting);
}
add_action( 'save_post', 'cwp_add_custom_post_meta', 10, 2 );
于 2014-05-02T17:30:42.760 回答