【问题标题】:WordPress - How to add/update post_meta (Custom Fields)?WordPress - 如何添加/更新 post_meta(自定义字段)?
【发布时间】:2013-10-21 20:50:17
【问题描述】:

我已经编写了这个简单的代码来添加一个新的 POST 到 WordPress 数据库(在 LOOP 之外):

include_once './wp-config.php';
include_once './wp-load.php';
include_once './wp-includes/wp-db.php';

$upname = 'TestName';
$updescription = 'Description';

  // Create post object
  $my_post = array();
  $my_post['post_title'] = $upname;
  $my_post['post_content'] = $updescription;
  $my_post['post_status'] = 'draft';
  $my_post['post_author'] = 1;

  if (current_user_can( 'manage_options' )) {

  // Insert the post into the database
  wp_insert_post( $my_post );  
  echo '<br /><b>The Advertisement is saved as Draft!</b>';
  } else {
  echo '<br /><b>You are NOT logged in, login to continue!</b>';
  }

它可以 100% 工作,但现在我希望添加 2 个自定义字段:"phone_num""birth_date"

如何在此代码中添加自定义字段?

【问题讨论】:

标签: php wordpress


【解决方案1】:

你应该使用它,它会帮助你更多。

我用过这个,效果很好。

// Insert the post into the database
$post_id =  wp_insert_post( $my_post );
add_post_meta($post_id,'phone_num',$upphone); or 
    update_post_meta($post_id,'phone_num',$upphone);
add_post_meta($post_id,'birth_date',$upbirthdate); or 
     update_post_meta($post_id,'birth_date',$upbirthdate);

谢谢。

【讨论】:

    【解决方案2】:

    我找到了一个解决方案,这对我有用:-)

    在我的代码中我更新/替换了:

    // Insert the post into the database
    wp_insert_post( $my_post );
    

    有了这个:

    // Insert the post into the database
    $post_id =  wp_insert_post( $my_post );
    update_post_meta($post_id,'phone_num',$upphone);
    update_post_meta($post_id,'birth_date',$upbirthdate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多