我试图做到的是在内容中传播相关帖子,比如每3段后再发布一次。
在我看来,需要做三件事:
1-循环。我现在用的是这样的东西:
<?php
$related = new WP_Query( array( \'post__in\' => $whatever) );
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
get_template_part(\'relatedpost\');
}
}
wp_reset_query();
2-拆分帖子-我正在使用此代码,这对于静态内容(如广告)非常有用。
function insert_related_post( $text )
{
if ( is_single() ) :
$insert = \'[ad]\';
$split_by = "</p>";
$insert_after = 3; //number of paragraphs
// make array of paragraphs
$paragraphs = explode( $split_by, $text);
$new_text = \'\'; // new text
$i = 1; // current ad index
// loop through array and build string for output
foreach( $paragraphs as $paragraph ) {
// add paragraph, preceeded by an ad after every $insert_after
$new_text .= ( $i % $insert_after == 0 ? $insert : \'\' ) . $paragraph;
// increase index
$i++;
}
return $new_text;
endif;
echo $text;
}
add_filter(\'the_content\', \'insert_related_post\');
3-在每三段后插入循环中的每个元素。我不知道该怎么做。
我想迭代应该是这样的。。。
<?php
$related = new WP_Query( array(
\'post__in\' => $whatever,
\'posts_per_page\' => \'1\',
\'offset\' => $i++/3,
) );
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
get_template_part(\'relatedpost\');
}
}
wp_reset_query();
。。。但我无法完成这项工作——那么我该把它放在哪里/怎么放?
最合适的回答,由SO网友:Max Yudin 整理而成
您可以缓冲模板部分,以便在帖子内容中使用它:
<?php
add_filter( \'the_content\', \'add_related_each_nth_p\' );
function add_related_each_nth_p( $content )
{
if ( ! is_single() ) {
return $content;
}
// the interval between added content
$paragraph_steps = 3;
// declare empty output
$output = \'\';
// declare related posts offset
$z = 0;
// make the array of paragraphs
$content = explode( \'</p>\', $content );
// iterate through the content paragraphs
for ( $i = 0; $i < count( $content ); $i++ ) {
// concatenate paragraphs one by one
$output .= $content[ $i ] . \'</p>\';
// check if interval is reached and if so, concatenate related
if ( 0 == $i % $paragraph_steps ) {
// run your query
$related = new WP_Query( array(
\'post__in\' => $whatever,
\'posts_per_page\' => \'1\',
\'offset\' => $z,
) );
// related post offset increments by one every interval
$z++;
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
// start buffering
ob_start();
get_template_part(\'relatedpost\');
// concatenate related post to the output
$output .= ob_get_contents();
// Clean the output buffer
ob_end_clean();
}
}
wp_reset_query();
}
}
return $output;
}
或者你可以移动
relatedpost
将零件标记模板化到函数中(请参见上面代码中的相应位置),例如:
<?php
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
$output .= \'<p>Related: \' . get_the_title() . \'</p>\';
}
}
不过,代码没有经过测试。