Пример #1
0
 /**
  * Clones provided page ID
  * @param  int $pageId
  * @return int
  */
 public function clonePage($pageId)
 {
     $oldPost = get_post($pageId);
     if (null === $oldPost) {
         return 0;
     }
     if ('revision' === $oldPost->post_type) {
         return 0;
     }
     $currentUser = wp_get_current_user();
     $newPost = array('menu_order' => $oldPost->menu_order, 'comment_status' => $oldPost->comment_status, 'ping_status' => $oldPost->ping_status, 'post_author' => $currentUser->ID, 'post_content' => $oldPost->post_content, 'post_excerpt' => $oldPost->post_excerpt, 'post_mime_type' => $oldPost->post_mime_type, 'post_parent' => $oldPost->post_parent, 'post_password' => $oldPost->post_password, 'post_status' => $oldPost->post_status, 'post_title' => '(dup) ' . $oldPost->post_title, 'post_type' => $oldPost->post_type, 'post_date' => $oldPost->post_date, 'post_date_gmt' => get_gmt_from_date($oldPost->post_date));
     $newId = wp_insert_post($newPost);
     /*
      * Generating unique slug
      */
     if ($newPost['post_status'] == 'publish' || $newPost['post_status'] == 'future') {
         $postName = wp_unique_post_slug($oldPost->post_name, $newId, $newPost['post_status'], $oldPost->post_type, $newPost['post_parent']);
         $newPost = array();
         $newPost['ID'] = $newId;
         $newPost['post_name'] = $postName;
         wp_update_post($newPost);
     }
     $this->cloneMeta($pageId, $newId);
     $this->cloneOpData($pageId, $newId);
     return $newId;
 }
function mcs_generate_submit_page($slug)
{
    $current_user = wp_get_current_user();
    if (!is_page($slug)) {
        $page = array('post_title' => __('Submit Events', 'my-calendar'), 'post_status' => 'publish', 'post_type' => 'page', 'post_author' => $current_user->ID, 'ping_status' => 'closed', 'post_content' => '[submit_event]');
        $post_ID = wp_insert_post($page);
        $post_slug = wp_unique_post_slug($slug, $post_ID, 'publish', 'page', 0);
        wp_update_post(array('ID' => $post_ID, 'post_name' => $post_slug));
    } else {
        $post = get_page_by_path($slug);
        $post_ID = $post->ID;
    }
    update_option('mcs_submit_id', $post_ID);
    return $post_ID;
}
 /**
  * Perfomr duplicating post/page
  * @param object $post
  * @param string $status
  * @param string $parent_id
  * @return int
  */
 function duplicate($post, $status = '', $parent_id = '')
 {
     $prefix = '';
     $suffix = '';
     $this->old_post_content = $post->post_content;
     $this->new_post_content = tf_generate_new_shortcode_ids($post->post_content);
     // We don't want to clone revisions
     if ($post->post_type == 'revision') {
         return;
     }
     if ($post->post_type != 'attachment') {
         $prefix = '';
         //$suffix = ' Copy';
         $suffix = '';
     }
     $new_post_author = $this->duplicate_get_current_user();
     $new_post = array('menu_order' => $post->menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_author' => $new_post_author->ID, 'post_content' => $this->new_post_content, 'post_excerpt' => $post->post_excerpt, 'post_mime_type' => $post->post_mime_type, 'post_parent' => $new_post_parent = empty($parent_id) ? $post->post_parent : $parent_id, 'post_password' => $post->post_password, 'post_status' => $new_post_status = empty($status) ? $post->post_status : $status, 'post_title' => $prefix . $post->post_title . $suffix, 'post_type' => $post->post_type);
     $new_post_id = wp_insert_post($new_post);
     // apply hook to duplicate action
     if ($post->post_type == 'page' || function_exists('is_post_type_hierarchical') && is_post_type_hierarchical($post->post_type)) {
         do_action('tf_duplicate_page', $new_post_id, $post);
     } else {
         do_action('tf_duplicate_post', $new_post_id, $post);
     }
     // If the copy is published or scheduled, we have to set a proper slug.
     if ($new_post_status == 'publish' || $new_post_status == 'future') {
         $post_name = wp_unique_post_slug($post->post_name, $new_post_id, $new_post_status, $post->post_type, $new_post_parent);
         $new_post = array();
         $new_post['ID'] = $new_post_id;
         $new_post['post_name'] = $post_name;
         // Update the post into the database
         wp_update_post($new_post);
     }
     // set new url
     if ($post->post_type == 'page') {
         $this->new_url = get_page_link($new_post_id);
     } else {
         $this->new_url = get_permalink($new_post_id);
     }
     // check if admin
     if ($this->edit_link) {
         $this->new_url = get_edit_post_link($new_post_id);
     }
     return $new_post_id;
 }
Пример #4
0
 /**
  * Create a duplicate from a post
  */
 private function create_duplicate($post, $status = '')
 {
     $prefix = __('Copy', 'newsplus') . ': ';
     $suffix = "";
     if (!empty($prefix)) {
         $prefix .= " ";
     }
     if (!empty($suffix)) {
         $suffix = " " . $suffix;
     }
     $new_post_author = wp_get_current_user();
     $new_post = array('menu_order' => $post->menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_author' => $new_post_author->ID, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_mime_type' => $post->post_mime_type, 'post_password' => $post->post_password, 'post_status' => $new_post_status = empty($status) ? $post->post_status : $status, 'post_title' => $prefix . $post->post_title . $suffix, 'post_type' => $post->post_type);
     $new_post_id = wp_insert_post($new_post);
     //copy metas
     global $wpdb;
     $metas = $wpdb->get_results('SELECT meta_key,meta_value FROM ' . $wpdb->postmeta . ' WHERE post_id=' . $post->ID, ARRAY_A);
     if (!empty($metas)) {
         foreach ($metas as $value) {
             $wpdb->insert($wpdb->postmeta, array('post_id' => $new_post_id, 'meta_key' => $value['meta_key'], 'meta_value' => $value['meta_value']));
         }
     }
     //copy categories
     $cats = $wpdb->get_results('SELECT term_taxonomy_id FROM ' . $wpdb->term_relationships . ' WHERE object_id=' . $post->ID, ARRAY_A);
     if (!empty($cats)) {
         foreach ($cats as $value) {
             $wpdb->insert($wpdb->term_relationships, array('object_id' => $new_post_id, 'term_taxonomy_id' => $value['term_taxonomy_id']));
         }
     }
     // If the copy is published or scheduled, we have to set a proper slug.
     $post_name = wp_unique_post_slug($post->post_name, $new_post_id, $new_post_status, $post->post_type);
     $new_post = array();
     $new_post['ID'] = $new_post_id;
     $new_post['post_name'] = $post_name;
     // Update the post into the database
     wp_update_post($new_post);
     //reset stat
     update_post_meta($new_post_id, 'mail_stat_data', '');
     return $new_post_id;
 }
Пример #5
0
 function raindrops_unique_entry_title($postid = '', $echo = false)
 {
     global $post;
     if (isset($post) && empty($postid)) {
         $postid = $post->ID;
     } elseif (empty($post)) {
         return;
     }
     $post_object = get_post($postid);
     $post_name = $post_object->post_name;
     $unique_title = urldecode(wp_unique_post_slug($post_name, $post->ID, 'publish', 'post', 0));
     preg_match('!(.+)(-[0-9]+)$!', $unique_title, $regs);
     if (isset($regs[2])) {
         if (true == $echo) {
             echo esc_html($regs[2]);
         } else {
             return esc_html($regs[2]);
         }
     }
 }
Пример #6
0
        function process_posts()
        {
            if (!($fp = fopen($this->file, "r"))) {
                echo '<p><strong>' . __('Failed to open file.', 'wc2') . '</strong></p>';
                wp_import_cleanup($this->id);
                return false;
            }
            global $wpdb;
            $wc2_item = WC2_DB_Item::get_instance();
            //all delete
            //$wc2_item->delete_all_item_data();
            //die();
            $err = new WP_Error();
            $sp = ",";
            $lines = array();
            $buf = '';
            while (!feof($fp)) {
                $temp = fgets($fp, 10240);
                if (0 == strlen($temp)) {
                    continue;
                }
                $num = substr_count($temp, '"');
                if (0 == $num % 2 && '' == $buf) {
                    $lines[] = $temp;
                } elseif (1 == $num % 2 && '' == $buf) {
                    $buf .= $temp;
                } elseif (0 == $num % 2 && '' != $buf) {
                    $buf .= $temp;
                } elseif (1 == $num % 2 && '' != $buf) {
                    $buf .= $temp;
                    $lines[] = $buf;
                    $buf = '';
                }
            }
            fclose($fp);
            //Post data - fixed
            define('COL_POST_ID', 0);
            define('COL_POST_AUTHOR', 1);
            define('COL_POST_CONTENT', 2);
            define('COL_POST_TITLE', 3);
            define('COL_POST_EXCERPT', 4);
            define('COL_POST_STATUS', 5);
            define('COL_POST_COMMENT_STATUS', 6);
            define('COL_POST_PASSWORD', 7);
            define('COL_POST_NAME', 8);
            define('COL_POST_MODIFIED', 9);
            define('COL_POST_CATEGORY', 10);
            define('COL_POST_TAG', 11);
            define('COL_POST_CUSTOM_FIELD', 12);
            define('COL_ITEM_CODE', 13);
            define('COL_ITEM_NAME', 14);
            $item_base_column = $wc2_item->get_item_base_column();
            $item_meta_column = $wc2_item->get_item_meta_column();
            $item_sku_column = $wc2_item->get_item_sku_column();
            $item_sku_meta_column = $wc2_item->get_item_sku_meta_column();
            $system = wc2_get_option('system');
            $this->encode_type = isset($system['csv_encode_type']) ? $system['csv_encode_type'] : 0;
            $start_col = 13;
            $sku_start_col = $start_col;
            foreach ((array) $item_base_column as $key => $column) {
                if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                    $sku_start_col++;
                }
            }
            foreach ((array) $item_meta_column as $key => $column) {
                if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                    $sku_start_col++;
                }
            }
            $post_status = array('publish', 'future', 'draft', 'pending', 'private');
            $pre_item_code = '';
            $item_id = 0;
            $sku_id = 1;
            $this->data_rows = count($lines);
            $this->success = 0;
            $this->false = 0;
            //Progressbar 処理件数SET
            echo '<script type="text/javascript">PG_Set_Max(' . $this->data_rows . ');</script>' . "\r\n";
            ob_flush();
            flush();
            foreach ($lines as $row => $line) {
                $datas = array();
                $datas = explode($sp, trim($line));
                $this->values = array();
                $buf = '';
                foreach ($datas as $data) {
                    $num = substr_count($data, '"');
                    if (0 == $num % 2 && '' == $buf) {
                        if ('"' == substr($data, 0, 1)) {
                            $data = substr($data, 1);
                        }
                        if ('"' == substr($data, -1)) {
                            $data = substr($data, 0, -1);
                        }
                        $data = str_replace(array('""'), '"', $data);
                        $this->values[] = false !== $data ? $data : '';
                    } elseif (1 == $num % 2 && '' == $buf) {
                        $buf .= $data;
                    } elseif (0 == $num % 2 && '' != $buf) {
                        $buf .= $sp . $data;
                    } elseif (1 == $num % 2 && '' != $buf) {
                        $buf .= $sp . $data;
                        if ('"' == substr($buf, 0, 1)) {
                            $buf = substr($buf, 1);
                        }
                        if ('"' == substr($buf, -1)) {
                            $buf = substr($buf, 0, -1);
                        }
                        $buf = str_replace(array('""'), '"', $buf);
                        $this->values[] = false !== $buf ? $buf : '';
                        $buf = '';
                    }
                }
                if ('Post ID' == $this->values[COL_POST_ID]) {
                    $this->data_rows -= 1;
                    $this->progress_add();
                    continue;
                }
                if ($pre_item_code == $this->values[COL_ITEM_CODE] && WC2_Utils::is_blank($this->values[COL_POST_ID])) {
                    $mode = 'add';
                    $post_id = '';
                } else {
                    $post_id = !WC2_Utils::is_blank($this->values[COL_POST_ID]) ? (int) $this->values[COL_POST_ID] : '';
                    if ($post_id) {
                        $post_ob = get_post($post_id);
                        if (!isset($post_ob->ID) || empty($post_ob)) {
                            $this->error_log($row, __("Post-ID {$post_id} does not exist.", 'wc2'));
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        $mode = 'upd';
                    } else {
                        $mode = 'add';
                    }
                }
                $wc2_item->set_the_post_id($post_id);
                //data_check
                foreach ($this->values as $key => $val) {
                    $value = trim($val);
                    switch ($key) {
                        case COL_POST_ID:
                            if (!preg_match("/^[0-9]+\$/", $value) && 0 != strlen($value)) {
                                $this->error_log($row, __('A value of the Post-ID is abnormal.', 'wc2'));
                            }
                            break;
                        case COL_POST_AUTHOR:
                        case COL_POST_COMMENT_STATUS:
                        case COL_POST_PASSWORD:
                        case COL_POST_NAME:
                        case COL_POST_TITLE:
                        case COL_POST_CONTENT:
                        case COL_POST_EXCERPT:
                            break;
                        case COL_POST_STATUS:
                            if (0 == strlen($value) || !in_array($value, $post_status)) {
                                $this->error_log($row, __('A value of the display status is abnormal.', 'wc2'));
                            }
                            break;
                        case COL_POST_MODIFIED:
                            if ('future' == $this->values[COL_POST_STATUS] && (0 == strlen($value) || '0000-00-00 00:00:00' == $value)) {
                                if (preg_match($date_pattern, $value, $match)) {
                                    if (checkdate($match[2], $match[3], $match[1]) && (0 < $match[4] && 24 > $match[4]) && (0 < $match[5] && 60 > $match[5]) && (0 < $match[6] && 60 > $match[6])) {
                                    } else {
                                        $this->error_log($row, __('A value of the schedule is abnormal.', 'wc2'));
                                    }
                                } else {
                                    $this->error_log($row, __('A value of the schedule is abnormal.', 'wc2'));
                                }
                            } else {
                                if (0 != strlen($value) && '0000-00-00 00:00:00' != $value) {
                                    if (preg_match("/^[0-9]+\$/", substr($value, 0, 4))) {
                                        if (strtotime($value) === false) {
                                            $this->error_log($row, __('A value of the schedule is abnormal.', 'wc2'));
                                        }
                                    } else {
                                        $datetime = explode(' ', $value);
                                        $date_str = $this->dates_interconv($datetime[0]) . ' ' . $datetime[1];
                                        if (strtotime($date_str) === false) {
                                            $this->error_log($row, __('A value of the schedule is abnormal.', 'wc2'));
                                        }
                                    }
                                }
                            }
                            break;
                        case COL_POST_CATEGORY:
                            if (0 == strlen($value)) {
                                $this->error_log($row, __('A category is non-input.', 'wc2'));
                            }
                            break;
                        case COL_POST_TAG:
                        case COL_POST_CUSTOM_FIELD:
                            break;
                        case COL_ITEM_CODE:
                            if (0 == strlen($value)) {
                                $this->error_log($row, __('An item code is non-input.', 'wc2'));
                            } else {
                                $post_ids = $wc2_item->get_some_post_ids_by_item_code($value);
                                if ('upd' == $mode) {
                                    if (1 < count($post_ids)) {
                                        $this->error_log($row, __('This Item-Code has been duplicated.', 'wc2'));
                                        foreach ($post_ids as $res_val) {
                                            $this->error_log($row, "item_code=" . $value . ", post_id=" . $res_val['item_post_id']);
                                        }
                                    } elseif (1 === count($post_ids)) {
                                        if ($post_ids[0]['item_post_id'] != $post_id) {
                                            $this->error_log($row, __('This Item-Code has already been used.', 'wc2'));
                                            $this->error_log($row, "item_code=" . $value . ", post_id=" . $post_ids[0]['item_post_id']);
                                        }
                                    }
                                } else {
                                    if ('add' == $mode) {
                                        if ($value != $pre_item_code) {
                                            if (0 < count($post_ids)) {
                                                $this->error_log($row, __('This Item-Code has already been used.', 'wc2'));
                                                foreach ($post_ids as $res_val) {
                                                    $this->error_log($row, "item_code=" . $value . ", post_id=" . $res_val['item_post_id']);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case COL_ITEM_NAME:
                            if (0 == strlen($value)) {
                                $this->error_log($row, __('An item name is non-input.', 'wc2'));
                            }
                            break;
                    }
                }
                //表示する Item column をエラーチェック
                $check_num = $start_col;
                foreach ($item_base_column as $key => $column) {
                    if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                        $check_column[$key] = $check_num;
                        $check_num++;
                    }
                }
                foreach ($item_meta_column as $key => $column) {
                    if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                        $check_column[$key] = $check_num;
                        $check_num++;
                    }
                }
                foreach ($item_sku_column as $key => $column) {
                    if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                        $check_column[$key] = $check_num;
                        $check_num++;
                    }
                }
                foreach ($item_sku_meta_column as $key => $column) {
                    if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                        $check_column[$key] = $check_num;
                        $check_num++;
                    }
                }
                foreach ($check_column as $column_key => $data_num) {
                    switch ($column_key) {
                        case ITEM_PRODUCT_TYPE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Product type is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_CHARGES_TYPE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Billing type is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_PURCHASE_LIMIT_LOWEST:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Purchase limit(lowest) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_PURCHASE_LIMIT_HIGHEST:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Purchase limit(highest) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_POINT_RATE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the point rate is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_NUM1:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount1(number) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_RATE1:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount1(rate) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_NUM2:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount2(number) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_RATE2:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount2(rate) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_NUM3:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount3(number) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_QUANTITY_DISCOUNT_RATE3:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount3(rate) is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_CODE:
                            if (0 == strlen($this->values[$data_num])) {
                                $this->error_log($row, __('A SKU code is non-input.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_NAME:
                        case ITEM_SKU_UNIT:
                            break;
                        case ITEM_SKU_STOCK:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the SKU stock is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_STATUS:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the SKU status is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_PRICE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the SKU price is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_COSTPRICE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the SKU cost price is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_LISTPRICE:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the SKU list price is abnormal.', 'wc2'));
                            }
                            break;
                        case ITEM_SKU_SET_QUANTITY_DISCOUNT:
                            if (!preg_match("/^[0-9]+\$/", $this->values[$data_num])) {
                                $this->error_log($row, __('A value of the Quantity discount applies is abnormal.', 'wc2'));
                            }
                            break;
                    }
                }
                if ('' != $this->get_log_line()) {
                    $this->create_log();
                    $this->progress_add();
                    continue;
                }
                $post = array();
                if ($pre_item_code != $this->values[COL_ITEM_CODE]) {
                    $sku_id = 1;
                    if ($this->values[COL_POST_MODIFIED] == '' || $this->values[COL_POST_MODIFIED] == '0000-00-00 00:00:00') {
                        $post['post_date'] = current_time('mysql');
                        $post['post_date_gmt'] = current_time('mysql', 1);
                        $post['post_modified'] = current_time('mysql');
                        $post['post_modified_gmt'] = current_time('mysql', 1);
                    } else {
                        if (preg_match("/^[0-9]+\$/", substr($this->values[COL_POST_MODIFIED], 0, 4))) {
                            $time_data = strtotime($this->values[COL_POST_MODIFIED]);
                        } else {
                            $datetime = explode(' ', $this->values[COL_POST_MODIFIED]);
                            $date_str = $this->dates_interconv($datetime[0]) . ' ' . $datetime[1];
                            $time_data = strtotime($date_str);
                        }
                        $post['post_date'] = date('Y-m-d H:i:s', $time_data);
                        $post['post_date_gmt'] = gmdate('Y-m-d H:i:s', $time_data);
                        $post['post_modified'] = date('Y-m-d H:i:s', $time_data);
                        $post['post_modified_gmt'] = gmdate('Y-m-d H:i:s', $time_data);
                    }
                    if ('publish' == $this->values[COL_POST_STATUS]) {
                        $now = current_time('mysql');
                        if (mysql2date('U', $post['post_modified'], false) > mysql2date('U', $now, false)) {
                            $this->values[COL_POST_STATUS] = 'future';
                        }
                    } elseif ('future' == $this->values[COL_POST_STATUS]) {
                        $now = current_time('mysql');
                        if (mysql2date('U', $post['post_modified'], false) <= mysql2date('U', $now, false)) {
                            $this->values[COL_POST_STATUS] = 'publish';
                        }
                    }
                    $post['ID'] = $post_id;
                    $post['post_author'] = !WC2_Utils::is_blank($this->values[COL_POST_AUTHOR]) ? $this->values[COL_POST_AUTHOR] : 1;
                    $post['post_content'] = $this->convert_encoding($this->values[COL_POST_CONTENT]);
                    $post['post_title'] = $this->convert_encoding($this->values[COL_POST_TITLE]);
                    $post['post_excerpt'] = $this->convert_encoding($this->values[COL_POST_EXCERPT]);
                    $post['post_status'] = $this->values[COL_POST_STATUS];
                    $post['comment_status'] = !WC2_Utils::is_blank($this->values[COL_POST_COMMENT_STATUS]) ? $this->values[COL_POST_COMMENT_STATUS] : 'close';
                    $post['ping_status'] = 'close';
                    $post['post_password'] = '******' == $post['post_status'] ? '' : $this->values[COL_POST_PASSWORD];
                    $post['post_type'] = ITEM_POST_TYPE;
                    $post['post_parent'] = 0;
                    $post_name = sanitize_title($this->convert_encoding($this->values[COL_POST_NAME]));
                    $post['post_name'] = wp_unique_post_slug($post_name, $post_id, $post['post_status'], $post['post_type'], $post['post_parent']);
                    $post['to_ping'] = '';
                    $post['pinged'] = '';
                    $post['menu_order'] = 0;
                    $post['post_content_filtered'] = '';
                    if (empty($post['post_name']) && !in_array($post['post_status'], array('draft', 'pending', 'auto-draft'))) {
                        $post['post_name'] = sanitize_title($post['post_title'], $post_id);
                    }
                    if ($mode == 'add') {
                        $post['guid'] = '';
                        if (false === $wpdb->insert($wpdb->posts, $post)) {
                            $this->error_log($row, __('This data was not registered in the database.', 'wc2'));
                            $pre_item_code = $this->values[COL_ITEM_CODE];
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        $post_id = $wpdb->insert_id;
                        $wc2_item->set_the_post_id($post_id);
                        $where = array('ID' => $post_id);
                        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_id)), $where);
                    } elseif ($mode == 'upd') {
                        $where = array('ID' => $post_id);
                        if (false === $wpdb->update($wpdb->posts, $post, $where)) {
                            $this->error_log($row, __('The data were not registered with a database.', 'wc2'));
                            $pre_item_code = $this->values[COL_ITEM_CODE];
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        //delete all metas of Item
                        $meta_key_table = array();
                        $cfrows = explode(';', trim($this->values[COL_POST_CUSTOM_FIELD]));
                        //if( !(1 === count($cfrows) && '' == reset($cfrows)) ) {
                        if ('' != reset($cfrows)) {
                            foreach ($cfrows as $cf) {
                                list($meta_key, $meta_value) = explode('=', $cf, 2);
                                if (!WC2_Utils::is_blank($meta_key)) {
                                    array_push($meta_key_table, $this->convert_encoding($meta_key));
                                }
                            }
                        }
                        $meta_key_table = apply_filters('wc2_filter_importitem_delete_postmeta', $meta_key_table);
                        $res = $wc2_item->delete_custome_field_key($meta_key_table);
                        if (false === $res) {
                            $this->error_log($row, __('Error : delete postmeta', 'wc2'));
                            $pre_item_code = $this->values[COL_ITEM_CODE];
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        //delete Item revisions
                        $res = $wc2_item->delete_item_revision();
                        if (false === $res) {
                            $this->error_log($row, __('Error : delete revisions', 'wc2'));
                            $pre_item_code = $this->values[COL_ITEM_CODE];
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        //delete relationships of category
                        $res = $wc2_item->delete_term_relationship();
                        if (false === $res) {
                            $this->error_log($row, __('Error : delete term_relationships(category)', 'wc2'));
                            $pre_item_code = $this->values[COL_ITEM_CODE];
                            $this->create_log();
                            $this->progress_add();
                            continue;
                        }
                        //delete relationships of tag
                        //$query = "SELECT term_taxonomy_id, COUNT(*) AS ct FROM {$wpdb->term_relationships} GROUP BY term_taxonomy_id";
                        //$relation_data = $wpdb->get_results( $query, ARRAY_A );
                        $relation_data = $wc2_item->get_count_term_taxonomy();
                        foreach ((array) $relation_data as $relation_rows) {
                            $term_taxonomy_where['term_taxonomy_id'] = $relation_rows['term_taxonomy_id'];
                            //	$term_taxonomy_id['term_taxonomy_id'] = $relation_rows['term_taxonomy_id'];
                            $term_taxonomy_updatas['count'] = $relation_rows['ct'];
                            if (false === $wpdb->update($wpdb->term_taxonomy, $term_taxonomy_updatas, $term_taxonomy_where)) {
                                $this->error_log($row, __('Error : delete term_relationships(tag)', 'wc2'));
                                $pre_item_code = $this->values[COL_ITEM_CODE];
                                continue;
                            }
                        }
                    }
                    //add term_relationships, edit term_taxonomy
                    //category
                    $categories = explode(';', $this->values[COL_POST_CATEGORY]);
                    $category_ids = array();
                    foreach ((array) $categories as $category) {
                        $cat = get_term_by('slug', $category, 'item');
                        if ($cat == false) {
                            $category = (string) $category;
                            $this->error_log($row, __(sprintf('Since the category slug "%s" does not exist or could not be category registration.', $this->convert_encoding($category)), 'wc2'));
                            continue;
                        }
                        $category_ids[] = $cat->term_id;
                    }
                    $term_taxonomy_ids = wp_set_post_terms($post_id, $category_ids, 'item');
                    foreach ($term_taxonomy_ids as $term_taxonomy_id) {
                        $wc2_item->term_taxonomy_count_post($term_taxonomy_id);
                    }
                    //tag
                    $tags_concat = str_replace(';', ',', $this->convert_encoding($this->values[COL_POST_TAG]));
                    $term_taxonomy_ids = wp_set_post_terms($post_id, $tags_concat, 'item-tag');
                    foreach ($term_taxonomy_ids as $term_taxonomy_id) {
                        $wc2_item->term_taxonomy_count_post($term_taxonomy_id);
                    }
                    //add custom field
                    $cfrows = explode(';', trim($this->values[COL_POST_CUSTOM_FIELD]));
                    //if( !(1 === count($cfrows) && '' == reset($cfrows)) ) {
                    if ('' != reset($cfrows)) {
                        $valstr = '';
                        foreach ($cfrows as $cf) {
                            list($meta_key, $meta_value) = explode('=', $cf, 2);
                            if (!WC2_Utils::is_blank($meta_key)) {
                                update_post_meta($post_id, $this->convert_encoding($meta_key), $this->convert_encoding($meta_value));
                            }
                        }
                    }
                    $wc2_item->clear_column();
                    //Item data set
                    $col = $start_col;
                    foreach ($item_base_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_value($key, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    foreach ($item_meta_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_value($key, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    //SKU data set
                    $col = $sku_start_col;
                    foreach ($item_sku_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_sku_value($key, $sku_id, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    foreach ($item_sku_meta_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_sku_value($key, $sku_id, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    if ($mode == 'add') {
                        $wc2_item->add_item_data();
                    } elseif ($mode == 'upd') {
                        $wc2_item->update_item_data();
                    }
                } else {
                    //sku登録のみの行
                    $sku_id++;
                    //SKU data set
                    $col = $sku_start_col;
                    foreach ($item_sku_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_sku_value($key, $sku_id, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    foreach ($item_sku_meta_column as $key => $column) {
                        if ($column['display'] != 'none' and $column['type'] != TYPE_PARENT) {
                            $wc2_item->set_the_item_sku_value($key, $sku_id, $this->set_value($col, $column['type']));
                            $col++;
                        }
                    }
                    $item_id = $wc2_item->get_item_id_by_post_id($post_id);
                    $sku_data = $wc2_item->get_item_sku_data($item_id, $sku_id);
                    if (0 == $wc2_item->count_sku_data($sku_id)) {
                        if (0 < $sku_id and '' != $wc2_item->get_the_item_sku_code($sku_id)) {
                            $res = $wc2_item->add_item_sku_data($sku_id, $wc2_item->get_item_sku_data($item_id, $sku_id));
                            if (false === $res) {
                                break;
                            }
                        }
                    } else {
                        $res = $wc2_item->update_item_sku_data($sku_id, $wc2_item->get_item_sku_data($item_id, $sku_id));
                        if (false === $res) {
                            break;
                        }
                    }
                }
                if ('' != $this->get_log_line()) {
                    $this->create_log();
                }
                //登録成功数加算
                $this->success += 1;
                $pre_item_code = $this->values[COL_ITEM_CODE];
                clean_post_cache($post_id);
                wp_cache_delete($post_id, 'posts');
                wp_cache_delete($post_id, 'post_meta');
                clean_object_term_cache($post_id, 'post');
                //進捗加算
                $this->progress_add();
            }
            wp_import_cleanup($this->id);
            $this->false = $this->data_rows - $this->success;
            echo '<h3>' . __('All Done.', 'wc2') . '</h3>
				  <h3>' . sprintf(__('Success %d failure %d', 'wc2'), $this->success, $this->false) . '</h3>';
            if (0 < strlen($this->log)) {
                WC2_Utils::wc2_log($this->log, "import_item.log");
                echo str_replace("\n", "<br />", $this->log);
            }
        }
 /**
  * Saves a doc.
  *
  * This method handles saving for both new and existing docs. It detects the difference by
  * looking for the presence of $this->doc_slug
  *
  * @since 1.0-beta
  */
 function save($args = false)
 {
     global $bp, $wp_rewrite;
     // bbPress plays naughty with revision saving
     add_action('pre_post_update', 'wp_save_post_revision');
     // Get the required taxonomy items associated with the group. We only run this
     // on a save because it requires extra database hits.
     $this->setup_terms();
     // Set up the default value for the result message
     $results = array('message' => __('Unknown error. Please try again.', 'bp-docs'), 'redirect' => 'create');
     // Backward compatibility. Had to change to doc_content to work with wp_editor
     $doc_content = '';
     if (isset($_POST['doc_content'])) {
         $doc_content = $_POST['doc_content'];
     } else {
         if (isset($_POST['doc']['content'])) {
             $doc_content = $_POST['doc']['content'];
         }
     }
     // Check group associations
     // @todo Move into group integration piece
     // This group id is only used to check whether the user can associate the doc with the group.
     $associated_group_id = isset($_POST['associated_group_id']) ? intval($_POST['associated_group_id']) : null;
     if (bp_is_active('groups')) {
         if (!empty($associated_group_id) && !current_user_can('bp_docs_associate_with_group', $associated_group_id)) {
             $retval = array('message_type' => 'error', 'message' => __('You are not allowed to associate a Doc with that group.', 'bp-docs'), 'redirect_url' => bp_docs_get_create_link());
             return $retval;
         }
     }
     if (empty($_POST['doc']['title'])) {
         // The title field is required
         $result['message'] = __('The title field is required.', 'bp-docs');
         $result['redirect'] = !empty($this->doc_slug) ? 'edit' : 'create';
     } else {
         $defaults = array('post_type' => $this->post_type_name, 'post_title' => $_POST['doc']['title'], 'post_name' => isset($_POST['doc']['permalink']) ? sanitize_title($_POST['doc']['permalink']) : sanitize_title($_POST['doc']['title']), 'post_content' => sanitize_post_field('post_content', $doc_content, 0, 'db'), 'post_status' => 'publish');
         $r = wp_parse_args($args, $defaults);
         if (empty($this->doc_slug)) {
             $this->is_new_doc = true;
             $r['post_author'] = bp_loggedin_user_id();
             // If there's a 'doc_id' value in the POST, use
             // the autodraft as a starting point
             if (isset($_POST['doc_id']) && 0 != $_POST['doc_id']) {
                 $post_id = (int) $_POST['doc_id'];
                 $r['ID'] = $post_id;
                 wp_update_post($r);
             } else {
                 $post_id = wp_insert_post($r);
             }
             if (!$post_id) {
                 $result['message'] = __('There was an error when creating the doc.', 'bp-docs');
                 $result['redirect'] = 'create';
             } else {
                 $this->doc_id = $post_id;
                 $the_doc = get_post($this->doc_id);
                 $this->doc_slug = $the_doc->post_name;
                 // A normal, successful save
                 $result['message'] = __('Doc successfully created!', 'bp-docs');
                 $result['redirect'] = 'single';
             }
         } else {
             $this->is_new_doc = false;
             $doc = bp_docs_get_current_doc();
             $this->doc_id = $doc->ID;
             $r['ID'] = $this->doc_id;
             // Make sure the post_name is set
             if (empty($r['post_name'])) {
                 $r['post_name'] = sanitize_title($r['post_title']);
             }
             // Make sure the post_name is unique
             $r['post_name'] = wp_unique_post_slug($r['post_name'], $this->doc_id, $r['post_status'], $this->post_type_name, $doc->post_parent);
             $this->doc_slug = $r['post_name'];
             // Save pre-update post data, for comparison by callbacks.
             $this->previous_revision = clone $doc;
             if (!wp_update_post($r)) {
                 $result['message'] = __('There was an error when saving the doc.', 'bp-docs');
                 $result['redirect'] = 'edit';
             } else {
                 // Remove the edit lock
                 delete_post_meta($this->doc_id, '_edit_lock');
                 delete_post_meta($this->doc_id, '_bp_docs_last_pinged');
                 // When the post has been autosaved, we need to leave a
                 // special success message
                 if (!empty($_POST['is_auto']) && $_POST['is_auto']) {
                     $result['message'] = __('You idled a bit too long while in Edit mode. In order to allow others to edit the doc you were working on, your changes have been autosaved. Click the Edit button to return to Edit mode.', 'bp-docs');
                 } else {
                     // A normal, successful save
                     $result['message'] = __('Doc successfully edited!', 'bp-docs');
                 }
                 $result['redirect'] = 'single';
             }
             $post_id = $this->doc_id;
         }
     }
     // If the Doc was successfully created, run some more stuff
     if (!empty($post_id)) {
         // Add to a group, if necessary
         if (!is_null($associated_group_id)) {
             bp_docs_set_associated_group_id($post_id, $associated_group_id);
         }
         // Make sure the current user is added as one of the authors
         wp_set_post_terms($post_id, $this->user_term_id, $this->associated_item_tax_name, true);
         // Save the last editor id. We'll use this to create an activity item
         update_post_meta($this->doc_id, 'bp_docs_last_editor', bp_loggedin_user_id());
         // Save settings
         bp_docs_save_doc_access_settings($this->doc_id);
         // Increment the revision count
         $revision_count = get_post_meta($this->doc_id, 'bp_docs_revision_count', true);
         update_post_meta($this->doc_id, 'bp_docs_revision_count', intval($revision_count) + 1);
     }
     // Provide a custom hook for plugins and optional components.
     // WP's default save_post isn't enough, because we need something that fires
     // only when we save from the front end (for things like taxonomies, which
     // the WP admin handles automatically)
     do_action('bp_docs_doc_saved', $this);
     do_action('bp_docs_after_save', $this->doc_id);
     $message_type = $result['redirect'] == 'single' ? 'success' : 'error';
     // Stuff data into a cookie so it can be accessed on next page load
     if ('error' === $message_type) {
         setcookie('bp-docs-submit-data', json_encode($_POST), time() + 30, '/');
     }
     $redirect_base = trailingslashit(bp_get_root_domain());
     if ($wp_rewrite->using_index_permalinks()) {
         $redirect_base .= 'index.php/';
     }
     $redirect_url = apply_filters('bp_docs_post_save_redirect_base', trailingslashit($redirect_base . bp_docs_get_docs_slug()));
     if ($result['redirect'] == 'single') {
         $redirect_url .= $this->doc_slug;
     } else {
         if ($result['redirect'] == 'edit') {
             $redirect_url .= $this->doc_slug . '/' . BP_DOCS_EDIT_SLUG;
         } else {
             if ($result['redirect'] == 'create') {
                 $redirect_url .= BP_DOCS_CREATE_SLUG;
             }
         }
     }
     $retval = array('message_type' => $message_type, 'message' => $result['message'], 'redirect_url' => $redirect_url);
     return $retval;
 }
Пример #8
0
/**
 * Ajax handler for Quick Edit saving a post from a list table.
 *
 * @since 3.1.0
 *
 * @global WP_List_Table $wp_list_table
 */
function wp_ajax_inline_save()
{
    global $wp_list_table, $mode;
    check_ajax_referer('inlineeditnonce', '_inline_edit');
    if (!isset($_POST['post_ID']) || !($post_ID = (int) $_POST['post_ID'])) {
        wp_die();
    }
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_ID)) {
            wp_die(__('You are not allowed to edit this page.'));
        }
    } else {
        if (!current_user_can('edit_post', $post_ID)) {
            wp_die(__('You are not allowed to edit this post.'));
        }
    }
    if ($last = wp_check_post_lock($post_ID)) {
        $last_user = get_userdata($last);
        $last_user_name = $last_user ? $last_user->display_name : __('Someone');
        printf($_POST['post_type'] == 'page' ? __('Saving is disabled: %s is currently editing this page.') : __('Saving is disabled: %s is currently editing this post.'), esc_html($last_user_name));
        wp_die();
    }
    $data =& $_POST;
    $post = get_post($post_ID, ARRAY_A);
    // Since it's coming from the database.
    $post = wp_slash($post);
    $data['content'] = $post['post_content'];
    $data['excerpt'] = $post['post_excerpt'];
    // Rename.
    $data['user_ID'] = get_current_user_id();
    if (isset($data['post_parent'])) {
        $data['parent_id'] = $data['post_parent'];
    }
    // Status.
    if (isset($data['keep_private']) && 'private' == $data['keep_private']) {
        $data['visibility'] = 'private';
        $data['post_status'] = 'private';
    } else {
        $data['post_status'] = $data['_status'];
    }
    if (empty($data['comment_status'])) {
        $data['comment_status'] = 'closed';
    }
    if (empty($data['ping_status'])) {
        $data['ping_status'] = 'closed';
    }
    // Exclude terms from taxonomies that are not supposed to appear in Quick Edit.
    if (!empty($data['tax_input'])) {
        foreach ($data['tax_input'] as $taxonomy => $terms) {
            $tax_object = get_taxonomy($taxonomy);
            /** This filter is documented in wp-admin/includes/class-wp-posts-list-table.php */
            if (!apply_filters('quick_edit_show_taxonomy', $tax_object->show_in_quick_edit, $taxonomy, $post['post_type'])) {
                unset($data['tax_input'][$taxonomy]);
            }
        }
    }
    // Hack: wp_unique_post_slug() doesn't work for drafts, so we will fake that our post is published.
    if (!empty($data['post_name']) && in_array($post['post_status'], array('draft', 'pending'))) {
        $post['post_status'] = 'publish';
        $data['post_name'] = wp_unique_post_slug($data['post_name'], $post['ID'], $post['post_status'], $post['post_type'], $post['post_parent']);
    }
    // Update the post.
    edit_post();
    $wp_list_table = _get_list_table('WP_Posts_List_Table', array('screen' => $_POST['screen']));
    $mode = $_POST['post_view'] === 'excerpt' ? 'excerpt' : 'list';
    $level = 0;
    $request_post = array(get_post($_POST['post_ID']));
    $parent = $request_post[0]->post_parent;
    while ($parent > 0) {
        $parent_post = get_post($parent);
        $parent = $parent_post->post_parent;
        $level++;
    }
    $wp_list_table->display_rows(array(get_post($_POST['post_ID'])), $level);
    wp_die();
}
 /**
  * Create a duplicate from a posts' instance
  */
 function duplicate_post_create_duplicate($post, $status = '')
 {
     $new_post_author = $this->duplicate_post_get_current_user();
     $new_post_status = $status;
     if (empty($new_post_status)) {
         $new_post_status = $post->post_status;
     }
     $new_post = array('menu_order' => $post->menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'pinged' => $post->pinged, 'post_author' => $new_post_author->ID, 'post_content' => $post->post_content, 'post_date' => $post->post_date, 'post_date_gmt' => get_gmt_from_date($post->post_date), 'post_excerpt' => $post->post_excerpt, 'post_parent' => $post->post_parent, 'post_password' => $post->post_password, 'post_status' => $new_post_status, 'post_title' => $post->post_title, 'post_type' => $post->post_type, 'to_ping' => $post->to_ping);
     $new_post_id = wp_insert_post($new_post);
     $edit_event_url = esc_attr(admin_url("post.php?post={$new_post_id}&action=edit"));
     $message = Ai1ec_Helper_Factory::create_admin_message_instance(sprintf(__('<p>The event <strong>%s</strong> was cloned succesfully. <a href="%s">Edit cloned event</a></p>', AI1EC_PLUGIN_NAME), $post->post_title, $edit_event_url));
     $message->set_message_type('updated');
     $this->admin_notice_helper->add_renderable_children($message);
     // If you have written a plugin which uses non-WP database tables to save
     // information about a post you can hook this action to dupe that data.
     if ($post->post_type == 'page' || function_exists('is_post_type_hierarchical') && is_post_type_hierarchical($post->post_type)) {
         do_action('dp_duplicate_page', $new_post_id, $post);
     } else {
         do_action('dp_duplicate_post', $new_post_id, $post);
     }
     delete_post_meta($new_post_id, '_dp_original');
     add_post_meta($new_post_id, '_dp_original', $post->ID);
     // If the copy gets immediately published, we have to set a proper slug.
     if ($new_post_status == 'publish' || $new_post_status == 'future') {
         $post_name = wp_unique_post_slug($post->post_name, $new_post_id, $new_post_status, $post->post_type, $post->post_parent);
         $new_post = array();
         $new_post['ID'] = $new_post_id;
         $new_post['post_name'] = $post_name;
         // Update the post into the database
         wp_update_post($new_post);
     }
     return $new_post_id;
 }
Пример #10
0
 /**
  * Create a duplicate from a post
  * @see https://wordpress.org/plugins/duplicate-post/
  */
 function duplicate($post, $status = 'draft', $parent_id = '')
 {
     // We don't want to clone revisions
     if ($post->post_type == 'revision') {
         return;
     }
     $new_post = array('menu_order' => $post->menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_author' => $post->ID, 'post_content' => $post->post_content, 'post_excerpt' => get_option('duplicate_post_copyexcerpt') == '1' ? $post->post_excerpt : "", 'post_mime_type' => $post->post_mime_type, 'post_parent' => $new_post_parent = empty($parent_id) ? $post->post_parent : $parent_id, 'post_password' => $post->post_password, 'post_status' => $new_post_status = empty($status) ? $post->post_status : $status, 'post_title' => $post->post_title, 'post_type' => $post->post_type);
     $new_post_id = wp_insert_post($new_post);
     // If the copy is published or scheduled, we have to set a proper slug.
     if ($new_post_status == 'publish' || $new_post_status == 'future') {
         $post_name = wp_unique_post_slug($post->post_name, $new_post_id, $new_post_status, $post->post_type, $new_post_parent);
         $new_post = array('ID' => $new_post_id, 'post_name' => $post_name);
         // Update the post into the database
         wp_update_post($new_post);
     }
     // If you have written a plugin which uses non-WP database tables to save
     // information about a post you can hook this action to dupe that data.
     if ($post->post_type == 'page' || is_post_type_hierarchical($post->post_type)) {
         do_action('dp_duplicate_page', $new_post_id, $post);
     } else {
         do_action('dp_duplicate_post', $new_post_id, $post);
     }
     delete_post_meta($new_post_id, '_dp_original');
     add_post_meta($new_post_id, '_dp_original', $post->ID);
     return $new_post_id;
 }
Пример #11
0
/**
 * {@internal Missing Short Description}}
 *
 * @since 2.5.0
 *
 * @param int|object $id    Post ID or post object.
 * @param string $title (optional) Title
 * @param string $name (optional) Name
 * @return array With two entries of type string
 */
function get_sample_permalink($id, $title = null, $name = null)
{
    $post = get_post($id);
    if (!$post) {
        return array('', '');
    }
    $ptype = get_post_type_object($post->post_type);
    $original_status = $post->post_status;
    $original_date = $post->post_date;
    $original_name = $post->post_name;
    // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
    if (in_array($post->post_status, array('draft', 'pending'))) {
        $post->post_status = 'publish';
        $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
    }
    // If the user wants to set a new name -- override the current one
    // Note: if empty name is supplied -- use the title instead, see #6072
    if (!is_null($name)) {
        $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
    }
    $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
    $post->filter = 'sample';
    $permalink = get_permalink($post, true);
    // Replace custom post_type Token with generic pagename token for ease of use.
    $permalink = str_replace("%{$post->post_type}%", '%pagename%', $permalink);
    // Handle page hierarchy
    if ($ptype->hierarchical) {
        $uri = get_page_uri($post);
        $uri = untrailingslashit($uri);
        $uri = strrev(stristr(strrev($uri), '/'));
        $uri = untrailingslashit($uri);
        $uri = apply_filters('editable_slug', $uri);
        if (!empty($uri)) {
            $uri .= '/';
        }
        $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
    }
    $permalink = array($permalink, apply_filters('editable_slug', $post->post_name));
    $post->post_status = $original_status;
    $post->post_date = $original_date;
    $post->post_name = $original_name;
    unset($post->filter);
    return $permalink;
}
/**
 * Create a duplicate from a post
 */
function duplicate_post_create_duplicate($post, $status = '', $parent_id = '')
{
    if (!duplicate_post_is_post_type_enabled($post->post_type) && $post->post_type != 'attachment') {
        wp_die(__('Copy features for this post type are not enabled in options page', 'duplicate-post'));
    }
    if ($post->post_type != 'attachment') {
        $prefix = sanitize_text_field(get_option('duplicate_post_title_prefix'));
        $suffix = sanitize_text_field(get_option('duplicate_post_title_suffix'));
        $title = ' ';
        if (get_option('duplicate_post_copytitle') == 1) {
            $title = $post->post_title;
            if (!empty($prefix)) {
                $prefix .= " ";
            }
            if (!empty($suffix)) {
                $suffix = " " . $suffix;
            }
        } else {
            $title = ' ';
        }
        $title = trim($prefix . $title . $suffix);
        if ($title == '') {
            // empty title
            $title = __('Untitled');
        }
        if (get_option('duplicate_post_copystatus') == 0) {
            $status = 'draft';
        }
    }
    $new_post_author = wp_get_current_user();
    $menu_order = $post->menu_order;
    $increase_menu_order_by = get_option('duplicate_post_increase_menu_order_by');
    if (!empty($increase_menu_order_by) && is_numeric($increase_menu_order_by)) {
        $menu_order += intval($increase_menu_order_by);
    }
    $new_post = array('menu_order' => $menu_order, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_author' => $new_post_author->ID, 'post_content' => get_option('duplicate_post_copycontent') == '1' ? addslashes($post->post_content) : "", 'post_content_filtered' => get_option('duplicate_post_copycontent') == '1' ? addslashes($post->post_content_filtered) : "", 'post_excerpt' => get_option('duplicate_post_copyexcerpt') == '1' ? addslashes($post->post_excerpt) : "", 'post_mime_type' => $post->post_mime_type, 'post_parent' => $new_post_parent = empty($parent_id) ? $post->post_parent : $parent_id, 'post_password' => get_option('duplicate_post_copypassword') == '1' ? $post->post_password : "", 'post_status' => $new_post_status = empty($status) ? $post->post_status : $status, 'post_title' => addslashes($title), 'post_type' => $post->post_type);
    if (get_option('duplicate_post_copydate') == 1) {
        $new_post['post_date'] = $new_post_date = $post->post_date;
        $new_post['post_date_gmt'] = get_gmt_from_date($new_post_date);
    }
    $new_post_id = wp_insert_post($new_post);
    // If the copy is published or scheduled, we have to set a proper slug.
    if ($new_post_status == 'publish' || $new_post_status == 'future') {
        $post_name = $post->post_name;
        if (get_option('duplicate_post_copyslug') != 1) {
            $post_name = '';
        }
        $post_name = wp_unique_post_slug($post_name, $new_post_id, $new_post_status, $post->post_type, $new_post_parent);
        $new_post = array();
        $new_post['ID'] = $new_post_id;
        $new_post['post_name'] = $post_name;
        // Update the post into the database
        wp_update_post($new_post);
    }
    // If you have written a plugin which uses non-WP database tables to save
    // information about a post you can hook this action to dupe that data.
    if ($post->post_type == 'page' || function_exists('is_post_type_hierarchical') && is_post_type_hierarchical($post->post_type)) {
        do_action('dp_duplicate_page', $new_post_id, $post);
    } else {
        do_action('dp_duplicate_post', $new_post_id, $post);
    }
    delete_post_meta($new_post_id, '_dp_original');
    add_post_meta($new_post_id, '_dp_original', $post->ID);
    return $new_post_id;
}
 function update_product_actions()
 {
     $nonce = filter_input(INPUT_POST, 'wcml_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
     if (!$nonce || !wp_verify_nonce($nonce, 'update_product_actions')) {
         echo json_encode(array('error' => __('Invalid nonce', 'wpml-wcml')));
         die;
     }
     global $woocommerce_wpml, $sitepress, $wpdb, $sitepress_settings, $iclTranslationManagement;
     //get post values
     $data = array();
     $records = $_POST['records'];
     parse_str($records, $data);
     $original_product_id = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT);
     $job_id = filter_input(INPUT_POST, 'job_id', FILTER_SANITIZE_NUMBER_INT);
     $language = filter_input(INPUT_POST, 'language', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
     $orig_product = get_post($original_product_id);
     if (!$data['title_' . $language]) {
         echo json_encode(array('error' => __('Title missing', 'wpml-wcml')));
         die;
     }
     $languages = $sitepress->get_active_languages();
     $product_trid = $sitepress->get_element_trid($original_product_id, 'post_' . $orig_product->post_type);
     $tr_product_id = apply_filters('translate_object_id', $original_product_id, 'product', false, $language);
     if (get_magic_quotes_gpc()) {
         foreach ($data as $key => $data_item) {
             if (!is_array($data_item)) {
                 $data[$key] = stripslashes($data_item);
             }
         }
     }
     if (is_null($tr_product_id)) {
         //insert new post
         $args = array();
         $args['post_title'] = $data['title_' . $language];
         $args['post_type'] = $orig_product->post_type;
         $args['post_content'] = $data['content_' . $language];
         $args['post_excerpt'] = $data['excerpt_' . $language];
         $args['post_status'] = $orig_product->post_status;
         $args['menu_order'] = $orig_product->menu_order;
         $args['ping_status'] = $orig_product->ping_status;
         $args['comment_status'] = $orig_product->comment_status;
         $product_parent = apply_filters('translate_object_id', $orig_product->post_parent, 'product', false, $language);
         $args['post_parent'] = is_null($product_parent) ? 0 : $product_parent;
         $_POST['to_lang'] = $language;
         if ($woocommerce_wpml->settings['products_sync_date']) {
             $args['post_date'] = $orig_product->post_date;
         }
         $tr_product_id = wp_insert_post($args);
         $translation_id = $wpdb->get_var($wpdb->prepare("SELECT translation_id\r\n                                                                  FROM {$wpdb->prefix}icl_translations\r\n                                                                  WHERE element_type=%s AND trid=%d AND language_code=%s AND element_id IS NULL ", "post_product", $product_trid, $language));
         if ($translation_id) {
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}icl_translations WHERE element_id=%d AND trid=%d", $tr_product_id, $product_trid));
             $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $tr_product_id), array('translation_id' => $translation_id));
             $iclTranslationManagement->update_translation_status(array('status' => ICL_TM_COMPLETE, 'needs_update' => 0, 'translation_id' => $translation_id, 'translator_id' => get_current_user_id()));
         } else {
             $sitepress->set_element_language_details($tr_product_id, 'post_' . $orig_product->post_type, $product_trid, $language);
         }
         $this->duplicate_product_post_meta($original_product_id, $tr_product_id, $data, true);
     } else {
         //update post
         $args = array();
         $args['ID'] = $tr_product_id;
         $args['post_title'] = $data['title_' . $language];
         $args['post_content'] = $data['content_' . $language];
         $args['post_excerpt'] = $data['excerpt_' . $language];
         $args['post_status'] = $orig_product->post_status;
         $args['ping_status'] = $orig_product->ping_status;
         $args['comment_status'] = $orig_product->comment_status;
         $product_parent = apply_filters('translate_object_id', $orig_product->post_parent, 'product', false, $language);
         $args['post_parent'] = is_null($product_parent) ? 0 : $product_parent;
         $_POST['to_lang'] = $language;
         wp_update_post($args);
         $post_name = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $tr_product_id));
         if (isset($data['post_name_' . $language]) && $post_name != $data['post_name_' . $language]) {
             // update post_name
             // need set POST variable ( WPML used them when filtered this function)
             $new_post_name = sanitize_title($data['post_name_' . $language] ? $data['post_name_' . $language] : $data['title_' . $language]);
             $_POST['new_title'] = $data['title_' . $language];
             $_POST['new_slug'] = $new_post_name;
             $new_slug = wp_unique_post_slug($new_post_name, $tr_product_id, $orig_product->post_status, $orig_product->post_type, $args['post_parent']);
             $wpdb->update($wpdb->posts, array('post_name' => $new_slug), array('ID' => $tr_product_id));
         }
         $sitepress->set_element_language_details($tr_product_id, 'post_' . $orig_product->post_type, $product_trid, $language);
         $this->duplicate_product_post_meta($original_product_id, $tr_product_id, $data);
     }
     do_action('wcml_update_extra_fields', $tr_product_id, $data, $language);
     do_action('wcml_before_sync_product_data', $original_product_id, $tr_product_id, $language);
     $this->sync_product_attr($original_product_id, $tr_product_id, $language, $data);
     $this->sync_default_product_attr($original_product_id, $tr_product_id, $language);
     $wpml_media_options = maybe_unserialize(get_option('_wpml_media'));
     //sync media
     if ($wpml_media_options['new_content_settings']['duplicate_featured']) {
         //sync feature image
         $this->sync_thumbnail_id($original_product_id, $tr_product_id, $language);
     }
     if ($wpml_media_options['new_content_settings']['duplicate_media']) {
         //sync product gallery
         $this->sync_product_gallery($original_product_id);
     }
     //sync taxonomies
     $this->sync_product_taxonomies($original_product_id, $tr_product_id, $language);
     // synchronize post variations
     $this->sync_product_variations($original_product_id, $tr_product_id, $language, $data);
     $this->sync_linked_products($original_product_id, $tr_product_id, $language);
     //save images texts
     if (isset($data['images'])) {
         foreach ($data['images'] as $key => $image) {
             //update image texts
             $wpdb->update($wpdb->posts, array('post_title' => $image['title'], 'post_content' => $image['description'], 'post_excerpt' => $image['caption']), array('id' => $key));
         }
     }
     $translations = $sitepress->get_element_translations($product_trid, 'post_product', false, false, true);
     if (ob_get_length()) {
         ob_clean();
     }
     ob_start();
     $return = array();
     $this->get_translation_statuses($translations, $languages, isset($_POST['slang']) && $_POST['slang'] != 'all' ? $_POST['slang'] : false, $product_trid, $job_id ? $language : false);
     $return['status'] = ob_get_clean();
     ob_start();
     $this->product_images_box($tr_product_id, $language);
     $return['images'][$language] = ob_get_clean();
     $is_variable_product = $this->is_variable_product($original_product_id);
     if ($is_variable_product && !$woocommerce_wpml->settings['file_path_sync'] && $woocommerce_wpml->settings['enable_multi_currency'] == WCML_MULTI_CURRENCIES_INDEPENDENT) {
         ob_start();
         $this->product_variations_box($tr_product_id, $language);
         $return['variations'][$language] = ob_get_clean();
     }
     // no longer a duplicate
     if (!empty($data['end_duplication'][$original_product_id][$language])) {
         delete_post_meta($tr_product_id, '_icl_lang_duplicate_of', $original_product_id);
     }
     $old_slug = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $tr_product_id));
     $return['slug'] = isset($new_slug) ? $new_slug : $old_slug;
     echo json_encode($return);
     die;
 }
function mc_generate_calendar_page($slug)
{
    global $current_user;
    get_currentuserinfo();
    if (!is_page($slug)) {
        $page = array('post_title' => __('My Calendar', 'my-calendar'), 'post_status' => 'publish', 'post_type' => 'page', 'post_author' => $current_user->ID, 'ping_status' => 'closed', 'post_content' => '[my_calendar]');
        $post_ID = wp_insert_post($page);
        $post_slug = wp_unique_post_slug($slug, $post_ID, 'publish', 'page', 0);
        wp_update_post(array('ID' => $post_ID, 'post_name' => $post_slug));
    } else {
        $post = get_page_by_path($slug);
        $post_ID = $post->ID;
    }
    update_option('mc_uri', get_permalink($post_ID));
    update_option('mc_uri_id', $post_ID);
    return $post_ID;
}
Пример #15
0
 /**
  * Copy the attachments
  * It simply copies the table entries, actual file won't be duplicated
  */
 protected function _duplicate_post_copy_attachments($new_id, $post)
 {
     //if (get_option('duplicate_post_copyattachments') == 0) return;
     // get old attachments
     $attachments = get_posts(array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID));
     // clone old attachments
     foreach ($attachments as $att) {
         $new_att_author = $this->_duplicate_post_get_current_user();
         $new_att = array('menu_order' => $att->menu_order, 'comment_status' => $att->comment_status, 'guid' => $att->guid, 'ping_status' => $att->ping_status, 'pinged' => $att->pinged, 'post_author' => $new_att_author->ID, 'post_content' => $att->post_content, 'post_date' => $att->post_date, 'post_date_gmt' => get_gmt_from_date($att->post_date), 'post_excerpt' => $att->post_excerpt, 'post_mime_type' => $att->post_mime_type, 'post_parent' => $new_id, 'post_password' => $att->post_password, 'post_status' => $this->_get_new_post_status($att->post_status), 'post_title' => $att->post_title, 'post_type' => $att->post_type, 'to_ping' => $att->to_ping);
         $new_att_id = wp_insert_post($new_att);
         // get and apply a unique slug
         $att_name = wp_unique_post_slug($att->post_name, $new_att_id, $att->post_status, $att->post_type, $new_id);
         $new_att = array();
         $new_att['ID'] = $new_att_id;
         $new_att['post_name'] = $att_name;
         wp_update_post($new_att);
     }
 }
Пример #16
0
/**
 * Update all dependent data if achievement type name has changed.
 *
 * @since  1.4.0
 *
 * @param  array $data      Post data.
 * @param  array $post_args Post args.
 * @return array            Updated post data.
 */
function badgeos_maybe_update_achievement_type($data = array(), $post_args = array())
{
    if (badgeos_achievement_type_changed($post_args)) {
        $original_type = get_post($post_args['ID'])->post_name;
        $new_type = wp_unique_post_slug(sanitize_title($post_args['post_title']), $post_args['ID'], $post_args['post_status'], $post_args['post_type'], $post_args['post_parent']);
        $data['post_name'] = badgeos_update_achievement_types($original_type, $new_type);
        add_filter('redirect_post_location', 'badgeos_achievement_type_rename_redirect', 99);
    }
    return $data;
}
Пример #17
0
 function woocommerce_duplicate_product($new_id, $post)
 {
     global $sitepress, $wpdb;
     //duplicate original first
     $trid = $sitepress->get_element_trid($post->ID, 'post_' . $post->post_type);
     $orig_id = $sitepress->get_original_element_id_by_trid($trid);
     $orig_lang = $this->get_original_product_language($post->ID);
     $wc_admin = new WC_Admin_Duplicate_Product();
     if ($orig_id == $post->ID) {
         $sitepress->set_element_language_details($new_id, 'post_' . $post->post_type, false, $orig_lang);
         $new_trid = $sitepress->get_element_trid($new_id, 'post_' . $post->post_type);
         $new_orig_id = $new_id;
     } else {
         $post_to_duplicate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID=%d", $orig_id));
         if (!empty($post_to_duplicate)) {
             $new_orig_id = $wc_admin->duplicate_product($post_to_duplicate);
             do_action('wcml_after_duplicate_product', $new_id, $post_to_duplicate);
             $sitepress->set_element_language_details($new_orig_id, 'post_' . $post->post_type, false, $orig_lang);
             $new_trid = $sitepress->get_element_trid($new_orig_id, 'post_' . $post->post_type);
             update_post_meta($new_id, '_icl_lang_duplicate_of', $new_orig_id);
             $sitepress->set_element_language_details($new_id, 'post_' . $post->post_type, $new_trid, $sitepress->get_current_language());
         }
     }
     $translations = $sitepress->get_element_translations($trid, 'post_' . $post->post_type);
     if ($translations) {
         foreach ($translations as $translation) {
             if (!$translation->original && $translation->element_id != $post->ID) {
                 $post_to_duplicate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID=%d", $translation->element_id));
                 if (!empty($post_to_duplicate)) {
                     $new_id = $wc_admin->duplicate_product($post_to_duplicate);
                     $new_id_obj = get_post($new_id);
                     $new_slug = wp_unique_post_slug(sanitize_title($new_id_obj->post_title), $new_id, $post_to_duplicate->post_status, $post_to_duplicate->post_type, $new_id_obj->post_parent);
                     $wpdb->update($wpdb->posts, array('post_name' => $new_slug), array('ID' => $new_id));
                     do_action('wcml_after_duplicate_product', $new_id, $post_to_duplicate);
                     $sitepress->set_element_language_details($new_id, 'post_' . $post->post_type, $new_trid, $translation->language_code);
                     update_post_meta($new_id, '_icl_lang_duplicate_of', $new_orig_id);
                 }
             }
         }
     }
 }
 /**
  * @ticket 5305
  */
 public function test_daylike_slugs_should_not_be_suffixed_for_invalid_day_numbers()
 {
     global $wp_rewrite;
     $wp_rewrite->init();
     $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%postname%/');
     $wp_rewrite->flush_rules();
     $p = $this->factory->post->create(array('post_type' => 'post', 'post_name' => 'foo'));
     $found = wp_unique_post_slug('32', $p, 'publish', 'post', 0);
     $this->assertEquals('32', $found);
     $wp_rewrite->set_permalink_structure('');
     flush_rewrite_rules();
 }
 /**
  * @ticket 5305
  */
 public function test_daylike_slugs_should_not_be_suffixed_for_invalid_day_numbers()
 {
     $this->set_permalink_structure('/%year%/%monthnum%/%postname%/');
     $p = self::factory()->post->create(array('post_type' => 'post', 'post_name' => 'foo'));
     $found = wp_unique_post_slug('32', $p, 'publish', 'post', 0);
     $this->assertEquals('32', $found);
 }
Пример #20
0
function wp_ajax_inline_save()
{
    global $wp_list_table;
    check_ajax_referer('inlineeditnonce', '_inline_edit');
    if (!isset($_POST['post_ID']) || !($post_ID = (int) $_POST['post_ID'])) {
        wp_die();
    }
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_ID)) {
            wp_die(__('You are not allowed to edit this page.'));
        }
    } else {
        if (!current_user_can('edit_post', $post_ID)) {
            wp_die(__('You are not allowed to edit this post.'));
        }
    }
    if ($last = wp_check_post_lock($post_ID)) {
        $last_user = get_userdata($last);
        $last_user_name = $last_user ? $last_user->display_name : __('Someone');
        printf($_POST['post_type'] == 'page' ? __('Saving is disabled: %s is currently editing this page.') : __('Saving is disabled: %s is currently editing this post.'), esc_html($last_user_name));
        wp_die();
    }
    $data =& $_POST;
    $post = get_post($post_ID, ARRAY_A);
    $post = wp_slash($post);
    //since it is from db
    $data['content'] = $post['post_content'];
    $data['excerpt'] = $post['post_excerpt'];
    // rename
    $data['user_ID'] = get_current_user_id();
    if (isset($data['post_parent'])) {
        $data['parent_id'] = $data['post_parent'];
    }
    // Status.
    if (isset($data['keep_private']) && 'private' == $data['keep_private']) {
        $data['visibility'] = 'private';
        $data['post_status'] = 'private';
    } else {
        $data['post_status'] = $data['_status'];
    }
    if (empty($data['comment_status'])) {
        $data['comment_status'] = 'closed';
    }
    if (empty($data['ping_status'])) {
        $data['ping_status'] = 'closed';
    }
    // Hack: wp_unique_post_slug() doesn't work for drafts, so we will fake that our post is published.
    if (!empty($data['post_name']) && in_array($post['post_status'], array('draft', 'pending'))) {
        $post['post_status'] = 'publish';
        $data['post_name'] = wp_unique_post_slug($data['post_name'], $post['ID'], $post['post_status'], $post['post_type'], $post['post_parent']);
    }
    // update the post
    edit_post();
    $wp_list_table = _get_list_table('WP_Posts_List_Table', array('screen' => $_POST['screen']));
    $mode = $_POST['post_view'];
    $level = 0;
    $request_post = array(get_post($_POST['post_ID']));
    $parent = $request_post[0]->post_parent;
    while ($parent > 0) {
        $parent_post = get_post($parent);
        $parent = $parent_post->post_parent;
        $level++;
    }
    $wp_list_table->display_rows(array(get_post($_POST['post_ID'])), $level);
    wp_die();
}
Пример #21
0
/**
 * Get a sample permalink based off of the post name.
 *
 * @since 2.5.0
 *
 * @param int    $id    Post ID or post object.
 * @param string $title Optional. Title to override the post's current title when generating the post name. Default null.
 * @param string $name  Optional. Name to override the post name. Default null.
 * @return array Array containing the sample permalink with placeholder for the post name, and the post name.
 */
function get_sample_permalink($id, $title = null, $name = null)
{
    $post = get_post($id);
    if (!$post) {
        return array('', '');
    }
    $ptype = get_post_type_object($post->post_type);
    $original_status = $post->post_status;
    $original_date = $post->post_date;
    $original_name = $post->post_name;
    // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
    if (in_array($post->post_status, array('draft', 'pending', 'future'))) {
        $post->post_status = 'publish';
        $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
    }
    // If the user wants to set a new name -- override the current one
    // Note: if empty name is supplied -- use the title instead, see #6072
    if (!is_null($name)) {
        $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
    }
    $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
    $post->filter = 'sample';
    $permalink = get_permalink($post, true);
    // Replace custom post_type Token with generic pagename token for ease of use.
    $permalink = str_replace("%{$post->post_type}%", '%pagename%', $permalink);
    // Handle page hierarchy
    if ($ptype->hierarchical) {
        $uri = get_page_uri($post);
        if ($uri) {
            $uri = untrailingslashit($uri);
            $uri = strrev(stristr(strrev($uri), '/'));
            $uri = untrailingslashit($uri);
        }
        /** This filter is documented in wp-admin/edit-tag-form.php */
        $uri = apply_filters('editable_slug', $uri, $post);
        if (!empty($uri)) {
            $uri .= '/';
        }
        $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
    }
    /** This filter is documented in wp-admin/edit-tag-form.php */
    $permalink = array($permalink, apply_filters('editable_slug', $post->post_name, $post));
    $post->post_status = $original_status;
    $post->post_date = $original_date;
    $post->post_name = $original_name;
    unset($post->filter);
    /**
     * Filters the sample permalink.
     *
     * @since 4.4.0
     *
     * @param array   $permalink Array containing the sample permalink with placeholder for the post name, and the post name.
     * @param int     $post_id   Post ID.
     * @param string  $title     Post title.
     * @param string  $name      Post name (slug).
     * @param WP_Post $post      Post object.
     */
    return apply_filters('get_sample_permalink', $permalink, $post->ID, $title, $name, $post);
}
Пример #22
0
 /**
  * Handles saving updates from the product editor
  *
  * Saves all product related information which includes core product data
  * and supporting elements such as images, digital downloads, tags,
  * assigned categories, specs and pricing variations.
  *
  * @author Jonathan Davis
  * @since 1.0
  *
  * @param Product $Product
  * @return void
  **/
 public function save(ShoppProduct $Product)
 {
     check_admin_referer('shopp-save-product');
     if (!current_user_can('shopp_products')) {
         wp_die(__('You do not have sufficient permissions to access this page.'));
     }
     ShoppSettings()->saveform();
     // Save workflow setting
     $status = $Product->status;
     // Set publish date
     if ('publish' == $_POST['status']) {
         $publishing = isset($_POST['publish']) ? $_POST['publish'] : array();
         $fields = array('month' => '', 'date' => '', 'year' => '', 'hour' => '', 'minute' => '', 'meridiem' => '');
         $publishdate = join('', array_merge($fields, $publishing));
         if (!empty($publishdate)) {
             $publish =& $_POST['publish'];
             if ($publish['meridiem'] == "PM" && $publish['hour'] < 12) {
                 $publish['hour'] += 12;
             }
             $publish = mktime($publish['hour'], $publish['minute'], 0, $publish['month'], $publish['date'], $publish['year']);
             $Product->status = 'future';
             unset($_POST['status']);
         } else {
             unset($_POST['publish']);
             // Auto set the publish date if not set (or more accurately, if set to an irrelevant timestamp)
             if ($Product->publish <= 86400) {
                 $Product->publish = null;
             }
         }
     } else {
         unset($_POST['publish']);
         $Product->publish = 0;
     }
     // Set a unique product slug
     if (empty($Product->slug)) {
         $Product->slug = sanitize_title($_POST['name']);
     }
     $Product->slug = wp_unique_post_slug($Product->slug, $Product->id, $Product->status, ShoppProduct::posttype(), 0);
     $Product->featured = 'off';
     if (isset($_POST['content'])) {
         $_POST['description'] = $_POST['content'];
     }
     $Product->updates($_POST, array('meta', 'categories', 'prices', 'tags'));
     do_action('shopp_pre_product_save');
     $Product->save();
     // Remove deleted images
     if (!empty($_POST['deleteImages'])) {
         $deletes = array();
         if (strpos($_POST['deleteImages'], ",") !== false) {
             $deletes = explode(',', $_POST['deleteImages']);
         } else {
             $deletes = array($_POST['deleteImages']);
         }
         $Product->delete_images($deletes);
     }
     // Update image data
     if (!empty($_POST['images']) && is_array($_POST['images'])) {
         $Product->link_images($_POST['images']);
         $Product->save_imageorder($_POST['images']);
         if (!empty($_POST['imagedetails'])) {
             $Product->update_images($_POST['imagedetails']);
         }
     }
     // Update Prices
     if (!empty($_POST['price']) && is_array($_POST['price'])) {
         // Delete prices that were marked for removal
         if (!empty($_POST['deletePrices'])) {
             $deletes = array();
             if (strpos($_POST['deletePrices'], ",")) {
                 $deletes = explode(',', $_POST['deletePrices']);
             } else {
                 $deletes = array($_POST['deletePrices']);
             }
             foreach ($deletes as $option) {
                 $Price = new ShoppPrice($option);
                 $Price->delete();
             }
         }
         $Product->resum();
         // Save prices that there are updates for
         foreach ($_POST['price'] as $i => $priceline) {
             if (empty($priceline['id'])) {
                 $Price = new ShoppPrice();
                 $priceline['product'] = $Product->id;
             } else {
                 $Price = new ShoppPrice($priceline['id']);
             }
             $priceline['sortorder'] = array_search($i, $_POST['sortorder']) + 1;
             $priceline['shipfee'] = Shopp::floatval($priceline['shipfee']);
             if (isset($priceline['recurring']['trialprice'])) {
                 $priceline['recurring']['trialprice'] = Shopp::floatval($priceline['recurring']['trialprice']);
             }
             if ($Price->stock != $priceline['stocked']) {
                 $priceline['stock'] = (int) $priceline['stocked'];
                 do_action('shopp_stock_product', $priceline['stock'], $Price, $Price->stock, $Price->stocklevel);
             } else {
                 unset($priceline['stocked']);
             }
             $Price->updates($priceline);
             $Price->save();
             // Save 'price' meta records after saving the price record
             if (isset($priceline['dimensions']) && is_array($priceline['dimensions'])) {
                 $priceline['dimensions'] = array_map(array('Shopp', 'floatval'), $priceline['dimensions']);
             }
             $settings = array('donation', 'recurring', 'membership', 'dimensions');
             $priceline['settings'] = array();
             foreach ($settings as $setting) {
                 if (!isset($priceline[$setting])) {
                     continue;
                 }
                 $priceline['settings'][$setting] = $priceline[$setting];
             }
             if (!empty($priceline['settings'])) {
                 shopp_set_meta($Price->id, 'price', 'settings', $priceline['settings']);
             }
             if (!empty($priceline['options'])) {
                 shopp_set_meta($Price->id, 'price', 'options', $priceline['options']);
             }
             $Product->sumprice($Price);
             if (!empty($priceline['download'])) {
                 $Price->attach_download($priceline['download']);
             }
             if (!empty($priceline['downloadpath'])) {
                 // Attach file specified by URI/path
                 if (!empty($Price->download->id) || empty($Price->download) && $Price->load_download()) {
                     $File = $Price->download;
                 } else {
                     $File = new ProductDownload();
                 }
                 $stored = false;
                 $tmpfile = sanitize_path($priceline['downloadpath']);
                 $File->storage = false;
                 $Engine = $File->engine();
                 // Set engine from storage settings
                 $File->parent = $Price->id;
                 $File->context = "price";
                 $File->type = "download";
                 $File->name = !empty($priceline['downloadfile']) ? $priceline['downloadfile'] : basename($tmpfile);
                 $File->filename = $File->name;
                 if ($File->found($tmpfile)) {
                     $File->uri = $tmpfile;
                     $stored = true;
                 } else {
                     $stored = $File->store($tmpfile, 'file');
                 }
                 if ($stored) {
                     $File->readmeta();
                     $File->save();
                 }
             }
             // END attach file by path/uri
         }
         // END foreach()
         unset($Price);
     }
     // END if (!empty($_POST['price']))
     $Product->load_sold($Product->id);
     // Refresh accurate product sales stats
     $Product->sumup();
     // Update taxonomies after pricing summary is generated
     // Summary table entry is needed for ProductTaxonomy::recount() to
     // count properly based on aggregate product inventory, see #2968
     foreach (get_object_taxonomies(Product::$posttype) as $taxonomy) {
         $tags = '';
         $taxonomy_obj = get_taxonomy($taxonomy);
         if (isset($_POST['tax_input']) && isset($_POST['tax_input'][$taxonomy])) {
             $tags = $_POST['tax_input'][$taxonomy];
             if (is_array($tags)) {
                 // array = hierarchical, string = non-hierarchical.
                 $tags = array_filter($tags);
             }
         }
         if (current_user_can($taxonomy_obj->cap->assign_terms)) {
             wp_set_post_terms($Product->id, $tags, $taxonomy);
         }
     }
     // Ensure taxonomy counts are updated on status changes, see #2968
     if ($status != $_POST['status']) {
         $Post = new StdClass();
         $Post->ID = $Product->id;
         $Post->post_type = ShoppProduct::$posttype;
         wp_transition_post_status($_POST['status'], $Product->status, $Post);
     }
     if (!empty($_POST['meta']['options'])) {
         $_POST['meta']['options'] = stripslashes_deep($_POST['meta']['options']);
     } else {
         $_POST['meta']['options'] = false;
     }
     // No variation options at all, delete all variation-pricelines
     if (!empty($Product->prices) && is_array($Product->prices) && (empty($_POST['meta']['options']['v']) || empty($_POST['meta']['options']['a']))) {
         foreach ($Product->prices as $priceline) {
             // Skip if not tied to variation options
             if ($priceline->optionkey == 0) {
                 continue;
             }
             if (empty($_POST['meta']['options']['v']) && $priceline->context == "variation" || empty($_POST['meta']['options']['a']) && $priceline->context == "addon") {
                 $Price = new ShoppPrice($priceline->id);
                 $Price->delete();
             }
         }
     }
     // Handle product spec/detail data
     if (!empty($_POST['details']) || !empty($_POST['deletedSpecs'])) {
         // Delete specs queued for removal
         $ids = array();
         $deletes = array();
         if (!empty($_POST['deletedSpecs'])) {
             if (strpos($_POST['deleteImages'], ",") !== false) {
                 $deletes = explode(',', $_POST['deleteImages']);
             } else {
                 $deletes = array($_POST['deletedSpecs']);
             }
             $ids = db::escape($_POST['deletedSpecs']);
             $Spec = new Spec();
             db::query("DELETE FROM {$Spec->_table} WHERE id IN ({$ids})");
         }
         if (is_array($_POST['details'])) {
             foreach ($_POST['details'] as $i => $spec) {
                 if (in_array($spec['id'], $deletes)) {
                     continue;
                 }
                 if (isset($spec['new'])) {
                     $Spec = new Spec();
                     $spec['id'] = '';
                     $spec['parent'] = $Product->id;
                 } else {
                     $Spec = new Spec($spec['id']);
                 }
                 $spec['sortorder'] = array_search($i, $_POST['details-sortorder']) + 1;
                 $Spec->updates($spec);
                 $Spec->save();
             }
         }
     }
     // Save any meta data
     if (isset($_POST['meta']) && is_array($_POST['meta'])) {
         foreach ($_POST['meta'] as $name => $value) {
             if (isset($Product->meta[$name])) {
                 $Meta = $Product->meta[$name];
                 if (is_array($Meta)) {
                     $Meta = reset($Product->meta[$name]);
                 }
             } else {
                 $Meta = new ShoppMetaObject(array('parent' => $Product->id, 'context' => 'product', 'type' => 'meta', 'name' => $name));
             }
             $Meta->parent = $Product->id;
             $Meta->name = $name;
             $Meta->value = $value;
             $Meta->save();
         }
     }
     $Product->load_data();
     // Reload data so everything is fresh for shopp_product_saved
     do_action_ref_array('shopp_product_saved', array(&$Product));
     unset($Product);
 }
 /**
  * Create a duplicate from a post
  */
 function duplicate_post_create_duplicate($post_to_dup, $status = '', $parent_id = '', $to_post_id = '')
 {
     // We don't want to clone revisions
     if ($post_to_dup->post_type == 'revision') {
         return;
     }
     if ($to_post_id != '') {
         $to_post = get_post($to_post_id);
         if (!$to_post) {
             return;
         }
     }
     if ($post_to_dup->post_type != 'attachment') {
         $prefix = $this->get_option('duplicate_post_title_prefix');
         $suffix = $this->get_option('duplicate_post_title_suffix');
         if (!empty($prefix)) {
             $prefix .= " ";
         }
         if (!empty($suffix)) {
             $suffix = " " . $suffix;
         }
         if ($this->get_option('duplicate_post_copystatus') == 0) {
             $status = 'draft';
         }
     }
     $new_post_author = $this->duplicate_post_get_current_user();
     $new_post = array('menu_order' => $post_to_dup->menu_order, 'comment_status' => $post_to_dup->comment_status, 'ping_status' => $post_to_dup->ping_status, 'post_author' => $new_post_author->ID, 'post_content' => $post_to_dup->post_content, 'post_excerpt' => $this->get_option('duplicate_post_copyexcerpt') == '1' ? $post_to_dup->post_excerpt : "", 'post_mime_type' => $post_to_dup->post_mime_type, 'post_parent' => $new_post_parent = empty($parent_id) ? $post_to_dup->post_parent : $parent_id, 'post_password' => $post_to_dup->post_password, 'post_status' => $new_post_status = empty($status) ? $post_to_dup->post_status : $status, 'post_title' => $prefix . $post_to_dup->post_title . $suffix, 'post_type' => $post_to_dup->post_type);
     if ($to_post_id != '') {
         $new_post["post_title"] = $to_post->post_title;
         $new_post["post_status"] = $to_post->post_status;
         $new_post["ID"] = $to_post_id;
     }
     if ($this->get_option('duplicate_post_copydate') == 1 && empty($to_post_id)) {
         $new_post['post_date'] = $new_post_date = $post_to_dup->post_date;
         $new_post['post_date_gmt'] = get_gmt_from_date($new_post_date);
     } else {
         if (!empty($to_post_id)) {
             // We are merging back, do not override publish date
             $new_post['post_date'] = $new_post_date = $to_post->post_date;
             $new_post['post_date_gmt'] = get_gmt_from_date($new_post_date);
         }
     }
     $new_post_id = wp_insert_post($new_post);
     delete_post_meta($new_post_id, '_dp_original_backup');
     // If the copy is published or scheduled, we have to set a proper slug.
     if ($to_post_id == '') {
         if ($new_post_status == 'publish' || $new_post_status == 'future') {
             $post_to_dup_name = wp_unique_post_slug($post_to_dup->post_name, $new_post_id, $new_post_status, $post_to_dup->post_type, $new_post_parent);
             $new_post = array();
             $new_post['ID'] = $new_post_id;
             $new_post['post_name'] = $post_to_dup_name;
             // Update the post into the database
             wp_update_post($new_post);
         }
     }
     // If you have written a plugin which uses non-WP database tables to save
     // information about a post you can hook this action to dupe that data.
     if ($post_to_dup->post_type == 'page' || function_exists('is_post_type_hierarchical') && is_post_type_hierarchical($post_to_dup->post_type)) {
         do_action('dp_duplicate_page', $new_post_id, $post_to_dup);
     } else {
         do_action('dp_duplicate_post', $new_post_id, $post_to_dup);
     }
     if ($to_post_id == '') {
         delete_post_meta($new_post_id, '_dp_original');
         add_post_meta($new_post_id, '_dp_original', $post_to_dup->ID);
     } else {
         wp_delete_post($post_to_dup->ID);
     }
     return $new_post_id;
 }
Пример #24
0
function popmake_set_popup_slug($data, $postarr)
{
    if ($data['post_type'] == 'popup') {
        $popup_name = popmake_post('popup_name');
        $post_slug = sanitize_title_with_dashes($popup_name, null, 'save');
        $data['post_name'] = wp_unique_post_slug(sanitize_title(popmake_post('popup_name')), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent']);
    }
    return $data;
}
Пример #25
0
/**
 * Insert or update a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, by setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * @since 1.0.0
 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
 *
 * @see sanitize_post()
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array $postarr {
 *     An array of elements that make up a post to update or insert.
 *
 *     @type int    $ID                    The post ID. If equal to something other than 0,
 *                                         the post with that ID will be updated. Default 0.
 *     @type int    $post_author           The ID of the user who added the post. Default is
 *                                         the current user ID.
 *     @type string $post_date             The date of the post. Default is the current time.
 *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
 *                                         the value of `$post_date`.
 *     @type mixed  $post_content          The post content. Default empty.
 *     @type string $post_content_filtered The filtered post content. Default empty.
 *     @type string $post_title            The post title. Default empty.
 *     @type string $post_excerpt          The post excerpt. Default empty.
 *     @type string $post_status           The post status. Default 'draft'.
 *     @type string $post_type             The post type. Default 'post'.
 *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_comment_status' option.
 *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_ping_status' option.
 *     @type string $post_password         The password to access the post. Default empty.
 *     @type string $post_name             The post name. Default is the sanitized post title.
 *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
 *                                         Default empty.
 *     @type string $pinged                Space or carriage return-separated list of URLs that have
 *                                         been pinged. Default empty.
 *     @type string $post_modified         The date when the post was last modified. Default is
 *                                         the current time.
 *     @type string $post_modified_gmt     The date when the post was last modified in the GMT
 *                                         timezone. Default is the current time.
 *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
 *     @type int    $menu_order            The order the post should be displayed in. Default 0.
 *     @type string $post_mime_type        The mime type of the post. Default empty.
 *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
 *     @type array  $tax_input             Array of taxonomy terms keyed by their taxonomy name. Default empty.
 *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
 * }
 * @param bool  $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_author' => $user_id, 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => '', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'import_id' => 0, 'context' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'db');
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    $guid = $postarr['guid'];
    if (!empty($postarr['ID'])) {
        $update = true;
        // Get the post ID and GUID.
        $post_ID = $postarr['ID'];
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $post_ID);
    } else {
        $previous_status = 'new';
    }
    $post_type = empty($postarr['post_type']) ? 'post' : $postarr['post_type'];
    $post_title = $postarr['post_title'];
    $post_content = $postarr['post_content'];
    $post_excerpt = $postarr['post_excerpt'];
    if (isset($postarr['post_name'])) {
        $post_name = $postarr['post_name'];
    }
    $maybe_empty = 'attachment' !== $post_type && !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    /**
     * Filter whether the post should be considered "empty".
     *
     * The post is considered "empty" if both:
     * 1. The post type supports the title, editor, and excerpt fields
     * 2. The title, editor, and excerpt fields are all empty
     *
     * Returning a truthy value to the filter will effectively short-circuit
     * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
     * will be returned instead.
     *
     * @since 3.3.0
     *
     * @param bool  $maybe_empty Whether the post should be considered "empty".
     * @param array $postarr     Array of post data.
     */
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    $post_status = empty($postarr['post_status']) ? 'draft' : $postarr['post_status'];
    if ('attachment' === $post_type && !in_array($post_status, array('inherit', 'private', 'trash'))) {
        $post_status = 'inherit';
    }
    if (!empty($postarr['post_category'])) {
        // Filter out empty terms.
        $post_category = array_filter($postarr['post_category']);
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Don't allow contributors to set the post slug for pending review posts.
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    /*
     * Create a valid post name. Drafts and pending posts are allowed to have
     * an empty post name.
     */
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $post_ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    /*
     * If the post date is empty (due to having been new or a draft) and status
     * is not 'draft' or 'pending', set date to now.
     */
    if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
        if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
            $post_date = current_time('mysql');
        } else {
            $post_date = get_date_from_gmt($postarr['post_date_gmt']);
        }
    } else {
        $post_date = $postarr['post_date'];
    }
    // Validate the date.
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    } else {
        $post_date_gmt = $postarr['post_date_gmt'];
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('attachment' !== $post_type) {
        if ('publish' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
                $post_status = 'future';
            }
        } elseif ('future' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
                $post_status = 'publish';
            }
        }
    }
    // Comment status.
    if (empty($postarr['comment_status'])) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_default_comment_status($post_type);
        }
    } else {
        $comment_status = $postarr['comment_status'];
    }
    // These variables are needed by compact() later.
    $post_content_filtered = $postarr['post_content_filtered'];
    $post_author = isset($postarr['post_author']) ? $postarr['post_author'] : $user_id;
    $ping_status = empty($postarr['ping_status']) ? get_default_comment_status($post_type, 'pingback') : $postarr['ping_status'];
    $to_ping = isset($postarr['to_ping']) ? sanitize_trackback_urls($postarr['to_ping']) : '';
    $pinged = isset($postarr['pinged']) ? $postarr['pinged'] : '';
    $import_id = isset($postarr['import_id']) ? $postarr['import_id'] : 0;
    /*
     * The 'wp_insert_post_parent' filter expects all variables to be present.
     * Previously, these variables would have already been extracted
     */
    if (isset($postarr['menu_order'])) {
        $menu_order = (int) $postarr['menu_order'];
    } else {
        $menu_order = 0;
    }
    $post_password = isset($postarr['post_password']) ? $postarr['post_password'] : '';
    if ('private' == $post_status) {
        $post_password = '';
    }
    if (isset($postarr['post_parent'])) {
        $post_parent = (int) $postarr['post_parent'];
    } else {
        $post_parent = 0;
    }
    /**
     * Filter the post parent -- used to check for and prevent hierarchy loops.
     *
     * @since 3.1.0
     *
     * @param int   $post_parent Post parent ID.
     * @param int   $post_ID     Post ID.
     * @param array $new_postarr Array of parsed post data.
     * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
     */
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // Don't unslash.
    $post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
    // Expected_slashed (everything!).
    $data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
    $emoji_fields = array('post_title', 'post_content', 'post_excerpt');
    foreach ($emoji_fields as $emoji_field) {
        if (isset($data[$emoji_field])) {
            $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
            if ('utf8' === $charset) {
                $data[$emoji_field] = wp_encode_emoji($data[$emoji_field]);
            }
        }
    }
    if ('attachment' === $post_type) {
        /**
         * Filter attachment post data before it is updated in or added to the database.
         *
         * @since 3.9.0
         *
         * @param array $data    An array of sanitized attachment post data.
         * @param array $postarr An array of unsanitized attachment post data.
         */
        $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
    } else {
        /**
         * Filter slashed post data just before it is inserted into the database.
         *
         * @since 2.7.0
         *
         * @param array $data    An array of slashed post data.
         * @param array $postarr An array of sanitized, but otherwise unmodified post data.
         */
        $data = apply_filters('wp_insert_post_data', $data, $postarr);
    }
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        /**
         * Fires immediately before an existing post is updated in the database.
         *
         * @since 2.5.0
         *
         * @param int   $post_ID Post ID.
         * @param array $data    Array of unslashed post data.
         */
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        // If there is a suggested ID, use it if not already present.
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // Use the newly generated $post_ID.
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title'], $post_ID), $post_ID, $data['post_status'], $post_type, $post_parent);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
        clean_post_cache($post_ID);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($postarr['tags_input']) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $postarr['tags_input']);
    }
    // New-style support for all custom taxonomies.
    if (!empty($postarr['tax_input'])) {
        foreach ($postarr['tax_input'] as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (!$taxonomy_obj) {
                /* translators: %s: taxonomy name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('Invalid taxonomy: %s.'), $taxonomy), '4.4.0');
                continue;
            }
            // array = hierarchical, string = non-hierarchical.
            if (is_array($tags)) {
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if (!empty($postarr['meta_input'])) {
        foreach ($postarr['meta_input'] as $field => $value) {
            update_post_meta($post_ID, $field, $value);
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID.
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    if ('attachment' === $postarr['post_type']) {
        if (!empty($postarr['file'])) {
            update_attached_file($post_ID, $postarr['file']);
        }
        if (!empty($postarr['context'])) {
            add_post_meta($post_ID, '_wp_attachment_context', $postarr['context'], true);
        }
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    if (!empty($postarr['page_template']) && 'page' == $data['post_type']) {
        $post->page_template = $postarr['page_template'];
        $page_templates = wp_get_theme()->get_page_templates($post);
        if ('default' != $postarr['page_template'] && !isset($page_templates[$postarr['page_template']])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            }
            update_post_meta($post_ID, '_wp_page_template', 'default');
        } else {
            update_post_meta($post_ID, '_wp_page_template', $postarr['page_template']);
        }
    }
    if ('attachment' !== $postarr['post_type']) {
        wp_transition_post_status($data['post_status'], $previous_status, $post);
    } else {
        if ($update) {
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('edit_attachment', $post_ID);
            $post_after = get_post($post_ID);
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 4.4.0
             *
             * @param int     $post_ID      Post ID.
             * @param WP_Post $post_after   Post object following the update.
             * @param WP_Post $post_before  Post object before the update.
             */
            do_action('attachment_updated', $post_ID, $post_after, $post_before);
        } else {
            /**
             * Fires once an attachment has been added.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('add_attachment', $post_ID);
        }
        return $post_ID;
    }
    if ($update) {
        /**
         * Fires once an existing post has been updated.
         *
         * @since 1.2.0
         *
         * @param int     $post_ID Post ID.
         * @param WP_Post $post    Post object.
         */
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        /**
         * Fires once an existing post has been updated.
         *
         * @since 3.0.0
         *
         * @param int     $post_ID      Post ID.
         * @param WP_Post $post_after   Post object following the update.
         * @param WP_Post $post_before  Post object before the update.
         */
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    /**
     * Fires once a post has been saved.
     *
     * The dynamic portion of the hook name, `$post->post_type`, refers to
     * the post type slug.
     *
     * @since 3.7.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 1.5.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('save_post', $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 2.0.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
Пример #26
0
/**
 * Insert an attachment.
 *
 * If you set the 'ID' in the $object parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 *
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 *
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 *
 * The $object parameter can have the following:
 *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
 *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
 *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
 *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
 *                       can accept pings.
 *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
 *                       to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Attachment post content filtered.
 *     'post_excerpt'  - Attachment excerpt.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
 *
 * @param string|array $object Arguments to override defaults.
 * @param string $file Optional filename.
 * @param int $parent Parent post ID.
 * @return int Attachment ID.
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '', 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    unset($object['filter']);
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    $post_type = 'attachment';
    if (!in_array($post_status, array('inherit', 'private'))) {
        $post_status = 'inherit';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        $post_category = array();
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid'));
    $data = wp_unslash($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    // support for all custom taxonomies
    if (!empty($tax_input)) {
        foreach ($tax_input as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (is_array($tags)) {
                // array = hierarchical, string = non-hierarchical.
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (!empty($context)) {
        add_post_meta($post_ID, '_wp_attachment_context', $context, true);
    }
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
 function save_post_actions($pidd, $post)
 {
     if ($post->post_type == 'view-template' && $post->post_status == 'draft') {
         // force the publish state.
         global $wpdb;
         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} \n\t\t\t\t\tSET post_status = 'publish' \n\t\t\t\t\tWHERE ID = %d", $pidd));
         $post_name = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} \n\t\t\t\t\tWHERE ID = %d \n\t\t\t\t\tLIMIT 1", $pidd));
         if (!isset($post_name) || empty($post_name)) {
             $candidate_slug = sanitize_title($_POST['post_title']);
             $slug = wp_unique_post_slug($candidate_slug, $pidd, 'publish', 'view-template', 0);
             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} \n\t\t\t\t\t\tSET post_name = %s \n\t\t\t\t\t\tWHERE ID = %d", $slug, $pidd));
         }
     }
     // Make sure it's on the Content Template editor page before saving info.
     // Otherwise inline CT editor will delete info it shouldn't.
     if ($post->post_type == 'view-template' && isset($_POST['_wpv_view_template_mode'])) {
         if (isset($_POST['_wpv-content-template-decription'])) {
             update_post_meta($pidd, '_wpv-content-template-decription', $_POST['_wpv-content-template-decription']);
         } else {
             update_post_meta($pidd, '_wpv-content-template-decription', '');
         }
         if (isset($_POST['_wpv_view_template_mode'][0])) {
             update_post_meta($pidd, '_wpv_view_template_mode', $_POST['_wpv_view_template_mode'][0]);
             // @todo maybe DEPRECATE this
             wpv_view_template_update_field_values($pidd);
         }
         if (isset($_POST['_wpv_view_template_extra_css'])) {
             update_post_meta($pidd, '_wpv_view_template_extra_css', $_POST['_wpv_view_template_extra_css']);
         }
         if (isset($_POST['_wpv_view_template_extra_js'])) {
             update_post_meta($pidd, '_wpv_view_template_extra_js', $_POST['_wpv_view_template_extra_js']);
         }
         $template_meta_html_state = array();
         if (isset($_POST['_wpv_view_template_extra_state']['css'])) {
             $template_meta_html_state['css'] = $_POST['_wpv_view_template_extra_state']['css'];
         }
         if (isset($_POST['_wpv_view_template_extra_state']['js'])) {
             $template_meta_html_state['js'] = $_POST['_wpv_view_template_extra_state']['js'];
         }
         if (!empty($template_meta_html_state)) {
             update_post_meta($pidd, '_wpv_view_template_extra_state', $template_meta_html_state);
         }
         if (isset($_POST['show_highlight'])) {
             $user_id = get_current_user_id();
             $show_highlight = esc_attr($_POST['show_highlight']);
             update_user_meta($user_id, 'show_highlight', $show_highlight);
         }
         if (isset($_POST['show_help'])) {
             $show_help = esc_attr($_POST['show_help']);
             update_option('wpv_content_template_show_help', $show_help);
         }
         //Save settings toggle status
         if (isset($_POST['_wpv_content_template_settings_toggle_single'])) {
             update_post_meta($pidd, '_wpv_content_template_settings_toggle_single', $_POST['_wpv_content_template_settings_toggle_single']);
         }
         if (isset($_POST['_wpv_content_template_settings_toggle_posts'])) {
             update_post_meta($pidd, '_wpv_content_template_settings_toggle_posts', $_POST['_wpv_content_template_settings_toggle_posts']);
         }
         if (isset($_POST['_wpv_content_template_settings_toggle_taxonomy'])) {
             update_post_meta($pidd, '_wpv_content_template_settings_toggle_taxonomy', $_POST['_wpv_content_template_settings_toggle_taxonomy']);
         }
         //Save settings
         global $WPV_settings;
         $this->clear_legacy_view_settings();
         // clear all options that have this template id
         foreach ($WPV_settings as $key => $value) {
             if ($value == $pidd) {
                 $WPV_settings[$key] = 0;
             }
         }
         foreach ($_POST as $index => $value) {
             if (strpos($index, 'views_template_loop_') === 0) {
                 $WPV_settings[$index] = $pidd;
             }
             if (strpos($index, 'views_template_for_') === 0) {
                 $WPV_settings[$index] = $pidd;
             }
             if (strpos($index, 'views_template_archive_for_') === 0) {
                 $WPV_settings[$index] = $pidd;
             }
         }
         $WPV_settings->save();
         do_action('wpv_action_wpv_save_item', $pidd);
     }
     if ($post->post_type == 'view-template') {
         wpv_register_wpml_strings($post->post_content);
     }
     // pass to the base class.
     parent::save_post_actions($pidd, $post);
 }
 /**
  * Function to create the duplicate of the product.
  *
  * @param mixed $post
  * @param int $parent (default: 0)
  * @param string $post_status (default: '')
  * @return int
  */
 public function duplicate_product($post, $parent = 0, $post_status = '')
 {
     global $wpdb;
     $new_post_author = wp_get_current_user();
     $new_post_date = current_time('mysql');
     $new_post_date_gmt = get_gmt_from_date($new_post_date);
     if ($parent > 0) {
         $post_parent = $parent;
         $post_status = $post_status ? $post_status : 'publish';
         $suffix = '';
         $post_title = $post->post_title;
     } else {
         $post_parent = $post->post_parent;
         $post_status = $post_status ? $post_status : 'draft';
         $suffix = ' ' . __('(Copy)', 'woocommerce');
         $post_title = $post->post_title . $suffix;
     }
     // Insert the new template in the post table
     $wpdb->insert($wpdb->posts, array('post_author' => $new_post_author->ID, 'post_date' => $new_post_date, 'post_date_gmt' => $new_post_date_gmt, 'post_content' => $post->post_content, 'post_content_filtered' => $post->post_content_filtered, 'post_title' => $post_title, 'post_excerpt' => $post->post_excerpt, 'post_status' => $post_status, 'post_type' => $post->post_type, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_password' => $post->post_password, 'to_ping' => $post->to_ping, 'pinged' => $post->pinged, 'post_modified' => $new_post_date, 'post_modified_gmt' => $new_post_date_gmt, 'post_parent' => $post_parent, 'menu_order' => $post->menu_order, 'post_mime_type' => $post->post_mime_type));
     $new_post_id = $wpdb->insert_id;
     // Set title for variations
     if ('product_variation' === $post->post_type) {
         $post_title = sprintf(__('Variation #%1$s of %2$s', 'woocommerce'), absint($new_post_id), esc_html(get_the_title($post_parent)));
         $wpdb->update($wpdb->posts, array('post_title' => $post_title), array('ID' => $new_post_id));
     }
     // Set name and GUID
     if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
         $wpdb->update($wpdb->posts, array('post_name' => wp_unique_post_slug(sanitize_title($post_title, $new_post_id), $new_post_id, $post_status, $post->post_type, $post_parent), 'guid' => get_permalink($new_post_id)), array('ID' => $new_post_id));
     }
     // Copy the taxonomies
     $this->duplicate_post_taxonomies($post->ID, $new_post_id, $post->post_type);
     // Copy the meta information
     $this->duplicate_post_meta($post->ID, $new_post_id);
     // Copy the children (variations)
     $exclude = apply_filters('woocommerce_duplicate_product_exclude_children', false);
     if (!$exclude && ($children_products = get_children('post_parent=' . $post->ID . '&post_type=product_variation'))) {
         foreach ($children_products as $child) {
             $this->duplicate_product($this->get_product_to_duplicate($child->ID), $new_post_id, $child->post_status);
         }
     }
     // Clear cache
     clean_post_cache($new_post_id);
     return $new_post_id;
 }
Пример #29
0
/**
 * Insert an attachment.
 *
 * If you set the 'ID' in the $object parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 *
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 *
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 *
 * The $object parameter can have the following:
 *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
 *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
 *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
 *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
 *                       can accept pings.
 *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
 *                       to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Attachment post content filtered.
 *     'post_excerpt'  - Attachment excerpt.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses $user_ID
 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
 *
 * @param string|array $object Arguments to override defaults.
 * @param string $file Optional filename.
 * @param int $parent Parent post ID.
 * @return int Attachment ID.
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_type = 'attachment';
    $post_status = 'inherit';
    // Make sure we set a valid category.
    if (!isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid'));
    $data = stripslashes_deep($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    wp_set_post_categories($post_ID, $post_category);
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (isset($post_parent) && $post_parent < 0) {
        add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
    }
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
 /**
  * Build data for group.
  *
  * Build data to importing group.
  *
  * @since 1.6.6
  * @access private
  *
  * @param string $group_name Group name
  * @param object $group Group data
  *
  * @return object data for import
  */
 private function get_data($group_name, $groups)
 {
     $this->reset_toolset_edit_last_list[$group_name] = array();
     $date = date('Y-m-d H:i');
     $new = array();
     foreach ($groups as $group) {
         if (isset($this->args['force_skip_post_name'][$group_name]) && in_array($group->__types_id, $this->args['force_skip_post_name'][$group_name])) {
             continue;
         }
         if (isset($this->args['force_import_post_name'][$group_name]) && in_array($group->__types_id, $this->args['force_import_post_name'][$group_name])) {
             $new[] = $group;
             switch ($group_name) {
                 case 'wp-types-group':
                     $this->fields += explode(',', $group->meta->_wp_types_group_fields);
                     break;
                 case 'wp-types-user-group':
                     $this->user_fields += explode(',', $group->meta->_wp_types_group_fields);
                     break;
             }
             $this->reset_toolset_edit_last_list[$group_name][] = $group->__types_id;
             continue;
         }
         if (isset($this->args['force_duplicate_post_name'][$group_name]) && in_array($group->__types_id, $this->args['force_duplicate_post_name'][$group_name])) {
             $one = $group;
             $one->__types_id = wp_unique_post_slug(sanitize_title_with_dashes($group->post_title, null, 'save'), null, 'publish', 'wp-types-group', null);
             $one->__types_title = $one->post_title = sprintf('%s %s', $group->post_title, $date);
             $new[$one->__types_id] = $one;
             continue;
         }
     }
     return $new;
 }