Custom Post Type and Taxonomy

User
function avada_owlimage_post_type() {
$args = array(
'label' => __('Owl Slider Images', 'avada'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'supports' => array('title', 'thumbnail'), // Only title & featured image
'menu_icon' => 'dashicons-format-image',
);

register_post_type('owl_slider_image', $args);
}
add_action('init', 'avada_owlimage_post_type');
also add taxonmy image category

Assistant
Here's how you can add a custom taxonomy called "Image Category" for your `owl_slider_image` post type:

### Updated Code:
“`php
function avada_owlimage_post_type() {
$args = array(
'label' => __('Owl Slider Images', 'avada'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'supports' => array('title', 'thumbnail'), // Only title & featured image
'menu_icon' => 'dashicons-format-image',
);

register_post_type('owl_slider_image', $args);
}
add_action('init', 'avada_owlimage_post_type');

function avada_register_image_category_taxonomy() {
$args = array(
'label' => __('Image Categories', 'avada'),
'public' => true,
'hierarchical' => true, // Works like categories (true) or tags (false)
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'image-category'),
);

User
<script>
jQuery(document).ready(function($) {
            var owl2 = jQuery(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false, // Enable navigation arrows
                dots: false, // Disable dots
                stagePadding: 0,
                responsive: {
                    0: {
                        items: 1.1,
                        margin: 8
                    },
                    768: {
                        items: 1.1,
                        margin: 8
                    },
                    1024: {
                        items: 3.5
                    }
                }
            });
        });
</script>
Assistant
You can add an option to filter carousel images by taxonomy (Image Category) in the Fusion Builder element. Here's how you can modify the code:

### βœ… **Updated Code with Taxonomy Option:**

<?php
if (!class_exists('Fusion_Custom_Owl_Carousel')) {
    class Fusion_Custom_Owl_Carousel
    {
        public function __construct()
        {
            // Hook into Avada to register the element
            add_action('fusion_builder_before_init', array($this, 'register_carousel_element'));
        }

        public function register_carousel_element()
        {
            if (class_exists('FusionBuilder')) {
                // Get taxonomy terms
                $categories = get_terms(array(
                    'taxonomy'   => 'image_category',
                    'hide_empty' => false,
                ));

                $category_options = array('' => esc_attr__('All Categories', 'Avada'));
                if (!empty($categories) && !is_wp_error($categories)) {
                    foreach ($categories as $category) {
                        $category_options[$category->slug] = $category->name;
                    }
                }

                // Register the new custom carousel element with Fusion Builder
                fusion_builder_map(array(
                    'name'        => 'Custom Owl Carousel',
                    'shortcode'   => 'custom_owl_carousel',
                    'icon'        => 'fusiona fa-sliders', // Font Awesome icon for the element
                    'category'    => 'Avada Custom Elements',
                    'params'      => [
                        [
                            'type'        => 'textfield',
                            'heading'     => esc_attr__('Number of Posts', 'Avada'),
                            'param_name'  => 'posts_per_page',
                            'value'       => '5',
                        ],
                        [
                            'type'        => 'select',
                            'heading'     => esc_attr__('Select Image Category', 'Avada'),
                            'param_name'  => 'image_category',
                            'value'       => $category_options,
                            'description' => esc_attr__('Filter images by category.', 'Avada'),
                        ],
                    ],
                ));
            }
        }
    }

    new Fusion_Custom_Owl_Carousel();
}

function bubori_custom_owl_carousel_shortcode($atts, $content = null)
{
    // Define default attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 5,
        'image_category' => '', // Default to all categories
    ), $atts, 'custom_owl_carousel');

    $args = [
        'post_type'      => 'owl_slider_image',
        'post_status'    => 'publish',
        'posts_per_page' => intval($atts['posts_per_page']),
    ];

    if (!empty($atts['image_category'])) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'image_category',
                'field'    => 'slug',
                'terms'    => $atts['image_category'],
            ]
        ];
    }

    $query = new WP_Query($args);
    ob_start();
?>
    <div class="owl-carousel owl-carousel-custom">
        <?php if ($query->have_posts()) : ?>
            <?php while ($query->have_posts()) :
                $query->the_post();

                if (has_post_thumbnail()):
                    $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
            ?>
                    <div class="carousel-item">
                        <img src="<?php echo esc_url($thumbnail_url); ?>" alt="Carousel Image">
                    </div>
            <?php endif;
            endwhile; ?>
        <?php endif; ?>
    </div>
    <script>
        jQuery(document).ready(function($) {
            var owl2 = $(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false,
                dots: false,
                stagePadding: 0,
                responsive: {
                    0: { items: 1.1, margin: 8 },
                    768: { items: 1.1, margin: 8 },
                    1024: { items: 3.5 }
                }
            });
        });
    </script>
<?php
    wp_reset_postdata();
    return ob_get_clean();
}

add_shortcode('custom_owl_carousel', 'bubori_custom_owl_carousel_shortcode');

### πŸ”Ή **What’s New?**
1. **Added a Dropdown to Select Taxonomy (Image Category)**
– The element now includes an option to filter images based on the `image_category` taxonomy.

2. **Dynamically Fetches Available Categories**
– The dropdown is automatically populated with all available categories from the `image_category` taxonomy.

3. **Filters Posts Based on Selected Category**
– The shortcode query is modified to include a `tax_query`, allowing filtering of images by category.

Now, when you add the **Custom Owl Carousel** element in Fusion Builder, you can choose an image category, and the slider will only display images from that category. πŸš€

User
<script>
jQuery(document).ready(function($) {
            var owl2 = jQuery(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false, // Enable navigation arrows
                dots: false, // Disable dots
                stagePadding: 0,
                responsive: {
                    0: {
                        items: 1.1,
                        margin: 8
                    },
                    768: {
                        items: 1.1,
                        margin: 8
                    },
                    1024: {
                        items: 3.5
                    }
                }
            });
        });
</script>
Assistant
It looks like you have added a taxonomy selection feature to your custom Owl Carousel element in Avada Fusion Builder. However, you might be facing an issue with filtering posts by the selected taxonomy.

### Possible Issues and Fixes:

#### 1. **Taxonomy Name Mismatch**
In `register_carousel_element()`, you are fetching terms from `owlimgcat`:

$categories = get_terms(array(
    'taxonomy'   => 'owlimgcat',
    'hide_empty' => false,
));

However, in the WP_Query `tax_query`, you are using `owl_img_category`:

$args['tax_query'] = [
    [
        'taxonomy' => 'owl_img_category',
        'field'    => 'slug',
        'terms'    => $atts['image_category'],
    ]
];

πŸ‘‰ **Fix:** Ensure that the taxonomy slug used in both places is the same. If your taxonomy is `owlimgcat`, update the `tax_query` accordingly:

$args['tax_query'] = [
    [
        'taxonomy' => 'owlimgcat', // Make sure this matches the registered taxonomy
        'field'    => 'slug',
        'terms'    => $atts['image_category'],
    ]
];

#### 2. **Check if Taxonomy Exists**
Ensure that the custom taxonomy (`owlimgcat` or `owl_img_category`) is correctly registered for `owl_slider_image`. You can check this by running:

global $wp_taxonomies;
var_dump($wp_taxonomies['owlimgcat']);

If it’s not registered, ensure it is correctly added using:

register_taxonomy('owlimgcat', 'owl_slider_image', array(
    'label' => __('Image Categories', 'Avada'),
    'rewrite' => array('slug' => 'owlimgcat'),
    'hierarchical' => true,
));

#### 3. **Check if Taxonomy Has Terms**
If you are not seeing any posts filtered by taxonomy, try testing your query with this before running `WP_Query`:

var_dump($args);

This will print the final query arguments, helping debug whether the taxonomy filter is being applied.

#### 4. **Check Shortcode Attributes**
In the `shortcode_atts` array, you are not setting a default value for `image_category`:

$atts = shortcode_atts(array(
    'posts_per_page' => 5,
), $atts, 'custom_owl_carousel');

πŸ‘‰ **Fix:** Add `image_category` to avoid undefined index issues:

$atts = shortcode_atts(array(
    'posts_per_page' => 5,
    'image_category' => '', // Default to empty (all categories)
), $atts, 'custom_owl_carousel');

### Final Debugging Steps:
1. Print `$args` before `WP_Query` to ensure the taxonomy filter is being applied.
2. Verify that the taxonomy name matches in `get_terms()` and `tax_query`.
3. Ensure that posts actually exist in the specified taxonomy.

Try these fixes and let me know if you still face issues! πŸš€

User
still drodown not shows taxonomy values for selection
Assistant
If the taxonomy dropdown in Avada Fusion Builder is not showing values, let's go step by step to debug and fix it.

### πŸ” **Possible Causes & Fixes**
#### 1️⃣ **Check if Taxonomy Exists**
Run this snippet inside `functions.php` or any template to check if the taxonomy `owlimgcat` exists and has terms:

$categories = get_terms(array(
    'taxonomy'   => 'owlimgcat',
    'hide_empty' => false,
));

if (!empty($categories) && !is_wp_error($categories)) {
    foreach ($categories as $category) {
        echo 'Slug: ' . esc_html($category->slug) . ' - Name: ' . esc_html($category->name) . '<br>';
    }
} else {
    echo 'No categories found or taxonomy does not exist.';
}

πŸ‘‰ **If this prints categories, then the issue is in Avada integration.**
πŸ‘‰ **If it prints "No categories found," then your taxonomy might not be properly registered.**

#### 2️⃣ **Ensure the Taxonomy is Registered**
Make sure your custom taxonomy is registered correctly in your theme/plugin:

function register_custom_owl_taxonomy() {
    register_taxonomy(
        'owlimgcat',  // Must match what you're using in `get_terms()`
        'owl_slider_image', // Must match your post type
        array(
            'label'        => __('Image Categories', 'Avada'),
            'rewrite'      => array('slug' => 'owlimgcat'),
            'hierarchical' => true,
            'show_admin_column' => true,
        )
    );
}
add_action('init', 'register_custom_owl_taxonomy');

#### 3️⃣ **Check if Terms are Actually Added**
Navigate to **WordPress Dashboard β†’ Owl Slider Image β†’ Image Categories** and add some terms manually.
If there are no categories, the dropdown will be empty.

#### 4️⃣ **Debug the `$category_options` Array**
Inside `register_carousel_element()`, add:

error_log(print_r($category_options, true));

Then check your PHP error log (typically in `/wp-content/debug.log`) to see if the `$category_options` array contains terms.

#### 5️⃣ **Modify `register_carousel_element()`**
Your taxonomy slug is `owlimgcat`, but in `WP_Query`, you used `owl_img_category`. **Make sure they match.**
Replace your current `$categories` query with:

$categories = get_terms(array(
    'taxonomy'   => 'owlimgcat', // Ensure it matches the registered taxonomy
    'hide_empty' => false,
));

$category_options = array('' => esc_attr__('All Categories', 'Avada'));

if (!empty($categories) && !is_wp_error($categories)) {
    foreach ($categories as $category) {
        $category_options[$category->slug] = $category->name;
    }
}

This should populate the dropdown.

### βœ… **Final Steps**
1. **Check if taxonomy exists** using step **1️⃣**.
2. **Ensure taxonomy is registered** using step **2️⃣**.
3. **Manually add terms** in step **3️⃣**.
4. **Debug the dropdown options** using step **4️⃣**.
5. **Ensure taxonomy slug matches in all places** using step **5️⃣**.

After trying these steps, let me know what you find! πŸš€

User
okay get option to select pages as meta field
Assistant
To add an option to select **pages** as a meta field in your **Fusion Builder Custom Owl Carousel**, follow these steps:

### βœ… **Modify `register_carousel_element()`**
Add a `select` dropdown for selecting a page:

public function register_carousel_element()
{
    if (class_exists('FusionBuilder')) {
        // Get all WordPress pages
        $pages = get_pages();
        $page_options = array('' => esc_attr__('Select a Page', 'Avada'));
        if (!empty($pages)) {
            foreach ($pages as $page) {
                $page_options[$page->ID] = $page->post_title;
            }
        }

        fusion_builder_map(array(
            'name'        => 'Custom Owl Carousel',
            'shortcode'   => 'custom_owl_carousel',
            'icon'        => 'fusiona fa-sliders',
            'category'    => 'Avada Custom Elements',
            'params'      => [
                [
                    'type'    => 'textfield',
                    'heading' => esc_attr__('Number of Posts', 'Avada'),
                    'param_name' => 'posts_per_page',
                    'value' => '5',
                ],
                [
                    'type'        => 'select',
                    'heading'     => esc_attr__('Select a Page', 'Avada'),
                    'param_name'  => 'selected_page',
                    'value'       => $page_options,
                    'description' => esc_attr__('Choose a page to link from the carousel.', 'Avada'),
                ],
            ],
        ));
    }
}

### βœ… **Modify the Shortcode to Use the Selected Page**
Modify `bubori_custom_owl_carousel_shortcode()` to get the selected page and use it in the carousel:

function bubori_custom_owl_carousel_shortcode($atts, $content = null)
{
    // Define default attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 5,
        'selected_page'  => '', // Add selected_page parameter
    ), $atts, 'custom_owl_carousel');

    $args = [
        'post_type'      => 'owl_slider_image',
        'post_status'    => 'publish',
        'posts_per_page' => isset($atts['posts_per_page']) ? intval($atts['posts_per_page']) : 5,
    ];

    $query = new WP_Query($args);
    ob_start();
?>
    <div class="owl-carousel owl-carousel-custom">
        <?php if ($query->have_posts()) : ?>
            <?php while ($query->have_posts()) :
                $query->the_post();

                if (has_post_thumbnail()):
                    $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
                    $page_link = !empty($atts['selected_page']) ? get_permalink($atts['selected_page']) : '#';
            ?>
                    <div class="carousel-item">
                        <a href="<?php echo esc_url($page_link); ?>" target="_blank">
                            <img src="<?php echo esc_url($thumbnail_url); ?>" alt="Carousel Image">
                        </a>
                    </div>
            <?php endif;
            endwhile; ?>
        <?php endif; ?>
    </div>
<?php
    return ob_get_clean();
}
add_shortcode('custom_owl_carousel', 'bubori_custom_owl_carousel_shortcode');

### πŸ”₯ **How It Works**
1. Adds a **Page Selection Dropdown** in Fusion Builder.
2. Retrieves all published pages and shows them in the dropdown.
3. Adds the selected page's **permalink as a link** to each carousel image.

### 🎯 **Test This:**
1. Edit your page in **Fusion Builder**.
2. Add the **Custom Owl Carousel** element.
3. Choose a page from the **"Select a Page"** dropdown.
4. Save and check if images now link to the selected page.

πŸš€ Let me know if you need more improvements! 🎯

User
also same page option selection in custom post type meta
Assistant
To add a **Page Selection Meta Field** in a **Custom Post Type**, follow these steps:

## βœ… **1. Add a Meta Box to Your Custom Post Type**
Modify the `functions.php` file or a plugin file:

function add_page_selection_meta_box() {
    add_meta_box(
        'selected_page_meta_box',
        __('Select a Page', 'Avada'),
        'render_page_selection_meta_box',
        'owl_slider_image', // Your custom post type slug
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'add_page_selection_meta_box');

function render_page_selection_meta_box($post) {
    // Get saved value
    $selected_page = get_post_meta($post->ID, '_selected_page', true);

    // Get all published pages
    $pages = get_pages();
    ?>
    <label for="selected_page"><?php esc_html_e('Choose a Page:', 'Avada'); ?></label>
    <select name="selected_page" id="selected_page">
        <option value=""><?php esc_html_e('Select a Page', 'Avada'); ?></option>
        <?php foreach ($pages as $page) : ?>
            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($selected_page, $page->ID); ?>>
                <?php echo esc_html($page->post_title); ?>
            </option>
        <?php endforeach; ?>
    </select>
    <?php
}

function save_selected_page_meta($post_id) {
    if (isset($_POST['selected_page'])) {
        update_post_meta($post_id, '_selected_page', sanitize_text_field($_POST['selected_page']));
    }
}
add_action('save_post', 'save_selected_page_meta');

## βœ… **2. Modify Shortcode to Use Selected Page in Carousel**
Update your shortcode function:

function bubori_custom_owl_carousel_shortcode($atts, $content = null)
{
    // Define default attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 5,
    ), $atts, 'custom_owl_carousel');

    $args = [
        'post_type'      => 'owl_slider_image',
        'post_status'    => 'publish',
        'posts_per_page' => intval($atts['posts_per_page']),
    ];

    $query = new WP_Query($args);
    ob_start();
?>
    <div class="owl-carousel owl-carousel-custom">
        <?php if ($query->have_posts()) : ?>
            <?php while ($query->have_posts()) :
                $query->the_post();

                if (has_post_thumbnail()):
                    $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
                    $page_id = get_post_meta(get_the_ID(), '_selected_page', true);
                    $page_link = !empty($page_id) ? get_permalink($page_id) : '#';
            ?>
                    <div class="carousel-item">
                        <a href="<?php echo esc_url($page_link); ?>" target="_blank">
                            <img src="<?php echo esc_url($thumbnail_url); ?>" alt="Carousel Image">
                        </a>
                    </div>
            <?php endif;
            endwhile; ?>
        <?php endif; ?>
    </div>
<?php
    return ob_get_clean();
}
add_shortcode('custom_owl_carousel', 'bubori_custom_owl_carousel_shortcode');

## 🎯 **How It Works**
1. βœ… Adds a **meta box** in the "owl_slider_image" custom post type.
2. βœ… Allows users to **select a page** from a dropdown.
3. βœ… Saves the **selected page ID** in post meta.
4. βœ… Updates the **carousel to link each image** to the selected page.

### πŸ›  **How to Test**
1. **Go to your Custom Post Type** (`owl_slider_image`).
2. **Edit a Post** β†’ Select a page from the dropdown β†’ Save.
3. **Insert the shortcode** `[custom_owl_carousel]` into a page.
4. Check if clicking the carousel image **redirects to the selected page**.

πŸš€ **Let me know if you need modifications!** 🎯

User
apply save on check if custom post type
Assistant
To ensure the **selected page meta field** is only saved for the **custom post type** (`owl_slider_image`), update the `save_selected_page_meta()` function like this:

### βœ… **Updated Save Function with Custom Post Type Check**

function save_selected_page_meta($post_id) {
    // Verify it's not an autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // Verify user permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // Verify nonce if added (optional security)
    if (isset($_POST['post_type']) && $_POST['post_type'] === 'owl_slider_image') {
        if (isset($_POST['selected_page'])) {
            update_post_meta($post_id, '_selected_page', sanitize_text_field($_POST['selected_page']));
        } else {
            delete_post_meta($post_id, '_selected_page'); // Remove if empty
        }
    }
}
add_action('save_post', 'save_selected_page_meta');

### πŸ”Ή **How It Works**
1. **Checks if the request is an autosave** and prevents saving.
2. **Ensures the user has permission** to edit the post.
3. **Validates that the post type is `owl_slider_image`** before saving the meta field.
4. **Deletes the meta field if the selection is empty**, keeping the database clean.

### πŸš€ **Next Steps**
– **Try editing a post** in `owl_slider_image`, selecting a page, and saving it.
– **Confirm that the meta field saves only for the custom post type.**
– **Check the carousel** to ensure the selected page links work correctly.

Let me know if you need further tweaks! 🎯

User
<script>
jQuery(document).ready(function($) {
            var owl2 = jQuery(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false, // Enable navigation arrows
                dots: false, // Disable dots
                stagePadding: 0,
                responsive: {
                    0: {
                        items: 1.1,
                        margin: 8
                    },
                    768: {
                        items: 1.1,
                        margin: 8
                    },
                    1024: {
                        items: 3.5
                    }
                }
            });
        });
</script>
Assistant
To apply the **selected page** option from the Fusion Builder element to the **carousel items in the shortcode**, update your `bubori_custom_owl_carousel_shortcode()` function like this:

### βœ… **Updated Shortcode with Page Link Meta**

function bubori_custom_owl_carousel_shortcode($atts, $content = null)
{
    // Define default attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 5,
        'selected_page' => '', // Store selected page ID
    ), $atts, 'custom_owl_carousel');

    $args = [
        'post_type'      => 'owl_slider_image',
        'post_status'    => 'publish',
        'posts_per_page' => isset($atts['posts_per_page']) ? intval($atts['posts_per_page']) : 5,
    ];

    if (!empty($atts['image_category'])) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'owl_img_category',
                'field'    => 'slug',
                'terms'    => $atts['image_category'],
            ]
        ];
    }

    $query = new WP_Query($args);
    ob_start();
?>
    <div class="owl-carousel owl-carousel-custom">
        <?php if ($query->have_posts()) : ?>
            <?php while ($query->have_posts()) : 
                $query->the_post();

                // Get the post thumbnail
                if (has_post_thumbnail()):
                    $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
                
                    // Get the selected page URL from meta
                    $selected_page_id = get_post_meta(get_the_ID(), '_selected_page', true);
                    $page_url = !empty($selected_page_id) ? get_permalink($selected_page_id) : '#';
            ?>
                    <div class="carousel-item">
                        <a href="<?php echo esc_url($page_url); ?>" target="_blank">
                            <img src="<?php echo esc_url($thumbnail_url); ?>" alt="Carousel Image">
                        </a>
                    </div>
            <?php endif;
            endwhile; ?>
        <?php endif; ?>
    </div>

    <script>
        jQuery(document).ready(function($) {
            var owl2 = jQuery(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false, // Enable navigation arrows
                dots: false, // Disable dots
                stagePadding: 0,
                responsive: {
                    0: { items: 1.1, margin: 8 },
                    768: { items: 1.1, margin: 8 },
                    1024: { items: 3.5 }
                }
            });
        });
    </script>
<?php
    return ob_get_clean();
}

add_shortcode('custom_owl_carousel', 'bubori_custom_owl_carousel_shortcode');

### πŸ”Ή **What This Update Does**
1. **Retrieves the `_selected_page` meta value** for each carousel item.
2. **Generates the correct URL for the linked page** using `get_permalink($selected_page_id)`.
3. **Wraps the image inside an “ tag** so clicking the image redirects to the selected page.
4. **Ensures a fallback (`#`)** if no page is selected.

### πŸš€ **Next Steps**
– **Add some test data:** Go to an `owl_slider_image` post, select a page, and save.
– **Check the carousel output:** Images should now link to their assigned pages.

Let me know if you need further improvements! 🎯

User
_selected_page is meta field apply this on meta query if this exist
Assistant
To apply the `_selected_page` meta field in the **WP_Query meta query**, update the shortcode to check if `_selected_page` exists and filter the query accordingly.

### βœ… **Updated Shortcode with Meta Query for `_selected_page`**

function bubori_custom_owl_carousel_shortcode($atts, $content = null)
{
    // Define default attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 5,
        'selected_page'  => '', // Store selected page ID
    ), $atts, 'custom_owl_carousel');

    $args = [
        'post_type'      => 'owl_slider_image',
        'post_status'    => 'publish',
        'posts_per_page' => isset($atts['posts_per_page']) ? intval($atts['posts_per_page']) : 5,
    ];

    // Apply meta query if selected_page exists
    if (!empty($atts['selected_page'])) {
        $args['meta_query'] = [
            [
                'key'     => '_selected_page',
                'value'   => intval($atts['selected_page']),
                'compare' => '=',
            ]
        ];
    }

    $query = new WP_Query($args);
    ob_start();
