Wordpress Image

Step 1: Set Up Plugin Directory Structure

Create a new folder for your plugin inside the wp-content/plugins directory of your WordPress installation. Inside the plugin folder, create the following files:

  • nft-plugin.php: The main plugin file.
  • nft-assets.js: JavaScript file to handle frontend functionality.
  • nft-styles.css: CSS file for styling the frontend.

Step 2: Plugin Header

In the nft-plugin.php file, start with the plugin header, which provides essential information about your plugin, and create an admin settings page for entering OpenSea API keys:

<?php
/*
Plugin Name: Your NFT Plugin
Description: A WordPress plugin for connecting MetaMask and displaying an NFT image gallery using Elementor.
Version: 1.0
Author: Your Name
*/

// Enqueue frontend scripts and styles
function nft_enqueue_assets() {
    wp_enqueue_script('nft-assets', plugin_dir_url(__FILE__) . 'nft-assets.js', array('jquery'), '1.0', true);
    wp_enqueue_style('nft-styles', plugin_dir_url(__FILE__) . 'nft-styles.css', array(), '1.0');
}
add_action('wp_enqueue_scripts', 'nft_enqueue_assets');

// Function to connect MetaMask
function nft_connect_metamask_script() {
    echo '<script>
        function connectMetaMask() {
            if (typeof window.ethereum !== "undefined") {
                window.ethereum
                    .request({ method: "eth_requestAccounts" })
                    .then((accounts) => {
                        alert("Connected to MetaMask. Wallet Address: " + accounts[0]);
                    })
                    .catch((error) => {
                        alert("MetaMask connection failed: " + error.message);
                    });
            } else {
                alert("MetaMask extension not detected. Please install MetaMask.");
            }
        }
    </script>';
}
add_action('wp_footer', 'nft_connect_metamask_script');

