Reputation: 51
I am wanting to echo a custom field created in a CTP to a widget.
I would usually use something like the below to call a field from a page ID, but as my CTP uses a slug rather than ID i'm looking for suggestions on how to do this.
<?php
$other_page = 173;
?>
<?php the_field('shop_content_box', $other_page); ?>
Thanks in advance!
Upvotes: 1
Views: 750
Reputation: 3401
Effectively, any CPT has its own slug. The same way non-custom post types (such as Posts, Pages or Attachments) have theirs (being respectively post
, page
and attachment
).
But be careful not to confuse a Custom Post Type with an actual post of that type. Any post in Wordpress (including, of course, those of a CPT), has an ID. If you want to query a Custom Field value with ACF's get_field
or the_field
of any other post/page you must use the ID, as in your example:
<?php the_field('shop_content_box', $other_page); ?>
So, if you only know the $other_page_slug
(I wonder how do you get the slug alone...) you should retrieve its Post Object. See: 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 );
?>
Upvotes: 1