在Wordpress中,我如何在每个帖子的第一个h2标签之后获取立即段落?

时间:2019-03-01 14:54:23

标签: php wordpress

在每个帖子的第一个h2标签之后,我如何定位紧邻的段落? (它们以特定的方式构造)

<!-- 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>

通常我会使用preg_match或preg_split,但Wordpress不会将post_content与我可以定位的p标签一起存储,因此似乎不可行。

编辑:

我想出了办法,下面的代码起作用了:

<?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;
      }
    }

1 个答案:

答案 0 :(得分:0)

在我的评论之后,使用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