Notice: is_main_query was called incorrectly - php

Was searching for two days what makes problem in my WordPress theme, and using debug I found this error, and that what I have in functions about that error code.
It displays notice on place where section box should be shown.
How can I fix this?
Notice: is_main_query was called incorrectly. In pre_get_posts, use the WP_Query->is_main_query() method,
// Filter to "pre_get_posts" to change query vars
add_action( 'pre_get_posts', 'dp_custom_get_posts' );
function dp_custom_get_posts( $query ) {
if(is_admin())
return;
$orderby = $query->get('orderby');
$order = $query->get('order');
// If no 'orderby' specified, get first sort type from selected sort types
$selected_sort_types = dp_selected_sort_types();
if(is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}
// Reset query vars based orderby parameter
if($orderby == 'comments') {
$query->set('orderby', 'comment_count');
}
elseif($orderby == 'views') {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'views');
// The arguments for BAW Post Views Count plugin
if(function_exists('baw_pvc_main')) {
global $timings;
$views_timing = $query->get('views_timing') ? $query->get('views_timing') : 'all';
$date = $views_timing == 'all' ? '' : '-'. date( $timings[$views_timing] );
$meta_key = apply_filters( 'baw_count_views_meta_key', '_count-views_' . $views_timing . $date, $views_timing, $date );
$query->set('meta_key', $meta_key);
}
}
elseif($orderby == 'likes') {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'likes');
}
elseif($orderby == 'title' && !$order) {
// If order by title, and no order specified, set "ASC" as default order.
$query->set('order', 'ASC');
}
// Only display posts on search results page
if (is_search() && $query->is_main_query())
$query->set('post_type', 'post');
// Make tax_query support "post-format-standard"
$tax_query = $query->get('tax_query');
if(!empty($tax_query)) {
foreach($tax_query as $index => $single_tax_query) {
if(empty($single_tax_query['terms']))
continue;
$in_post_formats = (array)$single_tax_query['terms'];
if($single_tax_query['taxonomy'] == 'post_format'
&& $single_tax_query['field'] == 'slug'
&& in_array('post-format-standard', $in_post_formats)) {
// Get reverse operator
$reverse_operator = 'IN';
if(empty($single_tax_query['operator']) || $single_tax_query['operator'] == 'IN')
$reverse_operator = 'NOT IN';
elseif($single_tax_query['operator'] == 'AND')
break;
// Get "not in post formats"
$post_formats = get_theme_support('post-formats');
$all_post_formats = array();
if(is_array( $post_formats[0])) {
$all_post_formats = array();
foreach($post_formats[0] as $post_format)
$all_post_formats[] = 'post-format-'.$post_format;
}
$not_in_post_formats = array_diff($all_post_formats, $in_post_formats);
// Reset post_format in tax_query
$query->query_vars['tax_query'][$index] = array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => $not_in_post_formats,
'operator' => $reverse_operator
);
}
}
}
return $query;
}
This is the code of an section box, or at least part of it, I'm not sure what I'm doing anymore:
function dp_section_box($args = array()) {
$defaults = array(
'post_type' => 'post',
'cat' => '',
'taxonomies' => array(),
'view' => 'grid-small',
'title' => '',
'link' => '',
'post__in' => '',
'posts_per_page' => '',
'hide_if_empty' => false
);
$args = wp_parse_args($args, $defaults);
extract($args);
$posts_per_page = absint($posts_per_page);
// Set default posts number if no specified
if(empty($posts_per_page)) {
if($view == 'grid-mini')
$posts_per_page = 8;
elseif($view == 'grid-small')
$posts_per_page = 6;
elseif($view == 'grid-medium')
$posts_per_page = 4;
elseif($view == 'list-small')
$posts_per_page = 3;
elseif($view == 'list-medium')
$posts_per_page = 2;
elseif($view == 'list-large')
$posts_per_page = 1;
}
$args['posts_per_page'] = $posts_per_page;
$args = dp_parse_query_args($args);
$query = new WP_Query($args);
// Output nothing if there is no posts
if(!$query->have_posts() && $hide_if_empty)
return;
// Output content before section
if(!empty($before))
echo '<div class="section-box section-before rich-content">'. do_shortcode(wp_kses_stripslashes($before)).'</div><!-- end .section-box -->';
// Section box begin
echo '<div class="section-box">';
global $section_view;
$section_view = $view;
// Get term name as title
$term = '';
$cat = '';
if(!empty($taxonomies['category']))
$cat = $taxonomies['category'];
if($cat)
$term = get_term($cat, 'category');
if(empty($title) && $term)
$title = $term->name;
if(empty($link) && $term)
$link = get_term_link($term, 'category');
$title = '<span class="name">'.$title.'</span>';
// Add link to title and more
$more = '';
if($link) {
$title = '<a class="name-link" href="'.$link.'">'.$title.'</a>';
$more = '<a class="more-link" href="'.$link.'"><span>'.__('More', 'dp').' <i class="mini-arrow-right"></i></span></a>';
}
// Output section header
echo '<div class="section-header"><h2 class="section-title">'.$title.'</h2>'.$more.'</div>';
// Output section content
echo '<div class="section-content '.$view.'"><div class="nag cf">';
while ($query->have_posts()) : $query->the_post();
get_template_part('item-video');
endwhile;
wp_reset_postdata();
echo '</div></div><!-- end .section-content -->';

the solution is given in your error itself "use the WP_Query->is_main_query() method"-
try this -
if($query->is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}
instead of this -
if(is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}

Related

Wordpress Replace words in already existed Posts

I have multiple words that i need to replace on posts that they are already added on the WordPress, but I don't want to change the full content, I need only the WordPress post output.
I have this code but is not working ... and I can't find how WordPress working about this ...
function SC_Replace_Words_On_Posts() {
$Replace_Words_Array = array(
'aaa' => 'aa',
);
if( isset($_REQUEST['post_id']) ) {
$Post_ID = $_REQUEST['post_id'];
} else {
$Post_ID = false;
}
$Post_Content = get_post_field('post_content', $Post_ID);
if($Post_Content != '' && is_array($Replace_Words_Array) && !empty($Replace_Words_Array)) {
foreach($Replace_Words_Array as $Find_Word => $Replace_Word) {
$Post_Content = SC_replaceWithCase($Find_Word, $Replace_Word, $Post_Content);
}
}
return $post;
}
add_filter("wp_insert_post_data", "SC_Replace_Words_On_Posts");

Get product variation and modify price - woocommerce

I'm looking for a way to target product variations and modify their prices based on the attributes each variation has. The below code is somewhat heading in the right direction, but instead of using product attributes to target variations, I'm relying on matching the variation's current price to a variable in order to target it. It works, but it leaves a ton of room for error with how vague it is.
add_filter('woocommerce_get_price','change_price', 10, 2);
function change_price($price, $productd){
if ( $productd->product_type == 'variation' || $productd->product_type == 'variable' ) {
$basicmp3 = 25;
$vprice = get_post_meta( $productd->variation_id, '_regular_price',true);
if ($vprice == $basicmp3) {
$vprice2 = $vprice * .5;
return $vprice2;
}
else{
return $vprice;
}
}
}
UPDATE Posted a working solution below
When you run a woocommerce class in a function, there's a need to call some global.
global $woocommerce; $product;
$product_variation = new WC_Product_Variation($_POST['variation_id']);
$regular_price = $product_variation->regular_price;
In other Word, it's not because you have $product as parameter that you can use the class functions (it's just a 'flatten' object like an array can be). You need to initialize a new object of a class to use $newproductobject->regular_price().
It's possible, if your code is part of a plugin that the woocommerce class are not yet load, then you'll need to include the file containing the class WC_Product _Variation. (Don't think it's the case)
Hope it helps !
Found a working solution. It's probably a little bloated since I'm no code master, but I does it's job! Below is a basic version, but this kind of flexibility will allow for more useful functions, such as automatically bulk discounting variation prices by user role for products who share certain attributes.
add_filter('woocommerce_get_price','change_price', 10, 2);
function change_price($price, $productd){
global $post, $woocommerce;
$post_id = $variation->ID;
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => $post->ID
);
$variations = get_posts( $args );
//declare variables for later use
$demomp3 = '';
$basicmp3 = '';
$basicwav = '';
$premiummp3 = '';
$premiumwav = '';
$syncmp3 = '';
$syncwav = '';
foreach ( $variations as $variation ) {
$variation_id = absint( $variation->ID );$variable_id = $this['variation_id'];
$variation_post_status = esc_attr( $variation->post_status );
$variation_data = get_post_meta( $variation_id );
$variation_data['variation_post_id'] = $variation_id;
//find attributes
$option1 = 'pa_license-options';
$option2 = 'pa_delivery-format';
$getmeta1 = get_post_meta($variation_id , 'attribute_'.$option1, true);
$getmeta2 = get_post_meta($variation_id , 'attribute_'.$option2, true);
$attribute1 = get_term_by('slug', $getmeta1, $option1);
$attribute2 = get_term_by('slug', $getmeta2, $option2);
$license = $attribute1->name;
$format = $attribute2->name;
//get the prices of each variation by the attribute combinations they have
if ($format === "mp3" && $license === "Demo License" ){
//retrieve variation price and assign it to the previously created variable
$demomp3 = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "mp3" && $license === "Basic License" ){
$basicmp3 = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "WAV" && $license === "Basic License" ){
$basicwav = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "mp3" && $license === "Premium License" ){
$premiummp3 = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "WAV" && $license === "Premium License" ){
$premiumwav = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "mp3" && $license === "Sync License" ){
$syncmp3 = get_post_meta($variation_id, '_regular_price', true );
}
if ($format === "WAV" && $license === "Sync License" ){
$syncwav = get_post_meta($variation_id, '_regular_price', true );
}
}
//Simple product doesn't need to be modified
if($productd->product_type == 'simple'){
return $price;
}
//adjust prices of variable products
if ( $productd->product_type == 'variation' || $productd->product_type == 'variable' ) {
$regprice = get_post_meta( $productd->variation_id, '_regular_price',true);
//target the current variation by matching its price to the one stored in the variable
if ($regprice == $demomp3) {
//apply price adjustment and return the new value
$price = $regprice * .5;
return $price;
}
else if ($regprice == $basicmp3) {
$price = $regprice * .5;
return $price;
}
else if ($regprice == $basicwav) {
$price = $regprice * .5;
return $price;
}
else if ($regprice == $premiummp3) {
$price = $regprice * .5;
return $price;
}
else if ($regprice == $premiumwav) {
$price = $regprice * .5;
return $price;
}
else if ($regprice == $syncmp3) {
$price = $regprice * .5;
return $price;
}
else if ($regprice == $syncwav) {
$price = $regprice * .5;
return $price;
}
else{
return $price;
}
}
}
Use the following script to update product variation. click here for detailed explanation.
https://www.pearlbells.co.uk/bulk-update-product-variation-price-woocommerce/
function getExistingProducts($updatedPrices,$skuArray) {
$loop = new WP_Query(array('post_type' => array('product', 'product_variation'), 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$id = get_the_ID();
$product = wc_get_product( $id );
$sku = get_post_meta($id, '_sku', true);
if( in_array( $sku, $skuArray ) ) {
$attributes = $product->get_attributes();
$attributes['medium-quantity-price']['value'] = $updatedPrices[$sku][4];
$attributes['low-quantity-price']['value'] = $updatedPrices[$sku][3];
// $attributes['v-low-quantity-price']['value'] = $updatedPrices[$sku][2];
update_post_meta( $id,'_product_attributes',$attributes);
echo ' Update Sku : '.$sku.' '.PHP_EOL;
}
endwhile;
}

Wordpress post loop, only shows variable when logged in as admin

The problem i have is when I am not logged into wordpress as the admin. It shows me the following thing on an events page.
http://www.productplusconcepts.nl/hiteclife/wp-content/themes/hi-tec/hl-step1.jpg
Now when I log into wordpress backend and go to the same events page it does show me the content in the square of the next picture.
http://www.productplusconcepts.nl/hiteclife/wp-content/themes/hi-tec/hl-step2.jpg
Here is my query for the loop.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args['post_type'] = 'evenementen';
$args['post_status'] = 'publish';
$args['relation'] = 'AND';
$args['order_by'] = 'datum_start';
$args['order'] = 'ASC';
$args['posts_per_page'] = 10;
$args['paged'] = $paged;
$args['meta_query'] = array(
array(
'key' => 'datum_eind',
'value' => date('Ymd'),
'compare' => '>='
)
);
if(!empty($_GET['maand'])){
$args['meta_query'] = array(
array(
'key' => 'datum_eind',
'value' => date('Ymd'),
'compare' => '>='
),
array(
'key' => 'welke_maand',
'value' => $_GET['maand'],
'compare' => '='
)
);
}
if(!empty($_GET['provincie'])){
$args['meta_query'] = array(
array(
'key' => 'datum_eind',
'value' => date('Ymd'),
'compare' => '>='
),
array(
'key'=> 'provincie',
'value'=> $_GET['provincie'],
'compare'=> '='
)
);
}
if(!empty($_GET['afstand'])){
$afstanden = explode(',', urldecode($_GET['afstand']));
$args['meta_query'] = array();
array_push($args['meta_query'],
array(
'key' => 'datum_eind',
'value' => date('Ymd'),
'compare' => '>='
)
);
foreach($afstanden as $afstand) {
array_push($args['meta_query'],
array(
'key'=>'afstand',
'value'=> $afstand,
'compare'=>'LIKE'
)
);
}
}
$overzicht = new WP_Query($args);
Now i work with 3 filters for the content it loads they work perfect but ill show the code within the loop.
if( $overzicht->have_posts() ) :
while( $overzicht->have_posts() ) : $overzicht->the_post(); ?>
<li>
<a href="<?php the_permalink();?>"><?php the_title();?>
<div class="click"></div>
<div class="extrainfo">
<span class="pull-right">
<?php echo '<span class="label label-info">' . get_field('plaats') . '</span>'; ?>
</span>
<span class="pull-left">
<?php
$afstanden = get_field('afstand');
//echo "<pre>";
//print_r($afstanden);
//echo "</pre>";
if(!empty($afstanden)) {
if(is_array($afstanden)) {
$items = array();
foreach($afstanden as $afstand) {
$fields = get_fields($afstand->ID);
$items[] = format_distance($fields['minimaal'], $fields['maximaal']);
}
if(count($items) > 1)
echo '<strong>Afstanden: </strong>';
elseif(count($items === 1))
echo '<strong>Afstand: </strong>';
echo fancify($items);
} else {
echo '<em>Geen afstand(en) beschikbaar.</em>';
}
} else {
echo '<em>Geen afstand(en) beschikbaar.</em>';
}
echo '<br>';
if(get_field('datum_start') && get_field('datum_eind')){
$date_start = datum_omzetten(get_field('datum_start'));
$date_eind = datum_omzetten(get_field('datum_eind'));
echo 'Van: '. $date_start . ' t/m: '. $date_eind;
}else{
echo datum_omzetten(get_field('datum'));
}
?>
</span>
</div>
</a>
<div class="clearfix"></div>
</li>
<?php
endwhile;
wp_reset_postdata();
else:
?>
<p>Helaas, er zijn geen evenementen gevonden. <br /><br>Wilt u een evenement aanmelden? Neem dan contact met ons op</p>
<?php
endif;
The only functions being called within the loop is format_distance and fancify within the template functions.php
Format Distance:
function format_distance($min, $max) {
if($min < $max)
return sprintf('%s-%skm', $min, $max);
elseif($min > $max)
return sprintf('>%skm', $min);
else
return '?';}
Fancify:
function fancify($items) {
if(is_array($items)) {
$str = '';
$size = count($items);
for($i = 0; $i < $size; $i++) {
$str .= $items[$i];
if($i < $size - 2)
$str .= ', ';
elseif($i < $size - 1)
$str .= ' of ';
}
return $str;
} else
return '?';}
I cannot seem to find the problem why the loop is only showing me the afstanden (distances) when I'm logged in.
Turns out this is a conflict between Wordpress Plugin Custom Advanced Fields and BBPress Forum. They both make use of get_field relation post object. Thats why i wasnt able to see the content when i wasnt logged in. To fix this problem add this to your theme's function file.
add_filter('acf/get_post_types', 'my_acf_post_type_filter', 20, 3);
function my_acf_post_type_filter ($post_types) {
$exclude = array('topic', 'reply');
// exclude
foreach( $exclude as $p )
{
unset( $post_types[ $p ] );
}
return $post_types; }

Handle search in Wordpress from WP_List_Table code

I need to add support for searching or filter items using WP_List_Table I read and didn't know how to get this done. I've already added the box trough this code:
function ft_list()
{
echo '</pre><div class="wrap"><h2>' . __('Frequent Traveler List') . '</h2>';
$ftList = new FT_WP_Table();
$ftList->search_box('search', 'search_id');
echo '</div>';
}
And this is how my prepare_items() functions looks:
public function prepare_items()
{
$searchcol = array(
'firstname',
'lastname',
'foid',
'no_frequent',
'create_time'
);
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array(
$columns,
$hidden,
$sortable
);
// SQL results
$posts = $this->get_sql_results();
empty($posts) AND $posts = array();
# >>>> Pagination
$per_page = $this->posts_per_page;
$current_page = $this->get_pagenum();
$total_items = count($posts);
$this->set_pagination_args(array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items / $per_page)
));
$last_post = $current_page * $per_page;
$first_post = $last_post - $per_page + 1;
$last_post > $total_items AND $last_post = $total_items;
// Setup the range of keys/indizes that contain
// the posts on the currently displayed page(d).
// Flip keys with values as the range outputs the range in the values.
$range = array_flip(range($first_post - 1, $last_post - 1, 1));
// Filter out the posts we're not displaying on the current page.
$posts_array = array_intersect_key($posts, $range);
# <<<< Pagination
// Prepare the data
$permalink = __('Edit:');
foreach ($posts_array as $key => $post) {
$link = get_edit_post_link($post->id);
$no_title = __('No title set');
$title = !$post->firstname ? "<em>{$no_title}</em>" : $post->firstname;
$posts[$key]->firstname = "<a title='{$permalink} {$title}' href='{$link}'>{$title}</a>";
}
$this->items = $posts_array;
}
Where I should add the code to filter items based on search parameter?
Looking at other classes that extend WP_List_Table I see they use something like
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false;
and pass that to the prepare_items() method.
In my test plugin I made this (see Percent in wpdb->prepare):
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false;
$do_search = ( $search ) ? $wpdb->prepare(" AND post_content LIKE '%%%s%%' ", $search ) : '';
$sql_results = $wpdb->get_results("
SELECT $sql_select
FROM $wpdb->posts
WHERE post_status = 'publish'
$do_search
ORDER BY $this->orderby $this->order "
);
And in display_tablenav() method I added:
<form action="" method="GET">
<?php
$this->search_box( __( 'Search' ), 'search-box-id' );
?>
<input type="hidden" name="page" value="<?= esc_attr($_REQUEST['page']) ?>"/>
</form>
I haven't created any search_box() method, letting the parent class render it.

cycle next page wordpress order by post title

I'm using Cycle jquery for my website.
I've added a php code do get a link at the end of my slideshow to go to the next page.
I want my pages to be sorted alphabetically but it's not working...
I've added "orderby=post_title" but still not working...
anybody can help me with this ?
here is my PHP code :
function dbdb_next_page_link() {
global $post;
if ( isset($post->post_parent) && $post->post_parent > 0 ) {
$children = get_pages('&orderby=menu_order&order=ASC&child_of='.$post->post_parent.'&parent='.$post->post_parent);
}
//print_r($children);
// throw the children ids into an array
foreach( $children as $child ) { $child_id_array[] = $child->ID; }
$next_page_id = relative_value_array($child_id_array, $post->ID, 1);
$output = '';
if( '' != $next_page_id ) {
$output .= ''. get_the_title($next_page_id) . ' ยป';
}
return get_page_link($next_page_id);
}
and a jsfiddle link : http://jsfiddle.net/KvBRV/
....
I have the same problem with a "select type" menu, my pages are not sorted alphabetically, I don't know why, here is my php code :
<div class="styled-select">
<?php
if(!$post->post_parent){
$children = get_pages(array(
'child_of' => $post->ID,
'post_type' => 'page',
'post_status' => 'publish',
'sort_order' => 'ASC',
'sort_column' => 'post_title',
));
}else{
$children = get_pages(array(
'child_of' => $post->post_parent,
'post_type' => 'page',
'post_status' => 'publish',
'sort_order' => 'ASC',
'sort_column' => 'post_title',
));
}
if ($children) {
echo '<select name="" onchange="location = this.options[this.selectedIndex].value;">';
echo '<option>'. 'A - Z' .'</option>';
function getInitials($name){
//split name using spaces
$words=explode(" ",$name);
$inits='';
//loop through array extracting initial letters
foreach($words as $word){
$inits = strtoupper(substr($word,0,1));
break;
}
return $inits;
}
$currval = "";
foreach($children as $child){
//print_r($child);
$permalink = get_permalink($child->ID);
$post_title = strtoupper($child->post_title);
$initial = getInitials($child->post_title);
if($initial!='' && $currval != $initial ) {
$currval = $initial;
echo '<optgroup label="'.$initial.'""></optgroup>';
}
echo '<option value="'.$permalink.'">'.$post_title.'</option>';
}
echo '</select>';
} ?>
<!-- FIN MENU DEROULANT A-Z -->
</div>
and a jsfiddle link : http://jsfiddle.net/Zp3Lt/
thanks a lot for your help !
Mattieu
get_pages doesnt accept any arg called orderby or order instead sort_column and sort_order is used ..
so your code would be
if ( isset($post->post_parent) && $post->post_parent > 0 ) {
$children = get_pages('sort_column=post_title&sort_order=ASC&child_of='.$post->post_parent.'&parent='.$post->post_parent);
}
Refer Here
Get Pages

Categories