PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 15, 2022

[FIXED] Wordpress SQL Select Multiple Meta Values / Meta Keys / Custom Fields

 January 15, 2022     mysql, php, phpmyadmin, wordpress     No comments   

Issue

I am trying to modify a wordpress / MySQL function to display a little more information. I'm currently running the following query that selects the post, joins the 'postmeta' and gets the info where the meta_key = _liked

    function most_liked_posts($numberOf, $before, $after, $show_count) {
 global $wpdb;

    $request = "SELECT ID, post_title, meta_value FROM $wpdb->posts, $wpdb->postmeta";
    $request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
    $request .= " AND post_status='publish' AND post_type='post' AND meta_key='_liked' ";
    $request .= " ORDER BY $wpdb->postmeta.meta_value+0 DESC LIMIT $numberOf";
    $posts = $wpdb->get_results($request);

    foreach ($posts as $post) {
     $post_title = stripslashes($post->post_title);
     $permalink = get_permalink($post->ID);
     $post_count = $post->meta_value;

     echo $before.'<a href="' . $permalink . '" title="' . $post_title.'" rel="nofollow">' . $post_title . '</a>';
  echo $show_count == '1' ? ' ('.$post_count.')' : '';
  echo $after;
    }
}

The important part being: $post_count = $post->meta_value;

But now I want to also grab a value that is attached to each post called wbphoto

How do I specify that $post_count = _liked and $photo = wbphoto

?

Here is a screen cap of my Phpmyadmin alt text


Solution

The SQL will look very ugly.

// Your Meta key names
    $metas = array(
        '_liked', '_another1'
    );

    foreach ($metas as $i=>$meta_key) {
        $meta_fields[] = 'm' . $i . '.meta_value as ' . $meta_key;
        $meta_joins[] = ' left join ' . $wpdb->postmeta . ' as m' . $i . ' on m' . $i . '.post_id=' . $wpdb->posts . '.ID and m' . $i . '.meta_key="' . $meta_key . '"';
    }
    $request = "SELECT ID, post_title, " .  join(',', $meta_fields) . " FROM $wpdb->posts ";
    $request .=  join(' ', $meta_joins);
    $request .= " WHERE post_status='publish' AND post_type='post'";
    $request .= " LIMIT $numberOf";

It will be better of making another SQL to retrieve meta themselves.



Answered By - Darkerstar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing