wordpress网站上的相关职位

时间:2016-11-04 14:34:49

标签: php wordpress

请帮助我,我被困住了。我需要根据评论下的类别来定位相关帖子,还要将附加的图片添加到列表中的每个内容并阅读更多内容。请参阅图片,了解我的意思。

Post position to resolve

这是我目前的代码:

single.php中

<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
get_header();

$post_type = get_post_type();
$sidebarPosition = get_option ( THEME_NAME."_sidebar_position" ); 
$sidebarPositionCustom = get_post_meta ( $post->ID, THEME_NAME."_sidebar_position", true ); 

$related = ci_get_related_posts( get_the_ID(), 3 );

if( $related->have_posts() ):
  ?>
  <div class="related-posts">
    <h3>Related posts</h3>
    <ul>
      <?php while( $related->have_posts() ): $related->the_post(); ?>
        <li>
          <h4><?php the_title(); ?></h4>
          <?php the_excerpt(); ?>
        </li>
      <?php endwhile; ?>
    </ul>
  </div>
  <?php
endif;
wp_reset_postdata();

if($post_type == "gallery") {
    get_template_part(THEME_INCLUDES.'gallery-single','style-1');
} else {
    get_template_part(THEME_INCLUDES.'news','single');
    get_footer();
}


?>

的functions.php

function ci_get_related_posts( $post_id, $related_count, $args = array() ) {
  $args = wp_parse_args( (array) $args, array(
    'orderby' => 'rand',
    'return'  => 'query', // Valid values are: 'query' (WP_Query object), 'array' (the arguments array)
  ) );

  $related_args = array(
    'post_type'      => get_post_type( $post_id ),
    'posts_per_page' => $related_count,
    'post_status'    => 'publish',
    'post__not_in'   => array( $post_id ),
    'orderby'        => $args['orderby'],
    'tax_query'      => array()
  );

  $post       = get_post( $post_id );
  $taxonomies = get_object_taxonomies( $post, 'names' );

  foreach( $taxonomies as $taxonomy ) {
    $terms = get_the_terms( $post_id, $taxonomy );
    if ( empty( $terms ) ) continue;
    $term_list = wp_list_pluck( $terms, 'slug' );
    $related_args['tax_query'][] = array(
      'taxonomy' => $taxonomy,
      'field'    => 'slug',
      'terms'    => $term_list
    );
  }

  if( count( $related_args['tax_query'] ) > 1 ) {
    $related_args['tax_query']['relation'] = 'OR';
  }

  if( $args['return'] == 'query' ) {
    return new WP_Query( $related_args );
  } else {
    return $related_args;
  }
}

1 个答案:

答案 0 :(得分:0)

我没有想要应用相关帖子的post_type,但是你可以在你需要的模板部分插入你在single.php中放置的代码(即:single-content-news.php)。找到此模板,您将能够准确查看添加代码的位置

你也可以试着把:

if($post_type == "gallery") {
    get_template_part(THEME_INCLUDES.'gallery-single','style-1');
    // does this template emebd the footer ? if not, if you want add get_footer(); in this statement
} else {
    get_template_part(THEME_INCLUDES.'news','single');
    get_footer();
}

$related = ci_get_related_posts( get_the_ID(), 3 );之前