Skip to content

Instantly share code, notes, and snippets.

@hatsumatsu
Last active March 12, 2019 11:56
Show Gist options
  • Save hatsumatsu/6583d65a3be468026bf0f563942b2f38 to your computer and use it in GitHub Desktop.
Save hatsumatsu/6583d65a3be468026bf0f563942b2f38 to your computer and use it in GitHub Desktop.
Custom query vars, rewrite rules and admin columns
/**
* Make a custom permalink structure on top of a custom post type for yearly archives
* mapping the year to a meta field
*/
/**
* Register a custom query variable in our example 'event_year'
* This can later be used in WP_Query like `get_query_var( 'event_year' )`
*
* @param array $query_vars query vars
* @return array $query_vars query vars
*/
function modifyQueryVars( $query_vars ) {
$query_vars[] = 'event_year';
return $query_vars;
}
add_filter( 'query_vars', 'modifyQueryVars' );
/**
* Register a custom rewrite rules on top of a custom post type for event year archives
* events/{year}
*/
function modifyRewriteRules() {
// by year
add_rewrite_rule(
'events/([0-9]{4})/?$',
'index.php?post_type=events&event_year=$matches[1]',
'top'
);
}
add_action( 'init', 'modifyRewriteRules' );
/**
* Add a custom admin column with data from the `event_year` meta field
* and make the post list sortable by its values
*/
/**
* Add a custom column to the events list
* Note: The name of Wordpress hook we use contains the post type!!!
*
* @param array $columns columns of the edit events list
* @return array $columns
*/
function modifyAdminColumns( $columns ) {
$columns[ 'event_date' ] = __( 'Event Date', 'your-text-domain' );
return $columns;
}
add_filter( 'manage_edit-events_columns', 'modifyAdminColumns' );
/**
* Populate the column with the actual values for each post
* Note: The name of Wordpress hook we use contains the post type!!!
*
* @param int $column_name name of the columns to render values in.
* @param int $post_id post ID
*/
function populateCustomAdminColumns( $column_name, $post_id ) {
if ( 'event_date' != $column_name ) {
return;
}
// get the value of your field...
if( $value = get_post_meta( $post_id, 'event-date', true ) ) {
echo $value;
} else {
echo __( 'None', 'your-text-domain' );
}
}
add_action( 'manage_events_posts_custom_column', 'populateCustomAdminColumns', 10, 2 );
/**
* Enable sorting the post list by our custom columns
* Note: The name of Wordpress hook we use contains the post type!!!
*
* @param array $columns columns of the edit events list
* @return array $columns
*/
function ModifySortableAdminColumns( $columns ) {
$columns[ 'event_date' ] = 'event_date';
return $columns;
}
add_filter( 'manage_edit-events_sortable_columns', 'ModifySortableAdminColumns' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment