在WordPress后端的TinyMCE模态窗口中调用PHP函数

Call PHP function inside TinyMCE modal window on the WordPress backend

本文关键字:调用 PHP 函数 窗口 模态 WordPress 后端 TinyMCE      更新时间:2023-09-26

我正在使用为TinyMCE插件注册的静态.js文件。您单击新按钮,它会打开模态窗口,其中包含一个表单,我用它来生成简码。问题是我需要从PHP函数填充我的一些表单字段。我已经看了几个小时的文章,还没有找到可行的解决方案。现在我的php函数是一个简码,所以我需要把它改编成一个常规的旧函数。但是最大的挑战是弄清楚如何安排它,以便.js文件可以采用表单中的函数。这是基本的东西。首先,.js文件的一些区块:

(function(){
    // creates the plugin
    tinymce.create('tinymce.plugins.myshortcode', {
        // creates control instances based on the control's id.
        createControl : function(id, controlManager) {
            if (id == 'myshortcode') {
                // creates the button
                var button = controlManager.createButton('myshortcode', {
                    title : 'My Shortcode', // title of the button
                    image : '../wp-content/plugins/my-shortcode/js/images/myshortcode.png',  // path to the button's image
                    onclick : function() {
                        // triggers the thickbox
                        var width = jQuery(window).width(), H = jQuery(window).height(), W = ( 720 < width ) ? 720 : width;
                        W = W - 80;
                        H = H - 80;
                        tb_show( 'My Shortcode', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=myshortcode-form' );
                    }
                });
                return button;
            }
            return null;
        }
    });
    // registers the plugin.
    tinymce.PluginManager.add('myshortcode', tinymce.plugins.myshortcode);
    jQuery(function(){
        var form = jQuery(' '
'
The HTML Web Form all goes in here.'
'
 ');
var table = form.find('table');
        form.appendTo('body').hide();
        form.find('#myshortcode-submit').click(function(){
            var options = { 
                'att1'  : '',
                'att2'   : '',
                'att3'   : '',
                'att4'   : '',
                };
            var shortcode = '[myshortcode';
            
                for( var index in options) {
                var value = table.find('#myshortcode-' + index).val();
                
                if ( value !== options[index] && value != null )
                    shortcode += ' ' + index + '="' + value + '"';
            }
            
            shortcode += '] content here. [/myshortcode]';
            
            tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode);
            
            tb_remove();
        });
    });
})()

但是在它说"HTML Web 表单进入此处"的地方,我需要有几个基于 PHP 函数生成的字段。到目前为止,我只写了两个中的一个,正如我所说,它目前是写成一个简码,所以我需要改变它(考虑到这里的其他大问题,不确定最好的方法(。但这里是:

add_shortcode('rolescapsdropdown', 'sc_rolescapsdropdown');
function sc_rolescapsdropdown($attr) {
    global $wp_roles;
    $all_roles = $wp_roles->roles; 
    $editable_roles = apply_filters('editable_roles', $all_roles); 
    $user = new WP_User( 1 );
    $capslist = $user->allcaps;
    $dropdown = '<select multiple>';
    foreach($editable_roles as $role=>$theroles){
        $dropdown .= '<option value="'.$role.'">'.$role.'</option>';
    }
    foreach($capslist as $cap=>$caps){
        if($cap !== 'administrator' && $cap !== 'level_0' && $cap !== 'level_1' && $cap !== 'level_2' && $cap !== 'level_3' && $cap !== 'level_4' && $cap !== 'level_5' && $cap !== 'level_6' && $cap !== 'level_7' && $cap !== 'level_8' && $cap !== 'level_9' && $cap !== 'level_10'){ 
            $dropdown .= '<option value="'.$cap.'">'.$cap.'</option>';
        }
    }
    $dropdown .= '</select>';
    return $dropdown;
}

我希望避免在这里学习Ajax。但是我尝试将.js文件制作为.php文件,并仅将JavaScript包装在<script>标签中,但随后所有TinyMCE按钮都消失了,所以显然它不允许我使用.php文件来注册插件。

更新 1

我的一个想法是尝试将Web表单移动到php文件,并仅让注册TMCE插件的.js文件调用它,但我不知道这是否有效,也不知道如何让.js文件识别外部php文件中表单的存在。

更新 2

基于ScottA的帮助,以下是我尝试的工作方式:

我已将其添加到我的静态.js文件中,其形式为:

$.get( "ajax/test.php", function( data ) {
  var options = data.options;
  for(row in options) {
     $("#option-list").append("<option value=" + options[row].value + ">" + options[row].name + "</option>");
     // debug for unexpected results
     console.log(data.options);
  }
}, "json" );

我在一个名为"ajax"的子目录中创建了这个 test.php 文件:

function rolescapsdropdown() {
    global $wp_roles;
    $all_roles = $wp_roles->roles; 
    $editable_roles = apply_filters('editable_roles', $all_roles); 
    $user = new WP_User( 1 );
    $capslist = $user->allcaps;
    $all_options = $editable_roles . $capslist;
    $all_options[]['value'] = $value;
    $all_options[]['name'] = $name;
    echo json_encode( array('options' => $all_options) );
}

我将这个 HTML 添加到静态.js文件中的表单中:

<select id="option-list"></select>

我得到的是一个空白的模态窗口。当我包含$.get函数时,根本没有显示任何 HTML。

更新 3

仍然得到一个空白的模态窗口。我将其转换回简码以查看其输出的内容。这。。。

add_shortcode('rolesdropdown', 'sc_rolesdropdown');
function sc_rolesdropdown() {
    global $wp_roles;
    $all_roles = $wp_roles->roles; 
    $editable_roles = apply_filters('editable_roles', $all_roles); 
    $user = new WP_User( 1 );
    $capslist = $user->allcaps;
    foreach ($editable_roles as $role=>$theroles){
        $all_options = $role;
    }
    foreach ($capslist as $cap=>$caps){
        $all_options .= $cap;
    }
    echo json_encode( array('options' => $all_options) );
}

在页面上输出以下内容:

{"选项":"trollswitch_themesedit_themesactivate_pluginsedit_pluginsedit_usersedit_filesmanage_optionsmoderate_commentsmanage_categoriesmanage_linksupload_filesimportunfiltered_htmledit_postsedit_others_postsedit_published_postspublish_postsedit_pagesreadlevel_10level_9level_8level_7level_6level_5level_4level_3level_2level_1level_0edit_others_pagesedit_published_pagespublish_pagesdelete_pagesdelete_others_pagesdelete_published_pagesdelete_postsdelete_others_postsdelete_published_postsdelete_private_postsedit_private_postsread_private_postsdelete_private_pagesedit_private_pagesread_private_pagesdelete_userscreate_usersunfiltered_uploadedit_dashboardupdate_pluginsdelete_pluginsinstall_pluginsupdate_themesinstall_themesupdate_corelist_usersremove_usersadd_userspromote_usersedit_theme_optionsdelete_themesexportbe_trollexec_phpedit_others_phpadministrator"}

但是,当在后端的模式窗口中时,当$.get调用包含该函数的文件时,窗口只是空白的。

你说你不想学习AJAX,但你不应该害怕。 jQuery的$.get()函数使得从外部文件中获取和处理数据变得非常容易。如果你的PHP函数驻留在一个单独的文件中,你可以对该文件进行$.get((调用,并在同一个jQuery函数中填充表单。

你的jQuery可以像这样简单:

$.get( "ajax/test.php", function( data ) {
  $( ".result" ).html( data );
});

假设你的文件,test.php返回了一个JSON数组,甚至是基于你在URL中传递的参数的纯文本(即:"ajax/test.php?userid=1&get=name"(,你可以使用jQuery来填充表单。

您的 jQuery:

$.get( "ajax/test.php?userid=1&get=name", function( data ) {
  $( "#myform input.firstname").val( data.firstname );
  $( "#myform input.lastname").val( data.lastname );
}, "json" );

测试.php可能如下所示:

<?php
// your function to retrieve the data from the database, a file, etc.
echo json_encode(array(
  "firstname" => "Burt",
  "lastname" => "Bartigan"
));
?>

说你不想使用 AJAX,但这是解决这个问题的最简单方法。

更多信息关于 $.get((;

有关 PHP json 函数的更多信息

--编辑--

要在下面回答您的评论:

您的 PHP:

$all_options[]['value'] = $value;
$all_options[]['name'] = $name;
// or however you can best get it
// from the database into an array
echo json_encode( array('options' => $all_optoins) );

你的jQuery:

$.get( "ajax/test.php", function( data ) {
  var options = data.options;
  for(row in options) {
     // append will place this inside the <select> HTML element
     $("#option-list").append("<option value=" + options[row].value + ">" + options[row].name + "</option>");
     // debug for unexpected results?
     console.log(data.options);
  }
}, "json" );

您的网页:

<select id="option-list"></select>

我只是遇到了同样的问题,这就是我解决它的方式。首先,我们需要将一些 PHP 值传递给 JavaScript 文件。由于无法使用wp_localize_script(我们不对脚本进行排队(,我们将直接以admin_head打印它:

foreach( array('post.php','post-new.php') as $hook )
    add_action( "admin_head-$hook", 'admin_head_js_vars' );
/**
 * Localize Script
 */
function admin_head_js_vars() 
{
        $img = plugins_url( '/js/images/myshortcode.png', __FILE__ );
        ?>
<!-- TinyMCE Shortcode Plugin -->
<script type='text/javascript'>
    var b5f_mce_config = {
        'tb_title': '<?php _e('Roles Shortcode'); ?>',
        'button_img': '<?php echo $img; ?>',
        'ajax_url': '<?php echo admin_url( 'admin-ajax.php')?>',
        'ajax_nonce': '<?php echo wp_create_nonce( '_nonce_tinymce_shortcode' ); ?>' 
    };
</script>
<!-- TinyMCE Shortcode Plugin -->
        <?php
}

这样,按钮创建如下所示:

title: b5f_mce_config.tb_title, // title of the button
image: b5f_mce_config.button_img, // path to the button's image

现在,我们将添加一个 Ajax 操作:

add_action( 'wp_ajax_b5f_tinymce_shortcode', 'b5f_tinymce_shortcode' );
function b5f_tinymce_shortcode()
{
    $do_check = check_ajax_referer( '_nonce_tinymce_shortcode', 'security', false ); 
    if( !$do_check )
        echo 'error';
    else
        include_once 'my-form.php';
    exit();
}

回到JS(注意我的例子是基于这个(:

jQuery(function($)
{
    /* Used in Ajax and Callback */
    var table;
    /**
     * Get the ThickBox contents wit Ajax
     */
    var data_alt = {
        action: 'b5f_tinymce_shortcode',
        security: b5f_mce_config.ajax_nonce
    };
    $.post( 
        b5f_mce_config.ajax_url, 
        data_alt,                   
        function( response )
        {
            if( 'error' == response  )
            {
                $('<div id="mygallery-form"><h1 style="color:#c00;padding:100px 0;width:100%;text-align:center">Ajax error</h1></div>')
                    .appendTo('body').hide();
            }
            else
            {
                form = $(response);
                table = form.find('table');
                form.appendTo('body').hide();
                form.find('#mygallery-submit').click(b5f_submit_gallery);
            }
        }
    ); 
    /**
     * Callback for submit click
     */
    function b5f_submit_gallery()
    {
        // Options defined in admin_head
        var shortcode = '[my_shortcode]';
        // inserts the shortcode into the active editor
        tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode);
        // closes Thickbox
        tb_remove();
    }
});

最后,Ajax附带的文件myform.php可以包含任何WordPress函数:

<?php
/**
 * Used by Ajax
 */
?>
<div id="mygallery-form">
<?php echo site_url(); ?>
</div>