programing

ACF 관계 필드 - 다른 포스트 유형의 get_field 값

newnotes 2023. 3. 1. 11:29
반응형

ACF 관계 필드 - 다른 포스트 유형의 get_field 값

POST 페이지(통상적인 투고 타입)에서 ACF 관계 필드를 설정했습니다.이 안에서 directory_listings의 포스트 타입 아래에 있는 회사명을 선택할 수 있습니다.

디렉토리 리스트 페이지에 다음의 코드가 표시되어 있기 때문에, get_field만을 사용하는 것은 기능하지 않습니다.이 값은 이 페이지에 없기 때문에, 대신에 POST 타입의 다른 곳에 있습니다.

정보를 어떻게 얻어야 할지 모르겠어요.

DIRECTORY_LISTINGS 포스트 유형 아래에 있는 페이지 중 하나의 코드:

$posts = get_field('related_articles');

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>

저는 텍스트로 설명을 잘 못하기 때문에 예시도입니다. 여기에 이미지 설명 입력

현재 회사 편집 페이지(directory_listing)에 관계 필드를 대신 설정했습니다.이것은, 다음의 경우에 동작합니다. 1) 이 비즈니스 리스트에 대한 관련의 투고 -> 투고 선택 -> 퍼블리시 -> 이 리스트가 비즈니스 리스트 페이지에 표시됩니다.예: http://bit.ly/1vwydDl (페이지 하단)

POST 편집 페이지에서 투고 업체를 선택하고 싶습니다.ACF를 통해 필드를 입력할 수 있지만 실제로 결과를 표시하도록 하는 것은 문제가 없습니다.

배경 정보:

get_field()에는 다음 3가지 파라미터가 있습니다.

  1. $field_name: 취득할 필드의 이름.예: "page_content" (필수)
  2. $post_id : 값이 입력된 특정 게시 ID.디폴트에서는, 현재의 투고 ID(필수는 아닙니다). 옵션 / 분류 / 사용자 등일 수도 있습니다.
  3. $format_value

(ID를 알고 있는) 특정 게시물 획득에만 관심이 있는 경우 키는 두 번째 파라미터가 됩니다.$post_idACF에는 마법 같은 것이 없습니다.간단히 말하면:meta_value(즉, 투고 리스트의 디렉토리가 각 투고(그 투고 리스트에 첨부)에 보존됩니다.$post_id).

다만, 당신의 경우는, 취득하고 싶은 투고의 ID를 알 수 없습니다.

솔루션:

우리가 당신이 원하는 것을 간단한 문장으로 설명한다면, 그 문장은 다음과 같이 됩니다.

에서 투고 표시/취득directory_listings(커스텀 투고 타입) 페이지에는,meta_value이 페이지를 가리키고 있습니다.

분명히, 당신은 사용할 수 없습니다.get_field()왜냐하면 당신의 문제는 "필드 획득"과는 아무런 관련이 없기 때문입니다.「특정 필드를 가지는 투고를 검색해 주세요」라고 하는 것이, ACF 에는 이 점에 관한 훌륭한 문서가 있습니다.

Word Press에는 WP_Query라고 불리는 멋진 클래스와 get_posts()라고 불리는 비슷한 놀라운 기능이 포함되어 있습니다.위의 문장을 다시 한 번 살펴본 후 함수로 변환하면 다음과 같은 작업을 수행할 수 있습니다.get_posts()서, 「」는meta_key 가지고 있다value of의$post_id.

좀 더 요.directory_listings페이지에는 다음과 같은 쿼리가 표시됩니다.

$related_articles = get_posts(array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'related_articles', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));

if( $related_articles ): 
    foreach( $related_articles as $article ): 

    // Do something to display the articles. Each article is a WP_Post object.
    // Example:

    echo $article->post_title;  // The post title
    echo $article->post_excerpt;  // The excerpt
    echo get_the_post_thumbnail( $article->ID );  // The thumbnail

    endforeach;
endif;

해당 쿼리에서 찾는 사용자 지정 필드인 경우 다음과 같이 수행할 수 있습니다.

<?php
$posts = get_field('related_articles');

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <?php the_field('your_custom_field',$post); ?>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>

만약 제가 이것을 제대로 이해했다면, 이것은 제가 가졌던 것과 같은 문제입니다.저 같은 경우에는 쇼트 코드를 사용하는 것이 더 좋았습니다.「」를 사용합니다.[acf field="person"]그 필드가 관계성 정보였기 때문에 그 사람의 아이디만 알려줬을 뿐 그들의 필드에 접근할 수 없었습니다. 「」, 「」를 사용합니다.[acf field="last_name", post_id=[acf field="person"]워드프레스 파서가 중첩된 쇼트코드를 허용하지 않기 때문에 이상적인 솔루션이 될 수 없습니다.

그래서 이 작은 php 솔루션을 생각해 냈습니다.

function import_cf_from_cpt( $atts ) {
    // import custom fields from other custom post types that are connected via a relationship to the calling custom post type
    // shortcode: [import <field from calling CPT of type relationship> <field name from field from other CPT>]
    // ex [import person last_name] --> Doe

    $postID = do_shortcode("[acf field={$atts[0]}]");
    // we use the first attribute to get the ID of the object
    $postField = get_field($atts[1], $postID);
    // next, using the ID we look for the field of the second attribute.
return $postField;
}
add_shortcode( 'import', 'import_cf_from_cpt' );

이것을 함수에 배치하다.php 파일에서는 쇼트 코드를 사용할 수 있습니다.

[import person last_name]예를 들어, 또는 다른 게시물에서 필드 값을 Import하기 위한 다른 조합입니다.

언급URL : https://stackoverflow.com/questions/27403089/acf-relationship-fields-get-field-values-from-other-post-type

반응형