Template for custom post archive. WordPress example open

Template for custom post archive. WordPress example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

After creating a new custom post type, the archive template for them will be a file archive.php in yours theme directory.

If you want this page to be different, create a file in the theme folder and name it post_type_name-archive.php

post_type_name – your custom post type name. Example: cars-archive.php

Example code in the file cars-archive.php:

<?php
get_header(); // Display the site header
?>

<div class="wrapper archive_cars">
    <?php 
	
		$args = array(
			'post_type' => 'cars',
			'post_status' => 'publish',
			'posts_per_page' => 4,
			'orderby' => 'rand',
			'order' => 'ASC',
		);
	
        $cars = new WP_Query($args); // Create a query to retrieve a list of cars

        if ( $cars->have_posts() ) { // Check if there are posts in the query

            while ( $cars->have_posts() ) {
                $properties->the_post(); // Move to the next post
                
                get_template_part('partials/content'); // Include content from the content.php file

            }
        } else {
            echo '<p>'.esc_html__('No Entries','myplugin').'</p>'; // Display a message for no entries
        }

        // Display pagination
        posts_nav_link();
    ?>
</div>

<?php
get_footer(); // Display the site footer
?>

Create an additional file content.php and place it in a folder partials. Should be yourthemename/partials/content.php:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <?php if (get_the_post_thumbnail(get_the_ID(), 'large')) {
        echo get_the_post_thumbnail(get_the_ID(), 'large'); // Display the car's image
    } ?>

    <h2><?php the_title(); ?></h2> <!-- Display the car's title -->
    <div class="description"><?php the_excerpt(); ?></div> <!-- Display the car's excerpt -->
    <div class="post_info">
        <span class="meta-field"><?php esc_html_e('Price:', 'mytheme');
        echo ' ' . esc_html(get_post_meta(get_the_ID(), 'price', true)); ?> </span> <!-- Display the car's price -->
    </div>
    <a href="<?php the_permalink(); ?>">Open </a><br> <!-- Display a link to open the full car details -->
</article>
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation