【问题标题】:Calling ACF from different CPT via slug通过 slug 从不同的 CPT 调用 ACF
【发布时间】:2017-04-20 23:56:44
【问题描述】:

我想将 CTP 中创建的自定义字段回显到小部件。

我通常会使用类似下面的方法从页面 ID 调用字段,但由于我的 CTP 使用 slug 而不是 ID,我正在寻找有关如何执行此操作的建议。

<?php
$other_page = 173;
?>

<?php the_field('shop_content_box', $other_page); ?>

提前致谢!

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    实际上,任何 CPT 都有自己的 slug。与非自定义帖子类型(例如帖子、页面或附件)的方式相同(分别为 postpageattachment)。

    但请注意不要将自定义帖子类型与该类型的实际帖子混淆。 Wordpress 中的任何帖子(当然包括 CPT 的帖子)都有一个 ID。如果您想使用任何其他帖子/页面的 ACF 的 get_fieldthe_field 查询自定义字段值您必须使用 ID,如您的示例中所示:

    <?php the_field('shop_content_box', $other_page); ?>
    

    所以,如果你只知道$other_page_slug(我想知道你是如何单独获得 slug 的......) 你应该检索它的 Post 对象。见:Get a post by its slug

    <?php
    function the_field_by_slug( $field, $slug, $cpt = 'post' ) {
        $args = [
            'name'           => $slug,
            'post_type'      => $cpt,
            'post_status'    => 'publish',
            'posts_per_page' => 1
        ];
        $my_post = get_posts( $args );
        if( $my_post ) {
            the_field( $field, $my_post->ID );
        }
    }
    the_field_by_slug( 'shop_content_box', $other_post_slug, $custom_post_type_slug );
    ?>
    

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2020-11-04
      • 1970-01-01
      • 2015-04-09
      • 2018-04-17
      • 2018-06-18
      • 1970-01-01
      • 2018-11-25
      • 2021-02-24
      相关资源
      最近更新 更多