맞춤 게시물 유형의 관리 목록에 분류 필터를 추가 하시겠습니까?


129

이라는 맞춤 게시물 유형을 만들고이라는 '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();
}

업체 정보 드롭 다운 목록을 업체 정보의 관리자 목록에 추가하려면 어떻게해야하나요?


8
덕분에 스크린 샷을 위해, 그것은 정말 사람들이하는 데 도움이됩니다.
MikeSchinkel

정확한 작업을 수행 할 수 있는 플러그인 Admin Taxonomy Filter 가 있습니다.
Anh Tran

답변:


140

업데이트 : 나는 새로운 완전한 답변을 포함했지만 심지어 처음 몇 개의 주석이 참조하는 맨 아래에 원래의 응답을 남겼습니다.


안녕하세요 @tarasm :

비록 어렵지 않아야한다고 말했지만 조금 복잡합니다. 그러나 코드를 파기 전에 ...

스크린 샷 :

... 완제품의 스크린 샷을 확인하십시오.

필터링 없음 목록 목록 페이지 :

필터링이없는 목록 목록 페이지
(출처 : mikeschinkel.com )

목록 목록 페이지 필터링 :

필터링 목록 목록 페이지
(출처 : mikeschinkel.com )

코드

그래서 우리는 간다 ... ( 참고 : 나는 분류법 이름에 단수형을 사용했다 business. .)

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_typelisting. 그렇지 않으면 모든 게시물 유형에 대해이 드롭 다운을 얻을 수 있지만 경우에 따라 원하는 것은 아니지만이 경우는 아닙니다.

다음으로를 사용하여 비즈니스 분류법에 대한 정보를로드합니다 get_taxonomy(). 분류법에 대한 레이블을 검색하려면이 레이블이 필요합니다 (예 : " Businesses "; 하드 코딩 할 수는 있지만 나중에 국제화해야하는 경우에는 좋지 않습니다). 그런 다음 배열의 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-이 인수는 함수에 categories이름 이 있더라도 용어를 가져올 분류법을 함수에 알려줍니다 . v2.8 이전 버전에서는 WordPress에 사용자 정의 분류법이 없었지만 팀이 추가되면 다른 이름으로 다른 함수를 작성하는 것보다이 함수에 분류법 인수를 추가하는 것이 더 쉬울 것이라고 결정했습니다.

  • name-이 인수를 사용하면 name드롭 다운에 대해 생성 된 <select> 요소 의 속성에 WordPress에서 사용하는 값을 지정할 수 있습니다 . 명확하지 않은 경우 필터링 할 때 URL에 사용될 값이기도합니다.

  • orderby-이 인수는 결과를 알파벳순으로 정렬하는 방법을 WordPress에 알려줍니다. 이 경우 name분류 체계의 용어 즉,이 경우 비즈니스 이름을 구매하도록 주문했습니다 .

  • selected-드롭 다운에 드롭 다운에 현재 필터가 표시되도록하려면이 인수가 필요합니다. term_id선택한 분류 용어에서 나온 것이어야합니다 . 우리의 경우에는 "Business # 2"term_id 에서 온 것일 수 있습니다 . 이 값은 어디에서 얻습니까? WordPress의 전역 변수에서 ; 그것은 모든 URL 매개 변수와 그 값의 배열을 포함하는 속성 을 가지고 있습니다 (물론 일부 플러그인이 이미 수정하지 않은 한) WordPress가 물건을 처리하는 방법을 고려할 때 사용자가 필터를 클릭하면 URL에 URL 매개 변수가 전달됩니다 사용자가 유효한 용어 (예 : 나열된 업체 중 하나)를 선택한 경우 버튼을 클릭합니다.$wp_queryqueryterm

  • hierarchical-이를 설정 true하여 분류의 계층 적 특성을 존중하고 실제로 용어 (비즈니스)에 하위가있는 경우이를 트리보기로 표시하도록 기능에 지시합니다. 스크린 샷에 대한 자세한 내용은 아래를 참조하십시오.

  • depth-이 논증은 hierarchical논증 과 협력하여 자녀를 표시하는 데 얼마나 많은 레벨이 기능을 적용해야하는지 결정합니다.

  • show_count- true이 인수가 드롭 다운 내에서 용어 이름 왼쪽의 괄호 안에 카운트 게시물을 표시하는 경우 . 이 경우 업체와 관련된 업체 정보가 표시됩니다. 스크린 샷에 대한 자세한 내용은 아래를 참조하십시오.

  • hide_empty-마지막으로 분류 와 관련하여 게시물과 관련 이 없는 용어 (예 : 업체 정보와 관련이없는 업체) true가있는 경우 드롭 다운에 포함되지 않도록 이를 설정 합니다.

분류 드롭 다운은 계층 구조 및 개수 여야합니다.
(출처 : mikeschinkel.com )

2 단계 : parse_query필터 후크

다음으로 parse_query매개 변수가 하나 인 필터 후크에 주의를 기울 $query입니다 /wp-includes/query.php(v3.0.1에서는 호출이 1549 행에 있음). WordPress가 URL 검사를 마치고 현재의 모든 적절한 값을 설정하면 호출됩니다. 활성 $wp_query같은 것들을 포함 $wp_query->is_home하고 $wp_query->is_author

parse_query필터 훅이 실행 된 후 WordPress는 get_posts()현재 활성화 된 내용에 따라 게시물 목록을 호출 하고로드합니다 $wp_query. 따라서 parse_queryWordPress에서로드 할 게시물에 대한 마음을 바꿀 수있는 좋은 장소입니다.

유스 케이스에서는 선택한 비즈니스를 기준으로 WordPress를 필터링하려고합니다. 즉, 선택한 업체와 관련된 업체 정보 만 표시합니다 ( '... 선택된 업체에 의해 '분류 된 업체 정보 만 '이라고 말하지만 기술적으로 정확하지 않습니다. category동료에 대한 자체 분류법입니까?' 를 business제외하고 category는 WordPress에 내장되어 business있으며 사용자 정의입니다.하지만 게시물 분류에 익숙한 사람들은 거의 동일하게 작동하므로 이해하는 데 도움이 될 수 있습니다.

코드에. 우리가 할 첫 번째 일은 현재 활성화에 대한 참조를 잡아이다 $wp_query년대를 query_vars자신의 그냥 그 워드 프레스 내에서 수행하는 방법과 같이 작업하는 것이 더 편리하도록 ' parse_query()기능. $wp_query->queryURL에 전달 된 매개 변수를 미러링하는 데 사용되는 것과 달리 $wp_query->query_vars배열은 WordPress가 실행하고 수정 될 것으로 예상되는 쿼리를 제어하는 ​​데 사용됩니다. 따라서 하나를 수정 해야하는 경우 그 중 하나입니다 (적어도 두 가지가 다르다고 생각 합니다. 다른 사람이 알고 있다면 알려 주시기 바랍니다 .)

<?php
add_filter('parse_query','convert_business_id_to_taxonomy_term_in_query');
function convert_business_id_to_taxonomy_term_in_query($query) {
    global $pagenow;
    $qv = &$query->query_vars;
    if ($pagenow=='edit.php' &&
            isset($qv['taxonomy']) && $qv['taxonomy']=='business' &&
            isset($qv['term']) && is_numeric($qv['term'])) {
        $term = get_term_by('id',$qv['term'],'business');
        $qv['term'] = $term->slug;
    }
}

다음으로 $pagenowURL 경로에서 실제로 WordPress를로드하는지 테스트 합니다 /wp-admin/edit.php. 다른 페이지에서 실수로 쿼리를 조이지 않도록하기 위해이 작업을 수행합니다. 우리는 또한 우리 모두가 있는지 확인하십시오 businessA와 taxonomy요소와 term도 요소입니다. (참고 taxonomyterm쌍입니다. 분류 용어를 쿼리 할 수 ​​있도록 함께 사용됩니다. 둘 다 또는 WordPress에 검사 할 분류 체계를 모릅니다.)

배열 요소 business에서 어떻게 나타 났는지 궁금 할 것입니다 . 우리가 훅에 쓴 것은 당신이 " "분류법을 참 으로 설정함으로써 분류법 을 등록 할 때 대기하는 곳에 놓인 워드 프레스의 내부 마술을 촉발 시켰 습니다 . 동일하게 유지하는 것이 가장 좋습니다) :taxonomyquery_varsparse_querybusinessquery_varregister_taxonomy()query_var

<?php
add_action('init','register_business_taxonomy');
    function register_business_taxonomy() {
        register_taxonomy('business',array('listing'),array(
        'label' => 'Businesses',
        'public'=>true,
        'hierarchical'=>true,
        'show_ui'=>true,
        'query_var'=>true
    ));
}

이제 WordPress의 $ wp_query는 분류 용어 ID가 아닌 표준 분류 체계 필터링 된 쿼리에 슬러그를 사용하도록 작성되었습니다. 이 사용 사례에서 필터링 쿼리를 작동시키기 위해 실제로 필요한 것은 다음과 같습니다.

taxonomy: 사업

term: 비즈니스-1 (예 slug)

이것들은 아닙니다 :

taxonomy: 사업

term: 27 (즉 term_id)

흥미롭게 불행히도에 의해 생성 된 드롭 다운 wp_dropdown_categories()설정된 <option>의의 value(용어의 / 사업)에 대한 속성을 ' term_id, 없는 용어 slug. 따라서 위의 스 니펫에서 다음과 같이 $wp_query->query_vars['term']숫자 term_id에서 문자열 slug로 변환해야합니다 (이것은 데이터베이스를 쿼리하는 가장 성능이 좋은 방법은 아니지만 WordPress가 term_ids에 대한 지원을 쿼리에 추가 할 때까지 최선을 다합니다!) :

<?php
$term = get_term_by('id',$qv['term'],'business');
$qv['term'] = $term->slug;

그리고 그게 다야! 이 두 기능을 사용하면 원하는 필터링을 얻을 수 있습니다.

하지만 더 기다려! :-)

계속해서 목록에 "비즈니스" 열을 추가했습니다. 왜냐하면 다음 질문이 될 것이라는 것을 알았 기 때문입니다. 필터링 대상에 대한 열이 없으면 최종 사용자에게는 매우 혼란 스러울 수 있습니다. (저는 스스로 어려움을 겪었고 코더였습니다!) 위의 스크린 샷에서 이미 "비즈니스" 열을 볼 수 있습니다 .

3 단계 : manage_posts_columns필터 후크

게시물 목록에 열을 추가하려면 두 개 이상의 후크를 호출해야합니다. 첫 번째는 manage_posts_columns또는 manage_listing_posts_columns대신 호출 한 포스트 유형별 버전 입니다. 하나의 매개 변수 ( posts_columns)를 허용 하며 다음에서 호출됩니다 /wp-admin/includes/template.php(v3.0.1에서는 호출이 623 행에 있음).

<?php
add_action('manage_listing_posts_columns', 'add_businesses_column_to_listing_list');
function add_businesses_column_to_listing_list( $posts_columns ) {
    if (!isset($posts_columns['author'])) {
        $new_posts_columns = $posts_columns;
    } else {
        $new_posts_columns = array();
        $index = 0;
        foreach($posts_columns as $key => $posts_column) {
            if ($key=='author')
                $new_posts_columns['businesses'] = null;
            $new_posts_columns[$key] = $posts_column;
        }
    }
    $new_posts_columns['businesses'] = 'Businesses';
    return $new_posts_columns;
}

당신의 manage_posts_columns값이 표시 항목 헤더이고 키가 내부 칼럼 식별자이다 후크 함수 열의 배열 전달됩니다. 표준 열 식별자에는 다음과 같은 것들이 포함될 수 있습니다 : 'cb', 'title',, 'author'' 'date'` 등

'cb'상기 인 checkbox열은 모두 'title''date'참조 post_title하고 post_date로부터 wp_posts각각 표. 'author'물론 post_author저자 이름이 wp_users테이블 에서 검색된 후의 필드 입니다.

'cb'게시물 열의 스크린 샷은 확인란입니다.
(출처 : mikeschinkel.com )

위해 manage_posts_columns후크 우리는 단순히 우리의 열을 삽입하고자하는 businesses$posts_columns전에 배열 'author'을 제거하지 않은 다른 플러그인을 가정, author아직 목록에서!

$new_posts_columns['businesses'] = 'Businesses';

( 내가 쓴 add_businesses_column_to_listing_list()이 PHP가 나에게 발생 한다 ?!? 아니면 적어도 그것을 할 수있는 워드 프레스 코어의 기능이있을거야 적절한 순서 연관 배열에 값을 삽입하는 쉬운 방법이? 그러나 구글 이후 제안 된 대안이 있다면 미리 모든 귀를 기울이고 감사 할 것입니다!)

