Archive matching Custom Field Value

Send Snippet To: Save this snippet to Code Collector Pro -- view all mihai2u's snippets
language: PHP
license: Other

Code for Snippet:

// Loads into the blog index template the value passed as a parameter after the CUSTOMVAR into it
  add_action('init', 'add_custom_meta_url');
  function add_custom_meta_url() {
    global $wp,$wp_rewrite;
    $wp_rewrite->flush_rules(false); // This should really be done in a plugin activation
// Matches CUSTOMFIELDNAME with CUSTOMVAR value. Works best for regular string custom fields
  add_action('parse_query', 'apply_custom_meta_to_query');
  function apply_custom_meta_to_query(&$query) {
    if (isset($query->query['rating'])) {
      $query->query_vars['meta_key'] = 'CUSTOMFIELDNAME';
      $query->query_vars['meta_value'] = $query->query['CUSTOMVAR'];
// For custom fields of type array - like a dropdown in Magic Fields, use a meta_compare of 'LIKE'
      $query->query_vars['meta_compare'] = 'LIKE';
Example usage:
3 posts have CUSTOMFIELDNAME custom field with a value of 'something'
will display all 3 posts in an index
comments powered by Disqus


Link to this snippet:

Download to Code Collector

To use the direct link to your snippet on either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 558
Date Added: 2014-04-22 11:20:25
Last Modified: 2014-06-10 06:59:33

Web Analytics