0

I am building a shortcode. I would love for the array with the category names "$catslugs" to be added via the shortcode. But reading the stuff on wordpress.org confuses me. The code below is partial. This simple shortcode works: [camp_posts] (more below code)

function camp_posts_function() {//Creates shortcode [camp_posts]

$catslugs = array('academic', 'adventure', 'arts', 'religious', 'special-interest', 'special-needs', 'sports','teen');//Must update as new Main categories are added 
$out = array();
foreach($catslugs as $slug) {
    array_push($out, get_category_by_slug($slug)->term_id);
    }
$CatIDs= implode(',', $out);

$camp_posts_bynumber = new WP_Query(array ('cat' => $CatIDs));

if( $camp_posts_bynumber->have_posts() ):

I want that array with "academic, adventure..." to be pulled in from the shortcode. I added "type" to my shortcode which was just [camp_posts] using the above code and now is [camp_posts type="academic, sports"]. I'm just not sure how to grab the info. I know it needs to be something like this:

function camp_posts_function($atts) {//Creates shortcode [camp_posts]
extract(shortcode_atts(array(
      'type' => 1,
   ), $atts));
$out = array();
foreach($atts as $slug) {
    array_push($out, get_category_by_slug($slug)->term_id);
    }
$CatIDs= implode(',', $out);
$camp_posts_bynumber = new WP_Query(array ('cat' => $CatIDs));

if( $camp_posts_bynumber->have_posts() ):

After fiddling some more, I am closer:

function camp_posts_function($atts) {//Creates shortcode [camp_posts]
$atts=shortcode_atts(
        array(
            'type' => 'nothing',
        ), $atts, 'camp_posts');
 return $atts['type'];

That returns "academic, sports". But I am unsure how to get it into $catslugs.

0

1 Answer 1

1

I figured it out. With the shortcode set as [camp_posts type="academic, sports"] the code that does the trick is this:

function camp_posts_function($atts) {//Creates shortcode [camp_posts type="academics, sports"]
$atts=shortcode_atts(
        array(
            'type' => 'nothing',
        ), $atts, 'camp_posts');
$ShortcodeAtts=esc_attr($atts['type']);//Puts "type" attribute into a variable
$ShortcodeAttsArray = explode(',', $ShortcodeAtts);

$IDout = array();//Initializes array
foreach($ShortcodeAttsArray as $slug) {
    array_push($IDout, get_category_by_slug($slug)->term_id);//Gets category ID of each category slug name
    }
$CatIDs= implode(',', $IDout);//Puts all category IDs into variable $CatIDs with a commas between

$camp_posts_bynumber = new WP_Query(array ('cat' => $CatIDs));

if( $camp_posts_bynumber->have_posts() ):

Your Answer

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

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