/** * Set Default Terms * Used in attachment-functions.php * * @since 0.1 */ function sell_media_set_default_terms($post_id, $post = null, $term_ids = null) { if (is_null($post)) { $post_type = get_post_type($post_id); } else { $post_type = $post->post_type; $post_status = $post->post_status; } if (empty($post_status)) { return; } if (empty($term_ids) || $term_ids === true) { $term_ids = sell_media_get_default_terms(); } $taxonomy = 'licenses'; $default_terms = array(); foreach ($term_ids as $term_id) { $tmp_term_id = get_term_by('id', $term_id, $taxonomy); if ($tmp_term_id) { $default_terms[] = (int) $tmp_term_id->term_id; $default_terms[] = (int) $tmp_term_id->parent; } } $defaults = array($taxonomy => $default_terms); $taxonomies = get_object_taxonomies($post_type); foreach ((array) $taxonomies as $taxonomy) { $terms = wp_get_post_terms($post_id, $taxonomy); if (empty($terms) && array_key_exists($taxonomy, $defaults)) { wp_set_object_terms($post_id, $defaults[$taxonomy], $taxonomy); } } }
function p2_at_names($content) { global $post, $comment; $name_map = p2_get_at_name_map(); // get users user_login and display_name map $content_original = $content; // save content before @names are found foreach ($name_map as $name => $values) { //loop and... $content = str_ireplace($name, $values['replacement'], $content); // Change case to that in $name_map $content = strtr($content, $name, $name); // Replaces keys with values longest to shortest, without re-replacing pieces it's already done if ($content != $content_original) { // if the content has changed, an @name has been found. $users_to_add[] = get_usermeta($name_map[$name]['id'], 'user_login'); } // add that user to an array. $content_original = $content; } if (is_array($users_to_add)) { $cache_data = implode($users_to_add); } // if we've got an array, make it a comma delimited string if (isset($cache_data) && $cache_data != wp_cache_get('mentions', $post->ID)) { wp_set_object_terms($post->ID, $users_to_add, 'mentions', true); // tag the post. wp_cache_set('mentions', $cache_data, $post->ID); } return $content; }
function wpp_edit_save_promotion($id, $title, $content, $category, $attach_id, $promoStart, $promoEnd, $nonce) { //sanitize data $id = sanitize_text_field($id); $title = sanitize_text_field($title); $content = sanitize_text_field($content); $category = sanitize_text_field($category); $attachid = sanitize_text_field($attach_id); $promoStart = sanitize_text_field($promoStart); $promoEnd = sanitize_text_field($promoEnd); //make sure this post belongs to the user $user_id = get_current_user_id(); $query = new WP_Query(array('post_type' => promo, 'p' => $id, 'posts_per_page' => '-1', 'post_status' => array('publish', 'pending', 'draft', 'trash'), 'author' => $user_id)); if ($query->found_posts === 0) { wp_die(); } wp_reset_query(); $data = array(); $post_information = array('ID' => $id, 'post_title' => $title, 'post_content' => $content, 'post-type' => 'promotion', 'post_status' => 'pending'); $post_id = wp_update_post($post_information); //set object terms wp_set_object_terms($post_id, $category, 'promotion_category', true); update_post_meta($post_id, 'wpp_promo_start', $promoStart); update_post_meta($post_id, 'wpp_promo_end', $promoEnd); update_post_meta($post_id, 'wpp_promo_logged', 'not_logged'); if (!is_wp_error($attach_id)) { //and if you want to set that image as Post then use set_post_thumbnail($post_id, $attach_id); } $data['id'] = $post_id; $data['start'] = wpp_date_to_unix($promoStart); $data['end'] = wpp_date_to_unix($promoEnd); wpp_schedule_promotion_events($data); }
function add_new_category() { if (is_user_logged_in()) { if (isset($_POST['cat_name']) && !empty($_POST['cat_name']) && isset($_POST['parent_id']) && !empty($_POST['parent_id'])) { $cat_name = esc_html($_POST['cat_name']); $parent_id = esc_html($_POST['parent_id']); $new_cat_args = array($cat_name, 'bookmark-category'); if ($parent_id == -1) { // Add Term to Bookmark Category $new_category = wp_insert_term($cat_name, 'bookmark-category'); } else { // Add Term to Bookmark Category $new_category = wp_insert_term($cat_name, 'bookmark-category', array('parent' => $parent_id)); } if (!is_wp_error($new_category)) { $term = get_term_by('id', $new_category['term_id'], 'bookmark-category'); // Add Term to User wp_set_object_terms($current_user->ID, array($term->slug), 'bookmark-category', true); $returner = array('success' => true, 'cat_id' => $new_category['term_id'], 'cat_slug' => $term->slug, 'cat_link' => get_term_link($term, 'bookmark-category')); } else { $returner = array('success' => false, 'reason' => 'WP Error on term creation.'); } } else { $returner = array('success' => false, 'reason' => 'Post values not set.'); } } else { $returner = array('success' => false, 'reason' => 'User not logged in.'); } echo json_encode($returner); exit; }
public function set_terms($key, $terms) { foreach ($terms as $term_data) { $term = new Term($term_data->name, $term_data->taxonomy); wp_set_object_terms($this->id, intval($term->id), $term_data->taxonomy, true); } }
/** * Migrate meta values to taxonomy terms. Delete meta after import * * ## OPTIONS * * <meta-key> * : Meta key to convert * * <taxonomy-slug> * : Taxonomy to move values into * * [--<field>=<value>] * : One or more args to pass to WP_Query. * * ## EXAMPLES * * wp mtt migrate meta_key taxonomy_slug * wp mtt migrate meta_key taxonomy_slug --posts_per_page=200 --paged=2 * */ function migrate($args, $assoc_args) { list($meta_key, $taxonomy) = $args; if (!($taxonomy_object = get_taxonomy($taxonomy))) { WP_CLI::error(sprintf("The taxonomy '%s' doesn't exist", $taxonomy)); } $defaults = array('post_type' => $taxonomy_object->object_type, 'posts_per_page' => -1, 'post_status' => 'any'); $query_args = array_merge($defaults, $assoc_args); $query = new WP_Query($query_args); // summary WP_CLI::log(sprintf("---\nPer page: %d \nPage: %d \nTotal pages: %d\n---", $query_args['posts_per_page'], isset($query_args['paged']) ? $query_args['paged'] : 1, $query->max_num_pages)); while ($query->have_posts()) { $query->the_post(); $id = get_the_id(); // get meta $metas = get_post_meta($id, $meta_key); // create term if (!$metas) { WP_CLI::log(WP_CLI::colorize("%c[{$id}]%n No meta, skipped")); } else { if (!is_wp_error(wp_set_object_terms($id, $metas, $taxonomy, true))) { WP_CLI::log(WP_CLI::colorize("%g[{$id}]%n Migrated: " . implode(', ', $metas))); // clean meta delete_post_meta($id, $meta_key); } else { WP_CLI::log(WP_CLI::colorize("%r[{$id}]%n Error: Could not set terms for post")); } } } }
public static function save($post_id) { if (isset($_POST['_unit'])) { update_post_meta($post_id, '_unit', sanitize_text_field($_POST['_unit'])); } if (isset($_POST['_unit_base'])) { update_post_meta($post_id, '_unit_base', $_POST['_unit_base'] === '' ? '' : wc_format_decimal($_POST['_unit_base'])); } if (isset($_POST['_unit_price_regular'])) { update_post_meta($post_id, '_unit_price_regular', $_POST['_unit_price_regular'] === '' ? '' : wc_format_decimal($_POST['_unit_price_regular'])); update_post_meta($post_id, '_unit_price', $_POST['_unit_price_regular'] === '' ? '' : wc_format_decimal($_POST['_unit_price_regular'])); } if (isset($_POST['_unit_price_sale'])) { update_post_meta($post_id, '_unit_price_sale', ''); // Update Sale Price only if is on sale (Cron?!) if (get_post_meta($post_id, '_price', true) != $_POST['_regular_price'] && $_POST['_unit_price_sale'] !== '') { update_post_meta($post_id, '_unit_price_sale', $_POST['_unit_price_sale'] === '' ? '' : wc_format_decimal($_POST['_unit_price_sale'])); update_post_meta($post_id, '_unit_price', $_POST['_unit_price_sale'] === '' ? '' : wc_format_decimal($_POST['_unit_price_sale'])); } } if (isset($_POST['_mini_desc'])) { update_post_meta($post_id, '_mini_desc', esc_html($_POST['_mini_desc'])); } if (isset($_POST['delivery_time']) && !is_numeric($_POST['delivery_time'])) { wp_set_post_terms($post_id, sanitize_text_field($_POST['delivery_time']), 'product_delivery_time'); } else { wp_set_object_terms($post_id, absint($_POST['delivery_time']), 'product_delivery_time'); } }
private function categorize($post_id, $categories_str) { $categories_arr = explode(',', $categories_str); foreach ($categories_arr as $category) { $categories_par = explode('>', $category); if (!isset($categories_par[0], $categories_par[1])) { $this->err($category, $post_id); } $categories_par[0] = trim($categories_par[0]); $categories_par[1] = trim($categories_par[1]); $parent_term = term_exists($categories_par[0], 'venture_categories'); if (!$parent_term) { $parent_term = wp_insert_term($categories_par[0], 'venture_categories'); } $parent_term_id = intval($parent_term['term_id']); $term = term_exists($categories_par[1], 'venture_categories', $parent_term_id); if (!$term) { $term = wp_insert_term($categories_par[1], 'venture_categories', array('parent' => $parent_term_id)); } if (is_wp_error($term)) { $this->err($category, $post_id); } $term_id = intval($term['term_id']); wp_set_object_terms($post_id, $parent_term_id, 'venture_categories', true); wp_set_object_terms($post_id, $term_id, 'venture_categories', true); } }
function sui_form_shortcode() { if (!is_user_logged_in()) { return '<p>You need to be logged in to submit an image.</p>'; } global $current_user; if (isset($_POST['sui_upload_image_form_submitted']) && wp_verify_nonce($_POST['sui_upload_image_form_submitted'], 'sui_upload_image_form')) { $result = sui_parse_file_errors($_FILES['sui_image_file'], $_POST['sui_image_caption']); if ($result['error']) { echo '<p>ERROR: ' . $result['error'] . '</p>'; } else { $user_image_data = array('post_title' => $result['caption'], 'post_status' => 'pending', 'post_author' => $current_user->ID, 'post_type' => 'user_images'); if ($post_id = wp_insert_post($user_image_data)) { sui_process_image('sui_image_file', $post_id, $result['caption']); wp_set_object_terms($post_id, (int) $_POST['sui_image_category'], 'sui_image_category'); } } } if (isset($_POST['sui_form_delete_submitted']) && wp_verify_nonce($_POST['sui_form_delete_submitted'], 'sui_form_delete')) { if (isset($_POST['sui_image_delete_id'])) { if ($user_images_deleted = sui_delete_user_images($_POST['sui_image_delete_id'])) { echo '<p>' . $user_images_deleted . ' images(s) deleted!</p>'; } } } echo sui_get_upload_image_form($sui_image_caption = $_POST['sui_image_caption'], $sui_image_category = $_POST['sui_image_category']); if ($user_images_table = sui_get_user_images_table($current_user->ID)) { echo $user_images_table; } }
function maybe_restore_object_terms($object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids) { if (isset($this->scheduled_term_restoration[$object_id][$taxonomy])) { wp_set_object_terms($object_id, $this->scheduled_term_restoration[$object_id][$taxonomy], $taxonomy); unset($this->scheduled_term_restoration[$object_id][$taxonomy]); } }
public function save($eventObj) { global $wpdb; //Check to see if this event has actually been added. $foundId = $wpdb->get_results("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_EventBriteId' AND meta_value={$eventObj->ID}"); $post_id = $foundId[0]->post_id; if ($post_id) { wp_update_post(array('ID' => $foundId, 'post_title' => $eventObj->post_title, 'post_content' => $eventObj->post_content, 'post_date' => $eventObj->post_date, 'post_author' => 1)); } else { $post_id = wp_insert_post(array('post_type' => 'tribe_events', 'post_title' => $eventObj->post_title, 'post_content' => $eventObj->post_content, 'post_status' => 'publish', 'post_date' => $eventObj->post_date, 'post_author' => 1)); //Static meta update_post_meta($post_id, '_EventShowTickets', 'yes'); update_post_meta($post_id, '_EventVenueID', 304); //hardcoded to ID of Amazing Things venue post update_post_meta($post_id, '_EventRegister', 'yes'); update_post_meta($post_id, '_EventOrigin', 'eventbrite-tickets'); //only want to run this once. if ($eventObj->logo_url) { $this->transfer_image($post_id, $eventObj); } } update_post_meta($post_id, '_EventStartDate', date_format($eventObj->start, 'Y-m-d H:i:s')); update_post_meta($post_id, '_EventEndDate', date_format($eventObj->end, 'Y-m-d H:i:s')); update_post_meta($post_id, '_EventBriteId', $eventObj->ID); update_post_meta($post_id, '_EventURL', esc_url($eventObj->url)); if ($eventObj->category) { wp_set_object_terms($post_id, $eventObj->category, 'tribe_events_cat'); } if ($eventObj->tags) { wp_set_object_terms($post_id, $eventObj->tags, 'post_tag', false); } if ($eventObj->format) { wp_set_object_terms($post_id, $eventObj->format, 'event-type'); } }
public function save($post_id) { if (!isset($_POST['fpr_metabox_nonce_field'])) { return $post_id; } $nonce = sanitize_text_field($_POST['fpr_metabox_nonce_field']); if (!wp_verify_nonce($nonce, 'ferina_product_retail_metabox_nonce')) { return $post_id; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } if ('retail-product' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } else { if (!current_user_can('edit_post', $post_id)) { return $post_id; } } $ferina_sku = sanitize_text_field($_POST['ferina_sku']); $ferina_prod_desc = $_POST['ferina_product_description']; $prices = sanitize_text_field($_POST['ferina_product_prices']); $productstyle = sanitize_text_field($_POST['ferina_style']); $ferina_product_images = $_POST['ferina_product_images']; $productstyle = $productstyle > 0 ? get_term($productstyle, 'style')->slug : NULL; update_post_meta($post_id, '_ferina_sku_product', $ferina_sku); update_post_meta($post_id, '_ferina_description_product', $ferina_prod_desc); update_post_meta($post_id, '_ferina_product_prices', $prices); update_post_meta($post_id, '_ferina_product_images', serialize($ferina_product_images)); wp_set_object_terms($post_id, $productstyle, 'style'); }
/** * Misc functions * * @since 1.0.0 * @updated 1.0.8 */ function mark_posts_misc_functions() { // mark all posts if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['mark-all-posts-term-id'])) { $term_id = $_GET['mark-all-posts-term-id']; /* TODO:: SECURITY */ // set color only for selected post types $get_mark_posts_settings = get_option('mark_posts_settings'); foreach ($get_mark_posts_settings['mark_posts_posttypes'] as $post_type) { $args = array('posts_per_page' => -1, 'post_type' => $post_type); // get all posts $all_posts = get_posts($args); foreach ($all_posts as $post) { // Sanitize the user input. $mydata = sanitize_text_field($term_id); $myterm = get_term($term_id, 'marker'); // Update the meta field. update_post_meta($post->ID, 'mark_posts_term_id', $mydata); // Update taxonomy count wp_set_object_terms($post->ID, $myterm->name, 'marker'); } } echo mark_posts_display_settings_updated(); } }
function ph_migrate_post_category_handler($post, $fields) { $metas = array(); foreach ($fields as $key => $value) { $prop = substr($key, strlen('categories:')); $metas[$prop] = $value; } $ids = $metas['ids']; if (isset($metas['taxonomy'])) { $taxonomies = $metas['taxonomy']; } else { $taxonomies = 'category'; } if (!is_array($ids)) { $ids = array($ids); $taxonomies = array($taxonomies); } else { if (!is_array($taxonomies)) { $taxonomies = array($taxonomies); } while (count($ids) > count($taxonomies)) { $taxonomies[] = $taxonomies[0]; } } $copy = array(); for ($i = 0; $i < count($ids); $i++) { if (!isset($copy[$taxonomies[$i]]) || !in_array($ids[$i], $copy[$taxonomies[$i]])) { $copy[$taxonomies[$i]][] = $ids[$i]; } } foreach ($copy as $taxonomy => $ids) { wp_set_object_terms($post['ID'], $ids, $taxonomy, false); } }
/** * * Assigns random terms to all posts in a taxonomy. * * By default all objects of the 'post' post type will be randomized, use the * --post_type flag to target pages or a custom post type. Use the --include * and --exclude flags to filter or ignore specific object IDs and the --before * and --after flags to specify a date range. Also, optionally pass --terms as * a list of terms you want to use for the randomization. If terms exist in the * target taxonomy, those terms will be used. If not, a string of 6 words * generated randomly will be used for the randomization. * * ## Options * * <taxonomy> * : The taxonomy that should get randomized * * ## Exmples * * wp randomize category * * @synopsis <taxonomy> [--include=<bar>] [--exclude=<foo>] [--post_type=<foo>] * [--before=<bar>] [--after=<date>] [--terms=<terms>] * **/ public function taxonomy($args, $assoc_args) { $taxonomy = $args[0]; $get_posts = $this->get_specified_posts($assoc_args); $message = $get_posts['message']; $posts = $get_posts['posts']; $args = $get_posts['args']; $preamble = "Will assign random {$taxonomy} terms"; print_r("{$preamble} {$message}.\n"); if (isset($assoc_args['terms'])) { $terms = explode(',', $assoc_args['terms']); \WP_CLI::log('Using terms ' . $assoc_args['terms']); } else { \WP_CLI::log('Gathering and processing random terms.'); $terms = $this->get_random_terms(); \WP_CLI::log('No term list given, using random terms.'); } foreach ($posts as $p) { $index = array_rand($terms); $term = $terms[$index]; \WP_CLI::log("Assigning {$term} to taxonomy {$taxonomy} for {$p->post_type} {$p->ID}"); if (!term_exists($term, $taxonomy)) { wp_insert_term($term, $taxonomy); } wp_set_object_terms($p->ID, $term, $taxonomy, $append = false); } }
function update_terms($post_id) { $comment_meta = $this->get_comment_meta(array('post_id' => $post_id)); $post_meta = get_post_meta($post_id, $this->meta_key); $terms = array_unique(array_merge($post_meta, $comment_meta)); wp_set_object_terms($post_id, $terms, $this->taxonomy); }
/** * Guarda una entrada para post type Tutorial * * @param string $nombre - Nombre de la autora * @param string $titulo - Título del tutorial * @param string $categoria - taxonomy term de categoría * @param string $url_video - URL de video del tutorial * @param string $url_imagen - URL relative de thumb del video * @return integer $post_id - ID del post creado. */ function save_tutorial() { $nombre = $_POST['name']; $titulo = $_POST['title']; $categoria_tutorial = $_POST['category']; $email = $_POST['email']; $url_video = $_POST['video_url']; $url_imagen = $_POST['img_url']; $tutorial_post = array('post_title' => $titulo, 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'tutoriales'); $post_id = wp_insert_post($tutorial_post); if (!$post_id) { $message = array('error' => 1, 'message' => 'Ha ocurrido un error. No se pudo guardar el tutorial.'); echo json_encode($message, JSON_FORCE_OBJECT); exit; } add_post_meta($post_id, '_nombre_meta', $nombre); add_post_meta($post_id, '_email_meta', $email); add_post_meta($post_id, '_url_video_meta', $url_video); add_post_meta($post_id, '_url_imagen_meta', $url_imagen); $categoria_tutorial_term = get_term_by('name', $categoria_tutorial, 'categoria-tutorial'); wp_set_object_terms($post_id, array($categoria_tutorial_term->term_id), 'categoria-tutorial'); $message = array('error' => 0, 'message' => '¡Tutorial guardado exitosamente!', 'permalink' => get_permalink($post_id), 'the_title' => get_the_title($post_id)); echo json_encode($message, JSON_FORCE_OBJECT); exit; }
function rcl_update_grouppost_meta($post_id, $postdata, $action) { if ($postdata['post_type'] != 'post-group') { return false; } if (isset($_POST['term_id'])) { $term_id = intval(base64_decode($_POST['term_id'])); } if (isset($term_id)) { wp_set_object_terms($post_id, (int) $term_id, 'groups'); } $gr_tag = sanitize_text_field($_POST['group-tag']); if ($gr_tag) { if (!$term_id) { $groups = get_the_terms($post_id, 'groups'); foreach ($groups as $group) { if ($group->parent != 0) { continue; } $group_id = $group->term_id; } } else { $group_id = $term_id; } $term = term_exists($gr_tag, 'groups', $group_id); if (!$term) { $term = wp_insert_term($gr_tag, 'groups', array('description' => '', 'slug' => '', 'parent' => $group_id)); } wp_set_object_terms($post_id, array((int) $term['term_id'], (int) $group_id), 'groups'); } }
function setUp() { global $wp_rewrite; parent::setUp(); set_current_screen('front'); $GLOBALS['wp_the_query'] = new WP_Query(); $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; $wp_rewrite->init(); $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%day%/%postname%/'); create_initial_taxonomies(); register_taxonomy('testtax', 'post', array('public' => true)); $wp_rewrite->flush_rules(); $this->tag_id = $this->factory->tag->create(array('slug' => 'tag-slug')); $this->cat_id = $this->factory->category->create(array('slug' => 'cat-slug')); $this->tax_id = $this->factory->term->create(array('taxonomy' => 'testtax', 'slug' => 'tax-slug')); $this->tax_id2 = $this->factory->term->create(array('taxonomy' => 'testtax', 'slug' => 'tax-slug2')); $this->post_id = $this->factory->post->create(); wp_set_object_terms($this->post_id, $this->cat_id, 'category'); wp_set_object_terms($this->post_id, array($this->tax_id, $this->tax_id2), 'testtax'); $this->cat = get_term($this->cat_id, 'category'); _make_cat_compat($this->cat); $this->tag = get_term($this->tag_id, 'post_tag'); $this->uncat = get_term_by('slug', 'uncategorized', 'category'); _make_cat_compat($this->uncat); add_action('pre_get_posts', array($this, 'pre_get_posts_tax_category_tax_query')); }
function test_multiple_terms() { $post_1 = $this->factory->post->create(); $post_2 = $this->factory->post->create(); register_taxonomy('test', 'post', array()); wp_set_object_terms($post_1, 'term-1', 'test'); wp_set_object_terms($post_1, 'term-2', 'test', true); wp_set_object_terms($post_2, 'term-1', 'test'); wp_set_object_terms($post_2, 'term-3', 'test', true); $qq = new QQuery(); $posts_both = $qq->tax('term-1')->go(); // should return both posts $this->assertEquals(2, count($posts_both)); $post_first = $qq->tax('term-2')->go(); // should only return the first $this->assertEquals(1, count($post_first)); $post_second = $qq->tax('term-3')->go(); // should only return the second $this->assertEquals(1, count($post_second)); $posts_none = $qq->tax(array('term-2', 'term-3'))->go(); // should return none because default to AND $this->assertEquals(0, count($posts_none)); $posts_both_again = $qq->tax(array('term-2', 'term-3'), array('relation' => 'OR'))->go(); // should return both because we set OR $this->assertEquals(2, count($posts_both_again)); }
/** * Set taxonomy terms on a BuddyPress object. * * @since 2.2.0 * * @see wp_set_object_terms() for a full description of function and parameters. * * @param int $object_id Object ID. * @param string|array $terms Term or terms to set. * @param string $taxonomy Taxonomy name. * @param bool $append Optional. True to append terms to existing terms. Default: false. * @return array Array of term taxonomy IDs. */ function bp_set_object_terms($object_id, $terms, $taxonomy, $append = false) { $site_id = bp_get_taxonomy_term_site_id($taxonomy); $switched = false; if ($site_id !== get_current_blog_id()) { switch_to_blog($site_id); bp_register_taxonomies(); $switched = true; } $tt_ids = wp_set_object_terms($object_id, $terms, $taxonomy, $append); if ($switched) { restore_current_blog(); } /** * Fires when taxonomy terms have been set on BuddyPress objects. * * @since 2.7.0 * * @param int $object_id Object ID. * @param array $terms Term or terms to remove. * @param array $tt_ids Array of term taxonomy IDs. * @param string $taxonomy Taxonomy name. */ do_action('bp_set_object_terms', $object_id, $terms, $tt_ids, $taxonomy); return $tt_ids; }
/** * Default fallback sanitization method. Applies filters. * @since 1.0.2 * @param mixed $value Meta value */ public function default_sanitization($value) { // Allow field type validation via filter $updated = apply_filters('cmb_validate_' . $this->field->type(), null, $value, $this->object_id, $this->field->args(), $this); if (null !== $updated) { return $updated; } switch ($this->field->type()) { case 'wysiwyg': //return $this->field->$value; // break; //return $this->field->$value; // break; case 'textarea_small': return $this->textarea($value); case 'taxonomy_select': case 'taxonomy_radio': case 'taxonomy_multicheck': if ($this->field->args('taxonomy')) { return wp_set_object_terms($this->object_id, $value, $this->field->args('taxonomy')); } case 'multicheck': case 'file_list': case 'oembed': // no filtering return $value; default: // Handle repeatable fields array // We'll fallback to 'sanitize_text_field' return is_array($value) ? array_map('sanitize_text_field', $value) : call_user_func('sanitize_text_field', $value); } }
function set_up_0_4_0_test_posts() { update_option('wp_gistpen_version', '0.3.1'); register_post_type('gistpens', array()); register_taxonomy('language', array('gistpens')); foreach (Language::$supported as $lang => $slug) { $result = wp_insert_term($lang, 'language', array('slug' => $slug)); if (is_wp_error($result)) { throw new Exception("Failed to insert term."); } } $terms = get_terms('language', 'hide_empty=0'); foreach ($terms as $term) { $languages[] = $term->slug; } $num_posts = count($languages); $this->gistpens = $this->factory->post->create_many($num_posts, array('post_type' => 'gistpens', 'post_status' => 'publish'), array('post_title' => new WP_UnitTest_Generator_Sequence('Post title %s'), 'post_name' => new WP_UnitTest_Generator_Sequence('Post title %s'), 'post_content' => new WP_UnitTest_Generator_Sequence('Post content %s'))); foreach ($this->gistpens as $gistpen_id) { // Pick a random language $num_posts = $num_posts - 1; $lang_num = rand(0, $num_posts); // Get the language's id $lang_slug = $languages[$lang_num]; // Remove the language and reindex the languages array unset($languages[$lang_num]); $languages = array_values($languages); // Give the post a description update_post_meta($gistpen_id, '_wpgp_gistpen_description', 'This is a description of the Gistpen.'); // Give the post the language wp_set_object_terms($gistpen_id, $lang_slug, 'language', false); // Create and set up the user $user_id = $this->factory->user->create(array('role' => 'administrator')); wp_set_current_user($user_id); } }
/** * @param int $original_post_id * @param string $lang * @param bool $duplicate sets whether missing terms should be created by duplicating the original term */ private function synchronize_terms($original_post_id, $lang, $duplicate) { global $wpml_post_translations; $wpml_post_translations->reload(); $translated_post_id = $wpml_post_translations->element_id_in($original_post_id, $lang); if ((bool) $translated_post_id === true) { $taxonomies = get_post_taxonomies($original_post_id); foreach ($taxonomies as $tax) { $terms_on_original = wp_get_object_terms($original_post_id, $tax); if (!$this->sitepress->is_translated_taxonomy($tax)) { if ($this->sitepress->get_setting('sync_post_taxonomies')) { // Taxonomy is not translated so we can just copy from the original foreach ($terms_on_original as $key => $term) { $terms_on_original[$key] = $term->term_id; } wp_set_object_terms($translated_post_id, $terms_on_original, $tax); } } else { /** @var int[] $translated_terms translated term_ids */ $translated_terms = $this->get_translated_term_ids($terms_on_original, $lang, $tax, $duplicate); wp_set_object_terms($translated_post_id, $translated_terms, $tax); } } } clean_object_term_cache($original_post_id, get_post_type($original_post_id)); }
private function import_testimonials_from_csv($testimonials_file) { //increase execution time before beginning import, as this could take a while set_time_limit(0); //use current timestamp for batch number $batch_number = time(); $testimonials = $this->csv_to_array($testimonials_file); foreach ($testimonials as $testimonial) { //defaults $the_name = $the_body = ''; if (isset($testimonial['Title'])) { $the_name = $testimonial['Title']; } if (isset($testimonial['Body'])) { $the_body = $testimonial['Body']; } //look for a testimonial with the title and body //if not found, insert this one $postslist = get_page_by_title($the_name, OBJECT, 'testimonial'); //if this is empty, a match wasn't found and therefore we are safe to insert if (empty($postslist)) { //insert the testimonials $tags = array(); $post = array('post_title' => $the_name, 'post_content' => $the_body, 'post_category' => array(1), 'tags_input' => $tags, 'post_status' => 'publish', 'post_type' => 'testimonial', 'post_author' => get_option('easy_t_testimonial_author', 1)); $new_id = wp_insert_post($post); // assign Staff Member Categories if any were specified // NOTE: we are using wp_set_object_terms instead of adding a tax_input key to wp_insert_posts, because // it is less likely to fail b/c of permissions and load order (i.e., taxonomy may not have been created yet) if (!empty($testimonial['Categories'])) { $post_cats = explode(',', $testimonial['Categories']); $post_cats = array_map('intval', $post_cats); // sanitize to ints wp_set_object_terms($new_id, $post_cats, 'easy-testimonial-category'); } //defaults, in case certain data wasn't in the CSV $client_name = isset($testimonial['Client Name']) ? $testimonial['Client Name'] : ""; $email = isset($testimonial['E-Mail Address']) ? $testimonial['E-Mail Address'] : ""; $position_location_other = isset($testimonial['Position / Location / Other']) ? $testimonial['Position / Location / Other'] : ""; $location_product_other = isset($testimonial['Location / Product / Other']) ? $testimonial['Location / Product / Other'] : ""; $rating = isset($testimonial['Rating']) ? $testimonial['Rating'] : ""; $htid = isset($testimonial['HTID']) ? $testimonial['HTID'] : ""; $featured_image = isset($testimonial['Featured Image']) ? $testimonial['Featured Image'] : ""; update_post_meta($new_id, '_ikcf_client', $client_name); update_post_meta($new_id, '_ikcf_email', $email); update_post_meta($new_id, '_ikcf_position', $position_location_other); update_post_meta($new_id, '_ikcf_other', $location_product_other); update_post_meta($new_id, '_ikcf_rating', $rating); update_post_meta($new_id, '_ikcf_htid', $htid); update_post_meta($new_id, '_ikcf_import_batch', $batch_number); // Look for a photo path on CSV // If found, try to import this photo and attach it to this staff member $this->import_testimonial_photo($new_id, $featured_image); $inserted = true; echo "Successfully imported '{$the_name}'!\n"; } else { //rejected as duplicate echo "Could not import {$the_name}; rejected as Duplicate\n"; } } }
/** * Add a term to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function create_item($request) { $post = get_post($request['post_id']); $term_id = absint($request['term_id']); $is_request_valid = $this->validate_request($request); if (is_wp_error($is_request_valid)) { return $is_request_valid; } $term = get_term($term_id, $this->taxonomy); $tt_ids = wp_set_object_terms($post->ID, $term->term_id, $this->taxonomy, true); if (is_wp_error($tt_ids)) { return $tt_ids; } $term = $this->terms_controller->prepare_item_for_response(get_term($term_id, $this->taxonomy), $request); $response = rest_ensure_response($term); $response->set_status(201); /** * Fires after a term is added to a post via the REST API. * * @param array $term The added term data. * @param WP_Post $post The post the term was added to. * @param WP_REST_Request $request The request sent to the API. */ do_action('rest_insert_term', $term, $post, $request); return $term; }
function save_post_hook($post_id) { if (get_post_type($post_id) == 'medic') { // delete_post_meta($post_id,'altele_foto'); $the_terms = get_the_terms($post_id, 'specialitate'); if (is_array($the_terms) && sizeof($the_terms > 0)) { foreach ($the_terms as $term) { //print_r($term->name); $page = get_page_by_title($term->name, 'OBJECT', 'specialitati'); if (!$page) { $new_post = array('post_type' => 'specialitati', 'post_name' => $term->name, 'post_title' => $term->name, 'post_content' => 'Pagina generata dinamic.', 'post_status' => 'publish'); //var_dump($new_post); $wp_error = new \wp_error(); $post_id = wp_insert_post($new_post, $wp_error); $done = wp_set_object_terms($post_id, $term->name, 'specialitate', true); } $page = get_page_by_title($term->name, 'OBJECT', 'cabinet'); // var_dump($page);die(); if (!$page) { $new_post = array('post_type' => 'cabinet', 'post_name' => $term->name, 'post_title' => $term->name, 'post_content' => 'Pagina generata dinamic.', 'post_status' => 'publish'); //var_dump($new_post);die(); $wp_error = new \wp_error(); $post_id = wp_insert_post($new_post, $wp_error); $done = wp_set_object_terms($post_id, $term->name, 'cabinet', true); } } } //die(); } }
/** * Create a dummy variation product. * * @since 2.3 * * @return WC_Product_Variable */ public static function create_variation_product() { global $wpdb; // Create all attribute related things $attribute_data = self::create_attribute(); // Create the product $product_id = wp_insert_post(array('post_title' => 'Dummy Product', 'post_type' => 'product', 'post_status' => 'publish')); // Set it as variable. wp_set_object_terms($product_id, 'variable', 'product_type'); // Price related meta update_post_meta($product_id, '_price', '10'); update_post_meta($product_id, '_min_variation_price', '10'); update_post_meta($product_id, '_max_variation_price', '15'); update_post_meta($product_id, '_min_variation_regular_price', '10'); update_post_meta($product_id, '_max_variation_regular_price', '15'); // General meta update_post_meta($product_id, '_sku', 'DUMMY SKU'); update_post_meta($product_id, '_manage_stock', 'no'); update_post_meta($product_id, '_tax_status', 'taxable'); update_post_meta($product_id, '_downloadable', 'no'); update_post_meta($product_id, '_virtual', 'taxable'); update_post_meta($product_id, '_visibility', 'visible'); update_post_meta($product_id, '_stock_status', 'instock'); // Attributes update_post_meta($product_id, '_default_attributes', array()); update_post_meta($product_id, '_product_attributes', array('pa_size' => array('name' => 'pa_size', 'value' => '', 'position' => '1', 'is_visible' => 0, 'is_variation' => 1, 'is_taxonomy' => 1))); // Link the product to the attribute $wpdb->insert($wpdb->prefix . 'term_relationships', array('object_id' => $product_id, 'term_taxonomy_id' => $attribute_data['term_taxonomy_id'], 'term_order' => 0)); $return['term_taxonomy_id'] = $wpdb->insert_id; // Create the variation $variation_id = wp_insert_post(array('post_title' => 'Variation #' . ($product_id + 1) . ' of Dummy Product', 'post_type' => 'product_variation', 'post_parent' => $product_id, 'post_status' => 'publish')); // Price related meta update_post_meta($variation_id, '_price', '10'); update_post_meta($variation_id, '_regular_price', '10'); // General meta update_post_meta($variation_id, '_sku', 'DUMMY SKU VARIABLE SMALL'); update_post_meta($variation_id, '_manage_stock', 'no'); update_post_meta($variation_id, '_downloadable', 'no'); update_post_meta($variation_id, '_virtual', 'taxable'); update_post_meta($variation_id, '_stock_status', 'instock'); // Attribute meta update_post_meta($variation_id, 'attribute_pa_size', 'small'); // Create the variation $variation_id = wp_insert_post(array('post_title' => 'Variation #' . ($product_id + 2) . ' of Dummy Product', 'post_type' => 'product_variation', 'post_parent' => $product_id, 'post_status' => 'publish')); // Price related meta update_post_meta($variation_id, '_price', '15'); update_post_meta($variation_id, '_regular_price', '15'); // General meta update_post_meta($variation_id, '_sku', 'DUMMY SKU VARIABLE SMALL'); update_post_meta($variation_id, '_manage_stock', 'no'); update_post_meta($variation_id, '_downloadable', 'no'); update_post_meta($variation_id, '_virtual', 'taxable'); update_post_meta($variation_id, '_stock_status', 'instock'); // Attribute meta update_post_meta($variation_id, 'attribute_pa_size', 'large'); // Add the variation meta to the main product update_post_meta($product_id, '_max_price_variation_id', $variation_id); return new WC_Product_Variable($product_id); }
function frontier_clone_post($fpost_sc_parms = array()) { //extract($fpost_sc_parms); //echo "CLONE POST<br>"; $frontier_permalink = get_permalink(); $concat = get_option("permalink_structure") ? "?" : "&"; if (isset($_POST['task'])) { $post_task = $_POST['task']; } else { if (isset($_GET['task'])) { $post_task = $_GET['task']; } else { $post_task = "notaskset"; } } $post_action = isset($_POST['action']) ? $_POST['action'] : "Unknown"; if ($post_task == "clone" && $_REQUEST['postid']) { $old_post = get_post($_REQUEST['postid']); $old_post_id = $old_post->ID; //double check current user can add a post with this post type if (frontier_can_add($old_post->post_type)) { require_once ABSPATH . '/wp-admin/includes/post.php'; global $current_user; //Get permalink from old post $old_permalink = get_permalink($old_post_id); // lets clone it $thispost = get_default_post_to_edit($fpost_sc_parms['frontier_add_post_type'], true); $new_post_id = $thispost->ID; $tmp_post = array('ID' => $new_post_id, 'post_type' => $old_post->post_type, 'post_title' => __("CLONED from", "frontier-post") . ': <a href="' . $old_permalink . '">' . $old_post->post_title . '</a>', 'post_content' => __("CLONED from", "frontier-post") . ': <a href="' . $old_permalink . '">' . $old_post->post_title . '</a><br>' . $old_post->post_content, 'post_status' => "draft", 'post_author' => $current_user->ID); //**************************************************************************************************** // Apply filter before update of post // filter: frontier_post_clone // $tmp_post Array that holds the updated fields // $old_post The post being cloed (Object) //**************************************************************************************************** $tmp_post = apply_filters('frontier_post_clone', $tmp_post, $old_post); // save post wp_update_post($tmp_post); //Get the updated post $new_post = get_post($new_post_id); //get all current post terms ad set them to the new post draft $taxonomies = get_object_taxonomies($old_post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag"); foreach ($taxonomies as $taxonomy) { $post_terms = wp_get_object_terms($old_post_id, $taxonomy, array('fields' => 'slugs')); wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false); } // Set featured image: $post_thumbnail_id = get_post_thumbnail_id($old_post_id); if (intval($post_thumbnail_id) > 0) { set_post_thumbnail($new_post_id, $post_thumbnail_id); } // Add/Update message frontier_post_set_msg(__("Post Cloned and ready edit", "frontier-post") . ": " . $new_post->post_title); frontier_post_set_msg(__("Post status set to Draft", "frontier-post")); frontier_user_post_list($fpost_sc_parms); } } }
/** * Thehe jQuery ajax call to create a new post. * Duplicates all the data including custom meta. * * @since 2.9 */ function m4c_duplicate_post() { // Get access to the database global $wpdb; // Check the nonce check_ajax_referer('m4c_ajax_file_nonce', 'security'); // Get variables $original_id = $_POST['original_id']; // Get the post as an array $duplicate = get_post($original_id, 'ARRAY_A'); $settings = get_mtphr_post_duplicator_settings(); // Modify some of the elements $duplicate['post_title'] = $duplicate['post_title'] . ' Copy'; // Set the status if ($settings['status'] != 'same') { $duplicate['post_status'] = $settings['status']; } // Set the post date $timestamp = $settings['timestamp'] == 'duplicate' ? strtotime($duplicate['post_date']) : current_time('timestamp', 0); $timestamp_gmt = $settings['timestamp'] == 'duplicate' ? strtotime($duplicate['post_date_gmt']) : current_time('timestamp', 1); if ($settings['time_offset']) { $offset = intval($settings['time_offset_seconds'] + $settings['time_offset_minutes'] * 60 + $settings['time_offset_hours'] * 3600 + $settings['time_offset_days'] * 86400); if ($settings['time_offset_direction'] == 'newer') { $timestamp = intval($timestamp + $offset); $timestamp_gmt = intval($timestamp_gmt + $offset); } else { $timestamp = intval($timestamp - $offset); $timestamp_gmt = intval($timestamp_gmt - $offset); } } $duplicate['post_date'] = date('Y-m-d H:i:s', $timestamp); $duplicate['post_date_gmt'] = date('Y-m-d H:i:s', $timestamp_gmt); $duplicate['post_modified'] = date('Y-m-d H:i:s', current_time('timestamp', 0)); $duplicate['post_modified_gmt'] = date('Y-m-d H:i:s', current_time('timestamp', 1)); // Remove some of the keys unset($duplicate['ID']); unset($duplicate['guid']); unset($duplicate['comment_count']); // Insert the post into the database $duplicate_id = wp_insert_post($duplicate); // Duplicate all the taxonomies/terms $taxonomies = get_object_taxonomies($duplicate['post_type']); foreach ($taxonomies as $taxonomy) { $terms = wp_get_post_terms($original_id, $taxonomy, array('fields' => 'names')); wp_set_object_terms($duplicate_id, $terms, $taxonomy); } // Duplicate all the custom fields $custom_fields = get_post_custom($original_id); foreach ($custom_fields as $key => $value) { if (is_array($value) && count($value) > 0) { foreach ($value as $i => $v) { add_post_meta($duplicate_id, $key, maybe_unserialize($v)); } } } echo 'Duplicate Post Created!'; die; // this is required to return a proper result }