WordPress - 在第一个图像之后显示代码



我正在尝试完成 Wordpress 函数,以便在 Wordpress 帖子中的第一个图像后显示代码块

我找到了将代码放在 X 段之后的唯一解决方案,但我需要在 X 图像之后放置代码

        <?php
    $show_after_p = 2;
    $content = apply_filters('the_content', $post->post_content);
    if(substr_count($content, '<p>') > $show_after_p)
    {
        $contents = explode("</p>", $content);
        $p_count = 1;
        foreach($contents as $content)
        {
            echo $content;
        if($p_count == $show_after_p)
        {
        ?>
                YOUR AD CODE GOES HERE
        <?php
        }
        echo "</p>";
        $p_count++;
    }
}
?>

测试的解决方案。您可以放入函数.php也可以放入插件文件中。

function sr_display_code_after_image( $content )
{
    $show_after_img = 1; // Position of image after which you want to show.
    if( substr_count($content, '<img') >= $show_after_img)
    {
        $contents = explode("<img", $content);
        $img_count = 0;
        foreach($contents as $content)
        {
            $before_tag = strstr($content, '/>', true); 
            $after_tag = strstr($content, '/>');
            echo "<img";
            echo $before_tag;
            echo "/>";
            if($img_count == $show_after_img)
            {           
                echo 'YOUR AD CODE GOES HERE';
            }
            echo substr($after_tag, 2);
            $img_count++;
        }
    } else 
    {
        echo $content;
    }
}
add_filter( 'the_content', 'sr_display_code_after_image' );

最新更新