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.
Related
My singleton pattern instance seems to lose its instance and becomes null between each request.
Whenever I call validate_api_endpoint_field when the settings are saved, my breakpoint is hit inside in the MyPlugin_Request_Manager::instance() and its value is null.
any tips?
MyPlugin_Settings.php
<?php
defined('ABSPATH') || exit;
if (!class_exists('MyPlugin_Settings')) {
class MyPlugin_Settings
{
const page = "myPlugin-settings";
const option_group_name = 'myPlugin_option_group';
const domain = "myPlugin";
protected static $_instance = null;
public function __construct()
{
self::load_dependencies();
}
public function load_dependencies()
{
require_once PAYDAY_PATH . 'classes/class-myPlugin-repository.php';
require_once PAYDAY_PATH . 'classes/class-myPlugin-request-manager.php';
}
public static function instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function admin_menu()
{
// Add a separator before the menu item.
// Bug: Makes the WooCommerce Product menu disappear
// slef::add_admin_menu_separator( 26 );
add_menu_page(
'MyPlugin',
'MyPlugin',
'manage_options',
'myPlugin-settings',
null,
'dashicons-building',
27
);
add_submenu_page('myPlugin', 'MyPlugin Settings', 'Settings', 'manage_options', self::page, array($this, 'render_plugin_settings'));
// TODO: Uncomment when Dashboard will be implemented
// add_submenu_page( 'myPlugin', 'Dashboard', 'Dashboard', 'manage_options', 'myPlugin', array(
// $this,
// 'display_page'
// ) );
}
function add_admin_menu_separator($position)
{
global $menu;
$index = 0;
foreach ($menu as $offset => $section) {
if (substr($section[2], 0, 9) == 'separator') {
$index++;
}
if ($offset >= $position) {
$menu[$position] = array('', 'read', "separator{$index}", '', 'wp-menu-separator');
break;
}
}
ksort($menu);
}
public function admin_init()
{
self::register_api_settings();
self::register_payment_methods_mapping();
self::register_payment_methods_create_invoice_on_order_status_mapping();
self::register_additional_invoice_settings_section();
}
public function admin_footer_text()
{
$current_screen = get_current_screen();
$base = $current_screen->parent_base;
if (substr($base, 0, 6) === "myPlugin") {
echo '<span id="footer-thankyou">' . esc_html__('Developed by MyPlugin ehf.', 'myPlugin') . '</span>';
}
}
public function register_api_settings()
{
$settings_section_id = 'myPlugin_api_section';
add_settings_section(
$settings_section_id,
esc_html__('API Settings', 'myPlugin'),
function () {
echo '<p>' . esc_html__('Access your ClientId and ClientSecret on MyPlugin.is underneath Settings -> Company Settings -> API', 'myPlugin') . '</p>';
},
self::page
);
// ClientId
$client_id_settings_field_id = "myPlugin_client_id";
add_settings_field(
$client_id_settings_field_id,
esc_html__('ClientID', 'myPlugin'),
array($this, 'display_field'),
self::page,
$settings_section_id,
array(
'type' => 'text', // Type of input field
'id' => $client_id_settings_field_id,
'class' => 'input-lg',
'name' => 'myPlugin_client_id',
'value' => get_option($client_id_settings_field_id, '') // The current value of the field, or set default value
)
);
register_setting(self::option_group_name, $client_id_settings_field_id, array($this, 'validate_clientId_field'));
// ClientSecret
$client_secret_settings_field_id = "myPlugin_client_secret";
add_settings_field(
$client_secret_settings_field_id,
esc_html__('ClientSecret', 'myPlugin'),
array($this, 'display_field'),
self::page,
$settings_section_id,
array(
'type' => 'password', // Type of input field
'id' => $client_secret_settings_field_id,
'class' => 'input-lg',
'name' => 'myPlugin_client_secret',
'value' => get_option($client_secret_settings_field_id, '') // The current value of the field, or set default value
)
);
register_setting(self::option_group_name, $client_secret_settings_field_id, array($this, 'validate_clientSecret_field'));
// API Endpoint
$api_endpoint_field_id = 'myPlugin_api_endpoint';
add_settings_field(
$api_endpoint_field_id,
esc_html__('API Endpoint', 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => 'myPlugin_api_endpoint',
'options' => [
esc_html__("Production", 'myPlugin') => "https://api.myPlugin.is",
esc_html__("Test", 'myPlugin') => "https://api.test.myPlugin.is",
esc_html__("Localhost", 'myPlugin') => "http://localhost:57283"
]
)
);
register_setting(self::option_group_name, $api_endpoint_field_id, array($this, 'validate_api_endpoint_field'));
}
public function register_payment_methods_mapping()
{
$settings_section_id = 'myPlugin_payment_methods_mapping_section';
add_settings_section(
$settings_section_id, // ID used to identify this section and with which to register options
// Title to be displayed on the administration page
__("Payment Methods - Mapping", 'myPlugin'),
// Callback used to render the description of the section
function () {
// TODO: Update if needed for redirecting for creating a new Payment Type within MyPlugin
echo '<p>' . __('Make sure the WooCommerce payment methods corresponds to the correct MyPlugin payment type.', 'myPlugin') . '</p>';
echo '<p>' . __('You might need to create a new payment type in MyPlugin first.', 'myPlugin') . '</p>';
},
// The page where to display the section
self::page
);
//$woocommerce_payment_methods = WC_Payment_Gateways::instance()->get_available_payment_gateways();
$woocommerce_payment_methods = WC_Payment_Gateways::instance()->payment_gateways();
$myPlugin_payment_types = MyPlugin_Repository::instance()->get_payment_types();
if (!isset($myPlugin_payment_types)) {
$myPlugin_payment_types = MyPlugin_Request_Manager::instance()->get_sales_payment_types();
MyPlugin_Repository::instance()->set_payment_types($myPlugin_payment_types);
}
$payment_type_select_options = array();
$payment_type_select_options[__('None', 'myPlugin')] = 'None';
if (isset($myPlugin_payment_types)) {
foreach ($myPlugin_payment_types as &$payment_type) {
// key => value
if (isset($payment_type) and gettype($payment_type) === "object") {
$payment_type = get_object_vars($payment_type);
$payment_type_select_options[$payment_type['title']] = $payment_type['id'];
}
if (isset($payment_type) and gettype($payment_type) === "array") {
$payment_type_select_options[$payment_type['title']] = $payment_type['id'];
}
}
}
foreach ($woocommerce_payment_methods as $payment_method) {
if ($payment_method->enabled == 'no') {
continue;
}
$id = $payment_method->id;
$title = $payment_method->get_method_title();
if ($title == "") {
try {
$title = $payment_method->title;
} catch (Exception $e) {
$title = "";
}
}
$field_id = 'myPlugin_payment_method_' . $id;
add_settings_field(
$field_id,
esc_html__($title, 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => esc_html__($field_id, 'myPlugin'),
'options' => $payment_type_select_options
)
);
register_setting(self::option_group_name, $field_id);
}
}
public function register_payment_methods_create_invoice_on_order_status_mapping()
{
$settings_section_id = 'myPlugin_create_invoice_on_order_status_section';
add_settings_section(
$settings_section_id,
'Payment Methods - Action: Create an invoice and mark it as paid',
function () {
echo '<p>' . esc_html__('Please select the corresponding WooCommerce Order Status to execute the following action:', 'myPlugin') . '</p>';
echo '<p>' . esc_html__('Create a new invoice in MyPlugin and mark it as paid.', 'myPlugin') . '</p>';
},
self::page
);
$woocommerce_payment_methods = WC_Payment_Gateways::instance()->payment_gateways();
foreach ($woocommerce_payment_methods as $payment_method) {
if ($payment_method->enabled == 'no') {
continue;
}
$id = $payment_method->id;
$title = $payment_method->get_method_title();
if ($title == "") {
try {
$title = $payment_method->title;
} catch (Exception $e) {
$title = "";
}
}
$field_id = 'myPlugin_payment_method_' . $id . '_create_invoice_on_action';
$order_statuses = wc_get_order_statuses();
add_settings_field(
$field_id,
esc_html__($title, 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => $field_id,
'options' => [
__("None", 'myPlugin') => "None",
__($order_statuses["wc-processing"], 'myPlugin') => "processing",
__($order_statuses["wc-completed"], 'myPlugin') => "completed",
]
)
);
register_setting(self::option_group_name, $field_id);
}
}
public function register_additional_invoice_settings_section()
{
$settings_section_id = 'myPlugin_invoice_settings_section';
add_settings_section(
$settings_section_id,
'Invoice Settings',
function () {
},
self::page
);
$send_email_on_invoice_create_field_id = "myPlugin_send_email_on_invoice_create";
add_settings_field(
$send_email_on_invoice_create_field_id,
esc_html__("Email the invoice as a PDF to customer when created", "myPlugin"),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => "myPlugin_send_email_on_invoice_create",
'options' => [
esc_html__('Yes', 'myPlugin') => "yes",
esc_html__('No', 'myPlugin') => "no",
]
)
);
register_setting(self::option_group_name, $send_email_on_invoice_create_field_id);
$invoice_date_option = "myPlugin_invoice_date_option";
add_settings_field(
$invoice_date_option,
esc_html__("When Invoice is created, invoice date and due date set to", "myPlugin"),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => "myPlugin_invoice_date_option",
'options' => [
esc_html__('to the date the order was first created', 'myPlugin') => "0",
esc_html__('to the date when the request is made to create an invoice', 'myPlugin') => "1",
]
)
);
register_setting(self::option_group_name, $invoice_date_option);
}
public function validate_clientId_field($input)
{
$valid = true;
$value = $input;
if (!isset($value) || empty(trim($value))) {
// We must support empty string when we clear cache and set value to empty string
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_clientId_error',
// esc_html__('ClientID is required.', 'myPlugin')
// );
}
if ($valid) {
$value = sanitize_text_field($value);
$value = strtolower($value);
}
if ($valid) {
if (strlen($value) != 32) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientId_error',
esc_html__('Invalid value for ClientID. Value has to be 32 characters long.', 'myPlugin')
);
}
}
if ($valid) {
if (!ctype_xdigit($value) || !self::is_valid_guid($value)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientId_error',
esc_html__('Invalid value for ClientID. Value has to be a hexadecimal number.', 'myPlugin')
);
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
$value = get_option('myPlugin_client_id');
}
return $value;
}
public function validate_clientSecret_field($input)
{
$valid = true;
$value = $input;
if (!isset($value) || empty(trim($value))) {
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_clientSecret_error',
// esc_html__('ClientSecret is required.', 'myPlugin')
// );
}
if ($valid) {
$value = trim($value);
$value = sanitize_text_field($value);
$value = strtolower($value);
}
if ($valid) {
if (strlen($value) != 32) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientSecret_error',
esc_html__('Invalid value for ClientSecret. Value has to be 32 characters long.', 'myPlugin')
);
}
}
if ($valid) {
if (!ctype_xdigit($value) || !self::is_valid_guid($value)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientSecret_error',
esc_html__('Invalid value for ClientSecret. Value has to be a hexadecimal number.', 'myPlugin')
);
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
$value = get_option('myPlugin_client_secret');
}
return $value;
}
// Last of three main credentials validation functions.
// we will validate all three credentials at once if the values have changed. if it is valid we will save the new values to this instance.
public function validate_api_endpoint_field($input)
{
$valid = true;
$value = $input;
$value = trim($value);
if (!isset($value) || empty($value)) {
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_api_endpoint_error',
// esc_html__('API Endpoint is required.', 'myPlugin')
// );
}
$value = sanitize_text_field($value);
if (!filter_var($value, FILTER_VALIDATE_URL)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_error',
esc_html__('Invalid value for API Endpoint. Value has to be a valid URL.', 'myPlugin')
);
}
if ($valid) {
$credential_changed = false;
$old_clientId = MyPlugin_Request_Manager::instance()->get_client_id();
$old_clientSecret = MyPlugin_Request_Manager::instance()->get_client_secret();
$old_api_endpoint = MyPlugin_Request_Manager::instance()->get_api_endpoint();
$new_clientId = get_option('myPlugin_client_id');
$new_clientSecret = get_option('myPlugin_client_secret');
$new_api_endpoint = $value;
if ($new_clientId != $old_clientId)
$credential_changed = true;
if ($new_clientSecret != $old_clientSecret)
$credential_changed = true;
if ($new_api_endpoint != $old_api_endpoint)
$credential_changed = true;
if ($credential_changed) {
if(isset($new_clientId) && !empty(trim($new_clientId))
&& isset($new_clientSecret) && !empty(trim($new_clientSecret))
&& isset($new_api_endpoint) &&! empty(trim($new_api_endpoint))) {
MyPlugin_Request_Manager::instance()->set_client_id($new_clientId);
MyPlugin_Request_Manager::instance()->set_client_secret($new_clientSecret);
MyPlugin_Request_Manager::instance()->set_api_endpoint($new_api_endpoint);
$new_auth_token = MyPlugin_Request_Manager::instance()->get_new_auth_token_and_save();
if (!isset($new_auth_token) || empty($new_auth_token)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_error',
esc_html__('Credentials are invalid. Please check your ClientID, ClientSecret and selected Api Endpoint. Make sure you have the correct values, and that you have saved the settings in MyPlugin.', 'myPlugin')
);
}
}else{
$valid = false;
}
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
// $value = get_option('myPlugin_api_endpoint');
// MyPlugin_Request_Manager::instance()->set_client_id(get_option('myPlugin_client_id'));
// MyPlugin_Request_Manager::instance()->set_client_secret(get_option('myPlugin_client_secret'));
// MyPlugin_Request_Manager::instance()->set_api_endpoint(get_option('myPlugin_api_endpoint'));
} else {
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_updated',
esc_html('Connection established.', 'myPlugin'),
'updated'
);
}
return $value;
}
public function display_field($args)
{
if ($args['type'] == 'password') {
}
echo "<input class=" . esc_html($args['class']) . " id=" . esc_html($args['id']) . " name=" . esc_html($args['name']) . " type='" . esc_html($args['type']) . "' value='" . esc_html($args['value']) . "' />";
}
public function display_select_field($args)
{
print("<select name=" . $args['name'] . ">");
foreach ($args['options'] as $key => $value) {
print("<option value=" . esc_html($value) . (selected(get_option(esc_html($args['name'])), esc_html($value)) ? " selected>" : ">") . esc_html__($key, 'myPlugin') . "</option>");
}
print("</select>");
}
public function plugin_action_links($links, $file)
{
if (substr($file, 0, 6) === "myPlugin") {
$settings_link = "" . esc_html__('Settings', 'myPlugin') . "";
// Insert in front
array_unshift($links, $settings_link);
}
return $links;
}
// Refresh Values button handler
public function admin_post_myPlugin_settings_refresh()
{
if (isset($_POST['refresh'])) {
$repository = MyPlugin_Repository::instance();
$repository->delete_payment_types();
$myPlugin_payment_types = MyPlugin_Request_Manager::instance()->get_sales_payment_types();
$repository->set_payment_types($myPlugin_payment_types);
wp_safe_redirect(esc_url(admin_url('admin.php?page=' . self::page)));
}
}
// Clear Cache button handler
public function admin_post_myPlugin_settings_clear_cache()
{
if (isset($_POST['clear_cache'])) {
$repository = MyPlugin_Repository::instance();
$repository->delete_payment_types();
$repository->delete_invoice_meta();
$repository->delete_auth_tokens();
$all_options = wp_load_alloptions();
if (isset($all_options)) {
foreach ($all_options as $option_name => $option_value) {
if (substr($option_name, 0, 6) === "myPlugin") {
update_option($option_name, "");
}
}
}
MyPlugin_Request_Manager::instance()->set_client_id("");
MyPlugin_Request_Manager::instance()->set_client_secret("");
MyPlugin_Request_Manager::instance()->set_api_endpoint("");
wp_safe_redirect(esc_url(admin_url('admin.php?page=' . self::page)));
}
}
public function is_valid_guid($str)
{
return preg_match('/^[0-9a-f]{12}[4][0-9a-f]{19}$/', $str);
}
public function render_plugin_settings()
{
?>
<div class="myPlugin_settings_wrap">
<h1><?php echo esc_html__("Settings", 'myPlugin'); ?></h1>
<div class="clear">
<a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=checkout§ion=myPlugin')); ?>">
<input type="button" class="button" value="<?php echo esc_html__('MyPlugin Claim Service Settings', 'myPlugin') ?>">
</a>
</div>
<?php
if(MyPlugin_Request_Manager::instance()->is_connected_to_endpoint()) {
echo "<h2 style='color:green;'>" . esc_html__("Active.", 'myPlugin') . "</h2>";
}else{
echo "<h2 style='color:red;'>" . esc_html__("This plugin is not active. Please fill in your credentials and save.", 'myPlugin') . "</h2>";
}
?>
<form method="POST" action="options.php">
<?php
settings_errors('myPlugin_option_group');
// Allocate all fields for a option group
settings_fields('myPlugin_option_group');
// Displays all the sections that are assigned to a certain page
do_settings_sections('myPlugin-settings');
// Render a Save Change button
submit_button();
?>
</form>
<!-- Inline Button Row - START -->
<form method="POST" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display: inline-block">
<input type="hidden" name="action" value="myPlugin_settings_refresh">
<input type="submit" id="refresh" name="refresh" class="button" value="<?php echo esc_html__("Refresh Values", 'myPlugin'); ?>">
</form>
<form method="POST" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display: inline-block; padding-left: 5px;">
<input type="hidden" name="action" value="myPlugin_settings_clear_cache">
<input type="submit" id="Disconnect" name="clear_cache" class="button" value="<?php echo esc_html__("Clear Cache", 'myPlugin'); ?>">
</form>
</div>
<?php
}
}
}
MyPlugin_Request_Manager.php
<?php
defined('ABSPATH') || exit;
if (!class_exists('MyPlugin_Request_Manager')) {
class MyPlugin_Request_Manager
{
// This is the singleton instance
private static $_instance = null;
protected $client_id;
protected $client_secret;
protected $api_endpoint;
protected $token;
protected $token_created_at;
// The constructor is private
// to prevent initiation with outer code.
private function __construct()
{
// Use $this instead of static::$_instance
$this->load_dependencies();
}
public function load_dependencies()
{
require_once MYPLUGIN_PATH . 'classes/class-myPlugin-repository.php';
require_once MYPLUGIN_PATH . 'classes/class-myPlugin-utils.php';
}
public static function instance()
{
if (static::$_instance == null) {
static::$_instance = new MyPlugin_Request_Manager();
static::$_instance->set_client_id(get_option('myPlugin_client_id'));
static::$_instance->set_client_secret(get_option('myPlugin_client_secret'));
static::$_instance->set_api_endpoint(get_option('myPlugin_api_endpoint'));
}
return static::$_instance;
}
public function get_client_id()
{
return static::$_instance->client_id;
}
public function set_client_id(string $client_id)
{
static::$_instance->client_id = $client_id;
}
public function get_client_secret()
{
return static::$_instance->client_secret;
}
public function set_client_secret(string $client_secret)
{
static::$_instance->client_secret = $client_secret;
}
public function get_api_endpoint()
{
return static::$_instance->api_endpoint;
}
public function set_api_endpoint(string $api_endpoint)
{
static::$_instance->api_endpoint = $api_endpoint;
}
}
}
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' );
What I want is to check if the columns $campo01 and $campo02 are empty or not, if not empty it displays on my page, the problem is that if a variable is empty it does not display the result of the variable that is not empty
class Test extends URLDynamic
{
public function Testando( $campo01, $campo02, $linguagem, $audio )
{
$CRUD = new CRUD;
$this->SetParametro();
$VerificaAudio = $this->SelectDados(
"campo01, campo02",
"table_01",
"WHERE mCat = ? AND mSlug = ? AND mStatus = ?",
array ( $this->SepURL[0], $this->SepURL[1], 1 )
);
foreach ( $VerificaAudio as $VerificouAudio ) {
$campo01 = $VerificouAudio['campo01'];
$campo02 = $VerificouAudio['campo02'];
if ( empty ( $campo01 ) ) {
echo 'Empty Campo 01';
} elseif ( empty ( $campo02 ) ) {
echo 'Empty Campo 02';
} else {
// Returns the value of each column.
echo $linguagem;
$Temporadas = $this->SelectDados(
"*",
"table_02",
"WHERE mCat = ? AND mSlug = ? AND tAudio = ? AND tStatus = ?",
array ( $this->SepURL[0], $this->SepURL[1], $audio, 1 )
);
} // end else
} // end foreach
}
}
$Test = new Test;
$Test->Testando( "Legendado", "Legendado" ); // campo01
$Test->Testando( "Dublado", "Dublado" ); // campo02
class Test
{
public $Teste01;
public $Teste02;
public function Testando($Param01, $Param02)
{
$this->Teste01 = '';
$this->Teste02 = 'Has value';
echo $this->checkIfEmpty($this->$Param01);
echo $this->checkIfEmpty($this->$Param02);
}
private function checkIfEmpty($var)
{
if (empty($var)) {
return 'Empty';
} else {
return $var;
}
}
}
Trying to modify a flash message function, but it is not working whatsoever. Is the $_SESSION[$type][$name] and so on format not acceptable?
function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
{
//We can only do something if name exists
if($name)
{
//No message, create it
if($message && empty($_SESSION[$type][$name]))
{
$_SESSION[$type][$name] = $message;
$_SESSION[$type][$name][$class] = $class;
$_SESSION[$type][$name][$dismiss] = $dismiss;
}
//Message exists, display it
else if($_SESSION[$type][$name] && empty($message))
{
echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name].' '.$_SESSION[$type][$name][$dismiss].'</div>';
unset($_SESSION[$type]);
}
}
}
Usage would be :
// set a message
<?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>
// display a message
<?php flash( 'test' ); ?>
I think the problem you're having is you're overwriting the $message with an array here:
$_SESSION[$type][$name] = $message; // Sets the message
$_SESSION[$type][$name][$class] = $class; // Overwrites it with an array
All you'll need to do is save the message to the same array (and make sure the index you give it can never be the same as $class or $dismiss. So for example:
$_SESSION[$type][$name]['messagetext'] = $message;
Then, of course, update the display part of the code to use that index:
echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name]['messagetext'].' '.$_SESSION[$type][$name][$dismiss].'</div>';
EDIT: After the discussion in the comments, the final code could look like this provided there is only going to be one message per $type and $name combination:
function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
{
//We can only do something if name exists
if($type)
{
//No message, create it
if($message && empty($_SESSION[$type][$name]))
{
$_SESSION[$type][$name]['message'] = $message;
$_SESSION[$type][$name]['class'] = $class;
$_SESSION[$type][$name]['dismiss'] = $dismiss;
}
//Message exists, display it
else if($_SESSION[$type] && empty($message))
{
foreach($_SESSION[$type] as $name=>$array) {
echo '<div class="'.$_SESSION[$type][$name]['class'].'">'.$_SESSION[$type][$name]['message'].' '.$_SESSION[$type][$name]['dismiss'].'</div>';
}
unset($_SESSION[$type]);
}
}
}
Usage would be:
// set a message
<?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>
// display all $type= 'error' messages
<?php flash( 'error' ); ?>
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.