Skip to content

Instantly share code, notes, and snippets.

@Crocoblock
Last active March 3, 2024 17:54
Show Gist options
  • Save Crocoblock/fd65c5f86c727ec3513f7a425ef0d32d to your computer and use it in GitHub Desktop.
Save Crocoblock/fd65c5f86c727ec3513f7a425ef0d32d to your computer and use it in GitHub Desktop.
Add custom admin column callback to post type
<?php
/**
* Functions may be used as a custom post type column callback
*/
/**
* If the function name does not contain 'jet_engine_custom_cb' prefix,
* the callback takes only two arguments: column name and post ID
* You may use such callbacks if you do not need to specify any arguments
* Example: show post author in a column
*/
function show_post_author_ac( $column, $post_id ) {
$post = get_post( $post_id );
$author_id = $post->post_author;
$author = get_user_by( 'ID', $author_id );
if ( ! $author ) {
return;
}
return $author->user_nicename;
}
/**
* If the function name contains 'jet_engine_custom_cb' prefix, callback may take any number of arguments.
* When using that callback in CPT, specify its arguments as follows:
* jet_engine_custom_cb_modified_date::arg1::arg2::arg3 (any number of arguments, separated by '::')
* Example: show post modified date with the ability to specify the format
*/
function jet_engine_custom_cb_modified_date( $post_id, $format = 'd.m.Y' ) {
$post = get_post( $post_id );
if ( ! $post ) {
return;
}
$modified = $post->post_modified;
$modified = strtotime( $modified );
$modified = wp_date( $format, $modified );
return $modified;
}
/**
* For convenience, callbacks may be added to the list of predefined callbacks
* using the filter 'jet-engine/post-type/predifined-columns-cb-for-js', which filters the array of callbacks
*/
add_filter( 'jet-engine/post-type/predifined-columns-cb-for-js', function( $column_callbacks ) {
$column_callbacks[ 'jet_engine_custom_cb_modified_date' ] = array(
'description' => __( 'Get post modified date', 'jet-engine' ),
'args' => array(
'format' => array(
'label' => __( 'Format', 'jet-engine' ),
'description' => __( 'Date format', 'jet-engine' ),
'value' => 'd.m.Y',
),
),
);
$column_callbacks[ 'show_post_author_ac' ] = array(
'description' => __( 'Show post author', 'jet-engine' ),
);
return $column_callbacks;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment