PHP code example of timohubois / post-type-and-taxonomy-archive-pages

1. Go to this page and download the library: Download timohubois/post-type-and-taxonomy-archive-pages library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

timohubois / post-type-and-taxonomy-archive-pages example snippets


/**
 * Retrieves the post object for a given post type's archive page.
 *
 * @param string|null $postType The post type to retrieve the archive page for.
 * @return WP_Post|null WP_Post on success, or null on failure.
 */
function getCustomPostTypeArchivePage(?string $postType = null): ?\WP_Post
{
    $postType = $postType ?? getCurrentQueryPostType();

    if ($postType === null) {
        return null;
    }

    $postTypeObject = get_post_type_object($postType);

    if (!$postTypeObject || !$postTypeObject->has_archive) {
        return null;
    }

    $archiveSlug = $postTypeObject->has_archive;

    if (!is_string($archiveSlug)) {
        return null;
    }

    $archivePage = get_page_by_path($archiveSlug);

    return ($archivePage instanceof \WP_Post) ? $archivePage : null;
}

/**
 * Retrieves the current post type from the global $wp_query object.
 *
 * @return string|null The current post type, or null if not found.
 */
function getCurrentQueryPostType(): ?string
{
    global $wp_query;
    return $wp_query->query['post_type'] ?? null;
}

$archivePage = getCustomPostTypeArchivePage('your_custom_post_type');
if ($archivePage) {
    echo "Archive page title: " . $archivePage->post_title;
    echo "Archive page ID: " . $archivePage->ID;
    echo "Archive page URL: " . get_permalink($archivePage->ID);
} else {
    echo "No archive page found for this post type.";
}