마침내 우리를 ...

4 단계 : manage_posts_custom_column행동 훅

두 번째로 비즈니스를 열에 표시하기 위해 수행해야 할 두 번째 일은 실제로 manage_posts_custom_column작업 후크를 사용하여 연결된 각 비즈니스의 이름을 출력하는 것입니다 . 이 후크는 두 개의 매개 변수 ( column_idpost_id)를 허용하며 /wp-admin/includes/template.php(v3.0.1에서는 호출이 1459 행에 있음)에서 호출됩니다.

<?php
add_action('manage_posts_custom_column', 'show_businesses_column_for_listing_list',10,2);
function show_businesses_column_for_listing_list( $column_id,$post_id ) {
    global $typenow;
    if ($typenow=='listing') {
        $taxonomy = 'business';
        switch ($column_name) {
        case 'businesses':
            $businesses = get_the_terms($post_id,$taxonomy);
            if (is_array($businesses)) {
                foreach($businesses as $key => $business) {
                    $edit_link = get_term_link($business,$taxonomy);
                    $businesses[$key] = '<a href="'.$edit_link.'">' . $business->name . '</a>';
                }
                //echo implode("<br/>",$businesses);
                echo implode(' | ',$businesses);
            }
            break;
        }
    }
}

이 후크는 각 게시물 (/ 비즈니스) 행의 각 열에 대해 호출됩니다. 먼저 listing맞춤 게시물 유형 으로 만 작업하고 있는지 확인한 다음 switch문을 사용하여 에 대해 테스트합니다 column_id. 나는 선택 switch이 후크는 종종 여러 열에 대한 출력을 생성하는 데 사용되기 때문에 우리는이처럼 보일 수 많은 다른 포스트 유형에 대해 하나 개의 기능을 사용 특히 :

<?php
add_action('manage_posts_custom_column', 'my_manage_posts_custom_column',10,2);
function my_manage_posts_custom_column( $column_id,$post_id ) {
    global $typenow;
    switch ("{$typenow}:{$column_id}") {
    case 'listing:business':
        echo '...whatever...';
        break;
    case 'listing:property':
        echo '...whatever...';
        break;
    case 'agent:listing':
        echo '...whatever...';
        break;
    }
}

유스 케이스를 조금만 더 get_the_terms()살펴보면이 분류 체계의 용어 목록 (즉,이 목록의 비즈니스)을 반환 하는 함수를 볼 수 있습니다 . 일반적으로 연관된 게시물을 나열하는 용어 프론트 엔드 웹 페이지의 퍼머 링크 를 얻습니다. 용어는 있지만 설치된 테마 및 / 또는 플러그인에 따라 다를 수 있습니다.

우리는 하이퍼 링크를 사용하여 용어를 하이퍼 링크하기 위해 퍼머 링크를 사용합니다. 그런 다음 모든 하이퍼 링크 용어 (/ businesses)를 파이프 ( ' |') 문자로 구분하여 병합 하여 PHP 버퍼로 출력하여 사용자의 브라우저 / HTTP 클라이언트로 보냅니다.

<?php
$businesses = get_the_terms($post_id,$taxonomy);
if (is_array($businesses)) {
    foreach($businesses as $key => $business) {
        $edit_link = get_term_link($business,$taxonomy);
        $businesses[$key] = '<a href="'.$edit_link.'">' . $business->name . '</a>';
    }
    //echo implode("<br/>",$businesses);
    echo implode(' | ',$businesses);
}

이제 우리는 마침내 끝났습니다.

요약

요약하자면 사용자 정의 게시물 목록 페이지에서 필터와 관련 열을 모두 가져 오려면 다음 4 개의 후크를 사용해야합니다 (아, 게시물 및 페이지에서도 작동 함).

  • 1 단계 : restrict_manage_posts행동 훅.
  • 2 단계 : parse_query필터 후크
  • 3 단계 : manage_posts_columns필터 후크
  • 4 단계 : manage_posts_custom_column행동 훅

코드를 다운로드 할 수있는 곳

그러나 위의 모든 내용을 읽도록 강요하면 코드를 파내어 시험해 볼 수 있다면 확실히 좋은 사람이 아닐 것입니다! 그러나 일부 사람들의 말과는 반대로 나는 훌륭합니다. 그래서 여기에 간다.

