更新自定义字段,如果为空

时间:2012-04-14 19:22:48

标签: wordpress custom-fields

如果自定义字段值为空白,如果它有任何值,则需要更新自定义字段值

我想只在空的时候更新 代码:

$custom_fields = get_post_custom($post_ID);//Current post id
    $my_custom_field = $custom_fields['artist'];//key name
    foreach ( $my_custom_field as $key => $value );
    if(empty($value) or ($value == '')){
        $artist_v = get_post_custom_values('artist', $post_ID);
        update_post_meta($post_ID, 'artist', $parent_title, $artist_v);
    }else{
        //add_post_meta($post_ID, 'artist', $parent_title, true);
    }

1 个答案:

答案 0 :(得分:0)

以下示例可能有所帮助:

`

        

    if(!empty($ARR_meta_data))
    {
      foreach($ARR_meta_data as $meta)
      {
    if(trim($meta['meta_value']) == "")
    {
          update_postmeta_by_meta_id($meta['meta_id'], "  YOUR CUSTOM VALUE   ");
    }
      } 
    }

    function get_postmeta_details_in_array($post_id, $meta_key)
    {
      global $wpdb;
      $sql = "SELECT * FROM ".$wpdb->prefix."postmeta 
          WHERE meta_key='{$meta_key}' AND post_id='{$post_id}'";

      return $wpdb->get_results($sql, ARRAY_A);
    }

    function update_postmeta_by_meta_id($meta_id, $meta_value)
    {
      global $wpdb;
      $sql = "UPDATE ".$wpdb->prefix."postmeta SET meta_value='$meta_value' 
          WHERE meta_id='$meta_id'";

      return $wpdb->query($sql);
    }
    ?>

`

在wordpress主题的functions.php中放置get_postmeta_details_in_array()和update_postmeta_by_meta_id()函数。