[英]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.