In post.php page of wp-admin I like to populate a post meta while the page is loading. For that I tried the following
add_action('load-post.php', 'show_buy_ticket_date');
function show_buy_ticket_date() {
$screen = get_current_screen();
if ($screen->post_type === 'ai1ec_event') {
$post_id = filter_input(INPUT_GET, 'post');
$buy_ticket_date_unix_timestamp = get_post_meta($post_id,
'buy_ticket_date', TRUE);
}
}
Here I fetched the post's meta value. But How can I populate it in one of the field in the form once edit page is loaded / before loading.
For e.g. the field looks like this
<input class="ai1ec-date-input ai1ec-form-control datepicker hasDatepicker" name="ai1ec_admin_buy_ticket-date-input" id="ai1ec_admin_buy_ticket-date-input" type="date">
You need to convert the timestamp to a date value suitable for input taking into account that, provided that the timestamp is in UTC time, you probably want to align it with your current timezone.
Finally, you pass the date value to input with the value attribute:
date_default_timezone_set( 'Europe/Helsinki' );
$buy_ticket_date = date( 'Y-n-j', intval( $buy_ticket_date_unix_timestamp ));
<input
class="ai1ec-date-input ai1ec-form-control datepicker hasDatepicker"
name="ai1ec_admin_buy_ticket-date-input"
id="ai1ec_admin_buy_ticket-date-input"
type="date" ,
value="<?php echo $buy_ticket_date; ?>
>
UPDATE:
Given the limitation that input is in some third-party code, I would update the field via JavaScript:
Pass $buy_ticket_date with localized JavaScript, PHP:
add_action( 'wp_enqueue_scripts', 'my_scripts' ) );
function my_scripts() {
// ... get $buy_ticket_date_unix_timestamp based on post ID
date_default_timezone_set( 'Europe/Helsinki' );
$buy_ticket_date = date( 'Y-n-j', intval( $buy_ticket_date_unix_timestamp ));
wp_register_script( 'my_script', MY_PLUGIN_URL . 'js/script.js', array( 'jquery' ) );
wp_localize_script( 'my_script', 'buy_ticket_date', $buy_ticket_date );
wp_enqueue_script( 'my_script' );
}
and JavaScript (script.js):
/*global document, jQuery */
(function ($) {
'use strict';
$(document).ready(function () {
$('#ai1ec_admin_buy_ticket-date-input').val(buy_ticket_date);
});
}(jQuery));
Related
I'm trying to find a way to choose a date and display it into a Wordpress page.
Simply put, that's the way this may operate:
One or several pages are input a shortcode or a PHP code via PHP insert
An operator/webmaster chooses a date from let's say a calendar or drop down
This date (formatted) shows into the pages that have the shortcode/PHP code
I do not want automatic or current date which I can do with this plugin.
Can anybody help achieve this with a plugin or a PHP snippet?
Display a custom date field in Settings->Reading:
function wpse_52414489_custom_date() {
// Add the section to reading settings so we can add our
// fields to it
add_settings_section(
'eg_custom_settings',
'My custom settings',
'',
'reading'
);
// Add the field with the names and function to use for our new
// settings, put it in our new section
add_settings_field(
'eg_custom_date',
'My custom date',
'eg_custom_date_callback',
'reading',
'eg_custom_settings'
);
// Register our setting so that $_POST handling is done for us and
// our callback function just has to echo the <input>
register_setting( 'reading', 'eg_custom_date' );
}
function eg_custom_date_callback() {
echo '<input name="eg_custom_date" id="eg_custom_date" type="date" value="' . get_option( 'eg_custom_date' ) . '" class="code" /> Explanation text';
}
add_action( 'admin_init', 'wpse_52414489_custom_date' );
Add your shortcode (EDIT: custom date format):
add_filter( 'init', function() {
add_shortcode( 'my-custom-date', function() {
return date( 'd/m/Y', strtotime( get_option( 'eg_custom_date' ) ) );
});
});
Usage:
[my-custom-date]
Output:
2018-09-18
I Need to make a event list in wordpress, show up by: "today" - "week" - "month" and all this show just my post. Witch is the best way to do that?
The author must just add the date and time of event and its appear in the current category us well.
If you just want to add the possibility for the author to add the date of an event, use the add_meta_boxes_{$post_slug} action.
This action allows to configure and print a new metabox in any post (choosen) post screen.
add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes');
add_action('save_post', 'save_sticked_metabox');
function adding_custom_meta_boxes(){
add_meta_box(
'sticked-list',
__( 'Featured list', $this->plugin_text_domain ),
'sticked_list_Render',
'post',
'side',
'default'
);
}
function sticked_list_Render(){
global $post;
$sticked = get_post_meta($post->ID, 'sticked', true);
$checked = '';
if($sticked != '' && isset($sticked)){
$checked = 'checked="checked"';
}
?>
<input type="checkbox" name="sticked" value="true" <?php echo $checked;?> > <?php _e('Check to set as pre-defined list', $this->plugin_text_domain);?>
<?
}
function save_sticked_metabox($post_id, $post){
if(isset($_POST['sticked'])){
update_post_meta($post_id, 'sticked', 'true');
}
else{
delete_post_meta($post_id, 'sticked');
}
}
This is just an example to show how to print a new metabox in the edit-post admin screen. You'll need to change the "sticked_list_render" to print a date & time picker.
I'm having difficulties with wp_editor(), tinyMCE and the_content filter in relation to oEmbed of video.
I am outputting a front end wp_editor() form to allow registered users to create new posts from the front end of the site. The new post created is a custom post type.
The target behaviour is:
The registered user enters content & clicks submit
The form is processed by jQuery/Ajax, with form data passed to a PHP function via post()
A new post created, and a response is generated for an Ajax callback
The response is a JSON array that contains the HTML of the new post content
The returned HTML has 'the_content' filter applied - embedded video should display properly
The Ajax callback removes the original form and appends the post HTML to a div
Everything works as expected with the exception of video oEmbed.
If a video link is added to the content (on a new line within the wp_editor), the content built by the Ajax callback includes the video URL wrapped in paragraph tags - oEmbed hasn't worked, even though the HTML has had 'the_content' filter applied.
Refreshing the page displays the new post in a loop, with content displayed by the_content() tag - and the video is displayed properly (oEmbed has worked).
Setting 'wpautop' => false in the wp_editor arguments doesn't help - messes up formatting, doesn't fix video.
Is there a tinyMCE setting that I'm missing?
Is there a problem with how I'm applying 'the_content' filter and/or building a HTML string for the Ajax callback?
Relevant code shown below.
Thanks!
JQuery
(function( $ ) { 'use strict';
$(function() {
$('#student-submission-button').click( function(event) {
// Prevent default action
// -----------------------
event.preventDefault();
var submission_nonce_id = $('#the_nonce_field').val();
var submission_title = $('#inputTitle').val();
tinyMCE.triggerSave();
var submission_content = $('#editor').val();
var Data = {
action: 'student_submission',
nonce: submission_nonce_id,
workbook_ID: submission_workbook_ID,
content: submission_content,
title: submission_title,
};
// Do AJAX request
$.post( ajax_url, Data, function(Response) {
if( Response ) {
var submissionStatus = Response.status;
var submissionMessage = Response.report;
var postHTML = Response.content;
if ( 'success' == submissionStatus ) {
$('#user-feedback').html( submissionMessage );
$('#new-post').append( postHTML );
}
// Hide the form
$('.carawebs-frontend-form').hide(800, function() {
$(this).remove();
});
}
});
});
});
})( jQuery );
PHP
/**
* Return data via Ajax (excerpt)
*
*
*/
$response = array();
if( is_int( $new_submission_ID ) ) {
// Build a success response
// ------------------------
$new_post = get_post( $new_submission_ID, OBJECT );
$new_post_content = $new_post->post_content;
$return_content = "<h2>$new_post->post_title</h2>";
$return_content .= apply_filters( 'the_content', $new_post_content );
$response['status'] = "success";
$response['report'] = "New post created, ID: $new_submission_ID";
$response['content'] = $return_content;
} else {
// error report
}
wp_send_json( $response ); // send $response as a JSON object
Form HTML and wp_editor()
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" enctype="multipart/form-data" class="carawebs-frontend-form">
<label for="inputTitle">Title</label>
<input type="text" class="form-control" id="inputTitle" name="inputTitle" placeholder="Title" value="" />
<label for="inputContent" class="topspace">Your Content</label>
<?php
$args = array(
'textarea_rows' => 45,
'teeny' => false,
'editor_height' => 400,
'editor_class' => 'cwfrontendadmin',
'quicktags' => false,
'textarea_name' => 'cw_content',
'tinymce' => array(
'content_css' => get_template_directory_uri() . '/assets/css/editor-style.css'
),
);
wp_editor( 'Enter your content...', 'editor', $args );
wp_nonce_field('name_of_action','the_nonce_field', true, true ); // name of action, name of nonce field
?>
<input id="student-submission-button" class="btn btn-primary" type="submit" name="submission-form" value="Save Content" />
Update
I've narrowed this down to the way that the_content filter is applied. I think filtered content is cached, so oEmbed may not get applied to all content if the post content is returned outside the loop.
Now I have video oEmbed working - using a different method of inserting post_content into a variable:
<?php
global $post;
$post = get_post($new_submission_ID);
setup_postdata( $post );
$new_content = apply_filters('the_content', get_the_content());
$new_post_link = get_the_permalink();
$new_post_title = get_the_title();
wp_reset_postdata( $post );
This works fine, but it would be good if someone could explain why the original method of building the HTML didn't work.
The oEmbed filter does not get applied if the post content is returned outside the loop, and global $post is not set.
This is because the video embed content is cached in the postmeta table, and is is inaccessible if the post content is returned outside the loop. The WP_Embed class which is hooked onto by the_content filter is not designed for use outside the loop - this is referenced on Trac here.
The following method returns a working Video oEmbed as per the original scenario. global $post needs to be set to make the cached video embed data available:
<?php
global $post;
$post = get_post( $new_submission_ID );
setup_postdata( $post );
$new_content = apply_filters( 'the_content', get_the_content() );
wp_reset_postdata( $post );
// return what you need via Ajax callback -
// $new_content contains the proper video embed HTML
TL;DR Version
If you need oEmbed filters to be applied outside the loop, you need to set the global post variable so that the WP_Embed class can access the cached video embed html in the post's meta.
The reason, according to other sources is because the WP_Embed::shortcode() (tasked with swapping out the video for the embedded html) is calling on the global $post variable for information.
This means you need to be sure that the global $post variable contains the information of the post you're requesting.
My AJAX response method now incorporates the global $post variable:
global $post;
$post = get_post( $id );
echo apply_filters( 'the_content', $post->post_content );
die();
This is essentially just an extension of your own findings, but I thought it might help to have a clear answer/solution to the problem of oEmbed + AJAX for WordPress.
I need a simple click counter for links in my wordpress posts. I used google a lot but couldnt find a working one. I want to count clicks from a specific class and store it in post_meta or as a custom field to display the count later.
here is some code i found but i cant get it to work..nothting happens when i click the link.
js
jQuery(document).ready(function($) {
$("a[link-out]").click(function() {
var linkout = $(this).attr("link-out");
var data = {
action: 'my_action',
postid: linkout
};
$.post(MyAjax.ajaxurl, data);
});
});
php
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/countclicks.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$post_id = $_POST['postid'];
$post_id = mysql_real_escape_string($post_id);
$wpdb->query("UPDATE wp_postmeta SET meta_value = meta_value+1 WHERE post_id = '$post_id' AND meta_key = 'clicks_out'");
}
here is another one i found here on stackoverflow, but also doenst work
coding ajax click counter on wordpress
Hi I am trying to creating some custom options for a template I am developing but I seem to be getting an error:
Warning: Illegal string offset 'show_header' in C:\xampp\htdocs\wordpress\wp-content\themes\01MyWork\includes\theme-options.php on line 62
This is the line that seems to be throwing the error:
$html = '<input type="checkbox" id="show_header" name="thanathos_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>';
And this is the entire code:
<?php
function thanatos_theme_menu(){
add_theme_page(
"Thanathos Theme Options",
"Thanathos Theme",
"administrator",
"thanathos_theme_options",
"thanathos_theme_display_callback"
);
}
add_action('admin_menu' , 'thanatos_theme_menu');
function thanathos_theme_display_callback(){
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Sandbox Theme Options</h2>
<?php settings_errors(); ?>
<!--Create the form that will be used to render our options-->
<form method="post" action="options.php">
<?php settings_fields('thanathos_theme_display_options'); ?>
<?php do_settings_sections( 'thanathos_theme_display_options' ); ?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
add_action('admin_init' , 'thanatos_initializa_theme_options');
function thanatos_initializa_theme_options(){
if( false == get_option( 'thanathos_theme_display_options' ) ) {
add_option( 'thanathos_theme_display_options' );
}
add_settings_section(
'general_settings_section',
'Thanatos Options',
'thanatos_general_options_callback',
'thanathos_theme_display_options'
);
add_settings_field(
'show_header',
'Header',
'thanathos_field_header_callback',
'thanathos_theme_display_options',
'general_settings_section',
array( // The array of arguments to pass to the callback. In this case, just a description.
'Activate this setting to display the header.'
)
);
register_setting('thanathos_theme_display_options', 'thanathos_theme_display_options');
}
function thanatos_general_options_callback(){
echo 'mergem la mare';
}
function thanathos_field_header_callback($args){
// First, we read the options collection
$options = get_option('thanathos_theme_display_options');
// Next, we update the name attribute to access this element's ID in the context of the display options array
// We also access the show_header element of the options collection in the call to the checked() helper function
$html = '<input type="checkbox" id="show_header" name="thanathos_theme_display_options[show_header]" value="1" ' . checked(1, $options['show_header'], false) . '/>';
// Here, we'll take the first argument of the array and add it to a label next to the checkbox
$html .= '<label for="show_header"> ' . $args[0] . '</label>';
echo $html;
}
?>
Yes, that's the problematic part:
if( false == get_option( 'thanathos_theme_display_options' ) ) {
add_option( 'thanathos_theme_display_options' );
}
That's the initial if statement at the beginning of the thanatos_initializa_theme_options() function.
You can find the solution in the very neat Theme Options API tut at http://wp.tutsplus.com/tutorials/theme-development/the-complete-guide-to-the-wordpress-settings-api-part-4-on-theme-options/#post-684925289
Or, more exactly more exactly in this article's comments section.
I'm pasting the Steve Bondy's smart solution here because for some reason making the page scroll to the appropriate comment doesn't work for me (in Chrome at least).
START quote
(...)One little issue I had - I followed along through reordering the code, up to just before adding the Social options. At that point I discovered that the code was broken. I would get an error like
Warning: Illegal string offset 'show_header' in ...\themes\Sandbox\functions.php
Warning: Illegal string offset 'show_content' in ...\themes\Sandbox\functions.php
Warning: Illegal string offset 'show_footer' in ...\themes\Sandbox\functions.php
It turns out that this error was caused by adding 'sandbox_theme_display_options' to the options table without giving it a value. If you change sandbox_initialize_theme_options as follows it will create and initialize the options, avoiding the error experienced by myself and others.
function sandbox_initialize_theme_options() {
// If the theme options don't exist, create them.
if( false == get_option( 'sandbox_theme_display_options' ) ) {
$options = array("show_header" => TRUE, "show_content" => TRUE, "show_footer" => TRUE);
add_option( 'sandbox_theme_display_options', $options);
} // end if
(...)
If the old code has been run the empty 'sandbox_theme_display_options' value must be deleted from the database first. Alternatively, the following code will also detect this case and correct it.
function sandbox_initialize_theme_options() {
// See if the options exist, and initialize them if they don't
$options = get_option( 'sandbox_theme_display_options' );
if( false == $options or $options == "" ) {
$options = array("show_header" => TRUE, "show_content" => TRUE, "show_footer" => TRUE);
update_option( 'sandbox_theme_display_options', $options);
} // end if
(...)
This checks for non-existant or empty options values and initializes the options using update_option instead of add_option.
EOF quote
You are using name="thanathos_theme_display_options[show_header]" in plain HTML. Probably you want to parse by PHP the string [show_header].
You may have to run:
delete_option('thanathos_theme_display_options');
during 'admin_init' if you think you have old plugin information mucking about in the database and need a fresh start.