@tarasm 참고 : 나는 용 훅 (Hook)을 포함register_post_type()하고register_taxonomy()다른 사람들을 다시 만들 필요없이이 밖으로 시도 할 수 있도록합니다. 이것을 테스트하기 전에이 두 함수 호출을 삭제하고 싶을 것입니다.


원래 답변 :

안녕하세요 @tarasm :

이 화면과 같이 상단에서 하나의 드롭 다운 을 찾고 있습니까? 또는 포스트 레코드 당 하나의 드롭 다운 을 찾고 있습니까? 그렇다면 후자가 어떻게 작동 할 것으로 예상됩니까?

WordPress 관리자에서 사용자 정의 게시물 유형에 대한 정렬 기준 기능을 작성하는 방법
(출처 : mikeschinkel.com )

전자 의 경우 Wordpress 사용자 정의 게시물 유형의 관리 영역을 사용자 정의 필드로 정렬하는 방법에 대한 질문에 대한이 답변을 살펴보십시오 . 그것이 당신이 필요한 것이라면 분류와 관련된 더 많은 세부 사항을 제공 할 수 있습니다.


카테고리 필터를 표시하는 상단의 1 드롭 다운을 찾고 있습니다. 사용자 정의 코드를 작성하지 않고이 작업을 수행하는 표준 방법이 있다면 방황했습니다.
Taras Mankovski

처음에는 홍당무 커스텀 코드없이 할 수 있다고 생각하지 않지만 커스텀 코드가 중요하다고 생각하지 않습니다. 준비를 의뢰하는 고객 전화가 있으므로 오늘 나중에해야합니다.
MikeSchinkel

2
동일한 필터에서 2 개의 다른 분류 체계를 필터링하려고하면 실제로 솔루션 (somatic 및 MikeSchinkel)이 작동하지 않습니다 .- / 2+를 동시에 필터링하려고하면 항상 최신 분류 체계를 필터링하십시오.
Ünsal Korkmaz

1
@ Ünsal 현재 WordPress (3.0) 버전은 여러 분류법 쿼리를 지원하지 않지만 버전 3.1에서 변경 될 것이라고 들었습니다. 이 예제를 여러 분류법과 함께 사용하려면 Posts_join 및 posts_where 필터 후크를 통해 쿼리에 조인과 위치를 추가해야합니다.
매니 Fleurmond

1
WP 3.1 이상에서는 @ drew-gourley 답변에서 1 단계와 2 단계가 더 좋습니다 (실제로 2 단계가 효과가 없었습니다. 새로운 WordPress 에서이 필터링에 변경 사항이 있다고 생각합니다).
Tomasz Struczyński

44

대체 구현을 공유하고 싶었습니다. 이것을 알아낼 때 Mike의 놀라운 자습서가 없었으므로 솔루션이 약간 다릅니다. 특히 Mike의 1 단계 를 단순화 하고 2 단계를 제거 하겠습니다 . 다른 단계는 여전히 적용 가능합니다.

Mike의 자습서에서를 사용 wp_dropdown_categories()하면 일부 수동 목록 작성이 필요하지만 슬러그 대신 ID 사용을 처리 하려면 복잡한 조건부 쿼리 수정 ( 2 단계 )이 필요합니다. 다중 분류법 필터와 같은 다른 시나리오를 처리하기 위해 해당 코드를 수정하는 어려움은 말할 것도 없습니다.

또 다른 방법은 결함 wp_dropdown_categories()을 전혀 사용하지 않고 자체 드롭 다운 선택 목록을 처음부터 작성하는 것입니다. 그렇게 복잡하지 않고 30 줄 미만의 코드를 취하며 후크가 전혀 필요하지 않습니다 parse_query.

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>";
        }
    }
}

원하는 분류 체계를 $filters배열에 연결하기 만하면 여러 분류 체계 필터를 신속하게 출력 할 수 있습니다. 그들은 Mike의 스크린 샷과 정확히 동일하게 나타납니다. 그런 다음 # 3# 4 단계를 수행 할 수 있습니다 .


