Skip to content

Custom Post Columns

Henner Renardi Setyono edited this page Aug 16, 2024 · 8 revisions
px_override_post_columns($post_type, $columns);

Override all the post type's columns

PARAMETER

$post_type (string)

$columns (array) - Collection of column's array in $slug => $args format. $slug is unique key and has some reserved name. Each $args contains:

  • label (string) - The column's label. Default is the titleized slug.

  • content (callable) - Callback to return string content. Accepts two parameters:

    • $post (WP_Post)
    • $fields (array) - all custom fields, will use ACF if installed.
  • orderby (string) - The columns to sort by.

    Possible values: 'ID', 'author', 'title', 'date', 'rand', 'comment_count'

    To sort by custom field, use 'meta_value__xxx' or 'meta_value_num__xxx'. Replace 'xxx' with the field name.

  • order (string) - The initial sorting order, either 'asc' or 'desc'. Default: 'desc'

  • icon (string) - Replace the column name with Icon from dashicons.

EXAMPLE

We have a Product table and want to add "Title", "Price", and "Discount" column like this:

Edje WordPress - Complex Column

px_override_post_columns('product', [
  'title' => [
    'label' => 'Name',
    // 'title' is a reserved column, therefore the content is automatically filled
  ],
  'price' => [
    'label' => 'Price',
    'content' => function ($post, $fields) {
      return $fields['price'];
    }
  ],
  'discount' => [
    'name' => 'Discount',
    'content' => function ($post, $fields) { 
      $discount = $fields['discount'] ?? 1;
      $price = $fields['price'] ?? null;
      if ($price) {
         $total = $price - ($price * $discount / 100);
         $saving = $price - $total;
         return $discount . '% Discount - You save ' . $saving;
      }
      return '';
    }
  ],
]);

Reserved Column Slugs

Using one of the reserved slug means the content is automatically populated. They are:

  1. Built-in Columns

    • title - Post's title with edit, quick edit, etc links
    • author
    • thumbnail - Featured image 75x75 size
    • content - The excerpt
    • comments - Comment count
    • date - Published date
  2. Taxonomy Slug like category.

    • List all terms in comma-separated string.