【问题标题】:WordPress shortcode to display related posts用于显示相关帖子的 WordPress 简码
【发布时间】:2019-06-20 11:41:26
【问题描述】:

显示相关帖子的 WordPress 简码

如何在 WordPress 中手动显示相关文章

这是我的代码:

function related_posts_shortcode( $atts ) {
extract(shortcode_atts(array(
    'limit' => '5',
), $atts));

global $wpdb, $post, $table_prefix;

if ($post->ID) {
    $retval = '<ul>';
    // Get tags
    $tags = wp_get_post_tags($post->ID);
    $tagsarray = array();
    foreach ($tags as $tag) {
        $tagsarray[] = $tag->term_id;
    }
    $tagslist = implode(',', $tagsarray);

    // Do the query
    $q = "SELECT p.*, count(tr.object_id) as count
        FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
            AND p.post_status = 'publish'
            AND p.post_date_gmt < NOW()
        GROUP BY tr.object_id
        ORDER BY count DESC, p.post_date_gmt DESC
        LIMIT $limit;";

    $related = $wpdb->get_results($q);
    if ( $related ) {
        foreach($related as $r) {
            $retval .= '
<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';  
   }
    } else {
        $retval .= '<li>No related posts found</li>';
    }
    $retval .= '</ul>
  ';
    return $retval;
    }
    return;
 }
 add_shortcode('related_posts', 'related_posts_shortcode');

它不像我想的那样工作。我做错了什么?

感谢任何帮助。

【问题讨论】:

    标签: php jquery wordpress post


    【解决方案1】:

    使用 Class WP Query 获取自定义循环 wp query classShortcode API

    // Create Shortcode related_posts_
    // Shortcode: [related_posts_ number="5"]
    function create_relatedposts_shortcode($atts) {
    
            $atts = shortcode_atts(
                array(
                   'number' => '5',
                ), $atts, 'related_posts_'
            );
    
            // Custom WP query relatedposts
            $args_relatedposts = array(
                'posts_per_page' => $atts['number'],
                'order' => 'DESC',
            );
    
            $relatedposts = new WP_Query( $args_relatedposts );
    
            if ( $relatedposts->have_posts() ) {
                while ( $relatedposts->have_posts() ) {
                    $relatedposts->the_post();
                    // add here your html for post 
                }
            } else {
                // not found post 
            }
    
            wp_reset_postdata();
    
    }
    add_shortcode( 'related_posts_', 'create_relatedposts_shortcode' );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多