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' );
Related
Idd like to add a class within the output of this piece of php code
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
echo $term->name;
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );
The code is used in my Wordpress functions php to generate a shortcode.
It should be something like this
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
echo '<div class="OutputClass" >';
echo $term->name;
echo '</div>';
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );
Unfortunatly this does not work.
Can you please help?
As the WordPress Code Reference states.
Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.
So first change it from echo to one return.
You could define a variable, concatenate to it and finally return it.
Result:
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
$sR = '<div class="OutputClass" >';
$sR .= $term->name;
$sR .= '</div>';
return $sR;
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );
If the class is always the same and thus could be hardcoded, then you are very close. Only one echo will be outputted, so concatenate it:
echo '<div class="OutputClass" >'.$term->name.'</div>';
If it's dynamic and you need to get the class name somewhere and pass it along, then that's a whole different story.
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' );
?>
I have the following code in my tweaks plugin.
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );
function sqhse_news_featimgmove( $content ) {
$content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "<div class='clearfix' style='margin-bottom:10px;'></div>", $content, 1 );
return $content;
}
What it does:
It adds the featured image after the first paragraph which is great and exactly what I need.
The problem: The code applies itself to single.php (great that's where I need it) but it also applies itself to single-training_courses.php (a template for a custom post type).
The help required: Apply the code to single.php and not any sub single templates such as single-training_courses.php
Is this achievable? and if so how may I achieve this?
You can use get_post_type() WordPress function and wrap your code inside an if statement as follow:
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );
function sqhse_news_featimgmove( $content ) {
if( get_post_type() == 'post' ) {
$content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "<div class='clearfix' style='margin-bottom:10px;'></div>", $content, 1 );
return $content;
}
return $content;
}
The filter you're using, the_content, as you've discovered will apply to all content areas. You need to add a conditional to check the post type you're on and adjust accordingly. My suggestion would be to use is_singular().
add_filter( 'the_content', 'sqhse_news_featimgmove', 20 );
function sqhse_news_featimgmove( $content ) {
if ( is_singular( 'post' ) ) {
$content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID,'post-single', array( 'class' => "img-fluid img-rounded w-100")) . "<div class='clearfix' style='margin-bottom:10px;'></div>", $content, 1 );
}
return $content;
}
When dealing with filters make sure you always return a value. If you have a conditional for example keep the return statement outside of it.
https://codex.wordpress.org/Function_Reference/is_singular
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.
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
}