【问题标题】:Wordpress Custom Post Type - cannot display single post pageWordpress 自定义帖子类型 - 无法显示单个帖子页面
【发布时间】:2019-05-08 01:32:18
【问题描述】:

我已经使用代码设置了 WordPress 自定义帖子类型。我已经设法让自定义帖子显示在“存档”页面中,但是,如果我点击“存档”页面中的链接,WP 找不到单个帖子页面。

我想我的自定义帖子永久链接可能有问题。希望有人能帮帮我

functions.php

add_action('init', 'create_portfolio');

function create_portfolio(){

    $portfolio_args = array(
        'label' => _('Portfolio'),
        'singular_label' => _('Portfolio Item'),
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => true,
        'supports' => array('title', 'editor', 'thumbnail')
    );

    register_post_type('portfolio', $portfolio_args);

}

页面模板

为了显示自定义帖子,我使用 WP Query 设置了一个新页面模板:

<?php

/*
Template Name: The Portfolio
*/

get_header(); ?>


<?php
$args = array(
    'post_type'   => 'portfolio',
    'post_status' => 'publish'
 );

$portfolios = new WP_Query( $args );


if( $portfolios->have_posts() ) :
  while( $portfolios->have_posts() ) : $portfolios->the_post();
    ?>

  <h1><a href="<?php echo get_post_permalink() ?>"><?php echo 
  the_title();?></a></h1>

     <?php the_post_thumbnail('medium'); ?>

      <?php //the_content(); ?>
      <?php the_excerpt(); ?>

    <?php

 // Stop the loop when all posts are displayed
 endwhile;

// If no posts were found
else :
?>
<p>Sorry no posts matched your criteria.</p>
<?php
endif;
?>   
<?php
get_footer();
?>

页面模板代码似乎可以正常工作,并且所有自定义帖子都按预期显示,但是当我单击“标题”链接时,我收到“未找到页面”错误。

我注意到,当我将鼠标悬停在“标题”链接上时,浏览器状态栏中会显示以下内容:

someplace.com/wp/portfolio/christmas-cake

但是,我被带到的错误页面有 URL:

someplace.com/wp/portfolio/christmas-cake/christmas-cake/

发生了什么事??

【问题讨论】:

  • 您是否测试过重新保存您的永久链接?我也会在你结束后添加这个:wp_reset_postdata()

标签: php wordpress


【解决方案1】:

我认为你只需要在你的主题中创建single-{posttype}.php 文件。

尝试创建single-portfolio.php 文件并在那里执行一些代码。

请从后台的设置 -> 永久链接选项再次保存永久链接设置。

您还需要在代码中传递帖子 ID 并替换它,如下所示:

<a href="<?php echo get_permalink($post->ID); ?>">

尝试一下,如果遇到任何问题,请告诉我。

【讨论】:

  • 非常感谢!我创建了 single-portfolio.php,添加了 get_permalink($post->ID) 并保存了永久链接。它现在运行良好。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多