WordPress:post_type->重写[' slug']返回post_type,而不是slug

时间:2017-06-05 15:23:59

标签: wordpress

在我的应用程序中,我需要在管理信息中心中创建一个小部件,该小部件将显示与每个帖子的数量相关联的所有post_types部分。

为完成上述操作,我在functions.php文件中添加了以下代码块:

add_action('wp_dashboard_setup', 'tp_post_counts_reference');

    function tp_post_counts_reference() {
        global $wp_meta_boxes;
        wp_add_dashboard_widget('custom_help_widget', 'Posts in all post types', 'custom_dashboard_help');
    }

    function custom_dashboard_help() {
        $types = get_post_types();
        foreach( $types as $type )
        {
            if($type != 'travelog' && $type != 'package_tour' && $type != 'hotel-info') continue;
            $typeobj = get_post_type_object( $type );

            echo '<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish . '<br />';
        }
    }

但是$typeobj->rewrite['slug']实际上输出的是post_type而不是相应的slug。

例如: 我有以下自定义帖子类型

Travelog(名称:Travelog,post_type:travelog,slug:travelogs)
酒店信息(姓名:酒店信息,post_type:hotel-info,slug:酒店)

的实际输出
'<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish

<a href="/travelog">Travelog</a>: 6

<a href="/hotel-info">Hotel</a>: 11

当我希望他们输出时:

<a href="/travelogs">Travelog</a>: 6

<a href="/hotels">Hotel</a>: 11

请告诉我我做错了什么:(

注意:我的WP版本是4.7.5

1 个答案:

答案 0 :(得分:1)

我建议您不要尝试手动构建帖子类型的网址,而是利用内置的WordPress功能get_post_type_archive_link

看起来像这样:

function custom_dashboard_help() {
    $types = get_post_types();

    // Alternate method for testing if custom type.
    $custom_types = array( 'travelog', 'package_tour', 'hotel-info' );
    foreach( $types as $type ) {
        // If not a custom post type, don't render the link
        if( ! in_array( $type, $custom_types ) ) {
            continue;
        }

        $typeobj = get_post_type_object( $type );

        // Use get_post_type_archive_link function to get URL
        echo '<a href="' . get_post_type_archive_link( $type ) . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts( $type )->publish . '<br />';
    }
}
相关问题