I have added 3 custom post types and for each post types I have ACF Field which i wish to display in the columns for each post types. I have added the code but tits not working if added in foreach loop.
Here is the Code.
$cpt_list = array(
'book','movie','presentation',
);
foreach ( $cpt_list as $key ) {
add_filter( "manage_edit-'.$key.'_posts_columns", function($columns) {
unset(
$columns['date']
);
$columns['custom_pass'] = __( 'Custom Password', 'theme' );
$columns['date'] = esc_html__( 'Date', 'theme' );
return $columns;
}
);
}
What am I doing wrong?
My Answer:
The issue with your code is that you are trying to use a variable `$key` inside the anonymous function passed to the `add_filter` function. This variable is not available inside the function because it is outside of the function's scope.
To fix this issue, you can use the `use` keyword to pass the `$key` variable to the anonymous function. Here is the updated code:
php
$cpt_list = array(
'book','movie','presentation',
);
foreach ( $cpt_list as $key ) {
add_filter( "manage_edit-{$key}_posts_columns", function($columns) use ($key) {
unset(
$columns['date']
);
$columns['custom_pass'] = __( 'Custom Password', 'theme' );
$columns['date'] = esc_html__( 'Date', 'theme' );
return $columns;
}
);
}
By using the `use ($key)` syntax, you can pass the `$key` variable to the anonymous function and access it inside the function. This should fix the issue and display the custom columns for each custom post type.
Rate this post
4 of 5 based on 1574 votesComments