Integrate AI to write description

Is there a way to integrate AI to write listing descriptions? Example user has entered their details above. And when they reach the description field section a button “Write with AI” will be shown and it will use the information from all the fields which was already input above and write the description for them.

im looking for the same solution, hivepres does not have it and nether do other form providers ive scoured, ill let you know if i find one and perhaps if you could do me the same favour? Once a form builder is found theres a way of exporting the response to a google sheet and for a plugin to fill out the hivepress form via importing the new data on the google sheet and then hiding the “add listing” button on the front end.

Hi,

Unfortunately, there is no simple solution for this, as we are not integrated with AI services. As a workaround, you can of course try third-party plugins, but we cannot guarantee 100% compatibility, as we have not tested them.

I might start working on this AI integration this weekend. Are there any hooks or important details I need to know about? @andrii

Hi,

Unfortunately, we cannot provide general guidance for this, as we are not familiar with your service and have not tested AI plugins with our products. However, you can review the developer documentation at this link Getting started | Developer Docs.

Have you found a way? I cant figure it out

This sounds really interesting, but far out of my comfort zone. Nevertheless, here’s AIs first attempt. This is untested, so use with caution, but regardless, it might help point you in the right direction! :slight_smile:

To add AI text generation to the HivePress “Add Listings” details page, allowing users to generate a description based on selected form attributes with a button in the description box, you’ll need to implement a custom solution. HivePress, a WordPress plugin for creating directory and listing websites, does not natively support this feature, so it requires custom coding involving JavaScript, PHP, and integration with an AI text generation service (e.g., OpenAI). Below is a detailed, step-by-step guide to achieve this.


Overview of the Solution

You’ll create a custom WordPress plugin (or modify your theme) to:

  1. Add a “Generate Description” button next to the description field on the listing submission form.
  2. Use JavaScript to collect the form’s attribute values when the button is clicked and send them to the server.
  3. Use PHP on the server to process the data, generate a prompt, and request a description from an AI service.
  4. Return the AI-generated text to the front-end and populate the description field.

This requires knowledge of WordPress development, JavaScript, PHP, and the chosen AI service’s API. If you’re not a developer, you may need to hire one.


Step-by-Step Implementation

1. Create a Custom Plugin

For maintainability, create a custom plugin rather than modifying your theme’s functions.php. Create a folder in wp-content/plugins, e.g., hivepress-ai-description, with a main file hivepress-ai-description.php:

<?php
/*
Plugin Name: HivePress AI Description
Description: Adds AI-generated descriptions to HivePress listing forms.
Version: 1.0
Author: Your Name
*/

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Enqueue scripts and handle AJAX
require_once plugin_dir_path(__FILE__) . 'includes/functions.php';

2. Add Front-End JavaScript

Enqueue a JavaScript file to add the button and handle the interaction. In includes/functions.php:

function hivepress_ai_enqueue_scripts() {
    // Target the listing submission page (adjust as needed)
    if (is_page('add-listing')) { // Replace with HivePress-specific check if needed
        wp_enqueue_script(
            'hivepress-ai-description',
            plugin_dir_url(__FILE__) . 'assets/js/ai-description.js',
            array('jquery'),
            '1.0',
            true
        );
        wp_localize_script(
            'hivepress-ai-description',
            'ajax_object',
            array('ajax_url' => admin_url('admin-ajax.php'))
        );
    }
}
add_action('wp_enqueue_scripts', 'hivepress_ai_enqueue_scripts');

Create assets/js/ai-description.js:

jQuery(document).ready(function($) {
    // Find the description field (adjust selector based on HivePress form structure)
    var descriptionField = $('textarea[name="description"]');
    if (descriptionField.length) {
        // Add the button
        var button = $('<button type="button" class="generate-description">Generate Description</button>');
        button.insertAfter(descriptionField);

        // Handle button click
        button.on('click', function() {
            var formData = $('form').serializeArray();
            var dataToSend = [];

            // Exclude the description field
            $.each(formData, function(index, field) {
                if (field.name !== 'description') {
                    dataToSend.push(field);
                }
            });

            // Send AJAX request
            $.ajax({
                url: ajax_object.ajax_url,
                type: 'POST',
                data: {
                    action: 'generate_description',
                    form_data: dataToSend
                },
                success: function(response) {
                    if (response.success) {
                        descriptionField.val(response.data);
                    } else {
                        alert('Failed to generate description.');
                    }
                },
                error: function() {
                    alert('An error occurred.');
                }
            });
        });
    }
});

