I am trying to make some information widget for the console on client sites (wordpress). The code below works as I need it, perfectly.
$url = 'https://example.site/wp-json/';
function _dashboard_clients_info()
{
global $url;
$request = wp_remote_get(esc_url_raw($url));
if (is_wp_error($request)) {
return false;
}
$html = wp_remote_retrieve_body($request);
$data = json_decode($html);
$head = current(array_filter($data, function ($current) {
return $current->_ID == 2;
}));
$posts = $data;
$foot = current(array_filter($data, function ($current) {
return $current->_ID == 3;
}));
$exclude = array(1, 2, 3, 4);
if (!empty($head->dash_description)) {
echo wpautop('<div class="dash_head">' . $head->dash_description . '</div>');
echo $head->html_css_js;
} else {
};
foreach ($posts as $post) {
if (!in_array($post->_ID, $exclude)) {
if (!empty($posts)) {
echo '<div class="dash_post">';
echo '<h3 class="dash_title">' . $post->dash_title . '</h3>';
echo wpautop('<div class="dash_description">' . $post->dash_description . '</div>');
echo $post->html_css_js;
echo '</div>';
}
} else {
};
}
if (!empty($foot->dash_description)) {
echo wpautop('<div class="dash_foot">' . $foot->dash_description . '</div>');
echo $foot->html_css_js;
} else {
};
}
function _add_dashboard_clients_widget()
{
global $url;
$request = wp_remote_get(esc_url_raw($url));
if (is_wp_error($request)) {
return false;
}
$html = wp_remote_retrieve_body($request);
$data = json_decode($html);
$title = current(array_filter($data, function ($current) {
return $current->_ID == 1;
}));
if (!empty($title->dash_description)) {
$title = '<div class="dash_title">' . $title->dash_description . '</div>';
} else {
};
add_meta_box('dashboard-clients-info', '' . $title . '', '_dashboard_clients_info', $screen, 'normal', 'high');
}
add_action('wp_dashboard_setup', '_add_dashboard_clients_widget');
But I understand that it is not perfect. In particular, I have to include $url twice to get the widget title and body.
I would like to make the $data variable global in order to get the $url once, and then take what me need. I tried it like this, but for some reason it doesn't work, it doesn't return anything.
$url = 'https://example.site/wp-json/';
$request = wp_remote_get(esc_url_raw($url));
if (is_wp_error($request)) {
return false;
}
$html = wp_remote_retrieve_body($request);
$data = json_decode($html);
function _dashboard_clients_info()
{
global $data;
$head = current(array_filter($data, function ($current) {
return $current->_ID == 2;
}));
$posts = $data;
$foot = current(array_filter($data, function ($current) {
return $current->_ID == 3;
}));
$exclude = array(1, 2, 3, 4);
if (!empty($head->dash_description)) {
echo wpautop('<div class="dash_head">' . $head->dash_description . '</div>');
echo $head->html_css_js;
} else {
};
foreach ($posts as $post) {
if (!in_array($post->_ID, $exclude)) {
if (!empty($posts)) {
echo '<div class="dash_post">';
echo '<h3 class="dash_title">' . $post->dash_title . '</h3>';
echo wpautop('<div class="dash_description">' . $post->dash_description . '</div>');
echo $post->html_css_js;
echo '</div>';
}
} else {
};
}
if (!empty($foot->dash_description)) {
echo wpautop('<div class="dash_foot">' . $foot->dash_description . '</div>');
echo $foot->html_css_js;
} else {
};
}
function _add_dashboard_clients_widget()
{
global $data;
$title = current(array_filter($data, function ($current) {
return $current->_ID == 1;
}));
if (!empty($title->dash_description)) {
$title = '<div class="dash_title">' . $title->dash_description . '</div>';
} else {
};
add_meta_box('dashboard-clients-info', 'test', '_dashboard_clients_info', $screen, 'normal', 'high');
}
add_action('wp_dashboard_setup', '_add_dashboard_clients_widget');
I will be grateful for any help in improving this. I'm just learning, I try to get knowledge in this way)))
You can easily define your API URL in wp-config.php, in the theme's functions.php or in a plugin's 'root' file (my-plugin.php for ex.):
define( 'DASHBOARD_API_URL', 'https://example.site/wp-json/' );
Then, create a method to receive the dashboard data making use of the defined DASHBOARD_API_URL:
function wp68412621_get_dashboard_data() {
$response = wp_remote_get( DASHBOARD_API_URL );
if ( is_wp_error( $response ) ) {
return false;
}
return wp_remote_retrieve_body( $response );
}
You should make use of transients to cache the API response in order to avoid excessive API calls. Let's adjust the previous method to:
function wp68412621_get_dashboard_data() {
$transient_key = 'dashboard_data';
$dashboard_data = get_transient( $transient_key );
if ( false === $dashboard_data ) {
$response = wp_remote_get( DASHBOARD_API_URL );
if ( is_wp_error( $response ) ) {
return false;
}
$dashboard_data = wp_remote_retrieve_body( $response );
set_transient( $transientKey, $dashboard_data, 900 );
}
return $dashboard_data;
}
Then, you can call the data method from any other method:
function wp68412621_dashboard_clients_info()
{
$data = wp68412621_get_dashboard_data();
if ( empty( $data ) ) {
return false;
}
// ...
}
function wp68412621_add_dashboard_clients_widget()
{
$data = wp68412621_get_dashboard_data();
if ( empty( $data ) ) {
return false;
}
// ...
}
add_action( 'wp_dashboard_setup', 'wp68412621_add_dashboard_clients_widget' );
Related
I have a SilverStripe (3.4) Page with a form that would work if I didn't have a DataObject in it.
public function AntwortForm($ID) {
$Nummer = Vortest_Fragen::get()->byID($ID);
if ($Nummer) {
$Art=$Nummer->Art;
}
if ($Art == 'Normal') {
$fields = new FieldList(
TextAreaField::create('Antwort'),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion', $this->request->param('Action'))
);
} else {
$Optionen = explode(';', $Nummer->Optionen);
$a = 'A';
for ( $i = 0 ; $i < count ($Optionen); $i++) {
$Op[$a] ='<div style="width:25px;display:inline;">' . $a . ')</div> ' . $Optionen[$i];
$a++;
}
$fields = new FieldList(
CheckboxSetField::create('Antwort', 'Antwort', $Op),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion',$this->request->param('Action')),
HiddenField::create('Art', 'Art', $Nummer->Art)
);
}
$actions = new FieldList(
FormAction::create('AntwortEintragen', 'Eintragen')
);
$form = new Form($this, 'AntwortForm', $fields, $actions);
return $form;
}
function AntwortEintragen($data, $form) {
$Antwort = Vortest_Antwort::get()->filter(array('FrageID' => $data['ID'], 'SchreiberID' => Member::currentUserID()));
foreach($Antwort as $item) {
$item->delete();
}
foreach ($data['Antwort'] as $Antwort) {
$Ant .= $Antwort . ',';
}
$Antwort = new Vortest_Antwort();
if ($data['Antwort']) {
$form->saveInto($Antwort);
if ($data['Art'] == 'Mechanics') {
$Antwort->Antwort = $Ant;
}
$Antwort->SchreiberID = Member::currentUserID();
$Antwort->FrageID = $data['ID'];
$Antwort->write();
}
$VID = $data['VortestID'];
if ($data['Aktion'] == 'AlleFragen') {
$this->redirect('/vortest/AlleFragen/' . $VID . '#' . $data['FrageNr']);
} elseif ($data['Aktion'] == 'Einzelfrage') {
$this->redirect('/vortest/Einzelfrage/' . $VID);
} else {
$this->redirect('/vortest/Test/' . $VID.'#' . $data['FrageNr']);
}
}
It works when I change the $ID to a number in this line $Nummer = Vortest_Fragen::get()->byID($ID);
When I don't change it I get the following error:
[Recoverable Error] Object of class SS_HTTPRequest could not be converted to string
How do I fix this problem?
Althought it is not clearly documented, Silverstripe secretly passes a request argument to and form methods on a controller. Your $ID argument is actually not what you think it is, you will find it is actually an SS_HTTPRequest object that Silverstripe has passed (without you realising).
To fix this, change the first line:
public function AntwortForm($ID) {
To:
public function AntwortForm($request, $ID) {
And make sure you update anywhere that you call this method :-)
I have this class for show error with session method using PHP.
class Messages {
//-----------------------------------------------------------------------------------------------
// Class Variables
//-----------------------------------------------------------------------------------------------
var $msgId;
var $msgTypes = array( 'help', 'info', 'warning', 'success', 'danger' );
var $msgClass = 'alert';
var $msgWrapper = " <div class='alert %s-%s flashit'>
<button class='close' aria-hidden='true' data-dismiss='alert' type='button'>×</button>
<p><i style='vertical-align: middle;' class='%s icon-2x'></i> %s</p>
</div>";
var $msgBefore = '';
var $msgAfter = "";
public function __construct() {
// Generate a unique ID for this user and session
$this->msgId = md5(uniqid());
// Create the session array if it doesnt already exist
if( !array_key_exists('flash_messages', $_SESSION) ) $_SESSION['flash_messages'] = array();
}
public function add($type, $message, $redirect_to=null) {
if( !isset($_SESSION['flash_messages']) ) return false;
if( !isset($type) || !isset($message[0]) ) return false;
// Replace any shorthand codes with their full version
if( strlen(trim($type)) == 1 ) {
$type = str_replace( array('h', 'i', 'w', 'e', 's'), array('help', 'info', 'warning', 'danger', 'success'), $type );
$icon = str_replace( array('h', 'i', 'w', 'e', 's'), array('fa-help', 'fa-info', 'fa-warning', 'fa-danger', 'fa-success'), $type );
// Backwards compatibility...
} elseif( $type == 'information' ) {
$type = 'info';
$icon = 'fa-info';
}
// Make sure it's a valid message type
if( !in_array($type, $this->msgTypes) ) die('"' . strip_tags($type) . '" is not a valid message type!' );
// If the session array doesn't exist, create it
if( !array_key_exists( $type, $_SESSION['flash_messages'] ) ) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = $message;
if( !is_null($redirect_to) ) {
header("Location: $redirect_to");
exit();
}
return true;
}
//-----------------------------------------------------------------------------------------------
// display()
// print queued messages to the screen
//-----------------------------------------------------------------------------------------------
public function display($type='all', $print=true) {
$messages = '';
$data = '';
if( !isset($_SESSION['flash_messages']) ) return false;
if( $type == 'g' || $type == 'growl' ) {
$this->displayGrowlMessages();
return true;
}
// Print a certain type of message?
if( in_array($type, $this->msgTypes) ) {
foreach( $_SESSION['flash_messages'][$type] as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
// Clear the viewed messages
$this->clear($type);
// Print ALL queued messages
} elseif( $type == 'all' ) {
foreach( $_SESSION['flash_messages'] as $type => $msgArray ) {
$messages = '';
foreach( $msgArray as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
}
// Clear ALL of the messages
$this->clear();
// Invalid Message Type?
} else {
return false;
}
// Print everything to the screen or return the data
if( $print ) {
echo $data;
} else {
return $data;
}
}
//..... more
}
Call:
$msg = new Messages();
$msg->add('i', 'This is a Information message!');
echo $msg->display();
Now in Output:
<i style="vertical-align: middle;" class=" icon-2x"></i>
Icon class not printed and empty: class=" icon-2x". how do can i fix this ?
EDit: Indeed i need to print for each type One class name.
i create function called empty_fields but i can't figure out, to make it work..
<?php
function empty_fields($field_name)
{
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
} else { $output = null; }
return $output;
}
to display in html
<?php empty_fields('indigofera'); ?>
Change
if(!empty($order['$field_name'])){
to
if(!empty($order[$field_name])){
'$field_name' does not evaluate to anything and it will search for
key '$field_name' in the $orders array everytime, hence will not work.
Hope it works.
If you use $order as a global variable, use:
function empty_fields($field_name)
{
global $order;
$output = null;
if(!empty($order[$field_name]))
{
$output = "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
return $output;
}
and use it:
<?php echo empty_fields('indigofera'); ?>
EDIT: the OOP way:
class Orders
{
private $order = null;
public function get_order()
{
$this->order = //....
}
public function empty_fields($field_name)
{
if(!isset($this->order) || empty($order[$field_name])) return;
return "<li>Indigofera - " . $order[$field_name] . "Kg</li>";
}
}
and use it:
<?php
$orders = new Orders();
$orders->get_order();
echo $orders->empty_fields("indigofera");
I'm using a WordPress plugin called User Submitted Posts. The plugin allows for users to upload multiple photos. I have it set up so that users can upload 0 to a max of 3. When I try to upload more than one pic, however, only one of them gets posted.
HTML:
<div id="usp">
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<ul id="usp_list">
<li class="usp_title">
<label for="user-submitted-title" class="usp_label">Post Title</label>
<div>
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
</div>
</li>
<li class="usp_tags">
<label for="user-submitted-tags" class="usp_label">Post Tags <small>(separate tags with commas)</small></label>
<div>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="" />
</div>
</li>
<li class="usp_content">
<label for="user-submitted-content" class="usp_label">Post Content</label>
<div>
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
</div>
</li>
<li class="usp_images">
<label for="user-submitted-image" class="usp_label">Upload an Image</label>
<div id="usp_upload-message"></div>
<div>
<input class="usp_input usp_clone" type="file" size="25" id="user-submitted-image" name="user-submitted-image[]" />
Add another image
</div>
</li>
<li class="usp_submit">
<input class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post" />
</li>
</ul>
</form>
PHP:
if (!class_exists('Public_Submission_Form')) {
class Public_Submission_Form {
var $version = '1.0';
var $_post_meta_IsSubmission = 'is_submission';
var $_post_meta_Submitter = 'user_submit_name';
var $_post_meta_SubmitterUrl = 'user_submit_url';
var $_post_meta_SubmitterIp = 'user_submit_ip';
var $_post_meta_Image = 'user_submit_image';
var $_post_meta_ImageInfo = 'user_submit_image_info';
var $settings = null;
function Public_Submission_Form() {
register_activation_hook(__FILE__, array(&$this, 'saveDefaultSettings'));
add_action('admin_init', array(&$this, 'checkForSettingsSave'));
add_action('admin_menu', array(&$this, 'addAdministrativeElements'));
add_action('init', array(&$this, 'enqueueResources'));
add_action('parse_request', array(&$this, 'checkForPublicSubmission'));
add_action('parse_query', array(&$this, 'addSubmittedStatusClause'));
add_action('restrict_manage_posts', array(&$this, 'outputUserSubmissionLink'));
add_filter('the_author', array(&$this, 'replaceAuthor'));
add_filter('the_author_link', array(&$this, 'replaceAuthorLink'));
add_filter('post_stati', array(&$this, 'addNewPostStatus'));
add_shortcode('user-submitted-posts', array(&$this, 'getPublicSubmissionForm'));
}
function addAdministrativeElements() {
add_options_page(__('User Submitted Posts'), __('User Submitted Posts'), 'manage_options', 'user-submitted-posts', array(&$this, 'displaySettingsPage'));
}
function addNewPostStatus($postStati) {
$postStati['submitted'] = array(__('Submitted'), __('User submitted posts'), _n_noop('Submitted', 'Submitted'));
return $postStati;
}
function addSubmittedStatusClause($wp_query) {
global $pagenow;
if (is_admin() && $pagenow == 'edit.php' && $_GET['user_submitted'] == '1') {
set_query_var('meta_key', $this->_post_meta_IsSubmission);
set_query_var('meta_value', 1);
set_query_var('post_status', 'pending');
}
}
function checkForPublicSubmission() {
if (isset($_POST['user-submitted-post']) && ! empty($_POST['user-submitted-post'])) {
$settings = $this->getSettings();
$title = stripslashes($_POST['user-submitted-title']);
$content = stripslashes($_POST['user-submitted-content']);
$authorName = stripslashes($_POST['user-submitted-name']);
$authorUrl = stripslashes($_POST['user-submitted-url']);
$tags = stripslashes($_POST['user-submitted-tags']);
$category = intval($_POST['user-submitted-category']);
$fileData = $_FILES['user-submitted-image'];
$publicSubmission = $this->createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData);
if (false == ($publicSubmission)) {
$errorMessage = empty($settings['error-message']) ? __('An error occurred. Please go back and try again.') : $settings['error-message'];
if( !empty( $_POST[ 'redirect-override' ] ) ) {
$redirect = stripslashes( $_POST[ 'redirect-override' ] );
$redirect = add_query_arg( array( 'submission-error' => '1' ), $redirect );
wp_redirect( $redirect );
exit();
}
wp_die($errorMessage);
} else {
$redirect = empty($settings['redirect-url']) ? $_SERVER['REQUEST_URI'] : $settings['redirect-url'];
if (! empty($_POST['redirect-override'])) {
$redirect = stripslashes($_POST['redirect-override']);
}
$redirect = add_query_arg(array('success'=>1), $redirect);
wp_redirect($redirect);
exit();
}
}
}
function checkForSettingsSave() {
if (isset($_POST['save-post-submission-settings']) && current_user_can('manage_options') && check_admin_referer('save-post-submission-settings')) {
$settings = $this->getSettings();
$settings['author'] = get_userdata($_POST['author']) ? $_POST['author'] : $settings['author'];
$settings['categories'] = is_array($_POST['categories']) && ! empty($_POST['categories']) ? array_unique($_POST['categories']) : array(get_option('default_category'));
$settings['number-approved'] = is_numeric($_POST['number-approved']) ? intval($_POST['number-approved']) : - 1;
$settings['redirect-url'] = stripslashes($_POST['redirect-url']);
$settings['error-message'] = stripslashes($_POST['error-message']);
$settings['min-images'] = is_numeric($_POST['min-images']) ? intval($_POST['min-images']) : $settings['max-images'];
$settings['max-images'] = (is_numeric($_POST['max-images']) && ($settings['min-images'] <= $_POST['max-images'])) ? intval($_POST['max-images']) : $settings['max-images'];
$settings['min-image-height'] = is_numeric($_POST['min-image-height']) ? intval($_POST['min-image-height']) : $settings['min-image-height'];
$settings['min-image-width'] = is_numeric($_POST['min-image-width']) ? intval($_POST['min-image-width']) : $settings['min-image-width'];
$settings['max-image-height'] = (is_numeric($_POST['max-image-height']) && ($settings['min-image-height'] <= $_POST['max-image-height'])) ? intval($_POST['max-image-height']) : $settings['max-image-height'];
$settings['max-image-width'] = (is_numeric($_POST['max-image-width']) && ($settings['min-image-width'] <= $_POST['max-image-width'])) ? intval($_POST['max-image-width']) : $settings['max-image-width'];
$settings['usp_name'] = stripslashes($_POST['usp_name']);
$settings['usp_url'] = stripslashes($_POST['usp_url']);
$settings['usp_title'] = stripslashes($_POST['usp_title']);
$settings['usp_tags'] = stripslashes($_POST['usp_tags']);
$settings['usp_category'] = stripslashes($_POST['usp_category']);
$settings['usp_content'] = stripslashes($_POST['usp_content']);
$settings['usp_images'] = stripslashes($_POST['usp_images']);
$settings['upload-message'] = stripslashes($_POST['upload-message']);
$settings['usp_form_width'] = stripslashes($_POST['usp_form_width']);
$this->saveSettings($settings);
wp_redirect(admin_url('options-general.php?page=user-submitted-posts&updated=1'));
}
}
function displaySettingsPage() {
include ('views/settings.php');
}
function enqueueResources() {
wp_enqueue_script('usp_script', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.js', array('jquery'), $this->version);
wp_enqueue_style('usp_style', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.css', false, $this->version, 'screen');
}
function getPublicSubmissionForm($atts = array(), $content = null) {
if ($atts === true) {
$redirect = $this->currentPageURL();
}
ob_start();
include (WP_PLUGIN_DIR.'/'.basename(dirname(__FILE__)).'/views/submission-form.php');
return ob_get_clean();
}
function outputUserSubmissionLink() {
global $pagenow;
if ($pagenow == 'edit.php') {
echo '<a id="usp_admin_filter_posts" class="button-secondary" href="'.admin_url('edit.php?post_status=pending&user_submitted=1').'">'.__('User Submitted Posts').'</a>';
}
}
function replaceAuthor($author) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
if ($isSubmission && ! empty($submissionAuthor)) {
return $submissionAuthor;
} else {
return $author;
}
}
function replaceAuthorLink($authorLink) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
$submissionLink = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
if ($isSubmission && ! empty($submissionAuthor)) {
if ( empty($submissionLink)) {
return $submissionAuthor;
} else {
return "<a href='{$submissionLink}'>{$submissionAuthor}</a>";
}
} else {
return $authorLink;
}
}
function saveDefaultSettings() {
$settings = $this->getSettings();
if ( empty($settings)) {
$currentUser = wp_get_current_user();
$settings = array();
$settings['author'] = $currentUser->ID;
$settings['categories'] = array(get_option('default_category'));
$settings['number-approved'] = -1;
$settings['redirect-url'] = ''; //site_url();
$settings['error-message'] = __('There was an error. Please ensure that you have added a title, some content, and that you have uploaded only images.');
$settings['min-images'] = 0;
$settings['max-images'] = 1;
$settings['min-image-height'] = 0;
$settings['min-image-width'] = 0;
$settings['max-image-height'] = 500;
$settings['max-image-width'] = 500;
$settings['usp_name'] = 'show';
$settings['usp_url'] = 'show';
$settings['usp_title'] = 'show';
$settings['usp_tags'] = 'show';
$settings['usp_category'] = 'show';
$settings['usp_content'] = 'show';
$settings['usp_images'] = 'hide';
$settings['upload-message'] = ''; // 'Please select your image(s) to upload:';
$settings['usp_form_width'] = '300'; // in pixels
$this->saveSettings($settings);
}
}
function getSettings() {
if ($this->settings === null) {
$defaults = array();
$this->settings = get_option('User Submitted Posts Settings', array());
}
return $this->settings;
}
function saveSettings($settings) {
if (!is_array($settings)) {
return;
}
$this->settings = $settings;
update_option('User Submitted Posts Settings', $this->settings);
}
function createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData) {
$settings = $this->getSettings();
$authorName = strip_tags($authorName);
$authorUrl = strip_tags($authorUrl);
$authorIp = $_SERVER['REMOTE_ADDR'];
if (!$this->validateTitle($title)) {
return false;
}
if (!$this->validateContent($title)) {
return false;
}
if (!$this->validateTags($tags)) {
return false;
}
$postData = array();
$postData['post_title'] = $title;
$postData['post_content'] = $content;
$postData['post_status'] = 'pending';
$postData['author'] = $settings['author'];
$numberApproved = $settings['number-approved'];
if ($numberApproved < 0) {} elseif ($numberApproved == 0) {
$postData['post_status'] = 'publish';
} else {
$posts = get_posts(array('post_status'=>'publish', 'meta_key'=>$this->_post_meta_Submitter, 'meta_value'=>$authorName));
$counter = 0;
foreach ($posts as $post) {
$submitterUrl = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
$submitterIp = get_post_meta($post->ID, $this->_post_meta_SubmitterIp, true);
if ($submitterUrl == $authorUrl && $submitterIp == $authorIp) {
$counter++;
}
}
if ($counter >= $numberApproved) {
$postData['post_status'] = 'publish';
}
}
$newPost = wp_insert_post($postData);
if ($newPost) {
wp_set_post_tags($newPost, $tags);
wp_set_post_categories($newPost, array($category));
if (!function_exists('media_handle_upload')) {
require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php');
}
$attachmentIds = array();
$imageCounter = 0;
for ($i = 0; $i < count($fileData['name']); $i++) {
$imageInfo = getimagesize($fileData['tmp_name'][$i]);
if (false === $imageInfo || !$this->imageIsRightSize($imageInfo[0], $imageInfo[1])) {
continue;
}
$key = "public-submission-attachment-{$i}";
$_FILES[$key] = array();
$_FILES[$key]['name'] = $fileData['name'][$i];
$_FILES[$key]['tmp_name'] = $fileData['tmp_name'][$i];
$_FILES[$key]['type'] = $fileData['type'][$i];
$_FILES[$key]['error'] = $fileData['error'][$i];
$_FILES[$key]['size'] = $fileData['size'][$i];
$attachmentId = media_handle_upload($key, $newPost);
if (!is_wp_error($attachmentId) && wp_attachment_is_image($attachmentId)) {
$attachmentIds[] = $attachmentId;
add_post_meta($newPost, $this->_post_meta_Image, wp_get_attachment_url($attachmentId));
$imageCounter++;
} else {
wp_delete_attachment($attachmentId);
}
if ($imageCounter == $settings['max-images']) {
break;
}
}
if (count($attachmentIds) < $settings['min-images']) {
foreach ($attachmentIds as $idToDelete) {
wp_delete_attachment($idToDelete);
}
wp_delete_post($newPost);
return false;
}
update_post_meta($newPost, $this->_post_meta_IsSubmission, true);
update_post_meta($newPost, $this->_post_meta_Submitter, htmlentities(($authorName)));
update_post_meta($newPost, $this->_post_meta_SubmitterUrl, htmlentities(($authorUrl)));
update_post_meta($newPost, $this->_post_meta_SubmitterIp, $authorIp);
}
return $newPost;
}
function imageIsRightSize($width, $height) {
$settings = $this->getSettings();
$widthFits = ($width <= intval($settings['max-image-width'])) && ($width >= $settings['min-image-width']);
$heightFits = ($height <= $settings['max-image-height']) && ($height >= $settings['min-image-height']);
return $widthFits && $heightFits;
}
function validateContent($content) {
return ! empty($content);
}
function validateTags($tags) {
return true;
}
function validateTitle($title) {
return ! empty($title);
}
function currentPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
}
$publicSubmissionForm = new Public_Submission_Form();
include ('library/template-tags.php');
}
== Template Tags ==
To display the images attached to user-submitted posts, use this template tag:
<?php post_attachments(); ?>
This template tag prints the URLs for all post attachments and accepts the following paramters:
<?php post_attachments($size, $beforeUrl, $afterUrl, $numberImages, $postId); ?>
$size = image size as thumbnail, medium, large or full -> default = full
$beforeUrl = text/markup displayed before the image URL -> default = <img src="
$afterUrl = text/markup displayed after the image URL -> default = " />
$numberImages = the number of images to display for each post -> default = false (display all)
$postId = an optional post ID to use -> default = uses global post
Additionally, the following template tag returns an array of URLs for the specified post image:
<?php get_post_images(); ?>
This tag returns a boolean value indicating whether the specified post is a public submission:
<?php is_public_submission(); ?>
What does var_dump($_FILES) look like? It looks like you're generating a unique field name for each file upload field, using $key = "public-submission-attachment-{$i}";. if that's the case, then your file access structure is incorrect. PHP will generate the $_FILES data for each fieldname 1 of 2 ways:
If you're using a unique somestring field name, you get a structure like:
$_FILES['somestring'] = array(
'name' => 'somefile.txt',
'type' => 'text/plain',
'size' => 1234,
'error' => 0,
'tmp_name'] => '/tmp/asdfasdfasdfa'
);
If you're using the PHP-centric array notation, somestring[] (note the []) for the field name, you get:
$_FILES['somestring'] = array(
'name' => array(
0 => 'somefile1.txt',
1 => 'somepic.jpg'
),
'type' => array(
0 => 'text/plain',
1 => 'image.jpeg'
)
etc...
);
Given that it you seem to be generating a unique field name, WITHOUT the array notation, you'd have to use option #1.
I need to modify a php search script so that it can handle multiple entries for a single field. The search engine is designed for a real estate website. The current search form allows users to search for houses by selecting a single neighborhood from a dropdown menu. Instead of a dropdown menu, I would like to use a list of checkboxes so that the the user can search for houses in multiple neighborhoods at one time. I have converted all of the dropdown menu items into checkboxes on the HTML side but the PHP script only searches for houses in the last checkbox selected. For example, if I selected: 'Dallas' 'Boston' 'New York' the search engine will only search for houses in New York.
Im new to PHP, so I am a little at a loss as to how to modify this script to handle the behavior I have described:
<?php
require_once(dirname(__FILE__).'/extra_search_fields.php');
//Add Widget for configurable search.
add_action('plugins_loaded',array('DB_CustomSearch_Widget','init'));
class DB_CustomSearch_Widget extends DB_Search_Widget {
function DB_CustomSearch_Widget($params=array()){
DB_CustomSearch_Widget::__construct($params);
}
function __construct($params=array()){
$this->loadTranslations();
parent::__construct(__('Custom Fields ','wp-custom-fields-search'),$params);
add_action('admin_print_scripts', array(&$this,'print_admin_scripts'), 90);
add_action('admin_menu', array(&$this,'plugin_menu'), 90);
add_filter('the_content', array(&$this,'process_tag'),9);
add_shortcode( 'wp-custom-fields-search', array(&$this,'process_shortcode') );
wp_enqueue_script('jquery');
if(version_compare("2.7",$GLOBALS['wp_version'])>0) wp_enqueue_script('dimensions');
}
function init(){
global $CustomSearchFieldStatic;
$CustomSearchFieldStatic['Object'] = new DB_CustomSearch_Widget();
$CustomSearchFieldStatic['Object']->ensureUpToDate();
}
function currentVersion(){
return "0.3.16";
}
function ensureUpToDate(){
$version = $this->getConfig('version');
$latest = $this->currentVersion();
if($version<$latest) $this->upgrade($version,$latest);
}
function upgrade($current,$target){
$options = $this->getConfig();
if(version_compare($current,"0.3")<0){
$config = $this->getDefaultConfig();
$config['name'] = __('Default Preset','wp-custom-fields-search');
$options['preset-default'] = $config;
}
$options['version']=$target;
update_option($this->id,$options);
}
function getInputs($params = false,$visitedPresets=array()){
if(is_array($params)){
$id = $params['widget_id'];
} else {
$id = $params;
}
if($visitedPresets[$id]) return array();
$visitedPresets[$id]=true;
global $CustomSearchFieldStatic;
if(!$CustomSearchFieldStatic['Inputs'][$id]){
$config = $this->getConfig($id);
$inputs = array();
if($config['preset']) $inputs = $this->getInputs($config['preset'],$visitedPresets);
$nonFields = $this->getNonInputFields();
if($config)
foreach($config as $k=>$v){
if(in_array($k,$nonFields)) continue;
if(!(class_exists($v['input']) && class_exists($v['comparison']) && class_exists($v['joiner']))) {
continue;
}
$inputs[] = new CustomSearchField($v);
}
foreach($inputs as $k=>$v){
$inputs[$k]->setIndex($k);
}
$CustomSearchFieldStatic['Inputs'][$id]=$inputs;
}
return $CustomSearchFieldStatic['Inputs'][$id];
}
function getTitle($params){
$config = $this->getConfig($params['widget_id']);
return $config['name'];
}
function form_processPost($post,$old){
unset($post['###TEMPLATE_ID###']);
if(!$post) $post=array('exists'=>1);
return $post;
}
function getDefaultConfig(){
return array('name'=>'Site Search',
1=>array(
'label'=>__('Key Words','wp-custom-fields-search'),
'input'=>'TextField',
'comparison'=>'WordsLikeComparison',
'joiner'=>'PostDataJoiner',
'name'=>'all'
),
2=>array(
'label'=>__('Category','wp-custom-fields-search'),
'input'=>'DropDownField',
'comparison'=>'EqualComparison',
'joiner'=>'CategoryJoiner'
),
);
}
function form_outputForm($values,$pref){
$defaults=$this->getDefaultConfig();
$prefId = preg_replace('/^.*\[([^]]*)\]$/','\\1',$pref);
$this->form_existsInput($pref);
$rand = rand();
?>
<div id='config-template-<?php echo $prefId?>' style='display: none;'>
<?php
$templateDefaults = $defaults[1];
$templateDefaults['label'] = 'Field ###TEMPLATE_ID###';
echo $this->singleFieldHTML($pref,'###TEMPLATE_ID###',$templateDefaults);
?>
</div>
<?php
foreach($this->getClasses('input') as $class=>$desc) {
if(class_exists($class))
$form = new $class();
else $form = false;
if(compat_method_exists($form,'getConfigForm')){
if($form = $form->getConfigForm($pref.'[###TEMPLATE_ID###]',array('name'=>'###TEMPLATE_NAME###'))){
?>
<div id='config-input-templates-<?php echo $class?>-<?php echo $prefId?>' style='display: none;'>
<?php echo $form?>
</div>
<?php }
}
}
?>
<div id='config-form-<?php echo $prefId?>'>
<?php
if(!$values) $values = $defaults;
$maxId=0;
$presets = $this->getPresets();
array_unshift($presets,__('NONE','wp-custom-fields-search'));
?>
<div class='searchform-name-wrapper'><label for='<?php echo $prefId?>[name]'><?php echo __('Search Title','wp-custom-fields-search')?></label><input type='text' class='form-title-input' id='<?php echo $prefId?>[name]' name='<?php echo $pref?>[name]' value='<?php echo $values['name']?>'/></div>
<div class='searchform-preset-wrapper'><label for='<?php echo $prefId?>[preset]'><?php echo __('Use Preset','wp-custom-fields-search')?></label>
<?php
$dd = new AdminDropDown($pref."[preset]",$values['preset'],$presets);
echo $dd->getInput()."</div>";
$nonFields = $this->getNonInputFields();
foreach($values as $id => $val){
$maxId = max($id,$maxId);
if(in_array($id,$nonFields)) continue;
echo "<div id='config-form-$prefId-$id'>".$this->singleFieldHTML($pref,$id,$val)."</div>";
}
?>
</div>
<br/><?php echo __('Add Field','wp-custom-fields-search')?>
<script type='text/javascript'>
CustomSearch.create('<?php echo $prefId?>','<?php echo $maxId?>');
<?php
foreach($this->getClasses('joiner') as $joinerClass=>$desc){
if(compat_method_exists($joinerClass,'getSuggestedFields')){
$options = eval("return $joinerClass::getSuggestedFields();");
$str = '';
foreach($options as $i=>$v){
$k=$i;
if(is_numeric($k)) $k=$v;
$options[$i] = json_encode(array('id'=>$k,'name'=>$v));
}
$str = '['.join(',',$options).']';
echo "CustomSearch.setOptionsFor('$joinerClass',".$str.");\n";
}elseif(eval("return $joinerClass::needsField();")){
echo "CustomSearch.setOptionsFor('$joinerClass',[]);\n";
}
}
?>
</script>
<?php
}
function getNonInputFields(){
return array('exists','name','preset','version');
}
function singleFieldHTML($pref,$id,$values){
$prefId = preg_replace('/^.*\[([^]]*)\]$/','\\1',$pref);
$pref = $pref."[$id]";
$htmlId = $pref."[exists]";
$output = "<input type='hidden' name='$htmlId' value='1'/>";
$titles="<th>".__('Label','wp-custom-fields-search')."</th>";
$inputs="<td><input type='text' name='$pref"."[label]' value='$values[label]' class='form-field-title'/></td><td><a href='#' onClick='return CustomSearch.get(\"$prefId\").toggleOptions(\"$id\");'>".__('Show/Hide Config','wp-custom-fields-search')."</a></td>";
$output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
$output.="<div id='form-field-advancedoptions-$prefId-$id' style='display: none'>";
$inputs='';$titles='';
$titles="<th>".__('Data Field','wp-custom-fields-search')."</th>";
$inputs="<td><div id='form-field-dbname-$prefId-$id' class='form-field-title-div'><input type='text' name='$pref"."[name]' value='$values[name]' class='form-field-title'/></div></td>";
$count=1;
foreach(array('joiner'=>__('Data Type','wp-custom-fields-search'),'comparison'=>__('Compare','wp-custom-fields-search'),'input'=>__('Widget','wp-custom-fields-search')) as $k=>$v){
$dd = new AdminDropDown($pref."[$k]",$values[$k],$this->getClasses($k),array('onChange'=>'CustomSearch.get("'.$prefId.'").updateOptions("'.$id.'","'.$k.'")','css_class'=>"wpcfs-$k"));
$titles="<th>".$v."</th>".$titles;
$inputs="<td>".$dd->getInput()."</td>".$inputs;
if(++$count==2){
$output.="<table class='form-field-table form-class-$k'><tr>$titles</tr><tr>$inputs</tr></table>";
$count=0;
$inputs = $titles='';
}
}
if($titles){
$output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
$inputs = $titles='';
}
$titles.="<th>".__('Numeric','wp-custom-fields-search')."</th><th>".__('Widget Config','wp-custom-fields-search')."</th>";
$inputs.="<td><input type='checkbox' ".($values['numeric']?"checked='true'":"")." name='$pref"."[numeric]'/></td>";
if(class_exists($widgetClass = $values['input'])){
$widget = new $widgetClass();
if(compat_method_exists($widget,'getConfigForm'))
$widgetConfig=$widget->getConfigForm($pref,$values);
}
$inputs.="<td><div id='$this->id"."-$prefId"."-$id"."-widget-config'>$widgetConfig</div></td>";
$output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
$output.="</div>";
$output.="Remove Field";
return "<div class='field-wrapper'>$output</div>";
}
function getRootURL(){
return WP_CONTENT_URL .'/plugins/' . dirname(plugin_basename(__FILE__) ) . '/';
}
function print_admin_scripts($params){
$jsRoot = $this->getRootURL().'js';
$cssRoot = $this->getRootURL().'css';
$scripts = array('Class.js','CustomSearch.js','flexbox/jquery.flexbox.js');
foreach($scripts as $file){
echo "<script src='$jsRoot/$file' ></script>";
}
echo "<link rel='stylesheet' href='$cssRoot/admin.css' >";
echo "<link rel='stylesheet' href='$jsRoot/flexbox/jquery.flexbox.css' >";
}
function getJoiners(){
return $this->getClasses('joiner');
}
function getComparisons(){
return $this->getClasses('comparison');
}
function getInputTypes(){
return $this->getClasses('input');
}
function getClasses($type){
global $CustomSearchFieldStatic;
if(!$CustomSearchFieldStatic['Types']){
$CustomSearchFieldStatic['Types'] = array(
"joiner"=>array(
"PostDataJoiner" =>__( "Post Field",'wp-custom-fields-search'),
"CustomFieldJoiner" =>__( "Custom Field",'wp-custom-fields-search'),
"CategoryJoiner" =>__( "Category",'wp-custom-fields-search'),
"TagJoiner" =>__( "Tag",'wp-custom-fields-search'),
"PostTypeJoiner" =>__( "Post Type",'wp-custom-fields-search'),
),
"input"=>array(
"TextField" =>__( "Text Input",'wp-custom-fields-search'),
"DropDownField" =>__( "Drop Down",'wp-custom-fields-search'),
"RadioButtonField" =>__( "Radio Button",'wp-custom-fields-search'),
"HiddenField" =>__( "Hidden Constant",'wp-custom-fields-search'),
),
"comparison"=>array(
"EqualComparison" =>__( "Equals",'wp-custom-fields-search'),
"LikeComparison" =>__( "Phrase In",'wp-custom-fields-search'),
"WordsLikeComparison" =>__( "Words In",'wp-custom-fields-search'),
"LessThanComparison" =>__( "Less Than",'wp-custom-fields-search'),
"MoreThanComparison" =>__( "More Than",'wp-custom-fields-search'),
"AtMostComparison" =>__( "At Most",'wp-custom-fields-search'),
"AtLeastComparison" =>__( "At Least",'wp-custom-fields-search'),
"RangeComparison" =>__( "Range",'wp-custom-fields-search'),
//TODO: Make this work...
// "NotEqualComparison" =>__( "Not Equal To",'wp-custom-fields-search'),
)
);
$CustomSearchFieldStatic['Types'] = apply_filters('custom_search_get_classes',$CustomSearchFieldStatic['Types']);
}
return $CustomSearchFieldStatic['Types'][$type];
}
function plugin_menu(){
add_options_page('Form Presets','WP Custom Fields Search',8,__FILE__,array(&$this,'presets_form'));
}
function getPresets(){
$presets = array();
foreach(array_keys($config = $this->getConfig()) as $key){
if(strpos($key,'preset-')===0) {
$presets[$key] = $key;
if($name = $config[$key]['name'])
$presets[$key]=$name;
}
}
return $presets;
}
function presets_form(){
$presets=$this->getPresets();
if(!$preset = $_REQUEST['selected-preset']){
$preset = 'preset-default';
}
if(!$presets[$preset]){
$defaults = $this->getDefaultConfig();
$options = $this->getConfig();
$options[$preset] = $defaults;
if($n = $_POST[$this->id][$preset]['name'])
$options[$preset]['name'] = $n;
elseif($preset=='preset-default')
$options[$preset]['name'] = 'Default';
else{
list($junk,$id) = explode("-",$preset);
$options[$preset]['name'] = 'New Preset '.$id;
}
update_option($this->id,$options);
$presets[$preset] = $options[$preset]['name'];
}
if($_POST['delete']){
check_admin_referer($this->id.'-editpreset-'.$preset);
$options = $this->getConfig();
unset($options[$preset]);
unset($presets[$preset]);
update_option($this->id,$options);
list($preset,$name) = each($presets);
}
$index = 1;
while($presets["preset-$index"]) $index++;
$presets["preset-$index"] = __('New Preset','wp-custom-fields-search');
$linkBase = $_SERVER['REQUEST_URI'];
$linkBase = preg_replace("/&?selected-preset=[^&]*(&|$)/",'',$linkBase);
foreach($presets as $key=>$name){
$config = $this->getConfig($key);
if($config && $config['name']) $name=$config['name'];
if(($n = $_POST[$this->id][$key]['name'])&&(!$_POST['delete']))
$name = $n;
$presets[$key]=$name;
}
$plugin=&$this;
ob_start();
wp_nonce_field($this->id.'-editpreset-'.$preset);
$hidden = ob_get_contents();
$hidden.="<input type='hidden' name='selected-preset' value='$preset'>";
$shouldSave = $_POST['selected-preset'] && !$_POST['delete'] && check_admin_referer($this->id.'-editpreset-'.$preset);
ob_end_clean();
include(dirname(__FILE__).'/templates/options.php');
}
function process_tag($content){
$regex = '/\[\s*wp-custom-fields-search\s+(?:([^\]=]+(?:\s+.*)?))?\]/';
return preg_replace_callback($regex, array(&$this, 'generate_from_tag'), $content);
}
function process_shortcode($atts,$content){
return $this->generate_from_tag(array("",$atts['preset']));
}
function generate_from_tag($reMatches){
global $CustomSearchFieldStatic;
ob_start();
$preset=$reMatches[1];
if(!$preset) $preset = 'default';
wp_custom_fields_search($preset);
$form = ob_get_contents();
ob_end_clean();
return $form;
}
}
global $CustomSearchFieldStatic;
$CustomSearchFieldStatic['Inputs'] = array();
$CustomSearchFieldStatic['Types'] = array();
class AdminDropDown extends DropDownField {
function AdminDropDown($name,$value,$options,$params=array()){
AdminDropDown::__construct($name,$value,$options,$params);
}
function __construct($name,$value,$options,$params=array()){
$params['options'] = $options;
$params['id'] = $params['name'];
parent::__construct($params);
$this->name = $name;
$this->value = $value;
}
function getHTMLName(){
return $this->name;
}
function getValue(){
return $this->value;
}
function getInput(){
return parent::getInput($this->name,null);
}
}
if (!function_exists('json_encode'))
{
function json_encode($a=false)
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a))
{
if (is_float($a))
{
// Always use "." for floats.
return floatval(str_replace(",", ".", strval($a)));
}
if (is_string($a))
{
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
else
return $a;
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a))
{
if (key($a) !== $i)
{
$isList = false;
break;
}
}
$result = array();
if ($isList)
{
foreach ($a as $v) $result[] = json_encode($v);
return '[' . join(',', $result) . ']';
}
else
{
foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
return '{' . join(',', $result) . '}';
}
}
}
function wp_custom_fields_search($presetName='default'){
global $CustomSearchFieldStatic;
if(strpos($presetName,'preset-')!==0) $presetName="preset-$presetName";
$CustomSearchFieldStatic['Object']->renderWidget(array('widget_id'=>$presetName,'noTitle'=>true),array('number'=>$presetName));
}
function compat_method_exists($class,$method){
return method_exists($class,$method) || in_array(strtolower($method),get_class_methods($class));
}
Your needs would require a non-trivial expansion of the plugin with a new input class. You should probably contact the plugin's developer(s) to request the feature or search for another plugin that satisfies your needs.
If you really want to take a crack at it yourself, I suggest putting the plugin aside and rolling your own search form and pushing that input into WP_query(). Here are a few links to get you started on that:
Modifying A Search Template
Working with WP_Query()
Query argument guide