OOP PHP method doesn't work when invoked within another method - php

I'm creating a PHP class for a Wordpress site. The following method works fine, but when I try to abstract it a bit by passing an argument and calling it within another method (see code further down below), it doesn't work anymore.
public function user_has_submitted_in_dog_category() {
$args = array(
'post_type' => 'submissions',
'author' => get_current_user_id(),
'tax_query' => array(
array(
'taxonomy' => 'submissions_categories',
'field' => 'slug',
'terms' => 'dog'
)
)
);
$user_posts = get_posts( $args );
if( count( $user_posts ) )
return true;
}
This is not working:
public function user_has_submitted_in_dog_category() {
$this->user_has_submitted_in_animal_category( 'dog' );
}
public function user_has_submitted_in_animal_category( $category ) {
$args = array(
'post_type' => 'submissions',
'author' => get_current_user_id(),
'tax_query' => array(
array(
'taxonomy' => 'submissions_categories',
'field' => 'slug',
'terms' => $category
)
)
);
$user_posts = get_posts( $args );
if( count( $user_posts ) )
return true;
}
By not working, I mean that user_has_submitted_in_dog_category() is not returning true. I call it in a template file as follows:
<?php if( $submission->user_has_submitted_in_dog_category() ) : ?>
<div class="msg">You have already submitted.</div>
<?php else : ?>
<div class="msg">You have not submitted yet.</div>
<?php endif; ?>
The block of code prints You have not submitted yet, but I do have posts in my custom taxonomy dog.

You need to return from your first (dog) method.
public function user_has_submitted_in_dog_category() {
return $this->user_has_submitted_in_animal_category( 'dog' );
}

Wordpress might be calling the method statically. You might be best off doing that yourself as the method doesn't seem to need an object instance to work:
public function user_has_submitted_in_dog_category() {
MyClass::user_has_submitted_in_animal_category( 'dog' );
}

Related

Showing list of posts including custom taxonomy terms

I'm working on a WP_Query loop that is suppose to show the list of posts in a following way
+ Custom taxonomy term 1
++ Post 1
++ Post 2
+ Custom taxonomy term 2
++ Post 1
++ Post 2
So in general it will work for CPT called 'career'. In a real life my custom taxonomy (job-category) is like: Drivers, Logistics, HR etc. And to each of such taxonomy/category I've got created specific posts. There is also a custom taxonomy called job-country which suggests the territory.
To achieve the way of showing my posts I am using the following code:
<?php
$terms = get_terms([
'taxonomy' => 'job-category',
'hide_empty' => true,
'orderby' => 'count',
'order' => 'DESC'
]);
usort( $terms, function( $a, $b ) {
$a_ste = (int) get_term_meta( $a->term_id, 'stick_to_end', true );
$b_ste = (int) get_term_meta( $b->term_id, 'stick_to_end', true );
if ($a_ste == $b_ste) return 0;
return ($a_ste < $b_ste) ? -1 : 1;
} );
if ($terms) { //categories exists
foreach ($terms as $category) { ?>
<h2 class="category-title">
<?= $category->name ?>
</h2>
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career',
'tax_query' => [
[
'taxonomy' => 'job-category',
'field' => 'term_id',
'terms' => $category->term_id,
]
]
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
} else { //no categories
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career'
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
?>
And it works. But because of certain reasons (working on an ajax filtering function) I need to achieve the same thing using traditional wp_query.
This is what I've got:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_type' => 'career',
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) && isset( $_POST['taxonomyfilter'] ))
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'job-category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
),
array(
'taxonomy' => 'job-country',
'field' => 'id',
'terms' => $_POST['taxonomyfilter']
)
);
// if you want to use multiple checkboxes, just duplicate the above 5 lines for each checkbox
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
But I've stucked in a place - how to add those terms / elements to the query? Obviously cannot mix get_terms with wpquery by simply copying instead echo'ing the title.
Do you have any suggestions how to solve this?

wp_set_object_terms not setting the terms for the post

This code does not set the object terms. Please help me sort out the issue. The code results in the posts list and doesn't set the terms.
I have checked the below data.
The query results in the list of post.
calculation part in the loop results in the value (lesser or greater than 0)
function set_expired_job_categories() {
global $post;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 368;
$job_ongoing_id = 367;
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to delete, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between <= 0 ) {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}wp_reset_postdata();
}
}
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
As it is in the functions file, I need to set the global $wp_taxonomies to populate the taxonomies data initially. Also, instead of using the tag_ID, I have revised with the slug. These two changes helped to work out the code. The revised code is below for reference.
Thank you all for your efforts.
function set_expired_job_categories() {
global $post;
global $wp_taxonomies;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 'expired';
$job_ongoing_id = 'ongoing';
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to set categories, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between >= 0 ) {
}else {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}
wp_reset_postdata();
}
}
// hook it to low priority value, due to CPT and Taxonomies
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
Reference: https://wordpress.org/support/topic/wp_set_object_terms-in-loop-is-not-work-in-taxonomy-cpt/

