Timber Twig: запросить пользовательский тип поста по категории и вывести шорткод постов - PullRequest
0 голосов
/ 21 марта 2019

Я пытаюсь создать новый пользовательский тип записи с именем report, добавить таксономию, запросить отчеты, а затем создать шорткод в формате [report_listing category="general"] для отображения отчетов в категории «Общие»..

Прямо сейчас, на report/index.twig, я получаю список всех отчетов, используя шорткод [report_listing], и ошибку No reports available при использовании [report_listing category="general"].

Я используюРасширенные пользовательские поля, но это не проблема для этого или остальной части сайта.Категории создаются и связываются с сообщениями, поскольку это пример {{ dump }} вывода на /index.twig для одного отчета при использовании [report_listing], и отображаются все отчеты:

["report_category"]=> array(1) { [0]=> object(Timber\Term)#2131 (15)
{ ["PostClass"]=> string(11) "Timber\Post" ["TermClass"]=> string(4) "Term"
["object_type"]=> string(4) "term" ["_children"]=> NULL ["name"]=> string(7)
"General" ["taxonomy"]=> string(15) "report_category" ["id"]=> int(89) ["ID"]=> int(89)
["term_id"]=> int(89) ["slug"]=> string(7) "general" ["term_group"]=> int(0)
["term_taxonomy_id"]=> int(89) ["parent"]=> int(0) ["count"]=> int(0) ["filter"]=> string(3) "raw" } } 

Я посмотрел ACF Запрос пользовательских типов записей с таксономиями , но я использую параметры tax_query.В журнале отладки нет ошибок php.

Цикл на index.twig:

{% if reports %}

    {% for report in reports %}

        (html)

    {% endfor %}

    {% else %}

        No reports available.

{% endif %}

Полный код в плагине, который генерирует пользовательский тип записи и генерирует шорткод:

// Add a standard Custom Post Type called report

function add_report_post_type() {
    register_post_type('report',
    array(
        'labels' => array(
            'name' => __('Reports'),
            'singular_name' => __('Report'),
            'add_new' => __('Add New'),
            'add_new_item' => __('Add Report'),
            'edit' => __('Edit'),
            'edit_item' => __('Edit Report'),
            'new_item' => __('New Report'),
            'view' => __('View Report'),
            'view_item' => __('View Report'),
            'search_items' => __('Search Reports'),
            'not_found' => __('No reports found'),
            'not_found_in_trash' => __('No reports found in Trash')
        ),
        'public' => true,
        'hierarchical' => true,
        'has_archive' => false,
        'supports' => array(
            'title',
            'revisions'
        ),
        'can_export' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-clipboard',
        'rewrite' => array(
            'slug' => 'report',
            'with_front' => false,
            'hierarchical' => true
        ),
        )
    );
}
add_action('init', 'add_report_post_type');


// Add categories

function reports_taxonomy() {
    $labels = array(
        'name'                       => _x( 'Report Categories', 'Taxonomy General Name', 'text_domain' ),
        'singular_name'              => _x( 'Report Categories', 'Taxonomy Singular Name', 'text_domain' ),
        'menu_name'                  => __( 'Categories', 'text_domain' ),
        'all_items'                  => __( 'All Items', 'text_domain' ),
        'parent_item'                => __( 'Parent Item', 'text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
        'new_item_name'              => __( 'New Item Name', 'text_domain' ),
        'add_new_item'               => __( 'Add New Item', 'text_domain' ),
        'edit_item'                  => __( 'Edit Item', 'text_domain' ),
        'update_item'                => __( 'Update Item', 'text_domain' ),
        'view_item'                  => __( 'View Item', 'text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
        'popular_items'              => __( 'Popular Items', 'text_domain' ),
        'search_items'               => __( 'Search Items', 'text_domain' ),
        'not_found'                  => __( 'Not Found', 'text_domain' ),
        'no_terms'                   => __( 'No items', 'text_domain' ),
        'items_list'                 => __( 'Items list', 'text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
    );
}


function create_report_taxonomy () {
register_taxonomy(
        'report_category', 'report',
        array(
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'meta_box_cb'                   => false,
            )
    );
}
add_action( 'init', 'create_report_taxonomy', 2 );



// Query all reports and create shortcode

function report_get_listing($params) {
    $reports = [];
    $context = Timber::get_context();

    $args = array(
        'post_type' => 'report',
        'orderby' => [
            'weight' => 'ASC',
            'post_date' => 'DESC'
        ],
        'post_status' => 'publish',
        'meta_query' => [
            'weight' => [
                'key'     => 'weight',
                'compare' => 'EXISTS',
                'type'    => 'NUMERIC'
            ],

        ],
    );


// Check for a report category in the query

  if (!empty($params['category'])) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'report_category',
                'terms' => explode(',', $params['category']),
                'field' => 'slug',
                'operator' => 'IN',
            ),
        );
    }

    query_posts($args);

    $report_listing = Timber::get_posts($args);

    foreach ($report_listing as $p) {
        $reports[] = get_single_report($p);
    }

    $context['reports'] = $reports;

    return Timber::compile('report/index.twig', $context);
}


// Build all the reports for the shortcode

function get_single_report($post) {
    $report = [
        'id' => $post->ID,
        'link' => $post->link,
        'title' => $post->title(),
        'date' => $post->post_date,
        'summary' => $post->get_field('summary'),
        'report_category' => $post->get_field('report_category'),
        'document' => $post->get_field('document'),
        'image' => $post->get_field('image'),
        'url' => $post->get_field('url')
    ];
    return $report;
}
add_shortcode('report_listing', 'report_get_listing');

Ответы [ 2 ]

2 голосов
/ 31 марта 2019

Проблема оказалась странным конфликтом плагинов :(. Я обнаружил, что с помощью монитора запросов. Приведенный выше пример кода в моем вопросе работает нормально.

0 голосов
/ 26 марта 2019

Читая ваш текущий вопрос и код, я вижу несколько проблем.Но я хотел бы обратиться к функции шорткода, которая, как мне кажется, заставляет отчеты не перечисляться по категориям.

// Query all reports and create shortcode

function report_get_listing($params) {
    $reports = [];

   $a = shortcode_atts( array(
    'category' => '', // [report_listing category=""]
   ), $params );

    $context = Timber::get_context();

    $args = array(
        'post_type' => 'report',
        'orderby' => [
            'weight' => 'ASC',
            'post_date' => 'DESC'
        ],
        'post_status' => 'publish',
        'meta_query' => [
            'weight' => [
                'key'     => 'weight',
                'compare' => 'EXISTS',
                'type'    => 'NUMERIC'
            ],

        ],
    );


  // Check for a report category in the query

  if (!empty($a['category'])) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'report_category',
                'terms' => explode(',', $a['category']),
                'field' => 'slug',
                'operator' => 'IN',
            ),
        );
    }

    query_posts($args);

    $report_listing = Timber::get_posts($args);

    foreach ($report_listing as $p) {
        $reports[] = get_single_report($p);
    }

    $context['reports'] = $reports;

    return Timber::compile('report/index.twig', $context);
}

add_shortcode('report_listing', 'report_get_listing');
...