我试图在wordpress admin(post.php)上创建一个按钮,用户输入。 当我添加例如" 1x312 "并点击按钮需要使用youtube.com/embed/ 1x312
打开新页面我使用以下代码在functions.php中创建按钮:
add_action('media_buttons', 'add_my_media_button');
function add_my_media_button(){
echo '<a target="_blank" href="https://youtube.com/embed/'.$variale.'" class="button button-default">Click here to view</a>';
echo '<input type="text">';
}
当我在输入字段中键入如何添加到我的函数中?
<?php $variable = <input type="text"> ?> - how to do that?
答案 0 :(得分:0)
你需要一个表单然后ajax将表单输入发送到它的函数。
像这样的Smth:<form action="<?php echo esc_url( home_url( '/' ) ); ?>" method="post" class="custom-button">
<div class="form__body">
<div class="form__row">
<label for="field-userinput" class="form__label">
<?php esc_html_e( 'Some Label Here', 'default' ); ?>
</label>
<div class="form__controls">
<input type="text" class="field" name="field-userinput" id="field-userinput" value="">
<span class="span-error"><?php esc_html_e( 'This field is required.', 'default' ); ?></span>
</div><!-- /.form__controls -->
</div><!-- /.form__row -->
</div><!-- /.form__body -->
<div class="form__actions">
<button class="form__btn btn" type="submit">
<?php esc_html_e( 'Submit', 'default' ); ?>
</button>
</div><!-- /.form__actions -->
</form>
然后是ajax:
$( 'form.custom-button' ).on( 'submit',function (e) {
e.preventDefault();
var form = $( this );
// validations here
if ( form.find( '.error' ).length === 0 ) {
$.ajax({
type: 'post',
url: siteUrl.ajax_url + '?action=custom_button',
data: form.serialize(),
success: function (response) {
// do smth on success
}
} );
} else {
e.preventDefault();
}
});
之后是wordpress:
add_action( 'wp_ajax_custom_button', 'custom_button' );
add_action( 'wp_ajax_nopriv_custom_button', 'custom_button' );
function custom_button() {
// here at the $_POST you will have the input and can make whatever you like with it
}