Custom Elementor Dropdown Widget
January 6, 2025 · AI Conversations
—
### 1. **Set up a custom plugin**
First, create a custom plugin to add the widget. If you don’t have one, follow these steps:
1. Create a folder in `wp-content/plugins/` named `custom-elementor-widgets`.
2. Inside the folder, create a file named `custom-elementor-widgets.php`.
Add the following code to initialize the plugin:
<?php
/**
* Plugin Name: Custom Elementor Widgets
* Description: Adds custom widgets to Elementor.
* Version: 1.0
* Author: Your Name
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
// Load custom widgets.
function custom_elementor_widgets_load() {
require_once plugin_dir_path( __FILE__ ) . 'widgets/taxonomy-widget.php';
}
add_action( 'elementor/widgets/widgets_registered', 'custom_elementor_widgets_load' );
—
### 2. **Create the widget**
Inside the plugin folder, create a `widgets` folder, and add a file `taxonomy-widget.php` with the following code:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Elementor_Taxonomy_Widget extends ElementorWidget_Base {
public function get_name() {
return 'taxonomy_widget';
}
public function get_title() {
return __( 'Taxonomy Widget', 'custom-elementor-widgets' );
}
public function get_icon() {
return 'eicon-editor-list-ul';
}
public function get_categories() {
return [ 'general' ];
}
protected function _register_controls() {
$taxonomies = get_taxonomies( [ 'public' => true ], 'objects' );
$taxonomy_options = [];
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_options[ $taxonomy->name ] = $taxonomy->label;
}
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'custom-elementor-widgets' ),
'tab' => ElementorControls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'taxonomy',
[
'label' => __( 'Select Taxonomy', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::SELECT,
'options' => $taxonomy_options,
]
);
$this->add_control(
'description',
[
'label' => __( 'Description', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::TEXTAREA,
'placeholder' => __( 'Enter description here...', 'custom-elementor-widgets' ),
]
);
$this->add_control(
'image',
[
'label' => __( 'Upload Image', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::MEDIA,
'default' => [
'url' => ElementorUtils::get_placeholder_image_src(),
],
]
);
$this->end_controls_section();
}
protected function render() {
$settings = $this->get_settings_for_display();
$taxonomy = $settings['taxonomy'];
$description = $settings['description'];
$image = $settings['image']['url'];
echo '<div class="taxonomy-widget">';
if ( $taxonomy ) {
echo '<p><strong>Selected Taxonomy:</strong> ' . esc_html( $taxonomy ) . '</p>';
}
if ( $description ) {
echo '<p><strong>Description:</strong> ' . esc_html( $description ) . '</p>';
}
if ( $image ) {
echo '<p><img src="' . esc_url( $image ) . '" alt="' . esc_attr( $description ) . '" style="max-width: 100%; height: auto;"></p>';
}
echo '</div>';
}
}
—
### 3. **Activate the plugin**
1. Go to your WordPress admin dashboard.
2. Navigate to `Plugins > Add New > Upload Plugin`.
3. Upload and activate your custom plugin.
—
### 4. **Use the widget in Elementor**
1. Open Elementor editor.
2. Search for "Taxonomy Widget" in the widget panel.
3. Drag and drop the widget to your desired location.
4. Configure the dropdown, description, and image options.
—
### Features of this Widget:
– **Dropdown:** Lists all public taxonomies in WordPress.
– **Description Field:** Allows you to add a text description.
– **Image Upload:** Lets you upload an image to display.
Let me know if you need further assistance!
—
### Updated Code for the Widget with a Repeater:
Replace the `taxonomy-widget.php` code with the following:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class Elementor_Taxonomy_Widget extends ElementorWidget_Base {
public function get_name() {
return 'taxonomy_widget_repeater';
}
public function get_title() {
return __( 'Taxonomy Widget with Repeater', 'custom-elementor-widgets' );
}
public function get_icon() {
return 'eicon-editor-list-ul';
}
public function get_categories() {
return [ 'general' ];
}
protected function _register_controls() {
$taxonomies = get_taxonomies( [ 'public' => true ], 'objects' );
$taxonomy_options = [];
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_options[ $taxonomy->name ] = $taxonomy->label;
}
// Repeater control
$repeater = new ElementorRepeater();
$repeater->add_control(
'taxonomy',
[
'label' => __( 'Select Taxonomy', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::SELECT,
'options' => $taxonomy_options,
]
);
$repeater->add_control(
'description',
[
'label' => __( 'Description', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::TEXTAREA,
'placeholder' => __( 'Enter description here...', 'custom-elementor-widgets' ),
]
);
$repeater->add_control(
'image',
[
'label' => __( 'Upload Image', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::MEDIA,
'default' => [
'url' => ElementorUtils::get_placeholder_image_src(),
],
]
);
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'custom-elementor-widgets' ),
'tab' => ElementorControls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'taxonomy_list',
[
'label' => __( 'Taxonomy Items', 'custom-elementor-widgets' ),
'type' => ElementorControls_Manager::REPEATER,
'fields' => $repeater->get_controls(),
'title_field' => '{{{ taxonomy }}} - {{{ description }}}',
]
);
$this->end_controls_section();
}
protected function render() {
$settings = $this->get_settings_for_display();
if ( ! empty( $settings['taxonomy_list'] ) ) {
echo '<div class="taxonomy-widget-repeater">';
foreach ( $settings['taxonomy_list'] as $index => $item ) {
$taxonomy = $item['taxonomy'];
$description = $item['description'];
$image = $item['image']['url'];
echo '<div class="taxonomy-item">';
if ( $taxonomy ) {
echo '<p><strong>Selected Taxonomy:</strong> ' . esc_html( $taxonomy ) . '</p>';
}
if ( $description ) {
echo '<p><strong>Description:</strong> ' . esc_html( $description ) . '</p>';
}
if ( $image ) {
echo '<p><img src="' . esc_url( $image ) . '" alt="' . esc_attr( $description ) . '" style="max-width: 100%; height: auto;"></p>';
}
echo '</div>';
}
echo '</div>';
}
}
}
—
### Explanation of the Changes:
1. **Added a Repeater Control:**
– Created an instance of `ElementorRepeater`.
– Added `taxonomy`, `description`, and `image` fields to the repeater.
2. **Dynamic Fields:**
– Used `{{{ taxonomy }}} – {{{ description }}}` as the `title_field` for better visualization in Elementor's interface.
3. **Rendering the Repeater:**
– Loop through the `taxonomy_list` setting to render each taxonomy item with its associated description and image.
4. **Styling Each Repeater Item:**
– Wrapped each item in a “ for easy styling.
—
### Output in Elementor:
1. Drag and drop the widget into your page.
2. Add multiple entries to the repeater:
– Select a taxonomy.
– Add a description.
– Upload an image.
3. Each repeater entry will display as an item in the frontend.
—
### Optional: Style the Output with CSS
You can add custom styles for better presentation:
.taxonomy-widget-repeater {
display: flex;
flex-direction: column;
gap: 20px;
}
.taxonomy-item {
border: 1px solid #ccc;
padding: 15px;
border-radius: 8px;
background-color: #f9f9f9;
}
.taxonomy-item img {
max-width: 100%;
height: auto;
border-radius: 5px;
}
Add this CSS to your theme or Elementor’s Custom CSS settings.
—
Let me know if you need further assistance! 🚀
“Leistungen” taxonmoies
Correct above sentence
"It will be a custom Elementor widget with the option to display 'Leistungen' taxonomies."
'taxonomy' => 'leistung',
'orderby' => 'name'
]);
include all even if 0 count
$terms = get_terms([
'taxonomy' => 'leistung',
'orderby' => 'name',
'hide_empty' => false, // Include terms with 0 count
]);
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
foreach ( $terms as $term ) {
echo '<p>' . esc_html( $term->name ) . '</p>';
}
} else {
echo '<p>No terms found.</p>';
}
### Explanation:
– **`'taxonomy' => 'leistung'`**: Specifies the taxonomy from which to fetch terms.
– **`'orderby' => 'name'`**: Orders terms alphabetically by their name.
– **`'hide_empty' => false`**: Ensures terms with a count of `0` (i.e., not associated with any posts) are included in the results.
– **Error Handling**: The `is_wp_error()` check ensures that no errors occurred while fetching terms.
This will retrieve and display all terms from the `leistung` taxonomy, even those not currently assigned to any post.
$terms = get_terms([
'taxonomy' => 'leistung',
'orderby' => 'name',
'hide_empty' => false, // Include terms with 0 count
]);
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
foreach ( $terms as $term ) {
echo '<p>Term Name: ' . esc_html( $term->name ) . '</p>';
echo '<p>Term ID: ' . esc_html( $term->term_id ) . '</p>';
}
} else {
echo '<p>No terms found.</p>';
}
### Key Property:
– **`$term->term_id`**: Fetches the unique ID of the term.
### Example Output:
For a taxonomy `leistung` with terms:
– Term: `Design` (ID: 12)
– Term: `Development` (ID: 15)
The output will be:
Term Name: Design
Term ID: 12
Term Name: Development
Term ID: 15
Let me know if you need further details! 😊
$term_id = 12; // Replace with your term ID
$term = get_term( $term_id, 'leistung' );
if ( ! is_wp_error( $term ) && $term ) {
echo '<p>Term Name: ' . esc_html( $term->name ) . '</p>';
echo '<p>Term Slug: ' . esc_html( $term->slug ) . '</p>';
echo '<p>Term Description: ' . esc_html( $term->description ) . '</p>';
echo '<p>Term Count: ' . esc_html( $term->count ) . '</p>';
} else {
echo '<p>Term not found.</p>';
}
### Explanation:
– **`get_term( $term_id, 'leistung' )`**: Fetches the term details from the `leistung` taxonomy using its ID.
– **Properties of `$term`:**
– **`$term->name`**: The name of the term.
– **`$term->slug`**: The slug (URL-friendly name) of the term.
– **`$term->description`**: The description of the term.
– **`$term->count`**: The number of posts associated with the term.
### Error Handling:
– **`! is_wp_error( $term )`**: Ensures the function didn't return an error.
– **`$term`**: Ensures the term exists.
Let me know if you need further clarification! 😊
$term_id = 12; // Replace with your term ID
$term_link = get_term_link( $term_id, 'leistung' );
if ( ! is_wp_error( $term_link ) ) {
echo '<p>Term URL: <a href="' . esc_url( $term_link ) . '">' . esc_html( $term_link ) . '</a></p>';
} else {
echo '<p>Unable to retrieve the term URL.</p>';
}
### Explanation:
– **`get_term_link( $term_id, 'leistung' )`**: Fetches the permalink (URL) for the term with the given ID in the `leistung` taxonomy.
– **Error Handling**: Check with `! is_wp_error( $term_link )` to ensure the URL was generated successfully.
### Example Output:
For a term with the ID `12` and slug `design` in the `leistung` taxonomy, the output URL might look like this:
Term URL: <a href="https://example.com/leistung/design">https://example.com/leistung/design</a>
This provides the clickable URL to the term archive page.
—
### Saving the Term ID
You might save the taxonomy term ID using a custom field or options field. For example:
update_post_meta( $post_id, '_leistung_term_id', $term_id );
Here:
– `'_leistung_term_id'` is the meta key.
– `$term_id` is the term ID you want to save.
—
### Displaying the Term Name from Saved ID
Retrieve the saved term ID and display its name using `get_term()`:
$term_id = get_post_meta( $post_id, '_leistung_term_id', true ); // Replace $post_id with your post ID
if ( $term_id ) {
$term = get_term( $term_id, 'leistung' );
if ( ! is_wp_error( $term ) && $term ) {
echo '<p>Term Name: ' . esc_html( $term->name ) . '</p>';
} else {
echo '<p>Term not found.</p>';
}
} else {
echo '<p>No term ID saved.</p>';
}
—
### Explanation:
1. **Save the Term ID:**
Use `update_post_meta()` to store the selected term ID for a specific post.
2. **Retrieve the Term ID:**
Use `get_post_meta()` to fetch the stored term ID from the meta key.
3. **Get Term Name:**
Pass the term ID to `get_term()` to retrieve the full term object, and use `$term->name` to get the name of the term.
—
### Example Workflow:
1. Save `Term ID = 12` for a post.
2. The term ID corresponds to a term with the name `Design`.
3. Output:
Term Name: Design
Let me know if you need help integrating this into your workflow! 😊
'taxonomy' => 'leistung',
'orderby' => 'name',
'hide_empty'=>false
]);
$taxonomy_options = [];
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_options[ $taxonomy->term_id ] = $taxonomy->name;
}
when select id shows in dropdown selected but not name
Here’s how to ensure the term name is displayed correctly in the dropdown and when selected:
### Updated Code Example for the Dropdown:
// Fetch all terms from the 'leistung' taxonomy
$taxonomies = get_terms([
'taxonomy' => 'leistung',
'orderby' => 'name',
'hide_empty' => false, // Include terms with 0 count
]);
$taxonomy_options = [];
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_options[ $taxonomy->term_id ] = $taxonomy->name; // Store term ID as key and term name as value
}
// Assume $selected_term_id holds the term ID you want to show as selected
$selected_term_id = get_post_meta( $post_id, '_leistung_term_id', true ); // Fetch the selected term ID
// Display the dropdown
?>
<select name="leistung_term" id="leistung_term">
<?php foreach ( $taxonomy_options as $term_id => $term_name ): ?>
<option value="<?php echo esc_attr( $term_id ); ?>" <?php selected( $term_id, $selected_term_id ); ?>>
<?php echo esc_html( $term_name ); ?>
</option>
<?php endforeach; ?>
</select>
### Key Components:
1. **Fetching Taxonomies:**
The `get_terms()` function retrieves the terms from the `leistung` taxonomy, and you're storing the term ID as the key and the term name as the value in the `$taxonomy_options` array.
2. **Populating the Dropdown:**
In the “ element:
– Use `foreach` to loop through the `$taxonomy_options`.
– For each option, set the `value` to the term ID and display the term name.
– Use the `selected()` function to ensure that the previously selected term ID is marked as selected in the dropdown.
### Output:
When the dropdown is rendered, it will show the term names, and when an option is selected, it will correctly correspond to the term ID behind the scenes.
### Important Functions:
– **`esc_attr()`**: Escapes the term ID for safe HTML output in attributes.
– **`esc_html()`**: Escapes the term name for safe HTML output in the dropdown options.
– **`selected()`**: Checks if the term ID matches the selected term ID to mark it as selected.
With this setup, the dropdown should now correctly display the term names, and selecting an option will reflect the associated term ID. Let me know if you need further assistance!
### Step 1: Create the Custom Widget
You’ll need to create a custom Elementor widget by extending the `ElementorWidget_Base` class. Here’s a complete example:
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class My_Custom_Taxonomy_Widget extends ElementorWidget_Base {
public function get_name() {
return 'custom_taxonomy_widget';
}
public function get_title() {
return __( 'Custom Taxonomy Widget', 'text-domain' );
}
public function get_icon() {
return 'eicon-posts-grid';
}
public function get_categories() {
return [ 'general' ]; // Adjust the category as needed
}
protected function _register_controls() {
$this->start_controls_section(
'section_content',
[
'label' => __( 'Content', 'text-domain' ),
]
);
$this->add_control(
'leistung_term',
[
'label' => __( 'Select Term', 'text-domain' ),
'type' => ElementorControls_Manager::SELECT,
'options' => $this->get_taxonomy_options(),
'default' => '',
]
);
$this->end_controls_section();
}
protected function render() {
$settings = $this->get_settings_for_display();
$selected_term_id = $settings['leistung_term'];
if ( $selected_term_id ) {
$term = get_term( $selected_term_id, 'leistung' );
if ( ! is_wp_error( $term ) && $term ) {
echo '<p>Selected Term: ' . esc_html( $term->name ) . '</p>';
} else {
echo '<p>Term not found.</p>';
}
} else {
echo '<p>No term selected.</p>';
}
}
private function get_taxonomy_options() {
$taxonomies = get_terms([
'taxonomy' => 'leistung',
'orderby' => 'name',
'hide_empty' => false,
]);
$taxonomy_options = [];
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_options[ $taxonomy->term_id ] = $taxonomy->name;
}
return $taxonomy_options;
}
}
// Register the widget
add_action( 'elementor/widgets/register', function( $widgets_manager ) {
$widgets_manager->register( new My_Custom_Taxonomy_Widget() );
});
### Explanation of the Code:
1. **Widget Definition**:
– `get_name()`: Returns the widget name.
– `get_title()`: Sets the title that appears in Elementor.
– `get_icon()`: Specifies the widget icon.
– `get_categories()`: Defines which category the widget appears in within Elementor.
2. **Controls**:
– `start_controls_section()`: Begins a new control section in the widget settings.
– `add_control()`: Adds a dropdown control for selecting taxonomy terms.
– `get_taxonomy_options()`: Retrieves and formats the taxonomy options.
3. **Rendering**:
– `render()`: Displays the selected term name. It checks if a term is selected and fetches its details using `get_term()`.
– **Error Handling**: Checks for errors and ensures the term is valid before displaying its name.
4. **Registration**:
– Registers the widget using `add_action()` to hook into Elementor's widget registration process.
### Usage:
– Add the widget to your Elementor layout.
– Select a term from the dropdown.
– The selected term's name will be displayed below the dropdown.
### Important Notes:
– Make sure to replace `'text-domain'` with your actual theme or plugin text domain.
– The taxonomy `leistung` must exist for the widget to work correctly.
With this setup, you'll have a custom Elementor widget that lets users select a taxonomy term and displays its name when selected. Let me know if you need further customization or assistance!