4
@somatic- 멋진 업데이트! 예, 사용 wp_dropdown_categories()에는 많은 해결 방법이 필요합니다. 가능한 경우 핵심 기능을 고수하려고하지만 때로는 지적한 것처럼 더 많은 작업이 필요합니다. WordPress에는 종종 문제를 해결하는 좋은 방법이 두 가지 이상 있음을 증명하려고합니다. 잘 했어!
MikeSchinkel

WordPress 3.1에서 작동하지 않았습니다. 정확히 무엇이 바뀌 었는지 파악하려고합니다. 그것은 여전히 ​​작동 해야하는 것처럼 보입니다 : 분류법과 용어 슬러그는 URL에 GET 값으로 표시되지만 결과는 모두 0 결과입니다.
Manny Fleurmond

이 작업을 시도했지만 parse_query 후크를 사용하고 분류법의 쿼리 변수를 확인하고이를 기반으로 분류법 및 용어 쿼리 변수를 설정하는 것이 유일한 방법이었습니다. WP 사용하기 3.1. 필터를 제출할 때 분류 및 용어가 URL에 표시되어야합니까?
sanchothefat

2
나를 위해 매력처럼 작동합니다! 실제로 매우 우아한 솔루션. 나는 당신에게 맥주를 빚지고 있습니다 :)
Michal Mau

@somatic 이것은 훌륭하지만 $ term-> count가 해당 게시물 유형에 대한 용어 만 계산하도록하는 방법이 있습니까? 예를 들어 사진과 비디오 모두에 대한 사용자 정의 분류법이있는 경우 비디오 사용자 정의 게시물 유형을 볼 때 해당 용어를 사용하는 총 비디오 게시물 수 대신 두 사용자 정의 게시물 유형에서 해당 용어에 대한 총 게시물 수를 표시합니다. 기간.
Greenhoe

13

다음은이를 사용하는 모든 사용자 정의 게시물 유형에 적용되는 모든 분류에서 필터를 자동으로 작성하고 적용하는 버전입니다. 어쨌든, 나는 또한 그것을 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'를 추가하는 플러그인을 사용하고 있습니다.이를 변경하거나 해당 인수를 제거하여 기본값으로 폴백해야합니다.


실제로 매우 섹시합니다. 나는 오류 통지를 받고 있었으므로 모두보기 0 값과 관련된 용어를 찾으려고하지 않기 위해 if (isset ($ var))를 if (isset ($ var) && $ var> 0)으로 변경했습니다. 아, 그리고 i를 todo_convert_restrict 기능에 $ 쿼리 반환했다
helgatheviking

11

늦은 답변

편집하다

필자는 이 기능을 가장 쉬운 방법으로 추가하는 플러그인 인 Filterama를 작성 했습니다 .

WordPress 3.5 이상 업데이트

일이 훨씬 쉬워 졌으므로 여기에 플러그인 또는 mu-plugin과 같은 매우 간단한 솔루션이 있습니다.

가능한 적은 리소스를 사용하고 필요한 화면에만로드하며 모든 사용자 지정 분류 체계에 대해 열 + 필터를 추가합니다.

add_action( 'plugins_loaded', array( 'WCM_Admin_PT_List_Tax_Filter', 'init' ) );
class WCM_Admin_PT_List_Tax_Filter
{
    private static $instance;

    public $post_type;

    public $taxonomies;

    static function init()
    {
        null === self::$instance AND self::$instance = new self;
        return self::$instance;
    }

    public function __construct()
    {
        add_action( 'load-edit.php', array( $this, 'setup' ) );
    }

    public function setup()
    {
        add_action( current_filter(), array( $this, 'setup_vars' ), 20 );

        add_action( 'restrict_manage_posts', array( $this, 'get_select' ) );

        add_filter( "manage_taxonomies_for_{$this->post_type}_columns", array( $this, 'add_columns' ) );
    }

    public function setup_vars()
    {
        $this->post_type  = get_current_screen()->post_type;
        $this->taxonomies = array_diff(
            get_object_taxonomies( $this->post_type ),
            get_taxonomies( array( 'show_admin_column' => 'false' ) )
        );
    }

    public function add_columns( $taxonomies )
    {
        return array_merge( taxonomies, $this->taxonomies );
    }


