根据您的静态内容和广告内容,我可能会创建一个自定义帖子类型,添加一个广告帖子和一个静态内容帖子,然后使用@birgire post injector class 在你需要的地方注意这两个帖子的注入。您可能需要稍微更改喷油器类以满足您的确切需要。
我很快编写了一个更通用的类(,它非常基础,您应该扩展它),您可以使用它在需要的地方注入任何类型的字符串内容。您可以(必须)根据需要对其进行改进/修改。请注意,没有进行数据清理或验证,因此您希望根据您的确切需要来处理这些问题
class MultiInjector
{
/**
* @var array $specialContent;
* @access protected
* @since 1.0.0
*/
protected $specialContent;
/**
* @var array $specialContent;
* @access protected
* @since 1.0.0
*/
protected $arrayValues;
/**
* @var array $pairs;
* @access protected
* @since 1.0.0
*/
protected $pairs;
/**
* Constructor
*
* @param array $specialContent; = []
* @since 1.0.0
*/
public function __construct( $specialContent = [] )
{
$this->specialContent = $specialContent;
}
public function init()
{
add_action( \'the_post\', [$this, \'thePost\'] );
}
/**
* Protected method specialContentValidated()
*
* Make sure we have post positions, if not, set defauls. Also, reset
* all array keys to numeric values
*
* @since 1.0.0
*/
protected function specialContentValidated()
{
$arrayValues = false;
if ( $this->specialContent
&& is_array( $this->specialContent )
) {
$arrayValues = array_values( $this->specialContent );
// Loop over the array of special content and set defaults if no custom values exist
foreach ( $arrayValues as $key=>$value ) {
$defaults = [
\'content\' => \'This is default content, make sure to set your own\',
\'postPosition\' => $key
];
$arrayValues[$key] = wp_parse_args( $value, $defaults );
}
}
$this->arrayValues = $arrayValues;
}
/**
* Protected method positions()
*
* Save an array of $key/postPosition pairs
*
* @since 1.0.0
*/
protected function positions()
{
$this->specialContentValidated();
$pairs = false;
if ( $this->arrayValues ) {
foreach ( $this->arrayValues as $key=>$value )
$pairs[$key] = $value[\'postPosition\'];
}
$this->pairs = $pairs;
}
public function thePost()
{
// Make sure this is the main query, if not, bail
if ( !in_the_loop() )
return;
$this->positions();
// Make sure we have special content to add, if not bail
if ( false === $this->arrayValues )
return;
// Set a static post counter to count the amount of posts
static $postCount = 0;
// Search for the post position in the $this->pairs array
$position = array_search( $postCount, $this->pairs );
if ( false !== $position ) {
// Everything checks out, display our custom content
echo $this->arrayValues[$position][\'content\'];
}
// Update the counter
$postCount++;
}
}
然后可以按如下方式使用它
add_action ( \'wp\', function ()
{
$args = [
0 => [
\'content\' => \'This is my content\',
\'postPosition\' => 4
],
1 => [
\'content\' => \'This is my other content\',
\'postPosition\' => 6
]
];
$q = new MultiInjector( $args );
$q->init();
});