Matt Fiddles

Life's so vast, there's just so much to do...

User Tools

Site Tools


Sidebar

"The suit into which the man's body had been stuffed looked as if it's only purpose in life was to demonstrate how difficult it was to get this sort of body into a suit. "



Where will you go today?

"`Ford, you're turning into a penguin. Stop it.'"

- Arthur experiences the improbability drive at work.
computers:websites:wordpress:functions

Wordpress Functions

Here a some functions of wordpress. See all of them at https://developer.wordpress.org/reference/

User Functions

get_currentuserinfo

Get current user's info:

      global $current_user;     //remember this one!
      get_currentuserinfo();
 
      echo 'Username: ' . $current_user->user_login . "\n";
      echo 'User email: ' . $current_user->user_email . "\n";
      echo 'User first name: ' . $current_user->user_firstname . "\n";
      echo 'User last name: ' . $current_user->user_lastname . "\n";
      echo 'User display name: ' . $current_user->display_name . "\n";
      echo 'User ID: ' . $current_user->ID . "\n";

https://codex.wordpress.org/Function_Reference/get_currentuserinfo

You can also call 'wp_get_current_user()' but you will need to use the init or any subsequent action to call that function, or run into problems. See here.

You can also get the id with get_current_user_id()

current_user_can

// current_user_can( $capability, $args );
if ( current_user_can('moderate_comments') ) {
  echo 'The current user can moderate comments';
}

See a list of capabilities at https://codex.wordpress.org/Function_Reference/current_user_can

get_userdata

Use to get info about a user, An alias of get_user_by('id').

Some of the things it can get are: ID, user_login, user_pass, user_nicename, user_email, user_url, user_registered, display_name. And of the user_meta if can get: user_firstname, user_lastname, nickname, description, wp_capabilities (array), and others.

      $user_info = get_userdata(1);
      echo 'Username: ' . $user_info->user_login . "\n";
      echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";
      echo 'User ID: ' . $user_info->ID . "\n";
      $first_name = $user_info->first_name;
      $last_name = $user_info->last_name;

https://codex.wordpress.org/Function_Reference/get_userdata

get_user_by

Get user data by field and data. Select user by:

  • 'id' - ID
  • 'slug' - user_nicename
  • 'email' - user_email
  • 'login' - user_login

Returns a WP_User object or false if no user is found. Will also return false if $field does not exist.

$user = get_user_by( 'email', 'user@example.com' );
echo 'User is ' . $user->first_name . ' ' . $user->last_name;

See the function page for a list of WP_User properties: https://codex.wordpress.org/Function_Reference/get_user_by

is_user_logged_in

Verify a user is logged in

is_user_logged_in();

If you get a 'Fatal error: Call to undefined function is_user_logged_in() in …' error, remember that the this is a pluggable function, and you can't call it too early:

Wrong:

include_once( __DIR__ ."/../../../wp-load.php");
// first, are they logged in?
if ( !is_user_logged_in() ) { 
  echo "Forbidden";
  exit;
}
//verify nonces, and that POST code was given
// actual code

Right:

include_once( __DIR__ ."/../../../wp-load.php");
function toggle5254() {
  // first, are they logged in?
  if ( !is_user_logged_in() ) { 
    echo "Forbidden";
    exit;
  }
  //verify nonces, and that POST code was given
  // actual code
 
}
add_action('init', 'toggle5254');

http://stackoverflow.com/questions/23562170/fatal-error-call-to-undefined-function-is-user-logged-in

wp_loginout

Shows a login link. This code adds a login/logout link as the last item in our menu.

add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
        //ob_start();
        $loginoutlink=wp_loginout(home_url(),false);
        //$loginoutlink=wp_loginout(get_permalink(),false);
        //$loginoutlink = ob_get_contents();
        //ob_end_clean();
        $items .= '<li>'. $loginoutlink .'</li>';
    return $items;
}

https://codex.wordpress.org/Function_Reference/wp_loginout

wp_generate_password

Generate a random password

wp_generate_password( [length=12], [special_chars=true], [extra_special_chars=false] );

  // get 12 random chars with special chars
  $pass=wp_generate_password();
 
  // get 15 random chars without special chars
  $pass=wp_generate_password(15,false);
 
  // get a new hash (useful for wp-config.php's keys)
  $pass=wp_generate_password(160,true,true);

https://codex.wordpress.org/Function_Reference/wp_generate_password

wp_create_user

Creating a new user

wp_create_user( $username, $password, $email );
$user_id = username_exists( $user_name );
if ( !$user_id and email_exists($user_email) == false ) {
	$random_password = wp_generate_password( );
	$user_id = wp_create_user( $user_name, $random_password, $user_email );
} else {
	echo __('User already exists.  Password inherited.');
}

https://codex.wordpress.org/Function_Reference/wp_create_user

And to update a user, use wp_update_user https://codex.wordpress.org/Function_Reference/wp_update_user

wp_lostpassword_url

Returns link for lost password

wp_lostpassword_url( $redirect );
<a href="<?php echo wp_lostpassword_url(); ?>" title="Lost Password">Lost Password</a>
<a href="<?php echo wp_lostpassword_url( get_bloginfo('url') ); ?>" title="Lost Password">Lost Password</a>

wp_redirect

Redirect a user to an absolute URI $location with (optional) $status, which defaults to 302.

<?php
wp_redirect( $location, $status );
exit;
?>

Note that you need to put an 'exit' after it or it won't work right.

https://codex.wordpress.org/Function_Reference/wp_redirect

wp_get_recent_posts

List recent posts;

  // wp_get_recent_posts( $args, $output )
 
  $args = array(
    'numberposts' => 10,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'include' => ,
    'exclude' => ,
    'meta_key' => ,
    'meta_value' =>,
    'post_type' => 'post',
    'post_status' => 'draft, publish, future, pending, private',
    'suppress_filters' => true );
 
  $recent_posts = wp_get_recent_posts( $args, ARRAY_A );

http://www.wpbeginner.com/wp-tutorials/how-to-display-recent-posts-in-wordpress/

get_posts

  $args = array(
	'posts_per_page'   => 5,
	'offset'           => 0,
	'category'         => '',
	'category_name'    => '',
	'orderby'          => 'post_date',
	'order'            => 'DESC',
	'include'          => '',
	'exclude'          => '',
	'meta_key'         => '',
	'meta_value'       => '',
	'post_type'        => 'post',
	'post_mime_type'   => '',
	'post_parent'      => '',
	'post_status'      => 'publish',
	'suppress_filters' => true 
  );
  $posts_array = get_posts( $args );

get_posts

  $args = array(
	'sort_order' => 'ASC',
	'sort_column' => 'post_title',
	'hierarchical' => 1,
	'exclude' => '',
	'include' => '',
	'meta_key' => '',
	'meta_value' => '',
	'authors' => '',
	'child_of' => 0,
	'parent' => -1,
	'exclude_tree' => '',
	'number' => '',
	'offset' => 0,
	'post_type' => 'page',
	'post_status' => 'publish'
  ); 
  $pages = get_pages($args);

get_post_meta

Returns a post's meta info;

  // $meta_values = get_post_meta( $post_id, $key, $single );
  $status = get_post_meta( $post['ID'] , 'status', true);

https://codex.wordpress.org/Function_Reference/get_post_meta

For getting meta values that have more than one value, use get_post_custom_values:

  // format: get_post_custom_values($key, $post_id);
  $mykey_values = get_post_custom_values( 'my_key' );
  foreach ( $mykey_values as $key => $value ) {
    echo "$key  => $value ( 'my_key' )<br />"; 
  }

Outputs:

0 => First value ( 'my_key' )
1 => Second value ( 'my_key' )
2 => Third value ( 'my_key' )

https://codex.wordpress.org/Function_Reference/get_post_custom_values

Also see get_post_custom https://codex.wordpress.org/Function_Reference/get_post_custom

wp_insert_post_data

Set and Change post info.

add_filter( 'wp_insert_post_data' , 'modify_post_5485' , '99', 2 );
function modify_post_5485( $data , $postarr ) 
{
  // get post info
  $user_info = get_userdata($data['post_author']);
  // set post title 
  $data['post_title'] = "Custom Post at " . date_i18n( 'g:ia \o\n D M d, Y', strtotime( $data['post_date'] ));
}

https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data

Post Date as Title: http://wpquestions.com/question/showChrono/id/9097

Note, sometimes if you are changing the post title, it won't work, especially if you are pulling meta data. You will find yourself having to press the Update button twice. In that case you need to run save_post on the post after it is saved. See the Next section:

save_post

Filter to re-save a post.

add_action( 'save_post', 'save_meta_data', 10, 2);
function save_meta_data($post_id,$post) {
  // some test so we will only save it once:
  if ( test )
   {
     // we have to remove the action or end up with an infinite loop
     remove_action( 'save_post', 'save_meta_data', 10, 2 );
     wp_update_post( array( 'ID' => $post_id ) );
     add_action( 'save_post', 'save_meta_data', 10, 2 );
   }
}

https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

https://wordpress.stackexchange.com/questions/76945/embed-new-post-form-inside-new-post-form/83717

update_post_meta

Update and add to a post's meta data.

add_action( 'save_post', 'notify', 10, 2);
function notify($post_id,$post) {
    // save meta data (remove filter to avoid infinite loop)
    remove_action( 'save_post', 'notify', 10, 2 );
    update_post_meta($post_id, 'notified', '1', true);
    add_action( 'save_post', 'notify', 10, 2 );
}

https://codex.wordpress.org/Function_Reference/update_post_meta

get_option and update_option

update_option( $option, $new_value );

update_option( 'default_comment_status', 'closed' );

get_option( $option ); returns value or false. $option = get_option( $option, 'default_value' ); $admin_email = get_option( 'admin_email' ); For a list of options, see https://codex.wordpress.org/Option_Reference ===== Others ===== home_url( $path ); show home url

get_the_title( $ID ); get post title

computers/websites/wordpress/functions.txt · Last modified: Apr 5, 2015 (4 years ago) by Matt Bagley