Shaun Taylor
Shaun Taylor

Reputation: 972

Pass PHP Variable into a shortcode

I'm trying to do something that seems really simple but I can't figure it out.

In my category template, I have this shortcode:

<?php echo do_shortcode( '[jobs categories="manufacturing"]' ); ?>

I also have this to show the title of the category:

<?php single_cat_title(); ?>

I would like to put them both together so I can pass the category into the shortcode so it fetches the correct job category listings. So I created this:

<?php $category = single_cat_title(); ?>
<?php echo do_shortcode('[jobs categories=' . $category . ']'); ?>

but it doesn't seem to work properly - Am I doing something wrong? Is this even possible?

Many thanks!!

Upvotes: 0

Views: 3291

Answers (1)

Xhynk
Xhynk

Reputation: 13840

If you look at the documentation for the single_cat_title() function, you'll see that it can either display or return the value, and it accepts two parameters $prefix and $display with default values of '' and true respectively.

What this means, is that just using single_cat_title(); will print Category Title to the document.

If you want to use it as a variable (without printing it to the document), you'll need to set the second parameter to false:

$category = single_cat_title( '', false );

This will define the $category variable for you, without printing anything, and you can then pass it to your shortcode (also note, that typically you'll want quotes around your attribute values in shortcodes):

echo do_shortcode( '[jobs categories="' . $category . '"]' );

You can make it a bit more succinct as well:

<?php
    $category = single_cat_title( '', false );
    echo do_shortcode( "[jobs categories='$category']" );
?>

Upvotes: 2

Related Questions