Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Plugin Name: Field to Category
- * Description: Bulk copy field categories to taxonomy terms
- * Author: bcworkz
- * Version: 0.10 beta
- * License: GPL v3.0
- */
- // Define targeted taxonomy
- define('F2C_TAX', 'industry');
- // Define targeted post type
- define('F2C_TYPE', 'company');
- // Define targeted field name
- define('F2C_FIELD', 'industry');
- // Define how many posts to process in one go
- define('F2C_LIMIT', 3 );
- // Admin screen appears under "Tools"
- add_action('admin_menu', 'f2c_add_menu');
- function f2c_add_menu() {
- //$parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function
- add_submenu_page( 'tools.php' ,'Field to Category', 'Field to Category', 'edit_posts', 'f2c_admin', 'f2c_admin');
- }
- /* Display admin screen */
- function f2c_admin() {
- ?>
- <div style="max-width: 50em;">
- <h1>Field to Category</h1>
- This utility bulk copies values from custom field "<strong><?php echo F2C_FIELD; ?></strong>"
- of post type "<strong><?php echo F2C_TYPE; ?></strong>" and creates and/or assigns the
- values as "<strong><?php echo F2C_TAX; ?></strong>" taxonomy terms. This utility will convert
- <?php echo F2C_LIMIT; ?> posts in one go. You can rerun this utility to process
- more posts not yet converted.<br><br>
- After taxonomy terms are assigned to each post, the related custom field is removed from
- the post.<br><br>
- <strong>IMPORTANT!</strong> This version is for beta testing and could contain bugs. You are strongly
- urged to make a complete backup of the WordPress database before
- running this utility. The authors of this utility are not liable for claims of
- lost or corrupted data and any damages arising from such loss. No warranty is expressed or implied.
- Use at your own risk.<br><br>
- <form method="POST" action="<?php echo admin_url('admin-post.php?action=f2c_convert'); ?>" novalidate="novalidate">
- <input type="hidden" id="_wpnonce" name="_wpnonce" value="<?php echo wp_create_nonce('f2c_convert'); ?>" />
- <input type="submit" name="submit" id="submit" class="button button-primary" value="Let's do this!" />
- </form>
- </div>
- <?php
- }
- /* Form submit handler */
- add_action('admin_post_f2c_convert', 'f2c_do_conversion');
- function f2c_do_conversion() {
- // extend available time (sec)
- @set_time_limit ( 100 );
- ?>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Field to Category Conversion Results</title>
- <style>
- .main {
- max-width: 60em;
- margin: 2em 3em;
- }
- </style>
- </head>
- <body class="main">
- <h1>Field to Category Conversion Results</h1>
- <?php
- if ( ! check_admin_referer('f2c_convert')) wp_die('Invalid form data');
- if ( ! current_user_can('edit_posts')) wp_die('You do not have proper user capability to do this.');
- if ( ! empty( $_POST )) {
- // Reality check
- if ( ! taxonomy_exists( F2C_TAX )) wp_die('Taxonomy '. F2C_TAX .' does not exist, process aborted.');
- // Get a batch of posts
- $args = array(
- 'post_type' => F2C_TYPE,
- 'post_status' => 'publish',
- 'meta_query' => array(
- array(
- 'key' => F2C_FIELD,
- 'compare' => 'EXISTS',
- ),
- ),
- 'posts_per_page' => F2C_LIMIT,
- );
- $the_query = new WP_Query( $args );
- echo "Processing {$the_query->post_count} posts";
- flush();
- // Process the posts
- if ( $the_query->have_posts() ) {
- $done = array();
- while ( $the_query->have_posts() ) {
- $the_query->the_post();
- $field = get_post_meta( get_the_ID(), F2C_FIELD, true );
- // Extract terms from field
- $families = explode('|', trim( $field ));
- // Initialize vars
- $term_ids = array(); $abort = false;
- /* Collect term IDs for current post */
- foreach ( $families as $family ) {
- // extract child terms
- $terms = explode('>', trim( $family ));
- $parent = 0;
- foreach ( $terms as $term ) {
- if ('' != $term) {
- $term_id = f2c_maybe_insert_term( $term, $parent );
- if ( ! $term_id ) {
- echo "<br>\nInsert term '$term' failed<br>\n";
- flush();
- $abort = true;
- continue;
- } else {
- $term_ids[] = $term_id;
- $parent = $term_id;
- }
- }
- } // end foreach $terms
- } // end foreach $families
- /* Assign collected terms to current post */
- if ( ! $abort ) {
- if ( 0 < count( $term_ids )) {
- $inserted = wp_set_post_terms( get_the_ID(), $term_ids, F2C_TAX, true );
- if ( ! $inserted || is_wp_error( $inserted )) {
- echo "<br>\nCould not add terms to post ID ".get_the_ID().", field removal will not be done for this post<br>\n";
- flush();
- continue;
- }
- }
- // Add post ID to field removal list
- $done[] = get_the_ID();
- } else {
- echo "<br>\nCould not create terms for post ID ".get_the_ID().", term assignments aborted for this post<br>\n";
- flush();
- }
- // Show progress
- echo '.';
- } // end while have_posts
- /* Remove field of posts that have terms assigned */
- echo "<br>\nConversion complete. Deleting the fields";
- flush();
- foreach ( $done as $post_ID ) {
- // Remove field
- if ( ! delete_post_meta( $post_ID, F2C_FIELD )) {
- echo "<br>\nError removing custom field for post ID $post_ID<br>\n";
- flush();
- }
- echo '.';
- } // foreach $done
- echo "<br>\nFields removed<br>\n";
- } else {
- // No posts found
- echo "<br>\nNo '". F2C_TAX ."' posts with the field '". F2C_FIELD ."' were found.<br>\n";
- } // end if have_posts
- echo "Done processing.<br>\nUse your browser's back button to return to the admin screen.<br>\n";
- } else {
- echo "You need to use the 'Let's do this!' button to run this utility.";
- }// end if 'POST'
- ?>
- </body>
- </html>
- <?php
- exit;
- }
- /**
- * get term ID if term exists, insert new term if not
- * string $name Name of term ID to get (not slug), required
- * int $parent Term ID of parent term, default 0 (top level)
- * return int|bool Term ID | false if unable to insert new term
- */
- function f2c_maybe_insert_term( $name, $parent = 0 ) {
- $term = get_terms([
- 'taxonomy' => F2C_TAX,
- 'name' => $name,
- 'hide_empty' => false,
- /*'child_of' => $parent,*/
- ]);
- //create term as needed
- if ( 0 == count( $term )) {
- $success = wp_insert_term( $name, F2C_TAX, ['parent' => $parent,]);
- if ( is_wp_error( $success )) return false;
- return (int) $success['term_id'];
- } else {
- return (int) $term[0]->term_id;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement