Пример #1
0
	function test_vb_insert_get_delete() {
		register_post_type( 'cpt', array( 'taxonomies' => array( 'post_tag', 'ctax' ) ) );
		register_taxonomy( 'ctax', 'cpt' );
		$post_types = array( 'post', 'cpt' );

		foreach ( $post_types as $post_type ) {
			$post = array(
				'post_author' => $this->author_id,
				'post_status' => 'publish',
				'post_content' => rand_str(),
				'post_title' => rand_str(),
				'tax_input' => array( 'post_tag' => 'tag1,tag2', 'ctax' => 'cterm1,cterm2' ),
				'post_type' => $post_type
			);

			// insert a post and make sure the ID is ok
			$id = wp_insert_post($post);
			$this->assertTrue(is_numeric($id));
			$this->assertTrue($id > 0);

			// fetch the post and make sure it matches
			$out = get_post($id);

			$this->assertEquals($post['post_content'], $out->post_content);
			$this->assertEquals($post['post_title'], $out->post_title);
			$this->assertEquals($post['post_status'], $out->post_status);
			$this->assertEquals($post['post_author'], $out->post_author);

			// test cache state
			$pcache = wp_cache_get( $id, 'posts' );
			$this->assertInstanceOf( 'stdClass', $pcache );
			$this->assertEquals( $id, $pcache->ID );

			update_object_term_cache( $id, $post_type );
			$tcache = wp_cache_get( $id, "post_tag_relationships" );
			$this->assertInternalType( 'array', $tcache );
			$this->assertEquals( 2, count( $tcache ) );

			$tcache = wp_cache_get( $id, "ctax_relationships" );
			if ( 'cpt' == $post_type ) {
				$this->assertInternalType( 'array', $tcache );
				$this->assertEquals( 2, count( $tcache ) );
			} else {
				$this->assertFalse( $tcache );
			}

			wp_delete_post( $id, true );
			$this->assertFalse( wp_cache_get( $id, 'posts' ) );
			$this->assertFalse( wp_cache_get( $id, "post_tag_relationships" ) );
			$this->assertFalse( wp_cache_get( $id, "ctax_relationships" ) );
		}

		$GLOBALS['wp_taxonomies']['post_tag']->object_type = array( 'post' );
	}
Пример #2
0
/**
 * Update taxonomies cache for the custom post types for the current query.
 */
function gdtt_custom_post_types_cache()
{
    global $wp_query;
    $post_ids = array();
    for ($i = 0; $i < count($wp_query->posts); $i++) {
        $post_ids[] = $wp_query->posts[$i]->ID;
    }
    if (!empty($post_ids)) {
        update_object_term_cache($post_ids, get_query_var("post_type"));
    }
}
Пример #3
0
 public function _prime_terms_cache($terms, $taxonomies)
 {
     if ($this->is_translated_taxonomy($taxonomies)) {
         foreach ($terms as $term) {
             $term_ids[] = is_object($term) ? $term->term_id : $term;
         }
     }
     if (!empty($term_ids)) {
         update_object_term_cache(array_unique($term_ids), 'term');
     }
     // adds language and translation of terms to cache
     return $terms;
 }
Пример #4
0
 public function option_sticky_posts($posts)
 {
     if ($this->curlang && !empty($posts)) {
         update_object_term_cache($posts, 'post');
         // to avoid queries in foreach
         foreach ($posts as $key => $post_id) {
             $lang = $this->model->post->get_language($post_id);
             if (empty($lang) || $lang->term_id != $this->curlang->term_id) {
                 unset($posts[$key]);
             }
         }
     }
     return $posts;
 }
Пример #5
0
 /**
  * filters get_pages per language
  *
  * @since 1.4
  *
  * @param array $pages an array of pages already queried
  * @param array $args get_pages arguments
  * @return array modified list of pages
  */
 public function get_pages($pages, $args)
 {
     if (isset($args['lang']) && empty($args['lang'])) {
         return $pages;
     }
     $language = empty($args['lang']) ? $this->curlang : $this->model->get_language($args['lang']);
     if (empty($language) || empty($pages) || !$this->model->is_translated_post_type($args['post_type'])) {
         return $pages;
     }
     static $once = false;
     // obliged to redo the get_pages query if we want to get the right number
     if (!empty($args['number']) && !$once) {
         $once = true;
         // avoid infinite loop
         $r = array('lang' => 0, 'numberposts' => -1, 'nopaging' => true, 'post_type' => $args['post_type'], 'fields' => 'ids', 'tax_query' => array(array('taxonomy' => 'language', 'field' => 'term_taxonomy_id', 'terms' => $language->term_taxonomy_id, 'operator' => 'NOT IN')));
         $args['exclude'] = array_merge($args['exclude'], get_posts($r));
         $pages = get_pages($args);
     }
     $ids = wp_list_pluck($pages, 'ID');
     // filters the queried list of pages by language
     if (!$once) {
         $ids = array_intersect($ids, $this->model->post->get_objects_in_language($language));
         foreach ($pages as $key => $page) {
             if (!in_array($page->ID, $ids)) {
                 unset($pages[$key]);
             }
         }
     }
     // not done by WP but extremely useful for performance when manipulating taxonomies
     update_object_term_cache($ids, $args['post_type']);
     $once = false;
     // in case get_pages is called another time
     return $pages;
 }
Пример #6
0
/**
 * update_post_caches() - Call major cache updating functions for list of Post objects.
 *
 * @package WordPress
 * @subpackage Cache
 * @since 1.5
 *
 * @uses $wpdb
 * @uses update_post_cache()
 * @uses update_object_term_cache()
 * @uses update_postmeta_cache()
 *
 * @param array $posts Array of Post objects
 */
function update_post_caches(&$posts)
{
    // No point in doing all this work if we didn't match any posts.
    if (!$posts) {
        return;
    }
    update_post_cache($posts);
    $post_ids = array();
    for ($i = 0; $i < count($posts); $i++) {
        $post_ids[] = $posts[$i]->ID;
    }
    update_object_term_cache($post_ids, 'post');
    update_postmeta_cache($post_ids);
}
function wpv_filter_extend_query_for_parametric_and_counters($post_query, $view_settings, $id)
{
    $dps_enabled = false;
    $counters_enabled = false;
    if (!isset($view_settings['dps']) || !is_array($view_settings['dps'])) {
        $view_settings['dps'] = array();
    }
    if (isset($view_settings['dps']['enable_dependency']) && $view_settings['dps']['enable_dependency'] == 'enable') {
        $dps_enabled = true;
        $controls_per_kind = wpv_count_filter_controls($view_settings);
        $controls_count = 0;
        $no_intersection = array();
        if (!isset($controls_per_kind['error'])) {
            //	$controls_count = array_sum( $controls_per_kind );
            $controls_count = $controls_per_kind['cf'] + $controls_per_kind['tax'] + $controls_per_kind['pr'] + $controls_per_kind['search'];
            if ($controls_per_kind['cf'] > 1 && (!isset($view_settings['custom_fields_relationship']) || $view_settings['custom_fields_relationship'] != 'AND')) {
                $no_intersection[] = __('custom field', 'wpv-views');
            }
            if ($controls_per_kind['tax'] > 1 && (!isset($view_settings['taxonomy_relationship']) || $view_settings['taxonomy_relationship'] != 'AND')) {
                $no_intersection[] = __('taxonomy', 'wpv-views');
            }
        } else {
            $dps_enabled = false;
        }
        if ($controls_count > 0) {
            if (count($no_intersection) > 0) {
                $dps_enabled = false;
            }
        } else {
            $dps_enabled = false;
        }
    }
    if (!isset($view_settings['filter_meta_html'])) {
        $view_settings['filter_meta_html'] = '';
    }
    if (strpos($view_settings['filter_meta_html'], '%%COUNT%%') !== false) {
        $counters_enabled = true;
    }
    global $WP_Views;
    if (!$dps_enabled && !$counters_enabled) {
        // Set the force value
        $WP_Views->set_force_disable_dependant_parametric_search(true);
        return $post_query;
    }
    // If after all we have dps, we need to populate the $wp_object_cache
    // Check if we need to create all the cache or just for the missing ones
    global $wp_object_cache;
    $cache_exclude_queried_posts = false;
    // we will only exclude already queried posts if there are any queried posts and the native cache exists (so they are already cached)
    $cache_use_native = true;
    if (is_object($wp_object_cache)) {
        if (isset($wp_object_cache->cache)) {
            // existing queried posts were already cached
            if (empty($post_query)) {
                $cache_exclude_queried_posts = false;
                // we passed an empty $post_query so there are no queried posts at all (surely coming from a form View shortcode)
            } else {
                $cache_exclude_queried_posts = true;
            }
        } else {
            $wp_object_cache->cache = array();
            $cache_exclude_queried_posts = false;
            // already queried posts were not cached where we need them
            $cache_use_native = false;
            // the native $wp_object_cache->cache property is not set, so we will recreate it instead of naturally caching metadata
        }
    }
    // In any case, we need to mimic the process that we used to generate the $query
    $view_settings_defaults = array('post_type' => 'any', 'orderby' => 'post-date', 'order' => 'DESC', 'paged' => '1', 'posts_per_page' => -1);
    extract($view_settings_defaults);
    $view_settings['view_id'] = $id;
    extract($view_settings, EXTR_OVERWRITE);
    $query = array('posts_per_page' => $posts_per_page, 'paged' => $paged, 'post_type' => $post_type, 'order' => $order, 'suppress_filters' => false, 'ignore_sticky_posts' => true);
    // Add special check for media (attachments) as their default status in not usually published
    if (sizeof($post_type) == 1 && $post_type[0] == 'attachment') {
        $query['post_status'] = 'any';
        // Note this can be overriden by adding a status filter.
    }
    $query = apply_filters('wpv_filter_query', $query, $view_settings, $id);
    // Now we have the $query as in the original one
    // We now need to overwrite the limit, offset, paged and pagination options
    // Also, we set it to just return the IDs
    $query['posts_per_page'] = -1;
    $query['ĺimit'] = -1;
    $query['paged'] = 1;
    $query['offset'] = 0;
    $query['fields'] = 'ids';
    if ($cache_exclude_queried_posts) {
        // do not query again already queried and cached posts
        $already = array();
        if (isset($post_query->posts) && !empty($post_query->posts)) {
            foreach ((array) $post_query->posts as $post_object) {
                $already[] = $post_object->ID;
            }
        }
        $WP_Views->returned_ids_for_parametric_search = $already;
        if (isset($query['pr_filter_post__in'])) {
            $query['post__in'] = $query['pr_filter_post__in'];
        } else {
            // If just for the missing ones, generate the post__not_in argument
            if (isset($query['post__not_in'])) {
                $query['post__not_in'] = array_merge((array) $query['post__not_in'], (array) $already);
            } else {
                $query['post__not_in'] = (array) $already;
            }
            // And adjust on the post__in argument
            if (isset($query['post__in'])) {
                $query['post__in'] = array_diff((array) $query['post__in'], (array) $query['post__not_in']);
                //unset( $query['post__in'] );
            }
        }
    }
    // Perform the query
    $aux_cache_query = new WP_Query($query);
    // In case we need to recreate our own cache object, we do not need to load there all the postmeta and taxonomy data, just for the elements involved in parametric search controls
    $filter_c_mode = isset($view_settings['filter_controls_mode']) && is_array($view_settings['filter_controls_mode']) ? $view_settings['filter_controls_mode'] : array();
    $filter_c_name = isset($view_settings['filter_controls_field_name']) && is_array($view_settings['filter_controls_field_name']) ? $view_settings['filter_controls_field_name'] : array();
    $f_taxes = array();
    $f_fields = array();
    foreach ($filter_c_mode as $f_index => $f_mode) {
        if (isset($filter_c_name[$f_index])) {
            switch ($f_mode) {
                case 'slug':
                    $f_taxes[] = $filter_c_name[$f_index];
                    break;
                case 'cf':
                    $f_fields[] = $filter_c_name[$f_index];
                    break;
                case 'rel':
                    if (function_exists('wpcf_pr_get_belongs')) {
                        $returned_post_types = $view_settings['post_type'];
                        $returned_post_type_parents = array();
                        if (empty($returned_post_types)) {
                            $returned_post_types = array('any');
                        }
                        foreach ($returned_post_types as $returned_post_type_slug) {
                            $parent_parents_array = wpcf_pr_get_belongs($returned_post_type_slug);
                            if ($parent_parents_array != false && is_array($parent_parents_array)) {
                                $returned_post_type_parents = array_merge($returned_post_type_parents, array_values(array_keys($parent_parents_array)));
                            }
                        }
                        foreach ($returned_post_type_parents as $parent_to_cache) {
                            $f_fields[] = '_wpcf_belongs_' . $parent_to_cache . '_id';
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
    // If we are using the native caching, update the cache for the posts returned by the aux query
    if (is_array($aux_cache_query->posts) && !empty($aux_cache_query->posts)) {
        $WP_Views->returned_ids_for_parametric_search = array_merge($WP_Views->returned_ids_for_parametric_search, $aux_cache_query->posts);
        $WP_Views->returned_ids_for_parametric_search = array_unique($WP_Views->returned_ids_for_parametric_search);
        if ($cache_use_native) {
            // If we are using the native caching, update the cache for the posts returned by the aux query
            update_postmeta_cache($aux_cache_query->posts);
            update_object_term_cache($aux_cache_query->posts, $view_settings['post_type']);
        } else {
            // Else, we need to fake an $wp_object_cache->cache
            $f_data = array('cf' => $f_fields, 'tax' => $f_taxes);
            $cache_combined = wpv_custom_cache_metadata($aux_cache_query->posts, $f_data);
            $wp_object_cache->cache = $cache_combined;
        }
    }
    return $post_query;
}
Пример #8
0
	/**
	 * @ticket 31086
	 */
	public function test_get_the_terms_should_return_zero_indexed_array_when_cache_is_primed() {
		register_taxonomy( 'wptests_tax', 'post' );
		$p = $this->factory->post->create();
		wp_set_object_terms( $p, array( 'foo', 'bar' ), 'wptests_tax' );

		// Prime cache.
		update_object_term_cache( array( $p ), array( 'post' ) );

		$found = get_the_terms( $p, 'wptests_tax' );

		$this->assertEqualSets( array( 0, 1 ), array_keys( $found ) );
	}
 /**
  * @group cache
  */
 public function test_taxonomy_classes_hit_cache()
 {
     global $wpdb;
     register_taxonomy('wptests_tax', 'post');
     wp_set_post_terms($this->post_id, array('foo', 'bar'), 'wptests_tax');
     wp_set_post_terms($this->post_id, array('footag', 'bartag'), 'post_tag');
     // Prime cache, including meta cache, which is used by get_post_class().
     update_object_term_cache($this->post_id, 'post');
     update_meta_cache('post', $this->post_id);
     $num_queries = $wpdb->num_queries;
     $found = get_post_class('', $this->post_id);
     $this->assertSame($num_queries, $wpdb->num_queries);
 }
 /**
  * Gets the event counts for individual days.
  *
  * @param array $args
  *
  * @return array The counts array.
  */
 public static function getEventCounts($args = array())
 {
     global $wpdb;
     do_action('log', 'getEventCounts() $args', 'tribe-events-query', $args);
     $date = date('Y-m-d');
     $defaults = array('post_type' => TribeEvents::POSTTYPE, 'start_date' => tribe_event_beginning_of_day($date), 'end_date' => tribe_event_end_of_day($date), 'display_type' => 'daily', 'hide_upcoming_ids' => null);
     $args = wp_parse_args($args, $defaults);
     $args['posts_per_page'] = -1;
     $args['fields'] = 'ids';
     // remove empty args and sort by key, this increases chance of a cache hit
     $args = array_filter($args, array(__CLASS__, 'filter_args'));
     ksort($args);
     $cache = new TribeEventsCache();
     $cache_key = 'daily_counts_and_ids_' . serialize($args);
     $found = $cache->get($cache_key, 'save_post');
     if ($found) {
         do_action('log', 'cache hit ' . __LINE__, 'tribe-events-cache', $args);
         return $found;
     }
     do_action('log', 'no cache hit ' . __LINE__, 'tribe-events-cache', $args);
     $cache_key = 'month_post_ids_' . serialize($args);
     $found = $cache->get($cache_key, 'save_post');
     if ($found && is_array($found)) {
         do_action('log', 'cache hit ' . __LINE__, 'tribe-events-cache', $args);
         $post_ids = $found;
     } else {
         do_action('log', 'no cache hit ' . __LINE__, 'tribe-events-cache', $args);
         $post_id_query = new WP_Query();
         $post_ids = $post_id_query->query($args);
         do_action('log', 'final args for month view post ids', 'tribe-events-query', $post_id_query->query_vars);
         do_action('log', 'Month view getEventCounts SQL', 'tribe-events-query', $post_id_query->request);
         $cache->set($cache_key, $post_ids, TribeEventsCache::NON_PERSISTENT, 'save_post');
     }
     do_action('log', 'Month view post ids found', 'tribe-events-query', $post_ids);
     $counts = array();
     $event_ids = array();
     if (!empty($post_ids)) {
         switch ($args['display_type']) {
             case 'daily':
             default:
                 global $wp_query;
                 $output_date_format = '%Y-%m-%d %H:%i:%s';
                 do_action('log', 'raw counts args', 'tribe-events-query', $args);
                 $raw_counts = $wpdb->get_results($wpdb->prepare("\n\t\t\t\t\t\t\tSELECT \ttribe_event_start.post_id as ID, \n\t\t\t\t\t\t\t\t\ttribe_event_start.meta_value as EventStartDate, \n\t\t\t\t\t\t\t\t\tDATE_FORMAT( tribe_event_end_date.meta_value, '%1\$s') as EventEndDate,\n\t\t\t\t\t\t\t\t\t{$wpdb->posts}.menu_order as menu_order\n\t\t\t\t\t\t\tFROM {$wpdb->postmeta} AS tribe_event_start\n\t\t\t\t\t\t\t\t\tLEFT JOIN {$wpdb->posts} ON (tribe_event_start.post_id = {$wpdb->posts}.ID)\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->postmeta} as tribe_event_end_date ON ( tribe_event_start.post_id = tribe_event_end_date.post_id AND tribe_event_end_date.meta_key = '_EventEndDate' )\n\t\t\t\t\t\t\tWHERE tribe_event_start.meta_key = '_EventStartDate'\n\t\t\t\t\t\t\tAND tribe_event_start.post_id IN ( %5\$s )\n\t\t\t\t\t\t\tAND ( (tribe_event_start.meta_value >= '%3\$s' AND  tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t\tOR (tribe_event_start.meta_value <= '%3\$s' AND tribe_event_end_date.meta_value >= '%3\$s')\n\t\t\t\t\t\t\t\tOR ( tribe_event_start.meta_value >= '%3\$s' AND  tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tORDER BY menu_order ASC, DATE(tribe_event_start.meta_value) ASC, TIME(tribe_event_start.meta_value) ASC;", $output_date_format, $output_date_format, $post_id_query->query_vars['start_date'], $post_id_query->query_vars['end_date'], implode(',', array_map('intval', $post_ids))));
                 do_action('log', 'raw counts query', 'tribe-events-query', $wpdb->last_query);
                 $start_date = new DateTime($post_id_query->query_vars['start_date']);
                 $end_date = new DateTime($post_id_query->query_vars['end_date']);
                 $days = TribeDateUtils::dateDiff($start_date->format('Y-m-d'), $end_date->format('Y-m-d'));
                 $term_id = isset($wp_query->query_vars[TribeEvents::TAXONOMY]) ? $wp_query->query_vars[TribeEvents::TAXONOMY] : null;
                 if (is_int($term_id)) {
                     $term = get_term_by('id', $term_id, TribeEvents::TAXONOMY);
                 } elseif (is_string($term_id)) {
                     $term = get_term_by('slug', $term_id, TribeEvents::TAXONOMY);
                 }
                 for ($i = 0, $date = $start_date; $i <= $days; $i++, $date->modify('+1 day')) {
                     $formatted_date = $date->format('Y-m-d');
                     $start_of_day = strtotime(tribe_event_beginning_of_day($formatted_date));
                     $end_of_day = strtotime(tribe_event_end_of_day($formatted_date)) + 1;
                     $count = 0;
                     $_day_event_ids = array();
                     foreach ($raw_counts as $record) {
                         $record_start = strtotime($record->EventStartDate);
                         $record_end = strtotime($record->EventEndDate);
                         /**
                          * conditions:
                          * event starts on this day (event start time is between start and end of day)
                          * event ends on this day (event end time is between start and end of day)
                          * event starts before start of day and ends after end of day (spans across this day)
                          * note:
                          * events that start exactly on the EOD cutoff will count on the following day
                          * events that end exactly on the EOD cutoff will count on the previous day
                          */
                         $event_starts_today = $record_start >= $start_of_day && $record_start < $end_of_day;
                         $event_ends_today = $record_end > $start_of_day && $record_end <= $end_of_day;
                         $event_spans_across_today = $record_start < $start_of_day && $record_end > $end_of_day;
                         if ($event_starts_today || $event_ends_today || $event_spans_across_today) {
                             if (isset($term->term_id)) {
                                 if (!has_term($term, TribeEvents::TAXONOMY, $record->ID)) {
                                     continue;
                                 }
                             }
                             if (count($_day_event_ids) < apply_filters('tribe_events_month_day_limit', tribe_get_option('monthEventAmount', '3'))) {
                                 $_day_event_ids[] = $record->ID;
                             }
                             $count++;
                         }
                     }
                     $event_ids[$formatted_date] = $_day_event_ids;
                     $counts[$formatted_date] = $count;
                 }
                 break;
         }
         // get a unique list of the event IDs that will be displayed, and update all their postmeta and term caches at once
         $final_event_ids = array();
         $final_event_ids = call_user_func_array('array_merge', $event_ids);
         $final_event_ids = array_unique($final_event_ids);
         do_action('log', 'updating term and postmeta caches for events', 'tribe-events-cache', $final_event_ids);
         update_object_term_cache($final_event_ids, TribeEvents::POSTTYPE);
         update_postmeta_cache($final_event_ids);
     }
     // return IDs per day and total counts per day
     $return = array('counts' => $counts, 'event_ids' => $event_ids);
     $cache = new TribeEventsCache();
     $cache_key = 'daily_counts_and_ids_' . serialize($args);
     $cache->set($cache_key, $return, TribeEventsCache::NON_PERSISTENT, 'save_post');
     do_action('log', 'final event counts result', 'tribe-events-query', $return);
     return $return;
 }
Пример #11
0
function update_post_caches(&$posts)
{
    global $post_cache;
    global $wpdb, $blog_id;
    // No point in doing all this work if we didn't match any posts.
    if (!$posts) {
        return;
    }
    // Get the categories for all the posts
    for ($i = 0; $i < count($posts); $i++) {
        $post_id_array[] = $posts[$i]->ID;
        $post_cache[$blog_id][$posts[$i]->ID] =& $posts[$i];
    }
    $post_id_list = implode(',', $post_id_array);
    update_object_term_cache($post_id_list, 'post');
    update_postmeta_cache($post_id_list);
}
 /**
  * Gets the event counts for individual days.
  *
  * @param array $args
  *
  * @return array The counts array.
  */
 public static function getEventCounts($args = array())
 {
     _deprecated_function(__METHOD__, '3.10.1');
     global $wpdb;
     $date = date('Y-m-d');
     $defaults = array('post_type' => Tribe__Events__Main::POSTTYPE, 'start_date' => tribe_beginning_of_day($date), 'end_date' => tribe_end_of_day($date), 'display_type' => 'daily', 'hide_upcoming_ids' => null);
     $args = wp_parse_args($args, $defaults);
     $args['posts_per_page'] = -1;
     $args['fields'] = 'ids';
     // remove empty args and sort by key, this increases chance of a cache hit
     $args = array_filter($args, array(__CLASS__, 'filter_args'));
     ksort($args);
     $cache = new Tribe__Cache();
     $cache_key = 'daily_counts_and_ids_' . serialize($args);
     $found = $cache->get($cache_key, 'save_post');
     if ($found) {
         return $found;
     }
     $cache_key = 'month_post_ids_' . serialize($args);
     $found = $cache->get($cache_key, 'save_post');
     if ($found && is_array($found)) {
         $post_ids = $found;
     } else {
         $post_id_query = new WP_Query();
         $post_ids = $post_id_query->query($args);
         $cache->set($cache_key, $post_ids, Tribe__Cache::NON_PERSISTENT, 'save_post');
     }
     $counts = array();
     $event_ids = array();
     if (!empty($post_ids)) {
         switch ($args['display_type']) {
             case 'daily':
             default:
                 global $wp_query;
                 $output_date_format = '%Y-%m-%d %H:%i:%s';
                 $raw_counts = $wpdb->get_results($wpdb->prepare("\n\t\t\t\t\t\t\tSELECT \ttribe_event_start.post_id as ID,\n\t\t\t\t\t\t\t\t\ttribe_event_start.meta_value as EventStartDate,\n\t\t\t\t\t\t\t\t\tDATE_FORMAT( tribe_event_end_date.meta_value, '%1\$s') as EventEndDate,\n\t\t\t\t\t\t\t\t\t{$wpdb->posts}.menu_order as menu_order\n\t\t\t\t\t\t\tFROM {$wpdb->postmeta} AS tribe_event_start\n\t\t\t\t\t\t\t\t\tLEFT JOIN {$wpdb->posts} ON (tribe_event_start.post_id = {$wpdb->posts}.ID)\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->postmeta} as tribe_event_end_date ON ( tribe_event_start.post_id = tribe_event_end_date.post_id AND tribe_event_end_date.meta_key = '_EventEndDate' )\n\t\t\t\t\t\t\tWHERE tribe_event_start.meta_key = '_EventStartDate'\n\t\t\t\t\t\t\tAND tribe_event_start.post_id IN ( %5\$s )\n\t\t\t\t\t\t\tAND ( (tribe_event_start.meta_value >= '%3\$s' AND  tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t\tOR (tribe_event_start.meta_value <= '%3\$s' AND tribe_event_end_date.meta_value >= '%3\$s')\n\t\t\t\t\t\t\t\tOR ( tribe_event_start.meta_value >= '%3\$s' AND  tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tORDER BY menu_order ASC, DATE(tribe_event_start.meta_value) ASC, TIME(tribe_event_start.meta_value) ASC;", $output_date_format, $output_date_format, $post_id_query->query_vars['start_date'], $post_id_query->query_vars['end_date'], implode(',', array_map('intval', $post_ids))));
                 $start_date = new DateTime($post_id_query->query_vars['start_date']);
                 $end_date = new DateTime($post_id_query->query_vars['end_date']);
                 $days = Tribe__Date_Utils::date_diff($start_date->format('Y-m-d'), $end_date->format('Y-m-d'));
                 $term_id = isset($wp_query->query_vars[Tribe__Events__Main::TAXONOMY]) ? $wp_query->query_vars[Tribe__Events__Main::TAXONOMY] : null;
                 $terms = array();
                 if (is_int($term_id)) {
                     $terms[0] = $term_id;
                 } elseif (is_string($term_id)) {
                     $term = get_term_by('slug', $term_id, Tribe__Events__Main::TAXONOMY);
                     if ($term) {
                         $terms[0] = $term->term_id;
                     }
                 }
                 if (!empty($terms) && is_tax(Tribe__Events__Main::TAXONOMY)) {
                     $terms = array_merge($terms, get_term_children($terms[0], Tribe__Events__Main::TAXONOMY));
                 }
                 for ($i = 0, $date = $start_date; $i <= $days; $i++, $date->modify('+1 day')) {
                     $formatted_date = $date->format('Y-m-d');
                     $count = 0;
                     $_day_event_ids = array();
                     foreach ($raw_counts as $record) {
                         $event = new stdClass();
                         $event->EventStartDate = $record->EventStartDate;
                         $event->EventEndDate = $record->EventEndDate;
                         $per_day_limit = apply_filters('tribe_events_month_day_limit', tribe_get_option('monthEventAmount', '3'));
                         if (tribe_event_is_on_date($formatted_date, $event)) {
                             if (!empty($terms) && !has_term($terms, Tribe__Events__Main::TAXONOMY, $record->ID)) {
                                 continue;
                             }
                             if (count($_day_event_ids) < $per_day_limit) {
                                 $_day_event_ids[] = $record->ID;
                             }
                             $count++;
                         }
                     }
                     $event_ids[$formatted_date] = $_day_event_ids;
                     $counts[$formatted_date] = $count;
                 }
                 break;
         }
         // get a unique list of the event IDs that will be displayed, and update all their postmeta and term caches at once
         $final_event_ids = call_user_func_array('array_merge', $event_ids);
         $final_event_ids = array_unique($final_event_ids);
         update_object_term_cache($final_event_ids, Tribe__Events__Main::POSTTYPE);
         update_postmeta_cache($final_event_ids);
     }
     // return IDs per day and total counts per day
     $return = array('counts' => $counts, 'event_ids' => $event_ids);
     $cache = new Tribe__Cache();
     $cache_key = 'daily_counts_and_ids_' . serialize($args);
     $cache->set($cache_key, $return, Tribe__Cache::NON_PERSISTENT, 'save_post');
     return $return;
 }
	/**
	 * @group cache
	 */
	public function test_taxonomy_classes_hit_cache() {
		global $wpdb;

		if ( is_multisite() ) {
			$this->markTestSkipped( 'Not testable in MS: wpmu_create_blog() defines WP_INSTALLING, which causes cache misses.' );
		}

		register_taxonomy( 'wptests_tax', 'post' );
		wp_set_post_terms( $this->post_id, array( 'foo', 'bar' ), 'wptests_tax' );
		wp_set_post_terms( $this->post_id, array( 'footag', 'bartag' ), 'post_tag' );

		// Prime cache, including meta cache, which is used by get_post_class().
		update_object_term_cache( $this->post_id, 'post' );
		update_meta_cache( 'post', $this->post_id );

		$num_queries = $wpdb->num_queries;

		$found = get_post_class( '', $this->post_id );

		$this->assertSame( $num_queries, $wpdb->num_queries );
	}
Пример #14
0
 /**
  * @group cache
  */
 public function test_taxonomy_classes_hit_cache()
 {
     global $wpdb;
     register_taxonomy('wptests_tax', 'post');
     wp_set_post_terms($this->post_id, array('foo', 'bar'), 'wptests_tax');
     wp_set_post_terms($this->post_id, array('footag', 'bartag'), 'post_tag');
     // Prime cache, including meta cache, which is used by get_post_class().
     update_object_term_cache($this->post_id, 'post');
     update_meta_cache('post', $this->post_id);
     $num_queries = $wpdb->num_queries;
     $found = get_post_class('', $this->post_id);
     // The 'site_icon' option check adds a query during unit tests. See {@see WP_Site_Icon::get_post_metadata()}.
     $expected_num_queries = $num_queries + 1;
     $this->assertSame($expected_num_queries, $wpdb->num_queries);
 }
Пример #15
0
	public function test_wp_update_term_should_clean_object_term_cache() {
		register_taxonomy( 'wptests_tax_for_post', 'post' );
		register_taxonomy( 'wptests_tax_for_page', 'page' );
		$post = $this->factory->post->create();
		$page = $this->factory->post->create( array(
			'post_type' => 'page',
		) );

		$t_for_post = $this->factory->term->create( array(
			'taxonomy' => 'wptests_tax_for_post',
		) );
		$t_for_page = $this->factory->term->create( array(
			'taxonomy' => 'wptests_tax_for_page',
		) );

		wp_set_post_terms( $post, array( $t_for_post ), 'wptests_tax_for_post' );
		wp_set_post_terms( $page, array( $t_for_page ), 'wptests_tax_for_page' );

		// Prime caches and verify.
		update_object_term_cache( array( $post ), 'post' );
		update_object_term_cache( array( $page ), 'page' );
		$this->assertNotEmpty( wp_cache_get( $post, 'wptests_tax_for_post_relationships' ) );
		$this->assertNotEmpty( wp_cache_get( $page, 'wptests_tax_for_page_relationships' ) );

		// Update a term in just one of the taxonomies.
		$found = wp_update_term( $t_for_post, 'wptests_tax_for_post', array(
			'slug' => 'foo',
		) );

		// Only the relevant cache should have been cleared.
		$this->assertFalse( wp_cache_get( $post, 'wptests_tax_for_post_relationships' ) );
		$this->assertNotEmpty( wp_cache_get( $page, 'wptests_tax_for_page_relationships' ) );
	}
Пример #16
0
 /**
  * @ticket 35180
  * @ticket 28922
  */
 public function test_get_the_terms_should_return_results_ordered_by_name_when_pulling_from_cache()
 {
     register_taxonomy('wptests_tax', 'post');
     $p = self::$post_ids[0];
     $t1 = self::factory()->term->create(array('taxonomy' => 'wptests_tax', 'name' => 'fff'));
     $t2 = self::factory()->term->create(array('taxonomy' => 'wptests_tax', 'name' => 'aaa'));
     $t3 = self::factory()->term->create(array('taxonomy' => 'wptests_tax', 'name' => 'zzz'));
     wp_set_object_terms($p, array($t1, $t2, $t3), 'wptests_tax');
     update_object_term_cache($p, 'post');
     $found = get_the_terms($p, 'wptests_tax');
     $this->assertSame(array($t2, $t1, $t3), wp_list_pluck($found, 'term_id'));
 }
Пример #17
0
/**
 * Call major cache updating functions for list of Post objects.
 *
 * @package WordPress
 * @subpackage Cache
 * @since 1.5.0
 *
 * @uses $wpdb
 * @uses update_post_cache()
 * @uses update_object_term_cache()
 * @uses update_postmeta_cache()
 *
 * @param array $posts Array of Post objects
 * @param string $post_type The post type of the posts in $posts. Default is 'post'.
 * @param bool $update_term_cache Whether to update the term cache. Default is true.
 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
 */
function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true)
{
    // No point in doing all this work if we didn't match any posts.
    if (!$posts) {
        return;
    }
    update_post_cache($posts);
    $post_ids = array();
    foreach ($posts as $post) {
        $post_ids[] = $post->ID;
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if (!is_array($post_type) && 'any' != $post_type && $update_term_cache) {
        update_object_term_cache($post_ids, $post_type);
    }
    if ($update_meta_cache) {
        update_postmeta_cache($post_ids);
    }
}
 /**
  * Get all the events in the month by directly querying the postmeta table
  * Also caches the postmeta and terms for the found events
  */
 protected function set_events_in_month()
 {
     global $wpdb;
     $grid_start_datetime = tribe_beginning_of_day($this->first_grid_date);
     $grid_end_datetime = tribe_end_of_day($this->final_grid_date);
     $cache = new Tribe__Cache();
     $cache_key = 'events_in_month' . $grid_start_datetime . '-' . $grid_end_datetime;
     // if we have a cached result, use that
     $cached_events = $cache->get($cache_key, 'save_post');
     if ($cached_events !== false) {
         $this->events_in_month = $cached_events;
         return;
     }
     $post_stati = array('publish');
     if (is_user_logged_in()) {
         $post_stati[] = 'private';
     }
     $post_stati = implode("','", $post_stati);
     $ignore_hidden_events_AND = $this->hidden_events_fragment();
     $events_request = $wpdb->prepare("SELECT tribe_event_start.post_id as ID,\n\t\t\t\t\t\ttribe_event_start.meta_value as EventStartDate,\n\t\t\t\t\t\ttribe_event_end_date.meta_value as EventEndDate\n\t\t\t\tFROM {$wpdb->postmeta} AS tribe_event_start\n\t\t\t\tLEFT JOIN {$wpdb->posts} ON tribe_event_start.post_id = {$wpdb->posts}.ID\n\t\t\t\tLEFT JOIN {$wpdb->postmeta} as tribe_event_end_date ON ( tribe_event_start.post_id = tribe_event_end_date.post_id AND tribe_event_end_date.meta_key = '_EventEndDate' )\n\t\t\t\tWHERE {$ignore_hidden_events_AND} tribe_event_start.meta_key = '_EventStartDate'\n\t\t\t\tAND ( (tribe_event_start.meta_value >= '%1\$s' AND  tribe_event_start.meta_value <= '%2\$s')\n\t\t\t\t\tOR (tribe_event_start.meta_value <= '%1\$s' AND tribe_event_end_date.meta_value >= '%1\$s')\n\t\t\t\t\tOR ( tribe_event_start.meta_value >= '%1\$s' AND  tribe_event_start.meta_value <= '%2\$s')\n\t\t\t\t)\n\t\t\t\tAND {$wpdb->posts}.post_status IN('{$post_stati}')\n\t\t\t\tORDER BY {$wpdb->posts}.menu_order ASC, DATE(tribe_event_start.meta_value) ASC, TIME(tribe_event_start.meta_value) ASC;\n\t\t\t\t", $grid_start_datetime, $grid_end_datetime);
     $this->events_in_month = $wpdb->get_results($events_request);
     // cache the postmeta and terms for all these posts in one go
     $event_ids_in_month = wp_list_pluck($this->events_in_month, 'ID');
     update_object_term_cache($event_ids_in_month, Tribe__Events__Main::POSTTYPE);
     update_postmeta_cache($event_ids_in_month);
     // cache the found events in the object cache
     $cache->set($cache_key, $this->events_in_month, 0, 'save_post');
 }
Пример #19
0
 /**
  * copy or synchronize terms
  *
  * @since 1.8
  *
  * @param int    $from id of the post from which we copy informations
  * @param int    $to   id of the post to which we paste informations
  * @param string $lang language slug
  * @param bool $sync true if it is synchronization, false if it is a copy, defaults to false
  */
 public function copy_taxonomies($from, $to, $lang, $sync = false)
 {
     // get taxonomies to sync for this post type
     $taxonomies = array_intersect(get_post_taxonomies($from), $this->get_taxonomies_to_copy($sync));
     // update the term cache to reduce the number of queries in the loop
     update_object_term_cache($sync ? array($from, $to) : $from, get_post_type($from));
     // copy or synchronize terms
     // FIXME quite a lot of query in foreach
     foreach ($taxonomies as $tax) {
         $terms = get_the_terms($from, $tax);
         // translated taxonomy
         if ($this->model->is_translated_taxonomy($tax)) {
             $newterms = array();
             if (is_array($terms)) {
                 foreach ($terms as $term) {
                     if ($term_id = $this->model->term->get_translation($term->term_id, $lang)) {
                         $newterms[] = (int) $term_id;
                         // cast is important otherwise we get 'numeric' tags
                     }
                 }
             }
             // for some reasons, the user may have untranslated terms in the translation. don't forget them.
             if ($sync) {
                 $tr_terms = get_the_terms($to, $tax);
                 if (is_array($tr_terms)) {
                     foreach ($tr_terms as $term) {
                         if (!$this->model->term->get_translation($term->term_id, $this->model->post->get_language($from))) {
                             $newterms[] = (int) $term->term_id;
                         }
                     }
                 }
             }
             if (!empty($newterms) || $sync) {
                 wp_set_object_terms($to, $newterms, $tax);
                 // replace terms in translation
             }
         } else {
             wp_set_object_terms($to, is_array($terms) ? array_map('intval', wp_list_pluck($terms, 'term_id')) : null, $tax);
         }
     }
 }
Пример #20
0
/**
 * Call major cache updating functions for list of Post objects.
 *
 * @package WordPress
 * @subpackage Cache
 * @since 1.5.0
 *
 * @uses $wpdb
 * @uses update_post_cache()
 * @uses update_object_term_cache()
 * @uses update_postmeta_cache()
 *
 * @param array $posts Array of Post objects
 * @param string $post_type The post type of the posts in $posts. Default is 'post'.
 * @param bool $update_term_cache Whether to update the term cache. Default is true.
 * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
 */
function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true)
{
    // No point in doing all this work if we didn't match any posts.
    if (!$posts) {
        return;
    }
    update_post_cache($posts);
    $post_ids = array();
    foreach ($posts as $post) {
        $post_ids[] = $post->ID;
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if ($update_term_cache) {
        if (is_array($post_type)) {
            $ptypes = $post_type;
        } elseif ('any' == $post_type) {
            // Just use the post_types in the supplied posts.
            foreach ($posts as $post) {
                $ptypes[] = $post->post_type;
            }
            $ptypes = array_unique($ptypes);
        } else {
            $ptypes = array($post_type);
        }
        if (!empty($ptypes)) {
            update_object_term_cache($post_ids, $ptypes);
        }
    }
    if ($update_meta_cache) {
        update_postmeta_cache($post_ids);
    }
}
Пример #21
0
 /**
  * Get the cart data from the PHP session and store it in class variables.
  */
 public function get_cart_from_session()
 {
     // Load cart session data from session
     foreach ($this->cart_session_data as $key => $default) {
         $this->{$key} = WC()->session->get($key, $default);
     }
     $update_cart_session = false;
     $this->removed_cart_contents = array_filter(WC()->session->get('removed_cart_contents', array()));
     $this->applied_coupons = array_filter(WC()->session->get('applied_coupons', array()));
     /**
      * Load the cart object. This defaults to the persistent cart if null.
      */
     $cart = WC()->session->get('cart', null);
     if (is_null($cart) && ($saved_cart = get_user_meta(get_current_user_id(), '_woocommerce_persistent_cart', true))) {
         $cart = $saved_cart['cart'];
         $update_cart_session = true;
     } elseif (is_null($cart)) {
         $cart = array();
     }
     if (is_array($cart)) {
         // Prime meta cache to reduce future queries
         update_meta_cache('post', wp_list_pluck($cart, 'product_id'));
         update_object_term_cache(wp_list_pluck($cart, 'product_id'), 'product');
         foreach ($cart as $key => $values) {
             $product = wc_get_product($values['variation_id'] ? $values['variation_id'] : $values['product_id']);
             if (!empty($product) && $product->exists() && $values['quantity'] > 0) {
                 if (!$product->is_purchasable()) {
                     // Flag to indicate the stored cart should be update
                     $update_cart_session = true;
                     /* translators: %s: product name */
                     wc_add_notice(sprintf(__('%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce'), $product->get_name()), 'error');
                     do_action('woocommerce_remove_cart_item_from_session', $key, $values);
                 } else {
                     // Put session data into array. Run through filter so other plugins can load their own session data
                     $session_data = array_merge($values, array('data' => $product));
                     $this->cart_contents[$key] = apply_filters('woocommerce_get_cart_item_from_session', $session_data, $values, $key);
                 }
             }
         }
     }
     // Trigger action
     do_action('woocommerce_cart_loaded_from_session', $this);
     if ($update_cart_session) {
         WC()->session->cart = $this->get_cart_for_session();
     }
     // Queue re-calc if subtotal is not set
     if (!$this->subtotal && !$this->is_empty() || $update_cart_session) {
         $this->calculate_totals();
     }
 }