Skip to content

WordPress Integration

Ankit Pokhrel edited this page Jul 31, 2019 · 3 revisions

Tus Server

A good way to setup tus server in WordPress is to create a small plugin with all required dependencies.

  1. Create a folder called wp-tus inside plugins folder.

  2. Go to newly created folder in your terminal and run composer init. This will create a composer.json file.

  3. Add ankitpokhrel/tus-php as your dependency.

    $ composer require ankitpokhrel/tus-php
  4. Create a file called wp-tus.php inside that directory.

  5. Bootstrap WordPress plugin.

    // wp-tus.php
    
    /**
     * Plugin Name: WP Tus
     * Plugin URI: <plugin URI>
     * Description: Tus Server in WordPress.
     * Version: 0.0.0
     * Author: <author name>
     * Author URI: <author URI>
     * License: GPL2 or later
     * License URI: http://www.gnu.org/licenses/gpl-2.0.html
     */
    
     // Avoid direct calls to this file.
     if ( ! defined( 'ABSPATH' )) {
         header( 'Status: 403 Forbidden' );
         header( 'HTTP/1.1 403 Forbidden' );
    
         die( 'Access Forbidden' );
     }
    
     // ...
  6. Load required dependencies.

     // wp-tus.php
    
     // ...
     
     require __DIR__ . '/vendor/autoload.php';
  7. Add routes to handle server request.

    // wp-tus.php
    
    // ...
    
    add_action( 'init', function () {
       add_rewrite_tag( '%tus%', '([^&]+)' );
       add_rewrite_rule( '^wp-tus/([^/]*)/?', 'index.php?tus=$matches[1]', 'top' );
    } );
  8. Send response from tus server if request comes to tus endpoint.

    // wp-tus.php
    
    // ...
    
    add_action('parse_request', function ( $wp ) {
        // Return if it is a normal request.
        if ( $wp->query_vars['pagename'] !== 'wp-tus' && empty( $wp->query_vars['tus'] ) ) {
            return;
        }
    
        $server = new \TusPhp\Tus\Server(); // Pass `redis` as first argument if you are using redis.
    
        $server
            ->setApiPath( '/wp-tus' ) // tus server endpoint.
            ->setUploadDir( __DIR__ . '/../uploads' );
    
        $response = $server->serve();
    
        $response->send();
    } );
  9. Activate your plugin from WordPress admin panel.

IMPORTANT: Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screen, Select Settings -> Permalinks and just click Save Changes button without changing anything.

You can now access tus server endpoints at http://yourapp.dev/wp-tus or http://yourapp.dev/wp-tus/.

Clone this wiki locally