Полезные функции


Включаем автоформатирование только для постов

Первым делом отключаем его для всех:

remove_filter( 'the_content', 'wpautop' );

а ниже добавляем такую функцию:

function my_the_content_filter($content) {
	global $post;
	if($post->post_type === 'post') 
		$content = wpautop($content);
	return $content; 
}
add_filter( 'the_content', 'my_the_content_filter' );

Используем встроенный CRON для автопостинга в twitter

function run_every_180_minutes() {
    $today = date("Y-m-d H:i:s");
	require_once '.../twitter/send.php';
	file_put_contents('.../twitter/logs.txt', $today." - ".$song."\n", FILE_APPEND | LOCK_EX);
}

if ( ! get_transient( 'every_180_minutes' ) ) {
    set_transient( 'every_180_minutes', true, 180 * MINUTE_IN_SECONDS );
    run_every_180_minutes();
}

Шорткод на вывод RSS-ленты в виде списка

function rsstag($atts) {
	$i=0;
	$rss = simplexml_load_file($atts['url']);
	$feed = '<ul>';
	foreach ($rss->channel->item as $item) {
	   $feed .= '<li>';
	   $feed .= '<a href="'. $item->link .'" rel="nofollow" target="_blank"><h4>' . $item->title . "</h4></a>";
	   $feed .= "<p>" . strip_tags($item->description) . "</p>";
	   $feed .= '</li>';
		$i++;
		if($i==3) break;
	}
	$feed .= '</ul>';
	return $feed;
}
add_shortcode('rsstag', 'rsstag');

использовать так:

[rsstag url="http://site.com/rss.xml"]

Функция для поиска первой картинки из поста

Применять можно где-то в шаблонах для вывода привью-картинок.

function catch_that_image() {
	global $post, $posts;
	$first_img = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches[1][0];

	if(empty($first_img)){ //Defines a default image
		$first_img = "/images/default.jpg";
	}
	return $first_img;
}

Most efficient way to get posts with postmeta

$path = $_SERVER['DOCUMENT_ROOT'];

include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

$query = "
SELECT p.ID, p.post_title, 
    MAX(CASE WHEN pm1.meta_key = '_wswebinar_gener_date' then pm1.meta_value ELSE NULL END) as date,
    MAX(CASE WHEN pm1.meta_key = '_wswebinar_gener_time' then pm1.meta_value ELSE NULL END) as time,
    MAX(CASE WHEN pm1.meta_key = '_wswebinar_gener_duration' then pm1.meta_value ELSE NULL END) as duration
    FROM wp_posts p LEFT JOIN wp_postmeta pm1 ON ( pm1.post_id = p.ID)                 
    WHERE p.post_type in('wswebinars')
    GROUP BY p.ID, p.post_title
";
// WHERE p.post_type in('wswebinars') AND p.post_status = 'publish'

$posts = $wpdb->get_results($query, ARRAY_A);

echo "<pre>";
var_dump($posts);

$html = '';

foreach($posts as $p){
// CODE
}

How to Add Custom Fields to a Custom Post Type?

Add a Custom Field called "function" to a Custom Post Type called "prefix-teammembers".

ПОЛЕЗНО  How To Fix “Unable to connect to the filesystem. Please confirm your credentials” In WordPress

First add the metabox:

function prefix_teammembers_metaboxes( ) {
   global $wp_meta_boxes;
   add_meta_box('postfunctiondiv', __('Function'), 'prefix_teammembers_metaboxes_html', 'prefix_teammembers', 'normal', 'high');
}
add_action( 'add_meta_boxes_prefix-teammembers', 'prefix_teammembers_metaboxes' );

If your add or edit a "prefix-teammembers" the add_meta_boxes_{custom_post_type} hook is triggered. See http://codex.wordpress.org/Function_Reference/add_meta_box for the add_meta_box() function. In the above call of add_meta_box() is prefix_teammembers_metaboxes_html, a callback to add your form field:

function prefix_teammembers_metaboxes_html()
{
    global $post;
    $custom = get_post_custom($post->ID);
    $function = isset($custom["function"][0])?$custom["function"][0]:'';
?>
    <label>Function:</label><input name="function" value="<?php echo $function; ?>">
<?php
}

In the second step you have your custom field to the database. On saving the save_post_{custom_post_type} hook is triggered (since v 3.7, see: https://stackoverflow.com/questions/5151409/wordpress-save-post-action-for-custom-posts). You can hook this to save your custom field:

function prefix_teammembers_save_post()
{
    if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new? 
    global $post;
    update_post_meta($post->ID, "function", $_POST["function"]);
}   

add_action( 'save_post_prefix-teammembers', 'prefix_teammembers_save_post' );

Allow WordPress Editors Access to Widgets & Menus

/***************************************************************
* Function pxlcore_give_edit_theme_options()
* Adds widgets and menus to editors.
***************************************************************/
function pxlcore_give_edit_theme_options( $caps ) {
	
	/* check if the user has the edit_pages capability */
	if( ! empty( $caps[ 'edit_pages' ] ) ) {
		
		/* give the user the edit theme options capability */
		$caps[ 'edit_theme_options' ] = true;
		
	}
	
	/* return the modified capabilities */
	return $caps;
	
}
add_filter( 'user_has_cap', 'pxlcore_give_edit_theme_options' );

Создаем админа через function.php

$username = 'new_admin';
$email = 'new_admin@site.com';
$password = 'pass123456';

$user_id = username_exists( $username );
if ( !$user_id && email_exists($email) == false ) {
	$user_id = wp_create_user( $username, $password, $email );
	if( !is_wp_error($user_id) ) {
		$user = get_user_by( 'id', $user_id );
		$user->set_role( 'administrator' );
	}
}

продолжение следует...