0

How do I target the immediate paragraph after the first h2 tag in every post? (They have been structured a specific way)

<!-- Example 1 -->

<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p><!-- PHP gets this paragraph -->
<p>Lorem Ipsum</p>


<!-- Example 2 -->

<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p><!-- PHP gets this paragraph -->
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p>

Normally I would use preg_match or preg_split, but Wordpress doesn't store the post_content with p tags I can target, so that didn't seem viable.

EDIT:

I figured out how to do this, the code below works:

<?php
    $texts = preg_split( '/\r\n|\r|\n/', get_the_content() );
    // Loop through items
    foreach($texts as $text) {
      // If $stop has been set true by presence of H2 in previous item, then break after echoing paragraph
      if ($stop == true) {
        echo $text;
        break;
      }
      // If first h2 present, then set $stop to true to stop loop after next item
      if (strpos($text, 'h2')) {
      $stop = true;
      }
    }
  • Obligatory: [don't _ever_ use RegEx to match HTML](https://stackoverflow.com/a/1732454/3578036) – JustCarty Mar 01 '19 at 15:06
  • Are you saying that you are storing the data as Markdown? I am assuming that is the case if you are saying that you cannot detect the `

    ` tags... If you are using Markdown then I guess you could use RegEx producing something horrible like this: https://regex101.com/r/5BCiUk/1 (>_<), however MD has different ways of writing headings (`##` under the line for instance). I strongly recommend reading up on: http://php.net/manual/en/function.simplexml-load-string.php

    – JustCarty Mar 01 '19 at 15:09

1 Answers1

0

Following on from my comment, use simplexml_load_string

$str = '
<div>
    <p>Lorem Ipsum1</p>
    <p>Lorem Ipsum2</p>

    <h2>Title</h2>
    <p>Lorem Ipsum3</p><!-- PHP gets this paragraph -->
    <p>Lorem Ipsum4</p>

    <h2>Title</h2>
    <p>Lorem Ipsum5</p>
</div>';

$xml = simplexml_load_string($str);
$headings = $xml->xpath('h2');

$contents = [];
foreach ($headings as $heading) {
    $contents[] = (string)$heading->xpath('following-sibling::p')[0];
}

Live demo

JustCarty
  • 3,839
  • 5
  • 31
  • 51
  • Hey, I edited my question with the solution I made myself. Principle is the same, except mine is a bit more Wordpress specific and accounts for the lack of p tags in the DB – James Cartwright Mar 01 '19 at 15:22
  • @JamesCartwright Glad you found a solution, though I implore you to edit your question with a sample of the contents found within `get_the_content()` as that would make your solution understandable to future visitors, and also might allow someone to come up with a _better_ solution - for want of a better word. – JustCarty Mar 01 '19 at 15:25