通过 slug 从不同的 CPT 调用 ACF
Calling ACF from different CPT via slug
我想将在 CTP 中创建的自定义字段回显到小部件。
我通常会使用类似下面的内容从页面 ID 调用字段,但由于我的 CTP 使用的是 slug 而不是 ID,我正在寻找有关如何执行此操作的建议。
<?php
$other_page = 173;
?>
<?php the_field('shop_content_box', $other_page); ?>
提前致谢!
实际上,任何 CPT 都有自己的 slug。非自定义 post 类型(例如 Posts、页面或附件)也有它们的方式(分别为 post
、page
和 attachment
)。
但请注意不要将 Custom Post Type 与该类型的实际 post 混淆. Wordpress 中的任何 post(当然包括 CPT 的)都有一个 ID。如果您想使用 ACF 的 get_field
或任何其他 post/page 的 the_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 );
?>
我想将在 CTP 中创建的自定义字段回显到小部件。
我通常会使用类似下面的内容从页面 ID 调用字段,但由于我的 CTP 使用的是 slug 而不是 ID,我正在寻找有关如何执行此操作的建议。
<?php
$other_page = 173;
?>
<?php the_field('shop_content_box', $other_page); ?>
提前致谢!
实际上,任何 CPT 都有自己的 slug。非自定义 post 类型(例如 Posts、页面或附件)也有它们的方式(分别为 post
、page
和 attachment
)。
但请注意不要将 Custom Post Type 与该类型的实际 post 混淆. Wordpress 中的任何 post(当然包括 CPT 的)都有一个 ID。如果您想使用 ACF 的 get_field
或任何其他 post/page 的 the_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 );
?>