Hello great WordPress developers, I would like to list posts from a specif category in the 2nd or middle paragraph of the post.
I tried adding some scripts to my function.php to achieve that, but I couldn't get the 2nd or middle paragraph of the article, which is the key part, to work.
function custom_related_posts( $content ) {
global $post;
$current_post_id = get_the_ID();
$html = '';
if ( is_singular( 'post' ) ) {
//get the categories of the current post
$cats = get_the_category( $current_post_id );
$cat_array = array();
foreach ( $cats as $key1 => $cat ) {
$cat_array[ $key1 ] = $cat->slug;
}
//get the tags of the current post
$tags = get_the_tags( $current_post_id );
$tag_array = array();
foreach ( $tags as $key2 => $tag ) {
$tag_array[ $key2 ] = $tag->slug;
}
$related_posts = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat_array
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag_array
)
),
'showposts' => 6,
'post_type' => array( 'post' ),
'category_name' => 'songs',
'orderby' => 1
)
);
if ( $related_posts->have_posts() ) {
$html .= '<div class="related-posts"><h3>Related posts</h3><ul class="related_post wp_rp"> ';
while ( $related_posts->have_posts() ) {
$related_posts->the_post();
$html .= '<li data-position="0" data-poid="in-215276" data-post-type="none"><a rel="bookmark" class="wp_rp_thumbnail" href="';
$html .= get_the_permalink();
$html .= '">';
if ( has_post_thumbnail( $post->ID ) ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
$html .= '<img class="featured-image" src="' . esc_url( $image[0] ) . '">';
}
$html .= '<a class="wp_rp_title" style="color:#333333" href="';
$html .= get_the_permalink();
$html .= '">';
$html .= '' . get_the_title() . '';
$html .= '</a>';
$html .= '</li>';
}
$html .= '</ul></div>';
wp_reset_postdata();
} else {
$html .= '<div class="related-posts">' . esc_html__( 'No related posts were found.', 'textdomain' ) . '</div>';
}
$content .= $html;
}
return $content;
}
add_filter( 'the_content', 'custom_related_posts' );
Post link: https://www.voxlyrics.com/drake-fountains-ft-tems/