首页 > 解决方案 > WordPress:get_permalink 在插件中不起作用

问题描述

我正在尝试构建一个站点地图插件,但被困在一个简单的 WordPress 循环中。每次我尝试获取 URL 时,网站都会崩溃。它get_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

}

标签: wordpress

解决方案


传递给 的参数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();

参考:


推荐阅读