<?php
/*
 * Plugin Name:       Filtered Gallery 
 * Plugin URI:        https://e...content-available-to-author-only...e.com/plugins/the-basics/
 * Description:       Filter your gallery with categories
 * Version:           1.0.0
 * Author:            Muhib
 * Author URI:        https://h...content-available-to-author-only...h.in/

 */

 if (!defined('ABSPATH')) {
    exit;
}

// Register Custom Post Type for Photos
function cpg_register_photo_post_type() {
    register_post_type('cpg_photo', array(
        'labels' => array(
            'name' => __('Photos'),
            'singular_name' => __('Photo'),
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'thumbnail'),
        'taxonomies' => array('category'), // Add default categories
    ));
}
add_action('init', 'cpg_register_photo_post_type');

// Shortcode to display the gallery
function cpg_photo_gallery_shortcode($atts) {
    ob_start();

    // Get categories
    $categories = get_categories(array(
        'taxonomy' => 'category',
    ));

    // Filtering form
    echo '<form method="GET" class="cpg-filter-form">';
    echo '<select name="cpg_category_filter">';
    echo '<option value="">' . __('Select a category', 'text-domain') . '</option>';
    foreach ($categories as $category) {
        echo '<option value="' . esc_attr($category->term_id) . '">' . esc_html($category->name) . '</option>';
    }
    echo '</select>';
    echo '<input type="submit" value="' . __('Filter', 'text-domain') . '">';
    echo '</form>';

    // Fetch photos based on selected category
    $args = array(
        'post_type' => 'cpg_photo',
        'posts_per_page' => -1,
    );

    if (!empty($_GET['cpg_category_filter'])) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => intval($_GET['cpg_category_filter']),
            ),
        );
    }

    $photos = new WP_Query($args);

    if ($photos->have_posts()) {
        echo '<div class="cpg-photo-gallery">';
        while ($photos->have_posts()) {
            $photos->the_post();
            echo '<div class="cpg-photo-item">';
            echo '<h3>' . get_the_title() . '</h3>';
            echo get_the_post_thumbnail(get_the_ID(), 'medium');
            echo '</div>';
        }
        echo '</div>';
        wp_reset_postdata();
    } else {
        echo '<p>' . __('No photos found', 'text-domain') . '</p>';
    }

    return ob_get_clean();
}
add_shortcode('cpg_photo_gallery', 'cpg_photo_gallery_shortcode');

function cpg_enqueue_styles() {
    wp_enqueue_style('cpg-style', plugin_dir_url(__FILE__) . 'style.css');
}
add_action('wp_enqueue_scripts', 'cpg_enqueue_styles');