我正在存储CPTproducts\' 将ID发布到CPT中companies\' post meta(meta\\U键=prefix_products). 因为一个公司可以有多个产品,所以我将它们存储到PHP序列化数组值中。
s:48:"a:3:{i:0;s:3:"334";i:1;s:3:"333";i:2;s:3:"331";}";
 其中334、333、331是post类型的三个post\\U ID
products.
我需要获取CPT的post\\u idcompanies 其中产品id(CTP的post\\U idproducts) 等于331(动态-可以是任何值)。它应该与meta\\u键的meta\\u值进行比较prefix_products.
我可以使用meta\\u值获取post\\u id,但我无法将数据存储为序列化数据(
到目前为止,我所做的还没有找到解决方案:
function get_company_of_the_product( $product_id ) {
    global $project_prefix;
    $prod_meta_key = $project_prefix .\'products\';
    $companies = get_posts( array(
            \'post_type\'     => \'companies\',
            \'post_status\'   => \'publish\',
            \'meta_key\'      => $prod_meta_key
        ) );
    $products_array = array();
    foreach ( $companies as $company ) {
        $products = get_post_meta( $company->ID, $prod_meta_key, true );
        $products_array[$company->ID] = unserialize( $products );
        //if( in_array( $product_id, $products_array ) ) return $company->ID; //I know it\'s wrong
    }
    var_dump($products_array);
}
 是这样,还是我错过了一些很容易的事情?我怎样才能解开这个谜语?
 
                    最合适的回答,由SO网友:websupporter 整理而成
                    我强烈建议将产品分开,不要将它们全部放在一个阵列中。或者甚至创建一个分类公司,但这更多的是根据当时的设计,可能是个坏主意。尽管如此,这是一个很好的问题要解决,所以让我们玩吧。
所以\'prefix_products\' 元密钥始终是一系列产品。现在,您需要所有销售具有特定ID的产品的公司。
这应该可以做到:
function get_all_companies_selling( $product_id ){
    global $wpdb;
    $sql = "select post_id from " . $wpdb->prefix . "postmeta where
        meta_key = \'prefix_products\' &&
        meta_value like \'%%%s%%\'";
    $product_id = \'s:\' . strlen( $product_id ) . \':"\' . (int) $product_id . \'";\';
    $sql = $wpdb->prepare( $sql, $product_id );
    $res = $wpdb->get_results( $sql );
    return $res;
}
get_all_companies_selling( 331  );
 
                
                
                SO网友:Slam
                这是很有可能的,尽管可能很慢。它本质上是一种反向关系搜索,常见于高级自定义字段或用于关系的任何其他自定义字段。
下面将不仅获取ID,还通过WP\\u查询返回一个posts对象数组。
$some_product_id = \'123\';
$args= array(
  \'post_type\' => \'companies\',  // only search postmeta of these cpts
  \'posts_per_page\' => 5,  // limit or not depending on your use
  \'orderby\' => \'date\',  // use whatever order you like
  \'meta_query\' => array(
    array(
    \'key\' => \'prefix_products\', // name of custom field
    \'value\' => \'"\' . $some_product_id . \'"\', // matches exactly "123" not just 123.
    \'compare\' => \'LIKE\'
  )
);
$the_related_companies = new WP_Query( $args );
if( $the_related_companies->have_posts() ) :
  <div class="container">
  while( $the_related_companies->have_posts() ) :
    [do stuff with your posts]
  endwhile;
  </div>
endif;
 (请原谅我的PHP,我一直在Blade中工作,很难回头)