自定义 post 类型单页 wp_query 将不起作用

Custom post type single page wp_query won't work

我创建了一个名为 "products" 的自定义 Post 类型和一个名为 "product_category" 的自定义分类 对于这个自定义 post 类型,我还创建了一个 Cpt-Template文件 "single-products.php" 用于显示个人 post 和 Taxonomy-Template "taxonomy-product_category" 用于显示我的所有 post 特定分类。

我使用 the_permalink() 获取单个 post 的 url,当您单击 post 时,您会直接跳转到 "single-product.php"-页面。我设法让所有这些都起作用,找到了单个 post 的 cpt-template 单页,但由于某种原因,我的 wp_query 不会从 [=28] 运行 =]-页面。它唯一会抓取的是 post 中的标题、编辑器和 thumbnail-image 内容,不会显示其他自定义字段。我在我的 CPT 中创建了一个带有一些自定义字段的元数据框。这些字段在 taxonomy-archive-page 中正常工作和显示,但在 single-page 中却不正常,我不明白为什么?

这是我的代码。我很高兴能得到一些帮助。提前致谢。

====== 我的自定义 Post 输入 "Products" =======

function create_taxonomy_products() {

    $labels = array(
        'name'              => _x( 'Produktkategorier', 'taxonomy singular name', 'products' ), 
        'singular_name'     => _x( 'Produktkategori', 'taxonomy singular name', 'products' ),
        'search_items'      => __( 'Sök Produktkategori', 'products' ),
        'all_items'         => __( 'Alla Produktkategorier', 'products' ),
        'parent_item'       => __( 'Förälder Produktkategori', 'products' ),
        'parent_item_colon' => __( 'Förälder Produktkategori:', 'products' ),
        'edit_item'         => __( 'Ändra Produktkategori', 'products' ),
        'update_item'       => __( 'Uppdatera Produktkategori', 'products' ),
        'add_new_item'      => __( 'Lägg till ny Produktkategori', 'products' ),
        'new_item_name'     => __( 'Nytt Produktkategorinamn', 'products' ),
        'menu_name'         => __( 'Produktkategori', 'products' ),  
        'not_found'         => __( 'Inga Produktkategorier hittade.', 'products' ),   
        'view_item'         => __( 'Se Produktkategorier', 'products' ),      
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => true, 
        'query_var' => true, 
        'show_admin_column' => true, 
        'rewrite' => array( 'slug' => 'produkter' ), 
    );

    register_taxonomy(
        // Name of our Taxonomy 
        'product_category', 'products', $args ); 
}

add_action('init', 'create_taxonomy_products', 0);


function register_custom_post_type_products() {

    $labels = array(
        'name'               => _x( 'Produkter', 'post type general name', 'products' ),
        'singular_name'      => _x( 'Produkt', 'post type singular name', 'products' ),
        'menu_name'          => _x( 'Produkter', 'admin menu', 'products' ),
        'name_admin_bar'     => _x( 'Produkter', 'add new on admin bar', 'products' ),
        'add_new'            => _x( 'Lägg till nya Produkter', 'Produkter', 'products' ),
        'add_new_item'       => __( 'Lägg till ny Produkt', 'products' ),
        'new_item'           => __( 'Nya Produkter', 'products' ),
        'edit_item'          => __( 'Ändra Produkter', 'products' ),
        'view_item'          => __( 'Se Produkter', 'products' ),
        'all_items'          => __( 'Alla Produkter', 'products' ),
        'search_items'       => __( 'Sök Produkter', 'products' ),
        'parent_item_colon'  => __( 'Förälder Produkter:', 'products' ),
        'not_found'          => __( 'Ingen Produkter hittad.', 'products' ),
        'not_found_in_trash' => __( 'Ingen Produkt hittad i papperskorgen.', 'products' ),

        'featured_image'        => __( 'Produktbild', 'products' ),
        'set_featured_image'    => __( 'Lägg till Produktbild', 'products' ),
        'remove_featured_image' => __( 'Ta bort Produktbild', 'products' ),
        'use_featured_image'    => __( 'Använd Produktbild', 'products' ),
    );

    $features = array(
        'title',
        'thumbnail',
        'editor',
    );

    $args = array (
        'labels' => $labels,
        'public' => true,
        'supports' => $features,
        'has_archive'         => false,
        'menu_icon' => 'dashicons-networking',
        'taxonomies' => array(
            'product_category',
        ),
    );
    // Name of our Custom Post Type
    register_post_type('products', $args); 
}

add_action( 'init', 'register_custom_post_type_products' );

function create_meta_box_products() {
    add_meta_box(
        'products_metabox',
        'Produkter:', 
        'create_metabox_products', 
        'products',
        'normal',
        'default'
    );
}

function products_metabox( $post ) {
    echo 'Info here';
}
add_action( 'add_meta_boxes', 'create_meta_box_products' );


function create_metabox_products( $post ) {
?>
    <form action="" method="post">
<?php
        wp_nonce_field('kk_metabox_nonce', 'kk_nonce');

        $products_name = get_post_meta($post->ID, 'products_name', true); 
        $products_desc = get_post_meta($post->ID, 'products_desc', true);       
?> 
        <p>
            <span><i>Type in name of product</i></span><br/>
            <input type="text" name="products_name" value="<?php echo esc_attr( $products_name ); ?>" placeholder="..." />
        </p>   
        <p>
            <span><i>Type in description of product</i></span><br/>
            <input type="text" name="products_desc" value="<?php echo esc_attr( $products_desc ); ?>" placeholder="..." />
        </p>       
    </form>
<?php 
} 


add_action( 'save_post', 'save_meta_products_name' );
function save_meta_products_name( $post_id ) {
    if(!isset($_POST['kk_nonce']) ||
        !wp_verify_nonce($_POST['kk_nonce'],
        'kk_metabox_nonce')) return;
    if(isset($_POST['products_name'])) {
        $new_value_products_name = ($_POST['products_name']);
        update_post_meta($post_id, 'products_name', $new_value_products_name);
    }
}

add_action( 'save_post', 'save_meta_products_desc' );
function save_meta_products_desc( $post_id ) {
    if(!isset($_POST['kk_nonce']) ||
        !wp_verify_nonce($_POST['kk_nonce'],
        'kk_metabox_nonce')) return;
    if(isset($_POST['products_desc'])) {
        $new_value_products_desc = ($_POST['products_desc']);
        update_post_meta($post_id, 'products_desc', $new_value_products_desc);
    }
}

====== 自定义 Post 类型模板 "single-product.php" =======

if ( have_posts() ) { 
?>
    <div class="container">
        <div class="row">
<?php             
            global $wp_query; 
            $term = $wp_query->get_queried_object();  
            $post_type = get_post_type( $post->ID );                

            $wp_query = new WP_Query(array(
                'post_type'         => 'products',
                'posts_per_page'    => -1, // -1 =  show all posts
                'tax_query'         => array(array('taxonomy' => 'product_category', 'field' => 'id', 'terms' => $term->term_id )),
            ));     
?>
<?php 
            while( $wp_query->have_posts() ) {
                $wp_query->the_post(); 

                $products_name = get_post_meta($post->ID, 'products_name'); 
                $products_desc = get_post_meta($post->ID, 'products_desc');  
?>                      
                <article class="products-col col-12 collapse entry-content">
                    <div class="col-12">
<?php                                                                               
                        $productsName = $products_name[0] ? '<h2>'.$products_name[0].'</h2>' : '';
                        echo isset($productsName) ? $productsName : '';  

                        $productsdesc = $products_desc[0] ? '<p>'.$products_desc[0].'</p>' : '';
                        echo isset($productsdesc) ? $productsdesc : '';                                                                                 

                        the_post_thumbnail();

                        the_content();
?>
                    </div>                                             
                </article>  
<?php 
            } // while      

            wp_reset_postdata();
?>
        </div> <!-- .row -->
    </div> <!-- .container -->
<?php 
} // if 

干杯,可以使用archive-products.php实现一个archive

Wordpress 为您提供了一个 WP_Query 用于您的单一-{post_typ}.php 和您的存档-{post-typ}.php

不需要重新声明 WP_Query:

global $wp_query; 
$term = $wp_query->get_queried_object();  
$post_type = get_post_type( $post->ID );                

$wp_query = new WP_Query(array(
    'post_type'         => 'products',
    'posts_per_page'    => -1, // -1 =  show all posts
    'tax_query'         => array(array('taxonomy' => 'product_category', 'field' => 'id', 'terms' => $term->term_id )),
));     

示例 archive-{post-typ}.php:

<?php
get_header();
if(have_posts()) : while(have_posts()) : the_post();
    the_title();
    echo '<div class="entry-content">';
    the_content();
    echo '</div>';
endwhile; endif;
get_footer();

?>


单-{post-类型}的示例。php:

<?php get_header(); ?>

<main id="main" class="site-main" role="main">

    <?php
    // Start the loop
    while ( have_posts() ) : the_post();
        echo '<h1>';
        the_title();
        echo '</h1>';

        echo '<a href="';
        the_permalink();
        echo '">That\'s me! -> '; the_title(); 
        echo '</a>';

        the_content();
    // End the loop.
    endwhile;
    ?>

</main><!-- .site-main -->

<?php get_footer(); ?>

代码片段未经测试。希望能帮到你

我终于让它工作了!感谢 Lukas R. 在我的单页 (single-products.php) 中没有重新声明 wp_query-class 的解释,我想通了。我无法让 archive-products.php 工作,但我已经有了用于此目的的 Custom Taxonomy 存档,(taxonomy-product_category)。我所要做的就是将我的字段包含在循环中

    <?php get_header(); ?>

<main id="main" class="site-main" role="main">
<?php
    // Start the loop
    while ( have_posts() ) : the_post();
        $products_intro = get_post_meta($post->ID, 'products_intro');
        $products_desc = get_post_meta($post->ID, 'products_desc'); 

        echo '<h1>';
        the_title();
        echo '</h1>';

        the_post_thumbnail();

        the_content();

        // Custom Metabox-fields
        $productsIntro = $products_intro[0] ? '<p class="products-title padd-bottom">'.$products_intro[0].'</p>' : '';
        echo isset($productsIntro) ? $productsIntro : '';   

        $productsdesc = $products_desc[0] ? '<p class="products-title padd-bottom">'.$products_desc[0].'</p>' : '';
        echo isset($productsdesc) ? $productsdesc : '';  

        // Advanced Custom Fields
        the_field('innehall');

    // End the loop.
    endwhile;
    ?>
</main>

<?php get_footer(); ?>