我已经拼凑了下面的代码。我把它保存在一个独立的PHP文件中,这样我就可以按需运行它了。
应该很清楚这意味着什么:循环所有类型为“product”和“product variance”的帖子,然后使用preg\\u replace删除所有div和span标签。
但出于某种原因,以下函数似乎无法删除标记:
<?php
require "wp-config.php";
// Post Types to include
$args = array(
\'posts_per_page\' => \'50\',
\'post_type\' => array(
\'product\',
\'product-variation\'
)
);
// The Query
$query = new WP_Query( $args );
$posts = $query->posts;
foreach($posts as $post) {
$tags = array( \'div\', \'span\');
$content = $post->post_content;
foreach ($tags as $tag) {
$cleanedcontent = preg_replace(\'#<\\s*\' . $tag . \'[^>]*>.*?<\\s*/\\s*\'. $tag . \'>#msi\', \'\', $content);
}
echo $cleanedcontent . \'<hr/>\';
// $cleaned_post = array(
// \'ID\' => $post->ID,
// \'post_content\' => $cleanedcontent
// );
// wp_update_post( $cleaned_post );
}
echo \'Done.\'
?>
最后,我将使用wp\\u update\\u post保存“清理”的内容-该部分当前已被注释掉。
我的代码部分基于以下内容:strip only specific tags (like <p>), but keep other tags (like <br/>)
你知道为什么我的函数没有去掉div标签吗?
SO网友:Jason Is My Name
我不知道你在这里到底在做什么,但我认为你是想从帖子内容中创建一段代码,然后去掉不必要的标签。
我会使用条形标签:https://www.w3schools.com/php/func_string_strip_tags.asp
<?php
require "wp-config.php";
// Post Types to include
$args = array(
\'posts_per_page\' => \'50\',
\'post_type\' => array(
\'product\',
\'product-variation\'
)
);
// The Query
$query = new WP_Query( $args );
$posts = $query->posts;
foreach($posts as $post) {
$content = $post->post_content;
$content = echo strip_tags($content, "<div><p><h1>"); // where you pass the code block, then state the tags that you wish to keep. I also cannot recall if it will need to be echo\'d or not.
}
echo \'Done.\'; ?>
在传递代码块的地方,说明要保留的标记。我也记不起是否需要回显。
如果我误解了,请道歉。
谢谢,杰森。
SO网友:Qaisar Feroz
代替
$content = $post->post_content;
foreach ($tags as $tag) {
$cleanedcontent = preg_replace(\'#<\\s*\' . $tag . \'[^>]*>.*?<\\s*/\\s*\'. $tag . \'>#msi\', \'\', $content);
}
使用
$content = $cleanedcontent = $post->post_content;
foreach ($tags as $tag) {
$cleanedcontent = preg_replace(\'#<\\s*\' . $tag . \'[^>]*>.*?<\\s*/\\s*\'. $tag . \'>#msi\', \'\', $cleanedcontent);
}