【问题标题】:Wordpress ACF: Using a page (with a specific page template) as a CPT archive pageWordpress ACF:使用页面(带有特定页面模板)作为 CPT 存档页面
【发布时间】:2018-10-04 16:56:56
【问题描述】:

我正在使用 ACF 在两个区域创建具有独立灵活布局部分的页面,即主页部分区域和侧边栏区域。

我有一个名为 case-studies 的 CPT,并创建了一个名为 case-studies 的页面。我在 CPT 中设置了'has_archive' => false,,希望该页面被使用但是(我理解)有一个层次结构,所以如果没有给出存档,那么它将加载我的 home.php(这是什么我用于我的新闻,posts 类型)。

有什么方法可以将页面用作 CPT 的存档?目前我能看到的唯一解决方案是使用ACF CPT Options Pages 插件并将我创建的 ACF 字段附加到我的“案例研究存档”页面但是,我必须复制我的所有代码以便他们可以调用正确的内容。例如:

the_field('field_name');the_field('field_name', 'cpt_case-studies');

是否有人能够将页面用作 CPT 的存档,并为该页面分配一个模板,该模板既可查询 CPT 帖子又具有页面中的 ACF 字段?

非常感谢您的帮助。如果还有什么我可以提供的,请告诉我。

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    最好的方法是将has_archive 参数设置为true,然后在您的主题中创建一个archive-case-studies.php 模板。您仍然可以使用 ACF 中的自定义字段。当您使用the_field()the_get() 时,第二个接受的参数是post id,但这是根据当前全局对象自动设置的。

    例如:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
        <?php the_field( 'custom_field', $post->ID ); ?>
    
    <?php endwhile; endif; ?>
    

    等同于:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
        <?php the_field( 'custom_field' ); ?>
    
    <?php endwhile; endif; ?>
    

    长话短说;使用带有自定义模板的存档页面,您将能够毫无问题地实现我认为您所追求的目标。如果您这样做,则比滚动自定义内容要少得多,因为存档页面可能会很痛苦。

    【讨论】:

    • 您好丹尼尔,感谢您的回答。这帮助我找到了正确的答案,我需要能够将页面内容放到 CPT 存档页面上。我将在下面纠正我的解决方案。再次感谢。
    【解决方案2】:

    基于 Daniel James 的回答,我创建了一个函数,该函数包含一个数组,用于获取我需要获取的所有页面的 ID,以便将其内容添加到特定的存档页面。

    function getOtherPageID($page = null) 
    {
        global $post; 
        $postIDs = [
            'case-studies' => 42, // 42 being the page ID of the content I need
        ];
    
        if(array_key_exists($page, $postIDs)) :
            $id = $postIDs[$page];
        endif;
    
        return $id;
    }
    

    通过在我的archive-case-studies.php 模板页面(或任何其他存档模板)中调用$id = getOtherPageID('case-studies');,我可以获取我需要的 ID,然后将其添加到 ACF 字段。然后在每个对应的 ACF 字段调用中,我只需将 $id 添加到 ACF 字段调用中:get_field('field_name', $id);

    希望这对其他人有所帮助。

    ----更新----

    我没有输入帖子 ID(在上面的例子中为 42),而是将其修改为使用 get_page_by_path(); 函数。因此,我的功能是:

    function getOtherPageID($page = null) 
    {
        global $post; 
        $postIDs = [
            'case-studies' => get_page_by_path( $page ),
        ];
    
        if(array_key_exists($page, $postIDs)) :
            $id = $postIDs[$page]->ID;
        endif;
    
        return $id;
    }
    

    现在这将获取帖子对象,然后将$id 设置为帖子对象的 ID,然后将其返回。

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 2016-12-01
      相关资源
      最近更新 更多