我正在使用高级自定义字段,并希望以与类别相同的布局显示页面,其中包含自定义字段具有特定值的帖子。
我不知道如何通过编程实现这一点,也不知道如何搜索有助于实现这一点的插件。
问题:
如何创建新的页面路由?或者我是否可以以某种方式避免这种情况,并为此使用类别模板并对过滤器进行编程?
该页面应添加到菜单中-我可能会使用自定义链接来完成此操作?
非常感谢您的帮助。
我正在使用高级自定义字段,并希望以与类别相同的布局显示页面,其中包含自定义字段具有特定值的帖子。
我不知道如何通过编程实现这一点,也不知道如何搜索有助于实现这一点的插件。
问题:
如何创建新的页面路由?或者我是否可以以某种方式避免这种情况,并为此使用类别模板并对过滤器进行编程?
该页面应添加到菜单中-我可能会使用自定义链接来完成此操作?
非常感谢您的帮助。
值得注意的是,通过Posteta进行查询(这是为了识别所有具有特定ACF字段的帖子所必须做的事情)可能会使您的网站陷入困境。
Alternative: taxonomy
如果改用分类法,它将为您节省大量编码,更容易,而且WP加载东西可能更快。让你从这个方向开始:周一中午。com/wordpress归档页分类法Answer to original question
但是,如果您想坚持使用自定义字段,可以采用以下方法:Changing the Page template
有几种方法可以使页面看起来像类别。如果希望创建的每个页面都使用自定义字段并显示为类别,则需要创建自定义字段page.php
在您的主题中。
如果有一天您可能会创建一个希望显示为页面的页面,那么您需要创建一个自定义tpl-page.php
在您的主题中。
Creating the template file
无论你走哪条路,如果你还没有使用自定义主题,首先create a child theme. 这样,每当父主题更新时,您就不会丢失自定义设置。基本上,您需要做的就是创建style.css
文件-添加一些最少必需的注释,以便WP识别子主题,确保更改名称,以便您可以轻松地在管理区域中选择正确的主题,并将原始主题作为父主题安装。style.css
这就是WP在技术上所需要的一切,让它认识到这里有一个新的主题。然后,复制父主题的category.php
(或archive.php
如果没有类别)内容并将其粘贴到新文件中-或者page.php
或tpl-page.php
, 以您在上面选择的为准。如果您已经在使用自定义主题,则可以编辑page.php
直接或复制category.php
进入一个名为tpl-page.php
.
然后,开始修改新文件的代码。您需要定制的内容将取决于您使用的主题。
您的新文件应该大致如下所示:
<?php
// If you are editing tpl-page.php, make sure to add comments at the top
// so WP will recognize this custom Page Template. If not, remove the comment.
/*
* Template Name: Page as Category
*/
// Keep the header call and basic page markup here. Yours will vary.
get_header(); ?>
<main><?php
// Check for custom field
if(get_field(\'your_acf_field_requirement\')) {
$customValue = get_field(\'your_acf_field_requirement\');
// Query all posts that have this value.
$args = array(
\'post_type\' => \'post\', // only grab Posts
\'numberposts\' => -1, // get all Posts that meet the requirements
\'meta_key\' => \'your_acf_meta_key_name\', // check this meta key
\'meta_value\' => "$customValue" // match the Page\'s requirement
);
$posts = new WP_Query($args);
if($posts->have_posts()) {
while($posts->have_posts()) {
$query->the_post();
// Now you have the data. Display it as you like.
// If your theme already has template parts, use one.
// If not, you might manually need to display content like this:
?><div class="onePost"><?php
the_title();
?></div><?php
}
}
// reset
wp_reset_postdata();
}
// If you are editing page.php, you should have a fallback in case the field is empty:
else {
// For this part, keep the original page.php loop. Any pages where the
// ACF field is empty will just appear as normal Pages.
}
// Keep the footer call and basic page markup here. Yours will vary.
?></main>
<?php get_footer(); ?>
一旦你在发展中走得更远,你可以就你可能不确定或停留在的地方提出更具体的问题。我正在尝试在函数中获取自定义帖子类型的类别。php,但它不返回任何值,当我在任何主题文件中运行此查询时,它工作正常。这是我的密码function get_destinations(){ $args = array( \'type\' => \'accomodation\', \'child_of\' => 0, \'parent\'