fork download
  1. <?php
  2. /*
  3.  * Plugin Name: Filtered Gallery
  4.  * Plugin URI: https://e...content-available-to-author-only...e.com/plugins/the-basics/
  5.  * Description: Filter your gallery with categories
  6.  * Version: 1.0.0
  7.  * Author: Muhib
  8.  * Author URI: https://h...content-available-to-author-only...h.in/
  9.  
  10.  */
  11.  
  12. if (!defined('ABSPATH')) {
  13. }
  14.  
  15. // Register Custom Post Type for Photos
  16. function cpg_register_photo_post_type() {
  17. register_post_type('cpg_photo', array(
  18. 'labels' => array(
  19. 'name' => __('Photos'),
  20. 'singular_name' => __('Photo'),
  21. ),
  22. 'public' => true,
  23. 'has_archive' => true,
  24. 'supports' => array('title', 'thumbnail'),
  25. 'taxonomies' => array('category'), // Add default categories
  26. ));
  27. }
  28. add_action('init', 'cpg_register_photo_post_type');
  29.  
  30. // Shortcode to display the gallery
  31. function cpg_photo_gallery_shortcode($atts) {
  32.  
  33. // Get categories
  34. $categories = get_categories(array(
  35. 'taxonomy' => 'category',
  36. ));
  37.  
  38. // Filtering form
  39. echo '<form method="GET" class="cpg-filter-form">';
  40. echo '<select name="cpg_category_filter">';
  41. echo '<option value="">' . __('Select a category', 'text-domain') . '</option>';
  42. foreach ($categories as $category) {
  43. echo '<option value="' . esc_attr($category->term_id) . '">' . esc_html($category->name) . '</option>';
  44. }
  45. echo '</select>';
  46. echo '<input type="submit" value="' . __('Filter', 'text-domain') . '">';
  47. echo '</form>';
  48.  
  49. // Fetch photos based on selected category
  50. $args = array(
  51. 'post_type' => 'cpg_photo',
  52. 'posts_per_page' => -1,
  53. );
  54.  
  55. if (!empty($_GET['cpg_category_filter'])) {
  56. $args['tax_query'] = array(
  57. 'taxonomy' => 'category',
  58. 'field' => 'term_id',
  59. 'terms' => intval($_GET['cpg_category_filter']),
  60. ),
  61. );
  62. }
  63.  
  64. $photos = new WP_Query($args);
  65.  
  66. if ($photos->have_posts()) {
  67. echo '<div class="cpg-photo-gallery">';
  68. while ($photos->have_posts()) {
  69. $photos->the_post();
  70. echo '<div class="cpg-photo-item">';
  71. echo '<h3>' . get_the_title() . '</h3>';
  72. echo get_the_post_thumbnail(get_the_ID(), 'medium');
  73. echo '</div>';
  74. }
  75. echo '</div>';
  76. wp_reset_postdata();
  77. } else {
  78. echo '<p>' . __('No photos found', 'text-domain') . '</p>';
  79. }
  80.  
  81. return ob_get_clean();
  82. }
  83. add_shortcode('cpg_photo_gallery', 'cpg_photo_gallery_shortcode');
  84.  
  85. function cpg_enqueue_styles() {
  86. wp_enqueue_style('cpg-style', plugin_dir_url(__FILE__) . 'style.css');
  87. }
  88. add_action('wp_enqueue_scripts', 'cpg_enqueue_styles');
Success #stdin #stdout 0.02s 26112KB
stdin
Standard input is empty
stdout
Standard output is empty