Please tell me how in MySql for Wordpress in the wp_posts table in the post_title field replace everything after the "-" sign.

For example, the value of the post_title field:

"Buy a phone - Sony in Moscow"

It is necessary to delete everything after the "-" sign, so that only "Buy a phone -" remains

Thanks in advance.

  • Thanks a lot, everyone. Problem solved. - Ruslan Bagrovsky
  • If solved - it is worth noting the issue resolved - SeVlad

4 answers 4

well, for example

LEFT(field, 1 + INSTR(field, '-')) 

or say

 CONCAT(SUBSTRING_INDEX(field, '-', 1), '-') 

Well, a few more options ...

The main thing is not to forget to handle the case when there is no dash in the field (in the variants where it is critical) ...

  • Thank you, your answer was the most practical to use. - Ruslan Bagrovsky

Add to functions.php

 function update_posts() { $current_user = wp_get_current_user(); if ( 'admin' !== $current_user->user_login ) { return; } $args = array( 'numberposts' => - 1, 'post_type' => 'post', ); $post_count = 0; $post_processed = 0; $posts = get_posts( $args ); foreach ( $posts as $post ) { $post_count ++; $title = $post->post_title; $pos = mb_strpos( $title, '-' ); if ( false !== $pos ) { $post->post_title = mb_substr( $title, 0, $pos + 1 ); wp_update_post( $post ); $post_processed ++; } } echo 'Count: ' . $post_count . ', processed: ' . $post_processed; } add_action ('init', 'update_posts'); 

and update any page of the site once, being registered under admin . Or correct in the admin code to your administrator login.

Then remove this code.

  • one
    +1 Well, at least you are the hope and support of newbies :) But it would be worthwhile to add about the mass of existing search-replace plug-ins with regulars. or famous script. A one-time operation. - SeVlad 7:37 pm
  • @SeVlad about plugins you better write)) - KAGG Design
  • Ehhh. Persuaded :) - SeVlad

Preamble
In the case of VP - no need to touch the base. It is necessary to forget about it to the fullest understanding of VP.
To change something (whether in the database, logic, etc.) you need to use the API .


Specifically on this issue.
For making one-time changes to the base there is a mass of ready-made plug-ins (disposable). Including and with the support of the regulars.
For example https://wordpress.org/plugins/search-regex/
https://wordpress.org/plugins/search-and-replace/
https://wordpress.org/plugins/better-search-replace/
and many others .

There is also a wonderful script .

And who still suffers from plagiophobia - see the answer KAGG Design :)

     UPDATE wp_posts JOIN wp_posts p2 ON p1.id = p2.id SET wp_posts.post_title = SUBSTRING(p2.post_title, 1, POSITION('-' IN p2.post_title)) WHERE wp_posts.post_title LIKE '%-%';