0

I'm trying to use shortcode in index.php but when I use PHP code in my shortcode, it displays out of shortcode structure.

this HTML code works

<?php echo do_shortcode('[myshortcode label="sample title" Description="Content Goes Here"]'); ?>

this code doesn't work and pushes PHP code out of short code structure

<?php echo do_shortcode('[myshortcode label="'. the_title() .'" Description="Content Goes Here"]'); ?>

it outputs like this:

sample title
<div class="hidden-content">
<span class="show-content"></span>
<div class="showme hidden" style="display: none;">Content Goes Here</div>
</div>

But it must be like this

<div class="hidden-content">
<span class="showcontent">sample title</span>
<div class="showme hidden" style="display: none;">Content Goes Here</div>
</div>

1 Answer 1

2

You need to change the_title() to get_the_title().

You are asking the shortcode to echo out a string that is returning the title.

It would be good for you to research the difference between the_title and get_the_title.

The main difference is that the_title is actually returning the title without any other requirement (this is simplified: there are filters happening as well) but it is why you see it first before the rest of the code.

2
  • you mean when working with shortcodes wee need to use get_the_title(). This interesting but works well I did not expect that how simple it was. Commented Oct 8, 2023 at 11:22
  • That's a generalization, but a good rule to follow. Usually in creating shortcodes I add everything to a single variable and then return that variable which is how it is more often done, and in that case yes you need to use get_ functions instead of functions that immediately return data (such as the_), Commented Oct 8, 2023 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.