Delete specific shortcode maintaining content - php

There is a way to delete a specific shortcode, maintaining the text inside?
For example: in this case [dropcap]A[/dropcap] I would like to eliminate the shortcode maintaining the "A", or any other letter inside.
Thanks!

Use this JS regex to strip out any characters between square brackets from the text, while leaving any text that might've come beween shortcode tags, like [dropcap]A[/dropcap].
var myReg = /\[.+\]/g;
paragraphText = paragraphText.replace(myReg, '');
or to remove a shortcode like:
[media-credit param=value param2="value2"]text you actually want goes here[/media-credit]
You can use the following to your functions.php file:
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);
}

Here's a plugin that will launch one time and parse ALL POSTS' content, stripping the shortcodes (and leaving the content) of any desired shortcodes. Simply enter the shortcodes you want to strip in the $shortcode_tags array and the post type you want to perform on in the $posts array.
NOTE: This will impact your database and can NOT be undone. It is highly recommended that you backup your database first.
<?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
}

Related

Wordpress shortcode php array to text in a text block

I am beginning to make a site in wordpress (so no php or html experience). I want to generate textlist from a mysql column into a text block.
I have made the php code for the shortcode below which returns an array which now displays in the textblock as "Array" instead of a list of strings.
If i just print the values they appear on the head of the page.
What are the next steps I need to do/look for. I can't find it because I probably do not know the correct search terms. My guess is something with HTML.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
foreach ( $marker_labels as $marker_label )
{
//print labels
echo $marker_label;
}
return $marker_labels;
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>
I have now this code which gives me a list exactly what i want but not in the "paragraph block" in wordpress where my shortcode is situated.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
foreach ( $marker_labels as $marker_label )
{
echo '<li>'. $marker_label.'</li>';
}
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>
I'm not 100% sure what you're trying to accomplish, but try this. You don't want to echo out all the values as you're looping through them. Concatenate everything in a variable and then return the entire string at the end of your shortcode. This should generate an unordered list.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
$output = '<ul>';
foreach ( $marker_labels as $marker_label )
{
$output .= '<li>' . $marker_label . '</li>';
}
$output .= '</ul>';
return $ouput;
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>

How to exclude specific post from wp functions.php code?

I used this code to show responsive ad from adsense after 5th paragraph.
Adding Ads After First And Second Paragraph of WordPress Post
This is the code I use on my site:
function prefix_insert_after_paragraph2( $ads, $content ) {
if ( ! is_array( $ads ) ) {
return $content;
}
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
$n = $index + 1;
if ( isset( $ads[ $n ] ) ) {
$paragraphs[$index] .= $ads[ $n ];
}
}
return implode( '', $paragraphs );
}
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
if ( is_single() && ! is_admin() ) {
$content = prefix_insert_after_paragraph2( array(
// The format is: '{PARAGRAPH_NUMBER}' => 'AD_CODE',
'5' => '<div>Ad code after FIRST paragraph goes here</div>',
), $content );
}
return $content;
}
I would like to exclude this code only for specific posts. How can I add the proper code to be able to exclude this function for post id=280?
Thank you.
Why do you want to exclude this function inside functions.php?
I think it's much easier to do it inside the post loop.
For example, to exclude the POST ID 280, if you're inside the page.php, or similar you can do this:
global $post;
if ($post->ID == 280){ remove_filter( 'the_content', 'prefix_insert_post_ads' ); }
This way you have the 'add_filter' on your functions.php file, and if you find the exception inside the post (ID=280), you remove the filter.
Just U have to check the current post_id. E.g. :
function prefix_insert_post_ads( $content ) {
global $post;
$post_id = $post->ID;
$post_ids_excluded = [280,....]; // excluded posts ids
if ( in_array($post_id,$post_ids_excluded) ){
return $content;
}
/*
... the same code .....
*/
}

Shortcode output always showing at top of custom template

my shortcode output always appear on the top of my custom template.
custom template
$tag= 'the_content';
remove_all_filters( $tag);
$postid = get_the_ID();
$post = get_post($postid);
$content = do_shortcode($post->post_content);
ob_start();
echo $content;
$result = ob_get_contents();
ob_end_clean();
return $result;
custom shortcode
function signupform_shortcode( $atts ) {
extract( shortcode_atts( array(
'socialmkt' => 'aweber'
), $atts ) );
if($socialmkt == 'aweber'){
if($display == 'popup') {
return include_once('modal-aweber.php');
}
}
}
add_shortcode('signupform', 'signupform_shortcode');
The shortcode it's place in the middle of a html landing.
I try adding ob_start() that i read in other posts but still not working.
Your shortcode callback is going to output content rather than return it which is why you're seeing it appear at the top of your page.
Using output buffering (ob_start() / ob_get_contents()) is a valid way of addressing the problem however you need to move the code.
Output buffering should be taking place inside your shortcode callback where the return value is required instead of output.
function signupform_shortcode( $atts ) {
extract( shortcode_atts( array(
'socialmkt' => 'aweber'
), $atts ) );
// Begin output buffering here. Any output below will be stored in a buffer.
ob_start();
if ( $socialmkt == 'aweber' ) {
if ( $display == 'popup' ) {
// Return, as previously used, doesn't help in this context.
include_once( 'modal-aweber.php' );
}
}
// Return (and delete unlike ob_get_contents()) the content of the buffer.
return ob_get_clean();
}
add_shortcode( 'signupform', 'signupform_shortcode' );

How to strip all visual composer shortcode/tags from wordpress's post_content fetched with custom query

I am working on a web-service(API) where i am fetching result WP_query() function and parse that in JSON format. which will further use in android application.
The problem is the post_content i am getting with query is composed by visual composer and the whole content is in form of such tags like
[VC_ROW][/VC_ROW][VC_COLUMN]some text[/VC_COLUMN] etc.
I want to remove/strip all these shortcode from the content and retrieve only plain text from it. Is there any visual composer function through which i can achieve this thing
<?php
require('../../../wp-load.php');
require_once(ABSPATH . 'wp-includes/functions.php');
require_once(ABSPATH . 'wp-includes/shortcodes.php');
header('Content-Type: application/json');
$post_name = $_REQUEST['page'];
if($post_name!=''){
if($post_name=='services') {
$args = array(
'post_parent' => $page['services']['id'],
'post_type' => 'page',
'post_status' => 'published'
);
$posts = get_children($args);
foreach($posts as $po){
$services_array[] = array('id'=>$po->ID,'title'=>$po->post_title,'image'=>get_post_meta($po->ID, 'webservice_page_image',true),'description'=>preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $po->post_content));
}
$post = array(
'status'=>'ok',
'services'=>$services_array
);
echo json_encode($post);
}
}
?>
I want to remove/strip all these shortcode from the content and retrieve only plain text from it.
Solution that worked for me:
$content = strip_tags( do_shortcode( $post->post_content ) );
do_shortcode triggers all visual composer shortcodes and thus returns html+text;
strip_tags removes all html tags and returns plain text.
Here, you can try and easily add some short codes in array that you needs and also you can remove all shortcodes via below code.
$the_content = '[VC_ROW][VC_COLUMN]some text1[/VC_COLUMN] etc.[/VC_ROW][VC_COLUMN_INNTER width="1/3"][/VC_COLUMN_INNTER]';
$shortcode_tags = array('VC_COLUMN_INNTER');
$values = array_values( $shortcode_tags );
$exclude_codes = implode( '|', $values );
// strip all shortcodes but keep content
// $the_content = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $the_content);
// strip all shortcodes except $exclude_codes and keep all content
$the_content = preg_replace( "~(?:\[/?)(?!(?:$exclude_codes))[^/\]]+/?\]~s", '', $the_content );
echo $the_content;
you want to remain some shortcodes you can't use strip_shortcodes() for that.
Best solution, solved.
Just add the following code to file wp-includes/rest-api.php, at the bottom:
/**
* Modify REST API content for pages to force
* shortcodes to render since Visual Composer does not
* do this
*/
add_action( 'rest_api_init', function ()
{
register_rest_field(
'page',
'content',
array(
'get_callback' => 'compasshb_do_shortcodes',
'update_callback' => null,
'schema' => null,
)
);
});
function compasshb_do_shortcodes( $object, $field_name, $request )
{
WPBMap::addAllMappedShortcodes(); // This does all the work
global $post;
$post = get_post ($object['id']);
$output['rendered'] = apply_filters( 'the_content', $post->post_content );
return $output;
}
I took it somewhere and update it a bit, to work a bit better :).
in functions.php add this function:
/** Function that cuts post excerpt to the number of a word based on previously set global * variable $word_count, which is defined below */
if(!function_exists('kc_excerpt')) {
function kc_excerpt($excerpt_length = 20) {
global $word_count, $post;
$word_count = $excerpt_length;
$post_excerpt = get_the_excerpt($post) != "" ? get_the_excerpt($post) : strip_tags(do_shortcode(get_the_content($post)));
$clean_excerpt = strpos($post_excerpt, '...') ? strstr($post_excerpt, '...', true) : $post_excerpt;
/** add by PR */
$clean_excerpt = strip_shortcodes(remove_vc_from_excerpt($clean_excerpt));
/** end PR mod */
$excerpt_word_array = explode (' ',$clean_excerpt);
$excerpt_word_array = array_slice ($excerpt_word_array, 0, $word_count);
$excerpt = implode (' ', $excerpt_word_array).'...'; echo ''.$excerpt.'';
}
}
and after that you call it normally kc_excerpt(20); and it will return normal post_content/excerpt
How to remove visual composer from wp post: i.e [vc_row][vc_column width=\"2/3\"][distance][vc_single_image image=\"40530\" img_size=\"large\"][distance][distance][distance][vc_column_text]
Also WP post remvoe short codes and html tags.
while($posts->have_posts()) {
$postContent = get_the_content();
//Remove html tags. and short code
$postContent = strip_tags( do_shortcode( $postContent ) );
//Remove visual composer tags [vc_column] etc
$postContent = preg_replace( "/\[(\/*)?vc_(.*?)\]/", '', $postContent );
}
Looking source code from wordpress api, I did a function to remove some shortcode from content. So this is the result:
function removeShortcode($content, $shortcodeList){
preg_match_all('#\[([^<>&/\[\]\x00-\x20=]++)#', $content, $matches);
$tagnames = array_intersect($shortcodeList, $matches[1]);
if(empty($tagnames)){
return $content;
}
$pattern = get_shortcode_regex($tagnames);
preg_match_all("/$pattern/", $content, $matchesTags);
foreach ($matchesTags[0] as $key => $value) {
$content = str_replace($value, $matchesTags[5][$key], $content);
}
return $content;
}
example:
$content = "<p>Hi, this is a [example]<b>example</b>[/example]. [end]</p>";
$shortcodesToRemove = ["example", "end"];
echo removeShortcode($content, $shortcodesToRemove);
foreach($posts as $po){
$services_array[] = array('id'=>$po->ID,'title'=>$po->post_title, 'description'=>do_shortcode($po->post_content));
}
You should try this.

Best way to use functions.php to filter ACF in Wordpress

I'm currently pulling in multiple pieces of content into my posts through an AFC with the value: "section_content". Furthermore, I'm using the code below to clean up my WP posts. How would I modify this filter to also include my ACF?
<?php
/**
* Clean posts from inline styling and unnecessary tags
*/
add_filter( 'the_content', 'clean_post_content' );
function clean_post_content($content) {
if ( is_single() ) {
$patterns = array(
'/(<[^>]+) style=".*?"/i', // Remove inline styling
'/<\/?font[^>]*>/', // Remove font tag
'/<(p|span)>(?>\s+| |(?R))*<\/\1>/', // Empty p, span (font tags already removed)
'/(<h[1-6]>[^<]*)<\/?strong>(.*?<\/h[1-6]>)/', // h1-6
);
$replacements = array(
'$1',
'',
'',
'$1$2'
);
$old_content = '';
while ($old_content != $content) {
$old_content = $content;
$content = preg_replace($patterns, $replacements, $content);
}
}
return $content;
}
?>
I guess you could use ACF Filters. I usually hook to acf/format_value in order to clean or modify my custom field values before printing them.
You can even hook to certain field types only, like:
function acf_brand_trademark( $value, $post_id, $field ) {
$value = preg_replace( '/Brand /', 'Brand<sup>™</sup> ', $value );
return $value;
}
add_filter('acf/format_value/type=textarea', 'acf_brand_trademark', 10, 3);
add_filter('acf/format_value/type=text', 'acf_brand_trademark', 10, 3);
Hope this helps!

Categories