[英]Associate template to Advanced Custom Fields post type
我正在尝试使用高级自定义字段插件,并将其与我编写的部分(可能不是正确的词)相关联,该部分将显示自定义帖子类型的字段。
如何将php文件与自定义帖子类型相关联?
目的是能够将部分嵌入到帖子中。
这是我的部分: cta-partial.php
<?php
/*
Template Name: CTA-Partial
*/
?>
<!-- cta markup -->
<!-- if there is an article then load -->
<?php
$args = array(
'post_type' => 'cta_post_type'
);
$query = new WP_Query( $args ); ?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) :
$query->the_post();?>
</div>
</div>
<!-- end the markup so as to allow full-width -->
<div class="article" style="background-image: url('<?php the_field('cta_background'); ?>')">
<div class="custom-background">
<div class="columns small-12 medium-6 image-container">
<div class="hide-for-medium">
<img src="<?php the_field('cta_background'); ?>">
</div>
</div>
<div class="columns small-12 medium-6 mobile-style">
<h1> <?php the_field('cta_title');?></h1>
<p><?php the_field('cta_text'); ?></p>
<a href="<?php the_field('button_link');?>"><button><?php the_field('button_label')?></button></a>
</div>
</div>
</div>
<div class="row">
<div class="columns small-12 medium-12 content-wrapper">
<!-- continue content loop -->
<?php endwhile; endif; wp_reset_postdata(); ?>
这是我要呈现与我的自定义字段帖子类型关联的php的文件。
这是ACF的文档: https : //www.advancedcustomfields.com/resources/我一直在搜索文档,但不确定是否可行。 谢谢您到目前为止所提供的帮助,仍在研究中。
我假设您要为该文件分配一个页面。 您可以使用archive-template.php类型的文件。
您可以将帖子ID(或用户ID,术语或其他字段)传递到ACF字段以检索位于其他位置的字段。 WP_Query
,看来WP_Query
是过大的。 尝试这个:
<?php
$cta_posts = get_posts( array(
'posts_per_page' => 1,
'post_type' => 'cta_post_type'
) );
if( $cta_posts ){
foreach( $cta_posts as $cta_post ):
?>
<div class="article" style="background-image: url(<?php the_field( 'cta_background', $cta_post->ID ); ?>)">
...
</div>
<?php
endforeach;
}
我的posts_per_page
假定您只希望页面上有一个CTA。 如果是这种情况,则帖子类型也可能会显得过大。 您可能想要查看ACF选项页面 ,将字段放在选项页面上,然后使用以下命令调用它们:
<div class="article" style="background-image: url(<?php the_field( 'cta_background', 'option' ); ?>)">
我认为您不需要在cta-partial.php部分中进行查询。
如果您使用的是<?php get_template_part('cta-partial.php'); ?>
<?php get_template_part('cta-partial.php'); ?>
分配的变量在局部变量中不可用。
如果使用<?php include( locate_template('cta-partial.php') ); ?>
<?php include( locate_template('cta-partial.php') ); ?>
相反,那么您确实有权访问从页面或帖子分配的变量。
在您的部分the_field()
,您可能需要调整the_field()
用法以获取当前帖子ID。 像这样:
<?php the_field('cta_background', $page_or_post_id); ?>
只需在您调用部分页面的原始页面中设置$page_or_post_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.