I have a form that allows a user to select a county from a dropdown menu, My form is then posted to my functions.php page where I've been using IF statements to run my queries.
if ($_POST['dropdown1'] == 'option 1' && $_POST['dropdown 2'] == 'option 4' && $_POST['county'] == 'cheshire' ) {
// RUN QUERY
}
My problem is however I can't realistically use IF statements for every county in every possible scenario as there will be thousands of options, has anybody got a better idea of how I can do this?
if ($_POST['vehicleType'] == 'hgv' && $_POST['coverageRegion'] == 'national' ) {
$customkey = 'vehicleType';
$customvalue = $_POST['vehicleType'];
$customkey1 = 'coverageRegion';
$customvalue1 = $_POST['coverageRegion'];
$customkey2 = 'locationType';
$customvalue2 = $_POST['locationType']; $args = array('orderby' => 'meta_value_num', 'meta_key' => 'order', 'order' => 'ASC',
'meta_query' => array(
array(
'key' => $customkey,
'value' => $customvalue,
'compare' => '='
),
array(
'key' => $customkey1,
'value' => $customvalue1,
'compare' => '='
),
array(
'key' => $customkey2,
'value' => $customvalue2,
'compare' => '='
)
) // end of array
); //end of if
$query = new WP_Query( $args);
// The Loop
$i = 0; $i = -1;
while ( $query->have_posts() )
{
$i++;
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
echo "<div class='clearfix card-prod ".($i==0?'first':'')."'><div class='top-dets'><span class='card-title'>";
echo the_title();
echo "</span>";
// Network query
$network_value = get_post_custom_values('srchnetwork');
foreach ( $network_value as $key => $value ) {
echo '<span class="srch-val-">'. $value . '</span>'; }// Pricing Query
$pricing_value = get_post_custom_values('srchpricing');
foreach ( $pricing_value as $key => $value ) {
echo '<span class="srch-val-1">'. $value . '</span>'; }
// Setup Query
$setup_value = get_post_custom_values('srchsetupfee');
foreach ( $setup_value as $key => $value ) {
echo '<span class="srch-val-2">'. $value . '</span>'; }
// Services Query
$services_value = get_post_custom_values('srchservices');
foreach ( $services_value as $key => $value ) {
echo '<span class="srch-val-3">'. $value . '</span></div>'; }
// Big Card Query
$bigcard_value = get_post_custom_values('bigcard');
foreach ( $bigcard_value as $key => $value ) {
echo '<a href="/" class="cardclick"><img src="/wp-content/themes/CAFC/images/cards/'. $value . '" alt="'; }
echo the_title() . '" /></a>';
echo '<img src="wp-content/themes/CAFC/images/top-choice.jpg" alt="Top Choice" class="topchoice">';
echo the_excerpt()."</div>"; }
}
}
You can write your code in this way so you don't have to deal with every possible option.
global $wpdb;
$postKeys = array('vehicleType', 'coverageRegion', 'locationType');
$args = array(
'orderby' => 'meta_value_num',
'meta_key' => 'order',
'order' => 'ASC',
'meta_query' => array()
);
foreach ($postKeys as $key) {
$args['meta_query'][] = array(
'key' => $key,
'value' => $wpdb->escape($_POST[$key]),
'compare' => '='
);
}
$query = new WP_Query($args);
Related
I'm trying to show 4 posts from each category. Tried this code which should fetch 4 posts from respective categories. then sort them as required in col1, col2, and so on.
<?php
$col1 = $col2 = $col3 = $col4 = $col5 = array();
$parsha_terms = get_terms('parsha');
foreach($parsha_terms as $term) {
$order = get_field('parsha_order', 'term_' . $term->term_id);
$column = get_field('parsha_column', 'term_' . $term->term_id);
$color_pdf = get_field('pdf', 'term_' . $term->term_id);
$posts = get_posts(
array(
'cat' => $cat_id,
'tax_query' => array(
array(
'posts_per_page' => 4,
'taxonomy' => 'parsha',
'field' => 'term_id',
'terms' => $term->term_id,
)
)
)
);
$data = array(
'term_id' => $term->term_id,
'name' => $term->name,
'order' => $order,
'column' => $column,
'post_ids' => $posts[0]->ID,
'post_title' => $posts[0]->post_title,
'color_pdfs' => $pdfcolor,
'color_pdf_link' => $color_pdf,
);
if($column == 1) {
array_push($col1, $data);
}
else if($column == 2) {
array_push($col2, $data);
}
else if($column == 3) {
array_push($col3, $data);
}
else if($column == 4) {
array_push($col4, $data);
}
else if($column == 5) {
array_push($col5, $data);
}
}
then in output, it shows only one result(post) of each category, but it should show 4.
<?php foreach($col1 as $item) { ?>
<li>
<p><?= $item['name']; ?></p>
<?= $item['post_title']; ?>
</li>
<?php } ?>
You're retrieving an array of $posts but you're then only adding the first element $posts[0] to your $data array.
You need to loop them with foreach
$posts = get_posts(
array(
'cat' => $cat_id,
'tax_query' => array(
array(
'posts_per_page' => 4,
'taxonomy' => 'parsha',
'field' => 'term_id',
'terms' => $term->term_id,
)
)
)
);
foreach($posts as $post) {
$data = array(
'term_id' => $term->term_id,
'name' => $term->name,
'order' => $order,
'column' => $column,
'post_ids' => $post->ID,
'post_title' => $post->post_title,
'color_pdfs' => $pdfcolor,
'color_pdf_link' => $color_pdf,
);
if($column == 1) {
array_push($col1, $data);
}
else if($column == 2) {
array_push($col2, $data);
}
else if($column == 3) {
array_push($col3, $data);
}
else if($column == 4) {
array_push($col4, $data);
}
else if($column == 5) {
array_push($col5, $data);
}
}
I am struggling with how to return an array of courses that includes an array of rooms with a capacity that is greater than or equal to the course enrollment of each course.
The following code returns an array in the structure I want, but only the last value. I have tried array_merge_recursive, and either get an error or only the last value again.
I created the arrays like this:
global $wpdb;
$course_query1 = new WP_Query( array( 'post_type' => 'courses', 'posts_per_page' => '-1' ) );
$courses = $course_query1->posts;
$course_array1 = array();
foreach($courses as $i => $course) {
$course_array1[$i]['course_name'] = $course->post_name;
$course_array1[$i]['cap'] = $course->course_enrolled;
$course_array1[$i]['cap_array'] = $course->room_matches;
}
$room_query1 = new WP_Query( array( 'post_type' => 'jost_rooms', 'posts_per_page' => '-1' ) );
$rooms = $room_query1->posts;
$room_array1 = array();
foreach($rooms as $i => $room) {
$room_array1[$i]['room_name'] = $room->post_name;
$room_array1[$i]['cap'] = $room->room_capacity;
}
And created the function like so:
function compare_capacities10($array1, $array2){
for($c = 0; $c < count($array1); $c++) {
foreach($array1[$c] as $ckey => $ccap) {
if ($ckey == 'cap') {
for($r = 0; $r < count($array2); $r++) {
foreach($array2[$r] as $rkey => $rcap) {
if (($rkey == 'cap') && ($rcap >= $ccap)){
//this structure is right but only returns last value
$result = array($ckey, $ccap, array($rkey, $rcap) );
}
}
}
}
}
}
return $result;
}
$capacity_array10 = compare_capacities10 ($course_array1,
$room_array1);
print_r($capacity_array10);
EDIT:
I'm adding the code below, because it's achieving the same thing as above, but is better in WordPress because I can add other key-values to the display:
$courses = new WP_Query( array( 'post_type' => 'courses', 'posts_per_page' => '-1' ) );
if ( $courses->have_posts() ) {
while ( $courses->have_posts() ) {
$courses->the_post();
$enr = get_post_meta(get_the_ID(), 'course_enrolled' , true);
$cname = get_the_title();
$rooms = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'rooms',
'meta_query' => array(
array(
'key' => 'room_capacity',
'posts_per_page' => '-1',
'value' => $enr,
'compare' => '>='
)
)
)
);
if ( $rooms->have_posts() ) {
while ( $rooms->have_posts() ) {
$rooms->the_post();
$rname = get_the_title();
$cap = get_post_meta(get_the_ID(), 'room_capacity' , true);
echo 'cname: ' . $cname . ' ' . 'enrolled: ' . $enr . 'rname: ' . $rname. 'capacity: ' . $cap . '<br/>';
}
}
}
} else {
echo "Loop not working";
}
wp_reset_postdata();
I think you'll want to use array_push there.
Here's a link to the doc.
Right now you're overwriting the $result variable each iteration.
I have big problem with my meta query. I would like to filter my posts, and I need query to compare post_title with my $_POST value.
Code:
function postsFilter(){
$args = array(
'post_type' => 'posts',
'meta_query' => array(
'relation' => 'AND'
)
);
if( isset($_POST['year']) && $_POST['year'] )
$args['meta_query'][] = array(
'key' => 'year',
'value' => $_POST['year'],
'compare' => '='
);
if( isset($_POST['theme']) && $_POST['theme'] )
$args['meta_query'][] = array(
'key' => 'theme',
'value' => $_POST['theme'],
'compare' => '='
);
if( isset($_POST['member']) && $_POST['member'] )
$args['meta_query'][] = array(
'key' => 'member_relation',
'value' => ``.$_POST['member'].``,
'compare' => 'LIKE'
);
$query = new WP_Query( $args );
echo "<script>
var posts_p = '" . json_encode( $query->query_vars ) . "',
current_page_p = " . 1 . " ,
max_page_p = " . $query->max_num_pages . ";
console.log(current_page_p, max_page_p);
</script>";
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
get_template_part('template-parts/content', 'posts');
endwhile;
if ( $query->max_num_pages > 1 )
echo '<div class="button-load-more_p btn-load-more text-center mx-auto w-100"><a class="btn btn-primary btn-md btn-with-icon fade-in full-visible load-more"><span>Load more</span></div></a></div>';
wp_reset_postdata();
else :
echo 'No publications found';
endif;
die();
}
and problem exists here:
if( isset($_POST['member']) && $_POST['member'] )
$args['meta_query'][] = array(
'key' => 'member_relation',
'value' => $_POST['member']
'compare' => 'LIKE'
);
because I don't know how to write this part of query,
member relation is POST OBJECT type file in Wordpress, I need compare $_POST['member'] with post_title value (maybe I am wrong ?)
$member = get_field('member_relation', $post_object->ID);
$member->post_title;
Is it possible to write this query? Please give me any advice or example solution of my problem.
Try This, merge your meta query argument with the post title arg.
if( isset( $_POST['title'] ) && !empty( $_POST['title'] ) ){
$args2 = array(
's' => '"'.$_POST['title'].'"'
) ;
$args = array_merge( $args, $args2);
}
I have a script that displays users who have published on my site.... Im wondering how I can set the limit that is shown to 10.. I'm new to PHP.. Would I be able to use a foreach to achieve this?
<?php
// Display the widget title
if ( $title ) {
echo $before_title . $title . $after_title;
}
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC'
);
$user_ids = get_users($args);
foreach ($user_ids as $user_id) {
if ($postcount) {
if(count_user_posts($user_id->ID)>0) {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
} else {
}
} else {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
}
}
You may try this (number):
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC',
'number' => 10 // <-- add this
);
You may also use offset, read more on Codex about get users().
The classic way would be to set a limit to your sql query
$args = array(
...
'posts_per_page' => 10
);
or your can add a counter
foreach ($user_ids as $user_id) {
$i++
...
if($i==10){break;}
}
I've been reading a lot of how to customize excerpt function in WordPress but I have no idea how to proceed with this.
The theme that I am using already have 4 pre-customized excerpt functions and the one that I will show here is closest to my desired but still needs to improve.
My question is how to stop erasing HTML formating from my content (line breaks, paragraphs, font variants, etc)?
add_shortcode('display_news_s5', 'be_display_posts_shortcode5');
function be_display_posts_shortcode5($atts) {
// Pull in shortcode attributes and set defaults
extract( shortcode_atts( array(
'post_type' => 'post',
'post_parent' => false,
'id' => false,
'tag' => '',
'category' => '',
'offset' => 0,
'posts_per_page' => '1',
'order' => 'DESC',
'orderby' => 'date',
'include_date' => false,
'include_excerpt' => false,
'excerpt_l' => 8,
'taxonomy' => false,
'tax_term' => true,
'tax_operator' => 'IN'
), $atts ) );
// Set up initial query for post
$args = array(
'post_type' => explode( ',', $post_type ),
'tag' => $tag,
'category_name' => $category,
'p' => $id,
'posts_per_page' => $posts_per_page,
'order' => $order,
'orderby' => $orderby,
'offset' => $offset
);
// If Post IDs
if( $id ) {
$posts_in = explode( ',', $id );
$args['post__in'] = $posts_in;
}
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = $post->ID;
}
$args['post_parent'] = $post_parent;
}
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $atts ) );
$count = 0;
if ( !$listing->have_posts() )
return apply_filters ('display_posts_shortcode_no_results', false );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$count++;
if( $count == 1 ){
$style = ' news-main-post';
} else {
$style = ' news-list-posts';
}
$title = '<div class="news-listing-title"><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></div>';
if ($include_date == 'true') $date = ' <div class="news-listing-meta"><span class="news-listing-date">'. get_the_date() . '</span><span class="news-listing-comment">('. get_comments_number() .')</span></div>';
else $date = '';
if ($include_excerpt == 'true') $excerpt = '<span>' .excerpt($excerpt_l) . '</span>';
else $excerpt = '';
$output = '<div class="news-listing' . $style . '"><div class="news-listing-item">'. $title . $excerpt . $date . '</div></div>';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $atts, $title, $excerpt, $date );
endwhile; wp_reset_query();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<div class="news-listing-wrapper-s3">' );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '<div class="clear"></div></div>' );
$return = $open . $inner . $close;
return $return;
}
Have a look here: LINK looks like its doing what you want to acchieve.