Shortcode-Attribute im WordPress-Plugin mit React

Lesezeit: 4 Minuten

Benutzer-Avatar
Malakiof

Ich versuche herauszufinden, wie Attribute an ein reaktionsbasiertes Plugin in WordPress übergeben werden (mithilfe von @wordpress/scripts).

meine main.php-Datei:

<?php
defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );

define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );

add_shortcode( 'my_app', 'my_app' );
/**
 * Registers a shortcode that simply displays a placeholder for our React App.
 */
function my_app( $atts = array(), $content = null , $tag = 'my_app' ){
    ob_start();
    ?>
        <div id="app">Loading...</div>
        <?php wp_enqueue_script( 'my-app', plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true ); ?>
    <?php 
    return ob_get_clean();
}

Also wenn ich die App mit diesem Shortcode laden möchte [my_app form=”login”], wie übergebe ich dieses Attribut an wp_enqueue_script() ? und wie kann ich einen Inhalt gemäß diesem Attribut auf der Reaktionsseite anzeigen? Ich versuche, ein Registrierungsformular anzuzeigen, wenn das Attribut “registrieren” ist

meine Reaktionshauptdatei:

import axios from 'axios';
const { Component, render } = wp.element;

class WP_App extends Component { 
constructor(props) {
    super(props);
    this.state = { username: '', password: '' };
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

render() {
    return (
        <div class="login">
            <form onSubmit={this.handleSubmit} class="justify-content-center">
            <div class="form-group">
                <label htmlFor="username">
                    Username
                </label>
                <input
                    class="form-control"
                    id="username"
                    onChange={this.handleUsernameChange}
                    value={this.state.username}
                    type="email"
                />
             </div>
            <div class="form-group">
                <label htmlFor="password">
                    Password
                </label>
                <input
                    class="form-control"
                    id="password"
                    onChange={this.handlePasswordChange}
                    value={this.state.password}
                    type="password"
                />
            </div>
            <button class="btn btn-primary">
                Submit
            </button>
            </form>
        </div>
    );
}

handleUsernameChange(e) {
    this.setState({ username: e.target.value });
}

handlePasswordChange(e) {
    this.setState({ password: e.target.value });
}

handleSubmit(e) {
    e.preventDefault();
    if (!this.state.username.length) {
        return;
    }
    if (!this.state.password.length) {
        return;
    }
    const creds = { username: this.state.username,
                    password: this.state.password };
    axios.post('https://example.com:8443/login', creds)
        .then(response => {
                console.log("SUCCESSS")
                window.open('https://example.com/login?t=" + response.data.token, "_blank")  
            }
        )
        .catch(error => {
            if (error.response && error.response.data){
                if (error.response.data === "USER_DISABLED"){
                    console.log("User account disabled."
                    )
                }
                if (error.response.data === "ACCOUNT_LOCKED"){
                    console.log("User account is locked probably due to too many failed login attempts."
                    )
                }
                else{
                    console.log("Login failed."
                    )
                }
            }
            else{
                console.log("Login failed."
                )
                
            }
            console.log(error.response)
        });
}
}


render(
    <WP_App />,
    document.getElementById("app')
);

Benutzer-Avatar
Andrii Kowalenko

WordPress Methode zum Laden benutzerdefinierter Daten für das Skript verwendet wird wp_localize_script Funktion.

Du könntest übrigens deine Shortcode-Funktion umschreiben

add_shortcode( 'my_app', 'my_app' );
/**
 * Registers a shortcode that simply displays a placeholder for our React App.
 */
function my_app( $atts = array(), $content = null , $tag = 'my_app' ){
    add_action( 'wp_enqueue_scripts', function() use ($atts) {
        wp_enqueue_script( 'my-app', plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true );
        wp_localize_script(
            'my-app',
            'myAppWpData',
            $atts 
        );
    });

    return '<div id="app">Loading...</div>';
}

Dann könnten Sie übrigens das Shortcode-Einstellungsobjekt über JavaScript verwenden:

window.myAppWpData['form'] // if you set form as shortcode param

Dann könnten Sie diese Optionen als Requisitenparameter für Ihre Reaktion festlegen WP_App Komponente.

Und dann könntest du deine rendern WP_APP Inhalt abhängig von seinem Shortcode-Parameter:

Hauptrender:

render(
    <WP_App shortcodeSettings={window.myAppWpData} />,
    document.getElementById('app')
);

und wie kann ich einen Inhalt gemäß diesem Attribut auf der Reaktionsseite anzeigen?

Sie könnten bedingte Logik gemäß Shortcode-atts-Werten verwenden. Weitere Details zur bedingten Reaktionslogik finden Sie auf der offiziellen Dokumentationsseite

https://reactjs.org/docs/conditional-rendering.html

WP_APP-Rendering:

Du könntest benutzen props.shortcodeSettings innerhalb von WP_APP render() Funktion zum Erstellen einer beliebigen Logik, mit der Sie Ihre Komponente anzeigen möchten.

render() {
    return (
       // you could use props.shortcodeSettings to build any logic
       // ...your code
    )
}

Wenn Sie mehrere Shortcodes auf der Seite haben möchten.

Sie könnten erwägen, hinzuzufügen uniqid( 'my-app' ) zum Skript-Handle-Namen

function my_app( $atts = array(), $content = null, $tag = 'my_app' ) {
    $id = uniqid( 'my-app' );
    
    add_action( 'wp_enqueue_scripts', function () use ( $atts, $id ) {
        wp_enqueue_script( "my-app", plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true );
        wp_localize_script(
            "my-app",
            "myAppWpData-$id",
            $atts
        );
    } );

    return sprintf( '<div id="app-%1" data-my-app="%1">Loading...</div>', $id );
}

Für diesen Weg – Sie könnten für Ihre implementieren index.jsDateilogik für mehrere Apps,

const shortcodesApps = document.querySelectorAll('[data-my-app]');

shortcodesApps.forEach((node) => {
    const nodeID = node.getAttribute('data-my-app');
    const shortcodeSettings = window[`myAppWpData-${nodeID}`];

    render(
        <WP_App shortcodeSettings={shortcodeSettings} />,
        node
    );
})

1382610cookie-checkShortcode-Attribute im WordPress-Plugin mit React

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy