I am using a script found at http://wpdevsnippets.com/add-category-tag-taxonomy-picture/. However, I cannot get the writer to answer a usage question, so here it is:
How do I use this script with a custom taxonomy on a page.php or archive.php template?
add_action('admin_head', 'wpds_admin_head');
add_action('edit_term', 'wpds_save_tax_pic');
add_action('create_term', 'wpds_save_tax_pic');
function wpds_admin_head() {
$taxonomies = get_taxonomies();
//$taxonomies = array('category'); // uncomment and specify particular taxonomies you want to add image feature.
if (is_array($taxonomies)) {
foreach ($taxonomies as $z_taxonomy) {
add_action($z_taxonomy . '_add_form_fields', 'wpds_tax_field');
add_action($z_taxonomy . '_edit_form_fields', 'wpds_tax_field');
}
}
}
// add image field in add form
function wpds_tax_field($taxonomy) {
wp_enqueue_style('thickbox');
wp_enqueue_script('thickbox');
if(empty($taxonomy)) {
echo '<div class="form-field">
<label for="wpds_tax_pic">Picture</label>
<input type="text" name="wpds_tax_pic" id="wpds_tax_pic" value="" />
</div>';
}
else{
$wpds_tax_pic_url = get_option('wpds_tax_pic' . $taxonomy->term_id);
echo '<tr class="form-field">
<th scope="row" valign="top"><label for="wpds_tax_pic">Picture</label></th>
<td><input type="text" name="wpds_tax_pic" id="wpds_tax_pic" value="' . $wpds_tax_pic_url . '" /><br />';
if(!empty($wpds_tax_pic_url))
echo '<img src="'.$wpds_tax_pic_url.'" style="max-width:200px;border: 1px solid #ccc;padding: 5px;box-shadow: 5px 5px 10px #ccc;margin-top: 10px;" >';
echo '</td></tr>';
}
echo '<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#wpds_tax_pic").click(function() {
tb_show("", "media-upload.php?type=image&TB_iframe=true");
return false;
});
window.send_to_editor = function(html) {
jQuery("#wpds_tax_pic").val( jQuery("img",html).attr("src") );
tb_remove();
}
});
</script>';
}
// save our taxonomy image while edit or save term
function wpds_save_tax_pic($term_id) {
if (isset($_POST['wpds_tax_pic']))
update_option('wpds_tax_pic' . $term_id, $_POST['wpds_tax_pic']);
}
// output taxonomy image url for the given term_id (NULL by default)
function wpds_tax_pic_url($term_id = NULL) {
if ($term_id)
return get_option('wpds_tax_pic' . $term_id);
elseif (is_category())
return get_option('wpds_tax_pic' . get_query_var('cat')) ;
elseif (is_tax()) {
$current_term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
return get_option('wpds_tax_pic' . $current_term->term_id);
}
}
And here is the function that is used to call this:
wpds_tax_pic_url();
or
wpds_tax_pic_url($category->cat_ID);
How do I use this script with a custom taxonomy on a page.php or archive.php template?
On archive.php, you can use the wpds_tax_pic_url(); without any parameters it should display the URL of the attached image.
if(wpds_tax_pic_url()){
echo '<img src="'.wpds_tax_pic_url().'" />';
}else{
// other image or nothing.
}
On page.php or post.php, something following would work
$terms = wp_get_post_terms($post_id, 'custom_taxonomy');
foreach ($terms as $t) {
if(wpds_tax_pic_url($t->term_id))
echo '<img src="'.wpds_tax_pic_url($t->term_id).'" />';
}
Related
I am adding a custom metabox for WordPress, I am able to save the value but unable to display the value in a page template.
Code in function.php
//Custome MetaBox
function custom_metabox() {
add_meta_box("custom_metabox_01", "Custom Metabox", "custom_metabox_field", "page", "side", "default", null);
}
add_action("admin_init", "custom_metabox");
function custom_metabox_field() {
wp_nonce_field(basename(__FILE__), "custom_metabox_01_nonce");
global $post;
$data = get_post_custom($post->ID);
$val = isset($data['custom_input']) ? esc_attr($data['custom_input'][0]) : 'no value';
echo '<input type="text" name="custom_input" id="custom_input" value="'.$val.'" />';
}
function save_detail() {
global $post;
if (!isset($_POST["custom_metabox_01_nonce"]) || !wp_verify_nonce($_POST["custom_metabox_01_nonce"], basename(__FILE__))){
return $post->ID;
}
if(!current_user_can("edit_post", $post->ID)){
return $post->ID;
}
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "custom_input", $_POST["custom_input"]);
}
add_action("save_post", "save_detail");
Code in template-parts/content/content-page.php
<div class="metabox">
<?php
$custom_post_type = get_post_meta($post->ID, 'custom_input', true);
echo 'meta box value: ' . $custom_post_type;
?>
</div>
Also please suggest to me how to implement the same only for "theme-template/default.php( Custom Page Template)"
Thanks in advance.
I have a banner on my Wordpress website that I want to be updated when the cart is not empty by Ajax.
Here is the non Ajaxified version:
function dynamic_banner() {
$atts = '<div class="woofc-shipping">' . alg_wc_get_left_to_free_shipping('<span style="color:#F79917"><i class="fas fa-shipping-fast" style="margin-left: 5px;"></i>Add %amount_left_for_free_shipping% more for Free shipping</span> <div class="woofc-total-right"></div>') . '</div>';
if ( ! WC()->cart->is_empty() ) {
?>
<script>
jQuery(function($){
$(".ban-text").replaceWith('<?php echo $atts; ?>')});
</script>
<?php
}
}
add_action('wp_head', 'dynamic_banner');
This is the HTML
<div class="head_strip over--hide" style="display: block;">
<p><strong>Free fast delivery*</strong> in purchases over <span class="special-price">295 NIS</span> even during the closure period!</span></p>
</div>
Have found a solution thanks to those threads by LoicTheAztec
Functions.php Code:
// Shortcode for the banner
function display_free_shipping_progress() {
return get_free_shipping_progress();
}
add_shortcode('fs_progress', 'display_free_shipping_progress');
// Function that makes calculations and display
function get_free_shipping_progress() {
$atts = '<div class="woofc-shipping">' . alg_wc_get_left_to_free_shipping('<span style="color:#F79917"><i class="fas fa-shipping-fast" style="margin-left: 5px;"></i>הוסיפי עוד %amount_left_for_free_shipping% למשלוח חינם</span> <div class="woofc-total-right"></div>') . '</div>';
$prodgress = WC()->cart->total;
//Check if cart has something else show default
if( $prodgress > 0 ) {
return '<div class="head_strip over--hide" style="display: block;">' . $atts . '</div>';
} else {
return '<div class="head_strip over--hide" style="display: block;"><span class="ban-text"><strong>*משלוח מהיר חינם</strong > בקניה מעל<span class="special-price">295₪</span> גם בתקופת הסגר!</span></div>';
}
}
// Refreshing "free shipping" progress on cart ajax events
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_free_shipping_progress' );
function refresh_free_shipping_progress( $fragments ){
$fragments['.head_strip'] = get_free_shipping_progress();
return $fragments;
}
Have passed all HTML needed to shortcode for simplicity like was recommended.
Function and filter to display a player post titles:
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="zoomsounds_player">'. do_shortcode('[zoomsounds_player source="'.trim($mp3[0]).'.mp3" play_in_footer_player="on" config="default" artistname="'.get_post_meta($id, 'arxiu_de_so', true).'" config="" ]');
/**if (wp_is_mobile())*/ {
if(get_post_meta($id, 'arxiu_de_so', true)!=""){
/** $player .= " <p id='arxiu_so'> Arxiu de so: ".get_post_meta($id, 'arxiu_de_so', true)."</p>";*/
/**$player .= '<span id="arxiuVal" style="opacity:1"> '.get_post_meta($id, 'arxiu_de_so', true).'</span>';*/
}
}
$player .="</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
The above code works fine with the_content filter and displays the player below the featured image. However, when I use this function with the the_title filter, the page doesn't load at all. The reason I want to use the_title is because I want the player to display above the featured image but below the post title.
Screenshot:-
This screenshot is to show that with the_content the player displays however it displays below post image.
Please have a look as below:
If you want to use the_title(), then you no need to pass the post_id in the the_title(), we have some params for the_title() if you want to add them like as below:
$before
(string) (Optional) Markup to prepend to the title.
Default value: ''
$after
(string) (Optional) Markup to append to the title.
Default value: ''
$echo
(bool) (Optional) Whether to echo or return the title. Default true for the echo.
Default value: true
If you want to use get_the_title(), then you must need to pass post_id inside the get_the_title($postId);
According to your code snippet, you must update your code with as below for get_the_title():
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title($id);
if(count($mp3)>1) {
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
And for the the_title(), you should update your code with as below:
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.the_title().'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
NOTE: You have not declared the title parameter in the zoomsounds_player shortcode so please pass and update accordingly.
I hope it would help you out.
I developed a small one-file plugin for a wordpress site. It's just adds an upload form for a file that POSTs to itself and then does some stuff with the file's contents once submitted.
It works fine on the staging environment, but on the live server there is a strange problem. Once I submit the form with the file the server does not bring me back to the same page but instead returns the following JSON:
{"success":false,"message":"Please enter a message."}
I am at loss what could be causing this. Has anybody come across such a problem?
The (simplified plugin):
function show_upload_form() {
if ($_FILES['userfile']) {
echo "<p>file received</p>";
$file = fopen($_FILES['userfile']['tmp_name'], "r");
$data = [];
while (!feof($file)) {
$data[] = fgetcsv($file,null,';');
}
foreach ($data as $line) {
$pid = $line[0];
if (isset($line[1])) {
$price = trim(str_replace(',', '.', $line[1]));
} else {
$price = "";
}
if (isset($line[2])) {
$title = trim(iconv("ISO-8859-1", "UTF-8", $line[2]));
} else {
$title = "";
}
global $wpdb;
$product_ids = $wpdb->get_results($wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s'", $pid));
foreach ($product_ids as $product_id) {
$elem = $product_id->post_id;
if ($price != "") {
update_post_meta($elem, '_price', $price);
update_post_meta($elem, '_sale_price', $price);
update_post_meta($elem, '_regular_price', $price);
}
if ($title != "") {
wp_update_post(array(
'ID' => $elem,
'post_title' => $title,
));
}
}
echo "<p>Produkt #".$pid;
if ($price != "") {
echo " - new price: ".$price."€";
}
if ($title != "") {
echo "- new title: ".$title;
}
}
} else {
echo "<form method=\"post\" enctype=\"multipart/form-data\">";
echo "<label for=\"file\">Select a file:</label>";
echo "<input type=\"file\" name=\"userfile\" id=\"file\">";
echo "<br /><br />";
echo "<button>Upload File</button>";
echo "<form>";
}
}
I appreciate any input.
Try something like this
<form action="<?=admin_url( 'admin-post.php' ) ?>" method="POST">
<input type="hidden" name="action" value="my_custom_plugin_action"/>
<input type="submit" value="SEND"/>
</form>
add_action( 'admin_post_nopriv_my_custom_plugin_action',array( "class_that_owns_that_function", 'show_upload_form' ) );
public function show_upload_form()
{
//Here write your code
}
Problem disappeared after deactivating and individually reactivating all the plugins for the second or third time. Guess this one will remain a mystery ...
This code adds a menu in the Settings section of Wordpress' administrator
Right now add_options_page is declared, so the custom menu appears inside Settings
I changed add_options_page to add_menu_page in order to bring that menu to the top-level, but then it stopped working (when I click the custom menu opens, but can't save settings anymore).
What's the remaining code I have to change in order to make this work?
Thanks in advance!
<?php
add_action('admin_menu', 'create_theme_options_page');
add_action('admin_init', 'register_and_build_fields');
function create_theme_options_page() {
add_options_page('Theme Options', 'Theme Options', 'administrator', __FILE__, 'options_page_fn');
}
function register_and_build_fields() {
register_setting('plugin_options', 'plugin_options', 'validate_setting');
add_settings_section('main_section', 'Main Settings', 'section_cb', __FILE__);
add_settings_field('color_scheme', 'Color Scheme:', 'color_scheme_setting', __FILE__, 'main_section');
add_settings_field('logo', 'Logo:', 'logo_setting', __FILE__, 'main_section'); // LOGO
add_settings_field('banner_heading', 'Banner Heading:', 'banner_heading_setting', __FILE__, 'main_section');
add_settings_field('adverting_information', 'Advertising Info:', 'advertising_information_setting', __FILE__, 'main_section');
add_settings_field('ad_one', 'Ad:', 'ad_setting_one', __FILE__, 'main_section'); // Ad1
add_settings_field('ad_two', 'Second Ad:', 'ad_setting_two', __FILE__, 'main_section'); // Ad2
}
function options_page_fn() {
?>
<div id="theme-options-wrap" class="widefat">
<div class="icon32" id="icon-tools"></div>
<h2>My Theme Options</h2>
<p>Take control of your theme, by overriding the default settings with your own specific preferences.</p>
<form method="post" action="options.php" enctype="multipart/form-data">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections(__FILE__); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
</div>
<?php
}
// Banner Heading
function banner_heading_setting() {
$options = get_option('plugin_options');
echo "<input name='plugin_options[banner_heading]' type='text' value='{$options['banner_heading']}' />";
}
// Color Scheme
function color_scheme_setting() {
$options = get_option('plugin_options');
$items = array("White", "Black", "#DDDDDD", "#444444");
echo "<select name='plugin_options[color_scheme]'>";
foreach ($items as $item) {
$selected = ( $options['color_scheme'] === $item ) ? 'selected = "selected"' : '';
echo "<option value='$item' $selected>$item</option>";
}
echo "</select>";
}
// Advertising info
function advertising_information_setting() {
$options = get_option('plugin_options');
echo "<textarea name='plugin_options[advertising_information]' rows='10' cols='60' type='textarea'>{$options['advertising_information']}</textarea>";
}
// Ad one
function ad_setting_one() {
echo '<input type="file" name="ad_one" />';
}
// Ad two
function ad_setting_two() {
echo '<input type="file" name="ad_two" />';
}
// Logo
function logo_setting() {
echo '<input type="file" name="logo" />';
}
function validate_setting($plugin_options) {
$keys = array_keys($_FILES);
$i = 0;
foreach ($_FILES as $image) {
// if a files was upload
if ($image['size']) {
// if it is an image
if (preg_match('/(jpg|jpeg|png|gif)$/', $image['type'])) {
$override = array('test_form' => false);
$file = wp_handle_upload($image, $override);
$plugin_options[$keys[$i]] = $file['url'];
} else {
$options = get_option('plugin_options');
$plugin_options[$keys[$i]] = $options[$logo];
wp_die('No image was uploaded.');
}
}
// else, retain the image that's already on file.
else {
$options = get_option('plugin_options');
$plugin_options[$keys[$i]] = $options[$keys[$i]];
}
$i++;
}
return $plugin_options;
}
function section_cb() {}
// Add stylesheet
add_action('admin_head', 'admin_register_head');
function admin_register_head() {
$url = get_bloginfo('template_directory') . '/functions/options_page.css';
echo "<link rel='stylesheet' href='$url' />\n";
}
Supply a proper handle when registering the menu page(fourth parameter).
Add menu example
Add top level menu page
add_menu_page( 'Theme Options', 'Theme Options', 'manage_options', 'my-theme-options', 'options_page_fn' );
Add submenu example
Add a submenu page to the new top level page
add_submenu_page( 'my-theme-options', 'Theme Sub1', 'Theme Sub1', 'manage_options', 'my-theme-options-subpage1', 'my_callback_function' );
Hope that helps..
And please consider posting your future WordPress questions on the WordPress Stack Exchange.
Regarding your main problem though, try updating the do_settings_section call to..
<?php do_settings_sections( 'main_section' ); ?>