WordPress无法在single.php页面上显示自定义帖子类型

时间:2014-12-13 04:17:26

标签: wordpress

我正在尝试制作名为products的WordPress自定义帖子类型。在我的主题function.php文件中,我编写了代码(请参阅下面的代码)。在WordPress管理员中,我可以看到一个名为Products的新菜单。我甚至创建了一个新产品,写了标题和内容并保存。

到目前为止一切都很好。我甚至可以在首页看到新的“产品”帖子。

然而,当我点击它时,WordPress找不到它并显示404 not found错误页面。但是对于WordPress正常post类型,它不会发生这样的情况,只有这样的自定义帖子类型。我在谷歌搜索了很多并按照他们的指示,但没有一个解决了我的问题。

enter image description here

请帮忙。以下是我的代码:

<?php
add_action('init', 'product_register');
function product_register() {
	$labels = array(
		'name'               => _x( 'Products', 'post type general name', 'your-plugin-textdomain' ),
		'singular_name'      => _x( 'Product', 'post type singular name', 'your-plugin-textdomain' ),
		'menu_name'          => _x( 'Products', 'admin menu', 'your-plugin-textdomain' ),
		'name_admin_bar'     => _x( 'Product', 'add new on admin bar', 'your-plugin-textdomain' ),
		'add_new'            => _x( 'Add New', 'product', 'your-plugin-textdomain' ),
		'add_new_item'       => __( 'Add New Product', 'your-plugin-textdomain' ),
		'new_item'           => __( 'New Product', 'your-plugin-textdomain' ),
		'edit_item'          => __( 'Edit Product', 'your-plugin-textdomain' ),
		'view_item'          => __( 'View Product', 'your-plugin-textdomain' ),
		'all_items'          => __( 'All Products', 'your-plugin-textdomain' ),
		'search_items'       => __( 'Search Products', 'your-plugin-textdomain' ),
		'parent_item_colon'  => __( 'Parent Products:', 'your-plugin-textdomain' ),
		'not_found'          => __( 'No products found.', 'your-plugin-textdomain' ),
		'not_found_in_trash' => __( 'No products found in Trash.', 'your-plugin-textdomain' )
	);

	$args = array(
		'labels'             => $labels,
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'product' ),
		'capability_type'    => 'post',
		'has_archive'        => true,
		'hierarchical'       => false,
		'menu_position'      => null,
		'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
	);
 
    register_post_type( 'product' , $args );
	flush_rewrite_rules();
}
add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {
	if ( ( is_home() && $query->is_main_query() ) || is_feed() )
	$query->set( 'post_type', array( 'post', 'product' ) );

	return $query;
}
?>

我的代码主要基于this link

的帮助

1 个答案:

答案 0 :(得分:0)

谢谢大家。现在我的自定义帖子类型正在运行。

我的错误是我使用以下条件将名为products.php的自定义帖子类型源代码文件包含在functions.php文件中:

if ( is_admin() ) {
      include_once('products.php'); 
}

然后,偶然地,我删除了条件并且只使用了:

include_once('products.php');

现在它工作正常。感谢大家的提示和帮助。他们对我很有帮助。