简体   繁体   中英

How pass WordPress shortcode with Parameters to template

I have template with child theme and I edit child template function.php

Goal is create short code witch will have parameters and part of template file

my function look like this:

function my_shortcode($atts = array() ) {
    extract(shortcode_atts(array(
        'catid' => '5'
    ), $atts));
    ob_start();
   include(get_template_part('mynews-temp'));
    return ob_get_clean();
}
add_shortcode('mynews', 'my_shortcode');

[mynews catid="5"] short code output must be news query with cat id 5

this is template part with query

<?phpif ( ! defined( 'ABSPATH' ) ) {exit( 'Direct script access denied.' );}
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'mynews',
'tax_query' => array(
array(
'taxonomy' => 'newstypes',
'field' => 'tag_ID',
'terms' => array('$catid')
),),));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><
<?php endforeach; ?>
<?php endif;    wp_reset_postdata(); ?>

It not works can not find what is mistake

PS witch is correct when i use child template:

 include(get_template_part('mynews-temp'));
 or  include(locate_template('mynews-temp'));

You can include the template parts like this: get_template_part('mynews-temp') . No need to include , that does nothing.

The rest of your code works perfectly. The only thing I could recommend is to simplify your code and just get all the regular post s to see if the problem is in the tax_query :

<?php
if ( ! defined( 'ABSPATH' ) ) {exit( 'Direct script access denied.' );}
$posts = get_posts(array(
    'posts_per_page' => -1,
    'post_type' => 'post',
    
));
//     'tax_query' => array(
//         array(
//             'taxonomy' => 'newstypes',
//             'field' => 'tag_ID',
//             'terms' => array('$catid')
//         ),),));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><
<?php endforeach; ?>
<?php endif;    wp_reset_postdata(); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM