Ajax in admin. Populating as items processed.
-
I am going to process some custom post type posts in the WP admin and want to list the title of each post as it is processed using Ajax. I have been searching the net and have pulled together bit’s and pieces of code but can’t get it to work. I have it populating once the whole loop as completed but I can’t work out how to display each post as it is processed.
Can anyone point me in the right direction please. This is the code I have so far.
/** * Add he page to the WP admin menu and set callbacks. */ add_action('admin_menu', 'mce_import_ee_add_plugin_page'); function mce_import_ee_add_plugin_page() { global $mce_import_settings; $mce_import_settings = add_options_page('MCE Import EE', 'MCE Import EE', 'manage_options', 'mce-import-ee', 'mce_import_ee_create_admin_page'); } /** * Display the Admin oage. */ function mce_import_ee_create_admin_page() { ?> <div class="wrap"> <?php settings_errors();?> <h2>MCE Import EE</h2> <p>Import Event Espresso posts into MCE</p> <?php $ee_args = array( 'post_type' => 'espresso_event', 'numberposts' => -1, ); $ee_posts = get_posts( $ee_args ); $ee_posts_count = count( $ee_posts ); ?> <p>Number of EE Posts: <?php echo $ee_posts_count; ?></p> <button id="import-start" type="submit" class="button button-primary" formaction="" formmethod="post">Import Courses</button> <ul id="post-listing"></ul> </div> <?php } add_action( 'admin_footer', 'mce_action_javascript' ); function mce_action_javascript() { $mce_nonce = wp_create_nonce( "mce-import-ee" ); global $mce_import_settings; ?> <script> jQuery( document ).ready( function( $ ) { $('#import-start').click( function () { $.ajax({ url: ajaxurl, method: 'POST', data: { action: 'mce-import', security: '<?php echo $mce_nonce; ?>;' }, xhr: function(){ var xhr = $.ajaxSettings.xhr(); xhr.onprogress = function( evt ){ $('#post-listing').html(evt.currentTarget.responseText); }; return xhr; } }); return false; }); }); </script> <?php } // The function that handles the AJAX request add_action( 'wp_ajax_mce-import', 'my_action_callback' ); function my_action_callback() { /*if ( !check_ajax_referer( 'mce-import-eeX', 'security' ) ) die( 'Permission check failed' );*/ $ee_args = array( 'post_type' => 'espresso_event', 'numberposts' => 5, ); $ee_posts = get_posts( $ee_args ); if ( $ee_posts ) { foreach ( $ee_posts as $ee_post ) { echo '<li>' . get_the_title( $ee_post->ID ) . '</li>'; /*ob_flush(); flush(); sleep(2);*/ } } else { echo '<li>No Results</li>'; } die(); // this is required to return a proper result }
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Ajax in admin. Populating as items processed.’ is closed to new replies.