0

I'm trying to add a shortcode within the text of the_content(). It is possible to add it to the beginning or the end however I cannot figure out how I would get it to show after say 200 characters.

Here's the shortcode that I need added:

[related-posts]

I've tried this but this isnt suitable for me because it replaces every paragaraph with a shortcode.

  • Why not use a plugin like Easy Adsense or something similar? Then you can inject scripts, shortcodes, whatever in the middle of your content. There are options to put code before, after, or in the middle after a defined character count. – unifiedac May 30 '14 at 21:33
1

Here's what I've used after finding something on the web (wpbeginner). It finds the fourth p tag closing and adds it after that. Originally it was to add ad banners in the middle of post content dynamically.

add_filter( 'the_content', 'prefix_insert_post_related' );

function prefix_insert_post_related( $content ) {

$related_code .= do_shortcode("[divider]");
$related_code .= do_shortcode("[bws_related_posts]");

if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $related_code, 4, $content );
}

return $content;
}

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {

    if ( trim( $paragraph ) ) {
        $paragraphs[$index] .= $closing_p;
    }

    if ( $paragraph_id == $index + 1 ) {
        $paragraphs[$index] .= $insertion;
    }
}

return implode( '', $paragraphs );
}
| improve this answer | |
0

yes you can,

 $kvcodes_con = the_content();
 $kvcodes_first_param = substr($kvcodes_con, 0, 200);
 $kvcodes_second_param = substr($kvcodes_con, 200);

 echo $kvcodes_final = $kvcodes_first_param.'[your-shortcode]'.$kvcodes_second_param;

I hope this will help you to add your short code within it

| improve this answer | |
  • Some remarks on this answer: 1) Don't use the_content(), since it will echo the content, not return it. 2) How do you handle the case when you insert the shortcode in the middle of a word? I guess we should try to avoid that. 3) How do you handle the case when you're in the middle of a tag, for example an image? We would also like to avoid this possibility. 4) What about multibyte characthers with substr()? One should use mb_substr() instead. 5) Write the full filter code, please. Hopefully you can use this to enhance the answer, I'm sure it will be great afterwards and very useful. – birgire May 30 '14 at 9:17
  • Thanks to those with the positive remarks. I've actually found a way, I'll post it as an answer. – Abu Nooh May 30 '14 at 17:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.