将默认相关帖子代码修改为自定义帖子类型

时间:2020-03-15 作者:user5248

我想将这个基本的相关帖子代码修改为我的自定义帖子类型“视频”。由于我是新手,有人能帮我理解我需要在代码中修改什么,以便从我的自定义帖子类型视频中提取相关内容吗?

问题代码:

<?php
// Get the current post ID
$post_id = get_the_ID();

// Get the post category
$cats = wp_get_post_categories($post_id);

if ($cats) {

?> 
          <h4>Related Posts</h4>

               <div id="posts-container" style="display: flex; align-items: center; justify-content: center;">

        <?php

    // Get the category ID
    $cat_id = $cats[0];

    // Build the query
    $args = array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => \'4\',
        \'cat\' => $cat_id
    );


    $query = new WP_Query($args);

    $posts = $query->posts;

    // Loop through the posts
    foreach ($posts as $post) {

        // Exclude the current post
        if ($post->ID != $post_id) {

?>

        <a class="ct-link-text" href="<?php
            echo get_the_permalink($post->ID);
?>" target="_self" style="padding: 5px;">
                    <div style="width: 300px; height: 300px; align-items: center; text-align: center; justify-content: center; 
            background-repeat: no-repeat; background-position: 50% 50%;background-image: linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)), url(<?php
            echo get_the_post_thumbnail_url($post->ID);
?>);   ;background-size: auto;" class="ct-div-block">
              <h4 style="color: #fff; font-size: 20px;"><?php
            echo get_the_title($post->ID);
?></h4>
            </div>
            </a>


        <?php

        }

    }

    wp_reset_query();

?></div><?php

}

?>

1 个回复
SO网友:Tony Djukic

假设您的CPT是“视频”,您会使用:

// Build the query
    $args = array(
        \'post_type\' => \'videos\',
        \'posts_per_page\' => \'4\',
        \'cat\' => $cat_id
    );

相关推荐