The code below produces an array of ids for all the published post types
// Test Function
add_action('wp_head', 'testa');
function testa() {
$city = get_post_meta( 47, 'wpsl_city', true ); // Echos the correct meta for a single id
$all_post_ids = get_posts(array(
'fields' => 'ids',
'posts_per_page' => -1,
'post_type' => 'wpsl_stores',
'post_status' => 'publish'
)); // Echos a list of ids for CPT
echo json_encode($all_post_ids);
}
How do I produce an array of meta values for 'wpsl_city' instead the post id?
Ex:
Right now I get [1,2,3]
Post ids
I need [New York, Chicago, Miami]
Corresponding post meta values for 'wpsl_city'
You have to iterate a loop of $all_post_ids. so you can get post id to get post meta value. try the below code.
// Test Function
add_action( 'wp_head', 'testa' );
function testa() {
$all_post_ids = get_posts(array(
'fields' => 'ids',
'posts_per_page' => -1,
'post_type' => 'wpsl_stores',
'post_status' => 'publish'
)); // Echos a list of ids for CPT
foreach ( $all_post_ids as $key => $post_id ) {
$city = get_post_meta( $post_id, 'wpsl_city', true ); // Echos the correct meta for a single id
echo implode(',', $city); // assume value as array.
}
}
Here is the final solution that worked for me:
add_action('wp_head', 'testa');
function testa() {
$city = array();
$all_post_ids = get_posts(array(
'fields' => 'ids',
'posts_per_page' => -1,
'post_type' => 'wpsl_stores',
'post_status' => 'publish'
)); // Echos a list of ids for CPT
foreach ( $all_post_ids as $key => $post_id ) {
$city[] = get_post_meta( $post_id, 'wpsl_city', true ); // Echos the correct meta for a single id
}
echo json_encode($city);
}
Related
I have registered a custom taxonomy as part of my custom post type, but when passing it through to get_categories() it returns an empty array. Any ideas as to why?
// Register FAQ Categories taxonomy
function bv_faq_register_categories() {
register_taxonomy(
'faq-category',
'faq',
array(
'label' => 'Categories',
'rewrite' => array('slug' => 'faq-category'),
'hierarchical' => true
)
);
}
add_action('init', 'bv_faq_register_categories');
// Category view
$categories = get_categories(array(
'taxonomy' => 'faq-category'
));
$categories is returning an empty array.
Have you tried get_terms instead?
$categories = get_terms( 'faq-category', array(
'orderby' => 'count',
'hide_empty' => 0
) );
Like #AD Styles said I would use get_terms using the custom taxonomy, to expand a bit here's some example code:
<?php
$post_type = 'faq-category';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) );
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'parent' => 0
) );
foreach( $terms as $term ) :
echo "<h1>".$term->name."</h1>";
endforeach;
endforeach;
?>
Your code looks ok. Do you have assigned this category to any post/post type?
If not then you will get an empty result. for testing you can set 'hide_empty' = false like this:
// Category view
$categories = get_categories(array(
'taxonomy' => 'faq-category',
'hide_empty' => false // set it true
));
Also, you can use get_terms() function.
how to fetch data from database in drupal7:
fields i have name:
subject:
email:
message:
give me the code for drupal 7 i want it in table form.
my insert code is this:
function form_example_form_submit($form, &$form_state) {
echo $name = $form_state['values']['textfield'];
echo $email = $form_state['values']['mail'];
echo $subject = $form_state['values']['subject'];
echo $message = $form_state['values']['message'];
echo $ip=ip_address();
echo $cb=$name;
//echo $timestamp = REQUEST_TIME;
echo $time=time();
$nid=db_insert('form') // Table name no longer needs {}
->fields(array(
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message,
'ip' => $ip,
'created_by' => $cb,
//'created_at' => $time,
))
->execute();
//print_r($nid);
drupal_set_message(t('The form has been submitted.'));
}
how can i fetch the data from database in drupal 7 in the form of table ,
give me the code .i m newbie in drupal 7 so its very difficult forme
Here is the snippet to fetch all content from "form" table with table format and pager. Also you can add condition which I have added in comment if required.
<?php
// Set header
$header = array(
array('data' => t('Name'), 'field' => 'name'),
array('data' => t('Email'), 'field' => 'email'),
array('data' => t('Subject'), 'field' => 'subject'),
array('data' => t('Message'), 'field' => 'message'),
);
//query to fetch all content
$query = db_select('form', 'f');
$query->fields('f');
//$query->condition('f.name', $search_name, '=') //if needed
$table_sort = $query->extend('TableSort') // Table sort extender
->orderByHeader($header); // Order by headers
$pager = $table_sort->extend('PagerDefault')
->limit(20); // Set page limit
$arr_result = $pager->execute();
$rows = array();
foreach($arr_result as $result) {
$rows[] = array(
$result->name,
$result->email,
$result->subject,
$result->message,
);
}
// Set empty output
$output = '';
if (!empty($rows)) {
$output = theme('table', array(
'header' => $header,
'rows' => $rows,
/*'attributes' => array(
'id' => 'sort-table' // add if want to add sorting
) */
));
$output .= theme('pager');
}
else {
$output .= t("No results found.");
}
return $output;
?>
Let me know if any query/confusion occurs for the same.
I’m trying to write a WP_Query which uses some data from two ACF checkboxes as part of the arguments.
I found the documentation showing how to use fields in custom queries however I cannot work out what the correct syntax for my checkboxes is.
My ACF’s:
Label: Promote to homepage?
Name: promote_to_homepage
Choices: Promoteto homepage : Promote to homepage
Label: Make feature?
Name: make_feature
Choices: Show as feature : Show as feature (top of homepage)
This is the query I have:
$the_query = new WP_Query(
array
(
'posts_per_page' => 1,
'meta_key' => 'promote_to_homepage',
'meta_value' => 'Promote to homepage',
'meta_key' => 'make_feature',
'meta_value' => 'Make feature'
)
);
I guess what I can’t figure out is why data is actually needed for meta_key and meta_value. Is the key the label? Is the value one of the choices? Or do I need to use meta_value => true or something? I have tried many variations and cannot get it to work.
Essentially what I want to do is output the most recent post that is checked for “Promote to homepage” and “Make feature”.
I have also tried:
array
(
'posts_per_page' => 1,
'meta_key' => 'promote_to_homepage',
'meta_value' => true,
'meta_key' => 'make_feature',
'meta_value' => true
)
Edit
This is the new code I have tried:
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'promote_to_homepage',
'value' => true,
),
array(
'key' => 'make_feature',
'value' => true,
),
)
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<h2>' . get_the_title() . '</h2>';
echo '<p>' . get_the_excerpt() . '</p>';
echo '<p>Read more</p>';
}
}
wp_reset_postdata();
Another option is to get a lot of posts like this:
$args = array(
'post_type' => 'posts',
);
$posts = get_posts($args);
foreach($posts as $item) :
$make_feature = get_post_meta($item->ID, 'make_feature', true );
var_dump($make_feature); //test
$promote_to_homepage = get_post_meta($item->ID, 'promote_to_homepage', true );
var_dimp($promote_to_homepage); //test
if(isset($make_feature) && isset($promote_to_homepage)):
print_r($item);
endif;
endforeach;
Check if this works first before limiting posts. If you don't get any results from var_dump variables, there's something up with ACF.
$args = array(
'post_type' => 'post', //replace 'post' with cpt if you need to.
'posts_per_page' => 1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'promote_to_homepage',
'value' => '1',
'compare' => '=='
),
array(
'key' => 'make_feature',
'value' => '1',
'compare' => '=='
),
)
);
$the_query = new WP_Query($args); // This will return posts and other data
$the_query = get_posts( $args ); // This will return the posts
How's that for ya? Choose WP_Query OR get_posts: get_posts will return the posts data from wp_query anyway so you may as well just use that.
I'm not entirely sure what you mean by 'true/yes' but you can play around with the values. If the key value in the custom field is literally 'true/yes' then you better have that as the value in the args - otherwise yes or true will do.
I'm trying to come up with a single array of all values in specific custom fields. The values themselves are also arrays. I've tried all sorts of array functions but haven't come across the right one or the right combination. Here is my code thus far:
$args = array(
'post_type' => 'match_report',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'report_home-scorers'
),
array(
'key' => 'report_away-scorers'
)
)
);
$reportscore = new WP_Query($args);
$scorersResults = array();
if ( $reportscore->have_posts() ) {
while ( $reportscore->have_posts() ) {
$reportscore->the_post();
$homescorers = get_post_meta($post->ID,'report_home-scorers',false);
$awayscorers = get_post_meta($post->ID,'report_away-scorers',false);
foreach ($homescorers as $homescorer){
array_push($scorersResults, $homescorer);
}
foreach ($awayscorers as $awayscorer){
array_push($scorersResults, $awayscorer);
}
?>
<?php } wp_reset_postdata(); //endif
}//endwhile
$scorerResults = remove_empty($scorersResults);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
Here what I get if I print_r($scorerResults); :
Array
(
[1] => Array
(
[0] => 1
[1] => 63
)
[2] => Array
(
[0] => 263
[1] => 195
)
[3] => Array
(
[0] =>
)
[4] => Array
(
[0] =>
)
)
I just want the values in the internal arrays in an array.
Assuming you want the $scoreResults array to end up as array(1,63,263,195) you could use the array_reduce function like this:
function gatherScores($lhs, $rhs) {
foreach ($rhs as $key => $value)
if ($value)
$lhs[] = $value;
return $lhs;
}
$scorerResults = array_reduce($scorerResults, "gatherScores", array());
I'm not sure what the blank values are in your third and fourth arrays and how they should be handled, so you may need to change the if ($value) condition to check for something different. As it stands it'll obviously also filter out zero scores.
What I am trying to do is display a table with checkboxes on the press of a button by ajax. The table should be initially hidden and get populated on the fly by a function call.
If initially I load $options1 with some dummy values , then after ajax call it throws in an error saying-
Notice: Undefined index: red in theme_tableselect() (line 3285 of
D:\wamp\www\drupal7\includes\form.inc).
where 'red' is the index of a dummy row value and #options don't get populated with the new values. What is the way to get this working ?
Here is the code for the form-
$form['mltag_new']['tag'] = array(
'#type' => 'button',
'#value' => t("Suggest Tags"),
'#ajax' => array(
'callback' => 'mltag_suggest_tags_ajax',
'wrapper' => 'mltag_suggest_tags_table_div',
'effect' => 'slide',
),
);
$options1 = array(); //initial dummy values
$options1['red']['tag'] = "A red row";
$options1['red']['chi'] = "A red row";
$form['mltag_new']['myselector'] = array (
'#type' => 'tableselect',
'#title' => 'My Selector',
'#header' => $header,
'#options' => $options1,
'#prefix' => '<div id="mltag_suggest_tags_table_div">',
'#suffix' => '</div>',
);
return $form;
and the Ajax callback looks something like this-
function mltag_suggest_tags_ajax($form, $form_state) {
//$content has some content
//pass the content to a function
include_once 'includes/content_tag.inc';
$tags = mltag_content_tag($content, variable_get('algo_type'), 20);
if (empty($tags)) {
$output .= t('Content is insufficient to generate Tags using this algorithm. <br>Please choose other algorithm from Settings Page.');
$form['mltag_new']['sample_text']['#markup'] = $output;
return $form['mltag_new']['sample_text'];
}
else {
$algo = variable_get('algo_type');
if ($algo == 1) {
$header = array(
'tag' => t('Tag'),
'frequency' => t('Frequency'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'frequency' => $value,
);
}
}
elseif ($algo == 2) {
$header = array(
'tag' => t('Tag'),
'chi' => t('Chi Square Value'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'chi' => $value,
);
}
}
$form['mltag_new']['myselector']['#header'] = $header;
$form['mltag_new']['myselector']['#options'] = $options;
return $form['mltag_new']['myselector'];
}
}
I replied to your post on Drupal.org about how I'm working on a somewhat similar problem. Try adding
$form['mltag_new']['myselector'] =
form_process_tableselect($form['mltag_new']['myselector']);
just before your return. Hopefully that helps you more than it did me. Beware that the #options just get rendered when the block reloads from the ajax, but the original $form object doesn't seem to be aware.
I know that this is a few years later, but I found this while searching for my own solution:
The tableselect module creates checkboxes in the $ form that have to be removed. in the example above, they would be in $form['mltag_new']['myselector'] with keys equal to the original $option1 in your original code. If you unset those, then call
$form['mltag_new']['myselector'] = form_process_tableselect($form['mltag_new']['myselector']);
before your return, it will eliminate the dummy rows.