How to filter New WP Query by Custom Field Value? - categories

I am creating new pages for each of my categories in wordpress. The post editor has a custom field that allows the selection of a sector type, this gets applied to the post on update. The custom field key is: sector, for custom field meta value options lets use SectorA, SectorB and SectorC. I am using a custom post type called projects.
I followed the advice at this link http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
How can I change the query line in the code below so that it filters the loop by a Sector name, lets use SectorA. I'll then reuse the code on each template page changing the value to SectorB and SectorC on the other pages.
I think this needs changing somehow:
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );
Currently it echos the sector value and description value successfully but is showing all the posts. So my attempt to limit it to sectorA using sector=sectorA doesn't seem to work?
This code is in functions.php:
function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}
And this code is on the Template Page:
<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$sector = get_post_custom_values("sector");
$description= get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>
Thanks for your help

May be this what you want
function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}
and modification of page
$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');

Try using this code.
<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>
<!-- If there are no custom fields, show nothing -->
<?php } else { ?>
<div class="sector">
<h3>Title</h3>
<?php foreach($sector as $sector) {
echo '<blockquote><p>'.$sector.'</p></blockquote>';
} ?>
</div>
<?php } ?>

Related

Zend : Error Occurs when create html file from zend phtml file for multiple employee

//controller function
function sendBulkMailAction(){
$template = "estimated-festival-bill-single.phtml";
foreach ($employeeArr as $profile_id => $employeeValue) {
$someData = array(); //here include some salary data
$model = new ViewModel($someData);
$model->setTemplate($template);
$htmlContent = "<!DOCTYPE html>\n\r<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\r<head>
<meta charset=\"utf-8\">
</head>
<body>"
. $this->getServiceLocator()->get('viewrenderer')->render($model)
. "</body>
</html>";
//create html file
//create pdf link from html by wkhtmlToPdf
//send this link via email to employee
}
}
//estimated-festival-bill-single.phtml
//simple code
<div> Employee Name</div>
<br>
<div><?php echo _get_salary_html(); ?></div>
<?php
function _get_salary_html(){
return "Salary Data";
}
?>
error show
Fatal error: Cannot redeclare _get_salary_html() (previously declared in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml:9) in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml on line 10
hints: when single employee its ok but for multiple employee show error
Because you are re-declaring function unknowingly. Add a condition around the function like below.
if (!function_exists('_get_salary_html')) {
function _get_salary_html() {
........
}
}

Auto complete/Suggest in Wordpress Form

I'm placing a search form of 6 fields on my home page which includes a text box field named course. I want to show course suggestions while user typing. One more is, I want to show/hide some fields according to the option of first field dropdown. Any help would be appreciated.
You can use jQuery Auto Suggest which is included with WordPress : wp_enqueue_script
With this you can write a form that does a Ajax lookup to the the Ajax URL handler. Which you can add_action onto. AJAX in Plugins
So you can ajax lookup and then on the action side you can just perform a get_posts to match titles, or a raw sql Query. And return what is needed. edit your functions.php.
add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
wp_enqueue_script('suggest');
}
add_action('wp_head', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery('#se_search_element_id').suggest(se_ajax_url + '?action=se_lookup');
});
</script>
<?php
}
add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');
function se_lookup() {
global $wpdb;
$search = like_escape($_REQUEST['q']);
$query = 'SELECT ID,post_title FROM ' . $wpdb->posts . '
WHERE post_title LIKE \'' . $search . '%\'
AND post_type = \'post_type_name\'
AND post_status = \'publish\'
ORDER BY post_title ASC';
foreach ($wpdb->get_results($query) as $row) {
$post_title = $row->post_title;
$id = $row->ID;
$meta = get_post_meta($id, 'YOUR_METANAME', TRUE);
echo $post_title . ' (' . $meta . ')' . "\n";
}
die();
}
Use ajax for both. You may have to write some mysql query to retrieve the required fields(post titles or whatever it is) from the table.

Zend_Form_Element_MultiCheckbox: How to display a long list of checkboxes as columns?

So I am using a Zend_Form_Element_MultiCheckbox to display a long list of checkboxes. If I simply echo the element, I get lots of checkboxes separated by <br /> tags. I would like to figure out a way to utilize the simplicity of the Zend_Form_Element_MultiCheckbox but also display as multiple columns (i.e. 10 checkboxes in a <div style="float:left">). I can do it manually if I had an array of single checkbox elements, but it isn't the cleanest solution:
<?php
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
?>
<div id="checkboxes">
<?php foreach ($columns as $columnOfCheckboxes): ?>
<div style="float:left;">
<?php foreach($columnOfCheckboxes as $checkbox): ?>
<?php echo $checkbox ?> <?php echo $checkbox->getLabel() ?><br />
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
How can I do this same sort of thing and still use the Zend_Form_Element_MultiCheckbox?
The best place to do this is using a view helper. Here is something I thought of really quickly that you could do. You can use this in your view scripts are attach it to a Zend_Form_Element.
I am going to assume you know how to use custom view helpers and how to add them to form elements.
class My_View_Helper_FormMultiCheckbox extends Zend_View_Helper_FormMultiCheckbox
{
public function formMultiCheckbox($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
// zend_form_element attrib has higher precedence
if (isset($attribs['listsep'])) {
$listsep = $attribs['listsep'];
}
// Store original separator for later if changed
$origSep = $listsep;
// Don't allow whitespace as a seperator
$listsep = trim($listsep);
// Force a separator if empty
if (empty($listsep)) {
$listsep = $attribs['listsep'] = "<br />\n";
}
$string = $this->formRadio($name, $value, $attribs, $options, $listsep);
$checkboxes = explode($listsep, $string);
$html = '';
// Your code
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
foreach ($columns as $columnOfCheckboxes) {
$html .= '<div style="float:left;">';
$html .= implode($origSep, $columnOfCheckboxes);
$html .= '</div>';
}
return $html;
}
}
If you need further explanation just let me know. I did this fairly quickly.
EDIT
The reason I named it the same and placed in a different directory was only to override Zend's view helper. By naming it the same and adding my helper path:
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
My custom view helper gets precedence over Zend's helper. Doing this allowed me to test without changing any of my forms,elements, or views that used Zend's helper. Basically, that's how you replace one of Zend's view helpers with one of your own.
Only reason I mentioned the note on adding custom view helpers and adding to form elements was because I assumed you might rename the helper to better suit your needs.

View Helper in Kohana

I am trying to figure out a way to do the following:
I want to make an action which will be loaded through ajax and also its the internal part of the page when page is reloaded.
I know this in ZEND framework by using View Helper, But don't know how to do in Kohana
I am new to Kohana.
EDIT:
Example of what I am trying to do http://www.espncricinfo.com/west-indies-v-india-2011/engine/current/match/489228.html?CMP=chrome
In above webpage when the whole web page is loaded the live score board is loaded with it. But when u click on "Refresh scoreboard" button only the live score board is replaced through ajax.
I want to create an action say action_scoreboard which will be used to bring scoreboard data. And action_index to load the whole page, but while in the view of action_index i need to call action_scoreboard.
Thanks
Not sure if this is the best way to do this, but this is how I like to handle the situation.
public function action_index($raw = 0) {
$records = Jelly::select('scores')->execute();
if ($raw == 0) {
$view = new View('purdy');
$view->records = $records;
$this->template->content = $view;
} else {
$this->auto_render = FALSE;
$this->request->headers['Content-Type'] = 'text/xml';
$view = new View('raw');
$view->records = $records;
$this->response->body($view->render());
}
}
### THE PURDY VIEW ###
<table>
<?
foreach ($records as $record) {
echo '<tr>';
echo '<td>'.$record->name.'</td>';
echo '<td>'.$record->value.'</td>';
echo '</tr>';
}
?>
</table>
### THE RAW VIEW ###
<?xml version="1.0" encoding="utf-8"?>
<scores>
<?
foreach ($records as $record) {
echo '<score>';
echo '<name>'.$record->name.'</name>';
echo '<value>'.$record->value.'</value>';
echo '</score>';
}
?>
</scores>
I used Kopjax - Pjax jQuery ajax module. Its code is available on gitgub

How to render a view with specific text?

I have a class like this:
class myData {
function render(){
$str = 'This is string.';
// have to code here
}
}
and a myview.phtml file:
<div id='someid'></div>
Q: Now I want to do something like this in another phtml file:
<?php
$obj = new myData ();
echo $obj->render(); // it should be <div id='someid'>This is string.</div>
?>
So how can I change my render function in myData class that it should get myview.phtml and place string between DIV tag(<div id='someid'></div>) and print.
Thanks
One possible solution could be to use Partial view helper. This helper can be used to " render a specified template within its own variable scope".
Specifically in myview.phtml you can add the following:
<div id='someid'><?php echo $this->myText; ?></div>
Then, in the another phtml you could have:
<?php
$obj = new myData ();
echo $this->partial('path/to/myview.phtml',array('myText' => $obj->render()));
?>
Maybe you are looking for something like this:
http://webgen.hu/class.html.txt
http://webgen.hu/class.html.php