    public function get_select()
    {
        $walker = new WCMF_walker;
        foreach ( $this->taxonomies as $tax )
        {
            wp_dropdown_categories( array(
                'taxonomy'        => $tax,
                'hide_if_empty'   => true,
                'show_option_all' => sprintf(
                    get_taxonomy( $tax )->labels->all_items
                ),
                'hide_empty'      => true,
                'hierarchical'    => is_taxonomy_hierarchical( $tax ),
                'show_count'      => true,
                'orderby'         => 'name',
                'selected'        => '0' !== get_query_var( $tax )
                    ? get_query_var( $tax )
                    : false,
                'name'            => $tax,
                'id'              => $tax,
                'walker'          => $walker,
            ) );
        }

    }

}

그런 다음 사용자 정의 된 Walker 클래스 만 있으면됩니다.

class WCMF_walker extends Walker_CategoryDropdown
{
    public $tree_type = 'category';
    public $db_fields = array(
        'parent' => 'parent',
        'id'     => 'term_id',
    );
    public $tax_name;

    public function start_el( &$output, $term, $depth, $args, $id = 0 )
    {
        $pad = str_repeat( '&nbsp;', $depth * 3 );
        $cat_name = apply_filters( 'list_cats', $term->name, $term );
        $output .= sprintf(
            '<option class="level-%s" value="%s" %s>%s%s</option>',
            $depth,
            $term->slug,
            selected(
                $args['selected'],
                $term->slug,
                false
            ),
            $pad.$cat_name,
            $args['show_count']
                ? "&nbsp;&nbsp;({$term->count})"
                : ''
        );
    }
}

소용돌이를 주었지만 get_select () 메소드가 누락 된 것 같습니다.
Dave Romsey 2016 년

@ goto10 당신이 옳았습니다. 업데이트되었습니다. Btw : 연결된 플러그인을 사용하는 것이 더 쉽습니다. 플러그인 저장소에서 1-2 주 안에 사용할 수 있습니다. (이미 확인)
kaiser

내가 사용했다 $this->setup_vars();의 시작 부분에 public function setup()있기 위하여 "manage_taxonomies_for_{$this->post_type}_columns"작업
기독교

하지만 테마 function.php와 함께 사용하기 때문일 수 있습니다.add_action( 'init', array( 'WCM_Admin_PT_List_Tax_Filter', 'init' ) );
Christian

@Christian 이것은 테마 자료가 아닙니다. 이것은 플러그인에 속하며 위의 코드는 현재 테마가로드되기 훨씬 전에로드됩니다.
카이저

7

나는 단지 빠른 메모를하고 싶었다. 최신 버전의 WP에서 관리자의 게시물 목록은 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;
  }
}

7

WP 3.2에서 작동합니다!

custom_post_type : custom_taxonomy : 장르

수정 만했다 : // 여기 변경

function restrict_books_by_genre() {
    global $typenow;
    $post_type = 'books'; // change HERE
    $taxonomy = 'genre'; // change HERE
    if ($typenow == $post_type) {
        $selected = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : '';
        $info_taxonomy = get_taxonomy($taxonomy);
        wp_dropdown_categories(array(
            'show_option_all' => __("Show All {$info_taxonomy->label}"),
            'taxonomy' => $taxonomy,
            'name' => $taxonomy,
            'orderby' => 'name',
            'selected' => $selected,
            'show_count' => true,
            'hide_empty' => true,
        ));
    };
}

add_action('restrict_manage_posts', 'restrict_books_by_genre');


function convert_id_to_term_in_query($query) {
    global $pagenow;
    $post_type = 'books'; // change HERE
    $taxonomy = 'genre'; // change HERE
    $q_vars = &$query->query_vars;
    if ($pagenow == 'edit.php' && isset($q_vars['post_type']) && $q_vars['post_type'] == $post_type && isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] != 0) {
        $term = get_term_by('id', $q_vars[$taxonomy], $taxonomy);
        $q_vars[$taxonomy] = $term->slug;
    }
}

add_filter('parse_query', 'convert_id_to_term_in_query');

WP 3.2+를위한 훌륭하고 쉬운 솔루션입니다.
petermolnar

작동하지만 __("Show All {$info_taxonomy->label}")번역 가능한 문자열을 사용하는 잘못된 방법입니다.
Mark Kaplun

2

restrict_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('&nbsp;', $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 .= '&nbsp;&nbsp;('. $category->count .')';
        if ( $args['show_last_update'] ) {
            $format = 'Y-m-d';
            $output .= '&nbsp;&nbsp;' . gmdate($format, $category->last_update_timestamp);
        }
        $output .= "</option>\n";
        }
} 

한 가지 참고 사항-계층 적 분류법 중 일부가 상당히 커서 깊이를 제한하려고 시도했지만 작동하지 않았습니다. wp_dropdown_categories 함수의 버그 일 수 있습니까?


2

이것은 잘 알려져 있지는 않지만 워드 프레스 3.5에서로 전달할 'show_admin_column' => trueregister_taxonomy있습니다. 이것은 두 가지 일을합니다.

  1. 분류 열을 관리자 게시물 유형 목록보기에 추가
  2. 분류 열에서 용어 이름을 클릭하면 실제로 해당 용어로 목록이 필터링 됩니다.

따라서 선택하는 것과 정확히 동일하지는 않지만 거의 동일한 기능으로 너비가 한 줄입니다.

https://make.wordpress.org/core/2012/12/11/wordpress-3-5-admin-columns-for-custom-taxonomies/

또한 읽을 수 있듯이 분류 열을 수동으로 추가하는 데 필요한 새 필터가 있습니다 (실제로 필요한 경우).


1

@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를 가져 오는 것 외에도 부모 및 수준 매개 변수를 사용합니다. 이 함수는 모든 루트 레벨 항을 선택하는 상위 0에 대한 작성 옵션을 가정합니다. 루프에서 함수는 현재 용어를 부모로 사용하고 레벨을 1 씩 증가시켜 재귀 적으로 호출합니다. 그것은 당신이 나무와 짜잔 아래로 갈수록 깊이를 자동으로 측면에 추가합니다!


1

WP 3.3.1에 대한 @Drew Gourley의 답변 업데이트 및 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('&nbsp;', $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";
    }
}

0

새로운 사용자로서 의견을 게시 할 수는 없지만 답변을 게시 할 수 있다는 사실에 사과드립니다.

WordPress 3.1 (RC 1)부터 Mike의 답변 (지난 몇 달 동안 나에게 도움이 되었음)은 더 이상 저에게 효과적이지 않습니다. 분류학 아동에 의해 제한하면 빈 결과가 나타납니다. 나는 Somatic의 업데이트를 시도했고 훌륭하게 작동했습니다. 더 나은 방법 은이 릴리스에서 처리 된 여러 분류법 쿼리를 사용 하는 것입니다.


어떤 이유로 somatic의 버전은 3.1에서 작동하지 않습니다
Manny Fleurmond

0

Mike와 somatic의 두 코드를 모두 시도해 보았고 각 기술에서 하나를 얻는 방법에 대해 궁금했습니다.

Mike의 코드를 사용하면 계층 옵션이 있는 드롭 다운 목록이 표시되어 많은 도움이됩니다. 그러나이 드롭 다운을 표시하기 위해 i를 복제했다 if ($typenow=='produtos') {...}기능에 문 restrict_listings_by_business()또한 if ($pagenow=='edit.php' && ... }에서 convert_business_id_to_taxonomy_term_in_query($query)지금 많은 코드를 제공 기능을.

somatic의 코드를 사용하여 드롭 다운과 bam으로보고 싶은 분류법을 지정하면됩니다. $filters = array('taxo1', 'taxo2');

질문 : 신체적 접근을 할 수 있고 계층 적 옵션을 가질 수 있습니까?

어쨌든이 튜토리얼에 대해 많은 감사를 드렸습니다.


계층 적 솔루션에 대한 나의 대답
Man Fleurmond

0

이에 대한 Mike의 튜토리얼은 훌륭합니다! 내가 스스로 알아 내야한다면이 기능을 내 미디어 카테고리 플러그인에 추가하는 것을 귀찮게하지 않았을 것이다.

즉, parse_query용어를 사용 하고 나서 쿼리를 할 필요가 없다고 생각합니다. 나만의 커스텀 워커 클래스를 만드는 것이 더 깨끗합니다. 그가 글을 쓸 때 3 살이 된 그의 포스트를 썼을 때 아마도 불가능했을 수도 있습니다.

github 에서이 훌륭한 스 니펫을 확인하십시오. 매력처럼 작동하고 드롭 다운 값의 ID를 슬러그로 변경하므로 쿼리를 수정하지 않고 기본적으로 작동합니다.

https://gist.github.com/stephenh1988/2902509

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.