示例#1
0
 /**
  * Generate some terms.
  *
  * ## OPTIONS
  *
  * <taxonomy>
  * : The taxonomy for the generated terms.
  *
  * [--count=<number>]
  * : How many terms to generate. Default: 100
  *
  * [--max_depth=<number>]
  * : Generate child terms down to a certain depth. Default: 1
  *
  * ## EXAMPLES
  *
  *     wp term-gen create category --count=50 --max_depth=6
  */
 public function create($args, $assoc_args)
 {
     global $wpdb;
     list($taxonomy) = $args;
     $defaults = array('count' => 100, 'max_depth' => 1);
     extract(array_merge($defaults, $assoc_args), EXTR_SKIP);
     $notify = \WP_CLI\Utils\make_progress_bar('Generating terms', $count);
     if (!taxonomy_exists($taxonomy)) {
         WP_CLI::error(sprintf("'%s' is not a registered taxonomy.", $taxonomy));
     }
     $label = get_taxonomy($taxonomy)->labels->singular_name;
     $slug = sanitize_title_with_dashes($label);
     $hierarchical = get_taxonomy($taxonomy)->hierarchical;
     $previous_term_id = 0;
     $current_parent = 0;
     $current_depth = 1;
     $max_id = (int) $wpdb->get_var("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} ORDER BY term_taxonomy_id DESC LIMIT 1");
     $suspend_cache_invalidation = wp_suspend_cache_invalidation(true);
     $created = array();
     $names = array();
     $this->text = file_get_contents(plugin_dir_path(__FILE__) . '/lorem-terms.txt');
     for ($i = $max_id + 1; $i <= $max_id + $count; $i++) {
         if ($hierarchical) {
             if ($previous_term_id && $this->maybe_make_child() && $current_depth < $max_depth) {
                 $current_parent = $previous_term_id;
                 $current_depth++;
             } else {
                 if ($this->maybe_reset_depth()) {
                     $current_parent = 0;
                     $current_depth = 1;
                 }
             }
         }
         $name = $this->get_random_term_name();
         $name = $this->get_unique_term_name($name, $taxonomy, $names);
         $args = array('parent' => $current_parent, 'slug' => sanitize_title($name));
         $term = wp_insert_term($name, $taxonomy, $args);
         if (is_wp_error($term)) {
             WP_CLI::warning($term);
         } else {
             $created[] = $term['term_id'];
             $previous_term_id = $term['term_id'];
             $names[] = $name;
         }
         $notify->tick();
         if (0 == $i % 200) {
             sleep(3);
         }
     }
     wp_suspend_cache_invalidation($suspend_cache_invalidation);
     clean_term_cache($created, $taxonomy);
     $notify->finish();
     if (count($created)) {
         WP_CLI::success(sprintf("%s terms created.", count($created)));
     } else {
         WP_CLI::warning("No terms created,");
     }
 }
 public function test_term_flushing_cache()
 {
     $post_id = $this->factory->post->create();
     $term_id = $this->factory->term->create(['banana', 'post_tag']);
     wp_set_post_terms($post_id, 'banana');
     $first_run = $this->query->query([]);
     $this->assertSame($this->obj->all_post_ids, false);
     clean_term_cache($term_id);
     $second_run = $this->query->query([]);
     $this->assertSame($this->obj->all_post_ids, false);
 }
 public static function wpSetUpBeforeClass($factory)
 {
     global $wpdb;
     register_taxonomy('wptests_tax', 'post');
     // Ensure that there is a term with ID 1.
     if (!get_term(1)) {
         $wpdb->insert($wpdb->terms, array('term_id' => 1));
         $wpdb->insert($wpdb->term_taxonomy, array('term_id' => 1, 'taxonomy' => 'wptests_tax'));
         clean_term_cache(1, 'wptests_tax');
     }
     self::$term_id = self::factory()->term->create(array('taxonomy' => 'wptests_tax'));
 }
示例#4
0
 public function test_cache_should_be_populated_by_successful_fetch()
 {
     global $wpdb;
     $t = self::factory()->term->create(array('taxonomy' => 'wptests_tax'));
     clean_term_cache($t, 'wptests_tax');
     // Prime cache.
     $term_a = get_term($t, 'wptests_tax');
     $num_queries = $wpdb->num_queries;
     // Second call shouldn't require a database query.
     $term_b = get_term($t, 'wptests_tax');
     $this->assertSame($num_queries, $wpdb->num_queries);
     $this->assertEquals($term_a, $term_b);
 }
 /**
  * @ticket 14162
  */
 public function test_should_prime_term_cache()
 {
     global $wpdb;
     register_taxonomy('wptests_tax', 'post');
     $t = self::factory()->term->create(array('taxonomy' => 'wptests_tax', 'slug' => 'foo'));
     clean_term_cache($t, 'wptests_tax');
     $num_queries = $wpdb->num_queries;
     $found = get_term_by('slug', 'foo', 'wptests_tax');
     $num_queries++;
     $this->assertTrue($found instanceof WP_Term);
     $this->assertSame($t, $found->term_id);
     $this->assertSame($num_queries, $wpdb->num_queries);
     // Calls to `get_term()` should now hit cache.
     $found2 = get_term($t);
     $this->assertSame($t, $found->term_id);
     $this->assertSame($num_queries, $wpdb->num_queries);
 }
示例#6
0
/**
 * Add new variation set via AJAX.
 *
 * If the variation set name is the same as an existing variation set,
 * the children variant terms will be added inside that existing set.
 * @since 3.8.8
 */
