Last active
December 10, 2015 14:49
-
-
Save lgedeon/4449965 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements taxonomy command. | |
* | |
* @package wp-cli | |
*/ | |
class Taxonomy_Command extends WP_CLI_Command { | |
/** | |
* Exports all terms from a taxonomy. | |
* | |
* @synopsis <taxonomy-name> | |
*/ | |
function export( $args, $assoc_args ) { | |
global $wpdb; | |
$taxonomy_name = isset( $args['0'] ) ? $args['0'] : 'post_tags'; | |
$output_header = isset( $args['1'] ) ? (bool) $args['1'] : true; | |
// set max length for string of object ids - in number of chars not number of ids | |
// limiting this make the returned array smaller so we can go farther without blowing up | |
$query = "SET SESSION group_concat_max_len = 80"; | |
mysql_query( $query, $wpdb->dbh ); | |
$query = "SELECT tr.object_id, tr.term_taxonomy_id, tt.*, t.*, GROUP_CONCAT(tr.object_id ORDER BY tr.object_id DESC) AS posts FROM $wpdb->terms AS t INNER JOIN ($wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt) ON (tr.term_taxonomy_id = tt.term_taxonomy_id AND t.term_id = tt.term_id) WHERE tt.taxonomy IN ('" . $taxonomy_name . "') GROUP BY tr.term_taxonomy_id"; | |
$rows = $wpdb->get_results($query, ARRAY_A ); | |
$query = "SELECT ID, post_title FROM $wpdb->posts"; | |
$titles = $wpdb->get_results($query, OBJECT_K ); | |
$file = fopen('taxonomylist.csv', 'w'); | |
foreach ( $rows as $row ) { | |
$post_ids = array_slice( explode( ',', $row['posts'], 6 ), 0, 5 ); | |
$posts = array(); | |
foreach ( $post_ids as $post_id ) { | |
$title = isset( $titles[$post_id]->post_title ) ? $titles[$post_id]->post_title : ''; | |
$posts[] = "$title http://techcrunch.com/?p=$post_id"; | |
} | |
$row['posts'] = implode( ', ', $posts ); | |
$row = array_intersect_key( $row, array_flip( array( 'term_id', 'name', 'slug', 'parent', 'count', 'posts' ) ) ); | |
if ( $output_header ) { | |
fputcsv( $file, array_keys( $row ) ); | |
$output_header = false; | |
} | |
fputcsv( $file, $row ); | |
//fputcsv( $file, array( serialize( $term ) ) ); | |
} | |
fclose($file); | |
} | |
} | |
WP_CLI::add_command( 'taxonomy', 'Taxonomy_Command' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment