从WordPress META_VALUE获取特定值

时间:2022-02-18 作者:Pardeep Kumar

a:1:{s:9:"toys_item";a:1:{s:16:"toys_item_ranger";a:11:{i:0;s:31:"2 x Seadoo GTX 230/IBR Jet-Skis";i:1;s:30:"1 x HD Runway 10′ Waterslide";i:2;s:14:"4 x F5 Seabobs";i:3;s:49:"3 x Water-Skis for children, teenagers and adults";i:4;s:43:"1 x 2 Person Nereus Kayak w/paddles & seats";i:5;s:14:"1 x Wake Board";i:6;s:35:"2 x Jobe Parana bamboo Paddleboards";i:7;s:44:"Seadoo Spark 900HO AXE 2UP/IBR Trixx Jet-Ski";i:8;s:31:"2 x Seadoo GTX 230/IBR Jet-Skis";i:9;s:14:"4 x F5 Seabobs";i:10;s:43:"1 x 2 Person Nereus Kayak w/paddles & seats";}}}

I want to show specific text from the above results, something like this:

2 x Seadoo GTX 230/IBR Jet-Skis
1 x HD Runway 10′ Waterslide
4 x F5 Seabobs
3 x Water-Skis for children, teenagers, and adults1 x 2 Person Nereus Kayak w/paddles & seats
1 x Wake Board
2 x Jobe Parana bamboo Paddleboards
Seadoo Spark 900HO AXE 2UP/IBR Trixx Jet-Ski
2 x Seadoo GTX 230/IBR Jet-Skis
4 x F5 Seabobs
1 x 2 Person Nereus Kayak w/paddles & seats

here is my code

<?php
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM wp_postmeta where meta_key = \'fat-mb-boat-toys\' AND post_id = $post_id"); // Query to fetch data from database table and storing in $results
if(!empty($results))
    // Checking if $results have some values or not
{    
        echo "<table>";
        echo "<tr>";
        echo "<th> Post ID <th>";
        echo "<th> Meta Key <th>";
        echo "<th> Meta Value <th>";
        echo "</tr>";

    foreach($results as $row){
       echo "<tr>";
       echo "<td>". $row->post_id ."<td>";
       echo "<td>". $row->meta_key ."<td>";
       echo "<td>". $row->meta_value ."<td>";
       echo "</tr>";
    }
        echo "<table>";


}
?> ```
1 个回复
SO网友:Pat J

你应该永远不需要使用$wpdb 获取数据。WordPress中内置了一些帮助函数,可以满足您的需要。

在这种情况下,使用get_post_meta().

使用过https://www.unserialize.com/ 要取消序列化数据,问题中的项目列表似乎位于$meta[\'toys_item\'][\'toys_item_ranger\']. 我将在我的代码片段中使用它来创建一个类似于您要查找的列表。

$meta = get_post_meta( $post_id, \'fat-mb-boat-toys\', true );
if (
    ! empty( $meta )
    && ! empty( $meta[\'toys_item\'] )
    && ! empty( $meta[\'toys_item\'][\'toys_item_ranger\'] ) 
) {
    foreach ( $meta[\'toys_item\'][\'toys_item_ranger\'] as $toy ) {
        echo $toy . \'<br />\';
    }
}