function wpsc_add_variation_set()
{
    $new_variation_set = $_POST['variation_set'];
    $variants = preg_split('/\\s*,\\s*/', $_POST['variants']);
    $parent_term_exists = term_exists($new_variation_set, 'wpsc-variation');
    // only use an existing parent ID if the term is not a child term
    if ($parent_term_exists) {
        $parent_term = get_term($parent_term_exists['term_id'], 'wpsc-variation');
        if ($parent_term->parent == '0') {
            $variation_set_id = $parent_term_exists['term_id'];
        }
    }
    if (empty($variation_set_id)) {
        $results = wp_insert_term($new_variation_set, 'wpsc-variation');
        if (is_wp_error($results)) {
            die('-1');
        }
        $variation_set_id = $results['term_id'];
    }
    $inserted_variants = array();
    if (!empty($variation_set_id)) {
        foreach ($variants as $variant) {
            $results = wp_insert_term($variant, 'wpsc-variation', array('parent' => $variation_set_id));
            if (is_wp_error($results)) {
                die('-1');
            }
            $inserted_variants[] = $results['term_id'];
        }
        require_once 'includes/walker-variation-checklist.php';
        /* --- DIRTY HACK START --- */
        /*
        There's a bug with term cache in WordPress core. See http://core.trac.wordpress.org/ticket/14485.
        The next 3 lines will delete children term cache for wpsc-variation.
        Without this hack, the new child variations won't be displayed on "Variations" page and
        also won't be displayed in wp_terms_checklist() call below.
        */
        clean_term_cache($variation_set_id, 'wpsc-variation');
        delete_option('wpsc-variation_children');
        wp_cache_set('last_changed', 1, 'terms');
        _get_term_hierarchy('wpsc-variation');
        /* --- DIRTY HACK END --- */
        wp_terms_checklist((int) $_POST['post_id'], array('taxonomy' => 'wpsc-variation', 'descendants_and_self' => $variation_set_id, 'walker' => new WPSC_Walker_Variation_Checklist($inserted_variants), 'checked_ontop' => false));
    }
    exit;
}
示例#7
0
 public function testTaxonomyAll()
 {
     include_once 'samples/Team.php';
     include_once 'samples/Person.php';
     $faker = FakerFactory::create();
     $samples = 5;
     $termIds = [];
     register_taxonomy(Team::getTaxonomy(), Team::getPostTypes());
     for ($i = 0; $i < $samples; $i++) {
         $t = self::factory()->term->create(['taxonomy' => Team::getTaxonomy()]);
         clean_term_cache($t, Team::getTaxonomy());
         //$termIds[] = wp_insert_term( $faker->word, Team::getTaxonomy() );
     }
     $teams = Team::all();
     $this->assertCount($samples, $teams);
     foreach ($teams as $term) {
         $this->assertInstanceOf(Team::class, $term);
     }
 }
示例#8
0
 /**
  * Handle storyline sorting.
  * 
  * @hook admin_init
  * @uses WebcomicAdmin::notify()
  */
 public function admin_init()
 {
     global $wpdb;
     if (isset($_POST['webcomic_action']) and 'term_sort' === $_POST['webcomic_action'] and wp_verify_nonce($_POST['webcomic_term_sort'], 'webcomic_term_sort')) {
         if (isset($_POST['webcomic_cancel_sort'])) {
             wp_redirect(add_query_arg(array('taxonomy' => $_POST['webcomic_taxonomy'], 'post_type' => $_POST['webcomic_collection']), admin_url('edit-tags.php')));
             die;
         } else {
             $terms = $count = array();
             parse_str($_POST['webcomic_terms'], $terms);
             foreach ($terms['term'] as $k => $v) {
                 $count[$v] = empty($count[$v]) ? 1 : $count[$v] + 1;
                 $wpdb->update($wpdb->terms, array('term_group' => $count[$v]), array('term_id' => $k));
                 $wpdb->update($wpdb->term_taxonomy, array('parent' => 'null' === $v ? 0 : $v), array('term_id' => $k, 'taxonomy' => $_POST['webcomic_taxonomy']));
             }
             clean_term_cache(array_keys($terms['term']), $_POST['webcomic_taxonomy']);
             WebcomicAdmin::notify('<b>' . __('Order updated.', 'webcomic') . '</b>');
         }
     }
 }
/**
 * Set the sort order of a term.
 *
 * @param int $term_id
 * @param int $index
 * @param string $taxonomy
 * @param bool $recursive (default: false)
 * @return int
 */
function wc_set_term_order($term_id, $index, $taxonomy, $recursive = false)
{
    $term_id = (int) $term_id;
    $index = (int) $index;
    // Meta name
    if (taxonomy_is_product_attribute($taxonomy)) {
        $meta_name = 'order_' . esc_attr($taxonomy);
    } else {
        $meta_name = 'order';
    }
    update_woocommerce_term_meta($term_id, $meta_name, $index);
    if (!$recursive) {
        return $index;
    }
    $children = get_terms($taxonomy, "parent={$term_id}&menu_order=ASC&hide_empty=0");
    foreach ($children as $term) {
        $index++;
        $index = wc_set_term_order($term->term_id, $index, $taxonomy, true);
    }
    clean_term_cache($term_id, $taxonomy);
    return $index;
}
 /**
  * @param int|array $terms_ids
  * @param $taxonomy
  */
 public function update_terms_relationship_cache($terms_ids, $taxonomy)
 {
     remove_filter('get_terms_args', array($this, 'get_terms_args_filter'));
     remove_filter('terms_clauses', array($this, 'terms_clauses'), 10);
     remove_filter('list_terms_exclusions', array($this, 'exclude_other_terms'), 1);
     clean_term_cache($terms_ids, $taxonomy);
     add_filter('get_terms_args', array($this, 'get_terms_args_filter'));
     // filters terms by language
     add_filter('terms_clauses', array($this, 'terms_clauses'), 10, 4);
     add_filter('list_terms_exclusions', array($this, 'exclude_other_terms'), 1, 2);
 }
