首页 > 解决方案 > 在 Wordpress 中,如何在每篇文章的第一个 h2 标记之后获得直接段落?

问题描述

如何定位每个帖子中第一个 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 不会使用我可以定位的 p 标签存储 post_content,所以这似乎不可行。

编辑:

我想出了如何做到这一点,下面的代码有效:

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

标签: phpwordpress

解决方案


继我的评论之后,使用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];
}

现场演示


推荐阅读