简体   繁体   中英

Display the custom posts by the terms

The think is I want to display on front-end of my WP the custom posts which has specific terms, but I have problem to get term_id of specific taxonomies using foreach loop. I m using fresh WP installation and I m working with Twenty twenty theme.

So first I create custom post type "devices" in my function.php, next I created taxonomy "copy_device" with terms "new", "used", "color", "wb". So I want to display for example all "new colour copy devices" but not "used colour copy devices".

I`m trying to display the custom post type with specific terms on front-end so I did the code below. But I get nothing... If I remove if statement "if ( $terms && ! is_wp_error( $terms ) ){" in page.php I get the error "Warning: Invalid argument supplied for foreach() in /(...)/public_html/wp-content/themes/twentytwenty/page.php on line 43"

Array ( )

line 43 is "foreach ( $terms as $term ) {"

FUNCTION.php

function td_devices_posttype() {
 $labels = array(
     'name'                => _x( 'Devices', 'Post Type General Name', 'textdomain' ),
     'singular_name'       => _x( 'Device', 'Post Type Singular Name', 'textdomain' ),
     'menu_name'           => esc_html__( 'Devices', 'textdomain' ),
     'parent_item_colon'   => esc_html__( 'Parent Device', 'textdomain' ),
     'all_items'           => esc_html__( 'All Devices', 'textdomain' ),
     'view_item'           => esc_html__( 'View Devices', 'textdomain' ),
     'add_new_item'        => esc_html__( 'Add New Devices', 'textdomain' ),
     'add_new'             => esc_html__( 'Add New', 'textdomain' ),
     'edit_item'           => esc_html__( 'Edit Devices', 'textdomain' ),
     'update_item'         => esc_html__( 'Update Devices', 'textdomain' ),
     'search_items'        => esc_html__( 'Search Devices', 'textdomain' ),
     'not_found'           => esc_html__( 'Not found', 'textdomain' ),
     'not_found_in_trash'  => esc_html__( 'Not found in Trash', 'textdomain' )
 );
 $args = array(
     'label'               => esc_html__( 'devices', 'textdomain' ),
     'description'         => esc_html__( 'All devices you have', 'textdomain' ),
     'labels'              => $labels,
     'taxonomies'          => array( 'copy_device'),
     'hierarchical'        => false,
     'public'              => true,
     'show_ui'             => true,
     'show_in_menu'        => true,
     'show_in_nav_menus'   => true,
     'show_in_admin_bar'   => true,
     'menu_position'       => 100,
     'can_export'          => true,
     'has_archive'         => esc_html__( 'devices' ),
     'exclude_from_search' => false,
     'publicly_queryable'  => true,
     'query_var'           => true,
     'show_admin_column'   => true,
     'capability_type'     => 'post',
     'rewrite'             => array('slug' => 'devices'),
     'supports'            => array( 'title','editor','thumbnail', 'custom-fields')
 );
 register_post_type( 'devices', $args );
}
add_action( 'init', 'td_devices_posttype' );

// custom taxonomies Copy devices
function td_posttype_taxonomy() {
    $labels = array(
        'name'                  => 'Copy Devices',
        'singular_name'         => 'Copy Device',
        'search_items'          => 'Search items',
        'all_items'             => 'All items',
        'parent_item'           => 'Parent item',
        'parent_item_colon'     => 'Parent item colon:',
        'edit_item'             => 'Edit item',
        'update_item'           => 'Update item',
        'add_new_item'          => 'Add new item',
        'new_item_name'         => 'New item name',
        'menu_name'             => 'Copy Devices'
    );

    $args = array (
        'hierarchical'          => true,
        'labels'                => $labels,
        'show_ui'               => true,
        'show_admin_column'     => true,
        'show_in_rest'          => true,
        'query_var'             => true,
        'rewrite'               => array( 'slug' => 'copy-device')
    );

    register_taxonomy( 'copy_device', array( 'devices' ), $args );
}
add_action('init', 'td_posttype_taxonomy');

In PAGE.php I have the following code:

            // trying to hook terms ID`s (Not working?)
            $termID = array();
            $terms = get_the_terms($post->ID, 'copy_device');


            if ( $terms && ! is_wp_error( $terms ) ){
              foreach ( $terms as $term ) {
                $termID[] = $term->term_id;
              }
              echo '<pre>'; print_r(array_values($termID)); echo '</pre>';
            }

            // Loop and return terms
            foreach ( $categories as $categorie ):

                // set up a new query
                $args = new WP_Query(
                    array(
                        'post_type' => 'devices',
                        'tax_query' => array(
                            array(
                                'taxonomy'          => 'copy_device',
                                'terms'             => array( 'new', 'colour' ),
                                'field'             => 'slug',
                                'hide_empty'        => false,
                            )
                        )
                    )
                );
            ?>

            <h3><?php echo $categorie->name; ?></h3>
            <ul>
            <?php while ($args->have_posts()) : $args->the_post(); ?>
                <li><?php the_title(); ?></li>
            <?php endwhile; ?>
            </ul>

            <?php
                $args = null;
                wp_reset_postdata();
              endforeach;
            ?>

if I do the following:

              array(
                'taxonomy'    => esc_html__('copy_device'),
                'hide_empty'  => true,
              )
            );?>

I get:

Array
(
[0] => WP_Term Object
(
[term_id] => 12
[name] => BW
[slug] => bw
[term_group] => 0
[term_taxonomy_id] => 12
[taxonomy] => copy_device
[description] =>
[parent] => 9
[count] => 1
[filter] => raw
)

[1] => WP_Term Object
(
[term_id] => 11
[name] => Colour
[slug] => colour
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => copy_device
[description] =>
[parent] => 9
[count] => 1
[filter] => raw
)

[2] => WP_Term Object
(
[term_id] => 9
[name] => New
[slug] => new
[term_group] => 0
[term_taxonomy_id] => 9
[taxonomy] => copy_device
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)

[3] => WP_Term Object
(
[term_id] => 10
[name] => Used
[slug] => used
[term_group] => 0
[term_taxonomy_id] => 10
[taxonomy] => copy_device
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
)

I have spend so many days trying to make this work. I was reading codex, forums, web sites and was experimentig with diffrent approach, but I failed... Is there any hardcore member who can help me out to make this work?

Use this code:

$args = array( 'post_type' => 'devices');

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$terms = get_the_terms(  get_the_id(), 'taxonomy');
foreach ( $terms as $term ) {
    $termID[] = $term->term_id;
}
echo $termID[0]; `
endwhile;


`

What is $categories? The foreach error is probably from this. I don't think you need to call WP_Query inside the loop. Remove the foreach loop of ( $categories as $categorie ) and WP_Query will return devices with new and color terms. Also, there is no 'hide_empty' parameter in tax query, you can remove it, too.

I`m sorry I get $categories like this:

<?php
            // get all devices
            $categories = get_terms(
              array(
                'taxonomy'    => esc_html__('copy_device'),
                'hide_empty'  => true,
              )
            );?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM