如何在第1、5、7、10个articlex元素后插入广告内容?
在WordPress短代码中指定位置插入广告的实现方法
需求:我已创建dispost短代码函数,用于在WordPress中根据搜索词显示文章,通过循环生成<articlex>元素展示内容。现在需要在第1、5、7、10个<articlex>元素后插入广告。
原代码:
/** * Display posts. */ function dispost($atts, $content = null) { global $post; extract(shortcode_atts(array( 'cat' => '', 'num' => '5', 'order' => 'DESC', 'orderby' => 'rand', 's' => '' ), $atts)); $args = array( 'cat' => $cat, 'posts_per_page' => $num, 'order' => $order, 'orderby' => $orderby, 's' => $s, ); $output = ''; $posts = get_posts($args); foreach($posts as $post) { setup_postdata($post); $output .= ' <articlex> <a href="'. get_the_permalink() .'"> '. get_the_post_thumbnail( $post->ID, 'Medium Large', array( 'class' => 'alignleft' ) ) .' </a> <div class="text"> <h2><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></h2> <p> '. get_the_excerpt() .' <br> <a class="post-preview-link" href="'. get_the_permalink() .'">Read More...</a> </p> </div> </articlex>'; } wp_reset_postdata(); return '<main>'. $output .'</main>'; }
实现方法
核心思路是在循环中跟踪当前生成的<articlex>序号,当序号匹配目标位置时插入广告代码:
- 初始化计数器,记录当前生成的
<articlex>数量 - 定义需要插入广告的位置数组(对应第N个
<articlex>之后) - 每生成一个
<articlex>后,检查当前序号是否在目标数组中,若是则插入广告
修改后的完整代码:
/** * Display posts with ads inserted at specific positions. */ function dispost($atts, $content = null) { global $post; extract(shortcode_atts(array( 'cat' => '', 'num' => '5', 'order' => 'DESC', 'orderby' => 'rand', 's' => '' ), $atts)); $args = array( 'cat' => $cat, 'posts_per_page' => $num, 'order' => $order, 'orderby' => $orderby, 's' => $s, ); $output = ''; $posts = get_posts($args); // 定义需要插入广告的articlex位置(第1、5、7、10个之后) $ad_positions = [1, 5, 7, 10]; $current_count = 0; foreach($posts as $post) { setup_postdata($post); $current_count++; $output .= ' <articlex> <a href="'. get_the_permalink() .'"> '. get_the_post_thumbnail( $post->ID, 'Medium Large', array( 'class' => 'alignleft' ) ) .' </a> <div class="text"> <h2><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></h2> <p> '. get_the_excerpt() .' <br> <a class="post-preview-link" href="'. get_the_permalink() .'">Read More...</a> </p> </div> </articlex>'; // 检查当前articlex序号是否在广告位置数组中,插入广告 if(in_array($current_count, $ad_positions)) { // 替换为你的广告代码,示例如下 $output .= '<div class="article-ad"> <p>这里是你的广告内容</p> </div>'; } } wp_reset_postdata(); return '<main>'. $output .'</main>'; }
说明
$ad_positions数组可根据需求自由调整插入位置- 广告代码部分请替换为实际的广告HTML(注意转义引号,保持和原代码一致的格式)
- 如果设置的
num(文章数量)小于目标位置(比如num=5时,7、10位置不会触发),代码会自动忽略不存在的位置,不会报错
内容的提问来源于stack exchange,提问作者Hamziga Hupic
相关产品推荐
相关产品推荐

