WP_Query: apply an SQL function to meta fileld value

You can use the filter posts_orderby. For a simple example: add_filter(‘posts_orderby’, ‘apply_sql_on_order’, 10, 2 ); function apply_sql_on_order($orderby, $query) { if(is_array($query->query_vars[“orderby”]) && array_key_exists(“apply_sql”, $query->query_vars[“orderby”])) { $orderby = preg_replace(“/(.*) (ASC|DESC)/”, $query->query_vars[“orderby”][“apply_sql”] . “($1) $2”, $orderby); } return $orderby; } $query = new WP_Query( array( ‘meta_query’ => array( ‘state_clause’ => array( ‘key’ => ‘state’ ), ), ‘orderby’ => … Read more

Make a loop to return x number of posts, but only if they have content or excerpt

Below is an example — tested and worked. The SQL query is: AND ({$wpdb->posts}.post_content != ” OR {$wpdb->posts}.post_excerpt != ”) And the example: <?php // This would be in functions.php or somewhere else where appropriate. function posts_where_require_content_or_excerpt( $where, $wp_query ) { global $wpdb; $where .= ” AND (” . ” {$wpdb->posts}.post_content != ”” . ” … Read more

How can i restore only Blogs from a SQL backup file?

“Blogs” or posts as they are called in WordPress are stored in the wp_posts table of your database. And custom fields related to your posts are stored in wp_postmeta table. So you should just be able to restore those two tables to get all your “Blogs”. This assumes your database is prefixed with wp_ of … Read more

SQL query to set posts in bulk based on the post content

Look into MySQL Wildcards. The correct MySQL Query for your search should be WHERE tb_posts.post_content LIKE “%example.com%” You should also be sure that you only target published posts (in contrast to nav_menu_items, revisions etc). Expand your WHERE with this: AND tb_posts.post_type IN (‘post’,’page’,*All Posttypes you use additionally*) AND tb_posts.post_status=”publish” So your complete Query should look … Read more

PHP -> SQL Query with Summing

Looking at this, I see that “Paid”, a string, isn’t in quotes. That would cause an error. You can add $wpdb->show_errors() and $wpdb->print_error() methods to reveal that, and any other mysql issues. Also when querying the database, you should use the $wpdb->prepare() method to escape and prepare your variables for query (yes $user->ID probably can’t … Read more

Deactivation Hook does not remove database

function my_plugin_remove_database() { global $wpdb; $db_table_name = $wpdb->prefix . ‘sandbox’; // table name $sql = “DROP TABLE IF EXISTS $db_table_name”; $rslt=$wpdb->query($sql); } register_deactivation_hook( __FILE__, ‘my_plugin_remove_database’ );