有一种方法可以删除特定的短代码,将文本保留在里面吗?
例如:在这种情况下[dropcap] A [/ dropcap]我想删除维护“A”或其他任何字母的短代码。
谢谢!
答案 0 :(得分:1)
使用此JS正则表达式删除文本中方括号之间的任何字符,同时保留可能来自短代码标记的任何文本,例如[dropcap]A[/dropcap]
。
var myReg = /\[.+\]/g;
paragraphText = paragraphText.replace(myReg, '');
或删除像:
这样的短代码[media-credit param=value param2="value2"]text you actually want goes here[/media-credit]
您可以将以下内容用于functions.php文件:
add_filter( 'the_excerpt', 'remove_media_credit_from_excerpt' );
function remove_media_credit_from_excerpt( $excerpt ) {
return preg_replace ('/\[media-credit[^\]]*\](.*)\[\/media-credit\]/', '$1', $excerpt);
}
答案 1 :(得分:1)
这是一个插件,它将启动一次并解析所有帖子'内容,剥离任何所需短代码的短代码(并留下内容)。只需在$ shortcode_tags数组中输入要删除的短代码,并在$ posts数组中输入要执行的帖子类型。
注意:这会影响您的数据库,无法撤消。强烈建议您先备份数据库。
<?php
/*
Plugin Name: Strip Shortcodes Example
*/
add_action( 'init', '_replace_shortcodes' );
function _replace_shortcodes() {
global $shortcode_tags;
// Make sure this only happens ONE time
if ( get_option( '_replace_shortcodes_did_once' ) !== false ) {
return;
}
update_option( '_replace_shortcodes_did_once', true );
add_action( 'admin_notices', '_replace_shortcodes_notice' );
// Get all of our posts
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => 'post', // Change this for other post types (can be "any")
));
// Make WP think this is the only shortcode when getting the regex (put in all shortcodes to perform on here)
$orig_shortcode_tags = $shortcode_tags;
$shortcode_tags = array(
'dropcap' => null,
);
$shortcode_regex = get_shortcode_regex();
$shortcode_tags = $orig_shortcode_tags;
// Loop through the posts
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
// Perform Regex to strip shortcodes for given shortcodes
$post_content = preg_replace_callback( "/$shortcode_regex/s", '_replace_shortcodes_callback', $post->post_content );
// Update our post in the database
wp_update_post( array(
'ID' => $post->ID,
'post_content' => $post_content,
) );
}
}
}
function _replace_shortcodes_callback( $matches ) {
// This is the shortcode content
$content = $matches[5];
// No content, so just return the whole thing unmodified
if ( empty( $content ) ) {
return $matches[0];
}
// Otherwise, just return the content (with no shortcodes)
return $content;
}
function _replace_shortcodes_notice() {
?>
<div class="updated">
<p>
All posts' content updated.
</p>
</div>
<?php
}