TablePress is a powerful plugin for WordPress that allows you to create and manage tables. It has a nice UI and works similar to Excel. Tables can contain any type of data, even formulas. It features sorting, pagination, filtering, and more. However, TablePress only supports inserting the tables into posts, pages via shortcode, which makes it less flexible if you want to display the tables elsewhere. In this post, we’ll show you how to use Meta Box to create a custom field for TablePress and display the selected table in a custom location in your page templates.

Prepare

Before going into the details, don’t forget to install both TablePress and Meta Box. Then go to Dashboard → TablePress and create some tables.

For the demo purpose, I created 2 tables for customer contacts and company offices as shown in the screenshot below:

tablepress tables

Each table has a unique ID 1, 2, etc. To insert tables into posts or pages, TablePress provides a shortcode:

[table id=1]

The plugin also has a button in the WordPress editor, that shows a list of tables. You can select which table to insert into the post content.

While this approach is really simple and easy to use, it allows you to insert tables only into the post content. In other places, you have to manually run the shortcode.

What other places you might ask? Well, if you build a landing page, you might need multiple content sections rather than just single content (post content). In those sections, you want to select which table to show. And the plugin can’t help you to do that.

That’s where Meta Box comes to rescue.

Integrating TablePress with Meta Box

Meta Box helps you create WordPress custom fields with simple lines of code. The plugin is lightweight and powerful. We’ll see how to use it to implement a list of TablePress’s tables for users to select. Then we’ll find out how to show the table in the frontend.

Creating a custom field for TablePress tables

TablePress creates a custom post type tablepress_table to store table data, where:

  • Post title is the table title
  • Post excerpt is the table description
  • Post content is the JSONified array of rows content (very interesting).

Because TablePress is using a custom post type, it’s reasonable to create a custom field with post field type in Meta Box. The post field allows you to select one or multiple posts of any custom post type. This field has several settings that can be displayed as a: simple select dropdown, checkbox list, or beautiful select dropdown with the select2 library.

Let’s follow Meta Box documentation and create a first meta box with one custom field for TablePress like this (copy and paste the following code to your theme’s functions.php file):

add_filter( 'rwmb_meta_boxes', function( $meta_boxes) {
    $meta_boxes[] = array(
        'title' => 'TablePress Tables',
        'fields' => array(
            array(
                'name'      => 'Select a table',
                'id'        => 'table',
                'type'      => 'post',
                'post_type' => 'tablepress_table',
            ),
        ),
    );
    return $meta_boxes;
} );

Creating a custom field with Meta Box is quite simple: simply pass an array with the field settings. For post, you need to set type to post and set the post_type to the custom post type, which is tablepress_table. The id will be the meta key when saving to the database.

Go to create a new post and you will see the meta box appeared below the post content like this:

wordpress custom field for table

Simply select the table and save the post!

Display table in the frontend

When saving the post, Meta Box saves the post ID in the custom field. However, TablePress doesn’t use post ID for table ID. So we have to find out a way to retrieve the table ID from post ID.

Fortunately, the connection between table ID and post ID is stored in the option tablepress_tables in the wp_options table in the database, which is a JSONified array (from a developer perspective, I wonder why TablePress doesn’t store values as a serialized array, which is the standard WordPress way).

And it has the following structure:

Array (
    [last_id]    => 2
    [table_post] => Array (
        [1] => 567
        [2] => 570
    )
)

So, the code to get table ID looks like this (copy and paste it into your theme’s functions.php file):

function prefix_get_tablepress_table_id( $post_id ) {
    $tables = get_option( 'tablepress_tables' );
    $tables = json_decode( $tables, true );
    if ( empty( $tables['table_post'] ) ) {
        return false;
    }
    $posts = array_flip( $tables['table_post'] );
    return isset( $posts[$post_id] ) ? $posts[$post_id] : false;
}

When we have the table ID, we can simply run the shortcode to show the TablePress table:

$post_id = rwmb_meta( 'table' ); // Get table post ID via Meta Box helper function.
$table_id = prefix_get_tablepress_table_id( $post_id );
$shortcode = "[table id='$table_id' /]";
echo do_shortcode( $shortcode );

Simply copy this code and paste it into your template file. If you are creating a landing page, then open your page template and paste the code in the section where you want the table to show.

Note that, we use rwmb_meta() helper function to get the custom field value, which is the post ID in this case. Then we call the prefix_get_tablepress_table_id that we created before to retrieve the table ID. Then run the shortcode.

However, we can optimize the code a little bit. Running shortcode directly is not very fast because it forces WordPress to look through a long list of shortcodes’ regular expressions. And regular expression is never fast.

So, we can use TablePress template tag to do that:

$post_id = rwmb_meta( 'table' ); // Get table post ID via Meta Box helper function.
$table_id = prefix_get_tablepress_table_id( $post_id );
$args = array(
    'id'             => $table_id,
    'use_datatables' => true,
    'print_name'     => false,
);
tablepress_print_table( $args );

Now the job of displaying table runs directly through TablePress, no shortcode parsing anymore. That helps increase the performance of your website.

Conclusion

With a little help from Meta Box and understanding how TablePress saves its data, we can make the editing screen more user-friendly. Our users can display tables where they want, without copying the shortcodes around.

We hope this tutorial helps you use Meta Box more flexible, especially when integrating with other plugins. If you have any suggestion, please let us know in the comments.


Also published on Medium.

Leave a Reply