Save array from drop-down menu in Wordpress - arrays

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>';
?>

Related

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!

cakephp post data field missing from SQL update statement

Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)

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; ?>

cakephp 2.2.2 pagination search condition

I am trying to add pagination in CakePHP 2.x with condition search in a form. However, in the View it doesn't give the next page with my condition. Here is my code:
Controller
public function result($palabraclave = null)
{
$this->layout = 'tempart';
$this->paginate = array(
'limit' => 5,
'order' => array(
'Articulo.created' => 'desc'),
'conditions'=>array("titulo like ?"=>"%".$this->data['Paginas']['palabraclave']."%")
)
$data = $this->paginate('Articulo');//Consulta a la base de datos
$this->set(compact('data'));
}
If I click "next" to see the next page result of the search, it doesn't pass on the pagination condition from page 1 to page 2. :(
View:
<div style="display: inline-block; width:70%;" id="test">
<?php foreach ($data as $da): ?>
<br />
<article>
<?php echo $this->Html->image('article_preview/mini_'.$da['Articulo']['imagen'], array('alt' => 'Hospital-Excel'))?>
<div style="text-align:left;">
<?php echo $this->Html->link("<h6 class='artnombre'>".$da['Articulo']['titulo']."<h6>", array('class'=>"artnombre",'action'=> 'articulo',$da['Articulo']['id']),array('escape' => false)); ?>
</div>
<br />
<p>
<?php echo $da['Articulo']['descripcion']; ?> <?php echo $this->Html->link('Read more ....', array('action'=> 'articulo',$da['Articulo']['id'])); ?>
<h5></h5>
</p>
<div class="puntoshorizontal" style="clear"></div>
</article>
<?php endforeach; ?>
<div style="text-align:center">
<?php
// Shows the page numbers
// Shows the next and previous links
echo $this->Paginator->prev('« Back', null, null, array('class' => 'disabled')) . " |";
echo $this->Paginator->numbers(). "| ";
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo "<br />";
echo $this->Paginator->counter();
// prints X of Y, where X is current page and Y is number of pages
?>
</div>
</div>
a way to persist your search params on each page you should do the following:
After you post data, in your method you have $this->data['Paginas']['palabraClave'] then save it the the session. So in each subsequent call to /resultados/pag1,2,..n you get the value of palabra clave from the session.
Finally you would get something like:
public function resultados(){
$conditions = array();
if($this->Session->check('conditions')){
$conditions = $this->Session->read('conditions');
}
if(isset($this->data)){
$conditions = array("titulo LIKE" => "%".this->data['Paginas']'palabraclave']"%",));
//save to the session
$this->Session->write('conditions',$conditions);
}
$data = $this->painate('Articulo',$conditions);
$this->set('data');
}
This may need some adjust but the idea I think is clear.
Set your paginate conditions when calling the paginate method, like this:
$data = $this->paginate('Articulo', array(
"titulo LIKE" => "%" . $this->data['Paginas']['palabraclave'] . "%",
));
as opposed to in the paginate property.
this is example:
1: pass all URL arguments to paginator functions
$this->Paginator->options(array('url' => $this->passedArgs));
2: Common mistake: not keep condition search with paginate
if($this->data){
$this->passedArgs = array(
'name' => $this->data[‘User’]['name']
);
}else{
if(isset($this->passedArgs['name'])){
$this->data[‘User’]['name'] = $this->passedArgs['name'];
}else{
$this->data[‘User’]['name'] = ;
}
}

WordPress: How to merge custom post type array?

i try to setup a yearly (grouped by month) archive for custom post types in WordPress. But my code did not work as aspected. Maybe it is obiviously for someone who is more familar with WordPress and PHP but i can't get it work.
The code below is grouping by month but each post type by itself. Maybe i need to merge booth. But how?
<?php query_posts (array ('post_type' => array('images', 'articles')));?>
<?php
if (have_posts()) : while (have_posts()) : the_post();
// save month to a variable
$month = the_date('M', '', '', FALSE);
// If not used before print it
if ($month != $m_check) {
echo "<h2>" . $month . "</h2>";
}
// save month to check variable
$m_check = $month;
?>
<?php the_title(); ?><br/>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query();?>
Regards, Steve
You will need this: http://wordpress.org/extend/plugins/posts-to-posts/ to achieve what you want with custom posts.
Ok... after a cup of tea i got it with an other (probably better) approach.
Solution
<?php
$args = array(
'post_type' => array('images', 'articles'),
'numberposts' => -1,
'post_status' => null,
'post_parent' => null,
);
$posts = get_posts($args);
if ($posts) {
foreach ($posts as $post) {
setup_postdata($post);
$month = mysql2date('m', $post->post_date);
if ($month != $check) {
echo "<h2>" . $month . "</h2>";
}
// save month to check variable
$check = $month;
echo $post->post_title;
echo '<br/>';
}
}
?>
Output
07
Eagle creek
Lorem Ispum dolor
Vancouver Island
Ottawa
Vancouver
06
Losabim oxygenium
Now it needs just a bit beautifying and i am done. By the way #negatif, thank you for your suggestion.
Easy and correct way to merge our custom loop argument in default wordpress loop.
$argss = array(
'paged' => $paged,
'posts_per_page' => 9,
'meta_query' => array(
'relation' => 'OR',
array (
'key' => '_expiration-date',
'value' => $tode, // custom values
'compare' => '>='
),
array (
'key' => '_expiration-date',
'compare' => 'NOT EXISTS'
),
),
);
global $wp_query;
// Merge custom query with $wp_query
$merged_args = array_merge( $wp_query->query, $argss );
// Query posts using the modified arguments
query_posts( $merged_args );
if ( have_posts() ) : while (have_posts()) : the_post();
.
.
.
.
.
..
else : ?>
<p><?php _e('Apologies, but no entries were found.', 'tb'); ?></p>
<?php endif;
//wp_reset_query();
?>

Resources