简体   繁体   中英

How can I add a shortcode to query Custom Post Type with ACF in Wordpress?

I am building a website for a client, and I needed to build a game release calendar using Custom Post Type and Advanced Custom Fields. Everything is built out, but the last step.

I need to be able to query the CPT automatically whenever a new game is added, and pull it into the WP Bakery Visual Composer front end via shortcode. Below is the code added to the functions.php file, but I'm getting syntax errors because of "<". Can anyone help me with the proper syntax/formatting for getting it to save and call in properly via the shortcode?

FUNCTIONS.PHP code

// Custom Game Releases Shortcode
add_shortcode( 'my_vc_php_output', 'game_release_listings');
function game_release_listings( $atts ) {
    <?php 

$posts = get_posts(array(
    'posts_per_page'    => -1,
    'post_type'         => 'game_release'
));

if( $posts ): ?>    
    <ul>
        
    <?php foreach( $posts as $post ): 
        
        setup_postdata( $post );
        
        ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_field('release_date'); ?></a>
        </li>
    
    <?php endforeach; ?>
    
    </ul>
    
    <?php wp_reset_postdata(); ?>

<?php endif; ?>
}

There's a rogue <?php tag in your code. Start with removing that. Also you can remove unnecessary ones at the bottom. Try this:

// Custom Game Releases Shortcode
add_shortcode( 'my_vc_php_output', 'game_release_listings');
function game_release_listings( $atts ) {

$posts = get_posts(array(
    'posts_per_page'    => -1,
    'post_type'         => 'game_release'
));

if( $posts ): ?>    
    <ul>
        
    <?php foreach( $posts as $post ): 
        
        setup_postdata( $post ); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_field('release_date'); ?></a>
        </li>
    
    <?php endforeach; ?>
    
    </ul>
    
    <?php wp_reset_postdata();

endif; 
}

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