WordPress.org

Make WordPress Core

Opened 4 years ago

Last modified 16 months ago

#35216 new defect (bug)

Return empty string from wp.shortcode.replace() callback is ignored

Reported by: prionkor Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 3.5
Component: Shortcodes Keywords: has-patch
Focuses: javascript Cc:
PR Number:

Description

I was trying to just remove a shortcode by returning empty string from wp.shortcode.replace() callback.

For example

var text = "This is some content with shortcode. [foo]some content[/foo]

text = wp.shortcode.replace('foo', text, function(tag){
    
    // attributes and content values are broken.

    return '';

});

The callback function simply get ignored. No replacement happened for the shortcode. If I return anything other then empty string for example ' ' (string with space) it does replace the shortcode.

I am not sure if this behavior was intended or not.

Attachments (1)

35216.diff (3.1 KB) - added by talldanwp 16 months ago.

Download all attachments as: .zip

Change History (7)

#1 @danielbachhuber
4 years ago

  • Version changed from 4.4 to 3.5

I am not sure if this behavior was intended or not.

It's going to be hard to determine the intended behavior :( This code landed in r22004, a pretty hefty changeset.

#2 @prionkor
4 years ago

For me the replace function should be replace the shortcode no matter what is returned from the callback function. Returning empty string should work like removing the shortcode.

#3 @swissspidy
4 years ago

  • Focuses administration removed
  • Keywords needs-patch added

I'd say the type of result should be properly checked instead of doing something like return result ? left + result + right : match;. An empty string is a legit use case and AFAIK also possible using the PHP equivalent.

This ticket was mentioned in Slack in #core by chriscct7. View the logs.


4 years ago

This ticket was mentioned in Slack in #core by chriscct7. View the logs.


4 years ago

@talldanwp
16 months ago

#6 @talldanwp
16 months ago

  • Keywords has-patch added; needs-patch removed

I've attached 35216.diff.

This change makes wp.shortcode.replace() behave more like its php counterpart do_shortcode

If the result of the callback is a string, number or truthy value, we replace the shortcode with that value (so therefore if an empty string is returned from the callback we'll see the desired behaviour).

For other falsey values that are not strings or numbers returned from the callback, the shortcode and shortcode content will be removed

Tests have been added for the various values that might be returned from the callback (empty string, null, undefined, 0, empty string)

Note: See TracTickets for help on using tickets.