관리자 페이지의 맞춤 게시물 유형에서 맞춤 입력란으로 필터링


11

고급 사용자 정의 필드를 사용하여 경쟁 이름, 답변 등에 대한 사용자 정의 필드를 작성했습니다. 이미지에 표시된대로 경쟁에 대한 사용자 정의 게시물 유형을 작성했으며 Wordpress functions.php를 사용하여 사용자 정의 필드 값에서 열을 작성했습니다.

나는 다른 이름 / 라벨은 아래 그림과 같은 대회에 -dropdown 상자에 "별로 필터"를 얻기 위해 노력하고있어,하지만 난 단지 내가 오히려 사용하지 분류법을 사용하여 솔루션을 찾을 수 있습니다 가능하면 난 단지에 대한 사용자 정의 필드를 사용했기 때문에 다른 모든 것.

사용자 정의 필드 만 사용하여 사용자 정의 "필터 기준"드롭 다운을 만들 수 있습니까?

에 의해 워드 프레스 필터


restrict_manage_posts동작 후크를 사용하여 드롭 다운 상자를 추가 할 수 있습니다 . WP는 자동으로 처리 할 수있는 분류 체계 드롭 다운 목록과 달리 WP가 상자에서 처리 할 내용을 알지 못하므로 필터에 대한 일부 논리를 추가해야한다는 것을 잊지 마십시오.
David Gard

추가 생각으로-원한다면 목록 테이블 내에서 이름 을 링크로 만들 수 있습니다 . 즉, 드롭 다운이 아닌 이름을 클릭하여 경쟁을 필터링 할 수 있습니다.
David Gard

답변:


12

Filter에 대한 결과를 표시하려면이 코드를 사용해보십시오.

add_filter( 'parse_query', 'prefix_parse_filter' );
function  prefix_parse_filter($query) {
   global $pagenow;
   $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';

   if ( is_admin() && 
     'competition' == $current_page &&
     'edit.php' == $pagenow && 
      isset( $_GET['competition-name'] ) && 
      $_GET['competition-name'] != '') {

    $competion_name = $_GET['competition-name'];
    $query->query_vars['meta_key'] = 'competition_name';
    $query->query_vars['meta_value'] = $competition_name;
    $query->query_vars['meta_compare'] = '=';
  }
}

필요에 따라 메타 키와 메타 값을 변경하십시오. "경쟁 이름을 meta_key로,"경쟁 이름 "을 선택 드롭 다운 이름으로 사용했습니다.


니스, 나는 게으른 느낌이 들었습니다 그래서 그는 추가 질문을 제안;)
David Gard

2 개의 답변이 완전한 답변 인 것처럼 보이며 결합되어야합니다.
RCNeil

10

restrict_manage_posts의 동작은 트리거 add_extra_tablenav()당신이 원하는 목록 표에 추가 드롭 다운을 추가하는 방법 인 기능을.

아래 예에서는 먼저 게시물 유형 이 올바른지 확인한 다음 테이블 의 competition_name키에 대해 저장된 모든 DB 값을 가져 옵니다 postmeta(필요에 따라 키 이름을 변경해야 함). 쿼리는 상당히 기본적이며 경쟁 이 게시 되었는지 확인 하고 드롭 다운에서 중복을 원하지 않는 고유 한 값만 취한 다음 알파벳순으로 정렬합니다.

다음으로 결과를 확인하고 (아무것도 드롭 다운을 출력하지 않음) 옵션 (모두 표시하는 defualt 포함)을 구성하십시오. 마지막으로 드롭 다운이 출력됩니다.

내 의견에서 언급했듯이, 이것은 이야기의 끝이 아닙니다. 필터가 활성화 된 경우 원하는 결과 만 표시하도록 목록 테이블에 지시하는 논리가 필요하지만 추가 지원이 필요한 경우이를 살펴보고 다른 질문을 시작하겠습니다. 힌트 -파일을 확인하십시오. /wp-admin/includes/class-wp-posts-list-table.php부모입니다..../wp-class-list-table.php

/**
 * Add extra dropdowns to the List Tables
 *
 * @param required string $post_type    The Post Type that is being displayed
 */
add_action('restrict_manage_posts', 'add_extra_tablenav');
function add_extra_tablenav($post_type){

    global $wpdb;

    /** Ensure this is the correct Post Type*/
    if($post_type !== 'competition')
        return;

    /** Grab the results from the DB */
    $query = $wpdb->prepare('
        SELECT DISTINCT pm.meta_value FROM %1$s pm
        LEFT JOIN %2$s p ON p.ID = pm.post_id
        WHERE pm.meta_key = "%3$s" 
        AND p.post_status = "%4$s" 
        AND p.post_type = "%5$s"
        ORDER BY "%3$s"',
        $wpdb->postmeta,
        $wpdb->posts,
        'competition_name', // Your meta key - change as required
        'publish',          // Post status - change as required
        $post_type
    );
    $results = $wpdb->get_col($query);

    /** Ensure there are options to show */
    if(empty($results))
        return;

    // get selected option if there is one selected
    if (isset( $_GET['competition-name'] ) && $_GET['competition-name'] != '') {
        $selectedName = $_GET['competition-name'];
    } else {
        $selectedName = -1;
    }

    /** Grab all of the options that should be shown */
    $options[] = sprintf('<option value="-1">%1$s</option>', __('All Competitions', 'your-text-domain'));
    foreach($results as $result) :
        if ($result == $selectedName) {
            $options[] = sprintf('<option value="%1$s" selected>%2$s</option>', esc_attr($result), $result);
        } else {
            $options[] = sprintf('<option value="%1$s">%2$s</option>', esc_attr($result), $result);
        }
    endforeach;

    /** Output the dropdown menu */
    echo '<select class="" id="competition-name" name="competition-name">';
    echo join("\n", $options);
    echo '</select>';

}

이것을 사용할 때, 오류가 발생합니다Notice: wpdb::prepare was called incorrectly. The query does not contain the correct number of placeholders (6) for the number of arguments passed (5). Please see Debugging in WordPress for more information. (This message was added in version 4.8.3.) in /[...]/wp-includes/functions.php on line 4773
rassoh

또한 같은 오류가 발생합니다
Vasim Shaikh

0

이것이 누구에게도 효과가 없다면, 내 솔루션은 사용자 정의 게시물 유형의 정렬 가능한 열 목록에 필터링하려고하는 열을 추가해야했습니다.

// Make Custom Post Type Custom Columns Sortable
function cpt_custom_columns_sortable( $columns ) {

    // Add our columns to $columns array
    $columns['item_number'] = 'item_number';
    $columns['coat_school'] = 'coat_school'; 

    return $columns;
} add_filter( 'manage_edit-your-custom-post-type-slug_sortable_columns', 'cpt_custom_columns_sortable' );

0

아래 쿼리를 교체하여 wpdb : prepare 오류를 수정하십시오.

$query = $wpdb->prepare('
        SELECT DISTINCT pm.meta_value FROM %1$s pm
        LEFT JOIN %2$s p ON p.ID = pm.post_id
        WHERE pm.meta_key = "%3$s" 
        AND p.post_status = "%4$s" 
        AND p.post_type = "%5$s"
        ORDER BY "%3$s"',
        $wpdb->postmeta,
        $wpdb->posts,
        'competition_name', // Your meta key - change as required
        'publish',          // Post status - change as required
        $post_type,
        'competition_name' //this is needed a second time to define "%3$s" in ORDER BY
  );
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.