Timber Twig:按类别查询自定义帖子类型并输出帖子的简短代码

时间:2019-03-20 21:58:10

标签: php wordpress twig advanced-custom-fields timber

我要做的是生成一个名为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 Querying custom post types with taxonomies,但是我正在使用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 个答案:

答案 0 :(得分:2)

这个问题原来是奇怪的插件冲突:(。我发现使用查询监视器。问题中的上述示例代码正常工作。

答案 1 :(得分:0)

通过阅读您当前的问题和代码,我可以看到一些问题。但是我想解决一下短代码功能,我认为这导致报告没有按类别列出。

void Start()
{
    //Invoke("Kill", life);
}

// Update is called once per frame
void Update()
{
    transform.position += transform.forward * speed * Time.deltaTime;

    if (isGrounded)
    {
      StartCoroutine( Kill());
    }
}

void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Ground")
    {
        isGrounded = true;
    }
}
//
void OnCollisionExit(Collision other)
{
    if (other.gameObject.tag == "Ground")
    {
        isGrounded = false;
    }
}
//Explosion code
IEnumerator Kill()
{
    Vector3 explosionCenterPosition = transform.position;
    rb.AddExplosionForce(explosionForce, explosionCenterPosition, explosionRadius);
    yield return new WaitForSeconds(2f);
    Destroy(gameObject);

}