使用Wordpress Functions.php文件将ACF字段作为一个短码返回。

问题描述 投票:1回答:4

我如何使用高级自定义字段作为一个短码。我在Wordpress functions.php文件中使用了以下代码,但没有成功。

这是我的代码。

function location_date_func( $atts ){

    return "<?php the_field('location_date', 658); ?>";
}
add_shortcode( 'location_date', 'location_date_func' );
php wordpress shortcode advanced-custom-fields
4个回答
1
投票

你需要正确地注册这个短码,让它返回数据来显示,而不是返回一个带有php代码的字符串。

function location_date_func( $atts ){
    //return string, dont echo it, so use get_field, not the_field
    return get_field('location_date', 658);
}
//create function to register shortcode
function register_shortcodes(){
   add_shortcode( 'location_date', 'location_date_func' );
}
// hook register function into wordpress init
add_action( 'init', 'register_shortcodes');

如果你使用的是php 5.3+,你可以使用anonomous函数来达到同样的效果。

add_action('init', function(){
    add_shortcode('location_date', function(){
        return get_field('location_date', 658);
    });
});

1
投票

成功了!

function location_date_func( $atts ){
    return apply_filters( 'the_content', get_post_field( 'location_details', 658 ) );
        }
add_shortcode( 'location_date_sc', 'location_date_func' );

0
投票

如果你想返回一个ACF字段的值,可以使用 the_field(),已经有一个 内置短码 来实现这一点。

[acf field="location_date" post_id="658"]

如果您想使用的是 [location_date] 短码,您需要使用 get_field() 来返回,而不是回音。语法方面,你的代码唯一的问题是你不需要双引号或 <?php 标签,因为它应该已经在一个PHP块中。它在功能上与 [acf] 短码,但不接受 post_id 参数。这个例子将被硬编码为发布ID 658,除非你修改它以接受一个ID作为 $atts 或使用 global $post;

function location_date_func( $atts ){
    return get_field( 'location_date', 658 );
}
add_shortcode( 'location_date', 'location_date_func' );

0
投票

add_shortcode('location_start_your_application_group', 'start_your_application_group');

function start_your_application_group() {
    $start_your_application_group = '';
    $start_your_application_group .= '<section class="start-your-application">';
     if ( have_rows( 'start_your_application_group', 'option' ) ) : 
         while ( have_rows( 'start_your_application_group', 'option' ) ) : the_row(); 
           $heading = get_sub_field( 'heading' );
             $content = get_sub_field( 'content' );

             if ( $heading !== '' ) {
                    $start_your_application_group .= '<h3 class="start-your-application__heading">' . $heading . '</h3>';
             }
             if ( $content !== '' ) {
                $start_your_application_group .= '<div class="start-your-application__content">' . $content . '</div>';
             }

             $image = get_sub_field( 'image' );
             if ( $image ) { 
                $start_your_application_group .= '<div class="start-your-application__image-container"><img class="start-your-application__image" src="' . $image['url'] .'" alt="' . $image['alt'] . '" /></div>';
            } 
        endwhile;
    endif;
    $start_your_application_group .= '</section>';

    return $start_your_application_group;
}
© www.soinside.com 2019 - 2024. All rights reserved.