1
votes

I have created a Custom Post Type named "products" and a Custom Taxonomy named "product_category" To this custom post type I also created a Cpt-Template file "single-products.php" for displaying individual posts and a Taxonomy-Template "taxonomy-product_category" for showing all of my post for a specific taxonomy.

I use the the_permalink() to get the url of the individual posts and when you click on a post you jump straight to "single-product.php"-page. I managed to get all of this to work, finding the cpt-template single page for a single post but for some reason my wp_query won't run from the "single-product.php"-page. The only thing it will grab is the title, editor and thumbnail-image content from the post, no other custom fields will be displayed. I have create a metabox with some custom fields in my CPT. Those fields works and displays as they should from the taxonomy-archive-page but not from the single-page and I'dont understand why?

Here is my code. I appreciate to get some help on this. Thanks in advance.

====== My Custom Post Type "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);
    }
}

====== Custom Post Type Template "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 
2

2 Answers

2
votes

Cheers, you can use the archive-products.php to realise an archive.

Wordpress provides you a WP_Query for your single-{post_typ}.php and your archive-{post-typ}.php

There is no need to redeclare the 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 )),
));     

Example for 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();

?>


Example for single-{post-typ}.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(); ?>

The code-snippets aren't tested. Hope I could help you out

0
votes

I finally got this to work! I figured out thanks to Lukas R. explanation of not redeclare wp_query-class in my single-page (single-products.php). I could not get the archive-products.php to work but instead I already had my Custom Taxonomy archive for this purpose, (taxonomy-product_category). All I had to do was include my fields in the loop

    <?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(); ?>