Notes:

  • Adjust the descriptionField selector if HivePress uses a different name (e.g., listing_description).
  • Check if the form has an ID (e.g., #listing-form) to scope the formData collection.

3. Handle the AJAX Request in PHP

Add the AJAX handler in includes/functions.php:

function hivepress_ai_generate_description() {
    if (!isset($_POST['form_data'])) {
        wp_send_json_error('No form data received.');
    }

    $form_data = $_POST['form_data'];
    $prompt = "Generate a description for a listing with the following attributes: ";

    // Build the prompt from form data
    foreach ($form_data as $field) {
        // Ideally, use HivePress API to get field labels (placeholder function)
        $label = function_exists('hivepress') ? hivepress()->form->get_field_label($field['name']) : $field['name'];
        if ($label) {
            $prompt .= $label . ": " . sanitize_text_field($field['value']) . ", ";
        }
    }
    $prompt = rtrim($prompt, ', ') . ".";

    // Call the AI service (e.g., OpenAI)
    $api_key = 'your_openai_api_key'; // Store securely, e.g., in wp_options
    $response = wp_remote_post('https://api.openai.com/v1/completions', array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
        ),
        'body' => json_encode(array(
            'model' => 'text-davinci-003', // Use the latest model available
            'prompt' => $prompt,
            'max_tokens' => 200, // Adjust for desired length
            'temperature' => 0.7, // Controls creativity
        )),
        'timeout' => 30,
    ));

    // Handle the AI response
    if (is_wp_error($response)) {
        wp_send_json_error('API request failed.');
    } else {
        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (isset($body['choices'][0]['text'])) {
            $generated_text = trim($body['choices'][0]['text']);
            wp_send_json_success($generated_text);
        } else {
            wp_send_json_error('No text generated.');
        }
    }
}
add_action('wp_ajax_generate_description', 'hivepress_ai_generate_description');
add_action('wp_ajax_nopriv_generate_description', 'hivepress_ai_generate_description');

Notes:

  • Replace 'your_openai_api_key' with your actual API key, ideally stored securely using WordPress options (update_option/get_option).
  • The hivepress()->form->get_field_label() function is hypothetical. Refer to the HivePress Code Reference to find the correct method (e.g., accessing form fields via HivePress\Models\Listing or form instances).
  • If labels aren’t available, use $field['name'] as a fallback, though it’s less user-friendly.

4. Set Up the AI Service

  • Choose a Service: This example uses OpenAI, but alternatives like Google’s Gemini or Hugging Face APIs could work.
  • Get an API Key: Sign up at OpenAI or your chosen provider.
  • Test the Integration: Ensure your server can make HTTP requests (e.g., curl or wp_remote_post).

How It Works

  1. Button Addition: On the “Add Listings” page, JavaScript adds a “Generate Description” button after the description textarea.
  2. Data Collection: When clicked, it collects all form field values (e.g., Category, Location, Price) except the description.
  3. Server Processing: The data is sent to the server, where PHP constructs a prompt (e.g., “Generate a description for a listing with the following attributes: Category: Real Estate, Location: New York, Price: $500,000.”).
  4. AI Generation: The prompt is sent to the AI service, which returns a generated description.
  5. Field Update: The description field is populated with the AI-generated text.

Additional Considerations

  • Form Identification: Replace is_page('add-listing') with a HivePress-specific check (e.g., a hook like hivepress/v1/forms/listing_submit) if available. Check HivePress documentation or inspect the page source.
  • Styling: Style the button with CSS (e.g., .generate-description { background: #0073aa; color: white; }) or use HivePress classes (e.g., hp-button).
  • Error Handling: Add a loading spinner or disable the button during the request:
    button.prop('disabled', true).text('Generating...');
    // In success/error: button.prop('disabled', false).text('Generate Description');
    
  • Cost: AI API calls may incur charges. Monitor usage and set limits if needed.
  • Field Labels: If HivePress doesn’t provide a direct API for labels, inspect the form HTML or database to map field names to labels.

Final Notes

This solution assumes a single-page form and English text. For multi-step forms or other languages, additional logic may be required. Test thoroughly, as HivePress’s form structure might vary based on customization. If you’re unsure about HivePress specifics, consult the HivePress documentation or community forums.

This implementation provides a seamless way for users to generate descriptions based on their selected attributes, enhancing the HivePress experience with AI capabilities.

Cheers,
Chris :victory_hand:

1 Like

Yes. I was able to build two simple and complex AI extensions powered by ChatGPT and huggingface api. But this start-up is unique, and the prompts are hardcoded into my custom extensions.

Hi kels, did you use the suggestion from ChrisB?

I am running a room / whole unit rental listing site. So will it be able to gather all information (including address field from mapbox) and use AI to write the description? I have not much knowledge in coding so any help is appreciated

No. I already started before he posted that.

If you can share the HTML structure of your listing form, I could try.

Hi Kels, thanks for trying to help. the code is too long to paste here. and i cant upload a file maybe you can share your email?

Try Pastebin.com - Nice to share with the community if you wouldn’t mind!

And/or, this is what GitHub is ideal for.

Cheers,
Chris :victory_hand: