Search code examples
phpwordpresscustom-post-type

WordPress - Hide table rows on condition


I have a custom CPT called Topics and only an editor or admin can create one. There are custom columns and custom meta box. It is only made for the backend purpose, not for publishing. So, it has a meta box and it will have a list of authors and selecting one will assign it to the author and will display in the name will be displayed in the table that has a custom column name Author. So, I want authors to see only those topics that has been assigned to them via meta box. Other Topics should be hidden. Is there a way to hide specific rows with the condition. 'cruiser_writer_value_key' will save the name of the author. So my condition is.

$writer_list_value = get_post_meta( $post_id, 'cruiser_writer_value_key', true );
$current_user = wp_get_current_user();

if($current_user->display_name == $writer_list_value){
    //display post row
}

else{
    //hide post row of the column
    }

I'm really stuck in this. And Yeah I have custom columns too. It's just that I don't want to the author to edit or read Topics that have not been assigned to them. So, my custom CPT is like this and the custom columns are there. See the picture for more details. Picture of the Topic CPT with custom Columns.


Solution

  • Use filter_posts_list to filter the posts add_action('pre_get_posts', 'filter_posts_list');

    function filter_posts_list($query)
    {
        //$pagenow holds the name of the current page being viewed
         global $pagenow, $typenow;  
    
         $user = wp_get_current_user();
            $allowed_roles = array('author');
            //Shouldn't happen for the admin, but for any role with the edit_posts capability and only on the posts list page, that is edit.php
            if(array_intersect($allowed_roles, $user->roles ) && ('edit.php' == $pagenow) &&  $typenow == 'your_custom_post_type')
            { 
            //global $query's set() method for setting the author as the current user's id
            $query->set(
            'meta_query', array(
            array(
                'key'     => 'yout_meta_key',
                'value'   => $user->display_name,
                'compare' => '==',
            ),
            )
            ); // here you can set your custom meta field using meta_query.
            }
    }