How to use WP_Query to get nested values of an object? - wordpress

I have searched a lot online with no luck on searching nested values
lets say i have a users array
[
{
id: 0,
billing: {
phone: "999999"
}
},
{
id: 1,
billing: {
phone: "777777"
}
}
]
I want to use WP_Query to filter by phone number is it possible to do that ? and how ?
function get_customers(WP_REST_Request $request) {
$param = $request['phone'];
$args = array(
'post_type' => 'customer',
'posts_per_page' => 1,
'meta_query' => array(
'key' => 'billing.phone',
'value' => $param,
'compare' => '='
)
);
$customers = new WP_Query($args);
return $customers->posts;
}
add_action( 'rest_api_init', function() {
register_rest_route('rc/v1', 'customers/(?P<phone>\d+)', [
'methods' => 'GET',
'callback' => 'get_customers'
]);
});

First, your meta_query syntax is wrong it's should be inside one more array check here and If your post meta key is 'billing.phone' then the below code will work fine.
function get_customers( WP_REST_Request $request ) {
$param = $request['phone'];
$args = array(
'post_type' => 'customer',
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => 'billing.phone',
'value' => $param,
'compare' => '='
)
)
);
$customers = new WP_Query($args);
return $customers->posts;
}
add_action( 'rest_api_init', function() {
register_rest_route('rc/v1', 'customers/(?P<phone>\d+)', [
'methods' => 'GET',
'callback' => 'get_customers'
]);
});

Related

get_posts() does not return featured_image field on Wordpress custom endpoint

Trying to get only the needed data on a custom endpoint in Wordpress. To do so, I am using get_posts() function.
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = $posts[0]->featured_media;
return $data;
}
It should return the ID of the featured image, but get_posts() doesn't even return that field.
get_posts returns array of Post Objects which don't have featured_media property available. Use get_post_thumbnail_id() instead.
See updated code below:
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = get_post_thumbnail_id( $posts[0]->ID );
return $data;
}

How to fix shortcode plugin in wordpress(elementor)?

I'm working with elementor plugin, and I code plugin(shortcode) to get posts data. I want to create plugin with swiper slider but it is not working correctly. It show's data but the_title() and other functions not loading data into slider only before slider. Inside console everything is ok.
This is class
class MRSolutionsSliderWoocommerce
{
function register()
{
add_action('wp_enqueue_scripts', array($this, 'enqueue'));
add_action( 'init', array($this, 'create_slider_posttype'));
add_action( 'init', array($this, 'create_slider_location_tax'));
add_action('wp_insert_post', array($this, 'set_default_slidermeta'));
add_shortcode('simpleslider', array($this, 'simple_slider_shortcode'));
}
function activate()
{
flush_rewrite_rules();
}
function deactivate()
{
flush_rewrite_rules();
}
function enqueue()
{
wp_enqueue_style('swiperCss', plugins_url('/assets/css/swiper.min.css', __FILE__));
wp_enqueue_script('swiperJs', plugins_url('/assets/js/swiper.min.js', __FILE__));
wp_enqueue_style('mrSliderWoocommerceStyle', plugins_url('/assets/css/style.css', __FILE__));
wp_enqueue_script('mrSliderWoocommerceScript', plugins_url('/assets/js/scripts.js', __FILE__));
}
function simple_slider_shortcode($atts = null) {
$no_products = 'Brak produktów na wyprzedaży';
$ss_atts = shortcode_atts(
array(
'slider_type' => '',
'limit' => 6,
'on_sale' => 0
), $atts, 'simpleslider'
);
$slides = array();
$args = array(
'post_type' => 'product',
'meta_key' => $ss_atts['total_sales'],
'orderby' => 'meta_value_num',
'posts_per_page' => $ss_atts['limit'],
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
if($ss_atts['on_sale'] == 1) {
$args = array(
'post_type' => 'product',
'posts_per_page' => $ss_atts['limit'],
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
} else {
$args = array(
'post_type' => 'product',
'meta_key' => $ss_atts['total_sales'],
'orderby' => 'meta_value_num',
'posts_per_page' => $ss_atts['limit']
);
}
$loop = new WP_Query( $args );
$return_prod = '';
if($loop->have_posts()) {
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$slides[] = '
<article class="swiper-slide">
<div class="slide-content">
<div class="slide-img">' . woocommerce_get_product_thumbnail() . '</div>
<h3 class="slide-title">' . get_the_title() . '</h3>
<p class="slide-text">' . wp_trim_words(get_the_content(), 15, '...' ) . '</p>
<a class="slide-btn" href="' . get_permalink() . '">Wybierz produkt</a>
</div>
</article>';
endwhile;
wp_reset_query();
return '
<div class="swiper-container">
<section class="swiper-wrapper">
'.implode('', $slides).'
</section>
</div>';
} else {
return '<h3 class="no-products-slider">' . $no_products . '</h3>';
}
}
function maxContentLength($content)
{
// Take the existing content and return a subset of it
return substr($content, 0, 100);
}
}
if(class_exists('MRSolutionsSliderWoocommerce'))
{
$mrSliderWoocommerce = new MRSolutionsSliderWoocommerce();
// Call register method
$mrSliderWoocommerce->register();
}
// activation
register_activation_hook(__FILE__, array($mrSliderWoocommerce, 'activate'));
// deactivation
register_deactivation_hook(__FILE__, array($mrSliderWoocommerce, 'deactivate'));
and this is js
jQuery(document).ready(function () {
var swiper = new Swiper('.swiper-container', {
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
slidesPerView: 3,
spaceBetween: 20,
// init: false,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
breakpoints: {
1024: {
slidesPerView: 2,
spaceBetween: 10,
},
560: {
slidesPerView: 1,
spaceBetween: 10,
}
}
});
});
This is result
enter image description here

Drupal 7 - Submit function not triggered on theme table

I want to be able to select items from two select lists and then submit (which will take me to another form.
The following is the code I have however the submit function (submit_function) does not appear to get triggered (it just refreshes the form). What am I doing wrong?
function myfunction($form, &$form_state)
{
$output = drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);
$header = array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
);
$rows = array(
array(
'columnone' => array(
'data' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
),
'columntwo' => array(
'data' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
),
'columnthree' =>array(
'data' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
)
),
),
);
$output['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#weight' => 2,
);
return $output;
}
That is quite normal, you are mixing form elements with static renderable elements. A drupal_get_form function expects a form build.
What you need to create is your custom form theme table which outputs a theme within a form build. Here is some sample code that could help you further:
function YOURMODULE_theme()
{
// define a table form theme
return array(
'YOURMODULE_table_form' => array(
'render element' => 'element'
),
);
}
function theme_YOURMODULE_table_form($vars)
{
$element = $vars['element'];
$form_keys = false;
$rows = array();
// loop through each row form elements
foreach (element_children($element) as $key) {
if (!$form_keys) {
$form_keys = array();
// retrieve the form keys for each row
foreach (element_children($element[$key]) as $f_key) {
$form_keys[$f_key] = isset($element[$key][$f_key]['#title'])
? $element[$key][$f_key]['#title']
: '';
}
}
$row = array();
foreach ($form_keys as $fieldkey => $fieldname) {
// render each field in a separate row
$row[] = array(
'data' => drupal_render($element[$key][$fieldkey])
);
}
$rows[] = $row;
}
// return a build for the table
return theme('table', array(
'header' => $vars['element']['#header'],
'rows' => $rows,
'empty' => isset($vars['element']['#empty'])
? $vars['element']['#header']
: '',
));
}
And the form using your logic:
function myfunction($form, &$form_state)
{
$form['table'] = array(
'#theme' => 'YOURMODULE_table_form',
'#header' => array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
),
'#tree' => true,
);
$form['table'][0] = array(
'columnone' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
'columntwo' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
'columnthree' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
),
);
return $form;
}

how to load database content to dropdown options (select)

i'm still working on my own drupal 7 module, and i'm having some trouble. I'm trying to load database content to dropdown option (select), i have read and write the same code from drupal example, but my database still not loading, only empty option.
what i'm asking is there anything wrong on my code or is there any faster way to load database to dropdown option other than the drupal example???
here the code i'm working on
function prod_entry_load($entry = array()) {
$select = db_select('aa_1122','aa');
$select->fields('aa');
foreach ($entry as $field => $value) {
$select->condition($field, $value);
}
return $select->execute()->fetchAll();
}
function prod(){
return drupal_get_form('prod_form');
}
function prod_form($form_state){
$form = array(
'#prefix' => '<div id="updateform">',
'#suffix' => '</div>',
);
$entries = prod_entry_load();
$keyed_entries = array();
if (empty($entries)) {
$form['no_values'] = array(
'#value' => t("No entries exist in the table dbtng_example table."),
);
return $form;
}
foreach ($entries as $entry) {
$options[$entry->no] = t("#no: #name ", array('#no' => $entry->no, '#name' => $entry->name));
$keyed_entries[$entry->no] = $entry;
}
$default_entry = !empty($form_state['values']['no']) ? $keyed_entries[$form_state['values']['no']] : $entries[0];
$form_state['entries'] = $keyed_entries;
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#ajax' => array(
'callback' => 'ajax_alert',
),
);
return $form;
}
function prod_form_update_callback($form, $form_state) {
$entry = $form_state['entries'][$form_state['values']['no']];
foreach (array('name') as $item) {
$form[$item]['#value'] = $entry->$item;
}
return $form;
}
You've just forgotten to add the #options key to your select element, the code should read like this:
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#options' => $options, // This is the bit that was missing
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
You could shorten your query/options code slightly using a combination of string concatenation in MySQL and the db fetchAllKeyed() method:
$query = db_select('aa_1122', 'aa')->fields('aa', array('no'));
$query->addExpression("CONCAT(no, ': ', name)", 'display');
$options = $query->execute()->fetchAllKeyed();

Drupal module function theming with ahah

My main question is:
Does the theme_hook() function gets called whenever the form gets rebuilt via ahah (ahah_helper) ?
I'm trying to show a select box, with some filtering options, when the user changes it, the table below it changes too.
I have this by now:
function veiculos_listar_form($form_state)
{
$form = array();
ahah_helper_register($form, $form_state);
//biulds $options
$form['listar_veics'] = array(
'#type' => 'fieldset',
'#prefix' => '<div id="listar-veics-wrapper">',
'#suffix' => '</div>',
'#tree' => TRUE,
);
if (!isset($form_state['values']['listar_veics']['filial']))
$form['#filial_veic'] = 1;
else
$form['#filial_veic'] = $form_state['values']['listar_veics']['filial'];
$form['listar_veics']['filial'] = array(
'#type' => 'select',
'#title' => "Listar veículos da filial",
'#options' => $filiais,
'#default_value' => $form['#filial_veic'],
'#ahah' => array(
'event' => 'change',
'path' => ahah_helper_path(array('listar_veics')),
'wrapper' => 'listar-veics-wrapper',
'method' => 'replace',
),
);
return $form;
}
function veiculos_listar_form_submit($form, &$form_state)
{
}
function _listar_veiculos_tabela($filial)
{
//builds $header and $data
$table = theme_table($header, $data);
return $table;
}
function theme_veiculos_listar_form($form)
{
$output = drupal_render($form);
$filial = $form['#filial_veic'];
$output .= '<br>' . $filial . '<br>';
$output .= _listar_veiculos_tabela($filial);
return $output;
}
function veiculos_theme() {
return array(
'veiculos_listar_form' => array(
'arguments' => array('form' => NULL),),
);
}
In my little and innocent world, it should work if theme_hook is called on every ahah event (change).
The problem is, the variable printed is always the same, like what the user is choosing isn't being stored. If the user select a different options, it shows the new option, but the $filial variable is always the same when the theme prints.
Like this:
http://img230.imageshack.us/img230/9646/62144334.jpg
Any suggestion on what i could do to make this work? I'm developing our own module, so using views module isn't a good idea.
Thanks.
You should redo code this way.
Ahah callback I do not wrote, I think you would not have problem with it.
Check some examples on drupal.org
function veiculos_listar_form($form_state)
{
$form = array();
ahah_helper_register($form, $form_state);
//biulds $options
// remove divs because we do not want to reload selector with ahah
$form['listar_veics'] = array(
'#type' => 'fieldset',
'#tree' => TRUE,
);
if (!isset($form_state['values']['listar_veics']['filial']))
$form['#filial_veic'] = 1;
else
$form['#filial_veic'] = $form_state['values']['listar_veics']['filial'];
// add cover div here, because we will reload table
$form['table'] = array(
'#prefix' => '<div id="listar-veics-wrapper">',
'#suffix' => '</div>',
'#type' => 'markup',
'#value' => _listar_veiculos_tabela($form['#filial_veic']),
);
$form['listar_veics']['filial'] = array(
'#type' => 'select',
'#title' => "Listar veículos da filial",
'#options' => $filiais,
'#default_value' => $form['#filial_veic'],
'#ahah' => array(
'event' => 'change',
'path' => ahah_helper_path(array('listar_veics')),
'wrapper' => 'listar-veics-wrapper',
'method' => 'replace',
),
);
return $form;
}
function veiculos_listar_form_submit($form, &$form_state)
{
}
function _listar_veiculos_tabela($filial)
{
//builds $header and $data
$table = theme_table($header, $data);
return $table;
}
function theme_veiculos_listar_form($form)
{
$output = drupal_render($form);
return $output;
}
function veiculos_theme() {
return array(
'veiculos_listar_form' => array(
'arguments' => array('form' => NULL),),
);
}

Resources