SlideShare a Scribd company logo
1 of 27
Download to read offline
Digging into WordPress
Custom Fields
Magdalena Paciorek
What are custom fields in WordPress?
How is metadata saved in the database?
wp_postmeta table
How to display metadata on a page?
get_post_meta()
https://developer.wordpress.org/reference/functions/get_post_meta/
<p>Release date:
<?php echo get_post_meta( get_the_ID(), 'release_date', true ); ?>
</p>
But what will happen if somebody adds a malicious script?
We need to escape before we echo
esc_html(), esc_attr(), esc_url(), esc_js()
https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/
<p>Release date:
<?php echo esc_html(get_post_meta( get_the_ID(), ‘release_date', true )); ?>
</p>
So the script can’t be executed any more
If we have a lot of metadata and we
call get_post_meta() function many
times on a page, does it mean we are
querying the database every time to
fetch the meta from the database?
WP Query
https://wordpress.tv/2014/11/15/helen-hou-sandi-so-you-know-wp_query-now-what/
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE post_type = 'post' AND
(post_status = 'publish' OR post_status = 'private') ORDER BY post_date DESC LIMIT 0, 10
SELECT FOUND_ROWS()
SELECT * FROM wp_posts WHERE ID IN (5,1)
SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt
ON t.term_id = tt.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id =
tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN
(1, 5) ORDER BY t.name ASC
SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id
IN (1,5) ORDER BY meta_id ASC
1
2
3
4
5
Object Cache
https://codex.wordpress.org/Class_Reference/WP_Object_Cache
get_post_meta() first checks for
meta in the cache. If it’s there, it
would retrieve it from cache.
If it’s not in cache, it sends a SQL
query to the database to fetch all
meta for given posts, updates cache
and then grabs the meta from cache.
We can turn off the meatadata query from WP Query
$args = array(
'update_post_meta_cache' => false
);
$query = new WP_Query( $args );
https://codex.wordpress.org/Class_Reference/WP_Query
Advanced Custom Fields
https://pl.wordpress.org/plugins/advanced-custom-fields/
How to display metadata added by ACF?
the_field(), get_field()
https://www.advancedcustomfields.com/resources/the_field/
<p>Release date:
<?php the_field( 'release_date' ); ?>
</p>
And what will happen if somebody adds a malicious script?
We should escape just like with get_post_meta()
esc_html(), esc_attr(), esc_url(), esc_js()
https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/
<p>Release date:
<?php echo esc_html( get_field( 'release_date' ) ); ?>
</p>
There is one more thing about the_field() i get_field()
Every time either of these functions is called, one extra SQL
query is being sent to the database.
Example:
SELECT post_id, meta_value
FROM wp_postmeta
WHERE meta_key = 'field_59ce9900201d9'
If we have 10 custom fields and we
call the_field() or get_field() function
10 times, we are sending 10
additional SQL queries to the
database.
So let’s improve it a little bit :)
just by changing the_field() to get_post_meta()
Before:
<p>Release date:
<?php echo esc_html( get_field( 'release_date' ) ); ?>
</p>
After:
<p>Release date:
<?php echo esc_html( get_post_meta( get_the_ID(), 'release_date', true ) ); ?>
</p>
Can we filter the posts by metadata?
WP Query - Custom Field Parameters
https://codex.wordpress.org/Class_Reference/WP_Query
Let’s say we want to display all reviews of movies directed by Woody Allen:
$args = array(
'meta_key' => 'directed_by',
'meta_value' => 'Woody Allen'
);
$query = new WP_Query( $args );
It is possible to query posts by
metadata. So why WordPress VIP
team considers avoiding querying
for meta_value in WP Query as a
good practice?
https://vip.wordpress.com/documentation/querying-on-meta_value/
WordPress postmeta table has an index on meta_key,
but not on meta_value
B-tree Structure
Markus Winand - http://use-the-index-luke.com/sql/anatomy/the-tree
We could construct WP Query in a 3 different ways
https://codex.wordpress.org/Class_Reference/WP_Query
1. //here we just query by meta_value which is not indexed
$query = new WP_Query( array( 'meta_value' => 'Woody Allen’ ) );
2. //here we query both by meta_key and meta_value, mysql can now use an index on
meta_key column
$query = new WP_Query( array( 'meta_key' => 'directed_by',
'meta_value' => 'Woody Allen’ ) );
3. //here we changed the way we use meta_keys which now hold an information about
the value, and we query only on meta_keys omitting meta_values completely
$query = new WP_Query( array( 'meta_key' => 'directed_by_woody_allen’ ) );
I’ve tested it on 15000 posts, each with 15 custom fields,
which sums up to over 200000 rows in wp_postmeta table
1. //1.53 s
$query = new WP_Query( array( 'meta_value' => 'Woody Allen’ ) );
2. //0.94 s
$query = new WP_Query( array( 'meta_key' => 'directed_by',
'meta_value' => 'Woody Allen’ ) );
3. //0.21 s
$query = new WP_Query( array( 'meta_key' => 'directed_by_woody_allen’ ) );
All 3 of them return the same results, but which one is the fastest?
A few useful links
https://codex.wordpress.org/Custom_Fields
https://metabox.io/optimizing-database-custom-fields/
https://wordpress.stackexchange.com/questions/16709/
meta-query-with-meta-values-as-serialize-arrays
https://wordpress.stackexchange.com/questions/215871/
explanation-of-update-post-meta-term-cache
https://tomjn.com/2017/02/27/not-post-meta-bad/
https://vip.wordpress.com/documentation/querying-on-meta_value/
Thank you!
Magdalena Paciorek
paciorek.magdalena@gmail.com
https://www.linkedin.com/in/paciorekmagdalena/
https://twitter.com/magda_paciorek

More Related Content

What's hot

Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 
feature toggles for ops
feature toggles for opsfeature toggles for ops
feature toggles for opsBram Vogelaar
 
Database presentation
Database presentationDatabase presentation
Database presentationwebhostingguy
 
Hands-on Lab: Migrating Oracle to PostgreSQL
Hands-on Lab: Migrating Oracle to PostgreSQL Hands-on Lab: Migrating Oracle to PostgreSQL
Hands-on Lab: Migrating Oracle to PostgreSQL Amazon Web Services
 
Creating a wanos vm on azure
Creating a wanos vm on azureCreating a wanos vm on azure
Creating a wanos vm on azurewanosnetworks
 
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안HyungTae Lim
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
 
Sql injection presentation
Sql injection presentationSql injection presentation
Sql injection presentationZara Joe
 
How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...Prancer Io
 
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)Loz Calver
 
Hands-on Lab: re-Modernize - Updating and Consolidating MySQL
Hands-on Lab: re-Modernize - Updating and Consolidating MySQLHands-on Lab: re-Modernize - Updating and Consolidating MySQL
Hands-on Lab: re-Modernize - Updating and Consolidating MySQLAmazon Web Services
 

What's hot (20)

Zend
ZendZend
Zend
 
Django
DjangoDjango
Django
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
feature toggles for ops
feature toggles for opsfeature toggles for ops
feature toggles for ops
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Hands-on Lab: Migrating Oracle to PostgreSQL
Hands-on Lab: Migrating Oracle to PostgreSQL Hands-on Lab: Migrating Oracle to PostgreSQL
Hands-on Lab: Migrating Oracle to PostgreSQL
 
Creating a wanos vm on azure
Creating a wanos vm on azureCreating a wanos vm on azure
Creating a wanos vm on azure
 
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Sql injection presentation
Sql injection presentationSql injection presentation
Sql injection presentation
 
Mule caching strategy with redis cache
Mule caching strategy with redis cacheMule caching strategy with redis cache
Mule caching strategy with redis cache
 
How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...How to use prancer to detect and fix the azure sql resources which uses tls v...
How to use prancer to detect and fix the azure sql resources which uses tls v...
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Cake php
Cake phpCake php
Cake php
 
lab56_db
lab56_dblab56_db
lab56_db
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Hands-on Lab: re-Modernize - Updating and Consolidating MySQL
Hands-on Lab: re-Modernize - Updating and Consolidating MySQLHands-on Lab: re-Modernize - Updating and Consolidating MySQL
Hands-on Lab: re-Modernize - Updating and Consolidating MySQL
 
Progressive What Apps?
Progressive What Apps?Progressive What Apps?
Progressive What Apps?
 

Similar to Digging into WordPress custom fields - WordCamp Brno 2017

Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
Things to keep in mind while creating a word press plugin from scratch
Things to keep in mind while creating a word press plugin from scratchThings to keep in mind while creating a word press plugin from scratch
Things to keep in mind while creating a word press plugin from scratchElsner Technologies Pvt Ltd
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Paul Bearne
 
WordPress Plugins: ur doin it wrong
WordPress Plugins: ur doin it wrongWordPress Plugins: ur doin it wrong
WordPress Plugins: ur doin it wrongWill Norris
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress PluginWill Norris
 
WordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkExove
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress WebsitesKyle Cearley
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012l3rady
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationMasashi Shibata
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Mike Schinkel
 
Wordpress plugin development tips
Wordpress plugin development tipsWordpress plugin development tips
Wordpress plugin development tipsMindfire Solutions
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Getting Started With WordPress Development
Getting Started With WordPress DevelopmentGetting Started With WordPress Development
Getting Started With WordPress DevelopmentAndy Brudtkuhl
 

Similar to Digging into WordPress custom fields - WordCamp Brno 2017 (20)

Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Things to keep in mind while creating a word press plugin from scratch
Things to keep in mind while creating a word press plugin from scratchThings to keep in mind while creating a word press plugin from scratch
Things to keep in mind while creating a word press plugin from scratch
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
WordPress Plugins: ur doin it wrong
WordPress Plugins: ur doin it wrongWordPress Plugins: ur doin it wrong
WordPress Plugins: ur doin it wrong
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
 
WordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a Framework
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
Wordpress plugin development tips
Wordpress plugin development tipsWordpress plugin development tips
Wordpress plugin development tips
 
New PHP Exploitation Techniques
New PHP Exploitation TechniquesNew PHP Exploitation Techniques
New PHP Exploitation Techniques
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Getting Started With WordPress Development
Getting Started With WordPress DevelopmentGetting Started With WordPress Development
Getting Started With WordPress Development
 
Optimizing wp
Optimizing wpOptimizing wp
Optimizing wp
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 

Recently uploaded

ETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxNIMMANAGANTI RAMAKRISHNA
 
Unidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxUnidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxmibuzondetrabajo
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Company Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxCompany Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxMario
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119APNIC
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
TRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxTRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxAndrieCagasanAkio
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 

Recently uploaded (11)

ETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptx
 
Unidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxUnidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptx
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Company Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxCompany Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptx
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
TRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxTRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptx
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 

Digging into WordPress custom fields - WordCamp Brno 2017

  • 1. Digging into WordPress Custom Fields Magdalena Paciorek
  • 2. What are custom fields in WordPress?
  • 3. How is metadata saved in the database? wp_postmeta table
  • 4. How to display metadata on a page? get_post_meta() https://developer.wordpress.org/reference/functions/get_post_meta/ <p>Release date: <?php echo get_post_meta( get_the_ID(), 'release_date', true ); ?> </p>
  • 5. But what will happen if somebody adds a malicious script?
  • 6. We need to escape before we echo esc_html(), esc_attr(), esc_url(), esc_js() https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/ <p>Release date: <?php echo esc_html(get_post_meta( get_the_ID(), ‘release_date', true )); ?> </p>
  • 7. So the script can’t be executed any more
  • 8. If we have a lot of metadata and we call get_post_meta() function many times on a page, does it mean we are querying the database every time to fetch the meta from the database?
  • 9. WP Query https://wordpress.tv/2014/11/15/helen-hou-sandi-so-you-know-wp_query-now-what/ SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE post_type = 'post' AND (post_status = 'publish' OR post_status = 'private') ORDER BY post_date DESC LIMIT 0, 10 SELECT FOUND_ROWS() SELECT * FROM wp_posts WHERE ID IN (5,1) SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN (1, 5) ORDER BY t.name ASC SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (1,5) ORDER BY meta_id ASC 1 2 3 4 5
  • 11. get_post_meta() first checks for meta in the cache. If it’s there, it would retrieve it from cache. If it’s not in cache, it sends a SQL query to the database to fetch all meta for given posts, updates cache and then grabs the meta from cache.
  • 12. We can turn off the meatadata query from WP Query $args = array( 'update_post_meta_cache' => false ); $query = new WP_Query( $args ); https://codex.wordpress.org/Class_Reference/WP_Query
  • 14. How to display metadata added by ACF? the_field(), get_field() https://www.advancedcustomfields.com/resources/the_field/ <p>Release date: <?php the_field( 'release_date' ); ?> </p>
  • 15. And what will happen if somebody adds a malicious script?
  • 16. We should escape just like with get_post_meta() esc_html(), esc_attr(), esc_url(), esc_js() https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/ <p>Release date: <?php echo esc_html( get_field( 'release_date' ) ); ?> </p>
  • 17. There is one more thing about the_field() i get_field() Every time either of these functions is called, one extra SQL query is being sent to the database. Example: SELECT post_id, meta_value FROM wp_postmeta WHERE meta_key = 'field_59ce9900201d9'
  • 18. If we have 10 custom fields and we call the_field() or get_field() function 10 times, we are sending 10 additional SQL queries to the database.
  • 19. So let’s improve it a little bit :) just by changing the_field() to get_post_meta() Before: <p>Release date: <?php echo esc_html( get_field( 'release_date' ) ); ?> </p> After: <p>Release date: <?php echo esc_html( get_post_meta( get_the_ID(), 'release_date', true ) ); ?> </p>
  • 20. Can we filter the posts by metadata? WP Query - Custom Field Parameters https://codex.wordpress.org/Class_Reference/WP_Query Let’s say we want to display all reviews of movies directed by Woody Allen: $args = array( 'meta_key' => 'directed_by', 'meta_value' => 'Woody Allen' ); $query = new WP_Query( $args );
  • 21. It is possible to query posts by metadata. So why WordPress VIP team considers avoiding querying for meta_value in WP Query as a good practice? https://vip.wordpress.com/documentation/querying-on-meta_value/
  • 22. WordPress postmeta table has an index on meta_key, but not on meta_value
  • 23. B-tree Structure Markus Winand - http://use-the-index-luke.com/sql/anatomy/the-tree
  • 24. We could construct WP Query in a 3 different ways https://codex.wordpress.org/Class_Reference/WP_Query 1. //here we just query by meta_value which is not indexed $query = new WP_Query( array( 'meta_value' => 'Woody Allen’ ) ); 2. //here we query both by meta_key and meta_value, mysql can now use an index on meta_key column $query = new WP_Query( array( 'meta_key' => 'directed_by', 'meta_value' => 'Woody Allen’ ) ); 3. //here we changed the way we use meta_keys which now hold an information about the value, and we query only on meta_keys omitting meta_values completely $query = new WP_Query( array( 'meta_key' => 'directed_by_woody_allen’ ) );
  • 25. I’ve tested it on 15000 posts, each with 15 custom fields, which sums up to over 200000 rows in wp_postmeta table 1. //1.53 s $query = new WP_Query( array( 'meta_value' => 'Woody Allen’ ) ); 2. //0.94 s $query = new WP_Query( array( 'meta_key' => 'directed_by', 'meta_value' => 'Woody Allen’ ) ); 3. //0.21 s $query = new WP_Query( array( 'meta_key' => 'directed_by_woody_allen’ ) ); All 3 of them return the same results, but which one is the fastest?
  • 26. A few useful links https://codex.wordpress.org/Custom_Fields https://metabox.io/optimizing-database-custom-fields/ https://wordpress.stackexchange.com/questions/16709/ meta-query-with-meta-values-as-serialize-arrays https://wordpress.stackexchange.com/questions/215871/ explanation-of-update-post-meta-term-cache https://tomjn.com/2017/02/27/not-post-meta-bad/ https://vip.wordpress.com/documentation/querying-on-meta_value/