function wp_update_term_count( $terms, $taxonomy ) {
	global $wpdb;

	if ( empty($terms) )
		return false;

	if ( !is_array($terms) )
		$terms = array($terms);

	$terms = array_map('intval', $terms);

	$taxonomy = get_taxonomy($taxonomy);
	if ( !empty($taxonomy->update_count_callback) ) {
		call_user_func($taxonomy->update_count_callback, $terms);
	} else {
		// Default count updater
		foreach ($terms as $term) {
			$count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = '$term'");
			$wpdb->query("UPDATE $wpdb->term_taxonomy SET count = '$count' WHERE term_taxonomy_id = '$term'");
		}

	}

	clean_term_cache($terms);

	return true;
}
 /**
  * Save new term order in database.
  *
  * @param  string   $taxonomy      Taxonomy name.
  * @param  object   $term          Term object.
  * @param  int      $custom_order  Taxonomy name.
  * @param  int|bool $new_parent_id ID of new parent element.
  * @return int|bool
  */
 private function reorder_term($taxonomy, $term, $custom_order, $new_parent_id = false)
 {
     global $wpdb;
     // new data
     $data = array('custom_order' => $custom_order);
     // update parent ID
     if ($new_parent_id !== false && $term->parent != $new_parent_id) {
         $data['parent'] = $new_parent_id;
     }
     $ret = $wpdb->update($wpdb->term_taxonomy, $data, array('term_taxonomy_id' => $term->term_taxonomy_id));
     clean_term_cache($term->term_id, $taxonomy);
     return $ret;
 }
示例#13
0
/**
 * Perform term count update immediately.
 *
 * @since 2.5.0
 *
 * @param array $terms The term_taxonomy_id of terms to update.
 * @param string $taxonomy The context of the term.
 * @return bool Always true when complete.
 */
function wp_update_term_count_now( $terms, $taxonomy ) {
	global $wpdb;

	$terms = array_map('intval', $terms);

	$taxonomy = get_taxonomy($taxonomy);
	if ( !empty($taxonomy->update_count_callback) ) {
		call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
	} else {
		$object_types = (array) $taxonomy->object_type;
		foreach ( $object_types as &$object_type ) {
			if ( 0 === strpos( $object_type, 'attachment:' ) )
				list( $object_type ) = explode( ':', $object_type );
		}

		if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
			// Only post types are attached to this taxonomy
			_update_post_term_count( $terms, $taxonomy );
		} else {
			// Default count updater
			_update_generic_term_count( $terms, $taxonomy );
		}
	}

	clean_term_cache($terms, '', false);

	return true;
}
/**
 * Set the sort order of a term
 *
 * @param int $term_id
 * @param int $index
 * @param string $taxonomy
 * @param bool $recursive (default: false)
 * @return int
 */
function documentate_set_term_order($term_id, $index, $taxonomy, $recursive = false)
{
    $term_id = (int) $term_id;
    $index = (int) $index;
    update_term_meta($term_id, 'order', $index);
    if (!$recursive) {
        return $index;
    }
    $children = get_terms($taxonomy, "parent={$term_id}&menu_order=ASC&hide_empty=0");
    foreach ($children as $term) {
        $index++;
        $index = documentate_set_term_order($term->term_id, $index, $taxonomy, true);
    }
    clean_term_cache($term_id, $taxonomy);
    return $index;
}
 public function portfolio_set_term_order($term_id, $index, $taxonomy, $recursive = false)
 {
     $term_id = (int) $term_id;
     $index = (int) $index;
     $meta_name = 'order';
     $this->update_a3_portfolio_category_meta($term_id, $meta_name, $index);
     if (!$recursive) {
         return $index;
     }
     $children = get_terms($taxonomy, "parent={$term_id}&menu_order=ASC&hide_empty=0");
     foreach ($children as $term) {
         $index++;
         $index = $this->portfolio_set_term_order($term->term_id, $index, $taxonomy, true);
     }
     clean_term_cache($term_id, $taxonomy);
     return $index;
 }
示例#16
0
/**
 * Add new variation set via AJAX.
 *
 * If the variation set name is the same as an existing variation set,
 * the children variant terms will be added inside that existing set.
 *
 * @since 3.8.8
 * @access private
 *
 * @uses term_exists()                      Returns true if term exists
 * @uses get_term()                         Gets all term data by term_id
 * @uses wp_insert_term()                   Inserts a term to the WordPress database
 * @uses is_wp_error()                      Checks whether variable is a WordPress error
 * @uses WP_Error                           WordPress Error class
 * @uses clean_term_cache()                 Will remove all of the term ids from the cache.
 * @uses delete_option()                    Deletes option from the database
 * @uses wp_cache_set()                     Saves the data to the cache.
 * @uses _get_term_hierarchy()              Retrieves children of taxonomy as Term IDs.
 * @uses wp_terms_checklist()               Output an unordered list of checkbox <input> elements labelled
 * @uses WPSC_Walker_Variation_Checklist    Walker variation checklist
 *
 * @return array Response args
 */
function _wpsc_ajax_add_variation_set()
{
    $new_variation_set = $_POST['variation_set'];
    $variants = preg_split('/\\s*,\\s*/', $_POST['variants']);
    $return = array();
    $parent_term_exists = term_exists($new_variation_set, 'wpsc-variation');
    // only use an existing parent ID if the term is not a child term
    if ($parent_term_exists) {
        $parent_term = get_term($parent_term_exists['term_id'], 'wpsc-variation');
        if ($parent_term->parent == '0') {
            $variation_set_id = $parent_term_exists['term_id'];
        }
    }
    if (empty($variation_set_id)) {
        $results = wp_insert_term(apply_filters('wpsc_new_variation_set', $new_variation_set), 'wpsc-variation');
        if (is_wp_error($results)) {
            return $results;
        }
        $variation_set_id = $results['term_id'];
    }
    if (empty($variation_set_id)) {
        return new WP_Error('wpsc_invalid_variation_id', __('Cannot retrieve the variation set in order to proceed.', 'wpsc'));
    }
    foreach ($variants as $variant) {
        $results = wp_insert_term(apply_filters('wpsc_new_variant', $variant, $variation_set_id), 'wpsc-variation', array('parent' => $variation_set_id));
        if (is_wp_error($results)) {
            return $results;
        }
        $inserted_variants[] = $results['term_id'];
    }
    require_once 'includes/walker-variation-checklist.php';
    if (!version_compare($GLOBALS['wp_version'], '3.8.3', '>')) {
        /* --- DIRTY HACK START --- */
        /*
        There's a bug with term cache in WordPress core. See http://core.trac.wordpress.org/ticket/14485. Fixed in 3.9.
        The next 3 lines will delete children term cache for wpsc-variation.
        Without this hack, the new child variations won't be displayed on "Variations" page and
        also won't be displayed in wp_terms_checklist() call below.
        */
        clean_term_cache($variation_set_id, 'wpsc-variation');
        delete_option('wpsc-variation_children');
        wp_cache_set('last_changed', 1, 'terms');
        _get_term_hierarchy('wpsc-variation');
        /* --- DIRTY HACK END --- */
    }
    ob_start();
    wp_terms_checklist((int) $_POST['post_id'], array('taxonomy' => 'wpsc-variation', 'descendants_and_self' => $variation_set_id, 'walker' => new WPSC_Walker_Variation_Checklist($inserted_variants), 'checked_ontop' => false));
    $content = ob_get_clean();
    $return = array('variation_set_id' => $variation_set_id, 'inserted_variants' => $inserted_variants, 'content' => $content);
    return $return;
}
 /**
  * Delete terms when counter if inferior to a specific number
  *
  * @param string $taxonomy 
  * @param integer $number 
  * @return boolean
  * @author Amaury Balmer
  */
 function removeRarelyUsed($taxonomy = 'post_tag', $number = 0)
 {
     global $wpdb;
     if ((int) $number > 100) {
         wp_die('Tcheater ?');
     }
     // Get terms with counter inferior to...
     $terms_id = $wpdb->get_col($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s AND count < %d", $taxonomy, $number));
     // Delete terms
     $counter = 0;
     foreach ((array) $terms_id as $term_id) {
         if ($term_id != 0) {
             wp_delete_term($term_id, $taxonomy);
             clean_term_cache($term_id, $taxonomy);
             $counter++;
         }
     }
     if ($counter == 0) {
         $this->message = __('No term deleted.', 'simpletags');
     } else {
         $this->message = sprintf(__('%1s term(s) deleted.', 'simpletags'), $counter);
     }
     return true;
 }
 static function handle_change_tax($term_ids, $taxonomy)
 {
     global $wpdb;
     $new_tax = $_POST['new_tax'];
     if (!taxonomy_exists($new_tax)) {
         return false;
     }
     if ($new_tax == $taxonomy) {
         return false;
     }
     $tt_ids = array();
     foreach ($term_ids as $term_id) {
         $term = get_term($term_id, $taxonomy);
         if ($term->parent && !in_array($term->parent, $term_ids)) {
             $wpdb->update($wpdb->term_taxonomy, array('parent' => 0), array('term_taxonomy_id' => $term->term_taxonomy_id));
         }
         $tt_ids[] = $term->term_taxonomy_id;
         if (is_taxonomy_hierarchical($taxonomy)) {
             $child_terms = get_terms($taxonomy, array('child_of' => $term_id, 'hide_empty' => false));
             $tt_ids = array_merge($tt_ids, wp_list_pluck($child_terms, 'term_taxonomy_id'));
         }
     }
     $tt_ids = implode(',', array_map('absint', $tt_ids));
     $wpdb->query($wpdb->prepare("\n\t\t\tUPDATE {$wpdb->term_taxonomy} SET taxonomy = %s WHERE term_taxonomy_id IN ({$tt_ids})\n\t\t", $new_tax));
     if (is_taxonomy_hierarchical($taxonomy) && !is_taxonomy_hierarchical($new_tax)) {
         $wpdb->query("UPDATE {$wpdb->term_taxonomy} SET parent = 0 WHERE term_taxonomy_id IN ({$tt_ids})");
     }
     clean_term_cache($tt_ids, $taxonomy);
     clean_term_cache($tt_ids, $new_tax);
     do_action('term_management_tools_term_changed_taxonomy', $tt_ids, $new_tax, $taxonomy);
     return true;
 }
 /**
  * Set `meta_key` of a specific term
  *
  * @since 0.1.0
  *
  * @param  int     $term_id
  * @param  string  $taxonomy
  * @param  string  $meta
  * @param  bool    $clean_cache
  */
 public function set_meta($term_id = 0, $taxonomy = '', $meta = '', $clean_cache = false)
 {
     // No meta_key, so delete
     if (empty($meta)) {
         delete_term_meta($term_id, $this->meta_key);
         // Update meta_key value
     } else {
         update_term_meta($term_id, $this->meta_key, $meta);
     }
     // Maybe clean the term cache
     if (true === $clean_cache) {
         clean_term_cache($term_id, $taxonomy);
     }
 }
function global_terms($term_id, $deprecated = '')
{
    global $wpdb;
    $term_id = intval($term_id);
    $c = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->terms} WHERE term_id = %d", $term_id));
    $global_id = $wpdb->get_var($wpdb->prepare("SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $c->slug));
    if ($global_id == null) {
        $wpdb->insert($wpdb->sitecategories, array('cat_name' => $c->name, 'category_nicename' => $c->slug));
        $global_id = $wpdb->insert_id;
    }
    if ($global_id == $term_id) {
        return $global_id;
    }
    if (get_option('default_category') == $term_id) {
        update_option('default_category', $global_id);
    }
    $wpdb->update($wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id));
    $wpdb->update($wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id));
    $wpdb->update($wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id));
    clean_term_cache($term_id);
    return $global_id;
}
 /**
  * When we update the terms at all, we should update the published post count for each author
  */
 function _update_users_posts_count($tt_ids, $taxonomy)
 {
     global $wpdb;
     $tt_ids = implode(', ', array_map('intval', $tt_ids));
     $term_ids = $wpdb->get_results("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id IN ({$tt_ids})");
     foreach ((array) $term_ids as $term_id_result) {
         $term = get_term_by('id', $term_id_result->term_id, $this->coauthor_taxonomy);
         $this->update_author_term_post_count($term);
     }
     $tt_ids = explode(', ', $tt_ids);
     clean_term_cache($tt_ids, '', false);
 }
示例#22
0
/**
 * Compares an array containing an old and new prominence term description and the appropriate slug and name to an array of current term descriptions. For each term whose current description matches the old description, the function updates the current description to the new description.
 *
 * This function contains commented-out logic that will allow you to from description to olddescription
 *
 * @param array $update The new details for the prominence tax term to be updated
 * @param array $term_descriptions Array of prominence terms, each prominence term as an associative array with keys: name, description, olddescription, slug
 * @uses var_log
 * @uses wp_update_term
 * @uses clean_term_cache
 *
 */
function largo_update_prominence_term_description_single($update, $term_descriptions)
{
    $logarray = array();
    // Toggle comment on these two lines to revert to old descriptions.
    if (in_array($update['olddescription'], $term_descriptions)) {
        #		if (in_array($update['description'], $term_descriptions)) {
        $id = get_term_by('slug', $update['slug'], 'prominence', 'ARRAY_A');
        // Comment out this function to avoid all prominence term updates.
        #		    /*
        wp_update_term($id['term_id'], 'prominence', array('name' => $update['name'], 'description' => $update['description'], 'slug' => $update['slug']));
        #		    */
        $logarray[] = 'Updated description of "' . $update['name'] . '" from "' . $update['olddescription'] . '" to "' . $update['description'] . '"';
        // Clean the entire prominence term cache
        clean_term_cache($id['term_id'], 'prominence', true);
    }
    // These are here so you can grep your server logs to see if the terms were updated.
    #	var_log($logarray);
    #	var_log("Done updating prominence terms");
    return $update;
}
示例#23
0
/**
 * Remove the category cache data based on ID.
 *
 * @since 2.1.0
 * @uses clean_term_cache() Clears the cache for the category based on ID
 *
 * @param int $id Category ID
 */
function clean_category_cache($id)
{
    clean_term_cache($id, 'category');
}
function cpm_action_build_storyline_schema()
{
    global $cpm_config;
    update_option('comicpress-enable-storyline-support', isset($_POST['enable-storyline-support']) ? 1 : 0);
    update_option('comicpress-storyline-show-top-category', isset($_POST['show-top-category']) ? 1 : 0);
    if (isset($_POST['enable-storyline-support'])) {
        $cpm_config->is_cpm_modifying_categories = true;
        $categories_to_create = array();
        $categories_to_rename = array();
        $category_ids_to_clean = array();
        extract(cpm_get_all_comic_categories());
        $comic_posts = cpm_query_posts();
        $comic_posts_by_category_id = array();
        foreach ($comic_posts as $post) {
            foreach (wp_get_post_categories($post->ID) as $category) {
                if (!isset($comic_posts_by_category_id[$category])) {
                    $comic_posts_by_category_id[$category] = array();
                }
                $comic_posts_by_category_id[$category][] = $post->ID;
            }
        }
        foreach ($_POST as $field => $value) {
            $value = stripslashes($value);
            $parts = explode("/", $field);
            if ($parts[0] == "0" && count($parts) > 1) {
                $category_id = end($parts);
                $category = get_category($category_id);
                if (!empty($category)) {
                    $category = (array) $category;
                    if ($category['cat_name'] != $value) {
                        $cpm_config->messages[] = sprintf(__('Category <strong>%1$s</strong> renamed to <strong>%2$s</strong>.', 'comicpress-manager'), $category['cat_name'], $value);
                        $category['cat_name'] = $value;
                        wp_update_category($category);
                        $category_ids_to_clean[] = $category_id;
                    }
                } else {
                    $categories_to_create[$field] = $value;
                }
                if (($index = array_search($field, $category_tree)) !== false) {
                    array_splice($category_tree, $index, 1);
                }
            }
        }
        if (isset($_POST['original-categories'])) {
            foreach (explode(",", $_POST['original-categories']) as $node) {
                if (!isset($_POST[$node])) {
                    $category_id = end(explode("/", $node));
                    $category = get_category($category_id);
                    $original_cat_name = $category->cat_name;
                    // ensure that we're not deleting a ComicPress category
                    $ok = true;
                    foreach (array('comiccat', 'blogcat') as $type) {
                        if ($category_id == $cpm_config->properties[$type]) {
                            $ok = false;
                        }
                    }
                    // ensure that the category truly is a child of the comic category
                    if ($ok) {
                        $category = get_category($category_id);
                        $ok = false;
                        if (!is_wp_error($category)) {
                            while ($category->parent != 0 && $category->parent != $cpm_config->properties['comiccat']) {
                                $category = get_category($category->parent);
                            }
                            if ($category->parent == $cpm_config->properties['comiccat']) {
                                $ok = true;
                            }
                        }
                    }
                    if ($ok) {
                        wp_delete_category($category_id);
                        $category_ids_to_clean[] = $category_id;
                        $cpm_config->messages[] = sprintf(__('Category <strong>%s</strong> deleted.', 'comicpress-manager'), $original_cat_name);
                    }
                }
            }
        }
        uksort($categories_to_create, 'cpm_sort_category_keys_by_length');
        $changed_field_ids = array();
        $removed_field_ids = array();
        $target_category_ids = array();
        foreach ($categories_to_create as $field => $value) {
            $original_field = $field;
            foreach ($changed_field_ids as $changed_field => $new_field) {
                if (strpos($field, $changed_field) === 0 && strlen($field) > strlen($changed_field)) {
                    $field = str_replace($changed_field, $new_field, $field);
                    break;
                }
            }
            $parts = explode("/", $field);
            $target_id = array_pop($parts);
            $parent_id = array_pop($parts);
            if (!category_exists($value)) {
                $category_id = wp_create_category($value, $parent_id);
                $category_ids_to_clean[] = $category_id;
                array_push($parts, $parent_id);
                array_push($parts, $category_id);
                $changed_field_ids[$original_field] = implode("/", $parts);
                $cpm_config->messages[] = sprintf(__('Category <strong>%s</strong> created.', 'comicpress-manager'), $value);
            } else {
                $cpm_config->warnings[] = sprintf(__("The category %s already exists. Please enter a new name.", 'comicpress-manager'), $value);
                $removed_field_ids[] = $field;
            }
        }
        $order = array_diff(explode(",", $_POST['order']), $removed_field_ids);
        for ($i = 0; $i < count($order); ++$i) {
            if (isset($changed_field_ids[$order[$i]])) {
                $order[$i] = $changed_field_ids[$order[$i]];
            }
        }
        // ensure we're writing sane data
        $new_order = array();
        $valid_comic_categories = array();
        foreach ($order as $node) {
            $parts = explode("/", $node);
            if ($parts[0] == "0" && count($parts) > 1) {
                $new_order[] = $node;
                $valid_comic_categories[] = end($parts);
            }
        }
        $comic_categories_preserved = array();
        foreach ($comic_posts as $post) {
            $categories = wp_get_post_categories($post->ID);
            if (count(array_intersect($valid_comic_categories, $categories)) == 0) {
                $all_parent_categories = array();
                foreach ($comic_posts_by_category_id as $category => $post_ids) {
                    if (in_array($post->ID, $post_ids)) {
                        foreach ($new_order as $node) {
                            $parts = explode("/", $node);
                            if ($category == end($parts)) {
                                $parts = explode("/", $node);
                                array_pop($parts);
                                if (count($parts) > 1) {
                                    $all_parent_categories[] = implode("/", $parts);
                                }
                            }
                        }
                    }
                }
                if (count($all_parent_categories) > 0) {
                    foreach ($all_parent_categories as $category_node) {
                        if (in_array($category_node, $new_order)) {
                            $categories[] = end(explode("/", $category_node));
                        }
                    }
                } else {
                    $categories[] = $cpm_config->properties['comiccat'];
                }
                wp_set_post_categories($post->ID, $categories);
                $comic_categories_preserved[] = $post->ID;
            }
        }
        if (count($comic_categories_preserved) > 0) {
            $cpm_config->messages[] = sprintf(__("The following orphaned comic posts were placed into their original category's parent: <strong>%s</strong>"), implode(", ", $comic_categories_preserved));
        }
        $cpm_config->messages[] = __('Storyline structure saved.', 'comicpress-manager');
        update_option("comicpress-storyline-category-order", implode(",", $new_order));
        clean_term_cache($category_ids_to_clean, 'category');
        wp_cache_flush();
    }
}
function wp_update_term_count_now( $terms, $taxonomy ) {
	global $wpdb;

	$terms = array_map('intval', $terms);

	$taxonomy = get_taxonomy($taxonomy);
	if ( !empty($taxonomy->update_count_callback) ) {
		call_user_func($taxonomy->update_count_callback, $terms);
	} else {
		// Default count updater
		foreach ($terms as $term) {
			$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
			$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
		}

	}

	clean_term_cache($terms);

	return true;
}
示例#26
0
 /**
  * Used to delete translations or update the translations when a language slug has been modified in settings
  *
  * @since 0.5
  *
  * @param string $old_slug the old language slug
  * @param string $new_slug optional, the new language slug, if not set it means the correspondant has been deleted
  */
 public function update_translations($old_slug, $new_slug = '')
 {
     global $wpdb;
     $terms = get_terms(array('post_translations', 'term_translations'));
     foreach ($terms as $term) {
         $tr = unserialize($term->description);
         if (!empty($tr[$old_slug])) {
             if ($new_slug) {
                 $tr[$new_slug] = $tr[$old_slug];
                 // Suppress this for delete
             } else {
                 $dr['id'][] = (int) $tr[$old_slug];
                 $dr['tt'][] = (int) $term->term_taxonomy_id;
             }
             unset($tr[$old_slug]);
             if (empty($tr) || 1 == count($tr)) {
                 $dt['t'][] = (int) $term->term_id;
                 $dt['tt'][] = (int) $term->term_taxonomy_id;
             } else {
                 $ut['case'][] = $wpdb->prepare('WHEN %d THEN %s', $term->term_id, serialize($tr));
                 $ut['in'][] = (int) $term->term_id;
             }
         }
     }
     // Delete relationships
     if (!empty($dr)) {
         $wpdb->query("\n\t\t\t\tDELETE FROM {$wpdb->term_relationships}\n\t\t\t\tWHERE object_id IN ( " . implode(',', $dr['id']) . " )\n\t\t\t\tAND term_taxonomy_id IN ( " . implode(',', $dr['tt']) . " )\n\t\t\t");
     }
     // Delete terms
     if (!empty($dt)) {
         $wpdb->query("DELETE FROM {$wpdb->terms} WHERE term_id IN ( " . implode(',', $dt['t']) . " ) ");
         $wpdb->query("DELETE FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id IN ( " . implode(',', $dt['tt']) . " ) ");
     }
     // Update terms
     if (!empty($ut)) {
         $wpdb->query("\n\t\t\t\tUPDATE {$wpdb->term_taxonomy}\n\t\t\t\tSET description = ( CASE term_id " . implode(' ', $ut['case']) . " END )\n\t\t\t\tWHERE term_id IN ( " . implode(',', $ut['in']) . " )\n\t\t\t");
     }
     foreach ($terms as $term) {
         clean_term_cache($term->term_id, $term->taxonomy);
     }
 }
示例#27
0
/**
 * Create a new term for a term_taxonomy item that currently shares its term
 * with another term_taxonomy.
 *
 * @ignore
 * @since 4.2.0
 * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
 *              `$term_taxonomy_id` can now accept objects.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int|object $term_id          ID of the shared term, or the shared term object.
 * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
 *                                     (corresponding to a row from the term_taxonomy table).
 * @param bool       $record           Whether to record data about the split term in the options table. The recording
 *                                     process has the potential to be resource-intensive, so during batch operations
 *                                     it can be beneficial to skip inline recording and do it just once, after the
 *                                     batch is processed. Only set this to `false` if you know what you are doing.
 *                                     Default: true.
 * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
 *                      database schema), `$term_id` is returned. When the term is successfully split, the
 *                      new term_id is returned. A WP_Error is returned for miscellaneous errors.
 */
function _split_shared_term($term_id, $term_taxonomy_id, $record = true)
{
    global $wpdb;
    if (is_object($term_id)) {
        $shared_term = $term_id;
        $term_id = intval($shared_term->term_id);
    }
    if (is_object($term_taxonomy_id)) {
        $term_taxonomy = $term_taxonomy_id;
        $term_taxonomy_id = intval($term_taxonomy->term_taxonomy_id);
    }
    // If there are no shared term_taxonomy rows, there's nothing to do here.
    $shared_tt_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->term_taxonomy} tt WHERE tt.term_id = %d AND tt.term_taxonomy_id != %d", $term_id, $term_taxonomy_id));
    if (!$shared_tt_count) {
        return $term_id;
    }
    /*
     * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
     * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
     */
    $check_term_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id = %d", $term_taxonomy_id));
    if ($check_term_id != $term_id) {
        return $check_term_id;
    }
    // Pull up data about the currently shared slug, which we'll use to populate the new one.
    if (empty($shared_term)) {
        $shared_term = $wpdb->get_row($wpdb->prepare("SELECT t.* FROM {$wpdb->terms} t WHERE t.term_id = %d", $term_id));
    }
    $new_term_data = array('name' => $shared_term->name, 'slug' => $shared_term->slug, 'term_group' => $shared_term->term_group);
    if (false === $wpdb->insert($wpdb->terms, $new_term_data)) {
        return new WP_Error('db_insert_error', __('Could not split shared term.'), $wpdb->last_error);
    }
    $new_term_id = (int) $wpdb->insert_id;
    // Update the existing term_taxonomy to point to the newly created term.
    $wpdb->update($wpdb->term_taxonomy, array('term_id' => $new_term_id), array('term_taxonomy_id' => $term_taxonomy_id));
    // Reassign child terms to the new parent.
    if (empty($term_taxonomy)) {
        $term_taxonomy = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id = %d", $term_taxonomy_id));
    }
    $children_tt_ids = $wpdb->get_col($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE parent = %d AND taxonomy = %s", $term_id, $term_taxonomy->taxonomy));
    if (!empty($children_tt_ids)) {
        foreach ($children_tt_ids as $child_tt_id) {
            $wpdb->update($wpdb->term_taxonomy, array('parent' => $new_term_id), array('term_taxonomy_id' => $child_tt_id));
            clean_term_cache($term_id, $term_taxonomy->taxonomy);
        }
    } else {
        // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
        clean_term_cache($new_term_id, $term_taxonomy->taxonomy);
    }
    // Clean the cache for term taxonomies formerly shared with the current term.
    $shared_term_taxonomies = $wpdb->get_row($wpdb->prepare("SELECT taxonomy FROM {$wpdb->term_taxonomy} WHERE term_id = %d", $term_id));
    if ($shared_term_taxonomies) {
        foreach ($shared_term_taxonomies as $shared_term_taxonomy) {
            clean_term_cache($term_id, $shared_term_taxonomy);
        }
    }
    // Keep a record of term_ids that have been split, keyed by old term_id. See {@see wp_get_split_term()}.
    if ($record) {
        $split_term_data = get_option('_split_terms', array());
        if (!isset($split_term_data[$term_id])) {
            $split_term_data[$term_id] = array();
        }
        $split_term_data[$term_id][$term_taxonomy->taxonomy] = $new_term_id;
        update_option('_split_terms', $split_term_data);
    }
    /**
     * Fires after a previously shared taxonomy term is split into two separate terms.
     *
     * @since 4.2.0
     *
     * @param int    $term_id          ID of the formerly shared term.
     * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
     * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
     * @param string $taxonomy         Taxonomy for the split term.
     */
    do_action('split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy);
    return $new_term_id;
}
示例#28
0
 function convert_tags()
 {
     global $wpdb;
     if ((!isset($_POST['tags_to_convert']) || !is_array($_POST['tags_to_convert'])) && empty($this->tags_to_convert)) {
         echo '<div class="narrow">';
         echo '<p>' . sprintf(__('Uh, oh. Something didn&#8217;t work. Please <a href="%s">try again</a>.'), 'admin.php?import=wp-cat2tag&amp;step=3') . '</p>';
         echo '</div>';
         return;
     }
     if (empty($this->tags_to_convert)) {
         $this->tags_to_convert = $_POST['tags_to_convert'];
     }
     $hybrid_tags = $clear_parents = false;
     $clean_cat_cache = $clean_term_cache = array();
     $default_cat = get_option('default_category');
     echo '<ul>';
     foreach ((array) $this->tags_to_convert as $tag_id) {
         $tag_id = (int) $tag_id;
         if ($tag = get_term($tag_id, 'post_tag')) {
             printf('<li>' . __('Converting tag <strong>%s</strong> ... '), $tag->name);
             if ($cat_ttid = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id = %d AND taxonomy = 'category'", $tag->term_id))) {
                 $objects_ids = get_objects_in_term($tag->term_id, 'post_tag');
                 $cat_ttid = (int) $cat_ttid;
                 $term_order = 0;
                 foreach ($objects_ids as $object_id) {
                     $values[] = $wpdb->prepare("(%d, %d, %d)", $object_id, $cat_ttid, $term_order);
                     clean_post_cache($object_id);
                 }
                 if ($values) {
                     $wpdb->query("INSERT INTO {$wpdb->term_relationships} (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
                     if ($default_cat != $tag->term_id) {
                         $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = %d", $tag->term_id));
                         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET count = %d WHERE term_id = %d AND taxonomy = 'category'", $count, $tag->term_id));
                     }
                 }
                 $hybrid_tags = true;
                 $clean_term_cache[] = $tag->term_id;
                 $clean_cat_cache[] = $tag->term_id;
                 echo __('All posts were added to the category with the same name.') . " *</li>\n";
                 continue;
             }
             // Change the tag to a category.
             $parent = $wpdb->get_var($wpdb->prepare("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_id = %d AND taxonomy = 'post_tag'", $tag->term_id));
             if (0 == $parent || 0 < (int) $parent && $this->_category_exists($parent)) {
                 $reset_parent = '';
                 $clear_parents = true;
             } else {
                 $reset_parent = ", parent = '0'";
             }
             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET taxonomy = 'category' {$reset_parent} WHERE term_id = %d AND taxonomy = 'post_tag'", $tag->term_id));
             $clean_term_cache[] = $tag->term_id;
             $clean_cat_cache[] = $cat['term_id'];
             echo __('Converted successfully.') . "</li>\n";
         } else {
             printf('<li>' . __('Tag #%s doesn\'t exist!') . "</li>\n", $tag_id);
         }
     }
     if (!empty($clean_term_cache)) {
         $clean_term_cache = array_unique(array_values($clean_term_cache));
         clean_term_cache($clean_term_cache, 'post_tag');
     }
     if (!empty($clean_cat_cache)) {
         $clean_cat_cache = array_unique(array_values($clean_cat_cache));
         clean_term_cache($clean_term_cache, 'category');
     }
     if ($clear_parents) {
         delete_option('category_children');
     }
     echo '</ul>';
     if ($hybrid_tags) {
         echo '<p>' . sprintf(__('* This tag is also a category. The converter has added all posts from it to the category. If you want to remove it, please confirm that all posts were added successfully, then delete it from the <a href="%s">Manage Tags</a> page.'), 'edit-tags.php') . '</p>';
     }
     echo '<p>' . sprintf(__('We&#8217;re all done here, but you can always <a href="%s">convert more</a>.'), 'admin.php?import=wp-cat2tag&amp;step=3') . '</p>';
 }
示例#29
0
/**
 * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table.
 *
 * @since 3.0.0
 *
 * @see term_id_filter
 *
 * @param int $term_id An ID for a term on the current blog.
 * @return int An ID from the global terms table mapped from $term_id.
 */
function global_terms($term_id, $deprecated = '')
{
    global $wpdb;
    static $global_terms_recurse = null;
    if (!global_terms_enabled()) {
        return $term_id;
    }
    // prevent a race condition
    $recurse_start = false;
    if ($global_terms_recurse === null) {
        $recurse_start = true;
        $global_terms_recurse = 1;
    } elseif (10 < $global_terms_recurse++) {
        return $term_id;
    }
    $term_id = intval($term_id);
    $c = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->terms} WHERE term_id = %d", $term_id));
    $global_id = $wpdb->get_var($wpdb->prepare("SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $c->slug));
    if ($global_id == null) {
        $used_global_id = $wpdb->get_var($wpdb->prepare("SELECT cat_ID FROM {$wpdb->sitecategories} WHERE cat_ID = %d", $c->term_id));
        if (null == $used_global_id) {
            $wpdb->insert($wpdb->sitecategories, array('cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug));
            $global_id = $wpdb->insert_id;
            if (empty($global_id)) {
                return $term_id;
            }
        } else {
            $max_global_id = $wpdb->get_var("SELECT MAX(cat_ID) FROM {$wpdb->sitecategories}");
            $max_local_id = $wpdb->get_var("SELECT MAX(term_id) FROM {$wpdb->terms}");
            $new_global_id = max($max_global_id, $max_local_id) + mt_rand(100, 400);
            $wpdb->insert($wpdb->sitecategories, array('cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug));
            $global_id = $wpdb->insert_id;
        }
    } elseif ($global_id != $term_id) {
        $local_id = $wpdb->get_row($wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE term_id = %d", $global_id));
        if (null != $local_id) {
            $local_id = global_terms($local_id);
        }
        if (10 < $global_terms_recurse) {
            $global_id = $term_id;
        }
    }
    if ($global_id != $term_id) {
        if (get_option('default_category') == $term_id) {
            update_option('default_category', $global_id);
        }
        $wpdb->update($wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id));
        $wpdb->update($wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id));
        $wpdb->update($wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id));
        clean_term_cache($term_id);
    }
    if ($recurse_start) {
        $global_terms_recurse = null;
    }
    return $global_id;
}
示例#30
0
 /**
  * Set order of a specific term
  *
  * @since 0.1.0
  *
  * @global object  $wpdb
  * @param  int     $term_id
  * @param  string  $taxonomy
  * @param  int     $order
  * @param  bool    $clean_cache
  */
 public static function set_term_order($term_id = 0, $taxonomy = '', $order = 0, $clean_cache = false)
 {
     global $wpdb;
     // Update the database row
     $wpdb->update($wpdb->term_taxonomy, array('order' => $order), array('term_id' => $term_id, 'taxonomy' => $taxonomy));
     // Maybe clean the term cache
     if (true === $clean_cache) {
         clean_term_cache($term_id, $taxonomy);
     }
 }