wordpress - WordPress:get_permalink 在插件中不起作用
问题描述
我正在尝试构建一个站点地图插件,但被困在一个简单的 WordPress 循环中。每次我尝试获取 URL 时,网站都会崩溃。它get_permalink
正在制作循环并使网站崩溃。我已经测试了这些,但它们都不适合我:
get_permalink
the_permalink
get_post_permalink
get_the_permalink
循环:
function fa_sitemap_build() {
// Create/open the file
$file = fopen( get_template_directory() . '/sitemap.xml','wb');
$the_query = get_posts('post_type = page');
foreach ( $the_query as $post ) {
$title = get_the_title($post->ID);
$link = get_permalink($post->ID);
$date = $post->post_modified;
$url .= '
<url>
<title>'.$title.'</title>
<url>'.$link.'</url>
<lastmod>'.$date.'</lastmod>
</url>
';
}
wp_reset_postdata();
$sitemap = '
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
'.$url.'
</urlset>';
// write content to the file
fwrite( $file, $sitemap );
fclose( $file ); // Close the file
}
解决方案
传递给 的参数get_posts()
必须是一个数组。试试下面的代码。
<?php
$args = array(
'post_type' => 'page',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
echo $post->title;
echo '<br />';
echo $post->post_content;
echo '<br />';
echo get_permalink( $post->ID );
}
或者您也可以使用以下代码,它的工作原理相同。
$args = array(
'post_type' => 'page',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
setup_postdata( $post );
the_title();
echo '<br />';
the_content();
echo '<br />';
the_permalink();
}
wp_reset_postdata();
参考:
get_posts()
法典上的功能
推荐阅读
- java - 查找给定值的数据,如果不存在,则查找该值数据系列中的最后一个条目
- java - 将 POJO 转换为地图
? - jquery - 在值列表中查询 json 以获取现有值
- javascript - 如果选中复选框,则解锁字段。VueJS
- c# - 无法连接到一个房间
- swiftui - 您将如何在 SwiftUI 表单中使用 CustomPicker 模拟 DatePicker 表单行为?
- reactjs - 在每个选择下拉框中显示一项
- laravel - 为什么我的 laravel 迁移脚本不起作用?
- flask - 为什么我无法从智能手机访问我的烧瓶应用程序?
- flutter - Flutter-desktop 无框窗口支持