【问题标题】:WordPress: Check how many elements are in a postWordPress:检查帖子中有多少元素
【发布时间】:2018-01-25 19:11:11
【问题描述】:

有什么方法可以检查 WordPress 帖子中有多少元素,如标题(h2、h3、...)、段落和链接?

目前我正在使用此代码:

<?php
    $content = get_the_content();

    $count_h2s = explode('<h2>', $content);
    $h2 = 0;

    foreach ($count_h2s as $count_h2) {
            $h2++;
    }
    echo $h2;
?>

它似乎适用于头条新闻。但是如果我用它来计算&lt;p&gt;-tags,我只会得到1。即使有更多。我可以想象这是因为这些标签不在编辑器中,但标题在?!

也许还有一种比我的代码更优雅的方式来计算元素;)

【问题讨论】:

  • 也许您可以找到打开的标签并计算匹配项,preg_match_all('/\&lt;\w+\&gt;/', $content, $matches); echo count($matches);
  • 我必须编辑代码吗?它显示结果为 1。但它算什么?

标签: php wordpress


【解决方案1】:

循环不是必须的,使用PHP函数substr_count

$query = get_post(get_the_ID());    
$content = apply_filters('the_content', $query->post_content);
$p_count = substr_count($content, '<p>');
echo $p_count ;

// Be aware, if there is a more-tag inside the post, this `<p>`-tag wouldn't count!

应该很容易用于其他标签,例如...

【讨论】:

  • 谢谢,但没有我得到 &lt;p&gt; 的 0 个结果。可能是因为编辑器中没有设置&lt;p&gt;?但它在帖子的 HTML 中。它适用于头条新闻。
  • 检查你正在扫描的源是否有&lt;p&gt;?
  • 我查了来源,有10多个&lt;p&gt;标签
  • 那就很奇怪了。如果您只是为$content 分配一个包含大量&lt;p&gt; 的字符串,看看您会得到什么。它在我的测试中运行良好。
  • 我在这里找到了解决方案:stackoverflow.com/a/32024022/1788961 我们需要获取所有标签的内容,例如:$content = apply_filters('the_content', $query-&gt;post_content);
【解决方案2】:

您似乎被 wordpress 用于自动将换行符转换为 &lt;p&gt; 标记的过滤器搞砸了。换行符不在您的编辑器中,因为它们是在事后通过过滤器添加的。 https://codex.wordpress.org/Function_Reference/wpautop

因此,当您在页面的 HTML 源代码中看到 &lt;p&gt; 标记时,您希望在 get_the_content() 中搜索换行符,因为这些是被转换为 &lt;p&gt; 标记的内容。

【讨论】:

  • 谢谢,我找到了解决办法。我需要得到这样的内容:$content = apply_filters('the_content', $query-&gt;post_content);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 2018-08-10
  • 2020-02-21
相关资源
最近更新 更多