Advertisement
bcworkz

field-to-cat.php

Apr 1st, 2020
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.55 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Plugin Name: Field to Category
  4.  * Description: Bulk copy field categories to taxonomy terms
  5.  * Author: bcworkz
  6.  * Version: 0.10 beta
  7.  * License: GPL v3.0
  8.  */
  9.  
  10. // Define targeted taxonomy
  11. define('F2C_TAX', 'industry');
  12.  
  13. // Define targeted post type
  14. define('F2C_TYPE', 'company');
  15.  
  16. // Define targeted field name
  17. define('F2C_FIELD', 'industry');
  18.  
  19. // Define how many posts to process in one go
  20. define('F2C_LIMIT', 3 );
  21.  
  22. // Admin screen appears under "Tools"
  23. add_action('admin_menu', 'f2c_add_menu');
  24. function f2c_add_menu() {
  25.                     //$parent_slug,   $page_title,        $menu_title,       $capability,  $menu_slug,   $function
  26.     add_submenu_page( 'tools.php' ,'Field to Category', 'Field to Category', 'edit_posts', 'f2c_admin', 'f2c_admin');
  27. }
  28.  
  29. /* Display admin screen */
  30. function f2c_admin() {
  31. ?>
  32.     <div style="max-width: 50em;">
  33.         <h1>Field to Category</h1>
  34.         This utility bulk copies values from custom field "<strong><?php echo F2C_FIELD; ?></strong>"
  35.         of post type "<strong><?php echo F2C_TYPE; ?></strong>" and creates and/or assigns the
  36.         values as "<strong><?php echo F2C_TAX; ?></strong>" taxonomy terms. This utility will convert
  37.         <?php echo F2C_LIMIT; ?> posts in one go. You can rerun this utility to process
  38.         more posts not yet converted.<br><br>
  39.  
  40.         After taxonomy terms are assigned to each post, the related custom field is removed from
  41.         the post.<br><br>
  42.  
  43.         <strong>IMPORTANT!</strong> This version is for beta testing and could contain bugs. You are strongly
  44.         urged to make a complete backup of the WordPress database before
  45.         running this utility. The authors of this utility are not liable for claims of
  46.         lost or corrupted data and any damages arising from such loss. No warranty is expressed or implied.
  47.         Use at your own risk.<br><br>
  48.  
  49.         <form method="POST" action="<?php echo admin_url('admin-post.php?action=f2c_convert'); ?>" novalidate="novalidate">
  50.             <input type="hidden" id="_wpnonce" name="_wpnonce" value="<?php echo wp_create_nonce('f2c_convert'); ?>" />
  51.             <input type="submit" name="submit" id="submit" class="button button-primary" value="Let's do this!" />
  52.         </form>
  53.     </div>
  54.  
  55. <?php
  56. }
  57.  
  58. /* Form submit handler */
  59. add_action('admin_post_f2c_convert', 'f2c_do_conversion');
  60. function f2c_do_conversion() {
  61.     // extend available time (sec)
  62.     @set_time_limit ( 100 );
  63.  
  64. ?>
  65.     <!DOCTYPE html>
  66.     <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
  67.     <head>
  68.     <meta charset="utf-8" />
  69.     <meta name="viewport" content="width=device-width, initial-scale=1">
  70.     <title>Field to Category Conversion Results</title>
  71.     <style>
  72.         .main {
  73.             max-width: 60em;
  74.             margin: 2em 3em;
  75.         }
  76.     </style>
  77.     </head>
  78.     <body class="main">
  79.     <h1>Field to Category Conversion Results</h1>
  80.  
  81. <?php
  82.     if ( ! check_admin_referer('f2c_convert')) wp_die('Invalid form data');
  83.     if ( ! current_user_can('edit_posts')) wp_die('You do not have proper user capability to do this.');
  84.     if ( ! empty( $_POST )) {
  85.         // Reality check
  86.         if ( ! taxonomy_exists( F2C_TAX )) wp_die('Taxonomy '. F2C_TAX .' does not exist, process aborted.');
  87.  
  88.         // Get a batch of posts
  89.         $args = array(
  90.             'post_type' => F2C_TYPE,
  91.             'post_status' => 'publish',
  92.             'meta_query' => array(
  93.                 array(
  94.                     'key'     => F2C_FIELD,
  95.                     'compare' => 'EXISTS',
  96.                 ),
  97.             ),
  98.             'posts_per_page' => F2C_LIMIT,
  99.         );
  100.         $the_query = new WP_Query( $args );
  101.         echo "Processing {$the_query->post_count} posts";
  102.         flush();
  103.  
  104.         // Process the posts
  105.         if ( $the_query->have_posts() ) {
  106.             $done = array();
  107.             while ( $the_query->have_posts() ) {
  108.                 $the_query->the_post();
  109.  
  110.                 $field = get_post_meta( get_the_ID(), F2C_FIELD, true );
  111.  
  112.                 // Extract terms from field
  113.                 $families = explode('|', trim( $field ));
  114.                 // Initialize vars
  115.                 $term_ids = array(); $abort = false;
  116.  
  117.                 /* Collect term IDs for current post */
  118.                 foreach ( $families as $family ) {
  119.                     // extract child terms
  120.                     $terms = explode('>', trim( $family ));
  121.                     $parent = 0;
  122.                     foreach ( $terms as $term ) {
  123.                         if ('' != $term) {
  124.                             $term_id = f2c_maybe_insert_term( $term, $parent );
  125.                             if ( ! $term_id ) {
  126.                                 echo "<br>\nInsert term '$term' failed<br>\n";
  127.                                 flush();
  128.                                 $abort = true;
  129.                                 continue;
  130.                             } else {
  131.                                 $term_ids[] = $term_id;
  132.                                 $parent = $term_id;
  133.                             }
  134.                         }
  135.                     } // end foreach $terms
  136.                 } // end foreach $families
  137.  
  138.                 /* Assign collected terms to current post */
  139.                 if ( ! $abort ) {
  140.                     if ( 0 < count( $term_ids )) {
  141.                         $inserted = wp_set_post_terms( get_the_ID(), $term_ids, F2C_TAX, true );
  142.                         if ( ! $inserted || is_wp_error( $inserted )) {
  143.                             echo "<br>\nCould not add terms to post ID ".get_the_ID().", field removal will not be done for this post<br>\n";
  144.                             flush();
  145.                             continue;
  146.                         }
  147.                     }
  148.                     // Add post ID to field removal list
  149.                     $done[] = get_the_ID();
  150.                 } else {
  151.                     echo "<br>\nCould not create terms for post ID ".get_the_ID().", term assignments aborted for this post<br>\n";
  152.                     flush();
  153.                 }
  154.                 // Show progress
  155.                 echo '.';
  156.             } // end while have_posts
  157.  
  158.             /* Remove field of posts that have terms assigned */
  159.             echo "<br>\nConversion complete. Deleting the fields";
  160.             flush();
  161.             foreach ( $done as $post_ID ) {
  162.                 // Remove field
  163.                 if ( ! delete_post_meta( $post_ID, F2C_FIELD )) {
  164.                     echo "<br>\nError removing custom field for post ID $post_ID<br>\n";
  165.                     flush();
  166.                 }
  167.                 echo '.';
  168.             } // foreach $done
  169.             echo "<br>\nFields removed<br>\n";
  170.         } else {
  171.             // No posts found
  172.             echo "<br>\nNo '". F2C_TAX ."' posts with the field '". F2C_FIELD ."' were found.<br>\n";
  173.         } // end if have_posts
  174.  
  175.         echo "Done processing.<br>\nUse your browser's back button to return to the admin screen.<br>\n";
  176.     } else {
  177.         echo "You need to use the 'Let's do this!' button to run this utility.";
  178.     }// end if 'POST'
  179. ?>
  180. </body>
  181. </html>
  182. <?php
  183.     exit;
  184. }
  185.  
  186. /**
  187.  *  get term ID if term exists, insert new term if not
  188.  *  string $name        Name of term ID to get (not slug), required
  189.  *  int $parent         Term ID of parent term, default 0 (top level)
  190.  *  return int|bool     Term ID | false if unable to insert new term
  191.  */
  192. function f2c_maybe_insert_term( $name, $parent = 0 ) {
  193.     $term = get_terms([
  194.         'taxonomy'      => F2C_TAX,
  195.         'name'          => $name,
  196.         'hide_empty'    => false,
  197.         /*'child_of'    => $parent,*/
  198.     ]);
  199.     //create term as needed
  200.     if ( 0 == count( $term )) {
  201.         $success = wp_insert_term( $name, F2C_TAX, ['parent' => $parent,]);
  202.         if ( is_wp_error( $success )) return false;
  203.         return (int) $success['term_id'];
  204.     } else {
  205.         return (int) $term[0]->term_id;
  206.     }
  207. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement