Adding Custom Fields to WordPress User Profile

The user profile of WordPress can be fairly easily adapted to add your own values​​. So you can add the necessary fields according to your requirements. Here is how you do it, we add a field for the address and the content will be stored in the database. Various hooks in WordPress make sure that you only have to worry about the fields.

The function to store the entries is fb_save_custom_user_profile_fields() and here it is important to check the rights of each active user, only if the rights are available, in this case for editing users (edit_user), then data may be stored.
The actual saving of data takes place via update_usermeta().

It can pass all kinds of fields of course, the input field is just an example. It is advisable to outsource the functions in a Plugin, an alternative is also the functions.php of the Theme, but is certainly not the best way.

Each function of the small sample was referred to two hooks. Because WordPress differentiate between editing of user profiles and update personal data. This is done using the constant IS_PROFILE_PAGE. On default this constant is on TRUE and so would the hooks show_user_profile and personal_options_update be enough to bring in new fields and save them. But this can vary depending on the installation and this way the admin cannot maintain these new fields. In particular, two more hooks are needed. Otherwise there might be many cases, where the admin has to maintain data which the user doesn't even see in his profile.

function fb_add_custom_user_profile_fields( $user ) {
?>
        <h3><?php _e('Extra Profile Information', 'your_textdomain'); ?></h3>
        <table class="form-table">
                <tr>
                        <th>
                                <label for="address"><?php _e('Address', 'your_textdomain'); ?>
                        </label></th>
                        <td>
                                <input type="text" name="address" id="address" value="<?php echo esc_attr( get_the_author_meta( 'address', $user->ID ) ); ?>" class="regular-text" /><br />
                                <span class="description"><?php _e('Please enter your address.', 'your_textdomain'); ?></span>
                        </td>
                </tr>
        </table>
<?php }
function fb_save_custom_user_profile_fields( $user_id ) {
        if ( !current_user_can( 'edit_user', $user_id ) )
                return FALSE;
        update_usermeta( $user_id, 'address', $_POST['address'] );
}
add_action( 'show_user_profile', 'fb_add_custom_user_profile_fields' );
add_action( 'edit_user_profile', 'fb_add_custom_user_profile_fields' );
add_action( 'personal_options_update', 'fb_save_custom_user_profile_fields' );
add_action( 'edit_user_profile_update', 'fb_save_custom_user_profile_fields' );

WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Easier Plugin Development by Moving Plugin Directory

If you're a experienced programmer you're testing your programs not only with the latest version of WordPress but also with some older versions since there are many dated installations. So you have several versions installed on your development server and want to test your newly created code with every single version.

You could copy your plugin files to all installed version's plugin directory manually every time you change the code... but you're a programmer, so this is no option, is it?
If your dev server works under a *nix system you probably have tried to use symbolic links but it didn't work. This is not a bug of WordPress but of PHP. So this does not work either.

Fortunately WordPress defines two constants which can help you to simplify things nonetheless: WP_PLUGIN_DIR and WP_PLUGIN_URL. These constants point to the plugin directory of the respective WordPress installation. They are defined since WordPress 2.6 and supporting older versions is most likely unnecessary
.
To make your plugins accessible to all your installed WordPress versions you simply move them to a central directory and define the constants accordingly:

define( 'WP_PLUGIN_DIR', '/var/www/plugins' ); // or with XAMPP C:/xampp/htdocs/plugins
define( 'WP_PLUGIN_URL', 'http://localhost/plugins' );

In this example the plugins reside in the directory 'plugins' in the root directory of the webserver. If you now define the above constants in every WordPress installation you have easy access to them to test your code with every version.

(Thanks to John Blackbourn on the wp-hackers list for having the idea.)

Hint for Multisite-Users

Also usable for WordPress Multisite

define( 'WPMU_PLUGIN_DIR', '/var/www/multisite-plugins' );
define( 'WPMU_PLUGIN_URL', 'http://localhost/multisite-plugins' );

WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

unserialize() Error at Offset… Different solutions

The problem is not always obvious, for example the error message in relation to the function unserialize(). If you look around the net to help you find countless search and few answers, because usually the problem lies in the source, in the passed value. But not always you can control it, especially in debugging helpers there are different contents.

To help some people who are seeking help, here are some solutions you can work with. Some are to be used only in conjunction with WordPress, because the function comes from the core. But there are similar things, of course, even without WP.

The first solution can be found directly in the comments for the function of PHP.net.

$object = preg_replace( '!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $object );

Similar this approach:

$object = preg_replace( '/;n;/', ';N;', $object );

Alternative others prefer to use trim()

$object = trim( $object );

But even with these solutions you can't always get what you want, you need a queries which gives you the answer whether it is serialized data or not. Usually unserialize() takes care of it, but as I said, this does not always help. WordPress provides its own functions for this.

  • is_serialized( $data )
  • is_serialized_string( $data )

With these two functions it can be queried in a clean way.
But also there you can use a simple snippet. Not the best practice maybe, therefore, I prefer to use the functions or outside of WP, a separate function, see Gist 1415653.

$is_serialized = preg_match( "/^(O:|a:)/", $object );

It may help one or the other, otherwise I use it as a memory aid.


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Activate WordPress Plugins Automatically via a Function

WordPress stores the active Plugins in the database table options, field activate_plugins, so it is easy to change this value to activate various Plugins by WordPress; either as a Plugin solution after setting up a new installation or because some Plugins need some other Plugins.

I show you as an example a solution. It is important that you don't use the Plugin names, but the string of the file, which is also required in various hooks. Below you will also find a simple solution to get to this string in your backend.

// example on admin init, control about register_activation_hook()
add_action( 'admin_init', 'fb_activate_plugins' );
// the exmple function
function fb_activate_plugins() {
        if ( ! current_user_can('activate_plugins') )
                wp_die(__('You do not have sufficient permissions to activate plugins for this site.'));
        $plugins = FALSE;
        $plugins = get_option('active_plugins'); // get active plugins
        if ( $plugins ) {
                // plugins to active
                $pugins_to_active = array(
                        'hello.php', // Hello Dolly
                        'adminimize/adminimize.php', // Adminimize
                        'akismet/akismet.php' // Akismet
                );
                foreach ( $pugins_to_active as $plugin ) {
                        if ( ! in_array( $plugin, $plugins ) ) {
                                array_push( $plugins, $plugin );
                                update_option( 'active_plugins', $plugins );
                        }
                }
        } // end if $plugins
}

The following function and its hook provides a direct output of the string of the Plugin file on the Plugin page in your backend, so please use it only for a quick finding.

add_filter( 'plugin_row_meta', 'fb_get_plugin_string', 10, 4 );
function fb_get_plugin_string( $plugin_meta, $plugin_file, $plugin_data, $status ) {
        // echo plugin file string
        echo '<code>' . $plugin_file . '</code><br>';
        return $plugin_meta;
}

WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Advent Calendar – WordPress, WPCron and the right Time

WordPress offers a pseudo-cronjob functionality, which allows the developer to execute scheduled events. For example, the whole Update Notification does it. In these so-called Scheduled Events you can define your own jobs. Thereby you should however pay attention to one important thing: time.

The wp-cron.php works outside the core and loads only the most important things and leaves all settings of WordPress open. In the Settings -> General set time zone is not included. wp-cron.php runs on UTC.

That means: Are we in the time zone of Berlin, the local time is UTC +1. Are we performing a scheduled event, it will always be one hour after the actual time we like to execute. To change this, we use the following function:

function get_offset_to_gmt_in_seconds() {
        $current_timezone_offset = get_option( 'gmt_offset' );
        $offset = $current_timezone_offset * 3600;
        return $offset;
}

Guest Post

This post is written by Thomas Herzog - hughwillfayle.de and is a guest post on WP Engineer about WordPress.
Thank you very much from my part to Thomas. Please see his nice plugins on the official WordPress repository.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Comment Length Limiter

If you have used Twitter, then you know that you are only allowed to type 140 characters in a single Tweet. There is a nice little number below the text field indicating how much is left to write.

It would be nice to have this feature for WordPress comments too. Or any text field, for that matter. It can be done with the following piece of JavaScript:

jQuery(function($) {
        // configure
        var comment_input = $( '#commentform textarea' );
        var submit_button = $( '#commentform .form-submit' );
        var comment_limit_chars = 1000;
        // stop editing here
        // display how many characters are left
        $( '<div class="comment_limit_info"><span>' + comment_limit_chars + '</span> characters left</div>' ).insertAfter( comment_input );
        comment_input.bind( 'keyup', function() {
                // calculate characters left
                var comment_length = $(this).val().length;
                var chars_left = comment_limit_chars - comment_length;
                // display characters left
                $( '.comment_limit_info span' ).html( chars_left );
                // hide submit button if too many chars were used
                if (submit_button)
                        ( chars_left < 0 ) ? submit_button.hide() : submit_button.show();
        });
});

https://gist.github.com/1422754

The first three vars below the // configure comment can be edited.
comment_input is the DOM element of the text field.
submit_button is the DOM element for the button to submit the form.
Finally, comment_limit_chars is the amount of characters allowed.

This snippet automatically inserts a div tag below the text field and updates the character count when the user types. The submit_button is optional. Set the var to null if you don't want it to be grayed out.

Please keep in mind that this only validates the input on the client side. If you have to rely on the maximum text length, like Twitter does, you need to check the length on the back end side with PHP too.

Guest Post

This post is written by Eric Teubert - www.satoripress.com and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Eric.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Pretty permalinks without mod_rewrite

There are still some third-class web hosters who do allow the .htaccess files … and turn off the standard module mod_rewrite. But without mod_rewrite, WordPress cannot use pretty permalinks, right? Wrong!

There’s another directive we can use: ErrorDocument.

ErrorDocument 404 /index.php

This will do almost the same as the rewrite rules WordPress offers. It will not work with caching plugins like W3 Total Cache, it will not catch empty searches and other .htaccess tricks you may want to use. So consider this trick as a temporary solution until you have found a real web hoster.


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

XML to Array

In terms of importing data is often set to be XML and have to pass an array in WordPress, which passes into the database. To get an array in PHP after parsing XML, you will always find a variety of threads and questions. In the following, therefore, a simple and quick solution that works great for PHP5.

// only for errors an parse
$filename = preg_replace(
    "/\<\!\[CDATA\[(.*?)\]\]\>/ies",
    "'[CDATA]' . base64_encode('$1') . '[/CDATA]'",
    $filename
);
// load xml file
$xml      = simplexml_load_string( $filename );
// seesaw ;-)
$json     = json_encode( $xml );
$options  = json_decode( $json, TRUE );
// see result
var_dump( $options );
// update in WordPress
update_option( 'my_settings_id', $options );

WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Debug enqueued Scripts and Styles in WordPress

WordPress can easily manage scripts and style sheets, a prerequisite is the use of the opportunities around wp_enqueue_script() and wp_enqueue_style(). A small function can help and returns the built-in scripts and styles.

Some Background

Scripts and style sheets can be introduced into WordPress in different ways, which applies to the backend and frontend. The classical methods of a meta element in the head or footer area is not recommended, because WordPress can do the management of scripts and style sheets since version 2.1 - a prerequisite is the use of the opportunities around wp_enqueue_script() and wp_enqueue_style(). Thus, various advantages are taken over directly by the WordPress core, compressing and delivering joint in one file all the scripts and style sheets. Also WordPress cares about that each script exists only once in the delivery, so there is no multiple use of jQuery for example.
Currently, there are similar approaches with different JS solutions. WordPress can take care of it and deliver optimized, each script only once and easily via the ID on the scripts.

But in order to evaluate your included scripts and style sheets, you can use the following solution where you already have all the included files in a list. The following function simply puts the addresses in the footer of WordPress, frontend - wp_footer and backend - admin_footer, this can be adjusted via hook, of course. This is only an idea.

In the following is the function which will be output via hook in backend and frontend. Parallel I've integrated it in the Plugin Debug Objects and the new version should go online around Christmas.

add_action('wp_footer', 'fb_urls_of_enqueued_stuff');
add_action('admin_footer', 'fb_urls_of_enqueued_stuff');
function fb_urls_of_enqueued_stuff( $handles = array() ) {
        global $wp_scripts, $wp_styles;
        // scripts
        foreach ( $wp_scripts -> registered as $registered )
                $script_urls[ $registered -> handle ] = $registered -> src;
        // styles
        foreach ( $wp_styles -> registered as $registered )
                $style_urls[ $registered -> handle ] = $registered -> src;
        // if empty
        if ( empty( $handles ) ) {
                $handles = array_merge( $wp_scripts -> queue, $wp_styles -> queue );
                array_values( $handles );
        }
        // output of values
        $output = '';
        foreach ( $handles as $handle ) {
                if ( ! empty( $script_urls[ $handle ] ) )
                        $output .= $script_urls[ $handle ] . '<br />';
                if ( ! empty( $style_urls[ $handle ] ) )
                        $output .= $style_urls[ $handle ] . '<br />';
        }
        echo $output;
}

WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Advent Calendar – WordPress Editor: Preserve the scroll position

WordPress has a nice editor, with which are several hundreds of articles written daily.

But in my opinion the editor has an usability issue.
Every time you save a post the scroll position of the editor will be on top again. If you want to continue writing the post you have first to find he old position again. This can be time-consuming.

Save editor scroll position on saving

To avoid this behavior I have written a snippet which I want to share now with you.

<?php
/**
 * The class will help you to recover the old scoll position in your Editor.
 * Either HTML or visuel editor.
 */
final class Preserve_Editor_Scroll_Position {
        /**
         * Init
         */
        public static function init() {
                add_filter( 'redirect_post_location', array( __CLASS__, 'add_query_arg' ) );
                add_action( 'edit_form_advanced', array( __CLASS__, 'add_input_field' ) );
                add_action( 'edit_page_form', array( __CLASS__, 'add_input_field' ) );
                add_filter( 'tiny_mce_before_init', array( __CLASS__, 'extend_tiny_mce' ) );
        }
        /**
         * Adds a hidden input field for scrolltop value
         */
        public static function add_input_field() {
                $position = ! empty( $_GET['scrollto'] ) ? $_GET['scrollto'] : 0;
                printf( '<input type="hidden" id="scrollto" name="scrollto" value="%d"/>', esc_attr( $position ) );
                // Print Javascript data
                add_action( 'admin_print_footer_scripts', array( __CLASS__, 'print_js' ), 55 ); // Print after Editor JS.
        }
        /**
         * Extend TinyMCE config with a setup function
         */
        public static function extend_tiny_mce( $init ) {
                if ( 'tinymce' == wp_default_editor() )
                        $init['setup'] = 'rich_scroll';
                return $init;
        }
        /**
         * Returns redirect url with query arg for scroll position
         */
        public static function add_query_arg( $location ) {
                if ( ! empty( $_POST['scrollto'] ) )
                        $location = add_query_arg( 'scrollto', (int) $_POST['scrollto'], $location );
                return $location;
        }
        /**
         * Prints Javascript data
         */
        public static function print_js() {
                ?>
        <script>
        ( function( $ ) {
                $( '#post' ).submit( function() {
                        scrollto =
                                $( '#content' ).is( ':hidden' ) ?
                                $( '#content_ifr' ).contents().find( 'body' ).scrollTop() :
                                $( '#content' ).scrollTop();
                        $( '#scrollto' ).val( scrollto );
                } );
                $( '#content' ).scrollTop( $( '#scrollto' ).val() );
        } )( jQuery );
        function rich_scroll( ed ) {
                ed.onInit.add( function() {
                        jQuery( '#content_ifr' ).contents().find( 'body' ).scrollTop( jQuery( '#scrollto' ).val() );
                } );
        };
        </script>
                <?php
        }
}
add_action( 'plugins_loaded', array( 'Preserve_Editor_Scroll_Position', 'init' ) );

If you want you can create your own plugin with this snippet or you can download the plugin Preserve Editor Scroll Position.

Guest Post

Dominik Schilling AvatarThis post is written by Dominik Schilling - wpgrafie.de and is a post in our Advent Calendar on WP Engineer about WordPress. Dominik is Student, Web Developer, WordPress Contributing Developer - ocean90 and he ♥ WordPress.
Thank you very much from my part to Dominik.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)




btbt
Designed by Wbcom Designs
#