douchuanchai2793 2019-08-04 17:32
浏览 58
已采纳

Wordpress - 首先查询自定义帖子类型的名称

I want to query first and last name using custom post type metaboxes.

Code i am using:

$name = 'John Doe';

$args = array( 
    'post_type'     => 'customers',
    'post_status'   => array( 'publish', 'pending', 'draft' ),
    'numberposts'   => -1,
    'order'         => 'ASC',
    'orderby'       => 'meta_value',
    'meta_key'      => 'customer_first_name'
    'meta_query'    => array(
        'relation'      => 'OR',
        array(
            'key'           => 'customer_first_name',
            'value'         => $name,
            'compare'       => 'LIKE',
        ),
        array(
            'key'           => 'customer_last_name',
            'value'         => $name,
            'compare'       => 'LIKE',
        ),      
    ),  
);  

$customers = get_posts($args);

$num = count( $customers );

If i search only "John" results are showing up. If i search full name "John Doe" there are no results. Why is that?

  • 写回答

1条回答 默认 最新

  • douxun4860 2019-08-04 17:40
    关注

    Of course it's show no result because you don't split the name first name and last name.

    $name = 'John Doe';
    $parts = explode(" ", $name);
    $first_name = $parts[0];
    $last_name = (count($name) > 1) ? $name[count($name)-1]: $first_name;
    $args = array( 
        'post_type'     => 'customers',
        'post_status'   => array( 'publish', 'pending', 'draft' ),
        'numberposts'   => -1,
        'order'         => 'ASC',
        'orderby'       => 'meta_value',
        'meta_key'      => 'customer_first_name',
        'meta_query'    => array(
            'relation'      => 'OR',
            array(
                'key'           => 'customer_first_name',
                'value'         => $first_name,
                'compare'       => 'LIKE',
            ),
            array(
                'key'           => 'customer_last_name',
                'value'         => $last_name,
                'compare'       => 'LIKE',
            ),      
        ),  
    );  
    
    $customers = get_posts($args);
    
    $num = count( $customers );
    

    Like international name, if last name is blank then last name will use first name too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 请教一下c语言的代码里有一个地方不懂
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档