?>
    <div class="owl-carousel owl-carousel-custom">
        <?php if ($query->have_posts()) : ?>
            <?php while ($query->have_posts()) : 
                $query->the_post();

                // Get the post thumbnail
                if (has_post_thumbnail()):
                    $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
                
                    // Get the selected page URL from meta
                    $selected_page_id = get_post_meta(get_the_ID(), '_selected_page', true);
                    $page_url = !empty($selected_page_id) ? get_permalink($selected_page_id) : '#';
            ?>
                    <div class="carousel-item">
                        <a href="<?php echo esc_url($page_url); ?>" target="_blank">
                            <img src="<?php echo esc_url($thumbnail_url); ?>" alt="Carousel Image">
                        </a>
                    </div>
            <?php endif;
            endwhile; ?>
        <?php endif; ?>
    </div>

    <script>
        jQuery(document).ready(function($) {
            var owl2 = jQuery(".owl-carousel-custom");
            owl2.owlCarousel({
                items: 3.5,
                margin: 16,
                autoplay: true,
                smartSpeed: 800,
                autoplayHoverPause: true,
                loop: true,
                nav: false, // Enable navigation arrows
                dots: false, // Disable dots
                stagePadding: 0,
                responsive: {
                    0: { items: 1.1, margin: 8 },
                    768: { items: 1.1, margin: 8 },
                    1024: { items: 3.5 }
                }
            });
        });
    </script>
<?php
    return ob_get_clean();
}

add_shortcode('custom_owl_carousel', 'bubori_custom_owl_carousel_shortcode');

### πŸ”Ή **What This Update Does**
1. **Filters the query using `_selected_page`**
– If the `selected_page` is set in the Fusion Builder element, only **carousel posts that match the meta value** will be retrieved.

2. **Ensures only relevant posts are fetched**
– If no `_selected_page` is stored for a post, it won’t be included in the carousel.

3. **Improved linking to selected pages**
– Carousel images will now correctly link to their respective pages.

### πŸš€ **Next Steps**
– **Test it by assigning `_selected_page` values** to `owl_slider_image` posts.
– **Verify that only posts with the matching `_selected_page` are displayed.**

Let me know if you need further refinements! πŸš€πŸŽ―

Leave a Comment

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