我已在functions.php
要添加到列中以查看帖子上的特色图像的文件。然而,我也希望对页面执行此操作,但如果我重复代码,将帖子替换为页面,则会在站点上产生错误。有人知道我如何用一点代码就可以做到这一点吗?
这是我发布的代码:
add_filter(\'manage_posts_columns\', \'add_img_column\');
add_filter(\'manage_posts_custom_column\', \'manage_img_column\', 10, 2);
function add_img_column($columns) {
$columns = array_slice($columns, 0, 1, true) + array("links" => "Image") + array_slice($columns, 1, count($columns) - 1, true);
return $columns;
}
function manage_img_column($column_name, $post_id) {
if( $column_name == \'links\' ) {
echo get_the_post_thumbnail($post_id, \'thumbnail\');
}
return $column_name;
}
但是,如果我在第二个页面上重复代码更改“posts”,这会给我带来错误:
add_filter(\'manage_posts_columns\', \'add_img_column\');
add_filter(\'manage_posts_custom_column\', \'manage_img_column\', 10, 2);
function add_img_column($columns) {
$columns = array_slice($columns, 0, 1, true) + array("links" => "Image") + array_slice($columns, 1, count($columns) - 1, true);
return $columns;
}
function manage_img_column($column_name, $post_id) {
if( $column_name == \'links\' ) {
echo get_the_post_thumbnail($post_id, \'thumbnail\');
}
return $column_name;
}
add_filter(\'manage_pages_columns\', \'add_img_column\');
add_filter(\'manage_pages_custom_column\', \'manage_img_column\', 10, 2);
function add_img_column($columns) {
$columns = array_slice($columns, 0, 1, true) + array("links" => "Image") + array_slice($columns, 1, count($columns) - 1, true);
return $columns;
}
function manage_img_column($column_name, $post_id) {
if( $column_name == \'links\' ) {
echo get_the_post_thumbnail($post_id, \'thumbnail\');
}
return $column_name;
}
很抱歉,如果这是一个很明显的答案,但我对wordpress和php还很陌生,所以请帮我解释一下原因
why 如果您能给出答案,我们将不胜感激!谢谢
最合适的回答,由SO网友:Jacob Peattie 整理而成
出现错误的原因是您有多个同名函数。有两个函数add_img_column()
还有两个打电话来manage_img_column()
. 在PHP中不能有两个同名函数。
不过,您甚至不需要两个函数。您可以将同一个函数挂钩到多个挂钩中。这就是您所需要的:
add_filter(\'manage_posts_columns\', \'add_img_column\');
add_filter(\'manage_pages_columns\', \'add_img_column\');
add_filter(\'manage_posts_custom_column\', \'manage_img_column\', 10, 2);
add_filter(\'manage_pages_custom_column\', \'manage_img_column\', 10, 2);
function add_img_column($columns) {
$columns = array_slice($columns, 0, 1, true) + array("links" => "Image") + array_slice($columns, 1, count($columns) - 1, true);
return $columns;
}
function manage_img_column($column_name, $post_id) {
if( $column_name == \'links\' ) {
echo get_the_post_thumbnail($post_id, \'thumbnail\');
}
return $column_name;
}