protected function get_metadata($ids, $meta_type) { global $wpdb; $table = _get_meta_table($meta_type); $id = $meta_type . '_id'; if (!$table) { return array(); } return array_map(array($this, 'unserialize_meta'), $wpdb->get_results("SELECT {$id}, meta_key, meta_value, meta_id FROM {$table} WHERE {$id} IN ( " . implode(',', wp_parse_id_list($ids)) . ' )', OBJECT)); }
/** * @group delete_term */ public function test_delete_term() { $taxonomy = 'category'; $term_id = $this->factory->term->create(array('taxonomy' => $taxonomy)); $term = get_term($term_id, 'category'); $Meta = new Smart_Custom_Fields_Meta($term); if (!_get_meta_table($Meta->get_meta_type())) { $Meta->add('text', 'text'); $this->Ajax->delete_term($term_id, '', $taxonomy, $term); $this->assertSame(array(), $Meta->get('text')); } }
/** * Replace the domain in meta tables * * @param string $type * @param integer $id * @param integer $objectId * @param string $key * @param mixed $value */ public function replaceDomainInMeta($type, $id, $objectId, $key, $value) { global $wpdb; $table = _get_meta_table($type); $column = sanitize_key($type . '_id'); $newValue = $this->replaceDomainRecursive($value); if ($value !== $newValue) { $data = ['meta_value' => maybe_serialize($newValue)]; $where = [$column => $objectId, 'meta_key' => $key, 'meta_value' => maybe_serialize($value)]; $wpdb->update($table, $data, $where); } }
protected function get_metadata($ids, $meta_type) { global $wpdb; $table = _get_meta_table($meta_type); $id = $meta_type . '_id'; if (!$table) { return array(); } $private_meta_whitelist_sql = "'" . implode("','", array_map('esc_sql', Jetpack_Sync_Defaults::$default_whitelist_meta_keys)) . "'"; $public_meta_blacklist_sql = "'" . implode("','", array_map('esc_sql', Jetpack_Sync_Defaults::$default_blacklist_meta_keys)) . "'"; return array_map(array($this, 'unserialize_meta'), $wpdb->get_results("SELECT {$id}, meta_key, meta_value, meta_id FROM {$table} WHERE {$id} IN ( " . implode(',', wp_parse_id_list($ids)) . ' )' . " AND ( ( meta_key LIKE '\\_%' AND meta_key IN ( {$private_meta_whitelist_sql} ) )" . " OR ( meta_key NOT LIKE '\\_%' AND meta_key NOT IN ( {$public_meta_blacklist_sql} ) ) )", OBJECT)); }
/** * @param string|int $identifier * @return array|bool */ function get_static_blocks_by_id($identifier) { /** @var $wpdb wpdb */ global $wpdb; if (!($table = _get_meta_table('post'))) { return false; } $postIds = $wpdb->get_col($wpdb->prepare("SELECT `post_id` FROM {$table} WHERE `meta_key` = '_identifier' AND `meta_value` = %s", $identifier)); if (empty($postIds)) { return false; } return get_posts(array('include' => $postIds, 'post_type' => 'static_block')); }
protected function get_metadata($ids, $meta_type) { global $wpdb; $table = _get_meta_table($meta_type); $id = $meta_type . '_id'; if (!$table) { return array(); } $private_meta_whitelist_sql = ''; $meta_module = Jetpack_Sync_Modules::get_module("meta"); switch ($meta_type) { case 'post': $private_meta_whitelist_sql = "'" . implode("','", array_map('esc_sql', $meta_module->get_post_meta_whitelist())) . "'"; break; case 'comment': $private_meta_whitelist_sql = "'" . implode("','", array_map('esc_sql', $meta_module->get_comment_meta_whitelist())) . "'"; break; } return array_map(array($this, 'unserialize_meta'), $wpdb->get_results("SELECT {$id}, meta_key, meta_value, meta_id FROM {$table} WHERE {$id} IN ( " . implode(',', wp_parse_id_list($ids)) . ' )' . " AND meta_key IN ( {$private_meta_whitelist_sql} ) ", OBJECT)); }
/** * Retrieve custom fields for object. * * @param WP_REST_Request $request * @return WP_REST_Request|WP_Error List of meta object data on success, WP_Error otherwise */ public function get_items($request) { $parent_id = (int) $request['parent_id']; global $wpdb; $table = _get_meta_table($this->parent_type); $parent_column = $this->get_parent_column(); $id_column = $this->get_id_column(); // @codingStandardsIgnoreStart $results = $wpdb->get_results($wpdb->prepare("SELECT {$id_column}, {$parent_column}, meta_key, meta_value FROM {$table} WHERE {$parent_column} = %d", $parent_id)); // @codingStandardsIgnoreEnd $meta = array(); foreach ($results as $row) { $value = $this->prepare_item_for_response($row, $request, true); if (is_wp_error($value)) { continue; } $meta[] = $this->prepare_response_for_collection($value); } return rest_ensure_response($meta); }
/** * Retrieve custom fields for object. * * @param int $id Object ID * @return (array[]|WP_Error) List of meta object data on success, WP_Error otherwise */ public function get_all_meta($id) { $check = $this->check_object($id); if (is_wp_error($check)) { return $check; } global $wpdb; $table = _get_meta_table($this->type); $parent_column = $this->get_parent_column(); $results = $wpdb->get_results($wpdb->prepare("SELECT meta_id, meta_key, meta_value FROM {$table} WHERE {$parent_column} = %d", $id)); $meta = array(); foreach ($results as $row) { $value = $this->prepare_meta($id, $row, true); if (is_wp_error($value)) { continue; } $meta[] = $value; } return apply_filters('json_prepare_meta', $meta, $id); }
/** * This implementation of get_objects_by_id() is a bit hacky since we're not passing in an array of meta IDs, * but instead an array of post or comment IDs for which to retrieve meta for. On top of that, * we also pass in an associative array where we expect there to be 'meta_key' and 'ids' keys present. * * This seemed to be required since if we have missing meta on WP.com and need to fetch it, we don't know what * the meta key is, but we do know that we have missing meta for a given post or comment. * * @param string $object_type The type of object for which we retrieve meta. Either 'post' or 'comment' * @param array $config Must include 'meta_key' and 'ids' keys * * @return array */ public function get_objects_by_id($object_type, $config) { global $wpdb; $table = _get_meta_table($object_type); if (!$table) { return array(); } if (!isset($config['meta_key']) || !isset($config['ids']) || !is_array($config['ids'])) { return array(); } $meta_key = $config['meta_key']; $ids = $config['ids']; $object_id_column = $object_type . '_id'; // Sanitize so that the array only has integer values $ids_string = implode(', ', array_map('intval', $ids)); $metas = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s", $meta_key)); $meta_objects = array(); foreach ((array) $metas as $meta_object) { $meta_object = (array) $meta_object; $meta_objects[$meta_object[$object_id_column]] = array('meta_type' => $object_type, 'meta_id' => $meta_object['meta_id'], 'meta_key' => $meta_key, 'meta_value' => $meta_object['meta_value'], 'object_id' => $meta_object[$object_id_column]); } return $meta_objects; }
public function auto_upgrade_options() { $current_db_version = 1; //Check version if ($this->options['db_version'] < $current_db_version) { global $wpdb; //DB_VERSION 1: Since 2.1.0-b5 if ($this->options['db_version'] < 1) { //RENAME meta_key _wjecf_matching_product_qty TO _wjecf_min_matching_product_qty $where = array("meta_key" => "_wjecf_matching_product_qty"); $set = array('meta_key' => "_wjecf_min_matching_product_qty"); $wpdb->update(_get_meta_table('post'), $set, $where); //RENAME meta_key woocommerce-jos-autocoupon TO _wjecf_is_auto_coupon $where = array("meta_key" => "woocommerce-jos-autocoupon"); $set = array('meta_key' => "_wjecf_is_auto_coupon"); $wpdb->update(_get_meta_table('post'), $set, $where); //Now we're version 1 $this->options['db_version'] = 1; } // Write options to database update_option('wjecf_options', $this->options, false); } }
/** * Delete metadata for the specified object. * * @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 Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete metadata entries * with this value. Otherwise, delete all entries with the specified meta_key. * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries * for all objects, ignoring the specified object_id. Otherwise, only delete matching * metadata entries for the specified object_id. * * @return bool True on successful delete, false on failure. */ function fw_delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) { /** * @var WPDB $wpdb */ global $wpdb; if (!$meta_type || !$meta_key || !is_numeric($object_id) && !$delete_all) { return false; } $object_id = absint($object_id); if (!$object_id && !$delete_all) { return false; } $table = _get_meta_table($meta_type); if (!$table) { return false; } $type_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); //$meta_value = wp_unslash($meta_value); /** * Filter whether to delete 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 $delete Whether to allow metadata deletion of 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 bool $delete_all Whether to delete the matching metadata entries * for all objects, ignoring the specified $object_id. * Default false. */ $check = apply_filters("delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all); if (null !== $check) { return (bool) $check; } $_meta_value = $meta_value; $meta_value = maybe_serialize($meta_value); $query = $wpdb->prepare("SELECT {$id_column} FROM {$table} WHERE meta_key = %s", $meta_key); if (!$delete_all) { $query .= $wpdb->prepare(" AND {$type_column} = %d", $object_id); } if ($meta_value) { $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value); } $meta_ids = $wpdb->get_col($query); if (!count($meta_ids)) { return false; } if ($delete_all) { $object_ids = $wpdb->get_col($wpdb->prepare("SELECT {$type_column} FROM {$table} WHERE meta_key = %s", $meta_key)); } /** * Fires immediately before deleting metadata of a specific type. * * The dynamic portion of the hook, $meta_type, refers to the meta * object type (comment, post, or user). * * @param array $meta_ids An array of metadata entry IDs to delete. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. */ do_action("delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value); // Old-style action. if ('post' == $meta_type) { /** * Fires immediately before deleting metadata for a post. * * @param array $meta_ids An array of post metadata entry IDs to delete. */ do_action('delete_postmeta', $meta_ids); } $query = "DELETE FROM {$table} WHERE {$id_column} IN( " . implode(',', $meta_ids) . " )"; $count = $wpdb->query($query); if (!$count) { return false; } if ($delete_all) { foreach ((array) $object_ids as $o_id) { wp_cache_delete($o_id, $meta_type . '_meta'); } } else { wp_cache_delete($object_id, $meta_type . '_meta'); } /** * Fires immediately after deleting metadata of a specific type. * * The dynamic portion of the hook name, $meta_type, refers to the meta * object type (comment, post, or user). * * @param array $meta_ids An array of deleted metadata entry IDs. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. */ do_action("deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value); // Old-style action. if ('post' == $meta_type) { /** * Fires immediately after deleting metadata for a post. * * @param array $meta_ids An array of deleted post metadata entry IDs. */ do_action('deleted_postmeta', $meta_ids); } return true; }
protected function executeSQL() { $import_entry = $this->options['custom_type'] == 'import_users' ? 'user' : 'post'; // prepare bulk SQL query $meta_table = _get_meta_table($import_entry); if ($this->post_meta_to_insert) { $values = array(); $already_added = array(); foreach (array_reverse($this->post_meta_to_insert) as $key => $value) { if (!empty($value['meta_key']) and !in_array($value['pid'] . '-' . $value['meta_key'], $already_added)) { $already_added[] = $value['pid'] . '-' . $value['meta_key']; $values[] = '(' . $value['pid'] . ',"' . $value['meta_key'] . '",\'' . maybe_serialize($value['meta_value']) . '\')'; } } $this->wpdb->query("INSERT INTO {$meta_table} (`" . $import_entry . "_id`, `meta_key`, `meta_value`) VALUES " . implode(',', $values)); $this->post_meta_to_insert = array(); } }
public function get_weather($type) { global $wpdb; $table = _get_meta_table('post'); $sql = "SELECT p.ID,p.post_title FROM " . $wpdb->posts . " as p " . " WHERE p.post_type LIKE %s"; $results = $wpdb->get_results($wpdb->prepare($sql, $type)); foreach ($results as $post) { $post_id = $post->ID; } $meta_data = get_metadata('post', $post_id); $data['post_id'] = $post_id; $data['weather_url'] = $meta_data['weather_url']['0']; $data['location'] = $meta_data['location']['0']; $data['weather_data'] = $this->get_weather_details($data); return $data; }
/** * Update the metadata cache for the specified objects. * * @since 2.9.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int|array $object_ids Array or comma delimited list of object IDs to update cache for * @return array|false Metadata cache for the specified objects, or false on failure. */ function update_meta_cache($meta_type, $object_ids) { global $wpdb; if (!$meta_type || !$object_ids) { return false; } $table = _get_meta_table($meta_type); if (!$table) { return false; } $column = sanitize_key($meta_type . '_id'); if (!is_array($object_ids)) { $object_ids = preg_replace('|[^0-9,]|', '', $object_ids); $object_ids = explode(',', $object_ids); } $object_ids = array_map('intval', $object_ids); $cache_key = $meta_type . '_meta'; $ids = array(); $cache = array(); foreach ($object_ids as $id) { $cached_object = wp_cache_get($id, $cache_key); if (false === $cached_object) { $ids[] = $id; } else { $cache[$id] = $cached_object; } } if (empty($ids)) { return $cache; } // Get meta info $id_list = join(',', $ids); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; $meta_list = $wpdb->get_results("SELECT {$column}, meta_key, meta_value FROM {$table} WHERE {$column} IN ({$id_list}) ORDER BY {$id_column} ASC", ARRAY_A); if (!empty($meta_list)) { foreach ($meta_list as $metarow) { $mpid = intval($metarow[$column]); $mkey = $metarow['meta_key']; $mval = $metarow['meta_value']; // Force subkeys to be array type: if (!isset($cache[$mpid]) || !is_array($cache[$mpid])) { $cache[$mpid] = array(); } if (!isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey])) { $cache[$mpid][$mkey] = array(); } // Add a value to the current pid/key: $cache[$mpid][$mkey][] = $mval; } } foreach ($ids as $id) { if (!isset($cache[$id])) { $cache[$id] = array(); } wp_cache_add($id, $cache[$id], $cache_key); } return $cache; }
/** * Saves simple fields data when post is being saved */ function save_postdata($post_id = null, $post = null) { // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times // so not checking nonce can lead to errors, for example losing post connector if (!isset($_POST['simple_fields_nonce']) || !wp_verify_nonce($_POST['simple_fields_nonce'], plugin_basename(__FILE__))) { return $post_id; } // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // why dont' we want to save revisions? i'll do that from now on, let's se what happens // dont's save if is revision // preview is a revison? should save then so preview with fields work // if (wp_is_post_revision($post_id) !== FALSE) return $post_id; // attach post connector // only save if being found in post variable, beacuse it may not exist if meta box is hidden/not outputted on page if (isset($_POST["simple_fields_selected_connector"])) { $simple_fields_selected_connector = isset($_POST["simple_fields_selected_connector"]) ? $_POST["simple_fields_selected_connector"] : null; update_post_meta($post_id, "_simple_fields_selected_connector", $simple_fields_selected_connector); } $post_id = (int) $post_id; $fieldgroups = isset($_POST["simple_fields_fieldgroups"]) ? $_POST["simple_fields_fieldgroups"] : null; $field_groups_option = $this->get_field_groups(); if (!($table = _get_meta_table("post"))) { return false; } global $wpdb; // We have a post_id and we have fieldgroups if ($post_id && is_array($fieldgroups)) { // Delete all exisiting custom fields meta that are not part of the keep-list $post_meta = get_post_custom($post_id); // new format.. can be anything... how to get it? $arr_meta_keys_to_keep = array("_simple_fields_been_saved", "_simple_fields_selected_connector"); foreach ($post_meta as $meta_key => $meta_val) { if (strpos($meta_key, "_simple_fields_") === 0) { // this is a meta for simple fields, check if it should be kept or deleted if (!in_array($meta_key, $arr_meta_keys_to_keep)) { delete_post_meta($post_id, $meta_key); } } } // cleanup missing keys, due to checkboxes not being checked $fieldgroups_fixed = $fieldgroups; foreach ($fieldgroups as $one_field_group_id => $one_field_group_fields) { foreach ($one_field_group_fields as $posted_id => $posted_vals) { if ($posted_id == "added") { continue; } $fieldgroups_fixed[$one_field_group_id][$posted_id] = array(); // loopa igenom "added"-värdena och fixa så att allt finns foreach ($one_field_group_fields["added"] as $added_id => $added_val) { $fieldgroups_fixed[$one_field_group_id][$posted_id][$added_id] = @$fieldgroups[$one_field_group_id][$posted_id][$added_id]; } } } $fieldgroups = $fieldgroups_fixed; // Save info about the fact that this post have been saved. This info is used to determine if a post should get default values or not. update_post_meta($post_id, "_simple_fields_been_saved", "1"); // Loop through each fieldgroups #sf_d($fieldgroups, '$fieldgroups'); foreach ($fieldgroups as $one_field_group_id => $one_field_group_fields) { // Loop through each field in each field group #simple_fields::debug("one_field_group_fields", $one_field_group_fields); #sf_d($one_field_group_fields); // Get info about the field group that are saved // (We only get ID:s posted, so no meta info about the group) $arr_fieldgroup_info = $this->get_field_group($one_field_group_id); foreach ($one_field_group_fields as $one_field_id => $one_field_values) { // one_field_id = id på fältet vi sparar. t.ex. id:et på "måndag" eller "tisdag" // one_field_values = sparade värden för detta fält, sorterat i den ordning som syns i admin // dvs. nyaste överst (med key "new0"), och sedan key 0, key 1, osv. #simple_fields::debug("save, loop fields, one_field_id", $one_field_id); #simple_fields::debug("save, loop fields, one_field_values", $one_field_values); // determine type of field we are saving $field_info = isset($field_groups_option[$one_field_group_id]["fields"][$one_field_id]) ? $field_groups_option[$one_field_group_id]["fields"][$one_field_id] : NULL; $field_type = $field_info["type"]; // @todo: this should be a function #simple_fields::debug("save, field_type", $field_type); $do_wpautop = false; if ($field_type == "textarea" && isset($field_info["type_textarea_options"]["use_html_editor"]) && $field_info["type_textarea_options"]["use_html_editor"] == 1) { // it's a tiny edit area, so use wpautop to fix p and br $do_wpautop = true; } $do_wpautop = apply_filters("simple_fields_save_postdata_do_wpautop", $do_wpautop, $post_id); // save entered value for each added group $num_in_set = 0; foreach ($one_field_values as $one_field_value) { // $one_field_id may be "added" because it's... a special kind of input field $arr_field_info = array(); $one_field_slug = ""; if ("added" === $one_field_id) { $one_field_slug = "added"; } else { #sf_d($arr_fieldgroup_info["fields"], 'fields'); foreach ($arr_fieldgroup_info["fields"] as $one_field_in_fieldgroup) { if (intval($one_field_in_fieldgroup["id"]) === intval($one_field_id)) { $arr_field_info = $one_field_in_fieldgroup; break; } } $one_field_slug = $arr_field_info["slug"]; #sf_d($one_field_slug, 'one_field_slug'); #sf_d($one_field_id, 'one_field_id'); #exit; } $custom_field_key = $this->get_meta_key($one_field_group_id, $one_field_id, $num_in_set, $arr_fieldgroup_info["slug"], $one_field_slug); $custom_field_value = $one_field_value; /*sf_d($custom_field_key, '$custom_field_key'); sf_d($one_field_group_id, '$one_field_group_id'); sf_d($one_field_id, '$one_field_id'); sf_d($num_in_set, 'num_in_set'); sf_d($arr_fieldgroup_info["slug"], 'arr_fieldgroup_info["slug"]'); sf_d($one_field_slug, 'one_field_slug');*/ if (array_key_exists($field_type, $this->registered_field_types)) { // Custom field type $custom_field_value = $this->registered_field_types[$field_type]->edit_save($custom_field_value); /* Date field: Array ( [date_unixtime] => 1351983600000 ) Map field: Array ( [lat] => 59.312089 [lng] => 18.074117 [name] => Monki Skrapan [formatted_address] => Götgatan 78, Stockholm, Sverige [address_components] => [{\"long_name\":\"78\",\"short_name\":\"78\",\"types\":[\"street_number\"]},{\"long_name\":\"Götgatan\",\"short_name\":\"Götgatan\",\"types\":[\"route\"]},{\"long_name\":\"Södermalm\",\"short_name\":\"Södermalm\",\"types\":[\"sublocality\",\"political\"]},{\"long_name\":\"Stockholm\",\"short_name\":\"Stockholm\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Stockholms län\",\"short_name\":\"Stockholms län\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"SE\",\"short_name\":\"SE\",\"types\":[\"country\",\"political\"]},{\"long_name\":\"11830\",\"short_name\":\"11830\",\"types\":[\"postal_code\"]}] ) */ //echo "xxx save value for custom field type"; sf_d($custom_field_value); } else { // core/legacy field type if ($do_wpautop) { $custom_field_value = wpautop($custom_field_value); } } // echo "<br>Saving value for post with id $post_id. Custom_field_key is $custom_field_key, custom_field_value is:";sf_d($custom_field_value); update_post_meta($post_id, $custom_field_key, $custom_field_value); $num_in_set++; } } } // if array } else { if (empty($fieldgroups)) { // if fieldgroups are empty we still need to save it // remove existing simple fields custom fields for this post // @todo: this should also be using wordpress own functions // TODO: use new meta keys names $wpdb->query("DELETE FROM {$table} WHERE post_id = {$post_id} AND meta_key LIKE '_simple_fields_fieldGroupID_%'"); } } // echo "end save"; }
/** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_sql($type, $primary_table, $primary_id_column, $context = null) { global $wpdb; if (!($meta_table = _get_meta_table($type))) { return false; } $meta_id_column = sanitize_key($type . '_id'); $join = array(); $where = array(); $key_only_queries = array(); $queries = array(); // Split out the queries with empty arrays as value foreach ($this->queries as $k => $q) { if (isset($q['value']) && is_array($q['value']) && empty($q['value'])) { $key_only_queries[$k] = $q; unset($this->queries[$k]); } } // Split out the meta_key only queries (we can only do this for OR) if ('OR' == $this->relation) { foreach ($this->queries as $k => $q) { if (!isset($q['value']) && !empty($q['key'])) { $key_only_queries[$k] = $q; } else { $queries[$k] = $q; } } } else { $queries = $this->queries; } // Specify all the meta_key only queries in one go if ($key_only_queries) { $join[] = "INNER JOIN {$meta_table} ON {$primary_table}.{$primary_id_column} = {$meta_table}.{$meta_id_column}"; foreach ($key_only_queries as $key => $q) { $where["key-only-{$key}"] = $wpdb->prepare("{$meta_table}.meta_key = %s", trim($q['key'])); } } foreach ($queries as $k => $q) { $meta_key = isset($q['key']) ? trim($q['key']) : ''; $meta_type = isset($q['type']) ? strtoupper($q['type']) : 'CHAR'; if ('NUMERIC' == $meta_type) { $meta_type = 'SIGNED'; } elseif (!in_array($meta_type, array('BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'))) { $meta_type = 'CHAR'; } $meta_value = isset($q['value']) ? $q['value'] : null; if (isset($q['compare'])) { $meta_compare = strtoupper($q['compare']); } else { $meta_compare = is_array($meta_value) ? 'IN' : '='; } if (!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'NOT EXISTS'))) { $meta_compare = '='; } $i = count($join); $alias = $i ? 'mt' . $i : $meta_table; if ('NOT EXISTS' == $meta_compare) { $join[$i] = "LEFT JOIN {$meta_table}"; $join[$i] .= $i ? " AS {$alias}" : ''; $join[$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column} AND {$alias}.meta_key = '{$meta_key}')"; $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL'; continue; } $join[$i] = "INNER JOIN {$meta_table}"; $join[$i] .= $i ? " AS {$alias}" : ''; $join[$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column})"; $where[$k] = ''; if (!empty($meta_key)) { $where[$k] = $wpdb->prepare("{$alias}.meta_key = %s", $meta_key); } if (is_null($meta_value)) { if (empty($where[$k])) { unset($join[$i]); } continue; } if (in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) { if (!is_array($meta_value)) { $meta_value = preg_split('/[,\\s]+/', $meta_value); } if (empty($meta_value)) { unset($join[$i]); continue; } } else { $meta_value = trim($meta_value); } if ('IN' == substr($meta_compare, -2)) { $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')'; } elseif ('BETWEEN' == substr($meta_compare, -7)) { $meta_value = array_slice($meta_value, 0, 2); $meta_compare_string = '%s AND %s'; } elseif ('LIKE' == substr($meta_compare, -4)) { $meta_value = '%' . like_escape($meta_value) . '%'; $meta_compare_string = '%s'; } else { $meta_compare_string = '%s'; } if (!empty($where[$k])) { $where[$k] .= ' AND '; } $where[$k] = ' (' . $where[$k] . $wpdb->prepare("CAST({$alias}.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value); } $where = array_filter($where); if (empty($where)) { $where = ''; } else { $where = ' AND (' . implode("\n{$this->relation} ", $where) . ' )'; } $join = implode("\n", $join); if (!empty($join)) { $join = ' ' . $join; } return apply_filters_ref_array('get_meta_sql', array(compact('join', 'where'), $this->queries, $type, $primary_table, $primary_id_column, $context)); }
/** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ public function get_sql($type, $primary_table, $primary_id_column, $context = null) { global $wpdb; if (!($meta_table = _get_meta_table($type))) { return false; } $meta_id_column = sanitize_key($type . '_id'); $join = array(); $where = array(); $key_only_queries = array(); $queries = array(); // Split out the queries with empty arrays as value foreach ($this->queries as $k => $q) { if (isset($q['value']) && is_array($q['value']) && empty($q['value'])) { $key_only_queries[$k] = $q; unset($this->queries[$k]); } } // Split out the meta_key only queries (we can only do this for OR) if ('OR' == $this->relation) { foreach ($this->queries as $k => $q) { if ((empty($q['compare']) || 'NOT EXISTS' != $q['compare']) && !array_key_exists('value', $q) && !empty($q['key'])) { $key_only_queries[$k] = $q; } else { $queries[$k] = $q; } } } else { $queries = $this->queries; } // Specify all the meta_key only queries in one go if ($key_only_queries) { $join[] = "INNER JOIN {$meta_table} ON {$primary_table}.{$primary_id_column} = {$meta_table}.{$meta_id_column}"; foreach ($key_only_queries as $key => $q) { $where["key-only-{$key}"] = $wpdb->prepare("{$meta_table}.meta_key = %s", trim($q['key'])); } } foreach ($queries as $k => $q) { $meta_key = isset($q['key']) ? trim($q['key']) : ''; $meta_type = $this->get_cast_for_type(isset($q['type']) ? $q['type'] : ''); if (array_key_exists('value', $q) && is_null($q['value'])) { $q['value'] = ''; } $meta_value = isset($q['value']) ? $q['value'] : null; if (isset($q['compare'])) { $meta_compare = strtoupper($q['compare']); } else { $meta_compare = is_array($meta_value) ? 'IN' : '='; } if (!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'NOT EXISTS', 'REGEXP', 'NOT REGEXP', 'RLIKE'))) { $meta_compare = '='; } $i = count($join); $alias = $i ? 'mt' . $i : $meta_table; if ('NOT EXISTS' == $meta_compare) { $join[$i] = "LEFT JOIN {$meta_table}"; $join[$i] .= $i ? " AS {$alias}" : ''; $join[$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column} AND {$alias}.meta_key = '{$meta_key}')"; $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL'; continue; } $join[$i] = "INNER JOIN {$meta_table}"; $join[$i] .= $i ? " AS {$alias}" : ''; $join[$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column})"; $where[$k] = ''; if (!empty($meta_key)) { $where[$k] = $wpdb->prepare("{$alias}.meta_key = %s", $meta_key); } if (is_null($meta_value)) { if (empty($where[$k])) { unset($join[$i]); } continue; } if (in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) { if (!is_array($meta_value)) { $meta_value = preg_split('/[,\\s]+/', $meta_value); } if (empty($meta_value)) { unset($join[$i]); continue; } } else { $meta_value = trim($meta_value); } if ('IN' == substr($meta_compare, -2)) { $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')'; } elseif ('BETWEEN' == substr($meta_compare, -7)) { $meta_value = array_slice($meta_value, 0, 2); $meta_compare_string = '%s AND %s'; } elseif ('LIKE' == $meta_compare || 'NOT LIKE' == $meta_compare) { $meta_value = '%' . $wpdb->esc_like($meta_value) . '%'; $meta_compare_string = '%s'; } else { $meta_compare_string = '%s'; } if (!empty($where[$k])) { $where[$k] .= ' AND '; } $where[$k] = ' (' . $where[$k] . $wpdb->prepare("CAST({$alias}.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value); } $where = array_filter($where); if (empty($where)) { $where = ''; } else { $where = ' AND (' . implode("\n{$this->relation} ", $where) . ' )'; } $join = implode("\n", $join); if (!empty($join)) { $join = ' ' . $join; } /** * Filter the meta query's generated SQL. * * @since 3.1.0 * * @param array $args { * An array of arguments. * * @type array $clauses Array containing the query's JOIN and WHERE clauses. * @type array $queries Array of meta queries. * @type string $type Type of meta. * @type string $primary_table Primary table. * @type string $primary_id_column Primary column ID. * @type object $context The main query object. * } */ return apply_filters_ref_array('get_meta_sql', array(compact('join', 'where'), $this->queries, $type, $primary_table, $primary_id_column, $context)); }
/** * Evaluate custom field mapping data source * * @since 2.20 * * @param integer post->ID of attachment * @param string category/scope to evaluate against: custom_field_mapping or single_attachment_mapping * @param array data source specification ( name, *data_source, *keep_existing, *format, mla_column, quick_edit, bulk_edit, *meta_name, *option, no_null ) * @param array (optional) _wp_attachment_metadata, default NULL (use current postmeta database value) * * @return string|array data source value */ private static function _evaluate_data_source($post_id, $category, $data_value, $attachment_metadata = NULL) { global $wpdb; static $upload_dir, $intermediate_sizes = NULL, $wp_attached_files = NULL, $wp_attachment_metadata = NULL; static $current_id = 0, $file_info = NULL, $parent_info = NULL, $references = NULL, $alt_text = NULL; if ('none' == $data_value['data_source']) { return ''; } $data_source = $data_value['data_source']; /* * Do this once per page load; cache attachment metadata if mapping all attachments */ if (NULL == $intermediate_sizes) { $upload_dir = wp_upload_dir(); $upload_dir = $upload_dir['basedir'] . '/'; $intermediate_sizes = get_intermediate_image_sizes(); if ('custom_field_mapping' == $category) { if (!($table = _get_meta_table('post'))) { $wp_attached_files = array(); $wp_attachment_metadata = array(); } else { $wp_attachment_metadata = $wpdb->get_results("SELECT post_id, meta_value FROM {$table} WHERE meta_key = '_wp_attachment_metadata'", OBJECT_K); $wp_attached_files = $wpdb->get_results("SELECT post_id, meta_value FROM {$table} WHERE meta_key = '_wp_attached_file'", OBJECT_K); } } // custom_field_mapping, i.e., mapping all attachments } // first call after page load /* * Do this once per post. Simulate SQL results for $wp_attached_files and $wp_attachment_metadata. */ if ($current_id != $post_id) { $current_id = $post_id; $parent_info = NULL; $references = NULL; $alt_text = NULL; if ('single_attachment_mapping' == $category) { $metadata = get_metadata('post', $post_id, '_wp_attached_file'); if (isset($metadata[0])) { $wp_attached_files = array($post_id => (object) array('post_id' => $post_id, 'meta_value' => $metadata[0])); } else { $wp_attached_files = array(); } if (NULL == $attachment_metadata) { $metadata = get_metadata('post', $post_id, '_wp_attachment_metadata'); if (isset($metadata[0])) { $attachment_metadata = $metadata[0]; } } if (empty($attachment_metadata)) { $attachment_metadata = array(); } $wp_attachment_metadata = array($post_id => (object) array('post_id' => $post_id, 'meta_value' => serialize($attachment_metadata))); } $file_info = MLAData_Source::_evaluate_file_information($upload_dir, $wp_attached_files, $wp_attachment_metadata, $post_id); } $size_info = array('file' => '', 'width' => '', 'height' => ''); $match_count = preg_match('/(.+)\\[(.+)\\]/', $data_source, $matches); if (1 == $match_count) { $data_source = $matches[1] . '[size]'; if (isset($file_info['sizes'][$matches[2]])) { $size_info = $file_info['sizes'][$matches[2]]; } } $result = ''; switch ($data_source) { case 'meta': $attachment_metadata = isset($wp_attachment_metadata[$post_id]->meta_value) ? maybe_unserialize($wp_attachment_metadata[$post_id]->meta_value) : array(); $result = MLAData::mla_find_array_element($data_value['meta_name'], $attachment_metadata, $data_value['option'], $data_value['keep_existing']); break; case 'template': if (in_array($data_value['option'], array('single', 'export', 'array', 'multi'))) { $default_option = 'array'; } else { $default_option = 'text'; } /* * Go through the template and expand the non-prefixed elements * as Data Sources */ $item_values = array(); $placeholders = MLAData::mla_get_template_placeholders($data_value['meta_name'], $default_option); foreach ($placeholders as $key => $placeholder) { if (empty($placeholder['prefix'])) { $field_value = $data_value; $field_value['data_source'] = $placeholder['value']; $field_value['meta_name'] = ''; $field_value['option'] = $placeholder['option']; $field_value['format'] = $placeholder['format']; if (isset($placeholder['args'])) { $field_value['args'] = $placeholder['args']; } $field_value = MLAData_Source::_evaluate_data_source($post_id, $category, $field_value, $attachment_metadata); $item_values[$key] = MLAData::mla_apply_field_level_format($field_value, $placeholder); } // Data Source } // foreach placeholder /* * Now expand the template using the above Data Source values */ $template = '[+template:' . $data_value['meta_name'] . '+]'; $item_values = MLAData::mla_expand_field_level_parameters($template, NULL, $item_values, $post_id, $data_value['keep_existing'], $default_option); if ('array' == $default_option) { $result = MLAData::mla_parse_array_template($template, $item_values); $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); } else { $result = MLAData::mla_parse_template($template, $item_values); } break; case 'parent': $data_source = 'post_parent'; /* fallthru */ /* fallthru */ case 'ID': case 'post_id': case 'post_author': case 'post_parent': case 'menu_order': case 'comment_count': $result = absint(MLAData_Source::_evaluate_post_information($post_id, $category, $data_source)); break; case 'alt_text': if (NULL == $alt_text) { $metadata = get_metadata('post', $post_id, '_wp_attachment_image_alt'); if (is_array($metadata)) { if (count($metadata) == 1) { $alt_text = maybe_unserialize($metadata[0]); } else { $alt_text = array(); foreach ($metadata as $single_key => $single_value) { $alt_text[$single_key] = maybe_unserialize($single_value); } } } } if (!empty($alt_text)) { $result = MLAData_Source::_evaluate_array_result($alt_text, $data_value['option'], $data_value['keep_existing']); } break; case 'mime_type': $data_source = 'post_mime_type'; /* fallthru */ /* fallthru */ case 'post_date': case 'post_date_gmt': case 'post_content': case 'post_title': case 'post_excerpt': case 'post_status': case 'comment_status': case 'ping_status': case 'post_name': case 'post_modified': case 'post_modified_gmt': case 'post_content_filtered': case 'guid': case 'post_mime_type': $result = MLAData_Source::_evaluate_post_information($post_id, $category, $data_source); break; case 'absolute_path': case 'absolute_file_name': case 'base_file': case 'path': case 'file_name': case 'name_only': case 'extension': case 'width': case 'height': case 'orientation': case 'hwstring_small': case 'aperture': case 'credit': case 'camera': case 'caption': case 'created_timestamp': case 'copyright': case 'focal_length': case 'iso': case 'shutter_speed': case 'title': if (isset($file_info[$data_source])) { $result = $file_info[$data_source]; } break; case 'file_size': $filesize = @filesize($file_info['absolute_file_name_raw']); if (!(false === $filesize)) { $result = $filesize; } break; case 'upload_date': $result = MLAData_Source::_evaluate_post_information($post_id, $category, 'post_date'); break; case 'dimensions': $result = $file_info['width'] . 'x' . $file_info['height']; if ('x' == $result) { $result = ''; } break; case 'pixels': $result = absint((int) $file_info['width'] * (int) $file_info['height']); if (0 == $result) { $result = ''; } else { $result = (string) $result; } break; case 'size_keys': $result = array(); foreach ($file_info['sizes'] as $key => $value) { $result[] = $key; } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); break; case 'size_names': $result = array(); foreach ($file_info['sizes'] as $key => $value) { $result[] = $value['file']; } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); break; case 'size_bytes': $result = array(); foreach ($file_info['sizes'] as $key => $value) { $filesize = @filesize($file_info['absolute_path_raw'] . $value['file']); if (false === $filesize) { $result[] = '?'; } else { switch ($data_value['format']) { case 'commas': if (is_numeric($filesize)) { $filesize = number_format((double) $filesize); } break; default: // no change } // format $result[] = $filesize; } } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); break; case 'size_pixels': $result = array(); foreach ($file_info['sizes'] as $key => $value) { $pixels = absint((int) $value['width'] * (int) $value['height']); switch ($data_value['format']) { case 'commas': if (is_numeric($pixels)) { $pixels = number_format((double) $pixels); } break; default: // no change } // format $result[] = $pixels; } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); break; case 'size_dimensions': $result = array(); foreach ($file_info['sizes'] as $key => $value) { $result[] = $value['width'] . 'x' . $value['height']; } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); break; case 'size_name[size]': $result = $size_info['file']; break; case 'size_bytes[size]': $result = @filesize($file_info['absolute_path_raw'] . $size_info['file']); if (false === $result) { $result = '?'; } break; case 'size_pixels[size]': $result = absint((int) $size_info['width'] * (int) $size_info['height']); break; case 'size_dimensions[size]': $result = $size_info['width'] . 'x' . $size_info['height']; if ('x' == $result) { $result = ''; } break; case 'parent_date': case 'parent_type': case 'parent_title': if (is_null($parent_info)) { $parent_info = MLAQuery::mla_fetch_attachment_parent_data(MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (isset($parent_info[$data_source])) { $result = $parent_info[$data_source]; } break; case 'parent_issues': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['parent_errors'])) { $result = $references['parent_errors']; /* * Remove (ORPHAN... */ $orphan_certain = '(' . __('ORPHAN', 'media-library-assistant') . ')'; $orphan_possible = '(' . __('ORPHAN', 'media-library-assistant') . '?)'; if (false !== strpos($result, $orphan_certain)) { $result = trim(substr($result, strlen($orphan_certain))); } elseif (false !== strpos($result, $orphan_possible)) { $result = trim(substr($result, strlen($orphan_possible))); } } break; case 'reference_issues': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['parent_errors'])) { $result = $references['parent_errors']; } break; case 'featured_in': case 'featured_in_title': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['features'])) { $result = array(); foreach ($references['features'] as $ID => $value) { if ('featured_in' == $data_source) { $result[] = sprintf('%1$s (%2$s %3$d)', $value->post_title, $value->post_type, $ID); } else { $result[] = $value->post_title; } } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); } else { $result = ''; } break; case 'inserted_in': case 'inserted_in_title': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['inserts'])) { $result = array(); foreach ($references['inserts'] as $base_file => $inserts) { foreach ($inserts as $value) { if ('inserted_in' == $data_source) { $result[] = sprintf('%1$s (%2$s %3$d)', $value->post_title, $value->post_type, $value->ID); } else { $result[] = $value->post_title; } } } ksort($result); $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); } else { $result = ''; } break; case 'gallery_in': case 'gallery_in_title': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['galleries'])) { $result = array(); foreach ($references['galleries'] as $ID => $value) { if ('gallery_in' == $data_source) { $result[] = sprintf('%1$s (%2$s %3$d)', $value['post_title'], $value['post_type'], $ID); } else { $result[] = $value['post_title']; } } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); } else { $result = ''; } break; case 'mla_gallery_in': case 'mla_gallery_in_title': if (is_null($references)) { $references = MLAQuery::mla_fetch_attachment_references($post_id, MLAData_Source::_evaluate_post_information($post_id, $category, 'post_parent')); } if (!empty($references['mla_galleries'])) { $result = array(); foreach ($references['mla_galleries'] as $ID => $value) { if ('mla_gallery_in' == $data_source) { $result[] = sprintf('%1$s (%2$s %3$d)', $value['post_title'], $value['post_type'], $ID); } else { $result[] = $value['post_title']; } } $result = MLAData_Source::_evaluate_array_result($result, $data_value['option'], $data_value['keep_existing']); } else { $result = ''; } break; default: $custom_value = apply_filters('mla_evaluate_custom_data_source', NULL, $post_id, $category, $data_value, $attachment_metadata); if (!is_null($custom_value)) { return $custom_value; } return ''; } // switch $data_source switch ($data_value['format']) { case 'raw': return $result; case 'commas': if (is_numeric($result)) { $result = str_pad(number_format((double) $result), 15, ' ', STR_PAD_LEFT); } break; case 'native': default: /* * Make some numeric values sortable as strings, make all value non-empty */ if (in_array($data_source, array('file_size', 'pixels', 'width', 'height'))) { $result = str_pad($result, 15, ' ', STR_PAD_LEFT); } elseif (empty($result)) { $result = ' '; } } // format return $result; }
/** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_sql($type, $primary_table, $primary_id_column, $context = null) { global $wpdb; if (!($meta_table = _get_meta_table($type))) { return false; } $meta_id_column = esc_sql($type . '_id'); $join = array(); $where = array(); foreach ($this->queries as $k => $q) { $meta_key = isset($q['key']) ? trim($q['key']) : ''; $meta_compare = isset($q['compare']) ? strtoupper($q['compare']) : '='; $meta_type = isset($q['type']) ? strtoupper($q['type']) : 'CHAR'; if (!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) { $meta_compare = '='; } if ('NUMERIC' == $meta_type) { $meta_type = 'SIGNED'; } elseif (!in_array($meta_type, array('BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'))) { $meta_type = 'CHAR'; } $i = count($join); $alias = $i ? 'mt' . $i : $meta_table; // Set JOIN $join[$i] = "INNER JOIN {$meta_table}"; $join[$i] .= $i ? " AS {$alias}" : ''; $join[$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column})"; $where[$k] = ''; if (!empty($meta_key)) { $where[$k] = $wpdb->prepare("{$alias}.meta_key = %s", $meta_key); } if (!isset($q['value'])) { if (empty($where[$k])) { unset($join[$i]); } continue; } $meta_value = $q['value']; if (in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) { if (!is_array($meta_value)) { $meta_value = preg_split('/[,\\s]+/', $meta_value); } if (empty($meta_value)) { unset($join[$i]); continue; } } else { $meta_value = trim($meta_value); } if ('IN' == substr($meta_compare, -2)) { $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')'; } elseif ('BETWEEN' == substr($meta_compare, -7)) { $meta_value = array_slice($meta_value, 0, 2); $meta_compare_string = '%s AND %s'; } elseif ('LIKE' == substr($meta_compare, -4)) { $meta_value = '%' . like_escape($meta_value) . '%'; $meta_compare_string = '%s'; } else { $meta_compare_string = '%s'; } if (!empty($where[$k])) { $where[$k] .= ' AND '; } $where[$k] = ' (' . $where[$k] . $wpdb->prepare("CAST({$alias}.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value); } $where = array_filter($where); if (empty($where)) { $where = ''; } else { $where = ' AND (' . implode("\n{$this->relation} ", $where) . ' )'; } $join = implode("\n", $join); if (!empty($join)) { $join = ' ' . $join; } return apply_filters_ref_array('get_meta_sql', array(compact('join', 'where'), $this->queries, $type, $primary_table, $primary_id_column, $context)); }
protected function get_metadata($ids, $meta_type, $meta_key_whitelist) { global $wpdb; $table = _get_meta_table($meta_type); $id = $meta_type . '_id'; if (!$table) { return array(); } $private_meta_whitelist_sql = "'" . implode("','", array_map('esc_sql', $meta_key_whitelist)) . "'"; return array_map(array($this, 'unserialize_meta'), $wpdb->get_results("SELECT {$id}, meta_key, meta_value, meta_id FROM {$table} WHERE {$id} IN ( " . implode(',', wp_parse_id_list($ids)) . ' )' . " AND meta_key IN ( {$private_meta_whitelist_sql} ) ", OBJECT)); }
private function get_meta_sql($name, $meta_query, $type, $primary_table, $primary_id_column) { $query = get_meta_sql($meta_query, $type, $primary_table, $primary_id_column); if (function_exists('_get_meta_table')) { $meta_table = _get_meta_table($type); $query['join'] = str_replace($meta_table, $name, $query['join']); $query['where'] = str_replace($meta_table, $name, $query['where']); $query['join'] = str_replace("JOIN {$name} ON", "JOIN {$meta_table} AS {$name} ON", $query['join']); } return array('join' => $query['join'], 'where' => $this->clean_meta_query_condition($query['where'])); }
public function delete_metadata($type, $object_id, $meta_ids) { global $wpdb; $table = _get_meta_table($type); if (!$table) { return false; } foreach ($meta_ids as $meta_id) { $wpdb->query($wpdb->prepare("DELETE FROM {$table} WHERE meta_id = %d", $meta_id)); } // if we don't have an object ID what do we do - invalidate ALL meta? if ($object_id) { wp_cache_delete($object_id, $type . '_meta'); } }
function hocwp_meta_table_registered($type) { return _get_meta_table($type); }
function pmwi_update_prices($pid) { $table = _get_meta_table('post'); $post_meta_infos = $this->wpdb->get_results("SELECT meta_key, meta_value FROM {$table} WHERE post_id={$pid}"); foreach ($post_meta_infos as $meta_info) { if (in_array($meta_info->meta_key, array('_regular_price_tmp', '_sale_price_tmp', '_sale_price_dates_from_tmp', '_sale_price_dates_from_tmp', '_sale_price_dates_to_tmp', '_price_tmp', '_stock_tmp'))) { $this->pushmeta($pid, str_replace('_tmp', '', $meta_info->meta_key), $meta_info->meta_value); delete_post_meta($pid, $meta_info->meta_key); } } //$this->executeSQL(); }
function fw_delete_post_meta($post_id, $meta_key, $meta_value = '') { // 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; $delete_all = false; if (!$meta_type || !$meta_key) { return false; } if (!($object_id = absint($object_id)) && !$delete_all) { return false; } if (!($table = _get_meta_table($meta_type))) { return false; } global $wpdb; $type_column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) // $meta_key = stripslashes($meta_key); // this was the trouble ! // $meta_value = stripslashes_deep($meta_value); // this was the trouble ! $check = apply_filters("delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all); if (null !== $check) { return (bool) $check; } $_meta_value = $meta_value; $meta_value = maybe_serialize($meta_value); $query = $wpdb->prepare("SELECT {$id_column} FROM {$table} WHERE meta_key = %s", $meta_key); if (!$delete_all) { $query .= $wpdb->prepare(" AND {$type_column} = %d", $object_id); } if ($meta_value) { $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value); } $meta_ids = $wpdb->get_col($query); if (!count($meta_ids)) { return false; } if ($delete_all) { $object_ids = $wpdb->get_col($wpdb->prepare("SELECT {$type_column} FROM {$table} WHERE meta_key = %s", $meta_key)); } do_action("delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value); // Old-style action. if ('post' == $meta_type) { do_action('delete_postmeta', $meta_ids); } $query = "DELETE FROM {$table} WHERE {$id_column} IN( " . implode(',', $meta_ids) . " )"; $count = $wpdb->query($query); if (!$count) { return false; } if ($delete_all) { foreach ((array) $object_ids as $o_id) { wp_cache_delete($o_id, $meta_type . '_meta'); } } else { wp_cache_delete($object_id, $meta_type . '_meta'); } do_action("deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value); // Old-style action. if ('post' == $meta_type) { do_action('deleted_postmeta', $meta_ids); } return true; }
function simple_fields_save_postdata($post_id = null, $post = null) { // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times // so not checking nonce can lead to errors, for example losing post connector if (!isset($_POST['simple_fields_nonce']) || !wp_verify_nonce($_POST['simple_fields_nonce'], plugin_basename(__FILE__))) { return $post_id; } // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // attach post connector $simple_fields_selected_connector = isset($_POST["simple_fields_selected_connector"]) ? $_POST["simple_fields_selected_connector"] : null; update_post_meta($post_id, "_simple_fields_selected_connector", $simple_fields_selected_connector); $post_id = (int) $post_id; $fieldgroups = isset($_POST["simple_fields_fieldgroups"]) ? $_POST["simple_fields_fieldgroups"] : null; $field_groups_option = get_option("simple_fields_groups"); if (!($table = _get_meta_table("post"))) { return false; } global $wpdb; if ($post_id && is_array($fieldgroups)) { // remove existing simple fields custom fields for this post $wpdb->query("DELETE FROM {$table} WHERE post_id = {$post_id} AND meta_key LIKE '_simple_fields_fieldGroupID_%'"); // cleanup missing keys, due to checkboxes not being checked $fieldgroups_fixed = $fieldgroups; foreach ($fieldgroups as $one_field_group_id => $one_field_group_fields) { foreach ($one_field_group_fields as $posted_id => $posted_vals) { if ($posted_id == "added") { // echo "<br><br>posted_id: $posted_id"; // echo "<br>posted_vals: "; bonny_d($posted_vals); // $fieldgroups_fixed[$one_field_group_id][$posted_id]["added"] = $posted_vals; continue; } $fieldgroups_fixed[$one_field_group_id][$posted_id] = array(); // echo "<br><br>posted_id: $posted_id"; // echo "<br>posted_vals: "; bonny_d($posted_vals); // bonny_d($added_vals); // loopa igenom "added"-värdena och fixa så att allt finns foreach ($one_field_group_fields["added"] as $added_id => $added_val) { // $fieldgroups_fixed // echo "<br>added_id: $added_id"; // echo "<br>added_val: $added_val"; $fieldgroups_fixed[$one_field_group_id][$posted_id][$added_id] = $fieldgroups[$one_field_group_id][$posted_id][$added_id]; } } } $fieldgroups = $fieldgroups_fixed; update_post_meta($post_id, "_simple_fields_been_saved", "1"); foreach ($fieldgroups as $one_field_group_id => $one_field_group_fields) { foreach ($one_field_group_fields as $one_field_id => $one_field_values) { // one_field_id = id på fältet vi sparar. t.ex. id:et på "måndag" eller "tisdag" // one_field_values = sparade värden för detta fält, sorterat i den ordning som syns i admin // dvs. nyaste överst (med key "new0"), och sedan key 0, key 1, osv. // determine type of field we are saving $field_info = isset($field_groups_option[$one_field_group_id]["fields"][$one_field_id]) ? $field_groups_option[$one_field_group_id]["fields"][$one_field_id] : NULL; $field_type = $field_info["type"]; // @todo: this should be a function $do_wpautop = false; if ($field_type == "textarea" && isset($field_info["type_textarea_options"]["use_html_editor"]) && $field_info["type_textarea_options"]["use_html_editor"] == 1) { // it's a tiny edit area, so use wpautop to fix p and br $do_wpautop = true; } // @todo: empty checkboxes = values saved for the wrong fieldgroup // it "jumps" past one of the groups when saving, so the wrong group gets the value // ide: korrigera arrayen? istället för sparandet $num_in_set = 0; // save entered value for each added group foreach ($one_field_values as $one_field_value) { $custom_field_key = "_simple_fields_fieldGroupID_{$one_field_group_id}_fieldID_{$one_field_id}_numInSet_{$num_in_set}"; $custom_field_value = $one_field_value; if ($do_wpautop) { $custom_field_value = wpautop($custom_field_value); #var_dump($custom_field_value);#exit; } update_post_meta($post_id, $custom_field_key, $custom_field_value); $num_in_set++; } } } // if array } else { if (empty($fieldgroups)) { // if fieldgroups are empty we still need to save it // remove existing simple fields custom fields for this post $wpdb->query("DELETE FROM {$table} WHERE post_id = {$post_id} AND meta_key LIKE '_simple_fields_fieldGroupID_%'"); } } }
/** * メタデータを削除 * * @param string $key メタキー * @param mixed $value 指定した場合、その値をもつメタデータのみ削除 * @return bool */ public function delete($key = '', $value = '') { if (_get_meta_table($this->meta_type)) { if ($key) { return delete_metadata($this->meta_type, $this->id, $key, $value); } } else { if (!$key) { return false; } $option_name = $this->get_option_name(); $option = get_option($option_name); if (isset($option[$key]) && $value === '') { unset($option[$key]); return update_option($option_name, $option); } if (isset($option[$key]) && $value !== '') { foreach ($option[$key] as $option_key => $option_value) { if ($option_value === $value) { unset($option[$key][$option_key]); } } return update_option($option_name, $option); } } }
/** * Retrieve custom fields for post. * * @param int $id Post ID * @return (array[]|WP_Error) List of meta object data on success, WP_Error otherwise */ public function get_all_meta($id) { $id = (int) $id; if (empty($id)) { return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 404)); } $post = get_post($id, ARRAY_A); if (empty($post['ID'])) { return new WP_Error('json_post_invalid_id', __('Invalid post ID.'), array('status' => 404)); } if (!$this->check_edit_permission($post)) { return new WP_Error('json_cannot_edit', __('Sorry, you cannot edit this post'), array('status' => 403)); } global $wpdb; $table = _get_meta_table('post'); $results = $wpdb->get_results($wpdb->prepare("SELECT meta_id, meta_key, meta_value FROM {$table} WHERE post_id = %d", $id)); $meta = array(); foreach ($results as $row) { $value = $this->prepare_meta($id, $row, true); if (is_wp_error($value)) { continue; } $meta[] = $value; } return apply_filters('json_prepare_meta', $meta, $id); }
/** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta, eg 'user', 'post'. * @param string $primary_table Database table where the object being filtered is stored (eg wp_users). * @param string $primary_id_column ID column for the filtered object in $primary_table. * @param object $context Optional. The main query object. * @return array { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql($type, $primary_table, $primary_id_column, $context = null) { if (!($meta_table = _get_meta_table($type))) { return false; } $this->meta_table = $meta_table; $this->meta_id_column = sanitize_key($type . '_id'); $this->primary_table = $primary_table; $this->primary_id_column = $primary_id_column; $sql = $this->get_sql_clauses(); /* * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should * be LEFT. Otherwise posts with no metadata will be excluded from results. */ if (false !== strpos($sql['join'], 'LEFT JOIN')) { $sql['join'] = str_replace('INNER JOIN', 'LEFT JOIN', $sql['join']); } /** * Filter the meta query's generated SQL. * * @since 3.1.0 * * @param array $args { * An array of meta query SQL arguments. * * @type array $clauses Array containing the query's JOIN and WHERE clauses. * @type array $queries Array of meta queries. * @type string $type Type of meta. * @type string $primary_table Primary table. * @type string $primary_id_column Primary column ID. * @type object $context The main query object. * } */ return apply_filters_ref_array('get_meta_sql', array($sql, $this->queries, $type, $primary_table, $primary_id_column, $context)); }
/** * Retrieve custom fields for post. * * @param int $id Post ID * @return (array[]|WP_Error) List of meta object data on success, WP_Error otherwise */ public function get_history($uid, $type) { if (empty($uid)) { $this->set_status(404); return array('message' => __('Invalid Unique ID.')); } //$post = get_post($id, ARRAY_A); if (empty($uid)) { $this->set_status(404); return array('message' => __('Invalid Unique ID.')); } if (!$this->check_edit_permission($post)) { //return new WP_Error( 'json_cannot_edit', __( 'Sorry, you cannot edit this post' ), array( 'status' => 403 ) ); } global $wpdb; $table = _get_meta_table('post'); $sql = "SELECT distinct(p.ID) FROM " . $wpdb->posts . " as p " . " INNER JOIN " . $table . " as m ON m.post_id=p.ID and m.meta_value='" . $uid . "'" . " WHERE p.post_type LIKE %s"; $results = $wpdb->get_results($wpdb->prepare($sql, $type)); $post_ids = array(); foreach ($results as $row) { $post_ids[] = $row->ID; } //return array($post_ids); $sql = "SELECT post_id, meta_value FROM {$table} WHERE post_id in ('" . implode("','", $post_ids) . "') and meta_key LIKE %s order by meta_value asc limit 0, 5"; $results = $wpdb->get_results($wpdb->prepare($sql, 'date_time')); $meta = array(); foreach ($results as $row) { $meta[] = array('post_id' => $row->post_id, 'date_time' => $row->meta_value); } return array('count' => count($meta), 'result' => $meta); }