Select Page URL Control

User
$repeater->add_control(
'pageurl',
[
'label' => __( 'Url', 'solaron' ),
'type' => ElementorControls_Manager::URL,
]
);
add option to select url from page list
Assistant
To add an option in Elementor to select a URL from a list of pages, you can create a custom control that retrieves the list of pages and presents them as selectable options. Here's how you can achieve this:

1. **Add a New Control**: In your Elementor widget or section, you need to create a new control for selecting pages. You'll use the `select` control type and fetch the list of pages dynamically.

2. **Modify Your Control Code**: Update your existing control definition as follows:

$repeater->add_control(
    'pageurl',
    [
        'label'   => __( 'Select Page', 'solaron' ),
        'type'    => ElementorControls_Manager::SELECT,
        'options' => $this->get_page_options(), // Call the method to get page options
    ]
);

3. **Create the Method to Retrieve Pages**: Add a method to get the list of pages. This method will retrieve all published pages and return them as an associative array.

private function get_page_options() {
    $pages = get_posts([
        'post_type'   => 'page',
        'numberposts' => -1,
        'post_status' => 'publish',
    ]);

    $options = [];
    foreach ($pages as $page) {
        $options[$page->ID] = $page->post_title; // Use the page ID as the key and title as the value
    }

    return $options;
}

4. **Add a URL Field for the Selected Page**: If you want to allow users to specify a custom URL as well, you can add an additional URL control. Here's how you can do that:

$repeater->add_control(
    'custom_url',
    [
        'label'   => __( 'Custom URL', 'solaron' ),
        'type'    => ElementorControls_Manager::URL,
        'placeholder' => __( 'https://your-link.com', 'solaron' ),
    ]
);

5. **Usage**: In your widget's render function, you can retrieve the selected page ID and generate the URL accordingly:

$settings = $repeater->get_settings_for_display();
$page_id = $settings['pageurl']; // Get the selected page ID
$page_url = get_permalink($page_id); // Get the URL of the selected page

// Use $page_url as needed in your output

With these changes, you'll have a select control in your Elementor widget that allows users to choose a page from a list, along with an option to specify a custom URL.

Leave a Comment

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