1

I have the following code within a WP loop

<?php
                // Get the selected taxonomies for the post type
                $terms = get_the_terms( get_the_ID(), 'course_type' );
                $classes = array();
                if ( $terms && ! is_wp_error( $terms ) ){
                    foreach ( $terms as $term) {
                        $classes[] = $term->slug;
                    }
                }
                ?>

What I am looking to do is print only the WP_Term object slug to use in the classes.

<div class="courses-search-result standout-box-shadow <?php print_r( $classes ); ?>">

Now, I have got it working to a point and printing a value in the classes - but it is also printing the array structure:

class="courses-search-result standout-box-shadow cilex-clearfix Array
(
    [0] => apprenticeship
)
"

Am I close to getting the correct code with my PHP? My knowledge of the language is basic right now so any help would be much appreciated.

1

2 Answers 2

7

print_r is a function intended for debugging, not formatted output.

The simplest way to achieve what you want is using implode, which combines the values of an array into a string; and then echo to display the string.

<div class="courses-search-result standout-box-shadow <?php echo implode(' ', $classes); ?>">
Sign up to request clarification or add additional context in comments.

Comments

2

I would recommend using implode() combined with a PHP short echo tag (i.e. <?= - available in PHP 5.4+ or earlier with the short_open_tag configuration setting enabled):

<div class="courses-search-result standout-box-shadow <?= implode(' ', $classes ); ?>">

Comments

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.