WordPress

Jak dodać stronę postu z przycisku bez ponownego ładowania

  • 16 kwietnia, 2024
  • 5 min read
Jak dodać stronę postu z przycisku bez ponownego ładowania


Jestem nowicjuszem w programowaniu i próbuję stworzyć stronę. Kiedy kliknę przycisk Gutemberg, wygeneruje stronę postu z tekstem i obrazem. Problem polega na tym, że strona tworzona jest przy każdym przeładowaniu strony administracyjnej, a nie tylko po przesłaniu przycisku. Dodałem to, ale nadal nie działa. W bazie danych mam utworzonych wiele postów. Co więcej, tekst na mojej opublikowanej stronie nie jest napisany:

if (isset($_POST['submit-gutenberg'])) { $post_id = $this->create_post();

public function woosterPartnerPluginSectionSetup()
    {
        // Add a new section to a settings page.
        add_settings_section('partner_badges_section2', __('Choississez votre constructeur de page', 'wooster-partner'), array($this, 'woosterPartnerPluginSection'), 'wooster_url', array());
    }

    /***
     * Creates a button to submit and generate a page
     * @return void
     */
    public function woosterPartnerPluginSection()
    {
       // echo'<p>' . __('TEST ','wooster-partner').'</p>
       //when post sent, it calls the method to create a post
       if (isset($_POST['submit-gutenberg'])) {
        $post_id = $this->create_post(); //
        if ($post_id) {
            $post_url = get_permalink($post_id);
            wp_redirect($post_url);
            exit();
        }

    }
    ?>

    <div style="display: flex;">
        <form method="POST" action="options.php" name="gutenberg" id="gutenberg-form">
        <?php submit_button('Gutenberg', 'primary', 'submit-gutenberg',false); ?>
        </form>
        <form method="POST" action="options.php" name="Elementor" style="margin-left: 2rem;">
        <?php submit_button('Elementor', 'primary', 'submit-elementor',false); ?>
        </form>
    </div>
        <?php
    ?>
<?php
}

    /***
     * Creates a post function
     * @return void
     */
    public function woosterPluginCallback()
    {
        $this->create_post(); // calls the create post method
        // echo json_encode($query->get_posts());
    }

    /***
     * To download image from the URL
     * @return void
     */
    public function download_image()
    {
        $image_url="
        // wp function for sideloading images from URL and attaching them to the media library
        $image = media_sideload_image($image_url, 'Image téléchargée depuis l\'URL');
        return $image;
    }
    /***
     * To download image from the URL
     * @return string $image
     */

    public function insert_to_media($image)
    {
        $image = $this->download_image();
        // it returns the attachment id
        $attachment = wp_insert_attachment(array(
            'post_title' => 'Image Wooster téléchargée',
            'post_content' => 'Image wooster',
            'post_status' => 'draft',
        ), $image);

        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attachment, $image);
        wp_update_attachment_metadata($attachment, $attach_data);

        return $attachment;
    }

    /***
     * Creates the post with the Json data and image
     * @return void
     */
    public function create_post()
    {
        $image = $this->download_image(); // calls the method
        $attachment_id = $this->insert_to_media($image);
        $json_data="{
                "post_type": "page",
                "post_status": "draft",
                "post_title": "Partenariat Wooster",
                "post_content": "<!-- wp:html -->
                <!-- wp:paragraph -->
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget vehicula orci,
                ut iaculis ex. Donec sed ornare nisi. Donec non sollicitudin ex. Aliquam at leo non odio hendrerit consectetur. Sed porttitor lacus placerat metus viverra facilisis.
                Aenean gravida ornare purus, ut posuere lectus dictum a. Nunc nisi leo, porta ut porta et, porttitor quis ante. In id arcu in sem vulputate fermentum. Vivamus libero augue,
                finibus id eros in, gravida vestibulum ex. Quisque ultrices, odio et consectetur vestibulum, arcu mi elementum nulla, a elementum massa libero quis nibh. Aenean pulvinar diam sem, a auct
                or nisl ullamcorper at.<!-- notionvc: 79475225-3863-439d-8bf9-d8194d4899b3 --></p>
                <!-- /wp:paragraph -->
                <!-- /wp:html -->"
            }";
        // the Json objects is decoded into an associative arrays
        $post_data = json_decode($json_data, true);

        // Get the URL of the attached image
        $image_url = wp_get_attachment_url($attachment_id);

        // Construct the post content with the image using Gutemberg block syntax
        $post_content = "<!-- wp:image {'id': $attachment_id} -->
                        <figure class="wp-block-image">
                        <img src="
                        </figure>
                        <!-- /wp:image -->
                        <!-- wp:paragraph -->".$post_data;

        // Add the image content to the post content, the 'post content' in the array $post_data is upddated
        $post_data['post_content'] = $post_content;

        // Insert the post in the database
        $post_id = wp_insert_post(array(
            'post_type' => 'page',
             'post_status' => 'draft',
             'post_title' => "Partenariat Wooster",
             'post_content' => $post_data['post_content']
         ));
        $post_id = wp_insert_post($post_data);
        // check if the post insertion is successful, then update
        if ($post_id) {
            // Update the post to reflect the changes
            $post_data['ID'] = $post_id;
            wp_update_post($post_data);
        }
    }
 }

i haczyki:

public function __construct()
{
    add_action('wooster_badge_content', array($this, 'woosterShowBadges'));
    // You need to use the template_redirectet hook (and not init) for the shortcode to be taken into account without displaying an error message in Gutenberg.
    add_action('template_redirect', array($this, 'makeShortcode'));
    // add_action('wp_loaded', array($this, 'makeShortcode'));

    add_action('wooster_badge_content', array($this, 'woosterShowForm'));
    add_action('admin_init', array($this, 'woosterPartnerBadgesSectionSetup'));
    add_action('admin_init', array($this, 'woosterPartnerBadgesFieldSetup'));
    add_action('admin_init', array($this, 'checkElementplugingisactive'));
    add_action('admin_init', array($this, 'woosterPartnerPluginSectionSetup'));
    add_action('admin_init', array($this, 'woosterPluginCallback'));
    add_action('admin_init', array($this, 'download_image'));
    add_action('admin_init', array($this, 'insert_to_media'));
    add_action('admin_init', array($this, 'create_post'));
}

Dziękuję za wszystkie elementy, które możesz przynieść, pomogą mi to zrozumieć

Warto przeczytać!  Przedstawiamy bezpłatne narzędzie do badania słów kluczowych: wygeneruj ponad 300 pomysłów na słowa kluczowe jednym kliknięciem


Źródło