public
Last active

'price' sortable column example

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
<?php
 
// Register the column
function price_column_register( $columns ) {
$columns['price'] = __( 'Price', 'my-plugin' );
return $columns;
}
add_filter( 'manage_edit-post_columns', 'price_column_register' );
 
// Display the column content
function price_column_display( $column_name, $post_id ) {
if ( 'price' != $column_name )
return;
$price = get_post_meta($post_id, 'price', true);
if ( !$price )
$price = '<em>' . __( 'undefined', 'my-plugin' ) . '</em>';
echo $price;
}
add_action( 'manage_posts_custom_column', 'price_column_display', 10, 2 );
 
// Register the column as sortable
function price_column_register_sortable( $columns ) {
$columns['price'] = 'price';
return $columns;
}
add_filter( 'manage_edit-post_sortable_columns', 'price_column_register_sortable' );
 
function price_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'price' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' => 'price',
'orderby' => 'meta_value_num'
) );
}
return $vars;
}
add_filter( 'request', 'price_column_orderby' );

This is pretty awesome! I'll have to give it a try with my taxonomy short description plugin. You've just invalidated my argument here: http://core.trac.wordpress.org/ticket/13650 Thanks for posting :)

By default first click on column name will sort ascending. I needed it to be descending first and after some poking in core that can be set by changing $columns['price'] = 'price'; to $columns['price'] = array( 'price', true );

@Rarst: Thank you so much for sharing that tweak.

The request filter is applied globally so its a good practice to apply it where required:-

global $pagenow, $post_type;

if (is_admin() && $pagenow == 'edit.php' && $post_type == 'product' && isset($_GET['orderby']) && $_GET['orderby'] == 'sponsor')
{
$Request = array_merge($Request, array(
'meta_key' => 'fh_sponsor_level',
'orderby' => 'meta_value_num'
));
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.