admin管理员组文章数量:1125350
Help me please.. I have plugin for vacancy/resume/companies in the form of posts on Wordpress.
The task is to perform a standard Wordpress search for arbitrary fields inside the record. The fields themselves are output in CMB2.
The search works by taxonomy and record name, but not by an arbitrary field.
Inside the plugin, on the companies display page, there was a search function by taxonomy and name. I added an additional field search, but without success.
<?php
class PNJobCompany extends PNJobForm {
private static $_instance;
private function __construct()
{
$this->includes();
$this->initHook();
}
private function includes()
{
}
private function initHook()
{
add_filter('template_include', [$this, 'templateInclude']);
add_action('wp_loaded', [$this, 'formHandler'], 20);
add_filter('build_company_seach_query', [$this, 'buildCompanySearchQuery'], 10, 3);
add_filter('wp_dropdown_users', [$this, 'userDropdown']);
}
public function templateInclude($template)
{
if (is_company_list_page()) {
$template = pnj_get_template('company/company-list', null, false);
}
return $template;
}
public function formHandler()
{
if (isset($_POST['pnj_action']) && !empty($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'pnj')) {
switch ($_POST['pnj_action']) {
case 'create-company':
$this->createHandler();
break;
case 'edit-company':
$this->editHandler();
break;
case "delete-company":
//$this->deleteHandler();
break;
}
}
}
/--The search starts here--/
function searchJoinFilter($where)
{
global $wpdb;
if (!empty($_REQUEST['query'])) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql($wpdb->esc_like(trim($_REQUEST['query']))) . '%\'';
}
return $where;
}
/**
* @param $posts_per_page
* @param $paged
* @return object WP_Query
*/
public function buildCompanySearchQuery($posts_per_page, $paged)
{
$query = [
'post_status' => 'publish',
'post_type' => 'company',
'posts_per_page' => $posts_per_page,
'paged' => $paged
];
//City
if (!empty($_REQUEST['location'])) {
$query['tax_query'] = [
'relation' => 'AND',
[
'taxonomy' => 'job-location',
'field' => 'term_id',
'terms' => $_REQUEST['location'],
'compare' => 'IN'
]
];
}
//My search inn_company
if (!empty($_REQUEST['company-inn'])) {
$meta_query = [
'key' => 'company_inn',
'field' => 'meta_value',
'value' => $_REQUEST['company-inn'],
'compare' => '='
];
$query['meta_query'] = $meta_query;
}
add_filter('posts_where', [$this, 'searchJoinFilter']);
$result = new WP_Query($query);
// Удаляем условие, чтобы другие вызовы WP_Query() не затрагивать
remove_filter('posts_where', [$this, 'searchJoinFilter']);
return $result;
}
/--End search here--/
public function initFields()
{
$this->fields = [
'post_title' => $_POST['title'] ?? '',
'post_content' => $_POST['description'] ?? '',
'employer_category' => $_POST['employer_category'] ?? '1',
'company_email' => $_POST['company_email'] ?? '',
'company_phone' => $_POST['company_phone'] ?? '',
'company_inn' => $_POST['company_inn'] ?? '',
'company_url' => $_POST['company_url'] ?? '',
'company_address' => $_POST['company_address'] ?? '',
'category' => $_POST['categories'] ?? '',
'location' => $_POST['location'] ?? '',
'company_form' => $_POST['company_form'] ?? '',
'metro' => $_POST['metro'] ?? '',
];
}
protected function validateFields()
{
foreach ($this->fields as $key => $value) {
switch ($key) {
case 'post_title':
if ($this->fields[$key] === '')
$this->addError('Пожалуйста, укажите название компании');
break;
case 'company_inn':
if (empty($this->fields[$key]))
$this->addError('Пожалуйста, введите идентификатор Федеральной налоговой службы вашей компании');
elseif (!preg_match('/^\d{10}$/', $this->fields[$key]))
$this->addError('Идентификатор Федеральной налоговой службы должен состоять из 10 цифр');
break;
case 'company_email':
if ($this->fields[$key] !== '' && !is_email($this->fields[$key]))
$this->addError('Неверный формат email');
// TODO Реализовать проверку за занятость email, тем самым запретить регистрацию нескольких компаний на одни email
break;
case 'company_phone':
if (empty($this->fields[$key])) {
$this->addError('Поле "Телефон" не божет быть пустым');
}
if (!$this->fields[$key] = format_phone($this->fields[$key])) {
$this->addError('Неверный формат телефона');
}
break;
case 'employer_category':
if (empty($this->fields['employer_category']))
$this->addError('Пожалуйста, укажите тип работодателя');
break;
case 'categories':
if (empty($this->fields['categories']))
$this->addError('Пожалуйста, укажите отрсль компании');
break;
case 'location':
if (empty($this->fields['location']))
$this->addError('Пожалуйста, укажите город');
break;
}
}
}
public function createHandler()
{
$user_id = get_current_user_id();
try {
if (empty($_POST['phone_prefix']) || empty($_POST['phone_code']) || empty($_POST['phone_number'])) {
$this->addError('Неверно указан телефон');
}
$_POST['company_phone'] = $_POST['phone_prefix'] . $_POST['phone_code'] . $_POST['phone_number'] . $_POST['phone_extension'];
$this->initFields();
$this->validateFields();
if (!empty($this->errors)) {
throw new Exception(implode('<br>', $this->errors));
}
$company_id = wp_insert_post([
'post_title' => sanitize_text_field($this->fields['post_title']),
'post_type' => 'company',
'post_status' => 'publish',
'post_author' => $user_id,
'post_content' => wp_kses_post($this->fields['post_content']),
'comment_status' => 'open'
]);
if (is_wp_error($company_id)) {
throw new Exception($company_id->get_error_message());
} else {
$fields = ['company_url', 'company_inn', 'company_email', 'company_phone', 'employer_category', 'company_address'];
foreach ($fields as $field) {
if (isset($_POST[$field])) {
update_metadata('company', $company_id, '_' . $field, sanitize_text_field($this->fields[$field]));
}
}
$taxonomies = [
'category' => 'job-category',
'company_form' => 'company-form',
'metro' => 'job-metro'
];
foreach ($taxonomies as $field => $taxonomy) {
wp_set_post_terms($company_id, $this->fields[$field], $taxonomy);
}
// set logo as featured
if (isset($_POST['company_logo'])) {
$logo_id = $_POST['company_logo'];
set_post_thumbnail($company_id, $logo_id);
}
pnj_flash_message(
'message',
'Новая компания успешно создана',
'alert-success'
);
$redirect = pnj_get_account_link('edit-company');
if (!empty($_REQUEST['redirect'])) {
$redirect = $_REQUEST['redirect'];
}
wp_redirect($redirect);
exit;
}
} catch (Exception $e) {
pnj_flash_message('message', $e->getMessage(), 'alert-danger');
}
}
public function editHandler()
{
if (!isset($_POST['company_id']))
return;
$this->initFields();
$user_id = get_current_user_id();
$company_id = $_POST['company_id'];
$company = get_post($company_id);
try {
$this->validateFields();
if ($company->post_type !== 'company') {
$this->addError('Не верный тип поста');
}
if ($company->post_author != $user_id && !is_user_role('administrator')) {
$this->addError('У вас нет прав для редактирования этой компании');
}
if (!empty($this->errors)) {
throw new Exception(implode('<br>', $this->errors));
}
wp_update_post([
'ID' => $company_id,
'post_title' => sanitize_text_field($this->fields['post_title']),
'post_content' => wp_kses_post($this->fields['post_content'])
]);
$fields = [
'company_email',
'company_phone',
'company_inn',
'company_url',
'employer_category',
'company_address'
];
foreach ($fields as $field) {
update_metadata('company', $company_id, sanitize_text_field('_' . $field), $this->fields[$field]);
}
$taxonomies = [
'inn' => 'company_inn',
'location' => 'job-location',
'category' => 'job-category',
'company_form' => 'company-form',
'metro' => 'job-metro'
];
wp_delete_object_term_relationships($company_id, $taxonomies);
foreach ($taxonomies as $field => $taxonomy) {
wp_set_post_terms($company_id, $this->fields[$field], $taxonomy);
}
if (isset($_POST['company_logo'])) {
$logo_id = $_POST['company_logo'];
if ($logo_id !== '')
set_post_thumbnail($company_id, $logo_id);
else
delete_post_thumbnail($company_id);
}
pnj_flash_message(
'message',
'Компания успешно отредактирована',
'alert-success'
);
$redirect = pnj_get_account_link('edit_company');
if (!empty($_REQUEST['redirect'])) {
$redirect = $_REQUEST['redirect'];
}
wp_redirect($redirect);
exit;
} catch (Exception $e) {
pnj_flash_message('message', $e->getMessage(), 'alert-danger');
}
}
/**
* @return object PNJobCompany
*/
public static function instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function userDropdown($output)
{
global $post;
if ($post->post_type === 'company') {
$output = str_replace('</select>', '', $output);
$users = get_users(['role' => PNJobAccount::EMPLOYER]);
foreach ($users as $user) {
if ($post->post_author == $user->ID) {
continue;
}
$output .= '<option value="' . $user->ID . '">' . sprintf(_x('%1$s (%2$s)', 'user dropdown'), $user->display_name, $user->user_login) . '</option>';
}
$output .= "</select>";
}
return $output;
}
}
PNJobCompany::instance();
本文标签: pluginsSearch result page admin paneldisplay values from the result39s metaboxes
版权声明:本文标题:plugins - Search result page admin panel - display values from the result's metaboxes 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736656928a1946279.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论