Instantly share code, notes, and snippets.

Embed
What would you like to do?
composer require a5hleyrich/wp-queue
class PostSaveJob extends \WP_Queue\Job
{
protected $postId;
public function __construct( $postId )
{
$this->postId = $postId;
}
public function handle()
{
$post = get_post($this->postId );
}
}
class PostSaveJob extends \WP_Queue\Job
{
protected $postId;
public function __construct( $postId )
{
$this->postId = $postId;
}
public function handle() {
$post = get_post( $this->postId );
if( ! in_array( get_post_type($post), [ 'post', 'page' ]) ){
return;
}
$controller = new \WP_REST_Posts_Controller( 'post' );
$route = 'wp/v2/posts/' . $this->postId;
$request = new \WP_REST_Request('GET', $route);
$request->set_param( 'id', $this->postId );
$response = $controller->get_item($request );
$name = sprintf( '%s/posts/%s.json', __DIR__, $post->post_name );
file_put_contents( $name, json_encode( $response ) );
return $name;
}
}
$fileName = ( new \calderawp\WordPressPlugin\Jobs\PostSaveJob( $postId ) )->handle();
class PostSaveJobTest extends TestCase {
public function testSaves(){
$postName = 'foo';
$postId = wp_insert_post( ['post_content' => 'fff', 'post_type' => 'post', 'post_status' => 'publish', 'post_name' => $postName ] );
$fileName = ( new \calderawp\WordPressPlugin\Jobs\PostSaveJob( $postId ) )->handle();
$this->assertTrue( file_exists( $fileName ) );
}
}
add_action( 'save_post', function( $postId ) {
wp_queue()->push( new PostSaveJob( $postId ) );
});
add_action( 'save_post', function( $postId ) {
wp_queue()->push( new PostSaveJob( $postId ), 600 );
});
add_action( 'plugins_loaded', function(){
wp_queue()->cron();
});
add_filter( 'wp_queue_default_connection', function() {
return 'sync';
} );
function workQueue( $jobs = 10, $attemptsPerJob = 3 ){
//Get a properly configured queue
$queue = wp_queue();
//Get the worker for the queue
$worker = $queue->worker($attemptsPerJob);
//Loop through jobs in queue until we've done the number passed in $jobs
// or no jobs left to run
$totalJobs = 0;
while( $worker->process() && $jobs <= $totalJobs ){
$totalJobs++;
}
//Work the queue and
return rest_ensure_response( [ 'totalJobs' => $totalJobs ] );
}
add_action( 'rest_api_init', function(){
register_rest_route( 'hi-roy', 'queue/run', [
'methods' => ['POST', 'GET' ],
'callback' => 'workQueue'
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment