'listing'
的自定义帖子类型,并添加了一个名为'businesses'
的自定义分类法。我想将商家的下拉列表添加到列表的管理员列表中。此功能在帖子的管理员列表中是这样的(我希望对“自定义帖子类型”使用相同的功能) :
这是我当前的代码(这里是Gist上的相同代码。):
<?php
/*
Plugin Name: Listing Content Item
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
class Listing {
var $meta_fields = array("list-address1","list-address2","list-country","list-province","list-city","list-postcode","list-firstname","list-lastname","list-website","list-mobile","list-phone","list-fax","list-email", "list-profile", "list-distributionrange", "list-distributionarea");
public function loadStyleScripts() {
$eventsURL = trailingslashit( WP_PLUGIN_URL ) . trailingslashit( plugin_basename( dirname( __FILE__ ) ) ) . 'css/';
wp_enqueue_style('listing-style', $eventsURL.'listing.css');
}
function Listing() {
// Register custom post types
register_post_type('listing', array(
'labels' => array(
'name' => __('Listings'), 'singular_name' => __( 'Listing' ),
'add_new' => __( 'Add Listing' ),
'add_new_item' => __( 'Add New Listing' ),
'edit' => __( 'Edit' ),
'edit_item' => __( 'Edit Listing' ),
'new_item' => __( 'New Listing' ),
'view' => __( 'View Listing' ),
'view_item' => __( 'View Listing' ),
'search_items' => __( 'Search Listings' ),
'not_found' => __( 'No listings found' ),
'not_found_in_trash' => __( 'No listings found in Trash' ),
'parent' => __( 'Parent Listing' ),
),
'singular_label' => __('Listing'),
'public' => true,
'show_ui' => true, // UI in admin panel
'_builtin' => false, // It's a custom post type, not built in
'_edit_link' => 'post.php?post=%d',
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array("slug" => "listings"), // Permalinks
'query_var' => "listings", // This goes to the WP_Query schema
'supports' => array('title','editor')
));
add_filter("manage_edit-listing_columns", array(&$this, "edit_columns"));
add_action("manage_posts_custom_column", array(&$this, "custom_columns"));
// Register custom taxonomy
#Businesses
register_taxonomy("businesses", array("listing"), array(
"hierarchical" => true,
"label" => "Listing Categories",
"singular_label" => "Listing Categorie",
"rewrite" => true,
));
# Region
register_taxonomy("regions", array("listing"), array(
'labels' => array(
'search_items' => __( 'Search Regions' ),
'popular_items' => __( 'Popular Regions' ),
'all_items' => __( 'All Regions' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Region' ),
'update_item' => __( 'Update Region' ),
'add_new_item' => __( 'Add New Region' ),
'new_item_name' => __( 'New Region Name' ),
'separate_items_with_commas' => __( 'Separate regions with commas' ),
'add_or_remove_items' => __( 'Add or remove regions' ),
'choose_from_most_used' => __( 'Choose from the most used regions' ),
),
"hierarchical" => false,
"label" => "Listing Regions",
"singular_label" => "Listing Region",
"rewrite" => true,
));
# Member Organizations
register_taxonomy("organizations", array("listing"), array(
'labels' => array(
'search_items' => __( 'Search Member Organizations' ),
'popular_items' => __( 'Popular Member Organizations' ),
'all_items' => __( 'All Member Organizations' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Member Organization' ),
'update_item' => __( 'Update Member Organization' ),
'add_new_item' => __( 'Add New Member Organization' ),
'new_item_name' => __( 'New Member Organization Name' ),
'separate_items_with_commas' => __( 'Separate member organizations with commas' ),
'add_or_remove_items' => __( 'Add or remove member organizations' ),
'choose_from_most_used' => __( 'Choose from the most used member organizations' ),
),
"hierarchical" => false,
"label" => "Member Organizations",
"singular_label" => "Member Organization",
"rewrite" => true,
));
# Retail Products
register_taxonomy("retails", array("listing"), array(
'labels' => array(
'search_items' => __( 'Search Retail Products' ),
'popular_items' => __( 'Popular Retail Products' ),
'all_items' => __( 'All Retail Products' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Retail Product' ),
'update_item' => __( 'Update Retail Product' ),
'add_new_item' => __( 'Add New Retail Product' ),
'new_item_name' => __( 'New Retail Product Name' ),
'separate_items_with_commas' => __( 'Separate retail products with commas' ),
'add_or_remove_items' => __( 'Add or remove retail products' ),
'choose_from_most_used' => __( 'Choose from the most used retail products' ),
),
"hierarchical" => false,
"label" => "Retail Products",
"singular_label" => "Retail Product",
"rewrite" => true,
));
# Farming Practices
register_taxonomy("practices", array("listing"), array(
'labels' => array(
'search_items' => __( 'Search Farming Practices' ),
'popular_items' => __( 'Popular Farming Practices' ),
'all_items' => __( 'All Farming Practices' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Farming Practice' ),
'update_item' => __( 'Update Farming Practice' ),
'add_new_item' => __( 'Add New Farming Practice' ),
'new_item_name' => __( 'New Farming Practice Name' ),
'separate_items_with_commas' => __( 'Separate farming practices with commas' ),
'add_or_remove_items' => __( 'Add or remove farming practices' ),
'choose_from_most_used' => __( 'Choose from the most used farming practices' ),
),
"hierarchical" => false,
"label" => "Farming Practices",
"singular_label" => "Farming Practice",
"rewrite" => true,
));
# Products
register_taxonomy("products", array("listing"), array(
'labels' => array(
'search_items' => __( 'Search Products' ),
'popular_items' => __( 'Popular Products' ),
'all_items' => __( 'All Products' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Product' ),
'update_item' => __( 'Update Product' ),
'add_new_item' => __( 'Add New Product' ),
'new_item_name' => __( 'New Product Name' ),
'separate_items_with_commas' => __( 'Separate products with commas' ),
'add_or_remove_items' => __( 'Add or remove products' ),
'choose_from_most_used' => __( 'Choose from the most used products' ),
),
"hierarchical" => false,
"label" => "Products",
"singular_label" => "Product",
"rewrite" => true,
));
// Admin interface init
add_action("admin_init", array(&$this, "admin_init"));
add_action("template_redirect", array(&$this, 'template_redirect'));
// Insert post hook
add_action("wp_insert_post", array(&$this, "wp_insert_post"), 10, 2);
}
function edit_columns($columns) {
$columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => "Business Name",
"description" => "Description",
"list-personal" => "Personal Information",
"list-location" => "Location",
"list-categorie" => "Categorie",
);
return $columns;
}
function custom_columns($column) {
global $post;
switch ($column) {
case "description":
the_excerpt();
break;
case "list-personal":
$custom = get_post_custom();
if(isset($custom["list-firstname"][0])) echo $custom["list-firstname"][0]."<br />";
if(isset($custom["list-lastname"][0])) echo $custom["list-lastname"][0]."<br />";
if(isset($custom["list-email"][0])) echo $custom["list-email"][0]."<br />";
if(isset($custom["list-website"][0])) echo $custom["list-website"][0]."<br />";
if(isset($custom["list-phone"][0])) echo $custom["list-phone"][0]."<br />";
if(isset($custom["list-mobile"][0])) echo $custom["list-mobile"][0]."<br />";
if(isset($custom["list-fax"][0])) echo $custom["list-fax"][0];
break;
case "list-location":
$custom = get_post_custom();
if(isset($custom["list-address1"][0])) echo $custom["list-address1"][0]."<br />";
if(isset($custom["list-address2"][0])) echo $custom["list-address2"][0]."<br />";
if(isset($custom["list-city"][0])) echo $custom["list-city"][0]."<br />";
if(isset($custom["list-province"][0])) echo $custom["list-province"][0]."<br />";
if(isset($custom["list-postcode"][0])) echo $custom["list-postcode"][0]."<br />";
if(isset($custom["list-country"][0])) echo $custom["list-country"][0]."<br />";
if(isset($custom["list-profile"][0])) echo $custom["list-profile"][0]."<br />";
if(isset($custom["list-distributionrange"][0])) echo $custom["list-distributionrange"][0]."<br />";
if(isset($custom["list-distributionarea"][0])) echo $custom["list-distributionarea"][0];
break;
case "list-categorie":
$speakers = get_the_terms(0, "businesses");
$speakers_html = array();
if(is_array($speakers)) {
foreach ($speakers as $speaker)
array_push($speakers_html, '<a href="' . get_term_link($speaker->slug, 'businesses') . '">' . $speaker->name . '</a>');
echo implode($speakers_html, ", ");
}
break;
}
}
// Template selection
function template_redirect() {
global $wp;
if (isset($wp->query_vars["post_type"]) && ($wp->query_vars["post_type"] == "listing")) {
include(STYLESHEETPATH . "/listing.php");
die();
}
}
// When a post is inserted or updated
function wp_insert_post($post_id, $post = null) {
if ($post->post_type == "listing") {
// Loop through the POST data
foreach ($this->meta_fields as $key) {
$value = @$_POST[$key];
if (empty($value)) {
delete_post_meta($post_id, $key);
continue;
}
// If value is a string it should be unique
if (!is_array($value)) {
// Update meta
if (!update_post_meta($post_id, $key, $value)) {
// Or add the meta data
add_post_meta($post_id, $key, $value);
}
}
else
{
// If passed along is an array, we should remove all previous data
delete_post_meta($post_id, $key);
// Loop through the array adding new values to the post meta as different entries with the same name
foreach ($value as $entry)
add_post_meta($post_id, $key, $entry);
}
}
}
}
function admin_init() {
// Custom meta boxes for the edit listing screen
add_meta_box("list-pers-meta", "Personal Information", array(&$this, "meta_personal"), "listing", "normal", "low");
add_meta_box("list-meta", "Location", array(&$this, "meta_location"), "listing", "normal", "low");
}
function meta_personal() {
global $post;
$custom = get_post_custom($post->ID);
if(isset($custom["list-firstname"][0])) $first_name = $custom["list-firstname"][0];else $first_name = '';
if(isset($custom["list-lastname"][0])) $last_name = $custom["list-lastname"][0];else $last_name = '';
if(isset($custom["list-website"][0])) $website = $custom["list-website"][0];else $website = '';
if(isset($custom["list-phone"][0])) $phone = $custom["list-phone"][0];else $phone = '';
if(isset($custom["list-mobile"][0])) $mobile = $custom["list-mobile"][0];else $mobile = '';
if(isset($custom["list-fax"][0])) $fax = $custom["list-fax"][0];else $fax = '';
if(isset($custom["list-email"][0])) $email = $custom["list-email"][0];else $email = '';
?>
<div class="personal">
<table border="0" id="personal">
<tr><td class="personal_field"><label>Firstname:</label></td><td class="personal_input"><input name="list-firstname" value="<?php echo $first_name; ?>" /></td></tr>
<tr><td class="personal_field"><label>Lastname:</label></td><td class="personal_input"><input name="list-lastname" value="<?php echo $last_name; ?>" /></td></tr>
<tr><td class="personal_field"><label>Email:</label></td><td class="personal_input"><input name="list-email" value="<?php echo $email; ?>" size="40"/></td></tr>
<tr><td class="personal_field"><label>Website:</label></td><td class="personal_input"><input name="list-website" value="<?php echo $website; ?>" size="40"/></td></tr>
<tr><td class="personal_field"><label>Phone:</label></td><td class="personal_input"><input name="list-phone" value="<?php echo $phone; ?>" /></td></tr>
<tr><td class="personal_field"><label>Mobile:</label></td><td class="personal_input"><input name="list-mobile" value="<?php echo $mobile; ?>" /></td></tr>
<tr><td class="personal_field"><label>Fax:</label></td><td class="personal_input"><input name="list-fax" value="<?php echo $fax; ?>" /></td></tr>
</table>
</div>
<?php
}
// Admin post meta contents
function meta_location() {
global $post;
$custom = get_post_custom($post->ID);
if(isset($custom["list-address1"])) $address1 = $custom["list-address1"][0];else $address1 = '';
if(isset($custom["list-address2"])) $address2 = $custom["list-address2"][0];else $address2 = '';
if(isset($custom["list-country"])) $country = $custom["list-country"][0];else $country = '';
if(isset($custom["list-province"])) $province = $custom["list-province"][0];else $province = '';
if(isset($custom["list-city"])) $city = $custom["list-city"][0];else $city = '';
if(isset($custom["list-postcode"])) $post_code = $custom["list-postcode"][0];else $post_code = '';
if(isset($custom["list-profile"])) $profile = $custom["list-profile"][0];else $profile = '';
if(isset($custom["list-distributionrange"])) $distribution_range = $custom["list-distributionrange"][0];else $distribution_range = '';
if(isset($custom["list-distributionarea"])) $distribution_area = $custom["list-distributionarea"][0];else $ddistribution_area = '';
?>
<div class="location">
<table border="0" id="location">
<tr><td class="location_field"><label>Address 1:</label></td><td class="location_input"><input name="list-address1" value="<?php echo $address1; ?>" size="60" /></td></tr>
<tr><td class="location_field"><label>Address 2:</label></td><td class="location_input"><input name="list-address2" value="<?php echo $address2; ?>" size="60" /></td></tr>
<tr><td class="location_field"><label>City:</label></td><td class="location_input"><input name="list-city" value="<?php echo $city; ?>" /></td></tr>
<tr><td class="location_field"><label>Province:</label></td><td class="location_input"><input name="list-province" value="Ontario" readonly /></td></tr>
<tr><td class="location_field"><label>Postal Code:</label></td><td class="location_input"><input name="list-postcode" value="<?php echo $post_code; ?>" /></td></tr>
<tr><td class="location_field"><label>Country:</label></td><td class="location_input"><input name="list-country" value="Canada" readonly /></td></tr>
<tr><td class="location_field"><label>Profile:</label></td><td class="location_input"><input name="list-profile" value="<?php echo $profile; ?>" size="60" /></td></tr>
<tr><td class="location_field"><label>Distribution Range:</label></td><td class="location_input"><input name="list-distributionrange" value="<?php echo $distribution_range; ?>" size="60" /></td></tr>
<tr><td class="location_field"><label>Distribution Area:</label></td><td class="location_input"><input name="list-distributionarea" value="<?php echo $distribution_area; ?>" size="60" /></td></tr>
</table>
</div>
<?php
}
}
// Initiate the plugin
add_action("init", "ListingInit");
function ListingInit() {
global $listing;
$listing = new Listing();
$add_css = $listing->loadStyleScripts();
}
如何将商家的下拉列表添加到列表的管理员列表中?
#1 楼
更新:我已经提供了一个完整的新答案,但是即使如此,我也将我的原始回复留在了底部,前面的几条评论均引用了该答案。@tarasm:
尽管我说过有点困难应该不难。但是在我们深入研究代码之前...
屏幕截图:
...让我们检查一下成品的屏幕截图:
没有过滤的列表列表页面:
(来源:mikeschinkel.com)
具有过滤功能的列表列表页面:
(来源:mikeschinkel.com)
代码
所以我们开始...(注意:我使用了单数形式的分类名称
business
;我希望能与您匹配。根据过去在WordPress和数据库开发方面的大量经验,我认为最好采用这种方式。)步骤1 :
restrict_manage_posts
操作钩。您需要做的第一件事是钩上没有参数的
restrict_manage_posts
操作,并从/wp-admin/edit.php
调用(在v3.0.1中,该调用位于第378行。)这将允许您生成在列表帖子列表上方的适当位置进行下拉选择。<?php
add_action('restrict_manage_posts','restrict_listings_by_business');
function restrict_listings_by_business() {
global $typenow;
global $wp_query;
if ($typenow=='listing') {
$taxonomy = 'business';
$business_taxonomy = get_taxonomy($taxonomy);
wp_dropdown_categories(array(
'show_option_all' => __("Show All {$business_taxonomy->label}"),
'taxonomy' => $taxonomy,
'name' => 'business',
'orderby' => 'name',
'selected' => $wp_query->query['term'],
'hierarchical' => true,
'depth' => 3,
'show_count' => true, // Show # listings in parens
'hide_empty' => true, // Don't show businesses w/o listings
));
}
}
首先检查
$typenow
变量,以确保我们实际上位于post_type
的listing
上。如果您不这样做,那么您会在所有情况下都想要的该类型的下拉列表中找到,但是在这种情况下不是。接下来,我们使用
get_taxonomy()
加载有关业务分类的信息。我们需要它来检索分类法的标签(即“业务”;我们可以进行硬编码,但是如果您以后需要进行国际化,那就不好了。)然后我们将wp_dropdown_categories()
以及$args
数组中的所有适当参数调用为生成下拉菜单<?php
return wp_dropdown_categories(array(
'show_option_all' => __("Show All {$business_taxonomy->label}"),
'taxonomy' => $taxonomy,
'name' => 'business',
'orderby' => 'name',
'selected' => $wp_query->query['term'],
'hierarchical' => true,
'depth' => 3,
'show_count' => true, // Show # listings in parens
'hide_empty' => true, // Don't show businesses w/o listings
));
但是合适的参数是什么?让我们分别来看一下:
show_optional_all
-非常简单明了,它是首先显示在下拉菜单中的内容,并且没有应用任何过滤。在我们的例子中,它的名称为“显示所有业务”,但我们可以将其称为“所有业务的清单”或任何您喜欢的名称。即使函数名称中包含taxonomy
,也可以从中提取术语。在v2.8和更早版本中,WordPress没有自定义分类法,但是当他们添加时,团队决定将一个分类法参数添加到此函数比创建另一个具有另一个名称的函数要容易得多。categories
-此参数允许您指定WordPress用于为下拉列表生成的#2 楼
只想共享一个替代实现。在弄清楚这一点时,我没有Mike的精彩教程,因此我的解决方案有所不同。具体来说,我将简化Mike的步骤1,并取消步骤2-其他步骤仍然适用。在Mike的教程中,使用
wp_dropdown_categories()
可以为我们节省一些手动列表构建,但需要一些步骤复杂的条件查询修改(步骤2),以处理其ID的使用,而不是处理。更不用说修改该代码以处理诸如其他分类过滤器之类的其他场景的困难了。从头开始列出。它不是那么复杂,只需不到30行代码,根本不需要钩挂wp_dropdown_categories()
:add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );
function my_restrict_manage_posts() {
// only display these taxonomy filters on desired custom post_type listings
global $typenow;
if ($typenow == 'photos' || $typenow == 'videos') {
// create an array of taxonomy slugs you want to filter by - if you want to retrieve all taxonomies, could use get_taxonomies() to build the list
$filters = array('plants', 'animals', 'insects');
foreach ($filters as $tax_slug) {
// retrieve the taxonomy object
$tax_obj = get_taxonomy($tax_slug);
$tax_name = $tax_obj->labels->name;
// retrieve array of term objects per taxonomy
$terms = get_terms($tax_slug);
// output html for taxonomy dropdown filter
echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
echo "<option value=''>Show All $tax_name</option>";
foreach ($terms as $term) {
// output each select option line, check against the last $_GET to show the current option selected
echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
}
echo "</select>";
}
}
}
只需将所需的分类法插入到
parse_query
数组中,您可以快速输出多个分类过滤器。它们看起来与Mike的屏幕截图完全相同。然后,您可以执行第3步和第4步。评论
@somatic-不错的更新!是的,使用wp_dropdown_categories()确实需要很多解决方法。我会尽可能地坚持使用核心功能,但是正如您指出的那样,有时这样做需要做更多的工作。只是为了证明使用WordPress,通常有不止一种解决问题的好方法。做得好!
– MikeSchinkel
2010-10-23 9:53
刚刚停止在WordPress 3.1上为我工作。试图找出到底发生了什么变化。看起来它仍然应该工作:分类法和术语条在url中显示为GET值,但其结果是0个结果
–曼妮·弗勒蒙德(Manny Fleurmond)
2011-2-24在6:40
我一直在尝试使其工作,但是我唯一的方法是使用parse_query挂钩,检查分类法的查询var并基于此设置分类法和术语查询vars。使用WP 3.1。提交过滤器时,URL中是否应显示分类法和术语?
– sanchothefat
2011-3-22在17:36
对我来说就像一个魅力!确实非常优雅的解决方案。我欠你啤酒:)
– Michal Mau
11年4月26日在11:31
@somatic这很好用,但是有没有办法让$ term-> count只计算该帖子类型的条件?例如,如果我对照片和视频都有自定义分类法,则在查看视频自定义帖子类型时会显示给我,这是两种自定义帖子类型中该词条的帖子总数,而不是仅使用该类别的视频帖子总数术语。
–格林豪
2015年6月11日13:40
#3 楼
这是该版本的一个版本,该版本会自动将所有分类法中的过滤器创建并应用到所有使用它们的自定义帖子类型。 (令人a目结舌)无论如何,我也对其进行了调整,使其可与wp_dropdown_categories()和wordpress 3.1一起使用。我正在处理的项目称为ToDo,您可以将函数重命名为对您有意义的名称,但这应该可以自动完成所有工作。function todo_restrict_manage_posts() {
global $typenow;
$args=array( 'public' => true, '_builtin' => false );
$post_types = get_post_types($args);
if ( in_array($typenow, $post_types) ) {
$filters = get_object_taxonomies($typenow);
foreach ($filters as $tax_slug) {
$tax_obj = get_taxonomy($tax_slug);
wp_dropdown_categories(array(
'show_option_all' => __('Show All '.$tax_obj->label ),
'taxonomy' => $tax_slug,
'name' => $tax_obj->name,
'orderby' => 'term_order',
'selected' => $_GET[$tax_obj->query_var],
'hierarchical' => $tax_obj->hierarchical,
'show_count' => false,
'hide_empty' => true
));
}
}
}
function todo_convert_restrict($query) {
global $pagenow;
global $typenow;
if ($pagenow=='edit.php') {
$filters = get_object_taxonomies($typenow);
foreach ($filters as $tax_slug) {
$var = &$query->query_vars[$tax_slug];
if ( isset($var) ) {
$term = get_term_by('id',$var,$tax_slug);
$var = $term->slug;
}
}
}
return $query;
}
add_action( 'restrict_manage_posts', 'todo_restrict_manage_posts' );
add_filter('parse_query','todo_convert_restrict');
请注意,我使用的插件添加了'term_order'作为订购条款的方式,您必须对此进行更改,或删除该参数以将其回退为默认值。
评论
确实很性感。我收到错误通知,因此我将if(isset($ var))更改为if(isset($ var)&& $ var> 0),以避免尝试查找与“查看全部0”值关联的字词。哦,我必须在todo_convert_restrict函数中返回$ query
–helgatheviking
2012年1月7日在22:17
#4 楼
最新答案编辑
我写了Filterama,它是一个插件,它将以最简单的方式添加此功能。
WordPress 3.5+的更新
现在,事情变得简单得多,这是一个非常简单的解决方案,例如插件或mu-plugin。
它使用的资源尽可能少,仅在所需的屏幕和为每种自定义分类法添加列+过滤器。
评论
进行了旋转,但似乎缺少get_select()方法。
–戴夫·罗姆西
13年3月15日在15:40
@ goto10你是对的。更新。顺便说一句:抓住链接的插件会更容易。一两个星期后即可在插件存储库中使用。 (已确认)。
– kaiser
13年3月16日在11:09
我不得不使用$ this-> setup_vars();在公共功能setup()的开头,以便使“ manage_taxonomies_for _ {$ this-> post_type} _columns”起作用
–基督徒
13年7月2日在11:44
但这可能是因为我在主题function.php中使用了add_action('init',array('WCM_Admin_PT_List_Tax_Filter','init'));
–基督徒
13年7月2日在11:52
@Christian这不是主题材料。它属于一个插件,如上面的代码所示,当前加载该主题的时间远远早于加载主题的时间。
– kaiser
13年7月2日在12:49
#5 楼
我只是想做个快速笔记。在较新版本的WP上,admin上的帖子列表由WP_Posts_List_Table类处理。现在apply_filters代码如下:if ( 'page' == $post_type )
$posts_columns = apply_filters( 'manage_pages_columns', $posts_columns );
else
$posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type );
$posts_columns = apply_filters( "manage_{$post_type}_posts_columns", $posts_columns );
因此,要添加新列,add_filter钩子应类似于:
add_filter( 'manage_posts_columns', 'my_add_columns', 10, 2);
这里有一个示例:
function my_add_columns($posts_columns, $post_type)
{
if ('myposttype' == $post_type) {
$posts_columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => "Title",
"anothercolumn" => "Bacon",
"date" => __( 'Date' )
);
return $posts_columns;
}
}
现在,用于帖子行。这是处理清单中列数据的代码:
default:
?>
<td <?php echo $attributes ?>><?php
if ( is_post_type_hierarchical( $post->post_type ) )
do_action( 'manage_pages_custom_column', $column_name, $post->ID );
else
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID );
?></td>
<?php
为了检索我们的帖子数据,我们必须添加一个如下所示的动作挂钩:
add_action( "manage_(here_goes_your_post_type)_posts_custom_column", "my_posttype_add_column", 10, 2);
示例(此示例使用分类法,但您可以查询其他任何东西):
function my_posttype_add_column($column_name, $post_id)
{
switch ($column_name) {
case 'anothercolumn':
$flavours = get_the_terms($post_id, 'flavour');
if (is_array($flavours)) {
foreach($flavours as $key => $flavour) {
$edit_link = get_term_link($flavour, 'flavour');
$flavours[$key] = '<a href="'.$edit_link.'">' . $flavour->name . '</a>';
}
echo implode(' | ',$flavours);
}
break;
default:
break;
}
}
#6 楼
在WP 3.2中可以使用!评论
对于WP 3.2及更高版本而言,这是一个不错的解决方案。
–petermolnar
15年7月30日在10:27
它可以工作,但是__(“ Show All {$ info_taxonomy-> label}”)是使用可翻译字符串的错误方法。
–马克·卡普伦
17年8月23日在5:24
#7 楼
我猜这不是众所周知,但是从wordpress 3.5开始,您可以将'show_admin_column' => true
传递给register_taxonomy
。这样做有两件事:将分类法列添加到管理员帖子类型列表视图中
通过单击分类法列上的术语名称,实际上将过滤
因此,它与select并不完全相同,但功能几乎相同,宽度仅一行代码。
https:// make .wordpress.org / core / 2012/12/11 / wordpress-3-5-admin-columns-for-custom-taxonomies /
此外,如您所见,还有一个专门定制的新过滤器用于手动添加分类法列(如果您确实需要)。
#8 楼
这是一种使用strict_manage_posts操作的方法。它似乎对我来说很好用,并增加了对所有帖子类型及其相关分类法按分类进行筛选的功能。// registers each of the taxonomy filter drop downs
function sunrise_fbt_add_taxonomy_filters() {
global $typenow; // the current post type
$taxonomies = get_taxonomies('','objects');
foreach($taxonomies as $taxName => $tax) {
if(in_array($typenow,$tax->object_type) && $taxName != 'category' && $taxName != 'tags') {
$terms = get_terms($taxName);
if(count($terms) > 0) {
//Check if hierarchical - if so build hierarchical drop-down
if($tax->hierarchical) {
$args = array(
'show_option_all' => 'All '.$tax->labels->name,
'show_option_none' => 'Select '.$tax->labels->name,
'show_count' => 1,
'hide_empty' => 0,
'echo' => 1,
'hierarchical' => 1,
'depth' => 3,
'name' => $tax->rewrite['slug'],
'id' => $tax->rewrite['slug'],
'class' => 'postform',
'depth' => 0,
'tab_index' => 0,
'taxonomy' => $taxName,
'hide_if_empty' => false);
$args['walker'] = new Walker_FilterByTaxonomy;
wp_dropdown_categories($args);
} else {
echo "<select name='".$tax->rewrite['slug']."' id='".$tax->rewrite['slug']."' class='postform'>";
echo "<option value=''>Show All ".$tax->labels->name."</option>";
foreach ($terms as $term) {
echo '<option value="' . $term->slug . '"', $_GET[$taxName] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
}
echo "</select>";
}
}
}
}
}
add_action( 'restrict_manage_posts', 'sunrise_fbt_add_taxonomy_filters', 100 );
/**
* Create HTML dropdown list of Categories.
*
* @package WordPress
* @since 2.1.0
* @uses Walker
*/
class Walker_FilterByTaxonomy extends Walker {
var $tree_type = 'category';
var $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
function start_el(&$output, $category, $depth, $args) {
$args['selected'] = get_query_var( $args['taxonomy'] );
$pad = str_repeat(' ', $depth * 3);
$cat_name = apply_filters('list_cats', $category->name, $category);
$output .= "\t<option class=\"level-$depth\" value=\"".$category->slug."\"";
if ( $category->slug == $args['selected'] )
$output .= ' selected="selected"';
$output .= '>';
$output .= $pad.$cat_name;
if ( $args['show_count'] )
$output .= ' ('. $category->count .')';
if ( $args['show_last_update'] ) {
$format = 'Y-m-d';
$output .= ' ' . gmdate($format, $category->last_update_timestamp);
}
$output .= "</option>\n";
}
}
一个注释-我尝试限制深度是因为我的一些层次分类法相当大,但没有用-可能是wp_dropdown_categories函数中的错误?
#9 楼
按照@kevin的要求,@ somatic答案的分层版本:<?php
add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );
function my_restrict_manage_posts() {
// only display these taxonomy filters on desired custom post_type listings
global $typenow;
if ($typenow == 'photos' || $typenow == 'videos') {
// create an array of taxonomy slugs you want to filter by - if you want to retrieve all taxonomies, could use get_taxonomies() to build the list
$filters = array('plants', 'animals', 'insects');
foreach ($filters as $tax_slug) {
// retrieve the taxonomy object
$tax_obj = get_taxonomy($tax_slug);
$tax_name = $tax_obj->labels->name;
// output html for taxonomy dropdown filter
echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
echo "<option value=''>Show All $tax_name</option>";
generate_taxonomy_options($tax_slug,0,0);
echo "</select>";
}
}
}
function generate_taxonomy_options($tax_slug, $parent = '', $level = 0) {
$args = array('show_empty' => 1);
if(!is_null($parent)) {
$args = array('parent' => $parent);
}
$terms = get_terms($tax_slug,$args);
$tab='';
for($i=0;$i<$level;$i++){
$tab.='--';
}
foreach ($terms as $term) {
// output each select option line, check against the last $_GET to show the current option selected
echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' .$tab. $term->name .' (' . $term->count .')</option>';
generate_taxonomy_options($tax_slug, $term->term_id, $level+1);
}
}
?>
我基本上删除了创建选项的代码,并将其放入自己的函数中。函数“ generate_taxonomy_options”除了采用tax_slug之外,还采用了parent和level参数。该函数假定其为父级0创建选项,它将选择所有根级别术语。在循环中,该函数将递归调用自身,使用该当前术语作为父项并将级别提高一级。它会在您越深越深的树上自动添加刻度线,瞧!
#10 楼
@Drew Gourley针对WP 3.3.1的答案的更新(并包含来自http://wordpress.org/support/topic/wp_dropdown_categories-generating-url-id-number-instead-of-slug?replies=6#post- 2529115):add_action('restrict_manage_posts', 'xyz_restrict_manage_posts');
function xyz_restrict_manage_posts() {
global $typenow;
$args = array('public'=>true, '_builtin'=>false);
$post_types = get_post_types($args);
if(in_array($typenow, $post_types)) {
$filters = get_object_taxonomies($typenow);
foreach ($filters as $tax_slug) {
$tax_obj = get_taxonomy($tax_slug);
$term = get_term_by('slug', $_GET[$tax_obj->query_var], $tax_slug);
wp_dropdown_categories(array(
'show_option_all' => __('Show All '.$tax_obj->label ),
'taxonomy' => $tax_slug,
'name' => $tax_obj->name,
'orderby' => 'term_order',
'selected' => $term->term_id,
'hierarchical' => $tax_obj->hierarchical,
'show_count' => false,
// 'hide_empty' => true,
'hide_empty' => false,
'walker' => new DropdownSlugWalker()
));
}
}
}
//Dropdown filter class. Used with wp_dropdown_categories() to cause the resulting dropdown to use term slugs instead of ids.
class DropdownSlugWalker extends Walker_CategoryDropdown {
function start_el(&$output, $category, $depth, $args) {
$pad = str_repeat(' ', $depth * 3);
$cat_name = apply_filters('list_cats', $category->name, $category);
$output .= "\t<option class=\"level-$depth\" value=\"".$category->slug."\"";
if($category->term_id == $args['selected'])
$output .= ' selected="selected"';
$output .= '>';
$output .= $pad.$cat_name;
$output .= "</option>\n";
}
}
#11 楼
很抱歉,作为新用户,我不能发表评论,但可以发表答案...从WordPress 3.1(RC 1)起,迈克的答案(这对我有帮助在过去的几个月里很好)对我来说不再有效;通过任何分类法子项进行限制都会得出空的结果。
我尝试了Somatic的更新,效果很好;更好的是,它可与此版本中已使用的多个分类法查询一起使用。
评论
由于某些原因,躯体版本在3.1中也不起作用
–曼妮·弗勒蒙德(Manny Fleurmond)
2011-2-24在6:17
#12 楼
刚刚尝试了Mike和somatic的两个代码,并想知道如何从每种技术中获得好处:使用Mike的代码,它显示了带有分层选项的下拉列表,这很有帮助。但是,为了显示两个下拉菜单,我必须在函数
if ($typenow=='produtos') {...}
中复制restrict_listings_by_business()
语句,并在if ($pagenow=='edit.php' && ... }
函数中复制convert_business_id_to_taxonomy_term_in_query($query)
,这现在提供了很多代码。我希望将分类法视为下拉菜单和bam起作用; $filters = array('taxo1', 'taxo2');
问题:我可以获取体细胞的方法并且也可以使用分层方法吗?
无论如何,还是非常感谢本教程,对您有很大帮助!
评论
我对分层解决方案的回答
–曼妮·弗勒蒙德(Manny Fleurmond)
2011年1月8日,下午6:02
#13 楼
迈克的教程很棒!如果我不得不自己解决这个问题,我可能不会费心将其添加到我的Media Categories插件中。这就是说,我想先使用
parse_query
然后查询该词没必要创建您自己的自定义沃克类更干净。也许当他写他的帖子时是不可能的-在我写这篇文章时它已经3岁了。在github上查看这个很棒的代码片段。像超级按钮一样工作,将下拉列表中的ID更改为段,因此无需修改查询即可直接运行。
https://gist.github.com/stephenh1988/2902509
#14 楼
只需将其添加到您的functions.php或插件代码中(并替换YOURCUSTOMTYPE和YOURCUSTOMTAXONOMY)即可。(我从generatewp获得了代码)
add_action( 'restrict_manage_posts', 'filter_backend_by_taxonomies' , 99, 2);
function filter_backend_by_taxonomies( $post_type, $which ) {
// Apply this to a specific CPT
if ( 'YOURCUSTOMTYPE' !== $post_type )
return;
// A list of custom taxonomy slugs to filter by
$taxonomies = array( 'YOURCUSTOMTAXONOMY' );
foreach ( $taxonomies as $taxonomy_slug ) {
// Retrieve taxonomy data
$taxonomy_obj = get_taxonomy( $taxonomy_slug );
$taxonomy_name = $taxonomy_obj->labels->name;
// Retrieve taxonomy terms
$terms = get_terms( $taxonomy_slug );
// Display filter HTML
echo "<select name='{$taxonomy_slug}' id='{$taxonomy_slug}' class='postform'>";
echo '<option value="">' . sprintf( esc_html__( 'Category', 'text_domain' ), $taxonomy_name ) . '</option>';
foreach ( $terms as $term ) {
printf(
'<option value="%1$s" %2$s>%3$s (%4$s)</option>',
$term->slug,
( ( isset( $_GET[$taxonomy_slug] ) && ( $_GET[$taxonomy_slug] == $term->slug ) ) ? ' selected="selected"' : '' ),
$term->name,
$term->count
);
}
echo '</select>';
}
}
评论
感谢您提供的屏幕截图,拥有它们确实有帮助。有一个插件Admin Taxonomy Filter可以完成确切的工作。