/** * Parse and sanitize 'orderby' keys passed to the user query. * * @since 4.2.0 * @access protected * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby Alias for the field to order by. * @return string Value to used in the ORDER clause, if `$orderby` is valid. */ protected function parse_orderby($orderby) { global $wpdb; $meta_query_clauses = $this->meta_query->get_clauses(); $_orderby = ''; if (in_array($orderby, array('login', 'nicename', 'email', 'url', 'registered'))) { $_orderby = 'user_' . $orderby; } elseif (in_array($orderby, array('user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered'))) { $_orderby = $orderby; } elseif ('name' == $orderby || 'display_name' == $orderby) { $_orderby = 'display_name'; } elseif ('post_count' == $orderby) { // todo: avoid the JOIN $where = get_posts_by_author_sql('post'); $this->query_from .= " LEFT OUTER JOIN (\n\t\t\t\tSELECT post_author, COUNT(*) as post_count\n\t\t\t\tFROM {$wpdb->posts}\n\t\t\t\t{$where}\n\t\t\t\tGROUP BY post_author\n\t\t\t) p ON ({$wpdb->users}.ID = p.post_author)\n\t\t\t"; $_orderby = 'post_count'; } elseif ('ID' == $orderby || 'id' == $orderby) { $_orderby = 'ID'; } elseif ('meta_value' == $orderby || $this->get('meta_key') == $orderby) { $_orderby = "{$wpdb->usermeta}.meta_value"; } elseif ('meta_value_num' == $orderby) { $_orderby = "{$wpdb->usermeta}.meta_value+0"; } elseif ('include' === $orderby && !empty($this->query_vars['include'])) { $include = wp_parse_id_list($this->query_vars['include']); $include_sql = implode(',', $include); $_orderby = "FIELD( {$wpdb->users}.ID, {$include_sql} )"; } elseif (isset($meta_query_clauses[$orderby])) { $meta_clause = $meta_query_clauses[$orderby]; $_orderby = sprintf("CAST(%s.meta_value AS %s)", esc_sql($meta_clause['alias']), esc_sql($meta_clause['cast'])); } return $_orderby; }
/** * Retrieve list of latest posts or posts matching criteria. * * The defaults are as follows: * 'numberposts' - Default is 5. Total number of posts to retrieve. * 'offset' - Default is 0. See {@link WP_Query::query()} for more. * 'category' - What category to pull the posts from. * 'orderby' - Default is 'date', which orders based on post_date. How to order the posts. * 'order' - Default is 'DESC'. The order to retrieve the posts. * 'include' - See {@link WP_Query::query()} for more. * 'exclude' - See {@link WP_Query::query()} for more. * 'meta_key' - See {@link WP_Query::query()} for more. * 'meta_value' - See {@link WP_Query::query()} for more. * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few. * 'post_parent' - The parent of the post or post type. * 'post_status' - Default is 'publish'. Post status to retrieve. * * @uses WP_Query::query() See for more default arguments and information. * @uses ES_WP_Query * @link http://codex.wordpress.org/Template_Tags/get_posts * * @param array $args Optional. Overrides defaults. * @return array List of posts. */ function es_get_posts($args = null) { $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'date', 'order' => 'DESC', 'include' => array(), 'exclude' => array(), 'meta_key' => '', 'meta_value' => '', 'post_type' => 'post', 'suppress_filters' => true); $r = wp_parse_args($args, $defaults); if (empty($r['post_status'])) { $r['post_status'] = 'attachment' == $r['post_type'] ? 'inherit' : 'publish'; } if (!empty($r['numberposts']) && empty($r['posts_per_page'])) { $r['posts_per_page'] = $r['numberposts']; } if (!empty($r['category'])) { $r['cat'] = $r['category']; } if (!empty($r['include'])) { $incposts = wp_parse_id_list($r['include']); $r['posts_per_page'] = count($incposts); // only the number of posts included $r['post__in'] = $incposts; } elseif (!empty($r['exclude'])) { $r['post__not_in'] = wp_parse_id_list($r['exclude']); } $r['ignore_sticky_posts'] = true; $r['no_found_rows'] = true; $get_posts = new ES_WP_Query(); return $get_posts->query($r); }
function setup_group_ids() { global $wpdb, $bp; $sql = "SELECT group_id FROM {$bp->groups->table_name_groupmeta} WHERE "; $join_clauses = array(); $where_clauses = array(); $counter = 1; $filter_count = count($this->filters); foreach ($this->filters as $key => $value) { $table_shortname = 'gmf' . $counter; $join_sql = $counter > 1 ? " LEFT JOIN {$bp->groups->table_name_groupmeta} {$table_shortname} ON gmf1.group_id = {$table_shortname}.group_id " : "{$bp->groups->table_name_groupmeta} {$table_shortname}"; $join_clauses[] = $join_sql; $clause = $wpdb->prepare("{$table_shortname}.meta_key = %s", $key); if (false !== $value) { $clause .= $wpdb->prepare(" AND {$table_shortname}.meta_value = %s", $value); } $where_clauses[] = $clause; // If this key matches the orderby param, stash the table shortname if (!empty($this->orderby) && $this->orderby == $key) { $this->orderby_shortname = $table_shortname; } $counter++; } if (!empty($where_clauses)) { $sql = "SELECT gmf1.group_id FROM " . implode(' ', $join_clauses) . " WHERE " . implode(' AND ', $where_clauses); } else { $sql = $wpdb->get_results("SELECT id FROM {$bp->groups->table_name} WHERE 1 = 0"); } $this->group_ids = wp_parse_id_list($wpdb->get_col($sql)); }
/** * Standard meta retrieval * * @param int $post_id * @param bool $saved * @param array $field * * @return array */ public static function meta($post_id, $saved, $field) { $meta = get_post_meta($post_id, $field['id'], true); $meta = wp_parse_id_list($meta); $meta = array_filter($meta); return $meta; }
/** * Filters out product categories the user does not have access to. * @since 2.5.8 * @global type $wpdb * @param array $args * @param array $taxonomies * @return array */ public function taxonomy_filter($args, $taxonomies) { global $wpdb; if (in_array('product_cat', $taxonomies)) { $disallowed = $this->get_cached_exclusions('cat'); if ($disallowed === false) { $user_roles = $this->get_roles_for_current_user(); $sql = " SELECT term_id FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = 'product_cat' AND term_id NOT IN (\n\t\t\t\tSELECT term_id FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = 'product_cat' AND term_id NOT IN (SELECT {$wpdb->prefix}woocommerce_termmeta.woocommerce_term_id FROM {$wpdb->prefix}woocommerce_termmeta WHERE meta_key = '_wc_restrictions')\n\t\t\t\tUNION ALL \n\t\t\t\tSELECT {$wpdb->prefix}woocommerce_termmeta.woocommerce_term_id FROM {$wpdb->prefix}woocommerce_termmeta WHERE ( (meta_key ='_wc_restrictions' AND meta_value = 'public') OR (meta_key = '_wc_restrictions_allowed' AND meta_value IN ('" . implode("','", $user_roles) . "') ) ) )"; $disallowed = $wpdb->get_col($sql); if ($disallowed !== false) { $session_id = WC_Catalog_Visibility_Compatibility::WC()->session->get_customer_id(); set_transient('twccr_' . $session_id . '_cat', $disallowed, 60 * 60 * 24); } } if ($disallowed && count($disallowed)) { $disallowed = array_map('intval', $disallowed); if (isset($args['include']) && !empty($args['include'])) { $include = wp_parse_id_list($args['include']); $allowed = array_filter(array_diff($include, $disallowed)); if (empty($allowed)) { $args['include'] = array(); $args['exclude'] = $disallowed; } else { $args['include'] = $allowed; } } else { $exclude = wp_parse_id_list($args['exclude']); $args['exclude'] = isset($exclude) && !empty($exclude) ? array_merge($exclude, $disallowed) : $disallowed; } } } else { } return $args; }
function circleflip_post_formats_save_metabox($post_id) { if (!isset($_POST['_circleflip_post_formats']) || !wp_verify_nonce($_POST['_circleflip_post_formats']['_nonce'], __FILE__) || defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || !current_user_can('edit_post', $post_id)) { return $post_id; } $format = get_post_format($post_id); $data = array(); if ('audio' === $format) { if (!empty($_POST['_circleflip_post_formats']['audio_id'])) { $data['audio_id'] = (int) $_POST['_circleflip_post_formats']['audio_id']; } else { $data['audio_embed'] = $_POST['_circleflip_post_formats']['audio_embed']; } } else { if ('video' === $format) { if (!empty($_POST['_circleflip_post_formats']['video_id'])) { $data['video_id'] = (int) $_POST['_circleflip_post_formats']['video_id']; } else { $data['video_embed'] = $_POST['_circleflip_post_formats']['video_embed']; } } else { if ('gallery' === $format) { $ids_string = $_POST['_circleflip_post_formats']['gallery']; $data['gallery'] = wp_parse_id_list($ids_string); $data['gallery_layout'] = $_POST['_circleflip_post_formats']['layout']; } } } update_post_meta($post_id, '_circleflip_post_formats', $data); }
/** * Modify query to filter users by group. * * @param WP_User_Query $user_query * @return WP_User_Query */ public static function pre_user_query($user_query) { global $pagenow, $wpdb; if ($pagenow == 'users.php' && empty($_GET['page'])) { if (isset($_REQUEST['group'])) { $group_id = $_REQUEST['group']; if (Groups_Group::read($group_id)) { $group = new Groups_Group($group_id); $users = $group->users; $include = array(); if (count($users) > 0) { foreach ($users as $user) { $include[] = $user->user->ID; } } else { // no results $include[] = 0; } $ids = implode(',', wp_parse_id_list($include)); $user_query->query_where .= " AND {$wpdb->users}.ID IN ({$ids})"; } } } return $user_query; }
/** * @group get_current_threads_for_user * @expectedDeprecated BP_Messages_Thread::get_current_threads_for_user */ public function test_get_current_threads_for_user_with_old_args() { $u1 = $this->factory->user->create(); $u2 = $this->factory->user->create(); $t1 = $this->factory->message->create(array('sender_id' => $u1, 'recipients' => array($u2), 'subject' => 'Foo')); $t2 = $this->factory->message->create(array('sender_id' => $u1, 'recipients' => array($u2), 'subject' => 'Bar')); $threads = BP_Messages_Thread::get_current_threads_for_user($u1, 'sentbox', 'all', null, null, 'ar'); $expected = array($t2); $found = wp_parse_id_list(wp_list_pluck($threads['threads'], 'thread_id')); $this->assertSame($expected, $found); }
public function find($ids) { if (is_numeric($ids)) { return $this->get_term($ids); } $incposts = wp_parse_id_list($ids); $this->posts_per_page = count($incposts); // only the number of posts included $this->post__in = $incposts; return count($incposts) == 1 ? $this->first() : $this->get(); }
function mb_remove_user_topic_bookmark($user_id, $topic_id) { $user_id = mb_get_user_id($user_id); $topic_id = mb_get_topic_id($topic_id); $favs = mb_get_user_topic_bookmarks($user_id); if (in_array($topic_id, $favs)) { wp_cache_delete('mb_get_topic_bookmarkers_' . $topic_id, 'message-board-users'); $_sub = array_search($topic_id, $favs); unset($favs[$_sub]); $favs = implode(',', wp_parse_id_list(array_filter($favs))); return update_user_meta($user_id, mb_get_user_topic_bookmarks_meta_key(), $favs); } return false; }
/** * Loads variation child IDs. * @param WC_Product * @param bool $force_read True to bypass the transient. * @return WC_Product */ public function read_children(&$product, $force_read = false) { $children_transient_name = 'wc_product_children_' . $product->get_id(); $children = get_transient($children_transient_name); if (empty($children) || !is_array($children) || !isset($children['all']) || !isset($children['visible']) || $force_read) { $all_args = $visible_only_args = array('post_parent' => $product->get_id(), 'post_type' => 'product_variation', 'orderby' => 'menu_order', 'order' => 'ASC', 'fields' => 'ids', 'post_status' => 'publish', 'numberposts' => -1); if ('yes' === get_option('woocommerce_hide_out_of_stock_items')) { $visible_only_args['meta_query'][] = array('key' => '_stock_status', 'value' => 'instock', 'compare' => '='); } $children['all'] = get_posts(apply_filters('woocommerce_variable_children_args', $all_args, $product, false)); $children['visible'] = get_posts(apply_filters('woocommerce_variable_children_args', $visible_only_args, $product, true)); set_transient($children_transient_name, $children, DAY_IN_SECONDS * 30); } $product->set_children(wp_parse_id_list((array) $children['all'])); $product->set_visible_children(wp_parse_id_list((array) $children['visible'])); }
/** * Filter BP_User_Query::populate_extras to add confirmed friendship status. * * Each member in the user query is checked for confirmed friendship status * against the logged-in user. * * @since 1.7.0 * * @global WPDB $wpdb WordPress database access object. * * @param BP_User_Query $user_query The BP_User_Query object. * @param string $user_ids_sql Comma-separated list of user IDs to fetch extra * data for, as determined by BP_User_Query. */ function bp_friends_filter_user_query_populate_extras(BP_User_Query $user_query, $user_ids_sql) { global $wpdb; // Stop if user isn't logged in. if (!($user_id = bp_loggedin_user_id())) { return; } $maybe_friend_ids = wp_parse_id_list($user_ids_sql); foreach ($maybe_friend_ids as $friend_id) { $status = BP_Friends_Friendship::check_is_friend($user_id, $friend_id); $user_query->results[$friend_id]->friendship_status = $status; if ('is_friend' == $status) { $user_query->results[$friend_id]->is_friend = 1; } } }
/** * Setup the object * * @param array $args Arguments containing from taxonomy, to taxonomy, * and additional optional params * * @since 1.0.0 */ public function __construct($args = array()) { $args = wp_parse_args($args, array('from_tax' => '', 'to_tax' => '', 'parent' => '', 'terms' => '')); if (!$args['from_tax'] || !$args['to_tax']) { return; } if (!empty($args['parent'])) { $this->parent = absint($args['parent']); } if (!empty($args['terms'])) { $this->terms = wp_parse_id_list($args['terms']); } $this->is_ui = isset($_GET['page']) && 'taxonomy-switcher' == $_GET['page']; $this->from = sanitize_text_field($args['from_tax']); $this->to = sanitize_text_field($args['to_tax']); }
public function exclude($taxonomy, $string) { global $yarpp; echo "<div class='yarpp_form_row yarpp_form_exclude'><div class='yarpp_form_label'>"; echo $string; echo "</div><div class='yarpp_scroll_wrapper'><div class='exclude_terms' id='exclude_{$taxonomy}'>"; $exclude_tt_ids = wp_parse_id_list(yarpp_get_option('exclude')); $exclude_term_ids = $yarpp->admin->get_term_ids_from_tt_ids($taxonomy, $exclude_tt_ids); if (count($exclude_term_ids)) { $terms = get_terms($taxonomy, array('include' => $exclude_term_ids)); foreach ($terms as $term) { echo "<input type='checkbox' name='exclude[{$term->term_taxonomy_id}]' id='exclude_{$term->term_taxonomy_id}' value='true' checked='checked' /> <label for='exclude_{$term->term_taxonomy_id}'>" . esc_html($term->name) . "</label> "; } } echo "</div></div></div>"; }
/** * Update the metadata cache for the specified objects. * * @since BuddyPress (1.6) * @global $wpdb WordPress database object for queries. * @param array $args See $defaults definition for more details * @return mixed Metadata cache for the specified objects, or false on failure. */ function bp_update_meta_cache($args = array()) { global $wpdb; $defaults = array('object_ids' => array(), 'object_type' => '', 'meta_table' => '', 'object_column' => '', 'cache_key_prefix' => ''); $r = wp_parse_args($args, $defaults); extract($r); if (empty($object_ids) || empty($object_type) || empty($meta_table)) { return false; } if (empty($cache_key_prefix)) { $cache_key_prefix = $meta_table; } if (empty($object_column)) { $object_column = $object_type . '_id'; } $object_ids = wp_parse_id_list($object_ids); $cache = array(); // Get meta info $id_list = join(',', $object_ids); $meta_list = $wpdb->get_results($wpdb->prepare("SELECT {$object_column}, meta_key, meta_value FROM {$meta_table} WHERE {$object_column} IN ({$id_list})", $object_type), ARRAY_A); if (!empty($meta_list)) { foreach ($meta_list as $metarow) { $mpid = intval($metarow[$object_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 ($object_ids as $id) { if (!isset($cache[$id])) { $cache[$id] = array(); } foreach ($cache[$id] as $meta_key => $meta_value) { wp_cache_set($cache_key_prefix . '_' . $id . '_' . $meta_key, $meta_value, 'bp'); } } return $cache; }
/** * Standard meta retrieval * * @param int $post_id * @param bool $saved * @param array $field * * @return array */ public static function meta($post_id, $saved, $field) { $meta = get_post_meta($post_id, $field['id'], true); $meta = wp_parse_id_list($meta); $meta = array_filter($meta); // Use $field['std'] only when the meta box hasn't been saved (i.e. the first time we run) $meta = !$saved ? $field['std'] : $meta; // Escape attributes $meta = self::call($field, 'esc_meta', $meta); // Make sure meta value is an array for clonable and multiple fields if ($field['clone'] || $field['multiple']) { if (empty($meta) || !is_array($meta)) { /** * Note: if field is clonable, $meta must be an array with values * so that the foreach loop in self::show() runs properly * @see self::show() */ $meta = $field['clone'] ? array('') : array(); } } return $meta; }
/** * Get post meta * * @param string $key Meta key. Required. * @param int|null $post_id Post ID. null for current post. Optional * @param array $args Array of arguments. Optional. * * @return mixed */ public static function meta($key, $args = array(), $post_id = null) { $post_id = empty($post_id) ? get_the_ID() : $post_id; $args = wp_parse_args($args, array('type' => 'text', 'multiple' => false, 'clone' => false)); // Always set 'multiple' true for following field types if (in_array($args['type'], array('checkbox_list', 'autocomplete', 'file', 'file_advanced', 'image', 'image_advanced', 'plupload_image', 'thickbox_image'))) { $args['multiple'] = true; } $field = array('id' => $key, 'type' => $args['type'], 'clone' => $args['clone'], 'multiple' => $args['multiple']); $class = RW_Meta_Box::get_class_name($field); switch ($args['type']) { case 'taxonomy_advanced': if (empty($args['taxonomy'])) { break; } $meta = get_post_meta($post_id, $key, !$args['multiple']); $term_ids = wp_parse_id_list($meta); // Allow to pass more arguments to "get_terms" $func_args = wp_parse_args(array('include' => $term_ids, 'hide_empty' => false), $args); unset($func_args['type'], $func_args['taxonomy'], $func_args['multiple']); $meta = get_terms($args['taxonomy'], $func_args); break; case 'taxonomy': $meta = empty($args['taxonomy']) ? array() : get_the_terms($post_id, $args['taxonomy']); break; case 'map': $field = array('id' => $key, 'multiple' => false, 'clone' => false); $meta = RWMB_Map_Field::the_value($field, $args, $post_id); break; case 'oembed': $meta = RWMB_OEmbed_Field::the_value($field, $args, $post_id); break; default: $meta = call_user_func(array($class, 'get_value'), $field, $args, $post_id); break; } return apply_filters('rwmb_meta', $meta, $key, $args, $post_id); }
function validate_args($args) { $args = wp_parse_args($args, self::$options->get_defaults()); // Category IDs foreach (array('exclude_cat', 'include_cat') as $key) { if (!empty($args[$key])) { $args[$key] = wp_parse_id_list($args[$key]); } } // Anchors if ('both' != $args['format']) { $args['anchors'] = false; } // Block numeric if (array_key_exists('block_numeric', $args)) { if ('block' == $args['format'] && !array_key_exists('month_format', $args)) { $args['month_format'] = $args['block_numeric'] ? 'numeric' : 'short'; } unset($args['block_numeric']); } // List format $args['list_format'] = trim($args['list_format']); return $args; }
/** * List all unlocked achievements for the specified user * * @since Achievements (3.3) * @subcommand list * @synopsis --user_id=<id> [--format=<table|csv|json>] */ public function _list($args, $assoc_args) { global $wpdb; $defaults = array('format' => 'table'); $assoc_args = array_merge($defaults, $assoc_args); if (!$assoc_args['user_id'] || !($user = get_userdata($assoc_args['user_id']))) { WP_CLI::error('Invalid User ID specified.'); } // Get the progress for this user $achievement_ids = $wpdb->get_col($wpdb->prepare("SELECT post_parent FROM {$wpdb->posts} WHERE post_type = %s AND post_author = %d", dpa_get_progress_post_type(), $user->ID)); if (empty($achievement_ids)) { WP_CLI::error(sprintf('User ID %d has not unlocked any achievements.', $user->ID)); } $achievement_ids = wp_parse_id_list($achievement_ids); $achievement_count = count($achievement_ids); $achievement_ids = implode(',', $achievement_ids); // Get the achievements $posts = $wpdb->get_results($wpdb->prepare("SELECT ID, post_title FROM {$wpdb->posts} WHERE ID in ({$achievement_ids}) AND post_type = %s AND post_status = %s ORDER BY post_title ASC", dpa_get_achievement_post_type(), 'publish')); if (empty($posts)) { WP_CLI::error(sprintf("No achievements unlocked by User ID %d have been found. This shouldn't happen.", $user->ID)); } WP_CLI::success(sprintf('%d achievements have been unlocked by User ID %d:', $achievement_count, $user->ID)); \WP_CLI\utils\format_items($assoc_args['format'], $posts, $this->fields); }
/** * Retrieve a list of pages. * * The defaults that can be overridden are the following: 'child_of', * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude', * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'. * * @since 1.5.0 * @uses $wpdb * * @param mixed $args Optional. Array or string of options that overrides defaults. * @return array List of pages matching defaults or $args */ function &get_pages($args = '') { global $wpdb; $defaults = array('child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => array(), 'include' => array(), 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'parent' => -1, 'exclude_tree' => '', 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish'); $r = wp_parse_args($args, $defaults); extract($r, EXTR_SKIP); $number = (int) $number; $offset = (int) $offset; // Make sure the post type is hierarchical $hierarchical_post_types = get_post_types(array('hierarchical' => true)); if (!in_array($post_type, $hierarchical_post_types)) { return false; } // Make sure we have a valid post status if (!in_array($post_status, get_post_stati())) { return false; } $cache = array(); $key = md5(serialize(compact(array_keys($defaults)))); if ($cache = wp_cache_get('get_pages', 'posts')) { if (is_array($cache) && isset($cache[$key])) { $pages = apply_filters('get_pages', $cache[$key], $r); return $pages; } } if (!is_array($cache)) { $cache = array(); } $inclusions = ''; if (!empty($include)) { $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include $parent = -1; $exclude = ''; $meta_key = ''; $meta_value = ''; $hierarchical = false; $incpages = wp_parse_id_list($include); if (!empty($incpages)) { foreach ($incpages as $incpage) { if (empty($inclusions)) { $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage); } else { $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage); } } } } if (!empty($inclusions)) { $inclusions .= ')'; } $exclusions = ''; if (!empty($exclude)) { $expages = wp_parse_id_list($exclude); if (!empty($expages)) { foreach ($expages as $expage) { if (empty($exclusions)) { $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage); } else { $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage); } } } } if (!empty($exclusions)) { $exclusions .= ')'; } $author_query = ''; if (!empty($authors)) { $post_authors = preg_split('/[\\s,]+/', $authors); if (!empty($post_authors)) { foreach ($post_authors as $post_author) { //Do we have an author id or an author login? if (0 == intval($post_author)) { $post_author = get_userdatabylogin($post_author); if (empty($post_author)) { continue; } if (empty($post_author->ID)) { continue; } $post_author = $post_author->ID; } if ('' == $author_query) { $author_query = $wpdb->prepare(' post_author = %d ', $post_author); } else { $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author); } } if ('' != $author_query) { $author_query = " AND ({$author_query})"; } } } $join = ''; $where = "{$exclusions} {$inclusions} "; if (!empty($meta_key) || !empty($meta_value)) { $join = " LEFT JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id )"; // meta_key and meta_value might be slashed $meta_key = stripslashes($meta_key); $meta_value = stripslashes($meta_value); if (!empty($meta_key)) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s", $meta_key); } if (!empty($meta_value)) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_value = %s", $meta_value); } } if ($parent >= 0) { $where .= $wpdb->prepare(' AND post_parent = %d ', $parent); } $where_post_type = $wpdb->prepare("post_type = '%s' AND post_status = '%s'", $post_type, $post_status); $query = "SELECT * FROM {$wpdb->posts} {$join} WHERE ({$where_post_type}) {$where} "; $query .= $author_query; $query .= " ORDER BY " . $sort_column . " " . $sort_order; if (!empty($number)) { $query .= ' LIMIT ' . $offset . ',' . $number; } $pages = $wpdb->get_results($query); if (empty($pages)) { $pages = apply_filters('get_pages', array(), $r); return $pages; } // Sanitize before caching so it'll only get done once $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { $pages[$i] = sanitize_post($pages[$i], 'raw'); } // Update cache. update_page_cache($pages); if ($child_of || $hierarchical) { $pages =& get_page_children($child_of, $pages); } if (!empty($exclude_tree)) { $exclude = (int) $exclude_tree; $children = get_page_children($exclude, $pages); $excludes = array(); foreach ($children as $child) { $excludes[] = $child->ID; } $excludes[] = $exclude; $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { if (in_array($pages[$i]->ID, $excludes)) { unset($pages[$i]); } } } $cache[$key] = $pages; wp_cache_set('get_pages', $cache, 'posts'); $pages = apply_filters('get_pages', $pages, $r); return $pages; }
public function get_term_ids_from_tt_ids($taxonomy, $tt_ids) { global $wpdb; $tt_ids = wp_parse_id_list($tt_ids); if (empty($tt_ids)) { return array(); } return $wpdb->get_col("select term_id from {$wpdb->term_taxonomy} where taxonomy = '{$taxonomy}' and term_taxonomy_id in (" . join(',', $tt_ids) . ")"); }
/** * Display the Group delete confirmation screen. * * We include a separate confirmation because group deletion is truly * irreversible. * * @since 1.7.0 */ function bp_groups_admin_delete() { if (!bp_current_user_can('bp_moderate')) { die('-1'); } $group_ids = isset($_REQUEST['gid']) ? $_REQUEST['gid'] : 0; if (!is_array($group_ids)) { $group_ids = explode(',', $group_ids); } $group_ids = wp_parse_id_list($group_ids); $groups = groups_get_groups(array('include' => $group_ids, 'show_hidden' => true, 'per_page' => null)); // Create a new list of group ids, based on those that actually exist $gids = array(); foreach ($groups['groups'] as $group) { $gids[] = $group->id; } $base_url = remove_query_arg(array('action', 'action2', 'paged', 's', '_wpnonce', 'gid'), $_SERVER['REQUEST_URI']); ?> <div class="wrap"> <?php screen_icon('buddypress-groups'); ?> <h2><?php _e('Delete Groups', 'buddypress'); ?> </h2> <p><?php _e('You are about to delete the following groups:', 'buddypress'); ?> </p> <ul class="bp-group-delete-list"> <?php foreach ($groups['groups'] as $group) { ?> <li><?php echo esc_html($group->name); ?> </li> <?php } ?> </ul> <p><strong><?php _e('This action cannot be undone.', 'buddypress'); ?> </strong></p> <a class="button-primary" href="<?php echo esc_url(wp_nonce_url(add_query_arg(array('action' => 'do_delete', 'gid' => implode(',', $gids)), $base_url), 'bp-groups-delete')); ?> "><?php _e('Delete Permanently', 'buddypress'); ?> </a> <a class="button" href="<?php echo esc_attr($base_url); ?> "><?php _e('Cancel', 'buddypress'); ?> </a> </div> <?php }
/** * Used internally to get a list of comment IDs matching the query vars. * * @since 4.4.0 * @access protected * * @global wpdb $wpdb WordPress database abstraction object. */ protected function get_comment_ids() { global $wpdb; // Assemble clauses related to 'comment_approved'. $approved_clauses = array(); // 'status' accepts an array or a comma-separated string. $status_clauses = array(); $statuses = $this->query_vars['status']; if (!is_array($statuses)) { $statuses = preg_split('/[\\s,]+/', $statuses); } // 'any' overrides other statuses. if (!in_array('any', $statuses)) { foreach ($statuses as $status) { switch ($status) { case 'hold': $status_clauses[] = "comment_approved = '0'"; break; case 'approve': $status_clauses[] = "comment_approved = '1'"; break; case 'all': case '': $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )"; break; default: $status_clauses[] = $wpdb->prepare("comment_approved = %s", $status); break; } } if (!empty($status_clauses)) { $approved_clauses[] = '( ' . implode(' OR ', $status_clauses) . ' )'; } } // User IDs or emails whose unapproved comments are included, regardless of $status. if (!empty($this->query_vars['include_unapproved'])) { $include_unapproved = $this->query_vars['include_unapproved']; // Accepts arrays or comma-separated strings. if (!is_array($include_unapproved)) { $include_unapproved = preg_split('/[\\s,]+/', $include_unapproved); } $unapproved_ids = $unapproved_emails = array(); foreach ($include_unapproved as $unapproved_identifier) { // Numeric values are assumed to be user ids. if (is_numeric($unapproved_identifier)) { $approved_clauses[] = $wpdb->prepare("( user_id = %d AND comment_approved = '0' )", $unapproved_identifier); // Otherwise we match against email addresses. } else { $approved_clauses[] = $wpdb->prepare("( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier); } } } // Collapse comment_approved clauses into a single OR-separated clause. if (!empty($approved_clauses)) { if (1 === count($approved_clauses)) { $this->sql_clauses['where']['approved'] = $approved_clauses[0]; } else { $this->sql_clauses['where']['approved'] = '( ' . implode(' OR ', $approved_clauses) . ' )'; } } $order = 'ASC' == strtoupper($this->query_vars['order']) ? 'ASC' : 'DESC'; // Disable ORDER BY with 'none', an empty array, or boolean false. if (in_array($this->query_vars['orderby'], array('none', array(), false), true)) { $orderby = ''; } elseif (!empty($this->query_vars['orderby'])) { $ordersby = is_array($this->query_vars['orderby']) ? $this->query_vars['orderby'] : preg_split('/[,\\s]/', $this->query_vars['orderby']); $orderby_array = array(); $found_orderby_comment_ID = false; foreach ($ordersby as $_key => $_value) { if (!$_value) { continue; } if (is_int($_key)) { $_orderby = $_value; $_order = $order; } else { $_orderby = $_key; $_order = $_value; } if (!$found_orderby_comment_ID && in_array($_orderby, array('comment_ID', 'comment__in'))) { $found_orderby_comment_ID = true; } $parsed = $this->parse_orderby($_orderby); if (!$parsed) { continue; } if ('comment__in' === $_orderby) { $orderby_array[] = $parsed; continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order($_order); } // If no valid clauses were found, order by comment_date_gmt. if (empty($orderby_array)) { $orderby_array[] = "{$wpdb->comments}.comment_date_gmt {$order}"; } // To ensure determinate sorting, always include a comment_ID clause. if (!$found_orderby_comment_ID) { $comment_ID_order = ''; // Inherit order from comment_date or comment_date_gmt, if available. foreach ($orderby_array as $orderby_clause) { if (preg_match('/comment_date(?:_gmt)*\\ (ASC|DESC)/', $orderby_clause, $match)) { $comment_ID_order = $match[1]; break; } } // If no date-related order is available, use the date from the first available clause. if (!$comment_ID_order) { foreach ($orderby_array as $orderby_clause) { if (false !== strpos('ASC', $orderby_clause)) { $comment_ID_order = 'ASC'; } else { $comment_ID_order = 'DESC'; } break; } } // Default to DESC. if (!$comment_ID_order) { $comment_ID_order = 'DESC'; } $orderby_array[] = "{$wpdb->comments}.comment_ID {$comment_ID_order}"; } $orderby = implode(', ', $orderby_array); } else { $orderby = "{$wpdb->comments}.comment_date_gmt {$order}"; } $number = absint($this->query_vars['number']); $offset = absint($this->query_vars['offset']); if (!empty($number)) { if ($offset) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . $number; } } if ($this->query_vars['count']) { $fields = 'COUNT(*)'; } else { $fields = "{$wpdb->comments}.comment_ID"; } $post_id = absint($this->query_vars['post_id']); if (!empty($post_id)) { $this->sql_clauses['where']['post_id'] = $wpdb->prepare('comment_post_ID = %d', $post_id); } // Parse comment IDs for an IN clause. if (!empty($this->query_vars['comment__in'])) { $this->sql_clauses['where']['comment__in'] = "{$wpdb->comments}.comment_ID IN ( " . implode(',', wp_parse_id_list($this->query_vars['comment__in'])) . ' )'; } // Parse comment IDs for a NOT IN clause. if (!empty($this->query_vars['comment__not_in'])) { $this->sql_clauses['where']['comment__not_in'] = "{$wpdb->comments}.comment_ID NOT IN ( " . implode(',', wp_parse_id_list($this->query_vars['comment__not_in'])) . ' )'; } // Parse comment parent IDs for an IN clause. if (!empty($this->query_vars['parent__in'])) { $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode(',', wp_parse_id_list($this->query_vars['parent__in'])) . ' )'; } // Parse comment parent IDs for a NOT IN clause. if (!empty($this->query_vars['parent__not_in'])) { $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode(',', wp_parse_id_list($this->query_vars['parent__not_in'])) . ' )'; } // Parse comment post IDs for an IN clause. if (!empty($this->query_vars['post__in'])) { $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode(',', wp_parse_id_list($this->query_vars['post__in'])) . ' )'; } // Parse comment post IDs for a NOT IN clause. if (!empty($this->query_vars['post__not_in'])) { $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode(',', wp_parse_id_list($this->query_vars['post__not_in'])) . ' )'; } if ('' !== $this->query_vars['author_email']) { $this->sql_clauses['where']['author_email'] = $wpdb->prepare('comment_author_email = %s', $this->query_vars['author_email']); } if ('' !== $this->query_vars['author_url']) { $this->sql_clauses['where']['author_url'] = $wpdb->prepare('comment_author_url = %s', $this->query_vars['author_url']); } if ('' !== $this->query_vars['karma']) { $this->sql_clauses['where']['karma'] = $wpdb->prepare('comment_karma = %d', $this->query_vars['karma']); } // Filtering by comment_type: 'type', 'type__in', 'type__not_in'. $raw_types = array('IN' => array_merge((array) $this->query_vars['type'], (array) $this->query_vars['type__in']), 'NOT IN' => (array) $this->query_vars['type__not_in']); $comment_types = array(); foreach ($raw_types as $operator => $_raw_types) { $_raw_types = array_unique($_raw_types); foreach ($_raw_types as $type) { switch ($type) { // An empty translates to 'all', for backward compatibility case '': case 'all': break; case 'comment': case 'comments': $comment_types[$operator][] = "''"; break; case 'pings': $comment_types[$operator][] = "'pingback'"; $comment_types[$operator][] = "'trackback'"; break; default: $comment_types[$operator][] = $wpdb->prepare('%s', $type); break; } } if (!empty($comment_types[$operator])) { $types_sql = implode(', ', $comment_types[$operator]); $this->sql_clauses['where']['comment_type__' . strtolower(str_replace(' ', '_', $operator))] = "comment_type {$operator} ({$types_sql})"; } } if ($this->query_vars['hierarchical'] && !$this->query_vars['parent']) { $this->query_vars['parent'] = 0; } if ('' !== $this->query_vars['parent']) { $this->sql_clauses['where']['parent'] = $wpdb->prepare('comment_parent = %d', $this->query_vars['parent']); } if (is_array($this->query_vars['user_id'])) { $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode(',', array_map('absint', $this->query_vars['user_id'])) . ')'; } elseif ('' !== $this->query_vars['user_id']) { $this->sql_clauses['where']['user_id'] = $wpdb->prepare('user_id = %d', $this->query_vars['user_id']); } // Falsy search strings are ignored. if (strlen($this->query_vars['search'])) { $search_sql = $this->get_search_sql($this->query_vars['search'], array('comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content')); // Strip leading 'AND'. $this->sql_clauses['where']['search'] = preg_replace('/^\\s*AND\\s*/', '', $search_sql); } // If any post-related query vars are passed, join the posts table. $join_posts_table = false; $plucked = wp_array_slice_assoc($this->query_vars, array('post_author', 'post_name', 'post_parent')); $post_fields = array_filter($plucked); if (!empty($post_fields)) { $join_posts_table = true; foreach ($post_fields as $field_name => $field_value) { // $field_value may be an array. $esses = array_fill(0, count((array) $field_value), '%s'); $this->sql_clauses['where'][$field_name] = $wpdb->prepare(" {$wpdb->posts}.{$field_name} IN (" . implode(',', $esses) . ')', $field_value); } } // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'. foreach (array('post_status', 'post_type') as $field_name) { $q_values = array(); if (!empty($this->query_vars[$field_name])) { $q_values = $this->query_vars[$field_name]; if (!is_array($q_values)) { $q_values = explode(',', $q_values); } // 'any' will cause the query var to be ignored. if (in_array('any', $q_values, true) || empty($q_values)) { continue; } $join_posts_table = true; $esses = array_fill(0, count($q_values), '%s'); $this->sql_clauses['where'][$field_name] = $wpdb->prepare(" {$wpdb->posts}.{$field_name} IN (" . implode(',', $esses) . ")", $q_values); } } // Comment author IDs for an IN clause. if (!empty($this->query_vars['author__in'])) { $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode(',', wp_parse_id_list($this->query_vars['author__in'])) . ' )'; } // Comment author IDs for a NOT IN clause. if (!empty($this->query_vars['author__not_in'])) { $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode(',', wp_parse_id_list($this->query_vars['author__not_in'])) . ' )'; } // Post author IDs for an IN clause. if (!empty($this->query_vars['post_author__in'])) { $join_posts_table = true; $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode(',', wp_parse_id_list($this->query_vars['post_author__in'])) . ' )'; } // Post author IDs for a NOT IN clause. if (!empty($this->query_vars['post_author__not_in'])) { $join_posts_table = true; $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode(',', wp_parse_id_list($this->query_vars['post_author__not_in'])) . ' )'; } $join = ''; if ($join_posts_table) { $join .= "JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID"; } if (!empty($this->meta_query_clauses)) { $join .= $this->meta_query_clauses['join']; // Strip leading 'AND'. $this->sql_clauses['where']['meta_query'] = preg_replace('/^\\s*AND\\s*/', '', $this->meta_query_clauses['where']); if (!$this->query_vars['count']) { $groupby = "{$wpdb->comments}.comment_ID"; } } if (!empty($this->query_vars['date_query']) && is_array($this->query_vars['date_query'])) { $this->date_query = new WP_Date_Query($this->query_vars['date_query'], 'comment_date'); $this->sql_clauses['where']['date_query'] = preg_replace('/^\\s*AND\\s*/', '', $this->date_query->get_sql()); } $where = implode(' AND ', $this->sql_clauses['where']); $pieces = array('fields', 'join', 'where', 'orderby', 'limits', 'groupby'); /** * Filter the comment query clauses. * * @since 3.1.0 * * @param array $pieces A compacted array of comment query clauses. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference. */ $clauses = apply_filters_ref_array('comments_clauses', array(compact($pieces), &$this)); $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $where = isset($clauses['where']) ? $clauses['where'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : ''; $this->filtered_where_clause = $where; if ($where) { $where = 'WHERE ' . $where; } if ($groupby) { $groupby = 'GROUP BY ' . $groupby; } if ($orderby) { $orderby = "ORDER BY {$orderby}"; } $found_rows = ''; if (!$this->query_vars['no_found_rows']) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->sql_clauses['select'] = "SELECT {$found_rows} {$fields}"; $this->sql_clauses['from'] = "FROM {$wpdb->comments} {$join}"; $this->sql_clauses['groupby'] = $groupby; $this->sql_clauses['orderby'] = $orderby; $this->sql_clauses['limits'] = $limits; $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}"; if ($this->query_vars['count']) { return intval($wpdb->get_var($this->request)); } else { $comment_ids = $wpdb->get_col($this->request); return array_map('intval', $comment_ids); } }
function get_all_for_group($group_id, $limit = false, $page = false, $exclude_admins_mods = true, $exclude_banned = true, $exclude = false) { global $bp, $wpdb; $pag_sql = ''; if (!empty($limit) && !empty($page)) { $pag_sql = $wpdb->prepare("LIMIT %d, %d", intval(($page - 1) * $limit), intval($limit)); } $exclude_admins_sql = ''; if (!empty($exclude_admins_mods)) { $exclude_admins_sql = "AND is_admin = 0 AND is_mod = 0"; } $banned_sql = ''; if (!empty($exclude_banned)) { $banned_sql = " AND is_banned = 0"; } $exclude_sql = ''; if (!empty($exclude)) { $exclude = implode(',', wp_parse_id_list($exclude)); $exclude_sql = " AND m.user_id NOT IN ({$exclude})"; } if (bp_is_active('xprofile')) { $members = $wpdb->get_results(apply_filters('bp_group_members_user_join_filter', $wpdb->prepare("SELECT m.user_id, m.date_modified, m.is_banned, u.user_login, u.user_nicename, u.user_email, pd.value as display_name FROM {$bp->groups->table_name_members} m, {$wpdb->users} u, {$bp->profile->table_name_data} pd WHERE u.ID = m.user_id AND u.ID = pd.user_id AND pd.field_id = 1 AND group_id = %d AND is_confirmed = 1 {$banned_sql} {$exclude_admins_sql} {$exclude_sql} ORDER BY m.date_modified DESC {$pag_sql}", $group_id))); } else { $members = $wpdb->get_results(apply_filters('bp_group_members_user_join_filter', $wpdb->prepare("SELECT m.user_id, m.date_modified, m.is_banned, u.user_login, u.user_nicename, u.user_email, u.display_name FROM {$bp->groups->table_name_members} m, {$wpdb->users} u WHERE u.ID = m.user_id AND group_id = %d AND is_confirmed = 1 {$banned_sql} {$exclude_admins_sql} {$exclude_sql} ORDER BY m.date_modified DESC {$pag_sql}", $group_id))); } if (empty($members)) { return false; } if (empty($pag_sql)) { $total_member_count = count($members); } else { $total_member_count = $wpdb->get_var(apply_filters('bp_group_members_count_user_join_filter', $wpdb->prepare("SELECT COUNT(user_id) FROM {$bp->groups->table_name_members} WHERE group_id = %d AND is_confirmed = 1 {$banned_sql} {$exclude_admins_sql} {$exclude_sql}", $group_id))); } // Fetch whether or not the user is a friend foreach ((array) $members as $user) { $user_ids[] = $user->user_id; } $user_ids = $wpdb->escape(join(',', (array) $user_ids)); if (bp_is_active('friends')) { $friend_status = $wpdb->get_results($wpdb->prepare("SELECT initiator_user_id, friend_user_id, is_confirmed FROM {$bp->friends->table_name} WHERE (initiator_user_id = %d AND friend_user_id IN ( {$user_ids} ) ) OR (initiator_user_id IN ( {$user_ids} ) AND friend_user_id = %d )", bp_loggedin_user_id(), bp_loggedin_user_id())); for ($i = 0, $count = count($members); $i < $count; ++$i) { foreach ((array) $friend_status as $status) { if ($status->initiator_user_id == $members[$i]->user_id || $status->friend_user_id == $members[$i]->user_id) { $members[$i]->is_friend = $status->is_confirmed; } } } } return array('members' => $members, 'count' => $total_member_count); }
/** * Extract images in [galleries] shortcodes from text. * * @since 2.3.0 * * @param string $richtext Content to parse. * @param string $plaintext Sanitized version of the content. * @param array $extra_args Bespoke data for a particular extractor (optional). * * @return array */ protected function extract_images_from_galleries($richtext, $plaintext, $extra_args = array()) { if (!isset($extra_args['post']) || !is_a($extra_args['post'], 'WP_Post')) { $post = new WP_Post((object) array('post_content' => $richtext)); } else { $post = $extra_args['post']; } // We're not using get_post_galleries_images() because it returns thumbnails; we want the original image. $galleries = get_post_galleries($post, false); $galleries_data = array(); if (!empty($galleries)) { // Validate the size of the images requested. if (isset($extra_args['width'])) { // A width was specified but not a height, so calculate it assuming a 4:3 ratio. if (!isset($extra_args['height']) && ctype_digit($extra_args['width'])) { $extra_args['height'] = round($extra_args['width'] / 4 * 3); } if (ctype_digit($extra_args['width'])) { $image_size = array($extra_args['width'], $extra_args['height']); } else { $image_size = $extra_args['width']; // e.g. "thumb", "medium". } } else { $image_size = 'full'; } /** * There are two variants of gallery shortcode. * * One kind specifies the image (post) IDs via an `ids` parameter. * The other gets the image IDs from post_type=attachment and post_parent=get_the_ID(). */ foreach ($galleries as $gallery_id => $gallery) { $data = array(); $images = array(); // Gallery ids= variant. if (isset($gallery['ids'])) { $images = wp_parse_id_list($gallery['ids']); // Gallery post_parent variant. } elseif (isset($extra_args['post'])) { $images = wp_parse_id_list(get_children(array('fields' => 'ids', 'order' => 'ASC', 'orderby' => 'menu_order ID', 'post_mime_type' => 'image', 'post_parent' => $extra_args['post']->ID, 'post_status' => 'inherit', 'post_type' => 'attachment'))); } // Extract the data we need from each image in this gallery. foreach ($images as $image_id) { $image = wp_get_attachment_image_src($image_id, $image_size); $data[] = array('url' => $image[0], 'width' => $image[1], 'height' => $image[2], 'gallery_id' => 1 + $gallery_id); } $galleries_data[] = $data; } } /** * Filters image galleries extracted from text. * * @since 2.3.0 * * @param array $galleries_data Galleries. See {@link BP_Media_Extractor::extract_images_from_galleries()}. * @param string $richtext Content to parse. * @param string $plaintext Copy of $richtext without any markup. * @param array $extra_args Bespoke data for a particular extractor. */ return apply_filters('bp_media_extractor_galleries', $galleries_data, $richtext, $plaintext, $extra_args); }
/** * This is the confirmation screen for actions. * * @since 2.0.0 * * @param string $action Delete, activate, or resend activation link. * * @return string */ public function signups_admin_manage($action = '') { if (!current_user_can($this->capability) || empty($action)) { die('-1'); } // Get the user IDs from the URL. $ids = false; if (!empty($_POST['allsignups'])) { $ids = wp_parse_id_list($_POST['allsignups']); } elseif (!empty($_GET['signup_id'])) { $ids = absint($_GET['signup_id']); } if (empty($ids)) { return false; } // Query for signups, and filter out those IDs that don't // correspond to an actual signup. $signups_query = BP_Signup::get(array('include' => $ids)); $signups = $signups_query['signups']; $signup_ids = wp_list_pluck($signups, 'signup_id'); // Set up strings. switch ($action) { case 'delete': $header_text = __('Delete Pending Accounts', 'buddypress'); if (1 == count($signup_ids)) { $helper_text = __('You are about to delete the following account:', 'buddypress'); } else { $helper_text = __('You are about to delete the following accounts:', 'buddypress'); } break; case 'activate': $header_text = __('Activate Pending Accounts', 'buddypress'); if (1 == count($signup_ids)) { $helper_text = __('You are about to activate the following account:', 'buddypress'); } else { $helper_text = __('You are about to activate the following accounts:', 'buddypress'); } break; case 'resend': $header_text = __('Resend Activation Emails', 'buddypress'); if (1 == count($signup_ids)) { $helper_text = __('You are about to resend an activation email to the following account:', 'buddypress'); } else { $helper_text = __('You are about to resend an activation email to the following accounts:', 'buddypress'); } break; } // These arguments are added to all URLs. $url_args = array('page' => 'bp-signups'); // These arguments are only added when performing an action. $action_args = array('action' => 'do_' . $action, 'signup_ids' => implode(',', $signup_ids)); if (is_network_admin()) { $base_url = network_admin_url('users.php'); } else { $base_url = bp_get_admin_url('users.php'); } $cancel_url = add_query_arg($url_args, $base_url); $action_url = wp_nonce_url(add_query_arg(array_merge($url_args, $action_args), $base_url), 'signups_' . $action); ?> <div class="wrap"> <h1><?php echo esc_html($header_text); ?> </h1> <p><?php echo esc_html($helper_text); ?> </p> <ol class="bp-signups-list"> <?php foreach ($signups as $signup) { $last_notified = mysql2date('Y/m/d g:i:s a', $signup->date_sent); ?> <li> <?php echo esc_html($signup->user_name); ?> - <?php echo sanitize_email($signup->user_email); ?> <?php if ('resend' == $action) { ?> <p class="description"> <?php printf(esc_html__('Last notified: %s', 'buddypress'), $last_notified); ?> <?php if (!empty($signup->recently_sent)) { ?> <span class="attention wp-ui-text-notification"> <?php esc_html_e('(less than 24 hours ago)', 'buddypress'); ?> </span> <?php } ?> </p> <?php } ?> </li> <?php } ?> </ol> <?php if ('delete' === $action) { ?> <p><strong><?php esc_html_e('This action cannot be undone.', 'buddypress'); ?> </strong></p> <?php } ?> <a class="button-primary" href="<?php echo esc_url($action_url); ?> "><?php esc_html_e('Confirm', 'buddypress'); ?> </a> <a class="button" href="<?php echo esc_url($cancel_url); ?> "><?php esc_html_e('Cancel', 'buddypress'); ?> </a> </div> <?php }
/** * Retrieve a list of pages. * * @global wpdb $wpdb WordPress database abstraction object. * * @since 1.5.0 * * @param array|string $args { * Optional. Array or string of arguments to retrieve pages. * * @type int $child_of Page ID to return child and grandchild pages of. Note: The value * of `$hierarchical` has no bearing on whether `$child_of` returns * hierarchical results. Default 0, or no restriction. * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'. * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author', * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order', * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'. * 'post_' can be omitted for any values that start with it. * Default 'post_title'. * @type bool $hierarchical Whether to return pages hierarchically. If false in conjunction with * `$child_of` also being false, both arguments will be disregarded. * Default true. * @type array $exclude Array of page IDs to exclude. Default empty array. * @type array $include Array of page IDs to include. Cannot be used with `$child_of`, * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`. * Default empty array. * @type string $meta_key Only include pages with this meta key. Default empty. * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`. * Default empty. * @type string $authors A comma-separated list of author IDs. Default empty. * @type int $parent Page ID to return direct children of. Default -1, or no restriction. * @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude. * Default empty array. * @type int $number The number of pages to return. Default 0, or all pages. * @type int $offset The number of pages to skip before returning. Requires `$number`. * Default 0. * @type string $post_type The post type to query. Default 'page'. * @type string $post_status A comma-separated list of post status types to include. * Default 'publish'. * } * @return array|false List of pages matching defaults or `$args`. */ function get_pages($args = array()) { global $wpdb; $defaults = array('child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => array(), 'include' => array(), 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'parent' => -1, 'exclude_tree' => array(), 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish'); $r = wp_parse_args($args, $defaults); $number = (int) $r['number']; $offset = (int) $r['offset']; $child_of = (int) $r['child_of']; $hierarchical = $r['hierarchical']; $exclude = $r['exclude']; $meta_key = $r['meta_key']; $meta_value = $r['meta_value']; $parent = $r['parent']; $post_status = $r['post_status']; // Make sure the post type is hierarchical. $hierarchical_post_types = get_post_types(array('hierarchical' => true)); if (!in_array($r['post_type'], $hierarchical_post_types)) { return false; } if ($parent > 0 && !$child_of) { $hierarchical = false; } // Make sure we have a valid post status. if (!is_array($post_status)) { $post_status = explode(',', $post_status); } if (array_diff($post_status, get_post_stati())) { return false; } // $args can be whatever, only use the args defined in defaults to compute the key. $key = md5(serialize(wp_array_slice_assoc($r, array_keys($defaults)))); $last_changed = wp_cache_get('last_changed', 'posts'); if (!$last_changed) { $last_changed = microtime(); wp_cache_set('last_changed', $last_changed, 'posts'); } $cache_key = "get_pages:{$key}:{$last_changed}"; if ($cache = wp_cache_get($cache_key, 'posts')) { // Convert to WP_Post instances. $pages = array_map('get_post', $cache); /** This filter is documented in wp-includes/post.php */ $pages = apply_filters('get_pages', $pages, $r); return $pages; } $inclusions = ''; if (!empty($r['include'])) { $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include $parent = -1; $exclude = ''; $meta_key = ''; $meta_value = ''; $hierarchical = false; $incpages = wp_parse_id_list($r['include']); if (!empty($incpages)) { $inclusions = ' AND ID IN (' . implode(',', $incpages) . ')'; } } $exclusions = ''; if (!empty($exclude)) { $expages = wp_parse_id_list($exclude); if (!empty($expages)) { $exclusions = ' AND ID NOT IN (' . implode(',', $expages) . ')'; } } $author_query = ''; if (!empty($r['authors'])) { $post_authors = preg_split('/[\\s,]+/', $r['authors']); if (!empty($post_authors)) { foreach ($post_authors as $post_author) { //Do we have an author id or an author login? if (0 == intval($post_author)) { $post_author = get_user_by('login', $post_author); if (empty($post_author)) { continue; } if (empty($post_author->ID)) { continue; } $post_author = $post_author->ID; } if ('' == $author_query) { $author_query = $wpdb->prepare(' post_author = %d ', $post_author); } else { $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author); } } if ('' != $author_query) { $author_query = " AND ({$author_query})"; } } } $join = ''; $where = "{$exclusions} {$inclusions} "; if ('' !== $meta_key || '' !== $meta_value) { $join = " LEFT JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id )"; // meta_key and meta_value might be slashed $meta_key = wp_unslash($meta_key); $meta_value = wp_unslash($meta_value); if ('' !== $meta_key) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s", $meta_key); } if ('' !== $meta_value) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_value = %s", $meta_value); } } if (is_array($parent)) { $post_parent__in = implode(',', array_map('absint', (array) $parent)); if (!empty($post_parent__in)) { $where .= " AND post_parent IN ({$post_parent__in})"; } } elseif ($parent >= 0) { $where .= $wpdb->prepare(' AND post_parent = %d ', $parent); } if (1 == count($post_status)) { $where_post_type = $wpdb->prepare("post_type = %s AND post_status = %s", $r['post_type'], reset($post_status)); } else { $post_status = implode("', '", $post_status); $where_post_type = $wpdb->prepare("post_type = %s AND post_status IN ('{$post_status}')", $r['post_type']); } $orderby_array = array(); $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified', 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent', 'ID', 'rand', 'comment_count'); foreach (explode(',', $r['sort_column']) as $orderby) { $orderby = trim($orderby); if (!in_array($orderby, $allowed_keys)) { continue; } switch ($orderby) { case 'menu_order': break; case 'ID': $orderby = "{$wpdb->posts}.ID"; break; case 'rand': $orderby = 'RAND()'; break; case 'comment_count': $orderby = "{$wpdb->posts}.comment_count"; break; default: if (0 === strpos($orderby, 'post_')) { $orderby = "{$wpdb->posts}." . $orderby; } else { $orderby = "{$wpdb->posts}.post_" . $orderby; } } $orderby_array[] = $orderby; } $sort_column = !empty($orderby_array) ? implode(',', $orderby_array) : "{$wpdb->posts}.post_title"; $sort_order = strtoupper($r['sort_order']); if ('' !== $sort_order && !in_array($sort_order, array('ASC', 'DESC'))) { $sort_order = 'ASC'; } $query = "SELECT * FROM {$wpdb->posts} {$join} WHERE ({$where_post_type}) {$where} "; $query .= $author_query; $query .= " ORDER BY " . $sort_column . " " . $sort_order; if (!empty($number)) { $query .= ' LIMIT ' . $offset . ',' . $number; } $pages = $wpdb->get_results($query); if (empty($pages)) { /** This filter is documented in wp-includes/post.php */ $pages = apply_filters('get_pages', array(), $r); return $pages; } // Sanitize before caching so it'll only get done once. $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { $pages[$i] = sanitize_post($pages[$i], 'raw'); } // Update cache. update_post_cache($pages); if ($child_of || $hierarchical) { $pages = get_page_children($child_of, $pages); } if (!empty($r['exclude_tree'])) { $exclude = wp_parse_id_list($r['exclude_tree']); foreach ($exclude as $id) { $children = get_page_children($id, $pages); foreach ($children as $child) { $exclude[] = $child->ID; } } $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { if (in_array($pages[$i]->ID, $exclude)) { unset($pages[$i]); } } } $page_structure = array(); foreach ($pages as $page) { $page_structure[] = $page->ID; } wp_cache_set($cache_key, $page_structure, 'posts'); // Convert to WP_Post instances $pages = array_map('get_post', $pages); /** * Filter the retrieved list of pages. * * @since 2.1.0 * * @param array $pages List of pages to retrieve. * @param array $r Array of get_pages() arguments. */ return apply_filters('get_pages', $pages, $r); }
/** * Retrieve the terms in a given taxonomy or list of taxonomies. * * You can fully inject any customizations to the query before it is sent, as * well as control the output with a filter. * * The {@see 'get_terms'} filter will be called when the cache has the term and will * pass the found term along with the array of $taxonomies and array of $args. * This filter is also called before the array of terms is passed and will pass * the array of terms, along with the $taxonomies and $args. * * The {@see 'list_terms_exclusions'} filter passes the compiled exclusions along with * the $args. * * The {@see 'get_terms_orderby'} filter passes the `ORDER BY` clause for the query * along with the $args array. * * @since 2.3.0 * @since 4.2.0 Introduced 'name' and 'childless' parameters. * @since 4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the `orderby` parameter. * Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return * a list of WP_Term objects. * * @global wpdb $wpdb WordPress database abstraction object. * @global array $wp_filter * * @param string|array $taxonomies Taxonomy name or list of Taxonomy names. * @param array|string $args { * Optional. Array or string of arguments to get terms. * * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug', * 'term_group', 'term_id', 'id', 'description'), 'count' for term * taxonomy count, 'include' to match the 'order' of the $include param, * or 'none' to skip ORDER BY. Defaults to 'name'. * @type string $order Whether to order terms in ascending or descending order. * Accepts 'ASC' (ascending) or 'DESC' (descending). * Default 'ASC'. * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts * 1|true or 0|false. Default 1|true. * @type array|string $include Array or comma/space-separated string of term ids to include. * Default empty array. * @type array|string $exclude Array or comma/space-separated string of term ids to exclude. * If $include is non-empty, $exclude is ignored. * Default empty array. * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude * along with all of their descendant terms. If $include is * non-empty, $exclude_tree is ignored. Default empty array. * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any * positive number. Default ''|0 (all). * @type int $offset The number by which to offset the terms query. Default empty. * @type string $fields Term fields to query for. Accepts 'all' (returns an array of complete * term objects), 'ids' (returns an array of ids), 'id=>parent' (returns * an associative array with ids as keys, parent term IDs as values), * 'names' (returns an array of term names), 'count' (returns the number * of matching terms), 'id=>name' (returns an associative array with ids * as keys, term names as values), or 'id=>slug' (returns an associative * array with ids as keys, term slugs as values). Default 'all'. * @type string|array $name Optional. Name or array of names to return term(s) for. Default empty. * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty. * @type bool $hierarchical Whether to include terms that have non-empty descendants (even * if $hide_empty is set to true). Default true. * @type string $search Search criteria to match terms. Will be SQL-formatted with * wildcards before and after. Default empty. * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like. * Default empty. * @type string $description__like Retrieve terms where the description is LIKE $description__like. * Default empty. * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity * of each term's "count" object variable. Default false. * @type string $get Whether to return terms regardless of ancestry or whether the terms * are empty. Accepts 'all' or empty (disabled). Default empty. * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies * are passed, $child_of is ignored. Default 0. * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty. * @type bool $childless True to limit results to terms that have no children. This parameter * has no effect on non-hierarchical taxonomies. Default false. * @type string $cache_domain Unique cache key to be produced when this query is stored in an * object cache. Default is 'core'. * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true. * @type array $meta_query Meta query clauses to limit retrieved terms by. * See `WP_Meta_Query`. Default empty. * } * @return array|int|WP_Error List of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies * do not exist. */ function get_terms($taxonomies, $args = '') { global $wpdb; $empty_array = array(); $single_taxonomy = !is_array($taxonomies) || 1 === count($taxonomies); if (!is_array($taxonomies)) { $taxonomies = array($taxonomies); } foreach ($taxonomies as $taxonomy) { if (!taxonomy_exists($taxonomy)) { return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); } } $defaults = array('orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(), 'number' => '', 'fields' => 'all', 'name' => '', 'slug' => '', 'parent' => '', 'childless' => false, 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '', 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core', 'update_term_meta_cache' => true, 'meta_query' => ''); $args = wp_parse_args($args, $defaults); $args['number'] = absint($args['number']); $args['offset'] = absint($args['offset']); // Save queries by not crawling the tree in the case of multiple taxes or a flat tax. $has_hierarchical_tax = false; foreach ($taxonomies as $_tax) { if (is_taxonomy_hierarchical($_tax)) { $has_hierarchical_tax = true; } } if (!$has_hierarchical_tax) { $args['hierarchical'] = false; $args['pad_counts'] = false; } // 'parent' overrides 'child_of'. if (0 < intval($args['parent'])) { $args['child_of'] = false; } if ('all' == $args['get']) { $args['childless'] = false; $args['child_of'] = 0; $args['hide_empty'] = 0; $args['hierarchical'] = false; $args['pad_counts'] = false; } /** * Filter the terms query arguments. * * @since 3.1.0 * * @param array $args An array of get_term() arguments. * @param array $taxonomies An array of taxonomies. */ $args = apply_filters('get_terms_args', $args, $taxonomies); // Avoid the query if the queried parent/child_of term has no descendants. $child_of = $args['child_of']; $parent = $args['parent']; if ($child_of) { $_parent = $child_of; } elseif ($parent) { $_parent = $parent; } else { $_parent = false; } if ($_parent) { $in_hierarchy = false; foreach ($taxonomies as $_tax) { $hierarchy = _get_term_hierarchy($_tax); if (isset($hierarchy[$_parent])) { $in_hierarchy = true; } } if (!$in_hierarchy) { return $empty_array; } } $_orderby = strtolower($args['orderby']); if ('count' == $_orderby) { $orderby = 'tt.count'; } elseif ('name' == $_orderby) { $orderby = 't.name'; } elseif ('slug' == $_orderby) { $orderby = 't.slug'; } elseif ('include' == $_orderby && !empty($args['include'])) { $include = implode(',', array_map('absint', $args['include'])); $orderby = "FIELD( t.term_id, {$include} )"; } elseif ('term_group' == $_orderby) { $orderby = 't.term_group'; } elseif ('description' == $_orderby) { $orderby = 'tt.description'; } elseif ('none' == $_orderby) { $orderby = ''; } elseif (empty($_orderby) || 'id' == $_orderby || 'term_id' === $_orderby) { $orderby = 't.term_id'; } else { $orderby = 't.name'; } /** * Filter the ORDERBY clause of the terms query. * * @since 2.8.0 * * @param string $orderby `ORDERBY` clause of the terms query. * @param array $args An array of terms query arguments. * @param array $taxonomies An array of taxonomies. */ $orderby = apply_filters('get_terms_orderby', $orderby, $args, $taxonomies); $order = strtoupper($args['order']); if (!empty($orderby)) { $orderby = "ORDER BY {$orderby}"; } else { $order = ''; } if ('' !== $order && !in_array($order, array('ASC', 'DESC'))) { $order = 'ASC'; } $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')"; $exclude = $args['exclude']; $exclude_tree = $args['exclude_tree']; $include = $args['include']; $inclusions = ''; if (!empty($include)) { $exclude = ''; $exclude_tree = ''; $inclusions = implode(',', wp_parse_id_list($include)); } if (!empty($inclusions)) { $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )'; $where .= $inclusions; } $exclusions = array(); if (!empty($exclude_tree)) { $exclude_tree = wp_parse_id_list($exclude_tree); $excluded_children = $exclude_tree; foreach ($exclude_tree as $extrunk) { $excluded_children = array_merge($excluded_children, (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0))); } $exclusions = array_merge($excluded_children, $exclusions); } if (!empty($exclude)) { $exclusions = array_merge(wp_parse_id_list($exclude), $exclusions); } // 'childless' terms are those without an entry in the flattened term hierarchy. $childless = (bool) $args['childless']; if ($childless) { foreach ($taxonomies as $_tax) { $term_hierarchy = _get_term_hierarchy($_tax); $exclusions = array_merge(array_keys($term_hierarchy), $exclusions); } } if (!empty($exclusions)) { $exclusions = ' AND t.term_id NOT IN (' . implode(',', array_map('intval', $exclusions)) . ')'; } else { $exclusions = ''; } /** * Filter the terms to exclude from the terms query. * * @since 2.3.0 * * @param string $exclusions `NOT IN` clause of the terms query. * @param array $args An array of terms query arguments. * @param array $taxonomies An array of taxonomies. */ $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args, $taxonomies); if (!empty($exclusions)) { $where .= $exclusions; } if (!empty($args['name'])) { $names = (array) $args['name']; foreach ($names as &$_name) { $_name = sanitize_term_field('name', $_name, 0, reset($taxonomies), 'db'); } $where .= " AND t.name IN ('" . implode("', '", array_map('esc_sql', $names)) . "')"; } if (!empty($args['slug'])) { if (is_array($args['slug'])) { $slug = array_map('sanitize_title', $args['slug']); $where .= " AND t.slug IN ('" . implode("', '", $slug) . "')"; } else { $slug = sanitize_title($args['slug']); $where .= " AND t.slug = '{$slug}'"; } } if (!empty($args['name__like'])) { $where .= $wpdb->prepare(" AND t.name LIKE %s", '%' . $wpdb->esc_like($args['name__like']) . '%'); } if (!empty($args['description__like'])) { $where .= $wpdb->prepare(" AND tt.description LIKE %s", '%' . $wpdb->esc_like($args['description__like']) . '%'); } if ('' !== $parent) { $parent = (int) $parent; $where .= " AND tt.parent = '{$parent}'"; } $hierarchical = $args['hierarchical']; if ('count' == $args['fields']) { $hierarchical = false; } if ($args['hide_empty'] && !$hierarchical) { $where .= ' AND tt.count > 0'; } $number = $args['number']; $offset = $args['offset']; // Don't limit the query results when we have to descend the family tree. if ($number && !$hierarchical && !$child_of && '' === $parent) { if ($offset) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . $number; } } else { $limits = ''; } if (!empty($args['search'])) { $like = '%' . $wpdb->esc_like($args['search']) . '%'; $where .= $wpdb->prepare(' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like); } // Meta query support. $join = ''; if (!empty($args['meta_query'])) { $mquery = new WP_Meta_Query($args['meta_query']); $mq_sql = $mquery->get_sql('term', 't', 'term_id'); $join .= $mq_sql['join']; $where .= $mq_sql['where']; } $selects = array(); switch ($args['fields']) { case 'all': $selects = array('t.*', 'tt.*'); break; case 'ids': case 'id=>parent': $selects = array('t.term_id', 'tt.parent', 'tt.count', 'tt.taxonomy'); break; case 'names': $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name', 'tt.taxonomy'); break; case 'count': $orderby = ''; $order = ''; $selects = array('COUNT(*)'); break; case 'id=>name': $selects = array('t.term_id', 't.name', 'tt.count', 'tt.taxonomy'); break; case 'id=>slug': $selects = array('t.term_id', 't.slug', 'tt.count', 'tt.taxonomy'); break; } $_fields = $args['fields']; /** * Filter the fields to select in the terms query. * * Field lists modified using this filter will only modify the term fields returned * by the function when the `$fields` parameter set to 'count' or 'all'. In all other * cases, the term fields in the results array will be determined by the `$fields` * parameter alone. * * Use of this filter can result in unpredictable behavior, and is not recommended. * * @since 2.8.0 * * @param array $selects An array of fields to select for the terms query. * @param array $args An array of term query arguments. * @param array $taxonomies An array of taxonomies. */ $fields = implode(', ', apply_filters('get_terms_fields', $selects, $args, $taxonomies)); $join .= " INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id"; $pieces = array('fields', 'join', 'where', 'orderby', 'order', 'limits'); /** * Filter the terms query SQL clauses. * * @since 3.1.0 * * @param array $pieces Terms query SQL clauses. * @param array $taxonomies An array of taxonomies. * @param array $args An array of terms query arguments. */ $clauses = apply_filters('terms_clauses', compact($pieces), $taxonomies, $args); $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $where = isset($clauses['where']) ? $clauses['where'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $order = isset($clauses['order']) ? $clauses['order'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; $query = "SELECT {$fields} FROM {$wpdb->terms} AS t {$join} WHERE {$where} {$orderby} {$order} {$limits}"; // $args can be anything. Only use the args defined in defaults to compute the key. $key = md5(serialize(wp_array_slice_assoc($args, array_keys($defaults))) . serialize($taxonomies) . $query); $last_changed = wp_cache_get('last_changed', 'terms'); if (!$last_changed) { $last_changed = microtime(); wp_cache_set('last_changed', $last_changed, 'terms'); } $cache_key = "get_terms:{$key}:{$last_changed}"; $cache = wp_cache_get($cache_key, 'terms'); if (false !== $cache) { if ('all' === $_fields) { $cache = array_map('get_term', $cache); } /** * Filter the given taxonomy's terms cache. * * @since 2.3.0 * * @param array $cache Cached array of terms for the given taxonomy. * @param array $taxonomies An array of taxonomies. * @param array $args An array of get_terms() arguments. */ return apply_filters('get_terms', $cache, $taxonomies, $args); } if ('count' == $_fields) { return $wpdb->get_var($query); } $terms = $wpdb->get_results($query); if ('all' == $_fields) { update_term_cache($terms); } // Prime termmeta cache. if ($args['update_term_meta_cache']) { $term_ids = wp_list_pluck($terms, 'term_id'); update_termmeta_cache($term_ids); } if (empty($terms)) { wp_cache_add($cache_key, array(), 'terms', DAY_IN_SECONDS); /** This filter is documented in wp-includes/taxonomy-functions.php */ return apply_filters('get_terms', array(), $taxonomies, $args); } if ($child_of) { foreach ($taxonomies as $_tax) { $children = _get_term_hierarchy($_tax); if (!empty($children)) { $terms = _get_term_children($child_of, $terms, $_tax); } } } // Update term counts to include children. if ($args['pad_counts'] && 'all' == $_fields) { foreach ($taxonomies as $_tax) { _pad_term_counts($terms, $_tax); } } // Make sure we show empty categories that have children. if ($hierarchical && $args['hide_empty'] && is_array($terms)) { foreach ($terms as $k => $term) { if (!$term->count) { $children = get_term_children($term->term_id, $term->taxonomy); if (is_array($children)) { foreach ($children as $child_id) { $child = get_term($child_id, $term->taxonomy); if ($child->count) { continue 2; } } } // It really is empty. unset($terms[$k]); } } } $_terms = array(); if ('id=>parent' == $_fields) { foreach ($terms as $term) { $_terms[$term->term_id] = $term->parent; } } elseif ('ids' == $_fields) { foreach ($terms as $term) { $_terms[] = $term->term_id; } } elseif ('names' == $_fields) { foreach ($terms as $term) { $_terms[] = $term->name; } } elseif ('id=>name' == $_fields) { foreach ($terms as $term) { $_terms[$term->term_id] = $term->name; } } elseif ('id=>slug' == $_fields) { foreach ($terms as $term) { $_terms[$term->term_id] = $term->slug; } } if (!empty($_terms)) { $terms = $_terms; } if ($number && is_array($terms) && count($terms) > $number) { $terms = array_slice($terms, $offset, $number); } wp_cache_add($cache_key, $terms, 'terms', DAY_IN_SECONDS); if ('all' === $_fields) { $terms = array_map('get_term', $terms); } /** This filter is documented in wp-includes/taxonomy */ return apply_filters('get_terms', $terms, $taxonomies, $args); }
/** * Display or retrieve the HTML list of categories. * * @since 2.1.0 * @since 4.4.0 Introduced the `hide_title_if_empty` and `separator` arguments. The `current_category` argument was modified to * optionally accept an array of values. * * @param string|array $args { * Array of optional arguments. * * @type int $child_of Term ID to retrieve child terms of. See get_terms(). Default 0. * @type int|array $current_category ID of category, or array of IDs of categories, that should get the * 'current-cat' class. Default 0. * @type int $depth Category depth. Used for tab indentation. Default 0. * @type bool|int $echo True to echo markup, false to return it. Default 1. * @type array|string $exclude Array or comma/space-separated string of term IDs to exclude. * If `$hierarchical` is true, descendants of `$exclude` terms will also * be excluded; see `$exclude_tree`. See get_terms(). * Default empty string. * @type array|string $exclude_tree Array or comma/space-separated string of term IDs to exclude, along * with their descendants. See get_terms(). Default empty string. * @type string $feed Text to use for the feed link. Default 'Feed for all posts filed * under [cat name]'. * @type string $feed_image URL of an image to use for the feed link. Default empty string. * @type string $feed_type Feed type. Used to build feed link. See get_term_feed_link(). * Default empty string (default feed). * @type bool|int $hide_empty Whether to hide categories that don't have any posts attached to them. * Default 1. * @type bool $hide_title_if_empty Whether to hide the `$title_li` element if there are no terms in * the list. Default false (title will always be shown). * @type bool $hierarchical Whether to include terms that have non-empty descendants. * See get_terms(). Default true. * @type string $order Which direction to order categories. Accepts 'ASC' or 'DESC'. * Default 'ASC'. * @type string $orderby The column to use for ordering categories. Default 'ID'. * @type string $separator Separator between links. Default '<br />'. * @type bool|int $show_count Whether to show how many posts are in the category. Default 0. * @type string $show_option_all Text to display for showing all categories. Default empty string. * @type string $show_option_none Text to display for the 'no categories' option. * Default 'No categories'. * @type string $style The style used to display the categories list. If 'list', categories * will be output as an unordered list. If left empty or another value, * categories will be output separated by `<br>` tags. Default 'list'. * @type string $taxonomy Taxonomy name. Default 'category'. * @type string $title_li Text to use for the list title `<li>` element. Pass an empty string * to disable. Default 'Categories'. * @type bool|int $use_desc_for_title Whether to use the category description as the title attribute. * Default 1. * } * @return false|string HTML content only if 'echo' argument is 0. */ function wp_list_categories($args = '') { $defaults = array('child_of' => 0, 'current_category' => 0, 'depth' => 0, 'echo' => 1, 'exclude' => '', 'exclude_tree' => '', 'feed' => '', 'feed_image' => '', 'feed_type' => '', 'hide_empty' => 1, 'hide_title_if_empty' => false, 'hierarchical' => true, 'order' => 'ASC', 'orderby' => 'name', 'separator' => '<br />', 'show_count' => 0, 'show_option_all' => '', 'show_option_none' => __('No categories'), 'style' => 'list', 'taxonomy' => 'category', 'title_li' => __('Categories'), 'use_desc_for_title' => 1); $r = wp_parse_args($args, $defaults); if (!isset($r['pad_counts']) && $r['show_count'] && $r['hierarchical']) { $r['pad_counts'] = true; } // Descendants of exclusions should be excluded too. if (true == $r['hierarchical']) { $exclude_tree = array(); if ($r['exclude_tree']) { $exclude_tree = array_merge($exclude_tree, wp_parse_id_list($r['exclude_tree'])); } if ($r['exclude']) { $exclude_tree = array_merge($exclude_tree, wp_parse_id_list($r['exclude'])); } $r['exclude_tree'] = $exclude_tree; $r['exclude'] = ''; } if (!isset($r['class'])) { $r['class'] = 'category' == $r['taxonomy'] ? 'categories' : $r['taxonomy']; } if (!taxonomy_exists($r['taxonomy'])) { return false; } $show_option_all = $r['show_option_all']; $show_option_none = $r['show_option_none']; $categories = get_categories($r); $output = ''; if ($r['title_li'] && 'list' == $r['style'] && (!empty($categories) || !$r['hide_title_if_empty'])) { $output = '<li class="' . esc_attr($r['class']) . '">' . $r['title_li'] . '<ul>'; } if (empty($categories)) { if (!empty($show_option_none)) { if ('list' == $r['style']) { $output .= '<li class="cat-item-none">' . $show_option_none . '</li>'; } else { $output .= $show_option_none; } } } else { if (!empty($show_option_all)) { $posts_page = ''; // For taxonomies that belong only to custom post types, point to a valid archive. $taxonomy_object = get_taxonomy($r['taxonomy']); if (!in_array('post', $taxonomy_object->object_type) && !in_array('page', $taxonomy_object->object_type)) { foreach ($taxonomy_object->object_type as $object_type) { $_object_type = get_post_type_object($object_type); // Grab the first one. if (!empty($_object_type->has_archive)) { $posts_page = get_post_type_archive_link($object_type); break; } } } // Fallback for the 'All' link is the posts page. if (!$posts_page) { if ('page' == get_option('show_on_front') && get_option('page_for_posts')) { $posts_page = get_permalink(get_option('page_for_posts')); } else { $posts_page = home_url('/'); } } $posts_page = esc_url($posts_page); if ('list' == $r['style']) { $output .= "<li class='cat-item-all'><a href='{$posts_page}'>{$show_option_all}</a></li>"; } else { $output .= "<a href='{$posts_page}'>{$show_option_all}</a>"; } } if (empty($r['current_category']) && (is_category() || is_tax() || is_tag())) { $current_term_object = get_queried_object(); if ($current_term_object && $r['taxonomy'] === $current_term_object->taxonomy) { $r['current_category'] = get_queried_object_id(); } } if ($r['hierarchical']) { $depth = $r['depth']; } else { $depth = -1; // Flat. } $output .= walk_category_tree($categories, $depth, $r); } if ($r['title_li'] && 'list' == $r['style'] && (!empty($categories) || !$r['hide_title_if_empty'])) { $output .= '</ul></li>'; } /** * Filters the HTML output of a taxonomy list. * * @since 2.1.0 * * @param string $output HTML output. * @param array $args An array of taxonomy-listing arguments. */ $html = apply_filters('wp_list_categories', $output, $args); if ($r['echo']) { echo $html; } else { return $html; } }
/** * @group get */ public function test_get_with_type_popular() { $time = time(); $g1 = $this->factory->group->create(array('name' => 'A Group', 'date_created' => bp_core_current_time())); $g2 = $this->factory->group->create(array('name' => 'D Group', 'date_created' => gmdate('Y-m-d H:i:s', $time - 100))); $g3 = $this->factory->group->create(array('name' => 'B Group', 'date_created' => gmdate('Y-m-d H:i:s', $time - 100000))); $g4 = $this->factory->group->create(array('name' => 'C Group', 'date_created' => gmdate('Y-m-d H:i:s', $time - 1000))); groups_update_groupmeta($g1, 'total_member_count', 1); groups_update_groupmeta($g2, 'total_member_count', 4); groups_update_groupmeta($g3, 'total_member_count', 2); groups_update_groupmeta($g4, 'total_member_count', 3); $groups = BP_Groups_Group::get(array('type' => 'popular')); $found = wp_parse_id_list(wp_list_pluck($groups['groups'], 'id')); $this->assertEquals(array($g2, $g4, $g3, $g1), $found); }