PHP - Retrieving data from repeater fields in WordPress - php

I have a custom field in WordPress called listing-two. listing-two is a simple repeater field which allows you to add another item to a list.
Since a list may have x amount of listings, what is the best way to retrieve the data from that field? At the moment I have
'listingTwo'=> get_field('listing-two')
Which will not work since there are multiple fields?
I've seen the AFC documentation to get an idea of how to get data, but none of them seem to work?
Edit:
I'm thinking the best way to go about this is via a for loop? I've tried the following, still not pulling anything through:
$textareaTwo = get_sub_field("listing-two");
if ($textareaTwo && count($textareaTwo)>0){
foreach ($textareaTwo as $textareaTwos){
$res = get_post($textareaTwos);
echo'Test'.$res;
}
}
Repeater field structure:
Field name: listing-two -> Has a sub field, with the field name list_item

Try this,
if(get_field('listing_two')){
$lists = get_field('listing_two');
foreach($lists as $list){
echo $list;
}
}

below is the code by which you can get all fields within listing_two
<?php if( have_rows('listing_two') ):
while( have_rows('listing_two') ): the_row();
// vars
$sub_field1 = get_sub_field('sub_field1');
$sub_field2 = get_sub_field('sub_field2');
$sub_field3 = get_sub_field('sub_field3');
echo $sub_field1;
echo $sub_field2;
echo $sub_field3;
endwhile;
endif; ?>

Related

Declare order to show foreach output with PHP

I am currently trying to set up a custom sortable list. Without getting into too much detail as this would become a very large post, I would like to use the PHP foreach function to show the list.
I currently have
$video_id = $row['videos'];
$res = preg_replace("/[^0-9,.]/", "",$video_id);
$exclude = explode(',', $res);
} ?>
....
<ul id="sortable2" class="connectedSortable">
<?php foreach ($video_list as $key => $item): ?>
<?php if(in_array($item['id'], $exclude)){ ?>
<li id="video-<?php echo $item['id'] ?>"><?php echo $item['id'],
$item['title'] ?></li>
<?php } ?>
<?php endforeach; ?>
</ul>
This generates a list of items from the database excluding items with an ID from an array which is also fetched from another table.
In this example, it will only show videos with the id 3,4 and 2. This is all working as expected. My issue is once I have reordered the items and refreshed the page they are loaded in numerical order. I need these to be load in the order specified (3,4 and 2 for this example).
Any help would be highly appreciated.
Thanks
I think what you are looking for is ORDER BY FIELD (MySql), this lets you order by a field in a specific way.
I need these to be load in the order specified (3,4 and 2 for this example).
Sounds like a good fit to me!
For example
SELECT * FROM table WHERE id IN(3,4,2) ORDER BY FIELD(id, 3,4,2)
This will select rows from table where the id is in the list and then order the results by id in the order they are place there, 3 then 4 then 2.
excluding items with an ID
This might cause some issue, the Field order by assumes you know at least some of the values in the field. Excluding implies that you know what you don't want but not necessarily what you do want, if that makes sense.
Maybe it's not an issue, I don't have enough information on your particular use case to determine that, so I am just mentioning it as a cautionary thing.
Thanks!

Foreach loop (or do while maybe?) - Want to return only one record depending on page

Solved this with edited code below. Thanks to all who helped!
I have two records in my db. Each record has 6 fields (challengeId, partnerName, code, challengeTitle, description, image_url). I select a given partnerName from my parent page view to go to my child page view.
I was using a foreach loop and having problems. I have now taken out my foreach loop and replaced it with <?php $challengename = $this->challengenames[$k] = current($this->challengenames); ?> but now cannot get the child page to display the values for challengeTitle that correspond to 'partnerName' I chose on my parent page. It always provides the challengeTitle value of the first record instead of the current record. I need to know how to make the challengeTitle value change depending on which partnerName I chose on my parent page.
Will making this a do while loop or if statement in the child page controller fix this?
Any advice (and code changes) is very much appreciated.
parent page controller
public function viewChallengesAction(){
//get instance for request
$request = JO_Request::getInstance();
//get activated challenge names and set variables
$myChallenge=$this->getChallenge();
$this->view->challengenames = array();
foreach($myChallenge AS $k=>$challengename){
$this->view->challengenames[$k]['href'] = WM_Router::create($request->getBaseUrl() . '?module=challenges&controller=index&action=yourChallenge?code=' . $challengename['partnerName']);
$this->view->challengenames[$k]['partnerName'] = $challengename['partnerName'];
}
CHILD VIEW
<div id="defaultcontainerwrapper" class="maxwidth">
<?php $challengename = $this->challenge; ?>
<header>
<h1>
<div class="list">
<span>Welcome to </span><?php echo $challengename['partnerName']; ?><span>'s Beat Waste Challenge!</span>
</div>
</h1>
</header>
<?php } ?>
</div>
CHILD CONTROLLER
public function yourChallengeAction(){
//get activated challenge names and set variables
$request = JO_Request::getInstance();
$myChallenge=$this->getChallenge();
$code = $request->getQuery("code");
$this->view->challengenames = array();
foreach($myChallenge AS $k=>$challengename){
if ($challengename['partnerName'] == $code)
{
$this->view->challenge = $challengename;
break;
}
}
If you don't know the key and want the current element of the array, you could use:
$challengename = current($this->challengenames);
Or the first element of the array:
$challengename = reset($this->challengenames);
Or the last element of the array:
$challengename = end($this->challengenames);
Just note that end and reset will change the pointer location of the array.
<?php $challengename = $this->challengenames[0] ?>
You are missing a last ; try add it agaign;
try below:
<?php $challengename = $this->challengenames[0]; ?>

Displaying Search Fields

This may not be enough information for anyone to answer this, but I might just be missing something y'all would know by looking at the code.
In my site's admin panel, I can assign custom fields to categories (No. of beds, baths, whatever I create), but in order for the fields to show up on the Advanced Search page, you have to assign the field(s) to all of my sites categories.
I am trying to get the field(s) to show up all the time, even if they are only assigned to certain categories, not all of them.
Here is the code that renders the fields on the Advanced Search page, but again, only renders them if the field is assigned to all categories:
<?php
$get_catID = get_CATID($_GET['ad_cat_cat']);
if(empty($get_catID)) $get_catID = 0;
$get_catID = array($get_catID);
$arr = get_category_fields_without_vals($get_catID, 'no');
for($i=0;$i<count($arr);$i++)
{
echo '<tr>';
echo '<td>'.$arr[$i]['field_name'].$arr[$i]['id'].':</td>';
echo '<td>'.$arr[$i]['value'].'</td>';
echo '</tr>';
}
?>

How to pass array values of checkbox to next part in multi-part form

I have a site based on wordpress. I need to allow people to create posts from frontend so I have made a multi-part form which works pretty well. There are three parts of the form and each part of the form is validated before moving to the next part. Data is passed to another page through hidden inputs.
My form template looks somewhat like this ( complete code is pretty massive and irrelevant here, so just showing just the relevant parts ) which I hope is enough to give an idea how the form works.
MULTI-PART FORM WP-TEMPLATE SAMPLE CODE :
<?php
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$page = $_POST['page'];
if ( $page == NULL ) { ?>
<?php include_once('multiparts/form-files/first_part.php'); ?>
<?php } else if ( $page == 1 ) { ?>
<?php include_once('multiparts/validation/validate_first_part.php');
if (isset($_POST['submit-1']) && (!empty($error))) { ?>
<div class="error-head">Cannot continue registration. Error/s highlighted below.</div><br/>
<?php echo $error . '</br>'; ?>
<?php } else {
include_once('multiparts/form-files/second_part.php');
}
?>
<?php
} else if ( $page == 2 ) { ?>
//SO ON AND SO FORTH
<?php
}
?>
Recently, I have a added several checkbox fields in the form with an intention to display values of selected checkboxes, in the created posts. So here is a relevant html form code that I am currently using.
<fieldset class="work-areas">
<label for="areas" class="label">INTERESTED IN :</label></br>
<div class="work-class">
<input type="checkbox" name="workareas[]" value="administration"/>administration</br>
<input type="checkbox" name="workareas[]" value="technical"/>technical</br>
<input type="checkbox" name="workareas[]" value="creative"/>creative</br>
<input type="checkbox" name="workareas[]" value="fieldwork"/>fieldwork</br>
<input type="checkbox" name="workareas[]" value="marketing"/>marketing</br>
</div>
</fieldset>
I insert the values of these checkboxes into the post just like any other custom fields using this code: add_post_meta($pid, 'areas', $workareas, true );. In the processing part it is assigned a meta_key areas. I display it in the single.php with the code below :
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
ISSUE: All this works well when the above given html form code for checkboxes is in the last/third part of the form. But it does work when the same checkbox fields is in the second part of the form. I guess it simply does not pass the array values of the selected checkboxes to the third part. Print_r shows an empty array and obviously does not display anything in the single.php too. Although I understand that the trouble is just the array of selected checkbox values, NOT being carried to the third part properly, I need help as I am noob to all this.
So the bottomline question is how do I save the array of the selected
checkboxes' values in the second part and carry it to the third part
and finally assign it to a variable which will hold the array values.
That which can be displayed in post using the code above.
THINGS TRIED : I have looked into this thread here and I am confused where I will insert my checkbox fields and not even sure it applies to my situation. I have been able to pass other text input values from one part to another part of the from using something like this :
<input type="hidden" name="eligible" value="<?php echo $eligible;?>" />
So, I tried using name="workareas[]" but did not work. I am doing print_r() for everything I am trying and till now have only been getting empty array. I am still going through tons of other threads looking for possible hints. In the meanwhile if you can help, that will be great. Thanks in advance.
UPDATE : Solved, please check the answer.
Not a WP user but your checkboxes are named "workareas" but you seem to refer to them as "areas" everywhere else.
Thanks for the suggestions in the comments but I have found a graceful and robust solution in my opinion, that is using sessions. I followed the basic idea from here which actually deals with a multipart form with sessions. Now I have the following code in my third/last part of the form, at the very beginning of the document. At this time please remember that the html checkbox fields as illustrated above in the question are in the second part.
<?php
session_start();
$_SESSION['workareas'] = $_POST['workareas'];
$result=$_POST['workareas'];
?>
The code is that is repeated during the validation of the third part is the same but this way the variable $result is still holding the values of the array of the selected checkboxes from the second part of the form.
session_start();
$result=$_SESSION['workareas'];
You can do a print_r($result) at this point and check. Furthermore, if you want to insert these array values to post in order for them to show up in the post just assign meta_key eg. areas to $result and use the code below to add it as a custom field :
add_post_meta($pid, 'areas', $result, true);
In the single.php you can use the code below to pull values from the array and show. Do not avoid if(is_array) statement else wordpress might throw an error warning: invalid arguments supplied foreach(). Goodluck.
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>

Pull Content Regardless of whether user has posts or not

This post relates to WordPress and CIMY User Extra Fields. I do not think you need a knowledge of the latter to help with this problem, as it seems to be a WordPress issue more than anything.
CIMY User Extra Fields is a plugin that allows registered users to have much more information in their profiles. You can add as many fields as you want. You then have to edit "author.php" to pull in the new information.
I am currently using the following code to pull in the new user profile fields:
<?php if (have_posts()) { $flag = true; while (have_posts()) { the_post();
if ($flag) { $value = get_cimyFieldValue(get_the_author_ID(), 'dj-name');
if ($value != NULL) echo "<p><strong>Staff Bio: </strong>" . cimy_uef_sanitize_content($value);
echo "</p>";
$flag = false; }}}?>
The issue is this. Some of my users have 0 posts and this code will only pull the extra field content for the user if that have 1 post or more. This is due to the "if (have_posts())" function I suspect. Is there someway to modify the code to display the information even if the user has 0 posts?
Thanks
Zach
If it's not a need that a user must have a post to have CIMY values stored (which I assume), you just don't need to check for post-count > 0. You probably have copied that chunk of code over from a post template.
The following example just takes the value, and if it is set, will do the output via echo:
<?php
$authorID = get_the_author_meta('ID');
$value = get_cimyFieldValue($authorID, 'dj-name');
if (!empty($value))
echo '<p><strong>Staff Bio: </strong>'
, cimy_uef_sanitize_content($value)
, '</p>'
;
?>

Categories