Find us on Facebook

LightBlog
Responsive Ads Here

Thứ Sáu, 29 tháng 12, 2017

Wordpress function with attribute pass to template

Question:

really new to this stuff.
I basicly want to create a shortcode with an attribute that calls the function "playlist_code" which inserts a template with that attribute.
This is my code so far, I cant get the template file to use the attribute that i declared in the function. If I use return to check the $tp_atts['id'] value I get the correct output, but I cant call it from the template it seems.
Function:
function playlist_code( $atts ){
$tp_atts = shortcode_atts(array('id' => '1'), $atts, 'playlist_code');
locate_template('template-parts/single_playlist.php', true);
}

add_shortcode('playlist_code', 'playlist_code'); 
Template:
<div class="playlist_container">
            <?php
                $tracks = get_post_meta($tp_atts['id'], 'tracks', true);
                $list = explode(',', trim($tracks));
                if ( $list ){
                    ?>
                    <div class="list-group list-group-lg">
                        <?php
                            $args = array(
                                'posts_per_page'   => -1,
                                'orderby'          => 'post__in',
                                'order'            => 'DESC',
                                'post_type'        => 'download',
                                'post__in'         => $list
                            );
                            $postsi = get_posts($args);
                            foreach ( $postsi as $post ) : setup_postdata( $post );
                                ?>
                                <div class="list-group-item">
                                <?php get_template_part( 'template-parts/content', 'download-list' ); ?>
                                </div>
                            <?php endforeach;
                            wp_reset_postdata();
                        ?>
                    </div>
                <?php } ?>
        </div>

Answer:

You can use set_query_var('playlist_id', $tp_atts['id']);.
When you later call locate_template with $load = true, it will call load_template, which extracts the query variables making them global, and accessible to the template file (in this case, as $playlist_id).

Không có nhận xét nào:

Đăng nhận xét