Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created May 22, 2020 09:38
Show Gist options
  • Save maheshwaghmare/016c5fadf1c81a44cfba11656832c50e to your computer and use it in GitHub Desktop.
Save maheshwaghmare/016c5fadf1c81a44cfba11656832c50e to your computer and use it in GitHub Desktop.
WordPress - Add custom sortable columns for custom post type.
<?php
/**
* Add custom column
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*/
if( ! function_exists( 'prefix_add_custom_column' ) ) :
function prefix_add_custom_column( $columns = array() ) {
$new_columns = array(
'portfolio-type' => __( 'Portfolio Type', 'textdomain' ),
);
return wp_parse_args( $new_columns, $columns );
}
add_filter('manage_astra-portfolio_posts_columns', 'prefix_add_custom_column', 10);
endif;
/**
* Column markup
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @param string Column slug.
* @param integer Post ID.
* @return void
*/
if( ! function_exists( 'prefix_custom_column_markup' ) ) :
function prefix_custom_column_markup( $column_name = '', $post_id = 0 ) {
if ( $column_name == 'portfolio-type') {
echo get_post_meta( $post_id, 'astra-portfolio-type', true );
}
}
add_action('manage_astra-portfolio_posts_custom_column', 'prefix_custom_column_markup', 10, 2);
endif;
/**
* Add Sortable Column
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @param array $columns Columns.
* @return array
*/
if( ! function_exists( 'prefix_add_custom_sortable_column' ) ) :
function prefix_add_custom_sortable_column( $columns = array() ) {
$new_columns = array(
'portfolio-type' => 'portfolio-type',
);
return wp_parse_args( $new_columns, $columns );
}
add_filter('manage_edit-astra-portfolio_sortable_columns', 'prefix_add_custom_sortable_column' );
endif;
/**
* Perform order by custom colum.
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*
* @param array $columns Columns.
* @return array
*/
if( ! function_exists( 'prefix_perform_custom_sortable_order' ) ) :
function prefix_perform_custom_sortable_order( $query ) {
if( ! is_admin() || ! $query->is_main_query() ) {
return;
}
$orderby = $query->get( 'orderby');
if ( 'portfolio-type' == $orderby ) {
$query->set( 'meta_key', 'astra-portfolio-type' );
$query->set( 'orderby', 'meta_value' );
}
}
add_action( 'pre_get_posts', 'prefix_perform_custom_sortable_order' );
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment