Wordpress - 在第一张图像后显示代码

时间:2017-03-22 12:26:51

标签: wordpress image

我正在尝试在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++;
    }
}
?>

1 个答案:

答案 0 :(得分:0)

经过测试的解决方案。您可以输入functions.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' );