WP_Query echoing arrays in different spots - arrays

Hello I need to echo a WP_Query in different areas so I can add content between each render post title..
SO basically I want to manual breakout the posts so I can place them around static content. Hope this is making sense.
I want to do something like this. Please see my notes.
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>'; // first post title
//echo 'some static content';
echo '<li>' . get_the_title() . '</li>'; //second post title
//echo 'some more static content';
endwhile;

You can use an array with all the static content:
$the_query = new WP_Query( $args );
$static_content = array ('content after first post','content after second post');
$counter = 0;
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
echo $static_content[$counter];
$counter++;
endwhile;

Related

Custom Fields - Repeater dropdown - list only unique & not blank values

Here's the thing that I'm using the ACF repeater subfield (firma) to store some data. Usually the user is typing here his parent company name like: google, alibaba, sodexo etc. So it might happen that in multiple posts, the value of this field will be the same. At the moment I have following code:
$args = array(
'post_type' => 'opencourses',
'meta_key' => 'terminy_warsztatow'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
echo '<select type="text" class="form-control" name="filtr_lokalizacja">';
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('terminy_warsztatow')):
while (have_rows('terminy_warsztatow')) : the_row();
// display your sub fields
$filtr_var = get_sub_field('firma');
echo '<option value="'. $filtr_var .'">';
echo $filtr_var;
echo '</option>';
endwhile;
else :
// no rows found
endif;
endwhile;
echo '</select>';
endif;
And it works - meaning: it shows all typed values. But instead of showing only UNIQUE values it generates a list similar to this:
Google
Alibaba
Google
Sodexo
Sodexo
Tesla
Tesla
Sodexo
How to avoid showing same values and hide empty as well? I know that there is php function array_unique but I was unable to implement that. I've done sth like:
$filtr_var = get_sub_field('firma');
$result = array_unique($filtr_var);
echo $result;
but then it shows no values at all.
I assume that "firma" is simple text input type in repeater. if so then arrya_unique function won't work for string output.
you need to save each value in array and then use in_array function to make it unique.
see below code.
$args = array(
'post_type' => 'opencourses',
'meta_key' => 'terminy_warsztatow'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
echo '<select type="text" class="form-control" name="filtr_lokalizacja">';
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('terminy_warsztatow')):
// $PreValue = array();
while (have_rows('terminy_warsztatow')) : the_row();
// display your sub fields
$filtr_var = get_sub_field('firma');
// compare current value in saved array
if( !in_array( $filtr_var, $PreValue ) )
{
echo '<option value="'. $filtr_var .'">';
echo $filtr_var;
echo '</option>';
}
// save value in array
$PreValue[] = $filtr_var;
endwhile;
else :
// no rows found
endif;
endwhile;
echo '</select>';
endif;
Hope this will help you!
Enjoy

how can i combine href with id number

Trying to get some data from db but I can't use href with id number in code.
I tried everything but coldn't make it.
<?php
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array($db->quoteName('title')));
$query->select(array($db->quoteName('id')));
$query->select(array($db->quoteName('start_date')));
$query->select(array($db->quoteName('end_date')));
$query->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
$results = $db->loadObjectList();
// display the results
foreach ( $results as $result) {
echo <<<HTML
$result->title .
HTML;
echo "<p>" . $result->start_date . "</p>";
echo "<p>" . $result->end_date . "</p>";
}
?>
I will be appreciated if someone help me.
Thanks in advance
Demonstration of issue then my suggested solution: (Online Demo)
$result = new stdClass();
$result->id = 333;
$result->title = 'title text';
echo <<<HTML
$result->title .
HTML;
Output:
Notice: Undefined variable: id in /in/s1YZG on line 7
title text .
Notice that $id isn't a declared variable. If it was, it would be rendered but all characters between the curly braces are treated literally because you are trying to echo within an echo.
Without heredoc syntax (heredoc can be funny about tabbing depending on php version):
echo "{$result->title} . "; // curly braces may help IDEs with highlighting
New Output:
title text .
As for your query building syntax...
You can save some typing and chain the method calls onto getQuery().
None of the quoteName() calls are necessary for stability/security, but if you insist on toeing Joomla's preferred practices, you can call quoteName() on the array in select().
Suggested Code:
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(array('title', 'id', 'start_date', 'end_date')))
->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
if (!$results = $db->loadObjectList()) {
echo "No results";
} else {
foreach ($results as $row) {
echo "{$row->title} . ";
echo "<p>{$row->start_date}</p>";
echo "<p>{$row->end_date}</p>";
}
}
Here is another post where loadObjectList() is called after a SELECT query which includes query error checking: https://joomla.stackexchange.com/a/22963/12352
When you have Joomla questions, please post them on Joomla Stack Exchange.
I would try it like this:
also you are trying to echo $id which isnt assigned. should be $results->id
<?php
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('title', 'id', 'start_date', 'end_date' ));
$query->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
$results = $db->loadObjectList();
// display the results
foreach ( $results as $key => $result) {
echo ' <a href="index.php?option=com_rbids&task=viewbids&id='.$result->id .'>'.$result->title .'</a>';
echo "<p>" . $result->start_date . "</p>";
echo "<p>" . $result->end_date . "</p>";
}
?>

Loop to display one product / several products by sku on Woocommerce?

I'm attempting to display one or more specific product(s) on my home page on Woocommerce, in a very simple fashion :
name of the product;
short description of the product;
price of the product;
quantity selector;
add to cart button;
Now, i've created a custom loop for doing so:
<?php
$args = array(
'post_type' => 'product',
'sku' => 'lundivegetarien',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
echo woocommerce_template_single_excerpt();
echo woocommerce_template_single_price();
echo woocommerce_template_single_add_to_cart();
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
Main problem here is that this loop displays all my products, irrespectively of the sku i'm trying to call. I would like to be more specific, and be able to choose to display one or several products i'd call by their specific sku.
What am i doing wrong?
Any pointers?
Help appreciated!
Sorted out the problem myself eventually, so dumb i was! Just turned to using categories and it works pretty fine!
Here's the updated code in cas anybody needs it!
<?php
$args = array( 'post_type' => 'product', 'product_cat' => 'name_of_the_category', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>
<p>
<?php
the_title();
?>
</p>
<?php
echo woocommerce_template_single_excerpt();
echo $product->get_price_html();
?>
<div class="order_form close">
<p>
<?php
woocommerce_template_loop_add_to_cart( $loop->post, $product );
?>
</p>
</div>
<br>
<?php
endwhile;
?>
Hope this will help someone!

Save array from drop-down menu in Wordpress

I have successfully pulled a custom post type through into a drop-down that is in a custom meta box. However, when displaying it on the front end I would like to also provide a link to the actual post, not just the name of the post. So I am guessing I need to save this as an array? Is this possible through a drop-down? Confused on how I should approach this. Any help is greatly appreciated.
Here is what I have so far:
// Add Meta Box To Select Overseeing Pastor
add_action('admin_init', 'ministry_select_add_meta');
function ministry_select_add_meta(){
add_meta_box('ministry_select_post', __('Overseeing Pastor'), 'ministry_select_meta', 'ministry', 'side');
}
function ministry_select_meta( $post ) {
$values = get_post_custom( $post->ID );
$selected = isset( $values['pastor_select'] ) ? esc_attr( $values['pastor_select'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<select name="pastor_select">
<?php
$args = array(
'post_type' => 'employee',
'position' => 'pastor'
);
$pastorList = new WP_Query($args); while ($pastorList->have_posts()) : $pastorList->the_post();
$is_selected = (get_the_title() == $selected) ? 'selected="selected"' : '';
echo '<option value="'.get_the_title().'" '.$is_selected.'>'.get_the_title().'</option>';
endwhile; wp_reset_postdata();
?>
</select>
<?php
}
add_action( 'save_post', 'ministry_select_save' );
function ministry_select_save( $post_id )
{
// Stop If Autosaving
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// Stop If Nonce Can't Be Verified
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// Stop If Unauthorized User
if( !current_user_can( 'edit_post' ) ) return;
// Make Sure Data Is Set Then Save
if( isset( $_POST['pastor_select'] ) )
update_post_meta( $post_id, 'pastor_select', esc_attr( $_POST['pastor_select'] ) );
}
To get the link of a Post you can use the get_permalink function
<?php $permalink = get_permalink( ); ?>
or like this if you are outside the Loop
<?php $permalink = get_permalink( $post->ID ); ?>
You can use that to print it in any place on your HTML code.
If what you want is go to the Post URL when the Post Title is selected in the Drop Down you can use JavaScript code to do that, doing something like:
<select name="pastor_select" onchange='location=this.options[this.selectedIndex].value;'>
<?php
$args = array(
'post_type' => 'employee',
'position' => 'pastor'
);
$pastorList = new WP_Query($args); while ($pastorList->have_posts()) : $pastorList->the_post();
$is_selected = (get_the_title() == $selected) ? 'selected="selected"' : '';
echo '<option value="'.get_permalink( ).'" '.$is_selected.'>'.get_the_title().'</option>';
endwhile; wp_reset_postdata();
?>
</select>
If what you want is save some POST information, is recommended save the ID of the POST, so later you can retrieve any data for that POST, what if you want to store permalink and title you can combine the functions get_permalink( ); and get_the_title(); in the select "value" attribute.
So I came up with a different solution. Instead of trying to save an array, I just saved the post ID which would allow me access to the title of the post as well as the permalink.
This is my modified code
<select name="pastor_select">
<?php
$args = array(
'post_type' => 'employee',
'position' => 'pastor'
);
$pastorList = new WP_Query($args); while ($pastorList->have_posts()) : $pastorList->the_post();
$employeeID = get_the_ID(); // THIS FIXED THE PROBLEM
$is_selected = ($employeeID == $selected) ? 'selected="selected"' : '';
echo '<option value="'.$employeeID.'" '.$is_selected.'>'.get_the_title().'</option>';
endwhile; wp_reset_postdata();
?>
</select>
And this is how I am calling it on the front end
<?php
$id = $post_meta_data['pastor_select'][0];
echo '<a href="'.get_permalink($id).'">';
echo get_the_title($id);
echo '</a>';
?>

Create a custom loop with post IDs taken from Magic Fields 2 duplicate text fields

I'm trying to create a custom loop with content related to specific post IDs whose numbers I'm getting from a Magic Fields duplicate text field called "reference_posts".
When I echo $testvalue; it outputs the correct listing of posts "20432,43242,34253," but when I try to output it inside the array I only get the first value repeated over and over "20432,20432,20432,".
I'm guessing the problem is that I have to envelope the second foreach within the first but I'm not managing to do that.
Can anyone help me out?
<?php
$value = get_field ('reference_posts') ;
foreach ( $value as $my_val ) {
$testvalue = $my_val . ",";
echo $testvalue;
$post_idarray = array( 'post__in' => array( $testvalue ) );
$postspecial = get_posts($post_idarray);
}
foreach( $postspecial as $post ) :
setup_postdata($post);
?>
<div>my content</div>
<?php endforeach; ?>
Thanks in advance!
Got it with:
<?php
$value = get_field ('reference_posts') ;
foreach ( $value as $my_val );
$args = array( 'include' => $value );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div>my content</div>
<?php endforeach; ?>

Resources