1
  • Let's assume there is a simple post.
  • It has some content and a few [gallery] shortcodes in it.
  • I need to add (or modify) attribute to specific shortcode and save in database (not temporarily modify or filter) the new post content.
  • So when viewing content in editor, it'll look something like this:
    • [gallery testattribute="1"]

Here is where I am now:

$post_id = 16; // Some post ID
$post_to_edit = get_post($post_id);
$content = $post_to_edit->post_content;

// find all shortcodes in the post_contnet
if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post_to_edit->post_content, $matches, PREG_SET_ORDER ) ) {
    foreach ( $matches as $shortcode ) {
        // filter only gallery shortcode
        if ( 'gallery' === $shortcode[2] ) {

            $gallery_shortcode_attributes = shortcode_parse_atts( $shortcode[3] );

            // Found the shortcode
            // need to add attribute to it
            // and modify $content variable
            // how?
        }
    }
}

// save the updated content to the database
wp_update_post( array(
    'ID'           => $post_id,
    'post_content' => $content
) );

I can't figure out the method to add/modify the attribute in $content. Should I do a simple string replacement?

  • Why exactly do you not want to use the default shortcode methods? – Jeroen Jan 25 '16 at 12:55
  • @Jeroen I need to allow admin to edit the shortcode from the frontend, and I can only modify post content. – Marvin3 Jan 25 '16 at 13:01
  • You might try parsing the shortcode as a string, add your attributes, then pass it through apply_filters( 'the_content', $yourcontenthere ); before displaying it on the page? I have no idea if that will work. – Craig Jan 25 '16 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.