WordPress database manipulation - markhowellsmead/helpers GitHub Wiki

Some of this code can destroy your website, database and server if used incorrectly. Only use it if you're 100% sure what you're doing. Copy+paste of this code is dangerous.

Delete all posts of a custom post type

Caution: may not delete related post meta or attachment.

$sql = "DELETE a,b,c FROM wp_posts a LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = '$post_type';";

WP_Query filters

(Via.)

  • posts_request – Filters the completed* SQL statement,
  • posts_pre_query – If this filter returns an array of posts, it will bypass the whole querying. By default, it returns null,
  • posts_results – Filters the raw posts result array,
  • the_preview – Filters the WP_Post object when previewing,
  • the_posts – Filters the retrieved array of WP_Post objects,
  • posts_search – Filters the Search SQL,
  • wp_search_stopwords – Filters an array of stopwords that are excluded from search,
  • posts_search_orderby – Filters the ORDER BY used when searching,
  • wp_query_search_exclusion_prefix – Filters the prefix which, if a term has, excludes them from search.

Programmatically modify query clauses

<?php

add_filter( 'posts_clauses', 'filter_clauses', 10, 2 );

/**
 * Filtering everything.
 *
 * @param array $clauses Array with all parts of the query.
 * @param WP_Query $wp_query Object.
 * @return string
 */
function filter_clauses( $clauses, $wp_query ) {
 $clauses['where'] = " AND post.post_title LIKE '%SOMETEXT%'";
 return $clauses;
}