Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created October 25, 2021 17:31
Show Gist options
  • Save trey8611/fe34c71f67486c1c5520167993a7fa69 to your computer and use it in GitHub Desktop.
Save trey8611/fe34c71f67486c1c5520167993a7fa69 to your computer and use it in GitHub Desktop.
[Dynamic Attachment Export Elements] Output separate attachment elements per-attachment.

This snippet finds the post with the most attachments in the database, then outputs and populates those in the export columns.

The snippet will need to be adjusted if you want it to only output attachments that are images.

function wpae_output_attachment_headers( $headers, $export_id ) { 
    global $wpdb;
    $sql = "SELECT `ID`, `post_parent`, COUNT(*)
    FROM `wp_posts`
    WHERE `post_type` = 'attachment'
    GROUP BY `post_parent`
    HAVING COUNT(*) > 1
    LIMIT 50";
    
    $result = $wpdb->get_row( $sql );
    if ( ! empty( $result ) ) {
        $result = json_decode( json_encode( (array) $result ), 1 );
        
        for ( $i = 0; $i < $result["COUNT(*)"]; $i++ ) {
            $field_name = 'attachment_url_' . $i;
            $headers[]  = $field_name;
        }
    }
    return $headers;
}

function wpae_output_attachment_data( $articles, $options, $export_id ) {
    global $wpdb;
    
    foreach ( $articles as $key => $article ) {
        $sql     = "SELECT `ID` from `{$wpdb->prefix}posts` WHERE `post_parent` = '" . $article['ID'] . "' AND `post_type` = 'attachment'";
        $results = $wpdb->get_results( $sql );
        
        if ( ! empty( $results ) ) {
            for ( $i = 0; $i < count( $results ); $i++ ) {
                $ikey                            = $i;
                $field_name                      = 'attachment_url_' . $i;
                $img_url                         = wp_get_attachment_url( $results[ $ikey ]->ID );
                $articles[ $key ][ $field_name ] = $img_url;
            }
        }
    }
    return $articles; // Return the array of records to export
}

add_filter( 'wp_all_export_csv_headers', 'wpae_output_attachment_headers', 10, 2 );
add_filter( 'wp_all_export_csv_rows', 'wpae_output_attachment_data', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment