jeudi 2 juin 2016

Wordpress Multisite, Injecting Dynamic Content into New Site Registration Form in 'site-new.php'

I have found a solution here by dennisg and edited by Hans Helge. The part I am working with is the injection of extra form fields using an IIFE and jQuery in an external file.

(function($) {
    $(document).ready(function() {
        $('<tr class="form-field form-required"></tr>').append(
            $('<th scope="row">New field</th>')
        ).append(
            $('<td></td>').append(
                $('<input class="regular-text" type="text" title="New Field" name="blog[new_field]">')
            ).append(
                $('<p>Explanation about your new field</p>')
            )
        ).insertAfter('#wpbody-content table tr:eq(2)');
    });
})(jQuery);

Thus far, I have successfully squeezed PHP into the above js. The following seems to work ok, when I suffix the file name with .php instead of .js

<?php
$user_def_cats = array('Subject', 'Person', 'Client');
?>
(function($) {
    $(document).ready(function() {
        $('<tr class="form-field form-required"></tr>').append(
            $('<th scope="row">Site Category</th>')
        ).append(
            $('<td></td>').append(
                $('<select name="blog[blog_cats]" ><?php
foreach ($user_def_cats as $key => $val) {
    echo "<option value=\"" . ($key + 1) . "\" >" . $val . "</option>";

}
?></select>')
            ).append(
                $('<p>Blog Category (Allows creation of different blog listings.)</p>')
            )
        ).insertAfter('#wpbody-content table tr:eq(2)');
    });
})(jQuery);

So, this works with sample data:

$user_def_cats = array('Subject', 'Person', 'Client');

Next, I try to access the dynamic content ('Subject','Person' ... etc ) using PHP by requiring once the main plugin file, so I can call a method to retrieve the dynamic form data using get_site_option().

require_once WP_PLUGIN_DIR . '/' . plugin_basename(__FILE__);

With the inclusion of this one line above, I get an error:

Uncaught SyntaxError: Unexpected token < http://ift.tt/22ztAvp line 1

This might be because the plugin file I am calling is echoing out stuff, which is outside of any legitimate js code. E.g. echo "Hi"; causes same error.

Reading around the web I see that perhaps, a better solution would be to save all my dynamic content into a data.json file (as opposed to wp_sitemeta using update_site_option() ), and then AJAX/ get_json to access the data. This would avoid the somewhat awkward cross over of PHP and JS.

Maybe there is a better way to add form fields with dyn content into admin site-new.php page?

Any light on this matter would be gratefully appreciated.

Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire