Question

I got a custom post type and link custom posts (issues of a magazine) to the main posts (articles) with relationship ACF. I registered a custom admin column to show issues linked to articles in the articles listing. I echo values of two ACFs used in the custom (issue) post - issue number and issue year to designate the custom post like "2016-04":

function add_linked_issue_posts_admin_column($column) {
    $column['linked_issue_post'] = 'Issue number';

    return $column;
}

add_filter('manage_posts_columns', 'add_linked_issue_posts_admin_column');

function add_linked_issue_post_admin_column_show_value($column_name, $post_ID) {
    if ($column_name == 'linked_issue_post') {
        $posts = get_field( 'article_issue_n', $post_ID );
        if( $posts ):
            foreach( $posts as $post): 
                setup_postdata($post);
                $issue_n = get_field('issue_number_cf', $post->ID);
                $issue_y = get_field('issue_year', $post->ID);
                echo ''.$issue_y.'-'.$issue_n.'';
            endforeach;
            wp_reset_postdata();
        endif;
    }
}

add_action('manage_posts_custom_column', 'add_linked_issue_post_admin_column_show_value', 10, 2);

function linked_issue_post_columng_make_sortable($columns)
{
    $columns['linked_issue_post'] = 'linked_issue_post';

    return $columns;
}

add_filter("manage_edit-post_sortable_columns", "linked_issue_post_columng_make_sortable" );

And it works fine. But the column is not being sorted by the echoed value. I mean, I'd like the column to be sorted ASC or DESC alphabetically/numerically, so that issue number 2016-04 would go after 2016-03. Tried a number of filters, but still don't have the result. Many thanks in advance!

Was it helpful?

Solution

Ah, the remedy was a simple one:

function issue_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'linked_issue_post' == $vars['orderby'] ) {       
        $vars = array_merge( $vars, array(
            'meta_key' => 'article_issue_n',
            'orderby' => 'meta_value'
        ) );
    }

    return $vars;
}
add_filter( 'request', 'issue_column_orderby' );

I probably omitted something before...

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top