Auto-place a featured image after x amount of paragraphs in WordPress?

I’m currently using Types with WordPress. The requirement is for me to be able to place an image – uploaded in Types- after every 2 paragraphs.

Now, I know how to pull in the field from Types. What I’m not sure about, (perhaps this is done with Javascript?) is how to then auto-place one image after 2 paragraphs, then another image after 4, etc.

Read More

Is this possible? My very limited jQuery knowledge informs me it might have something to do with an nth-child selector or something? But this is just a guess.

Any help would be greatly appreciated.

Related posts

Leave a Reply

2 comments

  1. Here’s an example of how to do it: http://jsfiddle.net/tkK6y/

    Let’s say you have an array of image URLS:

    var imgs = ['1.jpg', '2.jpg', '3.jpg'];
    

    And a div with n paragraphs:

    <div id="theDiv">
        <p>Foo</p>
        <p>Bar</p>
        ...
    </div>
    

    You can loop through every second paragraph and insert images after each one like this:

    var $div = $('#theDiv');
    var $paragraphs = $('p:nth-child(2n)', $div);
    var n = 0;
    $paragraphs.each(function () {
        var $newImage = $('<img src="' + imgs[n] + '" />'); // Creates an img tag
        $newImage.insertAfter(this);  // Inserts the img after the current paragraph
        n++;
    });
    
  2. There is a way to do this without jquery, only using php and the would be to do a custom loop where you would define a incrementing variable and you would display a result every other post using a basic math function like so:

    $x = 1; while (have_posts()) : the_post();
    if (($x % 2) == 1 && $x != 1)   {
    // Display your custom image here
    }
    
    $x++; endwhile;