WP add_filter within class constructor does not work

I'm using a basic PHP class to add callbacks to existing WC filters, outside the class the callbacks work as they should, but it seems the filters in the constructor do not call the functions, I tried many variations, but none of them work. This is the class:
class Filters implements FiltersInterface{
public function __construct()
{
add_filter("woocommerce_rest_product_object_query", array($this,'FilterByMeta'), 10,2);
add_filter("woocommerce_rest_query_var-tax_query", array($this,'FilterByTaxonomies'), 10,1);
}
public function FilterByMeta($args,$request){
$key = $request->get_param('meta-key');
if($key!='' && $key!=null)
{
$args['meta_key'] = $key;
}
$value = $request->get_param('meta-value');
if($value!='' && $value!=null)
{
$args['meta_value'] = $value;
}
return $args;
}
public function FilterByTaxonomies($args){
var_dump('--');
$attr_term = $_GET['attribute-term'];
$attr_name = $_GET['attribute-name'];
if($attr_term!='' && $attr_term!=null && $attr_name!='' && $attr_name!=null)
{
$args = array(
array(
'taxonomy' => $attr_name,
'field' => 'slug',
'terms' => $attr_term
)
);
return $args;
}
$cat= $_GET['category'];
if($cat!='' && $cat!=null)
{
$args = array(
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $cat
)
);
return $args;
}
return $args;
}
}
And this is in the index.php file i have in my custom 2-file plugin
include('cfilters.php');
$filters = new Filters;
I tried using the class name and 'CLASS 'in the add_filter, but it didnt work either
The problem was with the first filter not adding the key for the second one, after initializng the tax query in the first filter, it was working

in_array function not working when using variable?

In my below code I am trying to check whether the $query['skill'] value is contained in $c_skills. However it keeps failing. When I use the actual string that I am looking for, e.g. "test" then it functions as intended. My only thought is perhaps $query['skill'] doesn't return as a string, but I can't do a var_dump to find out since I am using wordpress and I am changing code to effect ajax query.
global $user_ID;
$query = $_REQUEST['query'];
if (isset($_REQUEST['query']['skill'])) {
if (isset($query['skill']) && $query['skill'] != '') {
global $wp_query, $ae_post_factory, $post, $current_user;
$post_object = $ae_post_factory->get(PROFILE);
$profile_id = get_user_meta( $user_ID, 'user_profile_id', true);
$profile = array('id' => 0, 'ID' => 0);
if($profile_id) {
$profile_post = get_post( $profile_id );
if($profile_post && !is_wp_error( $profile_post )){
$profile = $post_object->convert($profile_post);
}
}
$current_skills = get_the_terms( $profile, 'skill' );
if (!empty($current_skills)) {
$c_skills = array();
foreach ($current_skills as $key => $value) {
$c_skills[] = $value->name;
};
if(in_array( $query['skill'], $c_skills )) {
$query_args['tax_query'] = array(
'skill' => array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
}
}
I think your problem come from $query_args['tax_query'].
For me, the Key (skill) has nothing to do here.
Try to make it simple with
$query_args['tax_query'] = array(
array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
The place you use for skill between the two array is intended to be use for relation if you want to query more than one taxonomy.
Hope it works after this.

Function that saves new WP Query to array for use on single.php

Is it possible to run a function that always queries for a related post and saves that array to a variable in Wordpress?
if ( !function_exists( 'the_query_vars' ) ) {
function the_query_vars() {
global $post;
if ($post->post_status == 'publish') {
$args = array(
'post_type' => 'sponsor'
,'posts_per_page' => 1
,'post_belongs' => $post->ID
,'post_status' => 'publish'
,'suppress_filters' => false
);
$sponsor_query = new WP_Query($args);
return $the_query;
}
add_action( 'init', 'the_sponsor_vars' );
} }
Then I just wanted to use the $the_query "object?" and use it as if I had done a regular new WP_Query() from within the template file? Calling it out with familiar hook like:
echo $the_query->post_title
Tried the simplest thing first:
<?php print_r($the_query);?>
Been unsuccessful in returning the array of variables.
I considered that it was because the variable wasn't globally set, but I thought the advantage of the return command was to essentially store the results for use if the function is activated.
The function returns the Variable and not make it global.
If you want to access the result you have to assign the result of the function to a variable.
if (!function_exists('the_query_vars')) {
function the_query_vars()
{
global $post;
if ($post->post_status == 'publish') {
$args = array(
'post_type' => 'sponsor'
, 'posts_per_page' => 1
, 'post_belongs' => $post->ID
, 'post_status' => 'publish'
, 'suppress_filters' => false
);
$sponsor_query = new WP_Query($args);
return $sponsor_query;
}
add_action('init', 'the_sponsor_vars');
}
}
and where you want to use the result of the function:
$the_query = the_query_vars();

Categories