english

Cambiando el prefijo de tabla para WordPress

Publicado el 17 de Abril, 2007 a las 6:58am por Pi.
Categorías: WordPress.

Después de que descubriese que mi host no me daba bases de datos ilimitadas, pensé que debería optimizar el uso de bases de datos. Así que fui y cambié el prefijo de tabla de Wordpress, pensando en futuras expansiones de la base de datos que uso para WordPress (¿tal vez más blogs en el futuro?) Pero esto me dió algunos problemas que me costó resolver.

Cambiar el prefijo de tabla no fue tan simple, teniendo en cuenta cómo WordPress gestiona la información de usuario. Los pasos que hace falta dar para hacer esto son de hecho muy fáciles. El paso 1 es cambiar el prefijo de tabla en wp-config.php. Digamos que todavía tenemos el prefijo por defecto wp_. Así:
$table_prefix = 'wp_';
se convierte en
$table_prefix = 'wp_new_';

El paso 2 consiste en cambiar manualmente los nombres de tabla en tu base de datos. Usa tu herramienta favorita: MySQL Query Browser, phpMyAdmin, o ejecuta una petición SQL con un script PHP. El problema llega ahora, ya que se puede navegar por el sitio apropiadamente (ya que los prefijos tanto en wp-config.php como en la base de datos coinciden) pero no puedes administrar nada. Tan pronto como entres en el dominio de /admin/ en tu blog de WordPress, se muestra un mensaje: No tiene los permisos necesarios para acceder a esta página.

Busqué en Google, por supuesto, pero no encontré nada más que a otra gente teniendo mi mismo problema. Experimenté e intenté muchas cosas, pensando que tal vez WordPress tenía alguna clase de código de validación para que no se pudiesen cambiar las tablas tan fácilmente (aunque no entiendo para qué).

Al final tropecé con lo que parece un informe de bug de WordPress: Changing table prefix in wp-config doesn’t update database. No era realmente un informe de un fallo, pero me dio alguna pista. Después de ver que el informe fue rechazado ya que ellos creen que WordPress no necesita esta funcionalidad, empecé a seguir las sugerencias, descubriendo que estaban incompletas. Así que aquí está el tercer paso: cambiar manualmente algunos nombres de opciones.

Los detalles: alguna información de usuarios se salva en opciones que tienen el prefijo de tabla como parte del nombre de la opción. Estas opciones son:

  • Tabla xxxoptions
    • Opción xxxuser_roles
  • Tabla xxxusermeta
    • Opción xxxcapabilities
    • Opción xxxuser_level
    • Opción xxxautosave_draft_ids

La última opción no existe a no ser que hayas salvado borradores de artículos mientras los editabas, y es la parte no mencionada en el informe de bug original. Así que sólo necesitas cambiar los nombres de opciones, para que el antiguo prefijo de tabla se sustituya por el nuevo. Por lo que wp_user_roles se convierte en wp_new_user_roles.

Puedo imaginar un plugin para WordPress que pueda cambiar todos los prefijos de tabla y nombres de opciones por ti, si es que necesitas cambiar el prefijo de tabla en tu blog de WordPress ya instalado. Sin embargo, no voy a hacerlo yo, aunque debería ser sencillísimo…

Dicho todo esto, todavía no entiendo por qué WordPress usa el prefijo de tabla para la información de usuaro, no puede ser para no compartir información de usuaro entre blogs, ya que si cambias el prefijo de tabla, de todas maneras no puedes acceder a nada más… Bueno, de cualquier manera, espero que esta informacion te sea de ayuda.

17 comentarios.

Neerav

Comment on 2:59am.

Thanks a million for your instructions, once I was prepared i changed my WP table prefix in 3 minutes start to finish.

Quickly Change the WordPress MySQL Database Table Prefix < Rambling Thoughts Blog - Neerav Bhatt

Pingback on 3:29am.

[…] It took a while but I eventually found instructions at the Pi in the Sky Blog. […]

admin

Comment on 2:39pm.

It’s don’t works for WordPress 2.2.1: in this version you need also copy string from field ‘xx_user_roles’ from “clean” installation of WP (with needed prefix) to your working installation of WP.

Pi

Comment on 3:24pm.

I have not tried this method with 2.2.1 yet, when I update, I’ll check and update this information too.

Edit: you seem to have misunderstood the method I describe. I explain that you need to change the prefix of some option names too. You don’t need to copy xx_user_roles from a clean WP installation, you can keep your current user roles just changing the prefix of the already existing option. I’m sure that it will be the same in 2.2.1.

yongfook

Comment on 3:40am.

thanks for this tip! Just altered my prefix and couldn’t log in - this saved me from pulling out some hair :)

Philipp

Comment on 3:40pm.

Hi Pi,
I developed for BlogSecurity.org a plugin which does exactly what you covered with your post here. I got the post after some researches( after it initially didn’t work). And you saved me some time as I had normally would have to check all values within wp_tables for it. Anyway I would like to mention that it would be better to change xx_user_roles….and so on to xxuser_roles as, as well the _ can be a prefix for the table and isn’t needed( Or Am I on the wrong track?). And can you maybe tell me when the xx_user_level record is generated, as I couldn’t find it while working on the Plugin, is it maybe only created if your blog accepts User signups or multiple authors?

Pi

Comment on 8:36pm.

You’re not in the wrong track; the underscore usage slipped accidentally. I’ve edited the article to reflect that the underscore is not part of the option names, but of the prefix.

I thought of making a plugin, but honestly I am too lazy ^_^

Related to xx_user_level, I am not sure. I’d say it’s set when an user is first edited (as opposed to created). Look into ‘wp-includes/user.php’ to see some usage.

The Doctor What

Comment on 5:09pm.

I have added a bug to remove the column names using the $table_prefix.

http://trac.wordpress.org/ticket/4780

Pi

Comment on 8:56am.

That’s a sane decision, it’s a change that was needed for a long time.

juan

Comment on 8:00pm.

sencillamente genial, muchas gracias por una exposición tan sencilla y clara de un problema que nos ha dado muchos quebraderos de cabeza.

Wodpress-prefix, marknadsföringslänkar, tidningsprenumeration och ny jaktblogg — Jonny Elofsson

Pingback on 2:34pm.

[…] Har lagt ned lite tid nu på att förstå varför det ska vara så klurigt att ändra prefix på databastabellerna för en befintlig Wordpress-installation. Att ändra prefixet i tabellnamnet och i inställningsfilen wp-config.php skulle räcka trodde jag, men icke. Det fungerar för att siten ska se bra ut men det går inte att logga in som administratör. För detta måste man även ändra några inställningar i tabellerna [ev. prefix]_options och [ev.prefix]_usermeta. Läs vad som behöver ändras hos Pi in the Sky. […]

ND B

Comment on 11:15am.

Thanks! You saved me a lot of work!

Paulino Michelazzo

Comment on 9:52pm.

Great! Just a little detail to make me crazy. Thanks a lot for your info. Save my day ;-)

Best regards from Brazil

debswin

Comment on 7:54am.

I had my blog up and running but made the stupid, stupid mistake of going into settings and I changing the extension (”computer”) to “tech”. Once I realised it didn’t work, I went back and renamed the site extension to “computer” but my site is being directed to “tech” My front page page is showing up but without the theme (although the site says the theme is installed). When I click on a page, I get the 404 message.

Is my problem in the MySQL datbase? If so, how do I fix it? I am in big trouble because I need this site up and running in about 18 hours time.

Any help would be appreciated. It goes without saying that I am an idiot for changing the file name.

Thanks in advance.

Pi

Comment on 7:10pm.

I don’t know what you mean by “changing the extension” as it has been more than two years since I dwelled in the depths of wordpress. However I’d say that your problem is in the options table. Log into your database using phpmyadmin or whatever you have, and look there. Good luck.

Jeff

Comment on 12:33am.

Thanks for this, it set me in the right direction.

jc

Comment on 5:02am.

Thank you. Not sure what I did exactly but I changed some wp_ values to the new values and it worked. Thanks.

Dejar un comentario

Los comentarios pueden contener xhtml. Se requieren nombres y emails (los emails no se muestran), las url son opcionales.




Inseguramente seguro »« Inicio
Uno nunca debe ser esclavo de sus propias decisiones.  — Pi

Pi in the Sky funciona con WordPress. Vestido con Vistered Little. Alojado en MochaHost.