1

I know that manage_posts_custom_column, is used to add or remove custom columns to the custom post type page. The function kiran_custom_column_content which is hooked to the function is called as a loop for all the posts on the page. Now I want to show the post numbers in serial under the number column. So, how can I do that? If it is a while loop, may be I could have set a variable to 0 and then increment it. But how can I set a variable outside the function and increment it each time the function is called. I have tried to declare a variable globally and then increment it inside the function. But it is not working.

add_action( 'manage_sponsor_posts_custom_column', 'kiran_custom_column_content', 10, 2 );

global $postNumber;
$postNumber = 1;

function kiran_custom_column_content( $column, $post_id ) {

    switch ( $column ){
        case 'number':
        echo $postNumber;
        break;

        case 'carousel':
        echo 'Carousel';    
        break;
    }
 $postNumber++;
}
1

This code will add an Index value to each post which is determined by $wp_query->current_post, the number of posts per page, and the current page being viewed.

add_filter( 'manage_posts_columns', 'wpse240648_manage_posts_columns_index');
function wpse240648_manage_posts_columns_index($columns) {
    $columns['index'] = __( 'Index', 'your-text-domain' );
    return $columns;
}

add_action( 'manage_posts_custom_column',  'wpse240648_manage_posts_custom_column_index', 10, 3 );
function wpse240648_manage_posts_custom_column_index( $column, $post_id ) {

    if ( 'index' == $column ) {
        global $wp_query;
        // This line is needed to set up the query so that $wp_query->current_post works.
        $wp_query->the_post();

        $page_number = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 0;

        if ( $page_number > 1 ) {
            $current_index = ( $page_number * $wp_query->query_vars['posts_per_page'] ) - $wp_query->query_vars['posts_per_page'];
        } else {
            $current_index = 0;
        }

        echo esc_html( $wp_query->current_post + 1 + $current_index );      
    }
}

This code can be adapted for to work for other post types by changing the hook names appropriately:

manage_{$post_type}_posts_columns
manage_{$post_type}_posts_custom_column
  • You got it Kiran, take care! – Dave Romsey Sep 27 '16 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.