【问题标题】:WordPress Custom Query for Taxonomy分类学的 WordPress 自定义查询
【发布时间】:2016-01-14 14:25:56
【问题描述】:

我必须编辑某人的代码,但我不熟悉使用他们的方法查询帖子。我尝试将查询编辑为各种替代方案,但是我没有运气。我想更改以下查询以从名为“job_cat”的自定义分类法中选择数据,其中值等于 POST 值。代码如下:

$querystr = "
SELECT DISTINCT wposts.*
FROM $wpdb->posts wposts
LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id
LEFT JOIN $wpdb->postmeta wpostmeta2 ON wposts.ID = wpostmeta2.post_id
LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE wp_term_taxonomy.term_id = 94";
// If a job type is set and not equal to nothing or any jobs


if(isset($_POST['search-location']) && $_POST['search-location'] !== "" &&     $_POST['search-location'] !== "All") {
    $querystr .= " AND (wpostmeta2.meta_key = 'region' AND wpostmeta2.meta_value     = '".$_POST['search-location']."')";
}
    $querystr .= " ORDER BY post_date DESC LIMIT 50";

//Execute
//echo $querystr;
$pageposts = $wpdb->get_results($wpdb->prepare($querystr, OBJECT));

任何帮助都会很棒!

【问题讨论】:

  • 警告: 您的代码容易受到 SQL 注入攻击!阅读 Bobby Tables 的故事了解更多信息。
  • 我想你使用自定义查询,而不是 WP_Query 类。您能确认wpostmeta 是您的表的名称吗?
  • 查询字符串的其余部分在哪里?您在AND 之前没有分享过该部分。
  • @mevius 我已经添加了其余的代码,谢谢!
  • 这是 100% 错误的——不要在你的 PHP 中做 SQL 的事情。您需要使用 WP 功能。

标签: mysql sql wordpress post


【解决方案1】:

在生产 WordPress 站点中使用此代码非常危险。您需要删除它以及任何其他包含此类 SQL 查询的模板文件。

改为使用WP_Query,它会自动清理您的 SQL 请求。它有大量的参数,你可以设置它来从 WordPress 查询任何东西。下面是一个使用WP_Query 获取给定分类的帖子的示例,使用tax_query

<?php
// 1- Setup an argument to give to WP_Query
$taxonomy_args = array(
  // 2- use the tax_query to examine a taxonomy
  'tax_query' => array(
     array(
        'taxonomy' => 'job_cat',
        'terms' => 'XYZ',
        'field' => 'slug',
        'include_children' => true,
        'operator' => 'IN'
     )
  ),
  // 3- Make sure to define how many posts and what post-type they should be
  'posts_per_page' => 50,
  'post_type' => 'search-location',
);

$s = new WP_Query( $some_args );

if ( $s->have_posts() ) : $s->the_post();
    // 4- Here you will manipulate the data you get back
endif;
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多