首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将post标签作为类添加到自定义post类型循环中?

将post标签作为类添加到自定义post类型循环中的方法如下:

  1. 首先,需要创建一个自定义的post类型。可以使用WordPress提供的register_post_type函数来实现。例如,创建一个名为"custom_post"的自定义post类型:
代码语言:txt
复制
function create_custom_post_type() {
    register_post_type('custom_post',
        array(
            'labels' => array(
                'name' => 'Custom Posts',
                'singular_name' => 'Custom Post'
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail')
        )
    );
}
add_action('init', 'create_custom_post_type');
  1. 接下来,需要创建一个名为"custom_tag"的自定义分类法(taxonomy),用于给自定义post类型添加标签。可以使用register_taxonomy函数来实现。例如:
代码语言:txt
复制
function create_custom_taxonomy() {
    register_taxonomy(
        'custom_tag',
        'custom_post',
        array(
            'label' => 'Custom Tags',
            'rewrite' => array('slug' => 'custom-tag'),
            'hierarchical' => true
        )
    );
}
add_action('init', 'create_custom_taxonomy');
  1. 现在,可以在自定义post类型的循环中使用post标签作为类。可以使用WP_Query类来获取自定义post类型的循环,并使用get_the_terms函数获取每个post的标签。例如:
代码语言:txt
复制
$args = array(
    'post_type' => 'custom_post',
    'posts_per_page' => 10
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        
        $post_tags = get_the_terms(get_the_ID(), 'custom_tag');
        $post_classes = array();
        
        if ($post_tags && !is_wp_error($post_tags)) {
            foreach ($post_tags as $tag) {
                $post_classes[] = $tag->slug;
            }
        }
        
        echo '<div class="' . implode(' ', $post_classes) . '">';
        the_title();
        echo '</div>';
    }
    
    wp_reset_postdata();
} else {
    echo 'No custom posts found.';
}

以上代码会获取10个自定义post类型的循环,并将每个post的标签作为类添加到对应的HTML元素中。

这是一个基本的示例,你可以根据自己的需求进行修改和扩展。另外,腾讯云提供了云服务器、云数据库、云存储等相关产品,可以根据具体需求选择适合的产品。你可以访问腾讯云官方网站(https://cloud.tencent.com/)了解更多详情。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券