// Admin settings page for entering OpenSea API keys
function nft_admin_settings_page() {
    ?>
    <div class="wrap">
        <h1>Your NFT Plugin Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('nft-settings-group');
            do_settings_sections('nft-settings-group');
            ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">OpenSea API Key</th>
                    <td><input type="text" name="opensea_api_key" value="<?php echo esc_attr(get_option('opensea_api_key')); ?>" /></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

function nft_register_settings() {
    register_setting('nft-settings-group', 'opensea_api_key');
}
add_action('admin_init', 'nft_register_settings');

function nft_plugin_settings_menu() {
    add_options_page('Your NFT Plugin Settings', 'NFT Plugin', 'manage_options', 'nft-plugin-settings', 'nft_admin_settings_page');
}
add_action('admin_menu', 'nft_plugin_settings_menu');

// Shortcode to display NFT image gallery
function nft_gallery_shortcode($atts) {
    // Add logic to fetch NFT image URLs based on the user's wallet address and the OpenSea API key
    $api_key = get_option('opensea_api_key');
    $wallet_address = ''; // Replace this with the logic to get the user's wallet address from MetaMask or elsewhere

    // Call the OpenSea API to fetch the user's NFTs
    $nfts = nft_fetch_nfts($wallet_address, $api_key);

    // Output the NFT image gallery HTML
    ob_start();
    if (!empty($nfts)) {
        echo '<div class="nft-gallery">';
        foreach ($nfts as $nft) {
            echo '<img src="' . esc_url($nft['image_url']) . '" alt="' . esc_attr($nft['name']) . '">';
        }
        echo '</div>';
    } else {
        echo '<p>No NFTs found for this user.</p>';
    }
    return ob_get_clean();
}
add_shortcode('nft_gallery', 'nft_gallery_shortcode');

// Function to fetch NFTs using the OpenSea API
function nft_fetch_nfts($wallet_address, $api_key) {
    // Create a Guzzle HTTP client instance
    $client = new \GuzzleHttp\Client();

    // Set the OpenSea API endpoint and wallet address
    $endpoint = "https://api.opensea.io/api/v1/assets";
    $query = [
        'owner' => $wallet_address,
        'order_direction' => 'desc',
        'offset' => 0,
        'limit' => 10, // Adjust the limit as per your requirements
    ];

    // Send a GET request to the OpenSea API with the API key in the headers
    $response = $client->get($endpoint, [
        'query' => $query,
        'headers' => [
            'Accept' => 'application/json',
            'X-API-KEY' => $api_key,
        ],
    ]);

    // Decode the response JSON
    $data = json_decode($response->getBody(), true);

    // Extract the NFT image URLs and names from the API response
    $nfts = array();
    foreach ($data['assets'] as $asset) {
        $nft['image_url'] = $asset['image_url'];
        $nft['name'] = $asset['name'];
        $nfts[] = $nft;
    }

    return $nfts;
}

Step 3: CSS Styling

Create or update the nft-styles.css file in your plugin directory to style the NFT gallery:

/* nft-styles.css */

/* NFT Image Gallery */
.nft-gallery {
    display: flex;
    flex-wrap: wrap;
}

.nft-gallery img {
    max-width: 100%;
    margin: 5px;
}

Step 4: Elementor Widget Integration

Create a new file named elementor-widget.php inside your plugin folder (wp-content/plugins/your-nft-plugin/) and add the following code:

<?php
// Elementor widget class
class NFT_Gallery_Elementor_Widget extends \Elementor\Widget_Base {
    public function get_name() {
        return 'nft_gallery_elementor_widget';
    }

    public function get_title() {
        return 'NFT Image Gallery';
    }

    public function get_icon() {
        return 'eicon-gallery-grid';
    }

    public function get_categories() {
        return ['basic'];
    }

    protected function _register_controls() {
        // Elementor widget controls configuration
        $this->start_controls_section(
            'section_content',
            [
                'label' => 'NFT Image Gallery Settings',
            ]
        );

        // Repeater field for NFT image URLs
        $repeater = new \Elementor\Repeater();
        $repeater->add_control(
            'image_url',
            [
                'label' => 'NFT Image URL',
                'type' => \Elementor\Controls_Manager::URL,
                'default' => [
                    'url' => '',
                ],
            ]
        );

        $this->add_control(
            'gallery_images',
            [
                'label' => 'NFT Image URLs',
                'type' => \Elementor\Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [],
                'title_field' => '{{{ image_url.url }}}',
            ]
        );

        $this->end_controls_section();
    }

    protected function render() {
        // Get widget settings
        $settings = $this->get_settings_for_display();

        // Output the frontend HTML of the widget
        if (!empty($settings['gallery_images'])) {
            echo '<div class="nft-gallery">';

            foreach ($settings['gallery_images'] as $image) {
                $url = $image['image_url']['url'];
                echo '<img src="' . esc_url($url) . '" alt="NFT Image">';
            }

            echo '</div>';
        }
    }
}

Step 5: Activate the Plugin and Set OpenSea API Key

In your WordPress admin area, go to “Plugins” and activate your NFT plugin.

Then, navigate to “NFT Plugin” in the WordPress admin menu to access the plugin settings page. Enter your OpenSea API key and save the settings.

Step 6: Use the Elementor Widget

With the plugin updated, activated, and the OpenSea API key set, edit a page using Elementor. Look for the “NFT Image Gallery” widget under the “Basic” category in the Elementor widgets panel. Drag the widget to the desired location on the page.

In the widget settings, users can enter multiple NFT image URLs using the repeater field. The plugin will display these images as a gallery on the frontend.

Please note that this guide provides a basic implementation of the NFT image gallery with Elementor, including the plugin settings page for entering the OpenSea API key and fetching NFT image URLs using the API. Depending on your specific requirements, you may need to further customize the widget, add more controls, and enhance the frontend display. Additionally, ensure that you handle user inputs securely and validate the URLs before displaying the gallery.

Read More

1 thought on “Creating a WordPress plugin for integrating MetaMask and displaying NFT images as shortcodes

Comments are closed.