I need a function to check if post_content already exist in database.
Wordpress built in function post_exists() checks by post post_title.
I need to check by post_content regardless of the post_title.
There such a function exist?
How can I solve this?
Thank you for your help
It looks like a small variation on post_exists() should work. Create a function like this in your child theme's functions.php, and then use it instead of post_exists():
function post_exists_by_content($content) {
global $wpdb;
$post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
$query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
$args = array();
if ( !empty ( $content ) ) {
$query .= ' AND post_content = %s';
$args[] = $post_content;
}
if ( !empty ( $args ) )
return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
return 0;
}
Related
I am working on a website that is more of a search directory and haven't been able to find a clear answer on how to automatically create pretty links from long URL's with multiple query parameters (Wordpress).
For example, if the link looks like this: website.com/search/search-results/?address=98101,+seattle,+washington&contractor=plumber&latitude=1234&longitude=9876&filter=20&order=distance
Is there a way to make it look like this: website.com/search/search-results/98101/seattle/washington/plumber/
automatically without having to go through every link and the new pretty link will show the same page as the page with all of the query parameters?
Thanks in advance, I've been trying to figure this out all day and it's not my strong point...
Really interesting and quite technical question.
The following is not production ready. It is a working proof of concept.
I'm just pondering here. You could create a new Table (see Creating Tables with Plugins with a requested_url key and a shortened_url value. The whole system would be based on that approach.
First we creates a custom table in the database, if it doesn’t already exist. This table will be used to store our urls.
<?php
add_action( 'after_switch_theme', function () {
global $wpdb;
$table_name = $wpdb->prefix . 'wpso74035985';
$charset_collate = $wpdb->get_charset_collate();
$create_ddl = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
requested_url varchar(55) DEFAULT '' NOT NULL,
shortened_url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
maybe_create_table( $table_name, $create_ddl );
} );
We could then retrieve the requested url by parsing the $_SERVER['QUERY_STRING'] and verifying the url integrity through get_query_var() as it only retrieves public query variables that are recognized by WP_Query.
We would then search the table for the requested url, and if it doesn't already exist, set a new key pair value.
<?php
add_action( 'pre_get_posts', function ( $wp_query ) {
if ( ! is_admin() && $wp_query->is_main_query() ) {
if ( $wp_query->is_search() ) {
global $wp;
parse_str( filter_input( INPUT_SERVER, 'QUERY_STRING', FILTER_SANITIZE_STRING ), $variables );
$buffer = array();
foreach ( $variables as $variable => $value ) {
if ( get_query_var( $variable ) ) {
array_push( $buffer, array( $variable => $value ) );
};
};
$buffer = array_reduce( $buffer, 'array_merge', array() );
$requested_url = esc_url_raw( add_query_arg( $buffer, home_url( $wp->request ) ) );
global $wpdb;
$table_name = $wpdb->prefix . 'wpso74035985';
$results = $wpdb->get_results(
"SELECT * FROM $table_name"
);
$needle_key = array_search( $requested_url, array_column( $results, 'requested_url' ) );
if ( $needle_key === false ) {
$shortened_url = str_shuffle( base64_encode( random_bytes( 100 ) ) );
$shortened_url = preg_replace( '/\W/s', '', $shortened_url );
$shortened_url = substr( $shortened_url, 0, 7 );
$wpdb->insert(
$table_name,
array(
'requested_url' => sanitize_url( $requested_url ),
'shortened_url' => sanitize_url( home_url( $shortened_url ) ),
)
);
};
};
};
} );
There is no real science here, the $shortened_url is just a 7 bytes alpha numerical string (Why 7? Bit.ly a famous shortener is using 7 characters).
Through the template_redirect hook, we could check the shortened url against our table and redirect based on that.
<?php
add_action( 'template_redirect', function () {
if ( is_404() ) {
global $wp;
$shortened_url = home_url( $wp->request );
global $wpdb;
$table_name = $wpdb->prefix . 'shortener';
$results = $wpdb->get_results(
"SELECT * FROM $table_name"
);
$needle_key = array_search( $shortened_url, array_column( $results, 'shortened_url' ) );
if ( $needle_key !== false ) {
$location = $results[$needle_key]->requested_url;
wp_safe_redirect( $location );
exit();
};
};
} );
As we're checking for a 404 through is_404() first (pretty much limiting the number of empty request), you should also include a 404.php to your root.
On the front end you can access your table through
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'wpso74035985';
$results = $wpdb->get_results(
"SELECT * FROM $table_name"
);
var_dump( $results );
Now, a few thing to understand before you go to production with this, even tho we're generating a pseudo random string through random_bytes() and base64_encode() they're not actually fully randomized, so you could end up with a problem at some point where two shortened url are the same. You could do a while loop and constantly check if that shortened url already exist before using it.
You would also want to restrict the search query as much as you can to improve performance on the long term.
You might want also to add an expiry date.
I ran into the issue that woocommerce product search in admin not working and giving result as No product found though there are lots of products with my search input.
Also i haven't used relevancy search plugin so there will be no any issue.
I set debug true in wp-congig.php and its throwing one error related to wp_meta with printing whole query.
Also tried disable theme and try with default theme also tried to disable every plugin one by one but still no luck.
I was experiencing the same thing and adding the following code block to my functions.php file fixed it immediately:
function m_request_query( $query_vars ) {
global $typenow;
global $wpdb;
global $pagenow;
if ( 'product' === $typenow && isset( $_GET['s'] ) && 'edit.php' === $pagenow ) {
$search_term = esc_sql( sanitize_text_field( $_GET['s'] ) );
// Split the search term by comma.
$search_terms = explode( ',', $search_term );
// If there are more terms make sure we also search for the whole thing, maybe it's not a list of terms.
if ( count( $search_terms ) > 1 ) {
$search_terms[] = $search_term;
}
// Cleanup the array manually to avoid issues with quote escaping.
array_walk( $search_terms, 'trim' );
array_walk( $search_terms, 'esc_sql' );
$meta_key = '_sku';
$post_types = array( 'product', 'product_variation' );
$query = "SELECT DISTINCT posts.ID as product_id, posts.post_parent as parent_id FROM {$wpdb->posts} posts LEFT JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id WHERE postmeta.meta_key = '{$meta_key}' AND postmeta.meta_value IN ('" . implode( "','", $search_terms ) . "') AND posts.post_type IN ('" . implode( "','", $post_types ) . "') ORDER BY posts.post_parent ASC, posts.post_title ASC";
$search_results = $wpdb->get_results( $query );
$product_ids = wp_parse_id_list( array_merge( wp_list_pluck( $search_results, 'product_id' ), wp_list_pluck( $search_results, 'parent_id' ) ) );
$query_vars['post__in'] = array_merge( $product_ids, $query_vars['post__in'] );
}
return $query_vars;
}
add_filter( 'request', 'm_request_query', 20 );
Shout-out to mircian for the snippet.
I'm developing wordpress plugin.
I need to find out post_id from thumbnail_id(not reverse !).
How can I do this?
You can get result by this code
global $wpdb;
$_thumbnail_id = {thumbnail id};
$sql = "SELECT `post_id` FROM `wp_postmeta` WHERE `meta_value` = $_thumbnail_id";
$result = $wpdb->get_results( $sql, ARRAY_A );
//access first returned post id
var_dump($result[0]['post_id']);
If you added same image for multiple posts there will be multiple returns.
You can use get_the_ID() to get the post id. You can find this function in wp-includes/post-template.php
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
My code was working properly, but accidentally I deleted something, but I don't remember what. At this moment my plugin display only one, last user. Before everything was ok and plugin could display all users. Do you have any ideas? Thanks in advance
function my_count_posts_by_user(){
global $wpdb;
$result = count_users();
$total_users = $result['total_users'];
for($id = 1;$id<=$total_users;$id++){
$result = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, COUNT(wp_posts.post_author) AS 'Number_of_posts' FROM wp_users INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author WHERE wp_posts.post_type = 'post' AND wp_users.ID = $id AND wp_posts.post_status = 'publish'" , ARRAY_A);
}
echo '<table>';
foreach ($result as $x){
echo'<tr>';
echo'<td>'.'ID: '. $x['ID']."</td>";
echo'<td>'.'User : '. $x['display_name'].'</td>';
echo'<td>'.'Number of posts :'. $x['Number_of_posts'].'</td>';
echo'</tr>';
}
echo '</table>';
echo '<br>';
I think you should use WP API functions which will do everything for you.
get_users() function will get all users data just define fields which u require.
get_user_meta() function will get user meta data.
A small example
$users = get_users( array( 'fields' => array( 'ID' ) ) );
foreach( $users as $user_id ) {
print_r( get_user_meta( $user_id->ID ) );
}
Try this code:
function my_count_posts_by_user(){
global $wpdb;
$result = count_users();
$total_users = $result['total_users'];
for($id = 1;$id<=$total_users;$id++){
$result = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, COUNT(wp_posts.post_author) AS 'Number_of_posts' FROM wp_users INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author WHERE wp_posts.post_type = 'post' AND wp_users.ID = $id AND wp_posts.post_status = 'publish'" , ARRAY_A);
echo '<table>';
foreach ($result as $x){
echo'<tr>';
echo'<td>'.'ID: '. $x['ID']."</td>";
echo'<td>'.'User : '. $x['display_name'].'</td>';
echo'<td>'.'Number of posts :'. $x['Number_of_posts'].'</td>';
echo'</tr>';
}
echo '</table>';
echo '<br>';
}
}
I want to update a meta value with a specific meta key out of wordpress page. What I want is that, multiplying a meta value with a variable then write the result to another meta value.
for example;
$var=5
meta_key|meta_value
key-1 |10
key-2 |20
the meta_value for the key-1 = 100 (key-2 * $var). I have tried below code to retrieve key-1 but it returns nothing.
require_once("wp-load.php");
function wp_update_value( ) {
global $wpdb;
$mylink = $wpdb->get_results("
SELECT $wpdb->postmeta.meta_value
FROM $wpdb->postmeta
WHERE $wpdb->postmeta.meta_key = 'key-1'",
ARRAY_A);
$array = unserialize($mylink);
return $array;
}
How can I get two meta values by meta keys and update them for all posts?
You can do it inside a loop, something like:
<?php
header('Response: HTTP/1.1 200 OK');
define('WP_USE_THEMES', false);
require('../../../../wp-load.php');
$args = array(
'posts_per_page' => '-1',
);
$the_query = new WP_Query( $args );
$var = 5;
if ( $the_query->have_posts() ){
while ( $the_query->have_posts() ) : $the_query->the_post();
$value = 100 * (get_post_meta(get_the_ID(),'key-2',true) * $var);
update_post_meta(get_the_ID(), 'key-1', $value);
endwhile;
}
?>