function test_sanitize_meta() { $meta = sanitize_meta('some_meta', 'unsanitized', 'post'); $this->assertEquals('unsanitized', $meta); register_meta('post', 'some_meta', array($this, '_meta_sanitize_cb')); $meta = sanitize_meta('some_meta', 'unsanitized', 'post'); $this->assertEquals('sanitized', $meta); }
function circleflip_multimenu_save_metabox($page_ID, $page, $update) { if (!current_user_can('edit_page', $page_ID) || !isset($_POST['circleflip_multimenu_menu']) || !isset($_POST['circleflip_multimenu_nonce']) || !wp_verify_nonce($_POST['circleflip_multimenu_nonce'], 'circleflip-multimenu-save')) { return; } $_override_menu = sanitize_meta('_circleflip_multimenu', $_POST['circleflip_multimenu_menu'], 'page'); update_post_meta($page_ID, '_circleflip_multimenu', $_override_menu); }
function circleflip_headerBuilder_save_metabox($page_ID, $page, $update) { if (!current_user_can('edit_page', $page_ID) || !isset($_POST['circleflip_headerBuilder_menu']) || !isset($_POST['circleflip_headerBuilder_nonce']) || !wp_verify_nonce($_POST['circleflip_headerBuilder_nonce'], 'circleflip-headerBuilder-save')) { return; } $_override_menu = sanitize_meta('_circleflip_headerBuilder', $_POST['circleflip_headerBuilder_menu'], 'page'); $_override_slider = sanitize_meta('_circleflip_headerBuilder_slider', $_POST['circleflip_headerBuilder_slider'], 'page'); update_post_meta($page_ID, '_circleflip_headerBuilder', $_override_menu); update_post_meta($page_ID, '_circleflip_headerBuilder_slider', $_override_slider); }
public static function update_meta($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { if (!$meta_type || !$meta_key) { return false; } if (!($object_id = absint($object_id))) { return false; } if (!($table = self::_get_table_name($meta_type))) { return false; } global $wpdb; $column = esc_sql($meta_type . '_id'); $id_column = apply_filters('qsot-meta-id-field', 'meta_id', $meta_type); // expected_slashed ($meta_key) $meta_key = stripslashes($meta_key); $passed_value = $meta_value; $meta_value = stripslashes_deep($meta_value); $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type); if (null !== ($check = apply_filters("update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value))) { return (bool) $check; } if (!($meta_id = $wpdb->get_var($wpdb->prepare("SELECT {$id_column} FROM {$table} WHERE meta_key = %s AND {$column} = %d", $meta_key, $object_id)))) { return self::add_meta($meta_type, $object_id, $meta_key, $passed_value); } // Compare existing value to new value if no prev value given and the key exists only once. if (empty($prev_value)) { $old_value = self::get_meta($meta_type, $object_id, $meta_key); if (count($old_value) == 1 && $old_value[0] === $meta_value) { return false; } } $_meta_value = $meta_value; $meta_value = self::_maybe_json_encode($meta_value); $data = compact('meta_value'); $where = array($column => $object_id, 'meta_key' => $meta_key); if (!empty($prev_value)) { $prev_value = self::_maybe_json_encode($prev_value); $where['meta_value'] = $prev_value; } do_action("update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); $wpdb->update($table, $data, $where); wp_cache_delete($object_id, $meta_type . '_meta'); do_action("updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); return true; }
/** * Update metadata for the specified object. If no value already exists for the specified object * ID and metadata key, the metadata will be added. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of * metadata entry to update, object ID, meta key, and meta value * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of * updated metadata entry, object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param string $meta_value Metadata value * @param string $prev_value Optional. If specified, only update existing metadata entries with * the specified value. Otherwise, update all entries. * @return bool True on successful update, false on failure. */ function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { if (!$meta_type || !$meta_key) { return false; } if (!($object_id = absint($object_id))) { return false; } if (!($table = _get_meta_table($meta_type))) { return false; } global $wpdb; $column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) $meta_key = stripslashes($meta_key); $meta_value = stripslashes_deep($meta_value); $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type); $check = apply_filters("update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value); if (null !== $check) { return (bool) $check; } if (!($meta_id = $wpdb->get_var($wpdb->prepare("SELECT {$id_column} FROM {$table} WHERE meta_key = %s AND {$column} = %d", $meta_key, $object_id)))) { return add_metadata($meta_type, $object_id, $meta_key, $meta_value); } // Compare existing value to new value if no prev value given and the key exists only once. if (empty($prev_value)) { $old_value = get_metadata($meta_type, $object_id, $meta_key); if (count($old_value) == 1) { if ($old_value[0] === $meta_value) { return false; } } } $_meta_value = $meta_value; $meta_value = maybe_serialize($meta_value); $data = compact('meta_value'); $where = array($column => $object_id, 'meta_key' => $meta_key); if (!empty($prev_value)) { $prev_value = maybe_serialize($prev_value); $where['meta_value'] = $prev_value; } do_action("update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); $wpdb->update($table, $data, $where); wp_cache_delete($object_id, $meta_type . '_meta'); // users cache stores usermeta that must be cleared. if ('user' == $meta_type) { clean_user_cache($object_id); } do_action("updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); return true; }
/** * Update a meta field. * * ## OPTIONS * * <id> * : The ID of the object. * * <key> * : The name of the meta field to update. * * [<value>] * : The new value. If ommited, the value is read from STDIN. * * [--format=<format>] * : The serialization format for the value. Default is plaintext. * * @alias set */ public function update($args, $assoc_args) { list($object_id, $meta_key) = $args; $meta_value = WP_CLI::get_value_from_arg_or_stdin($args, 2); $meta_value = WP_CLI::read_value($meta_value, $assoc_args); $object_id = $this->check_object_id($object_id); $meta_value = sanitize_meta($meta_key, $meta_value, $this->meta_type); $old_value = sanitize_meta($meta_key, get_metadata($this->meta_type, $object_id, $meta_key, true), $this->meta_type); if ($meta_value === $old_value) { WP_CLI::success("Value passed for custom field '{$meta_key}' is unchanged."); } else { $success = update_metadata($this->meta_type, $object_id, $meta_key, $meta_value); if ($success) { WP_CLI::success("Updated custom field '{$meta_key}'."); } else { WP_CLI::error("Failed to update custom field '{$meta_key}'."); } } }
/** * Save the user's meta fields. * * @param array $submitted The submitted values. * @param array $keys The keys of fields that are to be updated. * @return int Number of fields updated. * @access public * @since 1.0.0 */ public function update_user_meta($submitted, $keys) { /* Exclude the core keys */ $mapped_keys = $this->get_mapped_keys(); $meta_fields = array_diff($keys, $this->get_core_keys()); $updated = 0; foreach ($meta_fields as $field) { if (isset($submitted[$field])) { $meta_key = array_key_exists($field, $mapped_keys) ? $mapped_keys[$field] : $field; $meta_value = sanitize_meta($meta_key, $submitted[$field], 'user'); update_user_meta($this->ID, $meta_key, $meta_value); $updated++; } } return $updated; }
* check if single Docu */ global $post; $post_type = get_post_type($post->ID); // check if we're using polylang plugin if (function_exists('pll_register_string')) { // get button text setting value from polylang $pdfbutton_text = pll__('PDF Button'); } else { $pdfbutton_text = sanitize_option('dkpdf_pdfbutton_text', get_option('dkpdf_pdfbutton_text', 'PDF Button')); } $pdfbutton_align = sanitize_option('dkpdf_pdfbutton_align', get_option('dkpdf_pdfbutton_align', 'right')); ?> <?php $hide_pdfbutton = sanitize_meta('_hide_pdfbutton', get_post_meta($post->ID, '_hide_pdfbutton'), 'checkbox'); // only show button if _hide_pdfbutton post meta is not checked if (!$hide_pdfbutton) { ?> <div class="dkpdf-button-container" style="text-align:<?php echo $pdfbutton_align; ?> "> <a class="dkpdf-button" href="<?php echo esc_url(add_query_arg('pdf', $post->ID)); ?> " target="_blank"><span class="dkpdf-button-icon"><i class="fa fa-file-pdf-o"></i></span> <?php echo $pdfbutton_text; ?>
/** * Update metadata for the specified object. If no value already exists for the specified object * ID and metadata key, the metadata will be added. * * @uses $wpdb WordPress database object for queries. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param mixed $meta_value Metadata value. Must be serializable if non-scalar. * @param mixed $prev_value Optional. If specified, only update existing metadata entries with * the specified value. Otherwise, update all entries. * * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure. */ function fw_update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { global $wpdb; if (!$meta_type || !$meta_key || !is_numeric($object_id)) { return false; } $object_id = absint($object_id); if (!$object_id) { return false; } $table = _get_meta_table($meta_type); if (!$table) { return false; } $column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) //$meta_key = wp_unslash($meta_key); $passed_value = $meta_value; //$meta_value = wp_unslash($meta_value); $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type); /** * Filter whether to update metadata of a specific type. * * The dynamic portion of the hook, $meta_type, refers to the meta * object type (comment, post, or user). Returning a non-null value * will effectively short-circuit the function. * * @param null|bool $check Whether to allow updating metadata for the given type. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. Must be serializable if non-scalar. * @param mixed $prev_value Optional. If specified, only update existing * metadata entries with the specified value. * Otherwise, update all entries. */ $check = apply_filters("update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value); if (null !== $check) { return (bool) $check; } // Compare existing value to new value if no prev value given and the key exists only once. if (empty($prev_value)) { $old_value = get_metadata($meta_type, $object_id, $meta_key); if (count($old_value) == 1) { if ($old_value[0] === $meta_value) { return false; } } } if (!($meta_id = $wpdb->get_var($wpdb->prepare("SELECT {$id_column} FROM {$table} WHERE meta_key = %s AND {$column} = %d LIMIT 1", $meta_key, $object_id)))) { return fw_add_metadata($meta_type, $object_id, $meta_key, $passed_value); } $_meta_value = $meta_value; $meta_value = maybe_serialize($meta_value); $data = compact('meta_value'); $where = array($column => $object_id, 'meta_key' => $meta_key); if (!empty($prev_value)) { $prev_value = maybe_serialize($prev_value); $where['meta_value'] = $prev_value; } /** * Fires immediately before updating metadata of a specific type. * * The dynamic portion of the hook, $meta_type, refers to the meta * object type (comment, post, or user). * * @param int $meta_id ID of the metadata entry to update. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. */ do_action("update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); if ('post' == $meta_type) { do_action('update_postmeta', $meta_id, $object_id, $meta_key, $meta_value); } $result = $wpdb->update($table, $data, $where); if (!$result) { return false; } wp_cache_delete($object_id, $meta_type . '_meta'); /** * Fires immediately after updating metadata of a specific type. * * The dynamic portion of the hook, $meta_type, refers to the meta * object type (comment, post, or user). * * @param int $meta_id ID of updated metadata entry. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. */ do_action("updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); if ('post' == $meta_type) { /** * Fires immediately after updating a post's metadata. * * @param int $meta_id ID of updated metadata entry. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. */ do_action('updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value); } return true; }
/** * Module Settings * * Generates settings based on default values and user values * * @since 1.0 */ function dslc_module_settings($options, $custom = false) { // Array to hold the settings. $settings = array(); // Go through all options. foreach ($options as $option) { if (isset($_POST[$option['id']])) { /** * Extension developers can decide for themselves * what escaping function to use for a particular option id. * * See switch block below for available options. */ $default_settings_escape_function = 'esc_attr'; $custom_settings_escape_function = $default_settings_escape_function; $custom_settings_escape_function = apply_filters('dslc_module_settings_cleaning_function', $default_settings_escape_function, $option['id']); // If value set use it? if ('content' === $option['id']) { $settings[$option['id']] = wp_kses_post($_POST[$option['id']]); } elseif ($custom_settings_escape_function !== $default_settings_escape_function) { switch ($custom_settings_escape_function) { case 'wp_kses_post': $settings[$option['id']] = wp_kses_post($_POST[$option['id']]); break; case 'sanitize_email': $settings[$option['id']] = sanitize_email($_POST[$option['id']]); break; case 'sanitize_file_name': $settings[$option['id']] = sanitize_file_name($_POST[$option['id']]); break; case 'sanitize_html_class': $settings[$option['id']] = sanitize_html_class($_POST[$option['id']]); break; case 'sanitize_key': $settings[$option['id']] = sanitize_key($_POST[$option['id']]); break; case 'sanitize_meta': $settings[$option['id']] = sanitize_meta($_POST[$option['id']]); break; case 'sanitize_text_field': $settings[$option['id']] = sanitize_text_field($_POST[$option['id']]); break; case 'sanitize_title': $settings[$option['id']] = sanitize_title($_POST[$option['id']]); break; case 'esc_html': $settings[$option['id']] = esc_html($_POST[$option['id']]); break; case 'esc_url': $settings[$option['id']] = esc_url($_POST[$option['id']]); break; case 'esc_js': $settings[$option['id']] = esc_js($_POST[$option['id']]); break; case 'esc_textarea': $settings[$option['id']] = esc_textarea($_POST[$option['id']]); break; default: $settings[$option['id']] = esc_attr($_POST[$option['id']]); break; } } else { $settings[$option['id']] = esc_attr($_POST[$option['id']]); } } else { // If value not set use default? $settings[$option['id']] = $option['std']; } } return $settings; }
/** * Create new posts based on import information */ public function process_product($post) { global $wpdb; wp_suspend_cache_invalidation(true); $merging = !empty($post['merging']) && $post['merging'] ? true : false; $processing_product_id = absint($post['post_id']); $insert_meta_data = array(); if (empty($post['post_parent'])) { $this->add_import_result('skipped', __('No product variation parent set', 'woocommerce-product-csv-import-suite'), $processing_product_id, 'Not set', $post['sku']); WC_Product_CSV_Import_Suite::log(__('> Skipping - no post parent set.', 'woocommerce-product-csv-import-suite')); return; } if (!empty($processing_product_id) && isset($this->processed_posts[$processing_product_id])) { $this->add_import_result('skipped', __('Product variation already processed', 'woocommerce-product-csv-import-suite'), $processing_product_id, get_the_title($post['post_parent']), $post['sku']); WC_Product_CSV_Import_Suite::log(__('> Post ID already processed. Skipping.', 'woocommerce-product-csv-import-suite')); return; } if ($post['post_status'] == 'auto-draft') { $this->add_import_result('skipped', __('Skipping auto-draft', 'woocommerce-product-csv-import-suite'), $processing_product_id, get_the_title($post['post_parent']), $post['sku']); WC_Product_CSV_Import_Suite::log(__('> Skipping auto-draft.', 'woocommerce-product-csv-import-suite')); return; } $post_parent = (int) $post['post_parent']; $post_parent_exists = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $post_parent)); if (!$post_parent_exists) { $this->add_import_result('failed', __('Variation parent does not exist', 'woocommerce-product-csv-import-suite'), $processing_product_id, 'Does not exist', $post['sku']); WC_Product_CSV_Import_Suite::log(sprintf(__('> Variation parent does not exist! (#%d)', 'woocommerce-product-csv-import-suite'), $post_parent)); return; } // Check post type to avoid conflicts with IDs if ($merging && get_post_type($processing_product_id) !== 'product_variation') { $this->add_import_result('skipped', __('Post is not a product variation', 'woocommerce-product-csv-import-suite'), $processing_product_id, 'Not a variation', $post['sku']); WC_Product_CSV_Import_Suite::log(sprintf(__('> “%s” is not a product variation.', 'woocommerce-product-csv-import-suite'), $processing_product_id), true); unset($post); return; } if ($merging) { // Only merge fields which are set $post_id = $processing_product_id; WC_Product_CSV_Import_Suite::log(sprintf(__('> Merging post ID %s.', 'woocommerce-product-csv-import-suite'), $post_id)); $postdata = array('ID' => $post_id); if (!empty($post['post_date'])) { $postdata['post_date'] = date("Y-m-d H:i:s", strtotime($post['post_date'])); } if (!empty($post['post_date_gmt'])) { $postdata['post_date_gmt'] = date("Y-m-d H:i:s", strtotime($post['post_date_gmt'])); } if (!empty($post['post_status'])) { $postdata['post_status'] = $post['post_status']; } if (!empty($post['menu_order'])) { $postdata['menu_order'] = $post['menu_order']; } $postdata['post_parent'] = $post_parent; if (sizeof($postdata)) { if (wp_update_post($postdata)) { WC_Product_CSV_Import_Suite::log(__('> Merged post data: ', 'woocommerce-product-csv-import-suite') . print_r($postdata, true)); } else { WC_Product_CSV_Import_Suite::log(__('> Failed to merge post data: ', 'woocommerce-product-csv-import-suite') . print_r($postdata, true)); } } } else { $processing_product_sku = ''; if (!empty($post['sku'])) { $processing_product_sku = $post['sku']; } if ($this->variation_exists($post_parent, $processing_product_id, $processing_product_sku)) { $this->add_import_result('skipped', __('Variation already exists', 'woocommerce-product-csv-import-suite'), $processing_product_id, get_the_title($post['post_parent']), $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> “%s” already exists.', 'woocommerce-product-csv-import-suite'), esc_html($post['post_title'])), true); unset($post); return; } // Insert product WC_Product_CSV_Import_Suite::log(__('> Inserting variation.', 'woocommerce-product-csv-import-suite')); $postdata = array('import_id' => $processing_product_id, 'post_date' => $post['post_date'] ? date('Y-m-d H:i:s', strtotime($post['post_date'])) : '', 'post_date_gmt' => $post['post_date_gmt'] ? date('Y-m-d H:i:s', strtotime($post['post_date_gmt'])) : '', 'post_status' => $post['post_status'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'], 'post_type' => 'product_variation'); $post_id = wp_insert_post($postdata, true); if (is_wp_error($post_id)) { $this->add_import_result('failed', __('Failed to import product variation', 'woocommerce-product-csv-import-suite'), $processing_product_id, get_the_title($post['post_parent']), $post['sku']); WC_Product_CSV_Import_Suite::log(sprintf(__('Failed to import product “%s”', 'woocommerce-product-csv-import-suite'), esc_html($post['post_title']))); return; } else { WC_Product_CSV_Import_Suite::log(sprintf(__('> Inserted - post ID is %s.', 'woocommerce-product-csv-import-suite'), $post_id)); // Set post title now we have an ID $postdata['ID'] = $post_id; $postdata['post_title'] = sprintf(__('Variation #%s of %s', 'woocommerce'), $post_id, get_the_title($post_parent)); wp_update_post($postdata); } } // map pre-import ID to local ID if (empty($processing_product_id)) { $processing_product_id = (int) $post_id; } $this->processed_posts[intval($processing_product_id)] = (int) $post_id; $this->process_terms($post_id, $post['terms']); // Process post meta if (!empty($post['postmeta']) && is_array($post['postmeta'])) { foreach ($post['postmeta'] as $meta) { if ($key = apply_filters('import_post_meta_key', $meta['key'])) { $insert_meta_data[$key] = maybe_unserialize($meta['value']); } } } // Import images and add to post if (!empty($post['images'])) { $featured = true; if ($merging) { // Remove old delete_post_meta($post_id, '_thumbnail_id'); // Delete old attachments $attachments = get_posts('post_parent=' . $post_id . '&post_type=attachment&fields=ids&post_mime_type=image&numberposts=-1'); foreach ($attachments as $attachment) { $url = wp_get_attachment_url($attachment); if (in_array($url, $post['images'])) { if ($url == $post['images'][0]) { $insert_meta_data['_thumbnail_id'] = $attachment; } unset($post['images'][array_search($url, $post['images'])]); } else { // Detach $attachment_post = array(); $attachment_post['ID'] = $attachment; $attachment_post['post_parent'] = ''; wp_update_post($attachment_post); } } WC_Product_CSV_Import_Suite::log(__('> > Old images processed', 'woocommerce-product-csv-import-suite')); } if ($post['images']) { foreach ($post['images'] as $image) { WC_Product_CSV_Import_Suite::log(sprintf(__('> > Importing image "%s"', 'woocommerce-product-csv-import-suite'), $image)); $wp_filetype = wp_check_filetype(basename($image), null); $wp_upload_dir = wp_upload_dir(); $filename = basename($image); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); $attachment_id = $this->process_attachment($attachment, $image, $post_id); if (!is_wp_error($attachment_id)) { if ($featured) { $insert_meta_data['_thumbnail_id'] = $attachment_id; } update_post_meta($attachment_id, '_woocommerce_exclude_image', 0); $featured = false; } else { WC_Product_CSV_Import_Suite::log('> > ' . $attachment_id->get_error_message()); } } } WC_Product_CSV_Import_Suite::log(__('> > Images set', 'woocommerce-product-csv-import-suite')); } // Delete existing meta first $wpdb->query('START TRANSACTION'); $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ( '" . implode("','", array_map('esc_sql', array_keys($insert_meta_data))) . "' ) and post_id = %d", $post_id)); // Format meta data foreach ($insert_meta_data as $key => $value) { $meta_key = wp_unslash($key); $meta_value = wp_unslash($value); $meta_value = sanitize_meta($meta_key, $meta_value, 'post'); $meta_value = maybe_serialize($meta_value); $meta_values[] = $wpdb->prepare("( %d, %s, %s )", $post_id, $meta_key, $meta_value); } // Then insert meta data $wpdb->query("INSERT INTO {$wpdb->postmeta} ( post_id, meta_key, meta_value ) VALUES " . implode(',', $meta_values)); $wpdb->query('COMMIT'); if ($merging) { $this->add_import_result('merged', 'Merge successful', $post_id, get_the_title($post_parent), $post['sku']); WC_Product_CSV_Import_Suite::log(sprintf(__('> Finished merging variation ID %s.', 'woocommerce-product-csv-import-suite'), $post_id)); } else { $this->add_import_result('imported', 'Import successful', $post_id, get_the_title($post_parent), $post['sku']); WC_Product_CSV_Import_Suite::log(sprintf(__('> Finished importing variation ID %s.', 'woocommerce-product-csv-import-suite'), $post_id)); } wp_suspend_cache_invalidation(false); clean_post_cache($post_id); unset($post); }
/** * Create new posts based on import information */ public function process_product($post) { global $wpdb; wp_suspend_cache_invalidation(true); $processing_product_id = absint($post['post_id']); $processing_product = get_post($processing_product_id); $processing_product_title = $processing_product ? $processing_product->post_title : ''; $processing_product_sku = $processing_product ? $processing_product->sku : ''; $merging = !empty($post['merging']); $insert_meta_data = array(); if (!empty($post['post_title'])) { $processing_product_title = $post['post_title']; } if (!empty($post['sku'])) { $processing_product_sku = $post['sku']; } if (!empty($processing_product_id) && isset($this->processed_posts[$processing_product_id])) { $this->add_import_result('skipped', __('Product already processed', 'woocommerce-product-csv-import-suite'), $processing_product_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(__('> Post ID already processed. Skipping.', 'woocommerce-product-csv-import-suite'), true); unset($post); return; } if (!empty($post['post_status']) && $post['post_status'] == 'auto-draft') { $this->add_import_result('skipped', __('Skipping auto-draft', 'woocommerce-product-csv-import-suite'), $processing_product_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(__('> Skipping auto-draft.', 'woocommerce-product-csv-import-suite'), true); unset($post); return; } // Check if post exists when importing if (!$merging) { if ($this->product_exists($processing_product_title, $processing_product_sku, $post['post_name'])) { $this->add_import_result('skipped', __('Product already exists', 'woocommerce-product-csv-import-suite'), $processing_product_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> “%s” already exists.', 'woocommerce-product-csv-import-suite'), esc_html($processing_product_title)), true); unset($post); return; } if ($processing_product_id && is_string(get_post_status($processing_product_id))) { $this->add_import_result('skipped', __('Importing post ID conflicts with an existing post ID', 'woocommerce-product-csv-import-suite'), $processing_product_id, get_the_title($processing_product_id), ''); WC_Product_CSV_Import_Suite::log(sprintf(__('> “%s” ID already exists.', 'woocommerce-product-csv-import-suite'), esc_html($processing_product_id)), true); unset($post); return; } } // Check post type to avoid conflicts with IDs if ($merging && $processing_product_id && get_post_type($processing_product_id) !== 'product') { $this->add_import_result('skipped', __('Post is not a product', 'woocommerce-product-csv-import-suite'), $processing_product_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> “%s” is not a product.', 'woocommerce-product-csv-import-suite'), esc_html($processing_product_id)), true); unset($post); return; } if ($merging) { // Only merge fields which are set $post_id = $processing_product_id; WC_Product_CSV_Import_Suite::log(sprintf(__('> Merging post ID %s.', 'woocommerce-product-csv-import-suite'), $post_id), true); $postdata = array('ID' => $post_id); if ($this->merge_empty_cells) { if (isset($post['post_content'])) { $postdata['post_content'] = $post['post_content']; } if (isset($post['post_excerpt'])) { $postdata['post_excerpt'] = $post['post_excerpt']; } if (isset($post['post_password'])) { $postdata['post_password'] = $post['post_password']; } if (isset($post['post_parent'])) { $postdata['post_parent'] = $post['post_parent']; } } else { if (!empty($post['post_content'])) { $postdata['post_content'] = $post['post_content']; } if (!empty($post['post_excerpt'])) { $postdata['post_excerpt'] = $post['post_excerpt']; } if (!empty($post['post_password'])) { $postdata['post_password'] = $post['post_password']; } if (isset($post['post_parent']) && $post['post_parent'] !== '') { $postdata['post_parent'] = $post['post_parent']; } } if (!empty($post['post_title'])) { $postdata['post_title'] = $post['post_title']; } if (!empty($post['post_author'])) { $postdata['post_author'] = absint($post['post_author']); } if (!empty($post['post_date'])) { $postdata['post_date'] = date("Y-m-d H:i:s", strtotime($post['post_date'])); } if (!empty($post['post_date_gmt'])) { $postdata['post_date_gmt'] = date("Y-m-d H:i:s", strtotime($post['post_date_gmt'])); } if (!empty($post['post_name'])) { $postdata['post_name'] = $post['post_name']; } if (!empty($post['post_status'])) { $postdata['post_status'] = $post['post_status']; } if (isset($post['menu_order'])) { $postdata['menu_order'] = $post['menu_order']; } if (!empty($post['comment_status'])) { $postdata['comment_status'] = $post['comment_status']; } if (sizeof($postdata) > 1) { $result = wp_update_post($postdata, true); if (is_wp_error($result)) { $errors = $result->get_error_messages(); $messages = array(); foreach ($errors as $error) { $messages[] = $error; } $this->add_import_result('failed', implode(', ', $messages), $post_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> Failed to update product %s', 'woocommerce-product-csv-import-suite'), $post_id), true); unset($post); return; } else { WC_Product_CSV_Import_Suite::log(__('> Merged post data: ', 'woocommerce-product-csv-import-suite') . print_r($postdata, true)); } } } else { // Get parent $post_parent = $post['post_parent']; if ($post_parent !== "") { $post_parent = absint($post_parent); if ($post_parent > 0) { // if we already know the parent, map it to the new local ID if (isset($this->processed_posts[$post_parent])) { $post_parent = $this->processed_posts[$post_parent]; // otherwise, attach it to an existing ID if the post exists, otherwise mark as an orphan for later } else { if (false === get_post_status($post_parent)) { $this->post_orphans[intval($processing_product_id)] = $post_parent; $post_parent = 0; } } } } // Insert product WC_Product_CSV_Import_Suite::log(sprintf(__('> Inserting %s', 'woocommerce-product-csv-import-suite'), esc_html($processing_product_title)), true); $postdata = array('import_id' => $processing_product_id, 'post_author' => $post['post_author'] ? absint($post['post_author']) : get_current_user_id(), 'post_date' => $post['post_date'] ? date('Y-m-d H:i:s', strtotime($post['post_date'])) : '', 'post_date_gmt' => $post['post_date_gmt'] ? date('Y-m-d H:i:s', strtotime($post['post_date_gmt'])) : '', 'post_content' => $post['post_content'], 'post_excerpt' => $post['post_excerpt'], 'post_title' => $processing_product_title, 'post_name' => $post['post_name'] ? $post['post_name'] : sanitize_title($processing_product_title), 'post_status' => $post['post_status'] ? $post['post_status'] : 'publish', 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'], 'post_type' => 'product', 'post_password' => $post['post_password'], 'comment_status' => $post['comment_status']); $post_id = wp_insert_post($postdata, true); if (is_wp_error($post_id)) { $this->add_import_result('failed', __('Failed to import product', 'woocommerce-product-csv-import-suite'), $processing_product_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('Failed to import product “%s”', 'woocommerce-product-csv-import-suite'), esc_html($processing_product_title))); unset($post); return; } else { WC_Product_CSV_Import_Suite::log(sprintf(__('> Inserted - post ID is %s.', 'woocommerce-product-csv-import-suite'), $post_id)); } } unset($postdata); // map pre-import ID to local ID if (empty($processing_product_id)) { $processing_product_id = (int) $post_id; } $this->processed_posts[intval($processing_product_id)] = (int) $post_id; $this->process_terms($post_id, $post['terms']); // Process post meta if (!empty($post['postmeta']) && is_array($post['postmeta'])) { foreach ($post['postmeta'] as $meta) { if ($key = apply_filters('import_post_meta_key', $meta['key'])) { $insert_meta_data[$key] = maybe_unserialize($meta['value']); } } } // Import images and add to post if (!empty($post['images']) && is_array($post['images'])) { $featured = true; $gallery_ids = array(); if ($merging) { // Get basenames $image_basenames = array(); foreach ($post['images'] as $image) { $image_basenames[] = basename($image); } // Loop attachments already attached to the product $attachments = get_posts('post_parent=' . $post_id . '&post_type=attachment&fields=ids&post_mime_type=image&numberposts=-1'); foreach ($attachments as $attachment_key => $attachment) { $attachment_url = wp_get_attachment_url($attachment); $attachment_basename = basename($attachment_url); // Don't import existing images if (in_array($attachment_url, $post['images']) || in_array($attachment_basename, $image_basenames)) { foreach ($post['images'] as $key => $image) { if ($image == $attachment_url || basename($image) == $attachment_basename) { unset($post['images'][$key]); WC_Product_CSV_Import_Suite::log(sprintf(__('> > Image exists - skipping %s', 'woocommerce-product-csv-import-suite'), basename($image))); if ($key == 0) { $insert_meta_data['_thumbnail_id'] = $attachment; $featured = false; } else { $gallery_ids[$key] = $attachment; } } } } else { // Detach image which is not being merged $attachment_post = array(); $attachment_post['ID'] = $attachment; $attachment_post['post_parent'] = ''; wp_update_post($attachment_post); unset($attachment_post); } } unset($attachments); } if ($post['images']) { foreach ($post['images'] as $image_key => $image) { WC_Product_CSV_Import_Suite::log(sprintf(__('> > Importing image "%s"', 'woocommerce-product-csv-import-suite'), $image)); $filename = basename($image); $attachment = array('post_title' => preg_replace('/\\.[^.]+$/', '', $processing_product_title . ' ' . ($image_key + 1)), 'post_content' => '', 'post_status' => 'inherit', 'post_parent' => $post_id); $attachment_id = $this->process_attachment($attachment, $image, $post_id); if (!is_wp_error($attachment_id) && $attachment_id) { WC_Product_CSV_Import_Suite::log(sprintf(__('> > Imported image "%s"', 'woocommerce-product-csv-import-suite'), $image)); // Set alt update_post_meta($attachment_id, '_wp_attachment_image_alt', $processing_product_title); update_post_meta($attachment_id, '_woocommerce_exclude_image', 0); if ($featured) { $insert_meta_data['_thumbnail_id'] = $attachment_id; } else { $gallery_ids[$image_key] = $attachment_id; } $featured = false; } else { WC_Product_CSV_Import_Suite::log(sprintf(__('> > Error importing image "%s"', 'woocommerce-product-csv-import-suite'), $image)); WC_Product_CSV_Import_Suite::log('> > ' . $attachment_id->get_error_message()); } unset($attachment, $attachment_id); } } WC_Product_CSV_Import_Suite::log(__('> > Images set', 'woocommerce-product-csv-import-suite')); ksort($gallery_ids); $insert_meta_data['_product_image_gallery'] = implode(',', $gallery_ids); } // Import attributes if (!empty($post['attributes']) && is_array($post['attributes'])) { if ($merging) { $attributes = array_filter((array) WC_Product_CSV_Import_Suite::get_meta_data($post_id, '_product_attributes')); $attributes = array_merge($attributes, $post['attributes']); } else { $attributes = $post['attributes']; } // Sort attribute positions uasort($attributes, array($this, 'attributes_cmp')); $insert_meta_data['_product_attributes'] = $attributes; } // Import GPF if (!empty($post['gpf_data']) && is_array($post['gpf_data'])) { $insert_meta_data['_woocommerce_gpf_data'] = $post['gpf_data']; } if (!empty($post['upsell_skus']) && is_array($post['upsell_skus'])) { $this->upsell_skus[$post_id] = $post['upsell_skus']; } if (!empty($post['crosssell_skus']) && is_array($post['crosssell_skus'])) { $this->crosssell_skus[$post_id] = $post['crosssell_skus']; } // Sales $insert_meta_data['total_sales'] = absint(WC_Product_CSV_Import_Suite::get_meta_data($post_id, 'total_sales')); // Delete existing meta first $wpdb->query('START TRANSACTION'); $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ( '" . implode("','", array_map('esc_sql', array_keys($insert_meta_data))) . "' ) and post_id = %d", $post_id)); // Format meta data foreach ($insert_meta_data as $key => $value) { $meta_key = wp_unslash($key); $meta_value = wp_unslash($value); $meta_value = sanitize_meta($meta_key, $meta_value, 'post'); $meta_value = maybe_serialize($meta_value); $meta_values[] = $wpdb->prepare("( %d, %s, %s )", $post_id, $meta_key, $meta_value); } // Then insert meta data $wpdb->query("INSERT INTO {$wpdb->postmeta} ( post_id, meta_key, meta_value ) VALUES " . implode(',', $meta_values)); $wpdb->query('COMMIT'); foreach ($insert_meta_data as $key => $value) { if ($key === '_file_paths') { do_action('woocommerce_process_product_file_download_paths', $post_id, 0, $value); break; } } if ($merging) { $this->add_import_result('merged', 'Merge successful', $post_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> Finished merging post ID %s.', 'woocommerce-product-csv-import-suite'), $post_id)); } else { $this->add_import_result('imported', 'Import successful', $post_id, $processing_product_title, $processing_product_sku); WC_Product_CSV_Import_Suite::log(sprintf(__('> Finished importing post ID %s.', 'woocommerce-product-csv-import-suite'), $post_id)); } wp_suspend_cache_invalidation(false); clean_post_cache($post_id); unset($post); }
function dsq_update_permalink($post) { global $dsq_api; if (DISQUS_DEBUG) { echo "updating post on disqus: {$post->ID}\n"; } $response = $dsq_api->api->update_thread(null, array('thread_identifier' => dsq_identifier_for_post($post), 'title' => dsq_title_for_post($post), 'url' => dsq_link_for_post($post))); //Make sure that response exists so that warnings are not thrown if (!empty($response)) { $cleaned_thread_id = sanitize_meta('dsq_thread_id', $response->id, 'post'); update_post_meta($post->ID, 'dsq_thread_id', $cleaned_thread_id); } return $response; }
/** * Update meta by ID. * * NOTE: This is the Connections equivalent of @see update_metadata_by_mid() in WordPress core ../wp-includes/meta.php * * @access public * @since 8.1.7 * @static * * @global wpdb $wpdb WordPress database abstraction object. * * @uses cnMeta::tableName() * @uses cnMeta::getByID() * @uses sanitize_meta() * @uses cnFormatting::maybeJSONencode() * @uses do_action() * @uses wpdb::update() * @uses wp_cache_delete() * * @param string $type Type of object metadata is for (e.g., entry, term). * @param int $id ID for a specific meta row. * @param string $value Metadata value. * @param mixed $key string|bool Optional, you can provide a meta key to update it. * * @return bool TRUE on successful update, FALSE on failure. */ public static function updateByID($type, $id, $value, $key = FALSE) { /** @var wpdb $wpdb */ global $wpdb; // Make sure everything is valid. if (!$type || !is_numeric($id)) { return FALSE; } $id = absint($id); if (!$id) { return FALSE; } $table = self::tableName($type); $column = sanitize_key($type . '_id'); $id_column = 'meta_id'; // Fetch the meta and go on if it's found. if ($meta = self::getByID($type, $id)) { $original_key = $meta->meta_key; $object_id = $meta->{$column}; // If a new meta_key (last parameter) was specified, change the meta key, // otherwise use the original key in the update statement. if (FALSE === $key) { $key = $original_key; } elseif (!is_string($key)) { return FALSE; } // Sanitize the meta $_meta_value = $value; $value = wp_unslash($value); $value = sanitize_meta($key, $value, 'cn_' . $type); $value = cnFormatting::maybeJSONencode($value); // Format the data query arguments. $data = array('meta_key' => $key, 'meta_value' => $value); // Format the where query arguments. $where = array(); $where[$id_column] = $id; /** This action is documented in includes/class.meta.php */ do_action("cn_update_{$type}_meta", $id, $object_id, $key, $_meta_value); // Run the update query, all fields in $data are %s, $where is a %d. $result = $wpdb->update($table, $data, $where, '%s', '%d'); if (!$result) { return FALSE; } // Clear the caches. wp_cache_delete($object_id, 'cn_' . $type . '_meta'); /** This action is documented in includes/class.meta.php */ do_action("cn_updated_{$type}_meta", $id, $object_id, $key, $_meta_value); return TRUE; } // And if the meta was not found. return FALSE; }
function ppr_save_metadata($post_id, $post) { if ($post->post_type == 'revision' || defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } // verify authorization if (isset($_POST['pprredirect_noncename'])) { if (!wp_verify_nonce($_REQUEST['pprredirect_noncename'], 'pprredirect_noncename')) { return $post_id; } } // check allowed to editing if (!current_user_can('edit_posts', $post_id)) { return $post_id; } if (!empty($my_meta_data)) { unset($my_meta_data); } $my_meta_data = array(); if (isset($_POST['pprredirect_active']) || isset($_POST['pprredirect_url']) || isset($_POST['pprredirect_type']) || isset($_POST['pprredirect_newwindow']) || isset($_POST['pprredirect_relnofollow']) || isset($_POST['pprredirect_meta_secs'])) { $protocols = apply_filters('qppr_allowed_protocols', array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp')); // find & save the form data & put it into an array $my_meta_data['_pprredirect_active'] = isset($_REQUEST['pprredirect_active']) ? sanitize_meta('_pprredirect_active', $this->isOne_none(intval($_REQUEST['pprredirect_active'])), 'post') : ''; $my_meta_data['_pprredirect_newwindow'] = isset($_REQUEST['pprredirect_newwindow']) ? sanitize_meta('_pprredirect_newwindow', $this->isOne_none($_REQUEST['pprredirect_newwindow']), 'post') : ''; $my_meta_data['_pprredirect_relnofollow'] = isset($_REQUEST['pprredirect_relnofollow']) ? sanitize_meta('_pprredirect_relnofollow', $this->isOne_none(intval($_REQUEST['pprredirect_relnofollow'])), 'post') : ''; $my_meta_data['_pprredirect_type'] = isset($_REQUEST['pprredirect_type']) ? sanitize_meta('_pprredirect_type', sanitize_text_field($_REQUEST['pprredirect_type']), 'post') : ''; $my_meta_data['_pprredirect_rewritelink'] = isset($_REQUEST['pprredirect_rewritelink']) ? sanitize_meta('_pprredirect_rewritelink', $this->isOne_none(intval($_REQUEST['pprredirect_rewritelink'])), 'post') : ''; $my_meta_data['_pprredirect_url'] = isset($_REQUEST['pprredirect_url']) ? esc_url_raw($_REQUEST['pprredirect_url'], $protocols) : ''; $my_meta_data['_pprredirect_meta_secs'] = isset($_REQUEST['pprredirect_meta_secs']) && $_REQUEST['pprredirect_meta_secs'] != '' ? (int) $_REQUEST['pprredirect_meta_secs'] : ''; $info = $this->appip_parseURI($my_meta_data['_pprredirect_url']); //$my_meta_data['_pprredirect_url'] = esc_url_raw($info['url']); $my_meta_data['_pprredirect_url'] = $info['url']; if ($my_meta_data['_pprredirect_url'] == 'http://' || $my_meta_data['_pprredirect_url'] == 'https://' || $my_meta_data['_pprredirect_url'] == '') { $my_meta_data['_pprredirect_url'] = ''; //reset to nothing $my_meta_data['_pprredirect_type'] = NULL; //clear Type if no URL is set. $my_meta_data['_pprredirect_active'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_rewritelink'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_newwindow'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_relnofollow'] = NULL; //turn it off if no URL is set } // Add values of $my_meta_data as custom fields if (count($my_meta_data) > 0) { foreach ($my_meta_data as $key => $value) { $value = implode(',', (array) $value); if ($value == '' || $value == NULL || $value == ',') { delete_post_meta($post->ID, $key); } else { if (get_post_meta($post->ID, $key, true) != '') { update_post_meta($post->ID, $key, $value); } else { add_post_meta($post->ID, $key, $value); } } } } $this->qppr_try_to_clear_cache_plugins(); } }
function ppr_save_metadata($post_id, $post) { if ($post->post_type == 'revision') { return; } // verify authorization if (isset($_POST['pprredirect_noncename'])) { if (!wp_verify_nonce($_REQUEST['pprredirect_noncename'], 'pprredirect_noncename')) { return $post_id; } } // check allowed to editing if (!current_user_can('edit_posts', $post_id)) { return $post_id; } if (!empty($my_meta_data)) { unset($my_meta_data); } $my_meta_data = array(); if (isset($_POST['pprredirect_active']) || isset($_POST['pprredirect_url']) || isset($_POST['pprredirect_type']) || isset($_POST['pprredirect_newwindow']) || isset($_POST['pprredirect_relnofollow'])) { // find & save the form data & put it into an array $my_meta_data['_pprredirect_active'] = isset($_REQUEST['pprredirect_active']) ? sanitize_meta('_pprredirect_active', $this->isOne_none(intval($_REQUEST['pprredirect_active'])), 'post') : ''; $my_meta_data['_pprredirect_newwindow'] = isset($_REQUEST['pprredirect_newwindow']) ? sanitize_meta('_pprredirect_newwindow', $this->isOne_none($_REQUEST['pprredirect_newwindow']), 'post') : ''; $my_meta_data['_pprredirect_relnofollow'] = isset($_REQUEST['pprredirect_relnofollow']) ? sanitize_meta('_pprredirect_relnofollow', $this->isOne_none(intval($_REQUEST['pprredirect_relnofollow'])), 'post') : ''; $my_meta_data['_pprredirect_type'] = isset($_REQUEST['pprredirect_type']) ? sanitize_meta('_pprredirect_type', sanitize_text_field($_REQUEST['pprredirect_type']), 'post') : ''; $my_meta_data['_pprredirect_rewritelink'] = isset($_REQUEST['pprredirect_rewritelink']) ? sanitize_meta('_pprredirect_rewritelink', $this->isOne_none(intval($_REQUEST['pprredirect_rewritelink'])), 'post') : ''; $my_meta_data['_pprredirect_url'] = isset($_REQUEST['pprredirect_url']) ? sanitize_meta('_pprredirect_url', $_REQUEST['pprredirect_url'], 'post') : ''; $info = $this->appip_parseURI($my_meta_data['_pprredirect_url']); //$my_meta_data['_pprredirect_url'] = esc_url_raw($info['url']); $my_meta_data['_pprredirect_url'] = $info['url']; if ($my_meta_data['_pprredirect_url'] == 'http://' || $my_meta_data['_pprredirect_url'] == 'https://' || $my_meta_data['_pprredirect_url'] == '') { $my_meta_data['_pprredirect_url'] = ''; //reset to nothing $my_meta_data['_pprredirect_type'] = NULL; //clear Type if no URL is set. $my_meta_data['_pprredirect_active'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_rewritelink'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_newwindow'] = NULL; //turn it off if no URL is set $my_meta_data['_pprredirect_relnofollow'] = NULL; //turn it off if no URL is set } // Add values of $my_meta_data as custom fields if (count($my_meta_data) > 0) { foreach ($my_meta_data as $key => $value) { $value = implode(',', (array) $value); if ($value == '' || $value == NULL || $value == ',') { delete_post_meta($post->ID, $key); } else { if (get_post_meta($post->ID, $key, true) != '') { update_post_meta($post->ID, $key, $value); } else { add_post_meta($post->ID, $key, $value); } } } } } }
function dsq_update_permalink($post) { global $dsq_api; if (DISQUS_DEBUG) { echo "updating post on disqus: {$post->ID}\n"; } $response = $dsq_api->api->update_thread(null, array('thread_identifier' => dsq_identifier_for_post($post), 'title' => dsq_title_for_post($post), 'url' => dsq_link_for_post($post))); $cleaned_thread_id = sanitize_meta('dsq_thread_id', $response->id, 'post'); update_post_meta($post->ID, 'dsq_thread_id', $cleaned_thread_id); return $response; }
public function test_register_meta_with_new_sanitize_callback_parameter() { register_meta('post', 'new_sanitized_key', array('sanitize_callback' => array($this, '_new_sanitize_meta_cb'))); $meta = sanitize_meta('new_sanitized_key', 'unsanitized', 'post'); unregister_meta_key('post', 'new_sanitized_key'); $this->assertEquals('new_sanitized_key new sanitized', $meta); }
function fw_add_post_meta($post_id, $meta_key, $meta_value, $unique = false) { // make sure meta is added to the post, not a revision if ($the_post = wp_is_post_revision($post_id)) { $post_id = $the_post; } $meta_type = 'post'; $object_id = $post_id; if (!$meta_type || !$meta_key) { return false; } if (!($object_id = absint($object_id))) { return false; } if (!($table = _get_meta_table($meta_type))) { return false; } global $wpdb; $column = esc_sql($meta_type . '_id'); // expected_slashed ($meta_key) // $meta_key = stripslashes($meta_key); // this was the trouble ! // $meta_value = stripslashes_deep($meta_value); // this was the trouble ! $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type); $check = apply_filters("add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique); if (null !== $check) { return $check; } if ($unique && $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE meta_key = %s AND {$column} = %d", $meta_key, $object_id))) { return false; } $_meta_value = $meta_value; $meta_value = maybe_serialize($meta_value); do_action("add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value); $result = $wpdb->insert($table, array($column => $object_id, 'meta_key' => $meta_key, 'meta_value' => $meta_value)); if (!$result) { return false; } $mid = (int) $wpdb->insert_id; wp_cache_delete($object_id, $meta_type . '_meta'); do_action("added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value); return $mid; }
public function inline_update() { global $wpdb; $edited_data = !empty($this->req_params['edited_data']) ? json_decode(stripslashes($this->req_params['edited_data']), true) : array(); $current_store_model = get_transient('sm_dashboard_model_' . $this->dashboard_key); $table_model = !empty($current_store_model[$this->dashboard_key]['tables']) ? $current_store_model[$this->dashboard_key]['tables'] : array(); $col_model = !empty($current_store_model[$this->dashboard_key]['columns']) ? $current_store_model[$this->dashboard_key]['columns'] : array(); if (empty($edited_data) || empty($table_model) || empty($col_model)) { return; } $edited_data = apply_filters('sm_inline_update_pre', $edited_data); $data_cols_serialized = array(); $data_cols_multiselect = array(); $data_cols_multiselect_val = array(); $data_cols_list = array(); $data_cols_list_val = array(); //Code for storing the serialized cols foreach ($col_model as $col) { $col_exploded = !empty($col['src']) ? explode("/", $col['src']) : array(); if (empty($col_exploded)) { continue; } if (sizeof($col_exploded) > 2) { $col_meta = explode("=", $col_exploded[1]); $col_nm = $col_meta[1]; } else { $col_nm = $col_exploded[1]; } if ($col['type'] == 'longstring') { $data_cols_serialized[] = $col_nm; } else { if ($col['type'] == 'multilist') { $data_cols_multiselect[] = $col_nm; $data_cols_multiselect_val[$col_nm] = !empty($col['values']) ? $col['values'] : array(); if (empty($data_cols_multiselect_val[$col_nm])) { continue; } $final_multiselect_val = array(); foreach ($data_cols_multiselect_val[$col_nm] as $key => $value) { $final_multiselect_val[$key] = $value['term']; } $data_cols_multiselect_val[$col_nm] = $final_multiselect_val; } else { if ($col['type'] == 'list') { $data_cols_list[] = $col_nm; $data_cols_list_val[$col_nm] = !empty($col['values']) ? $col['values'] : array(); } } } } $update_params_meta = array(); // for all tables with meta_key = meta_value like structure for updating the values $insert_params_meta = array(); // for all tables with meta_key = meta_value like structure for inserting the values $meta_data_edited = array(); $meta_index = 0; $old_post_id = ''; $meta_case_cond = 'CASE post_id '; $meta_keys_edited = array(); // array for storing the edited meta_keys foreach ($edited_data as $id => $edited_row) { $update_params_posts = array(); $update_params_custom = array(); // for custom tables $where_cond = array(); $insert_post = 0; //Code for inserting the post if (empty($id)) { $insert_params_posts = array(); foreach ($edited_row as $key => $value) { $edited_value_exploded = explode("/", $key); if (empty($edited_value_exploded)) { continue; } $update_table = $edited_value_exploded[0]; $update_column = $edited_value_exploded[1]; if ($update_table == 'posts') { $insert_params_posts[$update_column] = $value; } } if (!empty($insert_params_posts)) { $inserted_id = wp_insert_post($insert_params_posts); if (!is_wp_error($inserted_id) && !empty($inserted_id)) { $id = $inserted_id; $insert_post = 1; //Flag for determining whether post has been inserted } else { continue; } } else { continue; } } // if (empty($edited_row['posts/ID'])) continue; // $id = $edited_row['posts/ID']; foreach ($edited_row as $key => $value) { $edited_value_exploded = explode("/", $key); if (empty($edited_value_exploded)) { continue; } $update_cond = array(); // for handling the where condition $update_params_meta_flag = false; // flag for handling the query for meta_key = meta_value like structure $update_table = $edited_value_exploded[0]; $update_column = $edited_value_exploded[1]; if (empty($where_cond[$update_table])) { $where_cond[$update_table] = !empty($table_model[$update_table]['pkey']) && $update_column == $table_model[$update_table]['pkey'] ? 'WHERE ' . $table_model[$update_table]['pkey'] . ' = ' . $value : ''; } if (sizeof($edited_value_exploded) > 2) { $cond = explode("=", $edited_value_exploded[1]); if (sizeof($cond) == 2) { $update_cond[$cond[0]] = $cond[1]; } $update_column_exploded = explode("=", $edited_value_exploded[2]); $update_column = $update_column_exploded[0]; $update_params_meta_flag = true; } // handling the update array for posts table if ($update_table == 'posts' && $insert_post != 1) { if (empty($update_params_posts[$table_model[$update_table]['pkey']]) && !empty($id)) { $update_params_posts[$table_model[$update_table]['pkey']] = $id; } $update_params_posts[$update_column] = $value; } else { if ($update_params_meta_flag === true) { if (empty($id) || empty($update_cond['meta_key'])) { continue; } $meta_key = $update_cond['meta_key']; //Code for handling serialized data if (array_search($meta_key, $data_cols_serialized) !== false) { if (!empty($value)) { $value = json_decode($value, true); } } // update_post_meta($id, $meta_key, $value ); //Code for forming the edited data array if (empty($meta_data_edited[$update_table])) { $meta_data_edited[$update_table] = array(); } if (empty($meta_data_edited[$update_table][$id])) { $meta_data_edited[$update_table][$id] = array(); } $meta_data_edited[$update_table][$id][$update_cond['meta_key']] = $value; $meta_keys_edited[$update_cond['meta_key']] = ''; } else { if ($update_table == 'terms') { //code for handling updates for terms $term_ids = array(); //Code for handling multiselect data if (array_search($update_column, $data_cols_multiselect) !== false) { $actual_val = !empty($data_cols_multiselect_val[$update_column]) ? $data_cols_multiselect_val[$update_column] : array(); if (empty($value) || empty($actual_val)) { continue; } $edited_values = explode("<br>", $value); if (empty($edited_values)) { continue; } } else { if (array_search($update_column, $data_cols_list) !== false) { $actual_val = !empty($data_cols_list_val[$update_column]) ? $data_cols_list_val[$update_column] : array(); if (empty($value) || empty($actual_val)) { continue; } $edited_values = explode("<br>", $value); if (empty($edited_values)) { continue; } } } if (!empty($edited_values)) { foreach ($edited_values as $edited_value) { $term_id = array_search($edited_value, $actual_val); if ($term_id === false) { continue; } $term_ids[] = $term_id; } } if (!empty($term_ids)) { wp_set_object_terms($id, $term_ids, $update_column); } } } } } //Code for updating the posts table if (!empty($update_params_posts)) { wp_update_post($update_params_posts); } } //Code for updating the meta tables if (!empty($meta_data_edited)) { foreach ($meta_data_edited as $update_table => $update_params) { if (empty($update_params)) { continue; } $post_ids = array_keys($update_params); $meta_keys_edited = !empty($meta_keys_edited) ? array_keys($meta_keys_edited) : ''; $update_table_key = ''; //pkey for the update table if ($update_table == 'postmeta') { $update_table_key = 'post_id'; } //Code for getting the old values and meta_ids $old_meta_data = $this->get_meta_data($post_ids, $meta_keys_edited, $update_table, $update_table_key); $meta_data = array(); if (!empty($old_meta_data)) { foreach ($old_meta_data as $key => $old_values) { foreach ($old_values as $data) { if (empty($meta_data[$key])) { $meta_data[$key] = array(); } $meta_data[$key][$data['meta_key']] = array(); $meta_data[$key][$data['meta_key']]['meta_id'] = $data['meta_id']; $meta_data[$key][$data['meta_key']]['meta_value'] = $data['meta_value']; } } } $meta_index = 0; $insert_meta_index = 0; $index = 0; $insert_index = 0; $old_post_id = ''; $update_params_index = 0; //Code for generating the query foreach ($update_params as $id => $updated_data) { $updated_data_index = 0; $update_params_index++; foreach ($updated_data as $key => $value) { $key = wp_unslash($key); $value = wp_unslash($value); $meta_type = 'post'; if ($update_table == 'postmeta') { $value = sanitize_meta($key, $value, 'post'); } $updated_data_index++; // Filter whether to update metadata of a specific type. $check = apply_filters("update_{$meta_type}_metadata", null, $id, $key, $value, ''); if (null !== $check) { continue; } // Code for handling if the meta key does not exist if (empty($meta_data[$id][$key])) { // Filter whether to add metadata of a specific type. $check = apply_filters("add_{$meta_type}_metadata", null, $id, $key, $value, false); if (null !== $check) { continue; } if (empty($insert_params_meta[$update_table])) { $insert_params_meta[$update_table] = array(); $insert_params_meta[$update_table][$insert_meta_index] = array(); $insert_params_meta[$update_table][$insert_meta_index]['values'] = array(); } if ($insert_index >= 5 && $old_post_id != $id) { $insert_index = 0; $insert_meta_index++; } if ($old_post_id != $id) { $old_post_id = $id; $insert_index++; } $insert_params_meta[$update_table][$insert_meta_index]['values'][] = array('id' => $id, 'meta_key' => $key, 'meta_value' => $value); $value = maybe_serialize($value); if (empty($insert_params_meta[$update_table][$insert_meta_index]['query'])) { $insert_params_meta[$update_table][$insert_meta_index]['query'] = "(" . $id . ", '" . $key . "', '" . $value . "')"; } else { $insert_params_meta[$update_table][$insert_meta_index]['query'] .= ", (" . $id . ", '" . $key . "', '" . $value . "')"; } continue; } else { //Checking if edited value is same as old value if ($meta_data[$id][$key]['meta_value'] == $value) { unset($meta_data[$id][$key]); if (empty($meta_data[$id])) { unset($meta_data[$id]); } continue; } else { $meta_data[$id][$key]['meta_value'] = $value; } } $value = maybe_serialize($value); if (empty($update_params_meta[$update_table])) { $update_params_meta[$update_table] = array(); $update_params_meta[$update_table][$meta_index] = array(); $update_params_meta[$update_table][$meta_index]['ids'] = array(); $update_params_meta[$update_table][$meta_index]['query'] = ''; } if ($index >= 5 && $old_post_id != $id) { $update_params_meta[$update_table][$meta_index]['query'] .= ' ELSE meta_value END END '; $index = 0; $meta_index++; } if (empty($update_params_meta[$update_table][$meta_index]['query'])) { $update_params_meta[$update_table][$meta_index]['query'] = ' CASE post_id '; } if ($old_post_id != $id) { if (!empty($index)) { $update_params_meta[$update_table][$meta_index]['query'] .= ' ELSE meta_value END '; } $update_params_meta[$update_table][$meta_index]['query'] .= " WHEN '" . $id . "' THEN \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCASE meta_key "; $old_post_id = $id; $update_params_meta[$update_table][$meta_index]['ids'][] = $id; $index++; } $update_params_meta[$update_table][$meta_index]['query'] .= " WHEN '" . $key . "' THEN '" . $value . "' "; //Code for the last condition if ($update_params_index == sizeof($update_params) && $updated_data_index == sizeof($updated_data)) { $update_params_meta[$update_table][$meta_index]['query'] .= ' ELSE meta_value END END '; } } } // Start here... update the actions and query in for loop if (!empty($insert_params_meta)) { foreach ($insert_params_meta as $insert_table => $edited_data) { if (empty($edited_data)) { continue; } $insert_table_key = empty($insert_table_key) ? 'post_id' : $insert_table_key; foreach ($edited_data as $insert_params) { if (empty($insert_params['values']) || empty($insert_params['query'])) { continue; } $insert_meta_query = "INSERT INTO {$wpdb->prefix}" . $insert_table . " (" . $insert_table_key . ",meta_key,meta_value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t VALUES " . $insert_params['query']; if ($insert_table == 'postmeta') { // function to replicate wordpress add_metadata() $this->sm_add_post_meta('post', $insert_params['values'], $insert_meta_query); } else { $result_insert_meta = $wpdb->query($insert_meta_query); } } } } // Inline data updation for meta tables if (!empty($update_params_meta)) { foreach ($update_params_meta as $update_table => $edited_data) { if (empty($edited_data)) { continue; } $update_table_key = empty($update_table_key) ? 'post_id' : $update_table_key; foreach ($edited_data as $update_params) { if (empty($update_params['ids']) || empty($update_params['query'])) { continue; } $update_meta_query = "UPDATE {$wpdb->prefix}{$update_table}\n\t\t\t\t\t\t\t\t\t\t\t\t\tSET meta_value = " . $update_params['query'] . "\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE {$update_table_key} IN (" . implode(',', $update_params['ids']) . ")"; if ($update_table == 'postmeta') { // function to replicate wordpress update_postmeta() $this->sm_update_post_meta('post', $update_params['ids'], $meta_data, $update_meta_query); } else { $result_update_meta = $wpdb->query($update_meta_query); } } } } } } do_action('sm_inline_update_post', $edited_data); $msg_str = ''; if (sizeof($edited_data) > 1) { $msg_str = 's'; } echo sizeof($edited_data) . ' Record' . $msg_str . ' Updated Successfully!'; exit; }
/** * Update meta data by meta ID * * @since 3.3.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @param string $meta_value Metadata value * @param string $meta_key Optional, you can provide a meta key to update it * @return bool True on successful update, false on failure. */ function update_metadata_by_mid($meta_type, $meta_id, $meta_value, $meta_key = false) { global $wpdb; // Make sure everything is valid. if (!$meta_type || !is_numeric($meta_id)) { return false; } $meta_id = absint($meta_id); if (!$meta_id) { return false; } $table = _get_meta_table($meta_type); if (!$table) { return false; } $column = sanitize_key($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // Fetch the meta and go on if it's found. if ($meta = get_metadata_by_mid($meta_type, $meta_id)) { $original_key = $meta->meta_key; $object_id = $meta->{$column}; // If a new meta_key (last parameter) was specified, change the meta key, // otherwise use the original key in the update statement. if (false === $meta_key) { $meta_key = $original_key; } elseif (!is_string($meta_key)) { return false; } // Sanitize the meta $_meta_value = $meta_value; $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type); $meta_value = maybe_serialize($meta_value); // Format the data query arguments. $data = array('meta_key' => $meta_key, 'meta_value' => $meta_value); // Format the where query arguments. $where = array(); $where[$id_column] = $meta_id; /** This action is documented in wp-includes/meta.php */ do_action("update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); if ('post' == $meta_type) { /** This action is documented in wp-includes/meta.php */ do_action('update_postmeta', $meta_id, $object_id, $meta_key, $meta_value); } // Run the update query, all fields in $data are %s, $where is a %d. $result = $wpdb->update($table, $data, $where, '%s', '%d'); if (!$result) { return false; } // Clear the caches. wp_cache_delete($object_id, $meta_type . '_meta'); /** This action is documented in wp-includes/meta.php */ do_action("updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value); if ('post' == $meta_type) { /** This action is documented in wp-includes/meta.php */ do_action('updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value); } return true; } // And if the meta was not found. return false; }
/** * update_term_taxonomy_meta * * Update meta_value term taxonomy meta by term_taxonomy_id and $meta_key * Create news if meta_key doesn't exist in table * * @param int $term_taxonomy_id * @param string $meta_key * @param string $meta_value * @return boolean */ public static function update_term_taxonomy_meta($term_taxonomy_id, $meta_key, $meta_value) { global $wpdb; $sTable = $wpdb->prefix . self::get_instance()->get_meta_type() . "meta"; // Securize $meta_key = wp_unslash($meta_key); $meta_value = wp_unslash($meta_value); $meta_value = sanitize_meta($meta_key, $meta_value, self::get_instance()->get_meta_type()); // If not exist, create taxonomy_meta if (!($meta_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$sTable} WHERE meta_key=%s AND term_taxonomy_id = %d", $meta_key, $term_taxonomy_id)))) { return self::add_term_taxonomy_meta($term_taxonomy_id, $meta_key, $meta_value); } $meta_value = maybe_serialize($meta_value); $data = compact("meta_value"); $where = array('term_taxonomy_id' => $term_taxonomy_id, "meta_key" => $meta_key); $result = $wpdb->update($sTable, $data, $where); if (!$result) { return false; } return true; }