qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
275,507
<p>i make two list theme</p> <ol> <li><p>the posts have featured image and title, but empty content. i want get this list.</p></li> <li><p>and other posts with content list.</p></li> </ol> <p>I don't have any idea, help me please</p> <pre><code> $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash') 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'ID', 'order' =&gt; 'desc'); $blank_posts = array(); $posts = new WP_Query( $args ); if ( $posts-&gt;have_posts() ) : while ( $posts-&gt;have_posts() ) : $post = $posts-&gt;the_post(); $content = get_the_content(); if(empty($content)) { array_push( $blank_posts, $post); } endwhile; endif; /* print all blank content posts */ print_r($blank_posts); </code></pre> <p>this code doesn't work, Please give me some detailed code, thanks</p>
[ { "answer_id": 275492, "author": "Sabbir Hasan", "author_id": 76587, "author_profile": "https://wordpress.stackexchange.com/users/76587", "pm_score": 2, "selected": false, "text": "<p>Try using <strong>get_post_ancestors</strong>. Here is how you can apply this in your case:</p>\n\n<pre><code>&lt;?php\n global $wp_query;\n $post = $wp_query-&gt;post;\n $ancestors = get_post_ancestors($post);\n if( empty($post-&gt;post_parent) ) {\n $parent = $post-&gt;ID;\n } else {\n $parent = end($ancestors);\n } \n if(wp_list_pages(\"title_li=&amp;child_of=$parent&amp;echo=0\" )) { \n wp_list_pages(\"title_li=&amp;child_of=$parent&amp;depth=1\" ); \n } \n?&gt;\n</code></pre>\n\n<p>You'll probably need to remove the depth parameters to show you're 3rd level pages.</p>\n\n<p>Let me know if this helps!</p>\n" }, { "answer_id": 275540, "author": "Manoj Mohan", "author_id": 125085, "author_profile": "https://wordpress.stackexchange.com/users/125085", "pm_score": 0, "selected": false, "text": "<p>Replace <code>$parent</code> in <code>child_of</code> argument of <code>wp_list_pages</code> by <code>parent-&gt;ID</code>.\n<code>wp_list_pages</code> needs the post id instead of post object.</p>\n\n<pre><code>&lt;?php \n global $post;\n $direct_parent = $post-&gt;post_parent;\n $parent = $direct_parent-&gt;post_parent;\n wp_list_pages( array(\n 'child_of' =&gt; $parent,\n 'title_li' =&gt; false,\n 'depth' =&gt; 1\n ) );\n?&gt;\n</code></pre>\n" } ]
2017/08/02
[ "https://wordpress.stackexchange.com/questions/275507", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125061/" ]
i make two list theme 1. the posts have featured image and title, but empty content. i want get this list. 2. and other posts with content list. I don't have any idea, help me please ``` $args = array( 'post_type' => 'post', 'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash') 'posts_per_page' => -1, 'orderby' => 'ID', 'order' => 'desc'); $blank_posts = array(); $posts = new WP_Query( $args ); if ( $posts->have_posts() ) : while ( $posts->have_posts() ) : $post = $posts->the_post(); $content = get_the_content(); if(empty($content)) { array_push( $blank_posts, $post); } endwhile; endif; /* print all blank content posts */ print_r($blank_posts); ``` this code doesn't work, Please give me some detailed code, thanks
Try using **get\_post\_ancestors**. Here is how you can apply this in your case: ``` <?php global $wp_query; $post = $wp_query->post; $ancestors = get_post_ancestors($post); if( empty($post->post_parent) ) { $parent = $post->ID; } else { $parent = end($ancestors); } if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { wp_list_pages("title_li=&child_of=$parent&depth=1" ); } ?> ``` You'll probably need to remove the depth parameters to show you're 3rd level pages. Let me know if this helps!
275,511
<p>I am trying to add post-meta value and after this update query and after this get_post_meta value . but add_post_meta does not work .</p> <pre><code>&lt;?php add_post_meta($post_id, 'Product_Year', trim( $_POST['Product_Year'])); ?&gt; &lt;?php update_post_meta($post_id, 'Product_Year', trim( $_POST['Product_Year'])); ?&gt; echo $year=get_post_meta($post_id , 'Product_Year',true ); </code></pre>
[ { "answer_id": 275512, "author": "Sonali", "author_id": 84167, "author_profile": "https://wordpress.stackexchange.com/users/84167", "pm_score": 0, "selected": false, "text": "<p>Add last parameter, refer this <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_post_meta</a> </p>\n\n<pre><code>add_post_meta($post_id, 'Product_Year', trim( $_POST['Product_Year']), true);\n</code></pre>\n" }, { "answer_id": 275524, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 1, "selected": false, "text": "<p>You dont need to use <code>add_post_meta</code> and <code>update_post_meta</code> for same meta_key.</p>\n\n<p>You can simply use <code>update_post_meta</code> function and this will \n<strong>add</strong> if the meta_key does not exist and will <strong>update</strong> if meta_key exists.</p>\n" } ]
2017/08/02
[ "https://wordpress.stackexchange.com/questions/275511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120176/" ]
I am trying to add post-meta value and after this update query and after this get\_post\_meta value . but add\_post\_meta does not work . ``` <?php add_post_meta($post_id, 'Product_Year', trim( $_POST['Product_Year'])); ?> <?php update_post_meta($post_id, 'Product_Year', trim( $_POST['Product_Year'])); ?> echo $year=get_post_meta($post_id , 'Product_Year',true ); ```
You dont need to use `add_post_meta` and `update_post_meta` for same meta\_key. You can simply use `update_post_meta` function and this will **add** if the meta\_key does not exist and will **update** if meta\_key exists.
275,543
<p>I have the following situation:</p> <p>I created a custom Post Type names <strong>Works</strong>. And also attached to it custom taxonomy named <strong>Work Types</strong></p> <p>Here is the code</p> <pre><code>function rk_work_post_type(){ $labels = array( 'name' =&gt; 'Work', 'singular_name' =&gt; 'Work', 'add_new' =&gt; 'Add Work', 'all_items' =&gt; 'All Works', 'add_new_item' =&gt; 'Add Work', 'edit_item' =&gt; 'Edit Work', 'new_item' =&gt; 'New Work', 'view_item' =&gt; 'View Work', 'search_item' =&gt; 'Search Work', 'not_found' =&gt; 'No items found', 'not_found_in_trash' =&gt; 'No items found in trash', 'parent_item_colon' =&gt; 'Parent Item' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; true, 'publicly_queryable' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'comments', ), // 'taxonomies' =&gt; array('category', 'post_tag'), 'menu_icon' =&gt; 'dashicons-hammer', 'menu_position' =&gt; 5, 'exclude_from_search' =&gt; false, 'show_in_rest' =&gt; true, 'rest_base' =&gt; 'works', 'rest_controller_class' =&gt; 'WP_REST_Posts_Controller', ); register_post_type('work',$args); } add_action('init','rk_work_post_type'); function rk_work_taxonomies() { //add new taxonomy hierarchical $labels = array( 'name' =&gt; 'Work Types', 'singular_name' =&gt; 'Work type', 'search_items' =&gt; 'Search Types', 'all_items' =&gt; 'All Work Types', 'parent_item' =&gt; 'Parent Type', 'parent_item_colon' =&gt; 'Parent Type:', 'edit_item' =&gt; 'Edit Work Type', 'update_item' =&gt; 'Update Work Type', 'add_new_item' =&gt; 'Add New Work Type', 'new_item_name' =&gt; 'New Work Type Name', 'menu_name' =&gt; 'Work Types' ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'work_type' ), 'show_in_rest' =&gt; true, 'rest_base' =&gt; 'work_type', 'rest_controller_class' =&gt; 'WP_REST_Terms_Controller', ); register_taxonomy('work_type', array('work'), $args); } add_action( 'init' , 'rk_work_taxonomies' ); </code></pre> <p>The issue that i have is that i cant find a way to get the <strong>Works</strong> filtered by <strong>Work Type</strong> using REST API v2</p> <p>I read that after some wordpress update filter query was removed from REST API. So what is the proper way to do this now? Can you provide some example please?</p> <p>Thank you in advance!</p>
[ { "answer_id": 275545, "author": "Scriptile", "author_id": 125086, "author_profile": "https://wordpress.stackexchange.com/users/125086", "pm_score": 5, "selected": true, "text": "<p>Ok, the solution was:</p>\n\n<pre><code>example.com/wp-json/wp/v2/works?work_type=10\n</code></pre>\n\n<p>It views the work_types as id's.\nYou can view the id's in:</p>\n\n<pre><code>example.com/wp-json/wp/v2/works\n</code></pre>\n" }, { "answer_id": 330734, "author": "DARKVIDE", "author_id": 162536, "author_profile": "https://wordpress.stackexchange.com/users/162536", "pm_score": 2, "selected": false, "text": "<p>I installed the WP REST Filter plugin and then i'm able to filter post by category slug like: </p>\n\n<pre><code>http://www.example.com/wp-json/wp/v2/my_custom_posts?filter[my_custom_taxomony]=my_custom_taxonomy_slug\n</code></pre>\n\n<p>in your case:</p>\n\n<pre><code>http://www.example.com/wp-json/wp/v2/works?filter[work_type]=building\n</code></pre>\n" }, { "answer_id": 330738, "author": "Akshay Kungiri", "author_id": 162539, "author_profile": "https://wordpress.stackexchange.com/users/162539", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_posts/</a></p>\n\n<p>This link help</p>\n\n<p>It includes get_posts() method\nWhich is used to get post</p>\n\n<p>Pass post type in argument</p>\n" }, { "answer_id": 365373, "author": "ZecKa", "author_id": 82323, "author_profile": "https://wordpress.stackexchange.com/users/82323", "pm_score": 2, "selected": false, "text": "<p>If you really need to use slug as url parameter you can add a custom filter, take a look to <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"nofollow noreferrer\">rest_{$this->post_type}_query hook</a></p>\n\n<p>You can do something like that (post_type: work, taxonomy: work_type):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Filter work post type by work_type slug\n *\n * @param array $args\n * @param WP_Rest_Rquest $request\n * @return array $args\n */\nfunction filter_rest_work_query( $args, $request ) { \n $params = $request-&gt;get_params(); \n if(isset($params['work_type_slug'])){\n $args['tax_query'] = array(\n array(\n 'taxonomy' =&gt; 'work_type',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode(',', $params['work_type_slug'])\n )\n );\n }\n return $args; \n} \n// add the filter \nadd_filter( \"rest_work_query\", 'filter_rest_work_query', 10, 2 ); \n\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>https://example.com/wp-json/wp/v2/work?work_type_slug=slug01,slug02\n</code></pre>\n" } ]
2017/08/02
[ "https://wordpress.stackexchange.com/questions/275543", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125086/" ]
I have the following situation: I created a custom Post Type names **Works**. And also attached to it custom taxonomy named **Work Types** Here is the code ``` function rk_work_post_type(){ $labels = array( 'name' => 'Work', 'singular_name' => 'Work', 'add_new' => 'Add Work', 'all_items' => 'All Works', 'add_new_item' => 'Add Work', 'edit_item' => 'Edit Work', 'new_item' => 'New Work', 'view_item' => 'View Work', 'search_item' => 'Search Work', 'not_found' => 'No items found', 'not_found_in_trash' => 'No items found in trash', 'parent_item_colon' => 'Parent Item' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'publicly_queryable' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'comments', ), // 'taxonomies' => array('category', 'post_tag'), 'menu_icon' => 'dashicons-hammer', 'menu_position' => 5, 'exclude_from_search' => false, 'show_in_rest' => true, 'rest_base' => 'works', 'rest_controller_class' => 'WP_REST_Posts_Controller', ); register_post_type('work',$args); } add_action('init','rk_work_post_type'); function rk_work_taxonomies() { //add new taxonomy hierarchical $labels = array( 'name' => 'Work Types', 'singular_name' => 'Work type', 'search_items' => 'Search Types', 'all_items' => 'All Work Types', 'parent_item' => 'Parent Type', 'parent_item_colon' => 'Parent Type:', 'edit_item' => 'Edit Work Type', 'update_item' => 'Update Work Type', 'add_new_item' => 'Add New Work Type', 'new_item_name' => 'New Work Type Name', 'menu_name' => 'Work Types' ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'work_type' ), 'show_in_rest' => true, 'rest_base' => 'work_type', 'rest_controller_class' => 'WP_REST_Terms_Controller', ); register_taxonomy('work_type', array('work'), $args); } add_action( 'init' , 'rk_work_taxonomies' ); ``` The issue that i have is that i cant find a way to get the **Works** filtered by **Work Type** using REST API v2 I read that after some wordpress update filter query was removed from REST API. So what is the proper way to do this now? Can you provide some example please? Thank you in advance!
Ok, the solution was: ``` example.com/wp-json/wp/v2/works?work_type=10 ``` It views the work\_types as id's. You can view the id's in: ``` example.com/wp-json/wp/v2/works ```
275,569
<p>I mean:</p> <pre><code>add_action( 'after_setup_theme', 'thumbs_setup' ); function thumbs_setup() { add_theme_support( 'post-thumbnails' ); } </code></pre> <p>My media settings are 150x150px on thumbnails, but now <code>the_post_thumbnail()</code> will output a full sized image instead. Why?</p> <p>I see that the only way to have <code>the_post_thumbnail()</code> to really output the thumbnail size is to explicitly pass it:</p> <p><code>the_post_thumbnail('thumbnail')</code></p> <p>Why?</p>
[ { "answer_id": 275571, "author": "Luca Reghellin", "author_id": 10381, "author_profile": "https://wordpress.stackexchange.com/users/10381", "pm_score": 2, "selected": true, "text": "<p>I think adding support to 'post-thumbnails' also adds a new type of size: 'post-thumbnail'. But 'post-thumbnail' <strong>is not</strong> == 'thumb' or 'thumbnail', it's a new, different type.\nAlso, <code>the_post_thumbnail()</code> if called without params will output the 'post-thumbnail' size instead of the 'thumb' size.</p>\n\n<p>'thumb' (or 'thumbnail') are setted via admin media panel, while 'post-thumbnail' is not.</p>\n\n<p>Since the 'post-thumbnail' size is not yet setted, than <code>the_post_thumbnail()</code> doesn't really know what size to use, and thus it will output the full image.</p>\n\n<p>To set the 'post-thumbnail' size you must use standard <code>add-image-size()</code> passing 'post-thumbnail' as the name, or, just use <code>set_post_thumbnail_size()</code>.</p>\n" }, { "answer_id": 275574, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Post_Thumbnails\" rel=\"nofollow noreferrer\"><code>the_post_thumbnail</code></a> is unfortunately named, because it suggests a small image but actually refers to the featured image of a post. Adding support for it simply makes the 'featured image' box available in your post editor.</p>\n\n<p>Now, if you <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">look at the source code</a>, you see that if there is no size specified when calling <code>the_post_thumbnail</code>, the size is defined as <code>post-thumbnail</code>. However, this is not the name of the default thumbnail generated for every image, which is <code>thumbnail</code>. There is no image size called 'post-thumbnail' generated by default. As a result, WP will use the full image.</p>\n\n<p>There are several ways to get around this, but the easiest would be to use a filter available in <code>get_the_post_thumbnail</code>, the function that is used by <code>the_post_thumbnail</code>. You can reroute the default call from 'post-thumbnail' to 'tumbnail' like this:</p>\n\n<pre><code>add_filter ('post_thumbnail_size','wpse275569_post_thumbnail_size');\nfunction wpse275569_post_thumbnail_size ($size) {\n if ($size == 'post-thumbnail') $size = 'thumbnail';\n return $size;\n }\n</code></pre>\n" } ]
2017/08/02
[ "https://wordpress.stackexchange.com/questions/275569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
I mean: ``` add_action( 'after_setup_theme', 'thumbs_setup' ); function thumbs_setup() { add_theme_support( 'post-thumbnails' ); } ``` My media settings are 150x150px on thumbnails, but now `the_post_thumbnail()` will output a full sized image instead. Why? I see that the only way to have `the_post_thumbnail()` to really output the thumbnail size is to explicitly pass it: `the_post_thumbnail('thumbnail')` Why?
I think adding support to 'post-thumbnails' also adds a new type of size: 'post-thumbnail'. But 'post-thumbnail' **is not** == 'thumb' or 'thumbnail', it's a new, different type. Also, `the_post_thumbnail()` if called without params will output the 'post-thumbnail' size instead of the 'thumb' size. 'thumb' (or 'thumbnail') are setted via admin media panel, while 'post-thumbnail' is not. Since the 'post-thumbnail' size is not yet setted, than `the_post_thumbnail()` doesn't really know what size to use, and thus it will output the full image. To set the 'post-thumbnail' size you must use standard `add-image-size()` passing 'post-thumbnail' as the name, or, just use `set_post_thumbnail_size()`.
275,629
<p>I am trying to work out a submit contact form through ajax but somehow i fail in process and i can't figure out, every combination i try it returns <code>0</code> for some reason.</p> <p>This is my form</p> <pre><code>&lt;form name="sentMessage" id="contactForm" novalidate&gt; &lt;div class="form-group wow fadeInUp"&gt; &lt;input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-validation-required-message="Please enter your name."&gt; &lt;p class="help-block text-danger"&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="form-group wow fadeInUp"&gt; &lt;input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address."&gt; &lt;p class="help-block text-danger"&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="form-group wow fadeInUp"&gt; &lt;textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-validation-required-message="Please enter a message."&gt;&lt;/textarea&gt; &lt;p class="help-block text-danger"&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div class="col-lg-12 wow fadeInUp"&gt; &lt;div id="success"&gt;&lt;/div&gt; &lt;button type="submit" class="btn btn-danger btn-lg"&gt;Send Message&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>And this is the ajax script in included.</p> <pre><code> $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message console.log(name + email + message); if (firstName.indexOf(' ') &gt;= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } var data = $form.serialize(); console.log(data); $.ajax({ url: ajax_contact.ajaxurl, dataType: 'json', action: 'ajax_contact', data: ajax_contact.data, cache: false, success: function(data) { console.log(data); if(data.status == "success") { // Success message $('#success').html("&lt;div class='alert alert-success'&gt;"); $('#success &gt; .alert-success').html("&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;").append("&lt;/button&gt;"); $('#success &gt; .alert-success').append("&lt;strong&gt;" + data.message + "&lt;/strong&gt;"); $('#success &gt; .alert-success').append('&lt;/div&gt;'); //clear all fields $('#contactForm').trigger("reset"); } if(data.status == "error") { // Error message $('#success').html("&lt;div class='alert alert-danger'&gt;"); $('#success &gt; .alert-danger').html("&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;").append("&lt;/button&gt;"); $('#success &gt; .alert-danger').append("&lt;strong&gt;" + data.message + "&lt;/strong&gt;"); $('#success &gt; .alert-danger').append('&lt;/div&gt;'); //clear all fields $('#contactForm').trigger("reset"); } }, error: function() { // Fail message $('#success').html("&lt;div class='alert alert-danger'&gt;"); $('#success &gt; .alert-danger').html("&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;").append("&lt;/button&gt;"); $('#success &gt; .alert-danger').append("&lt;strong&gt;Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success &gt; .alert-danger').append('&lt;/div&gt;'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); </code></pre> <p>And i properly added to functions.php </p> <pre><code>function ajax_contact() { try { if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) { throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.'); } if (!is_email($_POST['email'])) { throw new Exception('Email address not formatted correctly.'); } $website_email = !empty(get_theme_option('contact_email')) ? get_theme_option('contact_email') : get_bloginfo('admin_email'); $subject = 'Website Contact Form from: '.$_POST['name']; $headers = 'From: '.get_bloginfo('name').' Contact Form ' .$website_email; $send_to = $website_email; $subject = get_bloginfo('name') . " Contact Form: " .$_POST['name']; $message = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: " . $_POST['name'] . "\n\nEmail: " . $_POST['email'] . "\n\nMessage:\n". $_POST['message'] . ""; if (wp_mail($send_to, $subject, $message, $headers)) { echo json_encode(array('status' =&gt; 'success', 'message' =&gt; 'Contact message sent.')); exit; } else { throw new Exception('Failed to send email. Check AJAX handler.'); } } catch (Exception $e) { echo json_encode(array('status' =&gt; 'error', 'message' =&gt; $e-&gt;getMessage())); exit; } die(); } add_action( 'wp_ajax_ajax_contact', 'ajax_contact' ); add_action( 'wp_ajax_nopriv_ajax_contact', 'ajax_contact' ); function ajax_contact_js() { wp_localize_script('ajax-contact', 'ajax_contact', array('ajaxurl' =&gt; admin_url('admin-ajax.php'))); } add_action('wp_enqueue_scripts', 'ajax_contact_js'); </code></pre> <p>And i also enqueued all the scripts that needed in separate function, so i don't get any errors and seems that everything is included and properly added but in function it fails somehow and i always get response 0.</p>
[ { "answer_id": 275639, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The <code>action: 'ajax_contact'</code> part in: </p>\n\n<pre><code>var data = $form.serialize();\nconsole.log(data);\n$.ajax({\n url: ajax_contact.ajaxurl,\n dataType: 'json',\n action: 'ajax_contact',\n data: ajax_contact.data,\n</code></pre>\n\n<p>is most likely the cause here, that your ajax request is failing.</p>\n\n<p>Move the <em>action</em> part into the <em>data</em> set instead. </p>\n\n<p>Since you're serializing the form data, you could try to add:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"action\" value=\"ajax_contact\" /&gt;\n</code></pre>\n\n<p>into your form.</p>\n\n<p>Also make sure the data attribute:</p>\n\n<pre><code>data: ajax_contact.data,\n</code></pre>\n\n<p>is getting the serialized data, but not the undefined <code>ajax_contact.data</code>.</p>\n\n<p>You can try with manual json string instead for testing.</p>\n\n<p>ps: also consider using <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\"><em>nonce</em></a> for extra security.</p>\n" }, { "answer_id": 275727, "author": "lonerunner", "author_id": 21135, "author_profile": "https://wordpress.stackexchange.com/users/21135", "pm_score": 1, "selected": true, "text": "<p>At the end i made it working like this.</p>\n\n<pre><code>&lt;form name=\"sentMessage\" id=\"contactForm\" method=\"post\" action=\"&lt;?php echo admin_url('admin-ajax.php'); ?&gt;\" role=\"form\" data-toggle=\"validator\"&gt;\n &lt;div class=\"form-group wow fadeInUp\"&gt;\n &lt;input type=\"text\" class=\"form-control\" placeholder=\"Your Name *\" id=\"name\" name=\"name\" required data-error=\"Please enter your name.\"&gt;\n &lt;div class=\"help-block with-errors text-danger\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"form-group wow fadeInUp\"&gt;\n &lt;input type=\"email\" class=\"form-control\" placeholder=\"Your Email *\" id=\"email\" name=\"email\" required data-error=\"Please enter your email address.\"&gt;\n &lt;div class=\"help-block with-errors text-danger\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"form-group wow fadeInUp\"&gt;\n &lt;textarea class=\"form-control\" placeholder=\"Your Message *\" id=\"message\" name=\"message\" required data-error=\"Please enter a message.\"&gt;&lt;/textarea&gt;\n &lt;div class=\"help-block with-errors text-danger\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"clearfix\"&gt;&lt;/div&gt;\n &lt;div class=\"col-lg-12 wow fadeInUp\"&gt;\n &lt;div id=\"success\"&gt;&lt;/div&gt;\n &lt;input type=\"hidden\" name=\"action\" value=\"ajax_contact\" /&gt;\n &lt;?php wp_nonce_field( 'contact_nonce', 'contact_nonce' ); ?&gt;\n &lt;button type=\"submit\" class=\"btn btn-danger btn-lg\"&gt;Send Message&lt;/button&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>As you can see on the form i added <code>method</code> to <code>post</code> and <code>action</code> to <code>wordpress ajax url</code>\nI also added hidden field with value to registered action hook and nonce field.</p>\n\n<p>And in javascript file i changed to this</p>\n\n<pre><code>$('#contactForm').on('submit', function(e) {\n e.preventDefault();\n var $form = $(this);\n $.post( $form.attr('action'), $form.serialize(), 'json')\n .done(function( data ) {\n var response = JSON.parse(data);\n if(response.status == \"success\") {\n // Success message\n $('#success').html(\"&lt;div class='alert alert-success'&gt;\");\n $('#success &gt; .alert-success').html(\"&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;\").append(\"&lt;/button&gt;\");\n $('#success &gt; .alert-success').append(\"&lt;strong&gt;\" + response.message + \"&lt;/strong&gt;\");\n $('#success &gt; .alert-success').append('&lt;/div&gt;');\n //clear all fields\n $('#contactForm').trigger(\"reset\");\n } else if(response.status == \"error\") {\n // Error message\n $('#success').html(\"&lt;div class='alert alert-danger'&gt;\");\n $('#success &gt; .alert-danger').html(\"&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;\").append(\"&lt;/button&gt;\");\n $('#success &gt; .alert-danger').append(\"&lt;strong&gt;\" + response.message + \"&lt;/strong&gt;\");\n $('#success &gt; .alert-danger').append('&lt;/div&gt;');\n //clear all fields\n $('#contactForm').trigger(\"reset\");\n } else {\n // Fail message\n $('#success').html(\"&lt;div class='alert alert-danger'&gt;\");\n $('#success &gt; .alert-danger').html(\"&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;\").append(\"&lt;/button&gt;\");\n $('#success &gt; .alert-danger').append(\"&lt;strong&gt;Sorry \" + firstName + \", it seems that my mail server is not responding. Please try again later!\");\n $('#success &gt; .alert-danger').append('&lt;/div&gt;');\n //clear all fields\n $('#contactForm').trigger(\"reset\");\n }\n })\n .fail(function() {\n // Fail message\n $('#success').html(\"&lt;div class='alert alert-danger'&gt;\");\n $('#success &gt; .alert-danger').html(\"&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;\").append(\"&lt;/button&gt;\");\n $('#success &gt; .alert-danger').append(\"&lt;strong&gt;Sorry \" + firstName + \", it seems that my mail server is not responding. Please try again later!\");\n $('#success &gt; .alert-danger').append('&lt;/div&gt;');\n //clear all fields\n $('#contactForm').trigger(\"reset\");\n });\n</code></pre>\n\n<p>The most important part was <code>JSON.parse</code>\nAnd function and registered hooks in .php file remain unchanged, only thing i added was check for nonce field.</p>\n" } ]
2017/08/03
[ "https://wordpress.stackexchange.com/questions/275629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21135/" ]
I am trying to work out a submit contact form through ajax but somehow i fail in process and i can't figure out, every combination i try it returns `0` for some reason. This is my form ``` <form name="sentMessage" id="contactForm" novalidate> <div class="form-group wow fadeInUp"> <input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-validation-required-message="Please enter your name."> <p class="help-block text-danger"></p> </div> <div class="form-group wow fadeInUp"> <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group wow fadeInUp"> <textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> <div class="clearfix"></div> <div class="col-lg-12 wow fadeInUp"> <div id="success"></div> <button type="submit" class="btn btn-danger btn-lg">Send Message</button> </div> </form> ``` And this is the ajax script in included. ``` $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message console.log(name + email + message); if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } var data = $form.serialize(); console.log(data); $.ajax({ url: ajax_contact.ajaxurl, dataType: 'json', action: 'ajax_contact', data: ajax_contact.data, cache: false, success: function(data) { console.log(data); if(data.status == "success") { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-success').append("<strong>" + data.message + "</strong>"); $('#success > .alert-success').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); } if(data.status == "error") { // Error message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-danger').append("<strong>" + data.message + "</strong>"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); } }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); ``` And i properly added to functions.php ``` function ajax_contact() { try { if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) { throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.'); } if (!is_email($_POST['email'])) { throw new Exception('Email address not formatted correctly.'); } $website_email = !empty(get_theme_option('contact_email')) ? get_theme_option('contact_email') : get_bloginfo('admin_email'); $subject = 'Website Contact Form from: '.$_POST['name']; $headers = 'From: '.get_bloginfo('name').' Contact Form ' .$website_email; $send_to = $website_email; $subject = get_bloginfo('name') . " Contact Form: " .$_POST['name']; $message = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: " . $_POST['name'] . "\n\nEmail: " . $_POST['email'] . "\n\nMessage:\n". $_POST['message'] . ""; if (wp_mail($send_to, $subject, $message, $headers)) { echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.')); exit; } else { throw new Exception('Failed to send email. Check AJAX handler.'); } } catch (Exception $e) { echo json_encode(array('status' => 'error', 'message' => $e->getMessage())); exit; } die(); } add_action( 'wp_ajax_ajax_contact', 'ajax_contact' ); add_action( 'wp_ajax_nopriv_ajax_contact', 'ajax_contact' ); function ajax_contact_js() { wp_localize_script('ajax-contact', 'ajax_contact', array('ajaxurl' => admin_url('admin-ajax.php'))); } add_action('wp_enqueue_scripts', 'ajax_contact_js'); ``` And i also enqueued all the scripts that needed in separate function, so i don't get any errors and seems that everything is included and properly added but in function it fails somehow and i always get response 0.
At the end i made it working like this. ``` <form name="sentMessage" id="contactForm" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" role="form" data-toggle="validator"> <div class="form-group wow fadeInUp"> <input type="text" class="form-control" placeholder="Your Name *" id="name" name="name" required data-error="Please enter your name."> <div class="help-block with-errors text-danger"></div> </div> <div class="form-group wow fadeInUp"> <input type="email" class="form-control" placeholder="Your Email *" id="email" name="email" required data-error="Please enter your email address."> <div class="help-block with-errors text-danger"></div> </div> <div class="form-group wow fadeInUp"> <textarea class="form-control" placeholder="Your Message *" id="message" name="message" required data-error="Please enter a message."></textarea> <div class="help-block with-errors text-danger"></div> </div> <div class="clearfix"></div> <div class="col-lg-12 wow fadeInUp"> <div id="success"></div> <input type="hidden" name="action" value="ajax_contact" /> <?php wp_nonce_field( 'contact_nonce', 'contact_nonce' ); ?> <button type="submit" class="btn btn-danger btn-lg">Send Message</button> </div> </form> ``` As you can see on the form i added `method` to `post` and `action` to `wordpress ajax url` I also added hidden field with value to registered action hook and nonce field. And in javascript file i changed to this ``` $('#contactForm').on('submit', function(e) { e.preventDefault(); var $form = $(this); $.post( $form.attr('action'), $form.serialize(), 'json') .done(function( data ) { var response = JSON.parse(data); if(response.status == "success") { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-success').append("<strong>" + response.message + "</strong>"); $('#success > .alert-success').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); } else if(response.status == "error") { // Error message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-danger').append("<strong>" + response.message + "</strong>"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); } else { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); } }) .fail(function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }); ``` The most important part was `JSON.parse` And function and registered hooks in .php file remain unchanged, only thing i added was check for nonce field.
275,708
<p>In the Public Function <code>Update</code> this code is sitting →</p> <blockquote> <pre><code>`public function update($new_instance, $old_instance) $instance['description_box'] = $new_instance['description_box']; </code></pre> </blockquote> <p>In the public function widget, this code is sitting →</p> <blockquote> <pre><code>public function widget($args, $instance) { $description_box = $instance[ 'description_box' ] ? 'true' : 'false'; </code></pre> </blockquote> <p>In the public function→</p> <blockquote> <pre><code>public function form( $instance ) { </code></pre> </blockquote> <p>This code is sitting → </p> <blockquote> <pre><code>&lt;p&gt; &lt;input class="checkbox" type="checkbox" &lt;?php checked( $instance[ 'description_box' ], 'on' ); ?&gt; id="&lt;?php echo $this-&gt;get_field_id( 'description_box' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'description_box' ); ?&gt;" /&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'description_box' ); ?&gt;"&gt;Check whether to display description or not&lt;/label&gt; &lt;/p&gt; </code></pre> </blockquote> <p>Now what i want is when the condition is true i.e. the box is checked then execute some code.</p> <pre><code>If ($description_box is true) { &lt;p&gt;some text&lt;/p&gt; } </code></pre> <p>How to correctly write this using this →<a href="https://codex.wordpress.org/Function_Reference/checked" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/checked</a></p> <p>Update →</p> <p>I tried using this →</p> <pre><code>&lt;?php if($description_box==0){ ?&gt; &lt;p&gt;&lt;&lt;/p&gt; &lt;?php } ?&gt; </code></pre> <p>But the problem is if the widget is in 2 different sidebars, in one checkbox ticked and in another not, but the result is same in both i.e. it either displays <code>&lt;p&gt;&lt;/p&gt;</code> or not based on the either <code>$description_box</code> is set to 0/1 or true/false in the <code>php</code> <code>if condition</code>. whats the remedy?</p>
[ { "answer_id": 275761, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Here's a full implementation of a simple widget with a checkbox that hides/shows something on the front end:</p>\n\n<pre><code>class Checkbox_Widget extends WP_Widget {\n public function __construct() {\n parent::__construct(\n 'checkbox-widget',\n 'Checkbox widget',\n array(\n 'classname' =&gt; 'widget_checkbox',\n )\n );\n }\n\n public function widget($args, $instance) {\n $checkbox = isset( $instance['checkbox'] ) ? $instance['checkbox'] : false;\n\n $args['before_widget'];\n\n if ( $checkbox === 'on' ) {\n echo 'I\\'m checked!';\n }\n\n $args['after_widget'];\n }\n\n public function form( $instance ) {\n $checkbox = isset( $instance['checkbox'] ) ? $instance['checkbox'] : false;\n ?&gt;\n\n &lt;p&gt;&lt;input type=\"checkbox\" id=\"&lt;?php echo $this-&gt;get_field_id( 'checkbox' ); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name( 'checkbox' ); ?&gt;\" &lt;?php checked( $checkbox, 'on' ); ?&gt;&gt;\n\n &lt;?php\n }\n\n public function update( $new_instance, $old_instance ) {\n $new_instance['checkbox'] = $new_instance['checkbox'] === 'on' ? 'on' : false;\n\n return $new_instance;\n }\n}\n</code></pre>\n\n<p>Based on you answers to my comment, I think we're you're going wrong is not getting the current value of the checkbox correctly. See, in my example, how the value of <code>$instance['checkbox']</code> is being set to <code>on</code> if it's checked, and then in the widget I'm checking if it equals <code>on</code> when outputting.</p>\n" }, { "answer_id": 275772, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>Now, based on your full code, there's 3 problems:</p>\n\n<p>Line 60 of your code is missing a semi colon and throwing a fatal error. So:</p>\n\n<pre><code>$instance['description_check_box'] = $new_instance['description_check_box'] \n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$instance['description_check_box'] = $new_instance['description_check_box']; \n</code></pre>\n\n<p>On line 66, you're using strings instead of proper boolean <code>true</code> or <code>false</code> values. Both if these are 'truthy' (see <a href=\"https://stackoverflow.com/a/6693908/2684861\">this answer</a> to another question for what that means), so will both resolve as <code>true</code> if used in an if statement. <code>if ('false')</code> is <code>true</code>. So:</p>\n\n<pre><code>$description_check_box = $instance[ 'description_check_box' ] ? 'true' : 'false';\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$description_check_box = $instance[ 'description_check_box' ] ? true : false;\n</code></pre>\n\n<p>On line 121 you haven't got <code>on</code> in quotes, so you're comparing <code>$description_check_box</code> to the <em>constant</em> <code>on</code>. This should be in quotes if you want to check if the value of <code>$description_check_box</code> is <code>on</code>. So:</p>\n\n<pre><code>&lt;?php if($description_check_box==on){ ?&gt;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>&lt;?php if($description_check_box=='on'){ ?&gt;\n</code></pre>\n\n<p>BUT. This still won't work. Because you'd be setting <code>$description_check_box</code> to <code>true</code> or <code>false</code> based on whether it's checked on line 66, but later you're checking if the value is <code>'on'</code>.</p>\n\n<p>You either need to set the value of <code>$description_check_box</code> to <code>'on'</code>, or change your comparison to checking if <code>$description_check_box</code> is <code>true</code>.</p>\n\n<p>You should also use <code>isset()</code> before using <code>$instance['description_check_box']</code>, because otherwise you'll get an undefined index notice in the customiser when WP_Debug is enabled.</p>\n\n<p>Refer to my other answer for my approach, which avoids all these problems.</p>\n" } ]
2017/08/03
[ "https://wordpress.stackexchange.com/questions/275708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
In the Public Function `Update` this code is sitting → > > > ``` > `public function update($new_instance, $old_instance) > > $instance['description_box'] = $new_instance['description_box']; > > ``` > > In the public function widget, this code is sitting → > > > ``` > public function widget($args, $instance) { > > $description_box = $instance[ 'description_box' ] ? 'true' : 'false'; > > ``` > > In the public function→ > > > ``` > public function form( $instance ) { > > ``` > > This code is sitting → > > > ``` > <p> <input class="checkbox" type="checkbox" <?php checked( $instance[ 'description_box' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'description_box' ); ?>" name="<?php echo $this->get_field_name( 'description_box' ); ?>" /> > <label for="<?php echo $this->get_field_id( 'description_box' ); ?>">Check whether to display description or not</label> > </p> > > ``` > > Now what i want is when the condition is true i.e. the box is checked then execute some code. ``` If ($description_box is true) { <p>some text</p> } ``` How to correctly write this using this →<https://codex.wordpress.org/Function_Reference/checked> Update → I tried using this → ``` <?php if($description_box==0){ ?> <p><</p> <?php } ?> ``` But the problem is if the widget is in 2 different sidebars, in one checkbox ticked and in another not, but the result is same in both i.e. it either displays `<p></p>` or not based on the either `$description_box` is set to 0/1 or true/false in the `php` `if condition`. whats the remedy?
Now, based on your full code, there's 3 problems: Line 60 of your code is missing a semi colon and throwing a fatal error. So: ``` $instance['description_check_box'] = $new_instance['description_check_box'] ``` Should be: ``` $instance['description_check_box'] = $new_instance['description_check_box']; ``` On line 66, you're using strings instead of proper boolean `true` or `false` values. Both if these are 'truthy' (see [this answer](https://stackoverflow.com/a/6693908/2684861) to another question for what that means), so will both resolve as `true` if used in an if statement. `if ('false')` is `true`. So: ``` $description_check_box = $instance[ 'description_check_box' ] ? 'true' : 'false'; ``` Should be: ``` $description_check_box = $instance[ 'description_check_box' ] ? true : false; ``` On line 121 you haven't got `on` in quotes, so you're comparing `$description_check_box` to the *constant* `on`. This should be in quotes if you want to check if the value of `$description_check_box` is `on`. So: ``` <?php if($description_check_box==on){ ?> ``` Should be: ``` <?php if($description_check_box=='on'){ ?> ``` BUT. This still won't work. Because you'd be setting `$description_check_box` to `true` or `false` based on whether it's checked on line 66, but later you're checking if the value is `'on'`. You either need to set the value of `$description_check_box` to `'on'`, or change your comparison to checking if `$description_check_box` is `true`. You should also use `isset()` before using `$instance['description_check_box']`, because otherwise you'll get an undefined index notice in the customiser when WP\_Debug is enabled. Refer to my other answer for my approach, which avoids all these problems.
275,716
<p>In WordPress page in put google map Embed Code like this</p> <pre><code>&lt;iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d805184.6317849847!2d144.49269473369353!3d-37.97123702210555!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6ad646b5d2ba4df7%3A0x4045675218ccd90!2sMelbourne+VIC!5e0!3m2!1sen!2sau!4v1501764505542" width="600" height="450" frameborder="0" style="border:0" allowfullscreen&gt;&lt;/iframe&gt; </code></pre> <p>After publish, this part dispear.</p> <pre><code> width="600" height="450" </code></pre> <p>So, map show up in a very small size, about 200px X 100px</p>
[ { "answer_id": 275761, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Here's a full implementation of a simple widget with a checkbox that hides/shows something on the front end:</p>\n\n<pre><code>class Checkbox_Widget extends WP_Widget {\n public function __construct() {\n parent::__construct(\n 'checkbox-widget',\n 'Checkbox widget',\n array(\n 'classname' =&gt; 'widget_checkbox',\n )\n );\n }\n\n public function widget($args, $instance) {\n $checkbox = isset( $instance['checkbox'] ) ? $instance['checkbox'] : false;\n\n $args['before_widget'];\n\n if ( $checkbox === 'on' ) {\n echo 'I\\'m checked!';\n }\n\n $args['after_widget'];\n }\n\n public function form( $instance ) {\n $checkbox = isset( $instance['checkbox'] ) ? $instance['checkbox'] : false;\n ?&gt;\n\n &lt;p&gt;&lt;input type=\"checkbox\" id=\"&lt;?php echo $this-&gt;get_field_id( 'checkbox' ); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name( 'checkbox' ); ?&gt;\" &lt;?php checked( $checkbox, 'on' ); ?&gt;&gt;\n\n &lt;?php\n }\n\n public function update( $new_instance, $old_instance ) {\n $new_instance['checkbox'] = $new_instance['checkbox'] === 'on' ? 'on' : false;\n\n return $new_instance;\n }\n}\n</code></pre>\n\n<p>Based on you answers to my comment, I think we're you're going wrong is not getting the current value of the checkbox correctly. See, in my example, how the value of <code>$instance['checkbox']</code> is being set to <code>on</code> if it's checked, and then in the widget I'm checking if it equals <code>on</code> when outputting.</p>\n" }, { "answer_id": 275772, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>Now, based on your full code, there's 3 problems:</p>\n\n<p>Line 60 of your code is missing a semi colon and throwing a fatal error. So:</p>\n\n<pre><code>$instance['description_check_box'] = $new_instance['description_check_box'] \n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$instance['description_check_box'] = $new_instance['description_check_box']; \n</code></pre>\n\n<p>On line 66, you're using strings instead of proper boolean <code>true</code> or <code>false</code> values. Both if these are 'truthy' (see <a href=\"https://stackoverflow.com/a/6693908/2684861\">this answer</a> to another question for what that means), so will both resolve as <code>true</code> if used in an if statement. <code>if ('false')</code> is <code>true</code>. So:</p>\n\n<pre><code>$description_check_box = $instance[ 'description_check_box' ] ? 'true' : 'false';\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$description_check_box = $instance[ 'description_check_box' ] ? true : false;\n</code></pre>\n\n<p>On line 121 you haven't got <code>on</code> in quotes, so you're comparing <code>$description_check_box</code> to the <em>constant</em> <code>on</code>. This should be in quotes if you want to check if the value of <code>$description_check_box</code> is <code>on</code>. So:</p>\n\n<pre><code>&lt;?php if($description_check_box==on){ ?&gt;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>&lt;?php if($description_check_box=='on'){ ?&gt;\n</code></pre>\n\n<p>BUT. This still won't work. Because you'd be setting <code>$description_check_box</code> to <code>true</code> or <code>false</code> based on whether it's checked on line 66, but later you're checking if the value is <code>'on'</code>.</p>\n\n<p>You either need to set the value of <code>$description_check_box</code> to <code>'on'</code>, or change your comparison to checking if <code>$description_check_box</code> is <code>true</code>.</p>\n\n<p>You should also use <code>isset()</code> before using <code>$instance['description_check_box']</code>, because otherwise you'll get an undefined index notice in the customiser when WP_Debug is enabled.</p>\n\n<p>Refer to my other answer for my approach, which avoids all these problems.</p>\n" } ]
2017/08/03
[ "https://wordpress.stackexchange.com/questions/275716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18787/" ]
In WordPress page in put google map Embed Code like this ``` <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d805184.6317849847!2d144.49269473369353!3d-37.97123702210555!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6ad646b5d2ba4df7%3A0x4045675218ccd90!2sMelbourne+VIC!5e0!3m2!1sen!2sau!4v1501764505542" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> ``` After publish, this part dispear. ``` width="600" height="450" ``` So, map show up in a very small size, about 200px X 100px
Now, based on your full code, there's 3 problems: Line 60 of your code is missing a semi colon and throwing a fatal error. So: ``` $instance['description_check_box'] = $new_instance['description_check_box'] ``` Should be: ``` $instance['description_check_box'] = $new_instance['description_check_box']; ``` On line 66, you're using strings instead of proper boolean `true` or `false` values. Both if these are 'truthy' (see [this answer](https://stackoverflow.com/a/6693908/2684861) to another question for what that means), so will both resolve as `true` if used in an if statement. `if ('false')` is `true`. So: ``` $description_check_box = $instance[ 'description_check_box' ] ? 'true' : 'false'; ``` Should be: ``` $description_check_box = $instance[ 'description_check_box' ] ? true : false; ``` On line 121 you haven't got `on` in quotes, so you're comparing `$description_check_box` to the *constant* `on`. This should be in quotes if you want to check if the value of `$description_check_box` is `on`. So: ``` <?php if($description_check_box==on){ ?> ``` Should be: ``` <?php if($description_check_box=='on'){ ?> ``` BUT. This still won't work. Because you'd be setting `$description_check_box` to `true` or `false` based on whether it's checked on line 66, but later you're checking if the value is `'on'`. You either need to set the value of `$description_check_box` to `'on'`, or change your comparison to checking if `$description_check_box` is `true`. You should also use `isset()` before using `$instance['description_check_box']`, because otherwise you'll get an undefined index notice in the customiser when WP\_Debug is enabled. Refer to my other answer for my approach, which avoids all these problems.
275,718
<p>Wordpress post favorite image not showing on wp-admin and on page although it is set on DB. I have inserted posts with unnecessary data and post meta in DB from other db, all is ok. When I call thumbnail url like this , it is working</p> <pre><code>$url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) ); echo $url; </code></pre> <p>But when I run it like this, not working, also not showing the image on post edit page on wp-admin.</p> <pre><code>echo get_the_post_thumbnail(); </code></pre> <p>What I have missed?</p> <blockquote> <p>Images urls are from the same server, but from different domains. website I am working in is website.tv/sub (another WP project), but the images urls are come from website.tv(the main WP project).</p> </blockquote>
[ { "answer_id": 275719, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You have to echo it out:</p>\n\n<pre><code>echo get_the_post_thumbnail();\n</code></pre>\n\n<p>Perhaps you meant to use <code>the_post_thumbnail();</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a></p>\n" }, { "answer_id": 275739, "author": "devdarsh", "author_id": 52892, "author_profile": "https://wordpress.stackexchange.com/users/52892", "pm_score": 0, "selected": false, "text": "<p>As you said the images are from another domain, it won't load. Check the database for 'siteurl' and 'home' columns in YOUR_TABLE_PREFIX_options table have the correct url that you're working on.</p>\n\n<p>Probably this may be the problem </p>\n\n<blockquote>\n <p>website.tv/sub and website.tv(the main WP project).</p>\n</blockquote>\n\n<p>Your main WP project is overriding the urls of your sub project. Try to move your sub project to a sub domain (sub.website.tv)</p>\n" } ]
2017/08/03
[ "https://wordpress.stackexchange.com/questions/275718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57668/" ]
Wordpress post favorite image not showing on wp-admin and on page although it is set on DB. I have inserted posts with unnecessary data and post meta in DB from other db, all is ok. When I call thumbnail url like this , it is working ``` $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $url; ``` But when I run it like this, not working, also not showing the image on post edit page on wp-admin. ``` echo get_the_post_thumbnail(); ``` What I have missed? > > Images urls are from the same server, but from different domains. > website I am working in is website.tv/sub (another WP project), but > the images urls are come from website.tv(the main WP project). > > >
You have to echo it out: ``` echo get_the_post_thumbnail(); ``` Perhaps you meant to use `the_post_thumbnail();` <https://developer.wordpress.org/reference/functions/the_post_thumbnail/>
275,724
<p>I want to replace ORDER word with something like Entry Form everywhere in the wordpress website. I am trying following method to replace Order word.</p> <pre><code>add_filter('gettext', 'translate_reply'); add_filter('ngettext', 'translate_reply'); function translate_reply($translated) { $translated = str_ireplace('Order' , 'something' , $translated); return $translated; </code></pre> <p>But when i apply this method some some sotecode stop working like order_id/ order_date etc.</p> <p>Any other idea how can i replace ORDER word without any extra effect.</p>
[ { "answer_id": 275719, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You have to echo it out:</p>\n\n<pre><code>echo get_the_post_thumbnail();\n</code></pre>\n\n<p>Perhaps you meant to use <code>the_post_thumbnail();</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a></p>\n" }, { "answer_id": 275739, "author": "devdarsh", "author_id": 52892, "author_profile": "https://wordpress.stackexchange.com/users/52892", "pm_score": 0, "selected": false, "text": "<p>As you said the images are from another domain, it won't load. Check the database for 'siteurl' and 'home' columns in YOUR_TABLE_PREFIX_options table have the correct url that you're working on.</p>\n\n<p>Probably this may be the problem </p>\n\n<blockquote>\n <p>website.tv/sub and website.tv(the main WP project).</p>\n</blockquote>\n\n<p>Your main WP project is overriding the urls of your sub project. Try to move your sub project to a sub domain (sub.website.tv)</p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275724", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114560/" ]
I want to replace ORDER word with something like Entry Form everywhere in the wordpress website. I am trying following method to replace Order word. ``` add_filter('gettext', 'translate_reply'); add_filter('ngettext', 'translate_reply'); function translate_reply($translated) { $translated = str_ireplace('Order' , 'something' , $translated); return $translated; ``` But when i apply this method some some sotecode stop working like order\_id/ order\_date etc. Any other idea how can i replace ORDER word without any extra effect.
You have to echo it out: ``` echo get_the_post_thumbnail(); ``` Perhaps you meant to use `the_post_thumbnail();` <https://developer.wordpress.org/reference/functions/the_post_thumbnail/>
275,726
<p>Even though I type "<a href="http://aoafinc.org/wp-admin" rel="nofollow noreferrer">http://aoafinc.org/wp-admin</a>" into the address bar, it was turned into "<a href="https://aoafinc.org/wp-admin" rel="nofollow noreferrer">https://aoafinc.org/wp-admin</a>". Also, all the links to images on my site are "https" instead of "http". Since my SSL certificate has expired, all these images can't be loaded.</p> <p>I just take over this website from someone and don't want to renew the SSL, also I am not very familiar with WP or SSL either, but I guess I don't have to manually edit all the image links, there should be somewhere on WP's back end to set the website as non-ssl and hopefully all links will become "http". And more essentially, why the browser is requesting HTTPS url even though I type in a HTTP url? </p>
[ { "answer_id": 275719, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You have to echo it out:</p>\n\n<pre><code>echo get_the_post_thumbnail();\n</code></pre>\n\n<p>Perhaps you meant to use <code>the_post_thumbnail();</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a></p>\n" }, { "answer_id": 275739, "author": "devdarsh", "author_id": 52892, "author_profile": "https://wordpress.stackexchange.com/users/52892", "pm_score": 0, "selected": false, "text": "<p>As you said the images are from another domain, it won't load. Check the database for 'siteurl' and 'home' columns in YOUR_TABLE_PREFIX_options table have the correct url that you're working on.</p>\n\n<p>Probably this may be the problem </p>\n\n<blockquote>\n <p>website.tv/sub and website.tv(the main WP project).</p>\n</blockquote>\n\n<p>Your main WP project is overriding the urls of your sub project. Try to move your sub project to a sub domain (sub.website.tv)</p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275726", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125207/" ]
Even though I type "<http://aoafinc.org/wp-admin>" into the address bar, it was turned into "<https://aoafinc.org/wp-admin>". Also, all the links to images on my site are "https" instead of "http". Since my SSL certificate has expired, all these images can't be loaded. I just take over this website from someone and don't want to renew the SSL, also I am not very familiar with WP or SSL either, but I guess I don't have to manually edit all the image links, there should be somewhere on WP's back end to set the website as non-ssl and hopefully all links will become "http". And more essentially, why the browser is requesting HTTPS url even though I type in a HTTP url?
You have to echo it out: ``` echo get_the_post_thumbnail(); ``` Perhaps you meant to use `the_post_thumbnail();` <https://developer.wordpress.org/reference/functions/the_post_thumbnail/>
275,749
<p>Every time i tried to update WordPress ,i faced this error:</p> <blockquote> <p>Fatal error: Maximum execution time of 120 seconds exceeded in G:\wamp\www\wordpress\wp-includes\Requests\Transport\fsockopen.php on line 246</p> </blockquote> <p>Code of line number 246 is:</p> <pre><code>$block = fread($socket, Requests::BUFFER_SIZE); </code></pre> <p>How can i solve this problem?</p>
[ { "answer_id": 275750, "author": "jreis", "author_id": 124042, "author_profile": "https://wordpress.stackexchange.com/users/124042", "pm_score": 0, "selected": false, "text": "<p>Increase the maximum execution time of PHP.</p>\n\n<p>You can do that on <code>php.ini</code>, on <code>.htaccess</code> or probably you can do it in the <code>wp-config.php</code> file.</p>\n\n<p>For mores information, visit <a href=\"https://codex.wordpress.org/Common_WordPress_Errors#Maximum_execution_time_exceeded\" rel=\"nofollow noreferrer\">this</a> codex page.</p>\n" }, { "answer_id": 275765, "author": "Prakash Dwivedi", "author_id": 125226, "author_profile": "https://wordpress.stackexchange.com/users/125226", "pm_score": 1, "selected": false, "text": "<p>This issue generally occurs when php script takes more time for execution than set in php.ini file</p>\n\n<p>You can resolve this issue by using two methods:</p>\n\n<p>Method 1: Editing .htaccess File Manually</p>\n\n<p>Put <strong>php_value max_execution_time 600</strong> in .htaccess file 600 is the value of execution time in seconds, you can use yours value, the maximum value is better.</p>\n\n<p>Method 2: You can use <a href=\"https://wordpress.org/plugins/wp-maximum-execution-time-exceeded/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-maximum-execution-time-exceeded/</a> plugin to maximise the execution tome</p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275749", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125218/" ]
Every time i tried to update WordPress ,i faced this error: > > Fatal error: Maximum execution time of 120 seconds exceeded in > G:\wamp\www\wordpress\wp-includes\Requests\Transport\fsockopen.php on > line 246 > > > Code of line number 246 is: ``` $block = fread($socket, Requests::BUFFER_SIZE); ``` How can i solve this problem?
This issue generally occurs when php script takes more time for execution than set in php.ini file You can resolve this issue by using two methods: Method 1: Editing .htaccess File Manually Put **php\_value max\_execution\_time 600** in .htaccess file 600 is the value of execution time in seconds, you can use yours value, the maximum value is better. Method 2: You can use <https://wordpress.org/plugins/wp-maximum-execution-time-exceeded/> plugin to maximise the execution tome
275,774
<p>i'm struggling with enqueueing the style.css and bootstrap.css files. i tried a lot solutions but no one worked. i also tried like in the video but it didnt work: <a href="https://youtu.be/mtOW2J7zOSk?t=6m28s" rel="nofollow noreferrer">https://youtu.be/mtOW2J7zOSk?t=6m28s</a></p> <p>can anyone tell me what i'm doing wrong please?</p> <pre><code>function load_styles() { wp_enqueue_style( 'bootstrap-min', get_template_directory_uri() . '/assets/css/bootstrap.min.css', array(), null); wp_enqueue_style( 'bootstrap-theme', get_template_directory_uri() . '/assets/css/bootstrap-theme.min.css', array( 'bootstrap-min' ), null ); wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css'); } add_action('wp_enqueue_scripts', 'load_styles'); </code></pre> <p>Directory:</p> <p><a href="https://i.stack.imgur.com/YfuBn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YfuBn.png" alt="Directory"></a></p>
[ { "answer_id": 275776, "author": "Prakash Dwivedi", "author_id": 125226, "author_profile": "https://wordpress.stackexchange.com/users/125226", "pm_score": 0, "selected": false, "text": "<p>I would suggest you to use following syntax:</p>\n\n<p>\n\n<pre><code>//Load the theme CSS\nfunction theme_styles() {\n wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css');\n wp_enqueue_style( 'main', get_template_directory_uri() . '/style.css');\n}\n\nadd_action( 'wp_enqueue_scripts', 'theme_styles' );\n</code></pre>\n" }, { "answer_id": 275896, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 1, "selected": false, "text": "<p>use <code>wp_head();</code> before <code>&lt;/head&gt;</code> in <code>header.php</code></p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125228/" ]
i'm struggling with enqueueing the style.css and bootstrap.css files. i tried a lot solutions but no one worked. i also tried like in the video but it didnt work: <https://youtu.be/mtOW2J7zOSk?t=6m28s> can anyone tell me what i'm doing wrong please? ``` function load_styles() { wp_enqueue_style( 'bootstrap-min', get_template_directory_uri() . '/assets/css/bootstrap.min.css', array(), null); wp_enqueue_style( 'bootstrap-theme', get_template_directory_uri() . '/assets/css/bootstrap-theme.min.css', array( 'bootstrap-min' ), null ); wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css'); } add_action('wp_enqueue_scripts', 'load_styles'); ``` Directory: [![Directory](https://i.stack.imgur.com/YfuBn.png)](https://i.stack.imgur.com/YfuBn.png)
use `wp_head();` before `</head>` in `header.php`
275,785
<p>I need to have a hidden custom field that will be automatically populated with the title of the post on save. My goal is to query posts by all its meta fields, including the title, but from my research I learned that it's not easily possible to combine title and meta_query.</p> <p>What should be the script for creating this hidden field as meta?</p>
[ { "answer_id": 275787, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": -1, "selected": false, "text": "<p>So you need hidden input field </p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"yourName\" value=\"yourValue\"/&gt; \n</code></pre>\n\n<p>After hitting submit button you will put this code</p>\n\n<pre><code>update_post_meta( $post_id, 'yourMeta_key', 'yourMeta_value' );\n</code></pre>\n\n<p>And wordpress will put this info in postmeta table\nwhen you want this data</p>\n\n<pre><code>get_post_meta( $post_id, 'yourMeta_key' );\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$productMeta = get_post_meta( $post_id );\n$productMeta['yourMeta_key'][0];\n</code></pre>\n\n<p>EDIT to get your data from hidden field use</p>\n\n<pre><code>$_POST['yourName']; // yourName is name of hidden input field\n</code></pre>\n" }, { "answer_id": 275792, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>This will automatically update a meta named <code>post_title</code> to the value of the post's title, no matter where you save the post from:</p>\n\n<pre><code>function wpse_275785_save_title_as_meta( $post_id, $post, $update ) {\n update_post_meta( $post_id, 'post_title', $post-&gt;post_title );\n}\nadd_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 );\n</code></pre>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125233/" ]
I need to have a hidden custom field that will be automatically populated with the title of the post on save. My goal is to query posts by all its meta fields, including the title, but from my research I learned that it's not easily possible to combine title and meta\_query. What should be the script for creating this hidden field as meta?
This will automatically update a meta named `post_title` to the value of the post's title, no matter where you save the post from: ``` function wpse_275785_save_title_as_meta( $post_id, $post, $update ) { update_post_meta( $post_id, 'post_title', $post->post_title ); } add_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 ); ```
275,788
<p>I want to create a filter in my functions.php theme to change the URL of $icon_html in this plugin function.</p> <pre><code>public function get_icon() { // paypal icon $icon_html = '&lt;img src="paypal.png" /&gt;'; return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this-&gt;get_id() ); } </code></pre> <p>How to perform this? $icon_html is not unique. </p> <p>Thank you, Thibault</p>
[ { "answer_id": 275787, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": -1, "selected": false, "text": "<p>So you need hidden input field </p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"yourName\" value=\"yourValue\"/&gt; \n</code></pre>\n\n<p>After hitting submit button you will put this code</p>\n\n<pre><code>update_post_meta( $post_id, 'yourMeta_key', 'yourMeta_value' );\n</code></pre>\n\n<p>And wordpress will put this info in postmeta table\nwhen you want this data</p>\n\n<pre><code>get_post_meta( $post_id, 'yourMeta_key' );\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$productMeta = get_post_meta( $post_id );\n$productMeta['yourMeta_key'][0];\n</code></pre>\n\n<p>EDIT to get your data from hidden field use</p>\n\n<pre><code>$_POST['yourName']; // yourName is name of hidden input field\n</code></pre>\n" }, { "answer_id": 275792, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>This will automatically update a meta named <code>post_title</code> to the value of the post's title, no matter where you save the post from:</p>\n\n<pre><code>function wpse_275785_save_title_as_meta( $post_id, $post, $update ) {\n update_post_meta( $post_id, 'post_title', $post-&gt;post_title );\n}\nadd_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 );\n</code></pre>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275788", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113942/" ]
I want to create a filter in my functions.php theme to change the URL of $icon\_html in this plugin function. ``` public function get_icon() { // paypal icon $icon_html = '<img src="paypal.png" />'; return apply_filters( 'woocommerce_gateway_icon', $icon_html, $this->get_id() ); } ``` How to perform this? $icon\_html is not unique. Thank you, Thibault
This will automatically update a meta named `post_title` to the value of the post's title, no matter where you save the post from: ``` function wpse_275785_save_title_as_meta( $post_id, $post, $update ) { update_post_meta( $post_id, 'post_title', $post->post_title ); } add_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 ); ```
275,800
<p>I recently migrated my old website to this domain: <a href="https://thequintessentialmind.com/" rel="nofollow noreferrer">https://thequintessentialmind.com/</a></p> <p>The ssl works fine but in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https. </p> <p><a href="https://i.stack.imgur.com/AWuKs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AWuKs.png" alt="enter image description here"></a></p> <p>I have difficulty locating that part of the code in any of the php files. Any ideas where could it be?</p>
[ { "answer_id": 275787, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": -1, "selected": false, "text": "<p>So you need hidden input field </p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"yourName\" value=\"yourValue\"/&gt; \n</code></pre>\n\n<p>After hitting submit button you will put this code</p>\n\n<pre><code>update_post_meta( $post_id, 'yourMeta_key', 'yourMeta_value' );\n</code></pre>\n\n<p>And wordpress will put this info in postmeta table\nwhen you want this data</p>\n\n<pre><code>get_post_meta( $post_id, 'yourMeta_key' );\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$productMeta = get_post_meta( $post_id );\n$productMeta['yourMeta_key'][0];\n</code></pre>\n\n<p>EDIT to get your data from hidden field use</p>\n\n<pre><code>$_POST['yourName']; // yourName is name of hidden input field\n</code></pre>\n" }, { "answer_id": 275792, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>This will automatically update a meta named <code>post_title</code> to the value of the post's title, no matter where you save the post from:</p>\n\n<pre><code>function wpse_275785_save_title_as_meta( $post_id, $post, $update ) {\n update_post_meta( $post_id, 'post_title', $post-&gt;post_title );\n}\nadd_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 );\n</code></pre>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111649/" ]
I recently migrated my old website to this domain: <https://thequintessentialmind.com/> The ssl works fine but in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https. [![enter image description here](https://i.stack.imgur.com/AWuKs.png)](https://i.stack.imgur.com/AWuKs.png) I have difficulty locating that part of the code in any of the php files. Any ideas where could it be?
This will automatically update a meta named `post_title` to the value of the post's title, no matter where you save the post from: ``` function wpse_275785_save_title_as_meta( $post_id, $post, $update ) { update_post_meta( $post_id, 'post_title', $post->post_title ); } add_action( 'save_post', 'wpse_275785_save_title_as_meta', 99, 3 ); ```
275,822
<p>I have uploaded an image that is 2100px wide into a post, and inserted that image in the post body. I'm building a custom theme based on Wordpress' Twenty Sixteen.</p> <p>The HTML looks OK:</p> <pre><code>&lt;img class="alignnone wp-image-2669 size-full" src="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg" alt="" width="2100" height="904" /&gt; </code></pre> <p>in the frontend, Wordpress does what I assume is its "responsive image" magic (I don't think I have added any plugins that would do this:)</p> <pre><code>&lt;img class="alignnone wp-image-2669 size-full" src="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg" alt="" width="2100" height="904" srcset="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg 2100w, http://.../wp-content/uploads/2017/07/GrillSommer1-300x129.jpg 300w, http://.../wp-content/uploads/2017/07/GrillSommer1-768x331.jpg 768w, http://.../wp-content/uploads/2017/07/GrillSommer1-1024x441.jpg 1024w, http://.../wp-content/uploads/2017/07/GrillSommer1-340x146.jpg 340w, http://.../wp-content/uploads/2017/07/GrillSommer1-500x215.jpg 500w, http://.../wp-content/uploads/2017/07/GrillSommer1-1200x517.jpg 1200w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /&gt; </code></pre> <p>If I'm reading the <code>srcset</code> information right, it should be serving </p> <p>I don't have a problem with that in principle - but on a 1920x1080 screen, I am being served the 1024px version, which of course looks incredibly blurry! </p> <p>Is there an obvious reason why this happens? </p>
[ { "answer_id": 275823, "author": "Rei", "author_id": 109614, "author_profile": "https://wordpress.stackexchange.com/users/109614", "pm_score": 0, "selected": false, "text": "<p>You can check tab <strong>media setting</strong> in wordpress<a href=\"https://i.stack.imgur.com/VFxgU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VFxgU.png\" alt=\"https://codex.wordpress.org/images/thumb/4/43/options-media.png/600px-options-media.png\"></a></p>\n" }, { "answer_id": 275890, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>Your image's src is pointing to the full size image, so it's not an issue of permalink. The issue happens because of the <code>sizes</code> values. There is a variable that determines the width of your content, which then later WordPress uses to generates the responsive sizes for your images. </p>\n\n<p>This global variable can be set manually in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>if( !isset($content_width) ) {\n $content_width = 1920;\n}\n</code></pre>\n\n<p>You can tweak with this variable to achieve your desired result.</p>\n" }, { "answer_id": 275894, "author": "Pekka", "author_id": 2161, "author_profile": "https://wordpress.stackexchange.com/users/2161", "pm_score": 1, "selected": false, "text": "<p>The problem seems to be specific to the Twenty Sixteen theme, whose content area I suppose is limited to a maximum width of 840 pixels. The theme adds rules for responsive images in its <code>functions.php</code>, in the <code>twentysixteen_content_image_sizes_attr()</code> function.</p>\n\n<pre><code>function twentysixteen_content_image_sizes_attr( $sizes, $size ) {\n\n $width = $size[0];\n\n 1200 &lt;= $width &amp;&amp; $sizes = '(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 1200px';\n\n if ( 'page' === get_post_type() ) {\n 1200 &gt; $width &amp;&amp; $sizes = '(max-width: ' . $width . 'px) 85vw, ' . $width . 'px';\n } else {\n 1200 &gt; $width &amp;&amp; 600 &lt;= $width &amp;&amp; $sizes = '(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px';\n 600 &gt; $width &amp;&amp; $sizes = '(max-width: ' . $width . 'px) 85vw, ' . $width . 'px';\n }\n\n return $sizes;\n}\nadd_filter( 'wp_calculate_image_sizes', 'twentysixteen_content_image_sizes_attr', 10 , 2 );\n</code></pre>\n\n<p>I'm honestly not quite sure how to adjust this to support a larger content width, or rather in my case, an image that is always 100% wide, so I'm disabling this for the time being. </p>\n\n<p>For production, it's probably smart to look into this in more detail, though - serving smaller images to smaller-screen devices is certainly a good idea.</p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2161/" ]
I have uploaded an image that is 2100px wide into a post, and inserted that image in the post body. I'm building a custom theme based on Wordpress' Twenty Sixteen. The HTML looks OK: ``` <img class="alignnone wp-image-2669 size-full" src="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg" alt="" width="2100" height="904" /> ``` in the frontend, Wordpress does what I assume is its "responsive image" magic (I don't think I have added any plugins that would do this:) ``` <img class="alignnone wp-image-2669 size-full" src="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg" alt="" width="2100" height="904" srcset="http://.../wp-content/uploads/2017/07/GrillSommer1.jpg 2100w, http://.../wp-content/uploads/2017/07/GrillSommer1-300x129.jpg 300w, http://.../wp-content/uploads/2017/07/GrillSommer1-768x331.jpg 768w, http://.../wp-content/uploads/2017/07/GrillSommer1-1024x441.jpg 1024w, http://.../wp-content/uploads/2017/07/GrillSommer1-340x146.jpg 340w, http://.../wp-content/uploads/2017/07/GrillSommer1-500x215.jpg 500w, http://.../wp-content/uploads/2017/07/GrillSommer1-1200x517.jpg 1200w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /> ``` If I'm reading the `srcset` information right, it should be serving I don't have a problem with that in principle - but on a 1920x1080 screen, I am being served the 1024px version, which of course looks incredibly blurry! Is there an obvious reason why this happens?
Your image's src is pointing to the full size image, so it's not an issue of permalink. The issue happens because of the `sizes` values. There is a variable that determines the width of your content, which then later WordPress uses to generates the responsive sizes for your images. This global variable can be set manually in your theme's `functions.php` file: ``` if( !isset($content_width) ) { $content_width = 1920; } ``` You can tweak with this variable to achieve your desired result.
275,838
<p>Trying to: </p> <p>Submit form using admin-ajax.php to update post data from 'draft' status to 'publish' status and add custom meta field for filter type.</p> <p>Form contents:</p> <pre><code>&lt;form action="&lt;?php echo admin_url( 'admin-ajax.php' ) ?&gt;" method="post"&gt; &lt;?php wp_nonce_field( 'submit_filter', 'my_filter_nonce' ); ?&gt; &lt;div class="small-6 medium-3 large-3 columns"&gt; &lt;div class="card"&gt; &lt;img src="&lt;?php echo get_the_post_thumbnail_url( $posts[0]-&gt;ID, 'thumbnail' ); ?&gt;" class="" id="normal"&gt; &lt;div class="card-section"&gt; &lt;input type="submit" value="No Filter" name="normal"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Form action:</p> <pre><code>// process form actions add_action( 'wp_ajax_nopriv_submit_filter', 'my_submission_filter' ); add_action( 'wp_ajax_submit_filter', 'my_submission_filter' ); function my_submission_filter() { $postid = get_the_ID(); $post_data = array( 'ID' =&gt; $postid, 'post_status' =&gt; 'publish' ); // add filter meta data add_post_meta($postid, 'filter', $_POST['filter']); // Update the post into the database wp_update_post( $my_post ); // redirect back to site to see post wp_redirect( site_url()); die(); } </code></pre> <p>Results:</p> <p>Blank page with a "0" in the top right corner and no updates to post.</p> <p>Would like:</p> <p>Help making this work :)</p>
[ { "answer_id": 275823, "author": "Rei", "author_id": 109614, "author_profile": "https://wordpress.stackexchange.com/users/109614", "pm_score": 0, "selected": false, "text": "<p>You can check tab <strong>media setting</strong> in wordpress<a href=\"https://i.stack.imgur.com/VFxgU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VFxgU.png\" alt=\"https://codex.wordpress.org/images/thumb/4/43/options-media.png/600px-options-media.png\"></a></p>\n" }, { "answer_id": 275890, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>Your image's src is pointing to the full size image, so it's not an issue of permalink. The issue happens because of the <code>sizes</code> values. There is a variable that determines the width of your content, which then later WordPress uses to generates the responsive sizes for your images. </p>\n\n<p>This global variable can be set manually in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>if( !isset($content_width) ) {\n $content_width = 1920;\n}\n</code></pre>\n\n<p>You can tweak with this variable to achieve your desired result.</p>\n" }, { "answer_id": 275894, "author": "Pekka", "author_id": 2161, "author_profile": "https://wordpress.stackexchange.com/users/2161", "pm_score": 1, "selected": false, "text": "<p>The problem seems to be specific to the Twenty Sixteen theme, whose content area I suppose is limited to a maximum width of 840 pixels. The theme adds rules for responsive images in its <code>functions.php</code>, in the <code>twentysixteen_content_image_sizes_attr()</code> function.</p>\n\n<pre><code>function twentysixteen_content_image_sizes_attr( $sizes, $size ) {\n\n $width = $size[0];\n\n 1200 &lt;= $width &amp;&amp; $sizes = '(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 1200px';\n\n if ( 'page' === get_post_type() ) {\n 1200 &gt; $width &amp;&amp; $sizes = '(max-width: ' . $width . 'px) 85vw, ' . $width . 'px';\n } else {\n 1200 &gt; $width &amp;&amp; 600 &lt;= $width &amp;&amp; $sizes = '(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px';\n 600 &gt; $width &amp;&amp; $sizes = '(max-width: ' . $width . 'px) 85vw, ' . $width . 'px';\n }\n\n return $sizes;\n}\nadd_filter( 'wp_calculate_image_sizes', 'twentysixteen_content_image_sizes_attr', 10 , 2 );\n</code></pre>\n\n<p>I'm honestly not quite sure how to adjust this to support a larger content width, or rather in my case, an image that is always 100% wide, so I'm disabling this for the time being. </p>\n\n<p>For production, it's probably smart to look into this in more detail, though - serving smaller images to smaller-screen devices is certainly a good idea.</p>\n" } ]
2017/08/04
[ "https://wordpress.stackexchange.com/questions/275838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125259/" ]
Trying to: Submit form using admin-ajax.php to update post data from 'draft' status to 'publish' status and add custom meta field for filter type. Form contents: ``` <form action="<?php echo admin_url( 'admin-ajax.php' ) ?>" method="post"> <?php wp_nonce_field( 'submit_filter', 'my_filter_nonce' ); ?> <div class="small-6 medium-3 large-3 columns"> <div class="card"> <img src="<?php echo get_the_post_thumbnail_url( $posts[0]->ID, 'thumbnail' ); ?>" class="" id="normal"> <div class="card-section"> <input type="submit" value="No Filter" name="normal"> </div> </div> </div> </form> ``` Form action: ``` // process form actions add_action( 'wp_ajax_nopriv_submit_filter', 'my_submission_filter' ); add_action( 'wp_ajax_submit_filter', 'my_submission_filter' ); function my_submission_filter() { $postid = get_the_ID(); $post_data = array( 'ID' => $postid, 'post_status' => 'publish' ); // add filter meta data add_post_meta($postid, 'filter', $_POST['filter']); // Update the post into the database wp_update_post( $my_post ); // redirect back to site to see post wp_redirect( site_url()); die(); } ``` Results: Blank page with a "0" in the top right corner and no updates to post. Would like: Help making this work :)
Your image's src is pointing to the full size image, so it's not an issue of permalink. The issue happens because of the `sizes` values. There is a variable that determines the width of your content, which then later WordPress uses to generates the responsive sizes for your images. This global variable can be set manually in your theme's `functions.php` file: ``` if( !isset($content_width) ) { $content_width = 1920; } ``` You can tweak with this variable to achieve your desired result.
275,859
<p>I have the following code in my main plugin file</p> <pre><code>&lt;?php include plugin_dir_path( __FILE__) . 'options.php'; include plugin_dir_path( __FILE__ ) . 'config.php'; include plugin_dir_path( __FILE__ ) . 'front/manage.php'; add_action( 'admin_init', 'restrict_admin', 1 ); //prepare wordpress for ajax this needs to be done early to avoid strange race conditions add_action( 'wp_ajax_devices', 'api_list_devices' ); add_action( 'wp_ajax_profiles', 'api_list_profiles' ); add_action( 'wp_ajax_held_accounts', 'api_list_held_accounts' ); add_action( 'wp_ajax_set_profile', 'api_set_profiles' ); define('AJAX_NONCE_NAME',"title_example"); //... </code></pre> <p>I assume since adding an action just lets admin-ajax.php know it should run some action at some point later, my includes aren't even executed, but I need them to authenticate the database connection. How can I tell wordpress to do my includes for parts of wordpress like this that are beyond my control? Do I have to enqueue, all the enqueueing examples seem to apply to the front end?</p>
[ { "answer_id": 275861, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 1, "selected": false, "text": "<p>\"...I need them to authenticate the database connection.\" </p>\n\n<p>Not exactly sure this is what you want, but in your ajax function you can connect to and use a database if you <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">declare the global variable $wpdb</a>.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code>function api_list_devices() {\n global $wpdb;\n\n $name = $_POST['name']; // ajax call sends \"name\"\n\n // try to insert $name into \"people\" tables \"name\" column\n if($wpdb-&gt;insert('people',array(\n 'name'=&gt;$name \n ))===FALSE){\n echo \"Error\";\n }\n else {\n echo \"Person '\".$name. \"' has been successfully added;\n }\n}\n</code></pre>\n" }, { "answer_id": 275866, "author": "awiebe", "author_id": 125273, "author_profile": "https://wordpress.stackexchange.com/users/125273", "pm_score": -1, "selected": false, "text": "<p>I wound up doing the following:</p>\n\n<ol>\n<li>prepending a function to each of my ajax actions that loads a file\nfull of defines</li>\n<li>left my database connection functions in the main\nplugin files since php includes are scoped to the function in which\nthey occurred(but define values are global)</li>\n</ol>\n\n<p>If anyone reading this happens to need an object, do step one but use the <strong>global</strong> keyword to assign the loaded object to the global namespace so it isn't lost when your dependency loading function is done, then simply refer to the global instance of your object.</p>\n\n<p>If a wordpress dev happens to be reading this, there should be a hook for loading dependencies before ajax happens, you can use reflection to make this transparent.</p>\n\n<ol>\n<li>Instruct plugin developer to check referer nonce to guard against malicious plugins.</li>\n<li><p>Use reflection to load handlers scope into caller scope see:\n<a href=\"https://stackoverflow.com/questions/2211877/giving-php-included-files-parent-variable-scope\">https://stackoverflow.com/questions/2211877/giving-php-included-files-parent-variable-scope</a></p></li>\n<li><p>Call ajax action handler as usual.</p></li>\n</ol>\n" } ]
2017/08/05
[ "https://wordpress.stackexchange.com/questions/275859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125273/" ]
I have the following code in my main plugin file ``` <?php include plugin_dir_path( __FILE__) . 'options.php'; include plugin_dir_path( __FILE__ ) . 'config.php'; include plugin_dir_path( __FILE__ ) . 'front/manage.php'; add_action( 'admin_init', 'restrict_admin', 1 ); //prepare wordpress for ajax this needs to be done early to avoid strange race conditions add_action( 'wp_ajax_devices', 'api_list_devices' ); add_action( 'wp_ajax_profiles', 'api_list_profiles' ); add_action( 'wp_ajax_held_accounts', 'api_list_held_accounts' ); add_action( 'wp_ajax_set_profile', 'api_set_profiles' ); define('AJAX_NONCE_NAME',"title_example"); //... ``` I assume since adding an action just lets admin-ajax.php know it should run some action at some point later, my includes aren't even executed, but I need them to authenticate the database connection. How can I tell wordpress to do my includes for parts of wordpress like this that are beyond my control? Do I have to enqueue, all the enqueueing examples seem to apply to the front end?
"...I need them to authenticate the database connection." Not exactly sure this is what you want, but in your ajax function you can connect to and use a database if you [declare the global variable $wpdb](https://codex.wordpress.org/Class_Reference/wpdb). Here's a simple example: ``` function api_list_devices() { global $wpdb; $name = $_POST['name']; // ajax call sends "name" // try to insert $name into "people" tables "name" column if($wpdb->insert('people',array( 'name'=>$name ))===FALSE){ echo "Error"; } else { echo "Person '".$name. "' has been successfully added; } } ```
275,907
<p>I've created a plugin using various classes. I want to be able to access the methods on several of the different classes from within the page templates of my custom theme. The method I'm currently using is to make static methods but I'm wondering if this is the best way to do it?</p> <p>An example could be a class with a method that checks whether the user is logged in and what their user role is. Let's call the class <code>Plugin_Access</code> and the method <code>has_access()</code>;</p> <p>Now let's say I need to customize content in the header, page template and footer using if() statements based on <code>has_access()</code>. To do this I would use <code>if( Plugin_Access::has_access() )</code>. To me I feel like this isn't the cleanest solution. I'm essentially calling the same method and getting the same result 3 times. If it had a call to the database within the method, this would be 3 calls rather than 1.</p> <p>One solution I thought of was to make the class a <code>singleton</code> and to store the result of the function in a variable within the class. Then the method would check this variable and if it's <code>null</code>, then complete the rest of the method, otherwise just return the stored variable.</p> <p>I feel like I'm definitely missing something. Thanks in advanced for any advice.</p>
[ { "answer_id": 275861, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 1, "selected": false, "text": "<p>\"...I need them to authenticate the database connection.\" </p>\n\n<p>Not exactly sure this is what you want, but in your ajax function you can connect to and use a database if you <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">declare the global variable $wpdb</a>.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code>function api_list_devices() {\n global $wpdb;\n\n $name = $_POST['name']; // ajax call sends \"name\"\n\n // try to insert $name into \"people\" tables \"name\" column\n if($wpdb-&gt;insert('people',array(\n 'name'=&gt;$name \n ))===FALSE){\n echo \"Error\";\n }\n else {\n echo \"Person '\".$name. \"' has been successfully added;\n }\n}\n</code></pre>\n" }, { "answer_id": 275866, "author": "awiebe", "author_id": 125273, "author_profile": "https://wordpress.stackexchange.com/users/125273", "pm_score": -1, "selected": false, "text": "<p>I wound up doing the following:</p>\n\n<ol>\n<li>prepending a function to each of my ajax actions that loads a file\nfull of defines</li>\n<li>left my database connection functions in the main\nplugin files since php includes are scoped to the function in which\nthey occurred(but define values are global)</li>\n</ol>\n\n<p>If anyone reading this happens to need an object, do step one but use the <strong>global</strong> keyword to assign the loaded object to the global namespace so it isn't lost when your dependency loading function is done, then simply refer to the global instance of your object.</p>\n\n<p>If a wordpress dev happens to be reading this, there should be a hook for loading dependencies before ajax happens, you can use reflection to make this transparent.</p>\n\n<ol>\n<li>Instruct plugin developer to check referer nonce to guard against malicious plugins.</li>\n<li><p>Use reflection to load handlers scope into caller scope see:\n<a href=\"https://stackoverflow.com/questions/2211877/giving-php-included-files-parent-variable-scope\">https://stackoverflow.com/questions/2211877/giving-php-included-files-parent-variable-scope</a></p></li>\n<li><p>Call ajax action handler as usual.</p></li>\n</ol>\n" } ]
2017/08/05
[ "https://wordpress.stackexchange.com/questions/275907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125295/" ]
I've created a plugin using various classes. I want to be able to access the methods on several of the different classes from within the page templates of my custom theme. The method I'm currently using is to make static methods but I'm wondering if this is the best way to do it? An example could be a class with a method that checks whether the user is logged in and what their user role is. Let's call the class `Plugin_Access` and the method `has_access()`; Now let's say I need to customize content in the header, page template and footer using if() statements based on `has_access()`. To do this I would use `if( Plugin_Access::has_access() )`. To me I feel like this isn't the cleanest solution. I'm essentially calling the same method and getting the same result 3 times. If it had a call to the database within the method, this would be 3 calls rather than 1. One solution I thought of was to make the class a `singleton` and to store the result of the function in a variable within the class. Then the method would check this variable and if it's `null`, then complete the rest of the method, otherwise just return the stored variable. I feel like I'm definitely missing something. Thanks in advanced for any advice.
"...I need them to authenticate the database connection." Not exactly sure this is what you want, but in your ajax function you can connect to and use a database if you [declare the global variable $wpdb](https://codex.wordpress.org/Class_Reference/wpdb). Here's a simple example: ``` function api_list_devices() { global $wpdb; $name = $_POST['name']; // ajax call sends "name" // try to insert $name into "people" tables "name" column if($wpdb->insert('people',array( 'name'=>$name ))===FALSE){ echo "Error"; } else { echo "Person '".$name. "' has been successfully added; } } ```
275,917
<p>I am using load to enqueue scripts only on my plugin page.</p> <p><a href="https://developer.wordpress.org/reference/hooks/load-page_hook/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/hooks/load-page_hook/</a></p> <pre><code>add_action("admin_menu", "sap_admin_menu"); function sap_admin_menu(){ $menu = add_menu_page("Sticky Audio Player Player manager", "Sticky Audio Player", "manage_options", "sap_player_manager", "sap_player_manager_page", 'dashicons-playlist-audio'); $submenu = add_submenu_page("sap_player_manager", "Sticky Audio Player Player manager", "Player manager", "manage_options", 'sap_player_manager', "sap_player_manager_page"); $submenu2 = add_submenu_page("sap_player_manager", "Sticky Audio Player Playlist manager", "Playlist manager", "manage_options", 'sap_playlist_manager', 'sap_playlist_manager_page'); add_action( 'load-' . $menu, 'sap_admin_enqueue_scripts' ); add_action( 'load-' . $submenu, 'sap_admin_enqueue_scripts' ); add_action( 'load-' . $submenu2, 'sap_admin_enqueue_scripts' ); } </code></pre> <p>This works well, however I would like to know how to detect on which page I am currently so I can enqueue different scripts in sap_admin_enqueue_scripts function:</p> <pre><code>function sap_admin_enqueue_scripts() { //I need to detect page here if ( is_page( 'sap_player_manager' ) ) {//this doesnt work } </code></pre> <p>I tried using is_page but I cant make it work.</p>
[ { "answer_id": 275921, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 1, "selected": false, "text": "<p>What about <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow noreferrer\"><code>get_current_screen()</code></a>?</p>\n\n<pre><code>$screen = get_current_screen();\n\nif ( 'sap_player_manager' === $screen-&gt;id ) {\n\n}\n</code></pre>\n" }, { "answer_id": 275922, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>look into <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow noreferrer\"><code>get_current_screen();</code></a></p>\n\n<p>Some notes from codex:</p>\n\n<blockquote>\n <p>This function is defined on most admin pages, but not all. Thus there are cases where <code>is_admin()</code> will return true, but attempting to call <code>get_current_screen()</code> will result in a fatal error because it is not defined. One known example is wp-admin/customize.php.</p>\n</blockquote>\n\n<p>There is also a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/current_screen\" rel=\"nofollow noreferrer\"><code>current_screen</code></a> hook for a different approach.</p>\n\n<p>Both make available a <code>WP_Screen</code>. in example:</p>\n\n<pre><code>WP_Screen Object {\n [\"action\"] =&gt; string(0) \"\"\n [\"base\"] =&gt; string(4) \"post\"\n [\"columns\":\"WP_Screen\":private] =&gt; int(0)\n [\"id\"] =&gt; string(12) \"someposttype\"\n [\"in_admin\":protected] =&gt; string(4) \"site\"\n [\"is_network\"] =&gt; bool(false)\n [\"is_user\"] =&gt; bool(false)\n [\"parent_base\"] =&gt; NULL\n [\"parent_file\"] =&gt; NULL\n [\"post_type\"] =&gt; string(12) \"someposttype\"\n [\"taxonomy\"] =&gt; string(0) \"\"\n [\"_help_tabs\":\"WP_Screen\":private] =&gt; array(0) { }\n [\"_help_sidebar\":\"WP_Screen\":private] =&gt; string(0) \"\"\n [\"_options\":\"WP_Screen\":private] =&gt; array(0) { }\n [\"_show_screen_options\":\"WP_Screen\":private] =&gt; NULL\n [\"_screen_settings\":\"WP_Screen\":private] =&gt; NULL\n}\n</code></pre>\n" }, { "answer_id": 275923, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 2, "selected": false, "text": "<p>You can do something like this </p>\n\n<pre><code>add_action( 'admin_menu', 'my_admin_menus' ); \n\nfunction my_admin_menus() {\n $GLOBALS['my_page'] = add_menu_page( 'Page Title', 'Menu Title', \n MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content');\n}\n\nadd_action( 'admin_enqueue_scripts', 'enqueue_admin_js');\n\nfunction enqueue_admin_js($hook) {\n if($GLOBALS['my_page'] === $hook) {\n wp_enqueue_script( 'jquery-ui-core' );\n wp_enqueue_script( 'jquery-ui-tabs' );\n // Isn't it nice to use dependencies and the already registered core js files?\n wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) );\n }\n}\n</code></pre>\n" } ]
2017/08/05
[ "https://wordpress.stackexchange.com/questions/275917", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45321/" ]
I am using load to enqueue scripts only on my plugin page. <https://developer.wordpress.org/reference/hooks/load-page_hook/> ``` add_action("admin_menu", "sap_admin_menu"); function sap_admin_menu(){ $menu = add_menu_page("Sticky Audio Player Player manager", "Sticky Audio Player", "manage_options", "sap_player_manager", "sap_player_manager_page", 'dashicons-playlist-audio'); $submenu = add_submenu_page("sap_player_manager", "Sticky Audio Player Player manager", "Player manager", "manage_options", 'sap_player_manager', "sap_player_manager_page"); $submenu2 = add_submenu_page("sap_player_manager", "Sticky Audio Player Playlist manager", "Playlist manager", "manage_options", 'sap_playlist_manager', 'sap_playlist_manager_page'); add_action( 'load-' . $menu, 'sap_admin_enqueue_scripts' ); add_action( 'load-' . $submenu, 'sap_admin_enqueue_scripts' ); add_action( 'load-' . $submenu2, 'sap_admin_enqueue_scripts' ); } ``` This works well, however I would like to know how to detect on which page I am currently so I can enqueue different scripts in sap\_admin\_enqueue\_scripts function: ``` function sap_admin_enqueue_scripts() { //I need to detect page here if ( is_page( 'sap_player_manager' ) ) {//this doesnt work } ``` I tried using is\_page but I cant make it work.
You can do something like this ``` add_action( 'admin_menu', 'my_admin_menus' ); function my_admin_menus() { $GLOBALS['my_page'] = add_menu_page( 'Page Title', 'Menu Title', MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content'); } add_action( 'admin_enqueue_scripts', 'enqueue_admin_js'); function enqueue_admin_js($hook) { if($GLOBALS['my_page'] === $hook) { wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-tabs' ); // Isn't it nice to use dependencies and the already registered core js files? wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) ); } } ```
275,930
<p>I just upgraded to PHP 7 only to find that WordPress 4.8.1 (latest version) still uses mysql_connect in the wp-db.php module, but mysql_connect has been deprecated.</p> <p>The following code is taken from wp-db-php, lines 1567-1571:</p> <pre><code>if ( WP_DEBUG ) { $this-&gt;dbh = mysql_connect( $this-&gt;dbhost, $this-&gt;dbuser, $this-&gt;dbpassword, $new_link, $client_flags ); } else { $this-&gt;dbh = @mysql_connect( $this-&gt;dbhost, $this-&gt;dbuser, $this&gt;dbpassword, $new_link, $client_flags); } </code></pre> <p>Here is the output when I try to run my program:</p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function mysql_connect() in D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php:1570 <br/> Stack trace: <br/> #0 D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php(658): wpdb->db_connect() <br/> #1 D:\ApacheHtdocs\ConneXions\wp-includes\load.php(404): wpdb->__construct('root', '', 'connexions', 'localhost') <br/> #2 D:\ApacheHtdocs\ConneXions\wp-settings.php(106): require_wp_db() <br/> #3 D:\ApacheHtdocs\ConneXions\wp-config.php(104): require_once('D:\ApacheHtdocs...') <br/> #4 D:\ApacheHtdocs\ConneXions\wp-load.php(37): require_once('D:\ApacheHtdocs...') <br/> #5 D:\ApacheHtdocs\ConneXions\wp-blog-header.php(13): require_once('D:\ApacheHtdocs...') <br/> #6 D:\ApacheHtdocs\ConneXions\index.php(17): require('D:\ApacheHtdocs...') <br/> #7 {main} thrown in D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php on line 1570</p> </blockquote> <p>I can't believe that WordPress says it recommends PHP 7, but it doesn't work with it. What am I missing here?</p>
[ { "answer_id": 275932, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": false, "text": "<p>This sounds like you do not have <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"noreferrer\">mysqli</a> installed and/or enabled on your server. IIRC <code>mysqli</code> was added to php in version 5.5, and the older <code>mysql</code> extension had been deprecated and fully retired since then. If you upgraded from a very old PHP version it might be that you still need the extra step of enabling <code>mysqli</code>.</p>\n\n<p>(wordpress checks for the existence of <code>mysqli</code> and only if it does not exist tries the older <code>mysql</code> functions.)</p>\n" }, { "answer_id": 275933, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>In addition to @MarkKaplun answer, I post some code from the wpdb class:</p>\n\n<p>Here's how the <code>wpdb::use_mysqli</code> is determined:</p>\n\n<p>It's initalized with:</p>\n\n<pre><code>/**\n * Whether to use mysqli over mysql.\n *\n * @since 3.9.0\n * @access private\n * @var bool\n */\nprivate $use_mysqli = false;\n</code></pre>\n\n<p>and then in the <code>wpdb</code> constructor we have:</p>\n\n<pre><code>/* Use ext/mysqli if it exists and:\n * - WP_USE_EXT_MYSQL is defined as false, or\n * - We are a development version of WordPress, or\n * - We are running PHP 5.5 or greater, or\n * - ext/mysql is not loaded.\n */\nif ( function_exists( 'mysqli_connect' ) ) {\n if ( defined( 'WP_USE_EXT_MYSQL' ) ) {\n $this-&gt;use_mysqli = ! WP_USE_EXT_MYSQL;\n } elseif ( version_compare( phpversion(), '5.5', '&gt;=' ) || ! function_exists( 'mysql_connect' ) ) {\n $this-&gt;use_mysqli = true;\n } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {\n $this-&gt;use_mysqli = true;\n }\n}\n</code></pre>\n" }, { "answer_id": 286088, "author": "Lawrence Oputa", "author_id": 113156, "author_profile": "https://wordpress.stackexchange.com/users/113156", "pm_score": 2, "selected": false, "text": "<p>What you should do to solve this problem, is to edit your php.ini file. </p>\n\n<p>run where is <code>php.ini</code>\nI found mine at:</p>\n\n<p><code>/etc/php/php.ini</code> (although I don't know what OS you are running simple find yours)</p>\n\n<p>Look for these two files:</p>\n\n<pre><code>extension=pdo_mysql.so\nextension=mysqli.so\n</code></pre>\n\n<p>and uncomment them. \nVoila, that would get the job done anytime.</p>\n\n<p>Further reading:\n<a href=\"https://wiki.archlinux.org/index.php/PHP\" rel=\"nofollow noreferrer\">https://wiki.archlinux.org/index.php/PHP</a></p>\n" }, { "answer_id": 296133, "author": "aldemarcalazans", "author_id": 116658, "author_profile": "https://wordpress.stackexchange.com/users/116658", "pm_score": 2, "selected": false, "text": "<p>Are you using Xamppp 7.x for Windows?</p>\n\n<p>It happened to me when I upgraded my Xampp 5.6 to Xampp 7.1. Inspecting the configuration file <strong>C:\\Xampp\\php\\php.ini</strong>, I noticed a lot of errors involving the name of PHP extensions (they lack the prefix php_ and the suffix .dll). One of them is related to mysqli.</p>\n\n<p>The wrong setting I found there:</p>\n\n<pre><code>extension=mysqli\n</code></pre>\n\n<p>The right setting (after editing this line):</p>\n\n<pre><code>extension=php_mysqli.dll\n</code></pre>\n\n<p>Correcting that solved my problem.</p>\n\n<p>By the way: don't forget to correct all other wrong settings (the correct name of the extensions can be seen at C:\\xampp\\php\\ext).</p>\n" } ]
2017/08/05
[ "https://wordpress.stackexchange.com/questions/275930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44926/" ]
I just upgraded to PHP 7 only to find that WordPress 4.8.1 (latest version) still uses mysql\_connect in the wp-db.php module, but mysql\_connect has been deprecated. The following code is taken from wp-db-php, lines 1567-1571: ``` if ( WP_DEBUG ) { $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); } else { $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this>dbpassword, $new_link, $client_flags); } ``` Here is the output when I try to run my program: > > Fatal error: Uncaught Error: Call to undefined function mysql\_connect() in D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php:1570 > > Stack trace: > > #0 D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php(658): wpdb->db\_connect() > > #1 D:\ApacheHtdocs\ConneXions\wp-includes\load.php(404): wpdb->\_\_construct('root', '', 'connexions', 'localhost') > > #2 D:\ApacheHtdocs\ConneXions\wp-settings.php(106): require\_wp\_db() > > #3 D:\ApacheHtdocs\ConneXions\wp-config.php(104): require\_once('D:\ApacheHtdocs...') > > #4 D:\ApacheHtdocs\ConneXions\wp-load.php(37): require\_once('D:\ApacheHtdocs...') > > #5 D:\ApacheHtdocs\ConneXions\wp-blog-header.php(13): require\_once('D:\ApacheHtdocs...') > > #6 D:\ApacheHtdocs\ConneXions\index.php(17): require('D:\ApacheHtdocs...') > > #7 {main} thrown in D:\ApacheHtdocs\ConneXions\wp-includes\wp-db.php on line 1570 > > > I can't believe that WordPress says it recommends PHP 7, but it doesn't work with it. What am I missing here?
This sounds like you do not have [mysqli](http://php.net/manual/en/book.mysqli.php) installed and/or enabled on your server. IIRC `mysqli` was added to php in version 5.5, and the older `mysql` extension had been deprecated and fully retired since then. If you upgraded from a very old PHP version it might be that you still need the extra step of enabling `mysqli`. (wordpress checks for the existence of `mysqli` and only if it does not exist tries the older `mysql` functions.)
275,977
<p>By default in the admin the Excerpt is hidden. See below.</p> <p><a href="https://i.stack.imgur.com/XnUPZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XnUPZ.png" alt="By default in the admin the Excerpt is hidden"></a></p> <p>I would like to make it show up by default.</p>
[ { "answer_id": 275985, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>The names of unchecked boxes in <code>Screen Options</code> for <code>Edit Post</code> screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_edit_post_show_excerpt( $user_login, $user ) {\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );\n</code></pre>\n\n<p>This will update user's meta ( after successful login ) by removing <code>postexcerpt</code> name from the array of unchecked boxes names.</p>\n\n<p><strong>Note</strong>: to avoid losing your change, create a child theme and put the code into its <code>functions.php</code>.</p>\n" }, { "answer_id": 281317, "author": "Dedering", "author_id": 128642, "author_profile": "https://wordpress.stackexchange.com/users/128642", "pm_score": 2, "selected": false, "text": "<p>Sharing a slight modification of Franks' solution. In my case, I don't want users to ever hide the excerpt so I've hooked the function to the <code>admin_init</code> instead of <code>wp_login</code>. </p>\n\n<p>Frank's function executes when the user logs into the site which means that once the user is logged in they can hide it again. This solution will fire every time an admin page is loaded which wilmake it impossible for the user to hide the field. </p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n</code></pre>\n" }, { "answer_id": 286576, "author": "David", "author_id": 131877, "author_profile": "https://wordpress.stackexchange.com/users/131877", "pm_score": 2, "selected": false, "text": "<p>neither solution worked for me - but this \"duct tape\" css fix worked for me:</p>\n\n<pre><code>/* always show excerpt .. hide display options */\nadd_action('admin_head', 'myplugin_modify_admin_header');\nfunction myplugin_modify_admin_header() {\n ?&gt;\n &lt;style type='text/css'&gt; \n #postexcerpt { display: block !important; } \n label[for=postexcerpt-hide] { display: none !important; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 325786, "author": "Chris B", "author_id": 159163, "author_profile": "https://wordpress.stackexchange.com/users/159163", "pm_score": 1, "selected": false, "text": "<p>While user meta stores unchecked meta boxes as an array, it does not store anything if the user has not modified the original defaults, returning a blank string instead. This results in errors on login if not accounted for, so I added an extra function &amp; hook to cover all bases. I also wrapped the unchecked variable with a conditional to make sure it didn't error if nothing was returned. Thanks to <a href=\"https://www.role-editor.com/show-excerpt-field-in-post-editor/\" rel=\"nofollow noreferrer\">Role-Editor</a> for the additional function.</p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n if(!empty($unchecked)){\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n\nfunction show_excerpt_meta_box($hidden, $screen) {\n if ( 'post' == $screen-&gt;base ) {\n foreach($hidden as $key=&gt;$value) {\n if ('postexcerpt' == $value) {\n unset($hidden[$key]);\n break;\n }\n }\n }\n return $hidden;\n}\nadd_filter( 'default_hidden_meta_boxes', 'show_excerpt_meta_box', 10, 2 );\n</code></pre>\n" } ]
2017/08/06
[ "https://wordpress.stackexchange.com/questions/275977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83781/" ]
By default in the admin the Excerpt is hidden. See below. [![By default in the admin the Excerpt is hidden](https://i.stack.imgur.com/XnUPZ.png)](https://i.stack.imgur.com/XnUPZ.png) I would like to make it show up by default.
The names of unchecked boxes in `Screen Options` for `Edit Post` screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's `functions.php`: ``` function wpse_edit_post_show_excerpt( $user_login, $user ) { $unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true ); $key = array_search( 'postexcerpt', $unchecked ); if ( FALSE !== $key ) { array_splice( $unchecked, $key, 1 ); update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked ); } } add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 ); ``` This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names. **Note**: to avoid losing your change, create a child theme and put the code into its `functions.php`.
275,979
<p>I have a custom post type "vegetables"</p> <p>I have a series of custom fields for each month of the year as check boxes</p> <p>I have a custom taxonomy "Seasons" that I want to assign based on what boxes are checked in my custom fields</p> <p>Summer if any June July August</p> <p>Fall if any September October November</p> <p>Winter if any December January February</p> <p>Spring if any March April May</p> <p>So the vegitable could be assigned all season or a single season based on what custom fields are checked </p> <pre><code>add_action( 'save_post', 'assign_cat_to', 10, 1 ); function assign_cat_to( $post_id ) { if ( 'seasonal-product' !== get_post_type( $post_id ) ) { return; } $term_slugs = array(); foreach ( $_POST as $field =&gt; $value ) { if ( 0 === strpos( $field, 'wpcf-available-in-' ) &amp;&amp; '1' === $value ) { $term_slugs[] = str_replace( 'wpcf-available-in-', '', $field ); } } if ( empty( $term_slugs ) ) { return; } $term_ids = array(); foreach ( $term_slugs as $term_slug ) { $term = get_term_by( 'slug', $term_slug, 'season' ); $term_ids[] = $term-&gt;term_id; } wp_set_object_terms( $post_id, $term_ids, 'season' ); } </code></pre> <p>I have made some updates based on actual fields and terms but I still do not understand how to assign "spring, summer, fall, winter" to the term.</p> <p>Alternatively I could store the season name "spring, summer, fall, winter" to the database instead of "1" would that make it easier to write to the term slug?</p>
[ { "answer_id": 275985, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>The names of unchecked boxes in <code>Screen Options</code> for <code>Edit Post</code> screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_edit_post_show_excerpt( $user_login, $user ) {\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );\n</code></pre>\n\n<p>This will update user's meta ( after successful login ) by removing <code>postexcerpt</code> name from the array of unchecked boxes names.</p>\n\n<p><strong>Note</strong>: to avoid losing your change, create a child theme and put the code into its <code>functions.php</code>.</p>\n" }, { "answer_id": 281317, "author": "Dedering", "author_id": 128642, "author_profile": "https://wordpress.stackexchange.com/users/128642", "pm_score": 2, "selected": false, "text": "<p>Sharing a slight modification of Franks' solution. In my case, I don't want users to ever hide the excerpt so I've hooked the function to the <code>admin_init</code> instead of <code>wp_login</code>. </p>\n\n<p>Frank's function executes when the user logs into the site which means that once the user is logged in they can hide it again. This solution will fire every time an admin page is loaded which wilmake it impossible for the user to hide the field. </p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n</code></pre>\n" }, { "answer_id": 286576, "author": "David", "author_id": 131877, "author_profile": "https://wordpress.stackexchange.com/users/131877", "pm_score": 2, "selected": false, "text": "<p>neither solution worked for me - but this \"duct tape\" css fix worked for me:</p>\n\n<pre><code>/* always show excerpt .. hide display options */\nadd_action('admin_head', 'myplugin_modify_admin_header');\nfunction myplugin_modify_admin_header() {\n ?&gt;\n &lt;style type='text/css'&gt; \n #postexcerpt { display: block !important; } \n label[for=postexcerpt-hide] { display: none !important; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 325786, "author": "Chris B", "author_id": 159163, "author_profile": "https://wordpress.stackexchange.com/users/159163", "pm_score": 1, "selected": false, "text": "<p>While user meta stores unchecked meta boxes as an array, it does not store anything if the user has not modified the original defaults, returning a blank string instead. This results in errors on login if not accounted for, so I added an extra function &amp; hook to cover all bases. I also wrapped the unchecked variable with a conditional to make sure it didn't error if nothing was returned. Thanks to <a href=\"https://www.role-editor.com/show-excerpt-field-in-post-editor/\" rel=\"nofollow noreferrer\">Role-Editor</a> for the additional function.</p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n if(!empty($unchecked)){\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n\nfunction show_excerpt_meta_box($hidden, $screen) {\n if ( 'post' == $screen-&gt;base ) {\n foreach($hidden as $key=&gt;$value) {\n if ('postexcerpt' == $value) {\n unset($hidden[$key]);\n break;\n }\n }\n }\n return $hidden;\n}\nadd_filter( 'default_hidden_meta_boxes', 'show_excerpt_meta_box', 10, 2 );\n</code></pre>\n" } ]
2017/08/06
[ "https://wordpress.stackexchange.com/questions/275979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125332/" ]
I have a custom post type "vegetables" I have a series of custom fields for each month of the year as check boxes I have a custom taxonomy "Seasons" that I want to assign based on what boxes are checked in my custom fields Summer if any June July August Fall if any September October November Winter if any December January February Spring if any March April May So the vegitable could be assigned all season or a single season based on what custom fields are checked ``` add_action( 'save_post', 'assign_cat_to', 10, 1 ); function assign_cat_to( $post_id ) { if ( 'seasonal-product' !== get_post_type( $post_id ) ) { return; } $term_slugs = array(); foreach ( $_POST as $field => $value ) { if ( 0 === strpos( $field, 'wpcf-available-in-' ) && '1' === $value ) { $term_slugs[] = str_replace( 'wpcf-available-in-', '', $field ); } } if ( empty( $term_slugs ) ) { return; } $term_ids = array(); foreach ( $term_slugs as $term_slug ) { $term = get_term_by( 'slug', $term_slug, 'season' ); $term_ids[] = $term->term_id; } wp_set_object_terms( $post_id, $term_ids, 'season' ); } ``` I have made some updates based on actual fields and terms but I still do not understand how to assign "spring, summer, fall, winter" to the term. Alternatively I could store the season name "spring, summer, fall, winter" to the database instead of "1" would that make it easier to write to the term slug?
The names of unchecked boxes in `Screen Options` for `Edit Post` screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's `functions.php`: ``` function wpse_edit_post_show_excerpt( $user_login, $user ) { $unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true ); $key = array_search( 'postexcerpt', $unchecked ); if ( FALSE !== $key ) { array_splice( $unchecked, $key, 1 ); update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked ); } } add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 ); ``` This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names. **Note**: to avoid losing your change, create a child theme and put the code into its `functions.php`.
275,988
<p>I have the following function for a shortcode below. I have the shortcode in a footer widget. For some reason the output is appearing outside of the container elements of the widget. I thought returning the values was the way to go so I'm kind of stuck here. </p> <pre><code>if (!function_exists('footer_get_latest_post')) { function footer_get_latest_post() { $footerPost = ''; $args = array('posts_per_page' =&gt; 1 ); $recent_posts = new WP_Query($args); while( $recent_posts-&gt;have_posts() ) { $recent_posts-&gt;the_post(); $footerPost = '&lt;div class="footer-post-thumb"&gt;' . the_post_thumbnail('thumbnail') . '&lt;/div&gt;'; $footerPost .= '&lt;div class="footer-post-content"&gt;&lt;h3&gt;' . the_title() . '&lt;/h3&gt;'; $footerPost .= the_content() . '&lt;/div&gt;'; } wp_reset_query(); return $footerPost; } } add_shortcode('FooterLatestPost', 'footer_get_latest_post'); </code></pre> <p>So the final html output looks something like:</p> <pre><code>&lt;img&gt; &lt;p&gt;Post Title&lt;/p&gt; &lt;p&gt;Post Content&lt;/p&gt; &lt;div class="footer-widget"&gt; empty &lt;/div&gt; </code></pre>
[ { "answer_id": 275985, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>The names of unchecked boxes in <code>Screen Options</code> for <code>Edit Post</code> screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_edit_post_show_excerpt( $user_login, $user ) {\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );\n</code></pre>\n\n<p>This will update user's meta ( after successful login ) by removing <code>postexcerpt</code> name from the array of unchecked boxes names.</p>\n\n<p><strong>Note</strong>: to avoid losing your change, create a child theme and put the code into its <code>functions.php</code>.</p>\n" }, { "answer_id": 281317, "author": "Dedering", "author_id": 128642, "author_profile": "https://wordpress.stackexchange.com/users/128642", "pm_score": 2, "selected": false, "text": "<p>Sharing a slight modification of Franks' solution. In my case, I don't want users to ever hide the excerpt so I've hooked the function to the <code>admin_init</code> instead of <code>wp_login</code>. </p>\n\n<p>Frank's function executes when the user logs into the site which means that once the user is logged in they can hide it again. This solution will fire every time an admin page is loaded which wilmake it impossible for the user to hide the field. </p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n</code></pre>\n" }, { "answer_id": 286576, "author": "David", "author_id": 131877, "author_profile": "https://wordpress.stackexchange.com/users/131877", "pm_score": 2, "selected": false, "text": "<p>neither solution worked for me - but this \"duct tape\" css fix worked for me:</p>\n\n<pre><code>/* always show excerpt .. hide display options */\nadd_action('admin_head', 'myplugin_modify_admin_header');\nfunction myplugin_modify_admin_header() {\n ?&gt;\n &lt;style type='text/css'&gt; \n #postexcerpt { display: block !important; } \n label[for=postexcerpt-hide] { display: none !important; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 325786, "author": "Chris B", "author_id": 159163, "author_profile": "https://wordpress.stackexchange.com/users/159163", "pm_score": 1, "selected": false, "text": "<p>While user meta stores unchecked meta boxes as an array, it does not store anything if the user has not modified the original defaults, returning a blank string instead. This results in errors on login if not accounted for, so I added an extra function &amp; hook to cover all bases. I also wrapped the unchecked variable with a conditional to make sure it didn't error if nothing was returned. Thanks to <a href=\"https://www.role-editor.com/show-excerpt-field-in-post-editor/\" rel=\"nofollow noreferrer\">Role-Editor</a> for the additional function.</p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n if(!empty($unchecked)){\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n\nfunction show_excerpt_meta_box($hidden, $screen) {\n if ( 'post' == $screen-&gt;base ) {\n foreach($hidden as $key=&gt;$value) {\n if ('postexcerpt' == $value) {\n unset($hidden[$key]);\n break;\n }\n }\n }\n return $hidden;\n}\nadd_filter( 'default_hidden_meta_boxes', 'show_excerpt_meta_box', 10, 2 );\n</code></pre>\n" } ]
2017/08/06
[ "https://wordpress.stackexchange.com/questions/275988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I have the following function for a shortcode below. I have the shortcode in a footer widget. For some reason the output is appearing outside of the container elements of the widget. I thought returning the values was the way to go so I'm kind of stuck here. ``` if (!function_exists('footer_get_latest_post')) { function footer_get_latest_post() { $footerPost = ''; $args = array('posts_per_page' => 1 ); $recent_posts = new WP_Query($args); while( $recent_posts->have_posts() ) { $recent_posts->the_post(); $footerPost = '<div class="footer-post-thumb">' . the_post_thumbnail('thumbnail') . '</div>'; $footerPost .= '<div class="footer-post-content"><h3>' . the_title() . '</h3>'; $footerPost .= the_content() . '</div>'; } wp_reset_query(); return $footerPost; } } add_shortcode('FooterLatestPost', 'footer_get_latest_post'); ``` So the final html output looks something like: ``` <img> <p>Post Title</p> <p>Post Content</p> <div class="footer-widget"> empty </div> ```
The names of unchecked boxes in `Screen Options` for `Edit Post` screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's `functions.php`: ``` function wpse_edit_post_show_excerpt( $user_login, $user ) { $unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true ); $key = array_search( 'postexcerpt', $unchecked ); if ( FALSE !== $key ) { array_splice( $unchecked, $key, 1 ); update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked ); } } add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 ); ``` This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names. **Note**: to avoid losing your change, create a child theme and put the code into its `functions.php`.
276,032
<p><a href="https://i.stack.imgur.com/mV5X3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mV5X3.png" alt="enter image description here"></a>i am learning html and php from scratch, i had upload a wordpress website, all ok, but i have problem with some editing, means i coluld not find which file i have to edit. i search index.php but in index.php file i did not find texts that i want to edit.</p> <p>i am using education base theme, my website <code>http://saraswati-school.com/</code></p> <p>i also read official documents of 'education base' theme, please help me, which in which file i can find text that i want to edit.</p> <p>i want to edit text in red rectangle in upper image. thanks</p> <p>website</p> <pre><code>http://saraswati-school.com/ </code></pre>
[ { "answer_id": 275985, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>The names of unchecked boxes in <code>Screen Options</code> for <code>Edit Post</code> screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_edit_post_show_excerpt( $user_login, $user ) {\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );\n</code></pre>\n\n<p>This will update user's meta ( after successful login ) by removing <code>postexcerpt</code> name from the array of unchecked boxes names.</p>\n\n<p><strong>Note</strong>: to avoid losing your change, create a child theme and put the code into its <code>functions.php</code>.</p>\n" }, { "answer_id": 281317, "author": "Dedering", "author_id": 128642, "author_profile": "https://wordpress.stackexchange.com/users/128642", "pm_score": 2, "selected": false, "text": "<p>Sharing a slight modification of Franks' solution. In my case, I don't want users to ever hide the excerpt so I've hooked the function to the <code>admin_init</code> instead of <code>wp_login</code>. </p>\n\n<p>Frank's function executes when the user logs into the site which means that once the user is logged in they can hide it again. This solution will fire every time an admin page is loaded which wilmake it impossible for the user to hide the field. </p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n</code></pre>\n" }, { "answer_id": 286576, "author": "David", "author_id": 131877, "author_profile": "https://wordpress.stackexchange.com/users/131877", "pm_score": 2, "selected": false, "text": "<p>neither solution worked for me - but this \"duct tape\" css fix worked for me:</p>\n\n<pre><code>/* always show excerpt .. hide display options */\nadd_action('admin_head', 'myplugin_modify_admin_header');\nfunction myplugin_modify_admin_header() {\n ?&gt;\n &lt;style type='text/css'&gt; \n #postexcerpt { display: block !important; } \n label[for=postexcerpt-hide] { display: none !important; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 325786, "author": "Chris B", "author_id": 159163, "author_profile": "https://wordpress.stackexchange.com/users/159163", "pm_score": 1, "selected": false, "text": "<p>While user meta stores unchecked meta boxes as an array, it does not store anything if the user has not modified the original defaults, returning a blank string instead. This results in errors on login if not accounted for, so I added an extra function &amp; hook to cover all bases. I also wrapped the unchecked variable with a conditional to make sure it didn't error if nothing was returned. Thanks to <a href=\"https://www.role-editor.com/show-excerpt-field-in-post-editor/\" rel=\"nofollow noreferrer\">Role-Editor</a> for the additional function.</p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n if(!empty($unchecked)){\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n\nfunction show_excerpt_meta_box($hidden, $screen) {\n if ( 'post' == $screen-&gt;base ) {\n foreach($hidden as $key=&gt;$value) {\n if ('postexcerpt' == $value) {\n unset($hidden[$key]);\n break;\n }\n }\n }\n return $hidden;\n}\nadd_filter( 'default_hidden_meta_boxes', 'show_excerpt_meta_box', 10, 2 );\n</code></pre>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125367/" ]
[![enter image description here](https://i.stack.imgur.com/mV5X3.png)](https://i.stack.imgur.com/mV5X3.png)i am learning html and php from scratch, i had upload a wordpress website, all ok, but i have problem with some editing, means i coluld not find which file i have to edit. i search index.php but in index.php file i did not find texts that i want to edit. i am using education base theme, my website `http://saraswati-school.com/` i also read official documents of 'education base' theme, please help me, which in which file i can find text that i want to edit. i want to edit text in red rectangle in upper image. thanks website ``` http://saraswati-school.com/ ```
The names of unchecked boxes in `Screen Options` for `Edit Post` screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's `functions.php`: ``` function wpse_edit_post_show_excerpt( $user_login, $user ) { $unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true ); $key = array_search( 'postexcerpt', $unchecked ); if ( FALSE !== $key ) { array_splice( $unchecked, $key, 1 ); update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked ); } } add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 ); ``` This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names. **Note**: to avoid losing your change, create a child theme and put the code into its `functions.php`.
276,036
<p>Is there a way to add a condition to know if the current item of the navigation walker is the last child of the menu or parent? </p> <pre><code>| Item 1 | Item 2 | | - Item 1.1 | - Item 2.1 | | - Item 1.2 | - Item 2.2 | | - Item 1.3 |&lt;----------------- Determine if current item is last child </code></pre> <p>For example: </p> <pre><code>if ($item-&gt;last_child(of_current_parent) { ... } </code></pre> <p>So, how do you determine if the current item is the last child of its siblings? </p> <p>EDIT: Solved my problem trying this: <a href="https://wordpress.stackexchange.com/a/49005/91164">https://wordpress.stackexchange.com/a/49005/91164</a> But had to change the logic quite a bit to fit my needs. See my answer below. </p>
[ { "answer_id": 275985, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>The names of unchecked boxes in <code>Screen Options</code> for <code>Edit Post</code> screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_edit_post_show_excerpt( $user_login, $user ) {\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 );\n</code></pre>\n\n<p>This will update user's meta ( after successful login ) by removing <code>postexcerpt</code> name from the array of unchecked boxes names.</p>\n\n<p><strong>Note</strong>: to avoid losing your change, create a child theme and put the code into its <code>functions.php</code>.</p>\n" }, { "answer_id": 281317, "author": "Dedering", "author_id": 128642, "author_profile": "https://wordpress.stackexchange.com/users/128642", "pm_score": 2, "selected": false, "text": "<p>Sharing a slight modification of Franks' solution. In my case, I don't want users to ever hide the excerpt so I've hooked the function to the <code>admin_init</code> instead of <code>wp_login</code>. </p>\n\n<p>Frank's function executes when the user logs into the site which means that once the user is logged in they can hide it again. This solution will fire every time an admin page is loaded which wilmake it impossible for the user to hide the field. </p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n</code></pre>\n" }, { "answer_id": 286576, "author": "David", "author_id": 131877, "author_profile": "https://wordpress.stackexchange.com/users/131877", "pm_score": 2, "selected": false, "text": "<p>neither solution worked for me - but this \"duct tape\" css fix worked for me:</p>\n\n<pre><code>/* always show excerpt .. hide display options */\nadd_action('admin_head', 'myplugin_modify_admin_header');\nfunction myplugin_modify_admin_header() {\n ?&gt;\n &lt;style type='text/css'&gt; \n #postexcerpt { display: block !important; } \n label[for=postexcerpt-hide] { display: none !important; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 325786, "author": "Chris B", "author_id": 159163, "author_profile": "https://wordpress.stackexchange.com/users/159163", "pm_score": 1, "selected": false, "text": "<p>While user meta stores unchecked meta boxes as an array, it does not store anything if the user has not modified the original defaults, returning a blank string instead. This results in errors on login if not accounted for, so I added an extra function &amp; hook to cover all bases. I also wrapped the unchecked variable with a conditional to make sure it didn't error if nothing was returned. Thanks to <a href=\"https://www.role-editor.com/show-excerpt-field-in-post-editor/\" rel=\"nofollow noreferrer\">Role-Editor</a> for the additional function.</p>\n\n<pre><code>function wpse_edit_post_show_excerpt() {\n $user = wp_get_current_user();\n $unchecked = get_user_meta( $user-&gt;ID, 'metaboxhidden_post', true );\n if(!empty($unchecked)){\n $key = array_search( 'postexcerpt', $unchecked );\n if ( FALSE !== $key ) {\n array_splice( $unchecked, $key, 1 );\n update_user_meta( $user-&gt;ID, 'metaboxhidden_post', $unchecked );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_edit_post_show_excerpt', 10 );\n\nfunction show_excerpt_meta_box($hidden, $screen) {\n if ( 'post' == $screen-&gt;base ) {\n foreach($hidden as $key=&gt;$value) {\n if ('postexcerpt' == $value) {\n unset($hidden[$key]);\n break;\n }\n }\n }\n return $hidden;\n}\nadd_filter( 'default_hidden_meta_boxes', 'show_excerpt_meta_box', 10, 2 );\n</code></pre>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91164/" ]
Is there a way to add a condition to know if the current item of the navigation walker is the last child of the menu or parent? ``` | Item 1 | Item 2 | | - Item 1.1 | - Item 2.1 | | - Item 1.2 | - Item 2.2 | | - Item 1.3 |<----------------- Determine if current item is last child ``` For example: ``` if ($item->last_child(of_current_parent) { ... } ``` So, how do you determine if the current item is the last child of its siblings? EDIT: Solved my problem trying this: <https://wordpress.stackexchange.com/a/49005/91164> But had to change the logic quite a bit to fit my needs. See my answer below.
The names of unchecked boxes in `Screen Options` for `Edit Post` screen are stored in user's meta, per individual user, as an array. Insert the following code in your theme's `functions.php`: ``` function wpse_edit_post_show_excerpt( $user_login, $user ) { $unchecked = get_user_meta( $user->ID, 'metaboxhidden_post', true ); $key = array_search( 'postexcerpt', $unchecked ); if ( FALSE !== $key ) { array_splice( $unchecked, $key, 1 ); update_user_meta( $user->ID, 'metaboxhidden_post', $unchecked ); } } add_action( 'wp_login', 'wpse_edit_post_show_excerpt', 10, 2 ); ``` This will update user's meta ( after successful login ) by removing `postexcerpt` name from the array of unchecked boxes names. **Note**: to avoid losing your change, create a child theme and put the code into its `functions.php`.
276,092
<p>I'm trying to create an anchor tag and using a variable as the link. </p> <p>Here's what my template looks like. </p> <pre><code>&lt;?php $website = tribe_get_event_website_link(); echo '&lt;a href="' . $website. '"&gt;REGISTER&lt;/a&gt;'; ?&gt; </code></pre> <p>So I'm creating a variable that will hold the link the I want to anchor it. And when I echo it back, it appears, but it doesn't come out properly. Here's what it looks like. </p> <p><img src="https://image.ibb.co/dtkDGa/Screen_Shot_2017_08_07_at_10_12_47_AM.png" alt="html"></p> <p>Any clue on what I'm doing wrong? </p> <p>edit:</p> <p>I also tried </p> <pre><code>&lt;a href="&lt;?php echo $website ?&gt;"&gt;REGISTER&lt;/a&gt; </code></pre> <p>but it still produces the same thing. </p>
[ { "answer_id": 276100, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>It's not really a WordPress related question, but it's a simple one. The <code>tribe_get_event_website_link()</code> function you are using outputs a full link. You can use SimpleXML to extract the <code>href</code> part and then use it later. It's as simple as this:</p>\n\n<pre><code>$website = tribe_get_event_website_link();\n$xml = new SimpleXMLElement( $website );\necho '&lt;a href=\"' . $xml['href']. '\"&gt;REGISTER&lt;/a&gt;';\n</code></pre>\n\n<p>If you are unable to store the functions value inside a variable (for example, if the function echos it), you can use <code>ob_get_clean()</code>:</p>\n\n<pre><code>ob_start();\n\ntribe_get_event_website_link();\n\n$website = ob_get_clean();\n</code></pre>\n\n<p>Now proceed with extracting the <code>href</code> as mentioned above.</p>\n" }, { "answer_id": 276103, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>Replace <code>tribe_get_event_website_link()</code> with <a href=\"https://theeventscalendar.com/function/tribe_get_event_website_url/\" rel=\"nofollow noreferrer\"><code>tribe_get_event_website_url()</code></a>.</p>\n\n<p>The first one is generating the link code. The second is just returning the url, which is what you need for the <code>href</code>.</p>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114057/" ]
I'm trying to create an anchor tag and using a variable as the link. Here's what my template looks like. ``` <?php $website = tribe_get_event_website_link(); echo '<a href="' . $website. '">REGISTER</a>'; ?> ``` So I'm creating a variable that will hold the link the I want to anchor it. And when I echo it back, it appears, but it doesn't come out properly. Here's what it looks like. ![html](https://image.ibb.co/dtkDGa/Screen_Shot_2017_08_07_at_10_12_47_AM.png) Any clue on what I'm doing wrong? edit: I also tried ``` <a href="<?php echo $website ?>">REGISTER</a> ``` but it still produces the same thing.
It's not really a WordPress related question, but it's a simple one. The `tribe_get_event_website_link()` function you are using outputs a full link. You can use SimpleXML to extract the `href` part and then use it later. It's as simple as this: ``` $website = tribe_get_event_website_link(); $xml = new SimpleXMLElement( $website ); echo '<a href="' . $xml['href']. '">REGISTER</a>'; ``` If you are unable to store the functions value inside a variable (for example, if the function echos it), you can use `ob_get_clean()`: ``` ob_start(); tribe_get_event_website_link(); $website = ob_get_clean(); ``` Now proceed with extracting the `href` as mentioned above.
276,097
<p>So, I need to show a page with the sub-categories of the current custom taxonomy, with their respective posts inside.</p> <p>What I need is, when I click on a sub-cat link, I get something like:</p> <pre><code>'Tipos' (custom taxonomy) - Auto (first sub-cat) - Sub-Item 1 (first sub-sub-cat) - Post 1 - Post 2 - Sub-Item 2 (second sub-sub-cat) - Post 1 - Post 2 </code></pre> <p>I have another sub-cats, but I dont wanna see them, since I clicked to see the sub-sub-cats inside the sub-cat 'auto'.</p> <p>The name of the Custom Post Type is 'Produtos'</p> <p>The name of the custom taxonomy is 'Tipos'</p> <p>The page I'm using is 'taxonomy-tipos.php</p> <p>I know I need to:</p> <ul> <li>Get the current custom taxonomy;</li> <li>Make a loop that shows a list of the sub-categories of that custom taxonomy;</li> <li>Inside the list of sub-categories, show the posts inside each sub-category;</li> </ul> <p>I understand about WordPress hierarchy, but the problem is that I need to automatically show those sub-categories based on the taxonomy, and I'm not being able to achieve that.</p> <p>With my code, I get all the categories inside the custom taxonomy. I wanna get only the ones inside the current one.</p> <p><strong>This is the code I tried:</strong></p> <pre><code>Removed the code so it wont confuse anyone </code></pre> <p>Can you guys give me a light? Thanks.</p> <p><strong>PROBLEM SOLVED. FINAL CODE (WORKING):</strong></p> <pre><code>$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term-&gt;name; $queried_object = get_queried_object(); $term_id = get_queried_object()-&gt;term_id; $taxonomyName = "tipos"; $termchildren = get_term_children( $term_id, $taxonomyName ); if ($termchildren != false){ foreach ($termchildren as $child) { $term2 = get_term_by( 'id', $child, $taxonomyName ); echo $term2-&gt;name; $my_query = new WP_Query( array( 'post_type' =&gt; 'produtos', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'DESC', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; $taxonomyName, 'field' =&gt; 'slug', 'terms' =&gt; $term2-&gt;slug, ) ), )); while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); //content you want to show endwhile; wp_reset_postdata(); } } else{ $my_query2 = new WP_Query( array( 'post_type' =&gt; 'produtos', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'DESC', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; $taxonomyName, 'field' =&gt; 'slug', 'terms' =&gt; $term-&gt;slug, ) ), )); while ($my_query2-&gt;have_posts()) : $my_query2-&gt;the_post(); //content you want to show endwhile; wp_reset_postdata(); } </code></pre>
[ { "answer_id": 276099, "author": "Greeso", "author_id": 34253, "author_profile": "https://wordpress.stackexchange.com/users/34253", "pm_score": 1, "selected": false, "text": "<p>I think you can easily achieve that if you understand <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">WordPress template hierarchy</a>. </p>\n\n<p>Looking at the <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">template hierarchy diagram</a>, and assuming you have categories and sub-categories, then you can achieve what you want in multiple ways.</p>\n\n<p><strong>Suggestion 1</strong></p>\n\n<ol>\n<li><p>Use <em>category.php</em> to display the posts of any category, including sub-categories.</p></li>\n<li><p>also in <em>category.php</em> add a condition at the top to detect if it is a \"parent\" category. If so, then display the sub-categories of that parent category.</p></li>\n</ol>\n\n<p><strong>Suggestion 2</strong></p>\n\n<ol>\n<li><p>Use <em>category.php</em> to display the posts of any category, including sub-categories.</p></li>\n<li><p>Use <em>category-$slug.php</em> for the parent category, and use it to display the sub categories for that parent.</p></li>\n</ol>\n\n<p>I think <strong>suggestion 2</strong> would be OK if you have one, or two parent categories. Because every time you add a new parent category, you have to create a new <em>category-$slug.php</em> file for it. So if you have many parent categories to be created, then use <strong>suggestion 1</strong>.</p>\n\n<p>Also, you can use the same solution for custom taxonomies as well, but use the hierarchy diagram to understand taxonomy files (i.e., use <em>taxonomy.php</em>, <em>taxonomy-$taxonomy.php</em> and <em>taxonomy-$taxonomy-$term.php</em> depending on your needs).</p>\n" }, { "answer_id": 276807, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 1, "selected": true, "text": "<p><strong>PROBLEM SOLVED.\nFINAL CODE (WORKING):</strong></p>\n\n<pre><code>$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );\necho $term-&gt;name;\n$queried_object = get_queried_object();\n$term_id = get_queried_object()-&gt;term_id;\n$taxonomyName = \"tipos\";\n$termchildren = get_term_children( $term_id, $taxonomyName );\nif ($termchildren != false){\n foreach ($termchildren as $child) {\n $term2 = get_term_by( 'id', $child, $taxonomyName );\n echo $term2-&gt;name; \n $my_query = new WP_Query( array(\n 'post_type' =&gt; 'produtos',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'DESC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $taxonomyName,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term2-&gt;slug,\n )\n ),\n ));\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();\n //content you want to show\n endwhile; \n wp_reset_postdata();\n }\n} else{\n $my_query2 = new WP_Query( array(\n 'post_type' =&gt; 'produtos',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'DESC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $taxonomyName,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term-&gt;slug,\n )\n ),\n ));\n while ($my_query2-&gt;have_posts()) : $my_query2-&gt;the_post();\n //content you want to show\n endwhile; \n wp_reset_postdata();\n}\n</code></pre>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44437/" ]
So, I need to show a page with the sub-categories of the current custom taxonomy, with their respective posts inside. What I need is, when I click on a sub-cat link, I get something like: ``` 'Tipos' (custom taxonomy) - Auto (first sub-cat) - Sub-Item 1 (first sub-sub-cat) - Post 1 - Post 2 - Sub-Item 2 (second sub-sub-cat) - Post 1 - Post 2 ``` I have another sub-cats, but I dont wanna see them, since I clicked to see the sub-sub-cats inside the sub-cat 'auto'. The name of the Custom Post Type is 'Produtos' The name of the custom taxonomy is 'Tipos' The page I'm using is 'taxonomy-tipos.php I know I need to: * Get the current custom taxonomy; * Make a loop that shows a list of the sub-categories of that custom taxonomy; * Inside the list of sub-categories, show the posts inside each sub-category; I understand about WordPress hierarchy, but the problem is that I need to automatically show those sub-categories based on the taxonomy, and I'm not being able to achieve that. With my code, I get all the categories inside the custom taxonomy. I wanna get only the ones inside the current one. **This is the code I tried:** ``` Removed the code so it wont confuse anyone ``` Can you guys give me a light? Thanks. **PROBLEM SOLVED. FINAL CODE (WORKING):** ``` $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; $queried_object = get_queried_object(); $term_id = get_queried_object()->term_id; $taxonomyName = "tipos"; $termchildren = get_term_children( $term_id, $taxonomyName ); if ($termchildren != false){ foreach ($termchildren as $child) { $term2 = get_term_by( 'id', $child, $taxonomyName ); echo $term2->name; $my_query = new WP_Query( array( 'post_type' => 'produtos', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => $taxonomyName, 'field' => 'slug', 'terms' => $term2->slug, ) ), )); while ($my_query->have_posts()) : $my_query->the_post(); //content you want to show endwhile; wp_reset_postdata(); } } else{ $my_query2 = new WP_Query( array( 'post_type' => 'produtos', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => $taxonomyName, 'field' => 'slug', 'terms' => $term->slug, ) ), )); while ($my_query2->have_posts()) : $my_query2->the_post(); //content you want to show endwhile; wp_reset_postdata(); } ```
**PROBLEM SOLVED. FINAL CODE (WORKING):** ``` $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; $queried_object = get_queried_object(); $term_id = get_queried_object()->term_id; $taxonomyName = "tipos"; $termchildren = get_term_children( $term_id, $taxonomyName ); if ($termchildren != false){ foreach ($termchildren as $child) { $term2 = get_term_by( 'id', $child, $taxonomyName ); echo $term2->name; $my_query = new WP_Query( array( 'post_type' => 'produtos', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => $taxonomyName, 'field' => 'slug', 'terms' => $term2->slug, ) ), )); while ($my_query->have_posts()) : $my_query->the_post(); //content you want to show endwhile; wp_reset_postdata(); } } else{ $my_query2 = new WP_Query( array( 'post_type' => 'produtos', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => $taxonomyName, 'field' => 'slug', 'terms' => $term->slug, ) ), )); while ($my_query2->have_posts()) : $my_query2->the_post(); //content you want to show endwhile; wp_reset_postdata(); } ```
276,108
<p>I'm using ACF to build some custom elements on pages and also WPML to manage the translations of these pages.</p> <p>I am currently seeing an issue where the pages do not save when I update the language content.</p> <p>In the WPML custom field settings I have each custom field down to the Translate option.</p> <p>Within each page I am copying the content to a language to pre-populate the custom fields and not use the synchronise option as I want to translate this independently.</p> <p>Any ideas as to why my content is not saving and reverting back to the original?</p> <p>Thanks</p>
[ { "answer_id": 276113, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>I've had a fair share of issues with ACF, but end up using it still.</p>\n\n<p>There could be 3 things causing your problem. </p>\n\n<p>you could try changing your php settings:</p>\n\n<pre><code>max_input_time = 42000\nmax_execution_time = 42000\nmax_input_vars = 50000\n</code></pre>\n\n<p>This next one is not a great fix as if WordPress ever decides to update their tables it could cause problems (but that hasn't happened yet):</p>\n\n<p>wp_options table, option_name column -> increase length from 64 to something else, like 255</p>\n\n<p>More painfully you need to shorten your field names. If you're using something like my_super_cool_extra_amazing_language_field, acf starts taking a lot memory. Shorten all field names.</p>\n\n<p>This is all of course assuming you're not using any special functions to save the field as i wouldn't be able to test those with out seeing them.</p>\n" }, { "answer_id": 276348, "author": "Shane Jones", "author_id": 37508, "author_profile": "https://wordpress.stackexchange.com/users/37508", "pm_score": 0, "selected": false, "text": "<p>Tried a number of solutions including the ones on this post.</p>\n\n<p>Turns out the the site already once had WMPL installed and the database tables were still in the database even after the plugin had been uninstalled. Some hangover values in there were causing the issues.</p>\n\n<p>The solution for me was to got into WPML > Support > troubleshooting > Reset PRO translation configuration, select the check check-box \"I am about to reset the project settings.\" and click to the button \"Reset all languages data and deactivate WPML\". </p>\n\n<p>When I did this and went through the install script everything worked fine and as expected.</p>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37508/" ]
I'm using ACF to build some custom elements on pages and also WPML to manage the translations of these pages. I am currently seeing an issue where the pages do not save when I update the language content. In the WPML custom field settings I have each custom field down to the Translate option. Within each page I am copying the content to a language to pre-populate the custom fields and not use the synchronise option as I want to translate this independently. Any ideas as to why my content is not saving and reverting back to the original? Thanks
I've had a fair share of issues with ACF, but end up using it still. There could be 3 things causing your problem. you could try changing your php settings: ``` max_input_time = 42000 max_execution_time = 42000 max_input_vars = 50000 ``` This next one is not a great fix as if WordPress ever decides to update their tables it could cause problems (but that hasn't happened yet): wp\_options table, option\_name column -> increase length from 64 to something else, like 255 More painfully you need to shorten your field names. If you're using something like my\_super\_cool\_extra\_amazing\_language\_field, acf starts taking a lot memory. Shorten all field names. This is all of course assuming you're not using any special functions to save the field as i wouldn't be able to test those with out seeing them.
276,116
<p>So I'm attempting to create a single page Wordpress theme and right now I'm using my index.php as the page they will initially see. </p> <p>In my index.php I use The Loop to create a bunch of <code>a</code> tags that link to the all of the post permalinks.</p> <p>What is the template file that I need to make or what do I need to define so that I can control what those posts look like once you travel to their permalink?</p>
[ { "answer_id": 276117, "author": "Chris MXol", "author_id": 125415, "author_profile": "https://wordpress.stackexchange.com/users/125415", "pm_score": -1, "selected": false, "text": "<p>Nvm, found it. It's single.php. </p>\n" }, { "answer_id": 276120, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>For those that come here looking for an understanding of the template hierarchy, it's best to start at the Codex: <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a> </p>\n\n<p>Lots of resources via the googles on building themes, including the Codex. </p>\n" }, { "answer_id": 287264, "author": "Alexander Taranenko", "author_id": 132325, "author_profile": "https://wordpress.stackexchange.com/users/132325", "pm_score": 0, "selected": false, "text": "<p>You can create new template php file.</p>\n\n<pre><code>//Template Name : Single Page Template\nget_header();\nif ( have_posts() ) : \n while ( have_posts() ) : the_post(); \n the_content(); \n the_permalink();//this is for the &lt;a&gt; bunch you are looking for\n endwhile; \nendif;\nget_footer();\n</code></pre>\n\n<p>Here , you can use \"//\" or \"/** **/\" to set the Template name , it varies from the theme you are using.\nand then , go to Add New Page and there on the right sidebar , you can choose this template , by default it was set \"Default Template\".\nThere on dropdown , you can find the newly created template file named \"Single Page Template\".</p>\n" } ]
2017/08/07
[ "https://wordpress.stackexchange.com/questions/276116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125415/" ]
So I'm attempting to create a single page Wordpress theme and right now I'm using my index.php as the page they will initially see. In my index.php I use The Loop to create a bunch of `a` tags that link to the all of the post permalinks. What is the template file that I need to make or what do I need to define so that I can control what those posts look like once you travel to their permalink?
You can create new template php file. ``` //Template Name : Single Page Template get_header(); if ( have_posts() ) : while ( have_posts() ) : the_post(); the_content(); the_permalink();//this is for the <a> bunch you are looking for endwhile; endif; get_footer(); ``` Here , you can use "//" or "/\*\* \*\*/" to set the Template name , it varies from the theme you are using. and then , go to Add New Page and there on the right sidebar , you can choose this template , by default it was set "Default Template". There on dropdown , you can find the newly created template file named "Single Page Template".
276,177
<p>I am trying to get the permalink and title into variables to use outside of a loop - I have made it work for the thumbnail but for some reason can t get it to work for these two.</p> <p>Here is my code:</p> <pre><code>&lt;div class="medium-12 medium-centered columns"&gt; &lt;?php global $post; // required $args = array('category' =&gt; 5, 'posts_per_page'=&gt; 7); // include category 5 (Action) $custom_posts = get_posts($args); $count3=1; foreach($custom_posts as $post) : setup_postdata($post); $v = get_the_post_thumbnail($post-&gt;ID, 'medium'); $var = "img".$count3; $$var = $v; $l = get_the_permalink(); $link = "link".$count3; $$l = $l; $t = get_the_title(); $tt = "title".$count3; $$t = $t; ?&gt; &lt;?php $count3++; ?&gt; &lt;?php endforeach; ?&gt; &lt;div class="row collapse imageGrid photogrid" data-equalizer="fullRow"&gt; &lt;div class="medium-4 columns" data-equalizer-watch="fullRow"&gt; &lt;a href="&lt;?php echo $link1; ?&gt;"&gt; &lt;span class="centertitle"&gt;&lt;?php echo $title1; ?&gt;&lt;/span&gt; &lt;?php echo $img1; ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="medium-4 columns" data-equalizer-watch="fullRow" data-equalizer="watchColumn"&gt; &lt;div class="row collapse" data-equalizer-watch="watchColumn"&gt; &lt;?php echo $img2; ?&gt; &lt;/div&gt; &lt;div class="row collapse" &gt; &lt;div class="medium-6 columns" data-equalizer-watch="watchColumn"&gt; &lt;?php echo $img3; ?&gt;&lt;/div&gt; &lt;div class="medium-6 columns" data-equalizer-watch="watchColumn"&gt;&lt;?php echo $img4; ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="medium-4 columns" data-equalizer-watch="fullRow" data-equalizer="watchColumn2"&gt; &lt;div class="row collapse"&gt; &lt;div class="medium-6 columns" &gt;&lt;?php echo $img5; ?&gt;&lt;/div&gt; &lt;div class="medium-6 columns" &gt;&lt;?php echo $img6; ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row collapse" data-equalizer-watch="watchColumn2"&gt; &lt;?php echo $img7; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I have tried different ways of putting the title including:</p> <p>$t = the_title('', '', false);</p> <p>as $t = the_title() echos the title straight away.</p> <p>Any help in how to put them into the variable would be much appreciated</p>
[ { "answer_id": 276136, "author": "Elroy Fernandes", "author_id": 88483, "author_profile": "https://wordpress.stackexchange.com/users/88483", "pm_score": 0, "selected": false, "text": "<p>You need to check location first and then change the display text or you can change the text from the back end. This <a href=\"https://docs.woocommerce.com/document/free-shipping/\" rel=\"nofollow noreferrer\">link</a> show you how. </p>\n" }, { "answer_id": 276137, "author": "Gene Sescon", "author_id": 125427, "author_profile": "https://wordpress.stackexchange.com/users/125427", "pm_score": -1, "selected": false, "text": "<p>you can use css on this.\nget the selector of free shipping. set display to hidden then use psuedo element :after to place the new text</p>\n\n<p>You can use this filter. To change the shipping title. This would be SEO friendly.</p>\n\n<pre><code>function filter_woocommerce_shipping_package_name( $sprintf, $i, $package ) { \n\n return $sprintf; \n}; \n\nadd_filter( 'woocommerce_shipping_package_name', 'filter_woocommerce_shipping_package_name', 10, 3 ); \n</code></pre>\n\n<p>Heres some reference</p>\n\n<p><a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_cart_totals_shipping_html.html#223\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/wc-apidocs/source-function-wc_cart_totals_shipping_html.html#223</a></p>\n\n<p><a href=\"https://docs.woocommerce.com/wc-apidocs/hook-docs.html\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/wc-apidocs/hook-docs.html</a></p>\n" }, { "answer_id": 276141, "author": "Niv Noiman", "author_id": 87951, "author_profile": "https://wordpress.stackexchange.com/users/87951", "pm_score": 2, "selected": true, "text": "<p>I found this answer .\nHope this will help you.\nmaybe with wpml for multi-lang</p>\n\n<p><a href=\"https://stackoverflow.com/questions/38296093/woocommerce-free-shipping-remove-raw-or-change-the-text-name-on-checkout-and-e\">https://stackoverflow.com/questions/38296093/woocommerce-free-shipping-remove-raw-or-change-the-text-name-on-checkout-and-e</a></p>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276177", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108232/" ]
I am trying to get the permalink and title into variables to use outside of a loop - I have made it work for the thumbnail but for some reason can t get it to work for these two. Here is my code: ``` <div class="medium-12 medium-centered columns"> <?php global $post; // required $args = array('category' => 5, 'posts_per_page'=> 7); // include category 5 (Action) $custom_posts = get_posts($args); $count3=1; foreach($custom_posts as $post) : setup_postdata($post); $v = get_the_post_thumbnail($post->ID, 'medium'); $var = "img".$count3; $$var = $v; $l = get_the_permalink(); $link = "link".$count3; $$l = $l; $t = get_the_title(); $tt = "title".$count3; $$t = $t; ?> <?php $count3++; ?> <?php endforeach; ?> <div class="row collapse imageGrid photogrid" data-equalizer="fullRow"> <div class="medium-4 columns" data-equalizer-watch="fullRow"> <a href="<?php echo $link1; ?>"> <span class="centertitle"><?php echo $title1; ?></span> <?php echo $img1; ?> </a> </div> <div class="medium-4 columns" data-equalizer-watch="fullRow" data-equalizer="watchColumn"> <div class="row collapse" data-equalizer-watch="watchColumn"> <?php echo $img2; ?> </div> <div class="row collapse" > <div class="medium-6 columns" data-equalizer-watch="watchColumn"> <?php echo $img3; ?></div> <div class="medium-6 columns" data-equalizer-watch="watchColumn"><?php echo $img4; ?></div> </div> </div> <div class="medium-4 columns" data-equalizer-watch="fullRow" data-equalizer="watchColumn2"> <div class="row collapse"> <div class="medium-6 columns" ><?php echo $img5; ?></div> <div class="medium-6 columns" ><?php echo $img6; ?></div> </div> <div class="row collapse" data-equalizer-watch="watchColumn2"> <?php echo $img7; ?> </div> </div> <?php wp_reset_query(); ?> </div> </div> ``` I have tried different ways of putting the title including: $t = the\_title('', '', false); as $t = the\_title() echos the title straight away. Any help in how to put them into the variable would be much appreciated
I found this answer . Hope this will help you. maybe with wpml for multi-lang <https://stackoverflow.com/questions/38296093/woocommerce-free-shipping-remove-raw-or-change-the-text-name-on-checkout-and-e>
276,179
<p>I want to get the current user id from inside my plugin and use it as a variable. </p> <p>My code is</p> <pre><code>$current_user = wp_get_current_user(); $user_id = $current_user-&gt;ID; $loc_statuss = $wpdb-&gt;get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=$user_id" ); $loc_status = $loc_statuss-&gt;status; </code></pre> <p>I have found a couple of questions the same but these answers don't seem to work for me.</p> <p>Thanks</p>
[ { "answer_id": 276185, "author": "Rahul Parikh", "author_id": 125461, "author_profile": "https://wordpress.stackexchange.com/users/125461", "pm_score": 1, "selected": false, "text": "<p>If you want current user id only then use get_current_user_id.\nbecause it reduce execution time. get_current_user_id get only current user id where wp_get_current_user get all user data.\nElse every things is perfect.</p>\n\n<pre><code>$user_id = get_current_user_id();\n\n$loc_statuss = $wpdb-&gt;get_row( \"SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=\".$user_id );\n$loc_status = $loc_statuss-&gt;status;\n</code></pre>\n" }, { "answer_id": 276192, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>Try this code:</p>\n\n<pre><code>// Set up the global variables\n$user_id;\n$loc_status;\n\n// When the user login, setup all variables that you need\n\nfunction get_user_informations( $redirect_to, $request, $user ) {\n //is there a user to check?\n if ( $user ) {\n $user_id = $user-&gt;id;\n\n $loc_statuss = $wpdb-&gt;get_row( \"SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=\".$user_id );\n $loc_status = $loc_statuss-&gt;status;\n\n }\n}\n\nadd_filter( 'login_redirect', 'get_user_informations', 10, 3 );\n</code></pre>\n\n<p>More about <code>login_redirect</code> in the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect\" rel=\"nofollow noreferrer\">Docs</a>.</p>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276179", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110675/" ]
I want to get the current user id from inside my plugin and use it as a variable. My code is ``` $current_user = wp_get_current_user(); $user_id = $current_user->ID; $loc_statuss = $wpdb->get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=$user_id" ); $loc_status = $loc_statuss->status; ``` I have found a couple of questions the same but these answers don't seem to work for me. Thanks
If you want current user id only then use get\_current\_user\_id. because it reduce execution time. get\_current\_user\_id get only current user id where wp\_get\_current\_user get all user data. Else every things is perfect. ``` $user_id = get_current_user_id(); $loc_statuss = $wpdb->get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=".$user_id ); $loc_status = $loc_statuss->status; ```
276,197
<p>Here's my challenge...</p> <p>I have 52 pages that require a full width background image that will be rendered via a .css style..</p> <p>So, what I will know are all the Page ID Numbers. The below code I believe is a tidy way of doing what I am trying to achieve.</p> <p>My question is, rather than have 52 instances of the below code, is it possible to simply place all Page ID's and <code>$classes</code> of 'css' separated by commas?</p> <pre><code>add_filter('body_class','wpsites_specific_page_body_class'); /** * @author Brad Dalton - WP Sites * * @link http://wpsites.net/web-design/style-images-custom-body-class/ */ function wpsites_specific_page_body_class($classes) { if(is_page('007') ) { $classes[] = 'demo-class'; return $classes; } } </code></pre> <p>Thank you for all direction.</p>
[ { "answer_id": 276202, "author": "Tom Webb", "author_id": 92615, "author_profile": "https://wordpress.stackexchange.com/users/92615", "pm_score": 0, "selected": false, "text": "<p>Try this.</p>\n\n<pre><code>function wpsites_specific_page_body_class($classes) {\n global $post;\n $posts = [7=&gt;'demo-class',8=&gt;'another-class']\n if (array_key_exists($post-&gt;ID,$posts))\n $classes[] = $posts[$post-&gt;ID];\n return $classes;\n }\n }\n</code></pre>\n\n<p>You can add any number of posts to the $posts array. It will set the class assigned to the post id.</p>\n" }, { "answer_id": 276203, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I would consider making it more flexible by <strong>marking</strong> the pages in question with post meta or custom taxonomy. That way you don't need to change a PHP code to choose what pages should have some custom look. </p>\n\n<p>Here's an example, if we mark the pages with the <code>wpse-layout</code> custom field with the value <code>1</code> (assuming there could be more layout options):</p>\n\n<pre><code>add_filter( 'body_class', function( $classes )\n{\n // Only target pages\n if( ! is_page() )\n return $classes;\n\n // Get the 'wpse_layout' post meta value for the current page\n $layout = get_post_meta( get_queried_object_id(), 'wpse_layout', true );\n\n if( empty( $layout ) )\n return $classes;\n\n // Inject the 'wpse-layout-1' body class, \n // if the custom field 'wpse-layout' has the value 1\n $classes[] = sprintf( 'wpse-layout-%d', $layout );\n\n return $classes;\n\n} );\n</code></pre>\n\n<p>This could be further adjusted in various ways, e.g. with some custom UI.</p>\n" }, { "answer_id": 276206, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>first get all page id <a href=\"https://codex.wordpress.org/Function_Reference/get_all_page_ids\" rel=\"nofollow noreferrer\">click here for more inforamtion</a> </p>\n\n<pre><code>add_filter('body_class','wpsites_specific_page_body_class');\n/**\n* @author Brad Dalton - WP Sites\n*\n* @link http://wpsites.net/web-design/style-images-custom-body-class/\n*/\nfunction wpsites_specific_page_body_class($classes) {\n $page_ids= get_all_page_ids();\n if(is_page($page_ids) ) {\n $classes[] = 'demo-class';\nreturn $classes;\n }\n}\n</code></pre>\n" }, { "answer_id": 276240, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>I would certainly go with Birgir's answer, it's the right approach. But since you asked, what you want to do can be done by using an array.</p>\n\n<p>Store your page IDs in an array, and then do a conditional:</p>\n\n<pre><code>$ids = array( '1', '23', '53', '99' ... '1001' );\nif( is_page( $ids ) ) {\n // Your code here\n}\n</code></pre>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a> function accepts either an integer, a string or an array.</p>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276197", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
Here's my challenge... I have 52 pages that require a full width background image that will be rendered via a .css style.. So, what I will know are all the Page ID Numbers. The below code I believe is a tidy way of doing what I am trying to achieve. My question is, rather than have 52 instances of the below code, is it possible to simply place all Page ID's and `$classes` of 'css' separated by commas? ``` add_filter('body_class','wpsites_specific_page_body_class'); /** * @author Brad Dalton - WP Sites * * @link http://wpsites.net/web-design/style-images-custom-body-class/ */ function wpsites_specific_page_body_class($classes) { if(is_page('007') ) { $classes[] = 'demo-class'; return $classes; } } ``` Thank you for all direction.
I would consider making it more flexible by **marking** the pages in question with post meta or custom taxonomy. That way you don't need to change a PHP code to choose what pages should have some custom look. Here's an example, if we mark the pages with the `wpse-layout` custom field with the value `1` (assuming there could be more layout options): ``` add_filter( 'body_class', function( $classes ) { // Only target pages if( ! is_page() ) return $classes; // Get the 'wpse_layout' post meta value for the current page $layout = get_post_meta( get_queried_object_id(), 'wpse_layout', true ); if( empty( $layout ) ) return $classes; // Inject the 'wpse-layout-1' body class, // if the custom field 'wpse-layout' has the value 1 $classes[] = sprintf( 'wpse-layout-%d', $layout ); return $classes; } ); ``` This could be further adjusted in various ways, e.g. with some custom UI.
276,230
<p>Having read elsewhere on Stack of two WP plugins forcing identical menu positions (with the likelihood of one then not appearing), I'm wondering how I can control the position of menu items added by plugins.</p> <p>I already use a function which seems to handle such submenu items in 'settings', and another function to reorder default (posts, pages, themes, plugins, settings, etcetera) 'top level' items - but which doesn't change the positioning of such items added by plugins.</p> <pre><code>function custom_menu_order() { return array( //Add items here in desired order. ); } add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', 'custom_menu_order' ); </code></pre> <p>As an example, of the two top-level menu items added by WooCommerce, one appears above the item added by ContactForm7 and the other below, and it'd be nice to reorder them accordingly - and also, to be able to better reorder items which don't force a menu position and instead appear at the bottom.</p> <p>I find it usually works fine for re-ordering default and 'edit.php?post_type=...' items, but those with 'admin.php?page=...' don't re-order.</p> <p>When my re-order function is disabled, the two WooCommerce items ('edit.php?post_type=product', and 'edit.php?post_type=shop_order') group together as intended, but when the function is reactivated they're split by ContactForm7 ('admin.php?page=wpcf7').</p> <p>And, one ('edit.php?post_type=shop_order') of the WooCommerce CPTs won't reorder - although the other ('edit.php?post_type=product') does.</p>
[ { "answer_id": 276248, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 4, "selected": false, "text": "<p>when you're creating a post type with register_post_type() you can set the menu position:</p>\n\n<blockquote>\n <p>menu_position\n (integer) (optional) The position in the menu order the post type should appear. show_in_menu must be true.</p>\n\n<pre><code> Default: null - defaults to below Comments \n\n 5 - below Posts\n 10 - below Media\n 15 - below Links\n 20 - below Pages\n 25 - below comments\n 60 - below first separator\n 65 - below Plugins\n 70 - below Users\n 75 - below Tools\n 80 - below Settings\n 100 - below second separator\n</code></pre>\n</blockquote>\n\n<p>If items have the same menu position they are sorted alphabetically.</p>\n\n<p>in your own plugin you can set the level. if you're trying to change the menu position of a plugin you haven't created, many of them may have it pluggable, or you can to edit their calls.</p>\n" }, { "answer_id": 276249, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 5, "selected": true, "text": "<p>To change top level admin menu items order you'll need two <code>hooks</code>, two <code>filters</code>, and one <code>function</code>. Put the following code in your current theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_custom_menu_order( $menu_ord ) {\n if ( !$menu_ord ) return true;\n\n return array(\n 'index.php', // Dashboard\n 'separator1', // First separator\n 'edit.php', // Posts\n 'upload.php', // Media\n 'link-manager.php', // Links\n 'edit-comments.php', // Comments\n 'edit.php?post_type=page', // Pages\n 'separator2', // Second separator\n 'themes.php', // Appearance\n 'plugins.php', // Plugins\n 'users.php', // Users\n 'tools.php', // Tools\n 'options-general.php', // Settings\n 'separator-last', // Last separator\n );\n}\nadd_filter( 'custom_menu_order', 'wpse_custom_menu_order', 10, 1 );\nadd_filter( 'menu_order', 'wpse_custom_menu_order', 10, 1 );\n</code></pre>\n\n<p>The returned array of top level admin menu items, above, represents menu items inserted by core, in their default order. To include menu items added by plugins, we have to add them to this array. Let's say we have two plugins added and activated ( for example: <code>Wordfence</code> and <code>NextCellent Gallery</code> ). We have to find names of these menu items, first. When we click on <code>Wordfence</code>'s top level menu item, the resulting URL will end with <code>?page=Wordfence</code>. The part after <code>?page=</code> is our name ( <code>Wordfence</code> ). For <code>NextCellent Gallery</code>, the name will be <code>nextcellent-gallery-nextgen-legacy</code>. Now, let's add these items to our array:</p>\n\n<pre><code>return array(\n 'index.php', // Dashboard\n 'separator1', // First separator\n 'edit.php', // Posts\n 'upload.php', // Media\n 'link-manager.php', // Links\n 'edit-comments.php', // Comments\n 'edit.php?post_type=page', // Pages\n 'separator2', // Second separator\n 'themes.php', // Appearance\n 'plugins.php', // Plugins\n 'users.php', // Users\n 'tools.php', // Tools\n 'separator3', // Third separator\n 'options-general.php', // Settings\n 'separator-last', // Last separator\n 'Wordfence', // Wordfence\n 'nextcellent-gallery-nextgen-legacy', // NextCellent Gallery\n);\n</code></pre>\n\n<p>We can, now, move items of this array, up and down, to get the final order.</p>\n\n<p><strong>Note</strong>: you can use <a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"noreferrer\">Admin Menu Editor</a> plugin, for easy drag and drop actions, as well. </p>\n" }, { "answer_id": 315621, "author": "rassoh", "author_id": 18713, "author_profile": "https://wordpress.stackexchange.com/users/18713", "pm_score": 4, "selected": false, "text": "<p>The existing answers are fine, but if you would add a new custom post type, you would have to re-edit those functions again and again. </p>\n\n<p>To fix this, I developed this small function. Just define your <code>$new_positions</code> inside the <code>my_new_menu_order</code> function:</p>\n\n<pre><code>/**\n * Activates the 'menu_order' filter and then hooks into 'menu_order'\n */\nadd_filter('custom_menu_order', function() { return true; });\nadd_filter('menu_order', 'my_new_admin_menu_order');\n/**\n * Filters WordPress' default menu order\n */\nfunction my_new_admin_menu_order( $menu_order ) {\n // define your new desired menu positions here\n // for example, move 'upload.php' to position #9 and built-in pages to position #1\n $new_positions = array(\n 'upload.php' =&gt; 9,\n 'edit.php?post_type=page' =&gt; 1\n );\n // helper function to move an element inside an array\n function move_element(&amp;$array, $a, $b) {\n $out = array_splice($array, $a, 1);\n array_splice($array, $b, 0, $out);\n }\n // traverse through the new positions and move \n // the items if found in the original menu_positions\n foreach( $new_positions as $value =&gt; $new_index ) {\n if( $current_index = array_search( $value, $menu_order ) ) {\n move_element($menu_order, $current_index, $new_index);\n }\n }\n return $menu_order;\n};\n</code></pre>\n" }, { "answer_id": 372063, "author": "eCommerce Phil", "author_id": 192436, "author_profile": "https://wordpress.stackexchange.com/users/192436", "pm_score": 1, "selected": false, "text": "<p>Thanks to rassoh for a nice option.</p>\n<p>Here is a revised version that contains a list of pages that should probably always stay at the top...</p>\n<pre><code>/**\n * These 2 filters and 1 function move the built in WordPress admin pages to\n * the top so they don't get pushed down the menu every time a new plugin is installed.\n * Activates the 'menu_order' filter and then hooks into 'menu_order'\n */\nadd_filter('custom_menu_order', function() { return true; });\nadd_filter('menu_order', 'my_new_admin_menu_order');\n/**\n * Filters WordPress' default menu order\n */\nfunction my_new_admin_menu_order( $menu_order ) {\n // define your new desired menu positions here\n // for example, move 'upload.php' to position #9 and built-in pages to position #1\n $new_positions = array(\n 'index.php' =&gt; 1, // Dashboard\n 'edit.php' =&gt; 2, // Posts\n 'upload.php' =&gt; 3, // Media\n 'edit.php?post_type=page' =&gt; 4, // Pages\n 'edit-comments.php' =&gt; 5 // Comments\n );\n // helper function to move an element inside an array\n function move_element(&amp;$array, $a, $b) {\n $out = array_splice($array, $a, 1);\n array_splice($array, $b, 0, $out);\n }\n // traverse through the new positions and move \n // the items if found in the original menu_positions\n foreach( $new_positions as $value =&gt; $new_index ) {\n if( $current_index = array_search( $value, $menu_order ) ) {\n move_element($menu_order, $current_index, $new_index);\n }\n }\n return $menu_order;\n};\n</code></pre>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
Having read elsewhere on Stack of two WP plugins forcing identical menu positions (with the likelihood of one then not appearing), I'm wondering how I can control the position of menu items added by plugins. I already use a function which seems to handle such submenu items in 'settings', and another function to reorder default (posts, pages, themes, plugins, settings, etcetera) 'top level' items - but which doesn't change the positioning of such items added by plugins. ``` function custom_menu_order() { return array( //Add items here in desired order. ); } add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', 'custom_menu_order' ); ``` As an example, of the two top-level menu items added by WooCommerce, one appears above the item added by ContactForm7 and the other below, and it'd be nice to reorder them accordingly - and also, to be able to better reorder items which don't force a menu position and instead appear at the bottom. I find it usually works fine for re-ordering default and 'edit.php?post\_type=...' items, but those with 'admin.php?page=...' don't re-order. When my re-order function is disabled, the two WooCommerce items ('edit.php?post\_type=product', and 'edit.php?post\_type=shop\_order') group together as intended, but when the function is reactivated they're split by ContactForm7 ('admin.php?page=wpcf7'). And, one ('edit.php?post\_type=shop\_order') of the WooCommerce CPTs won't reorder - although the other ('edit.php?post\_type=product') does.
To change top level admin menu items order you'll need two `hooks`, two `filters`, and one `function`. Put the following code in your current theme's `functions.php`: ``` function wpse_custom_menu_order( $menu_ord ) { if ( !$menu_ord ) return true; return array( 'index.php', // Dashboard 'separator1', // First separator 'edit.php', // Posts 'upload.php', // Media 'link-manager.php', // Links 'edit-comments.php', // Comments 'edit.php?post_type=page', // Pages 'separator2', // Second separator 'themes.php', // Appearance 'plugins.php', // Plugins 'users.php', // Users 'tools.php', // Tools 'options-general.php', // Settings 'separator-last', // Last separator ); } add_filter( 'custom_menu_order', 'wpse_custom_menu_order', 10, 1 ); add_filter( 'menu_order', 'wpse_custom_menu_order', 10, 1 ); ``` The returned array of top level admin menu items, above, represents menu items inserted by core, in their default order. To include menu items added by plugins, we have to add them to this array. Let's say we have two plugins added and activated ( for example: `Wordfence` and `NextCellent Gallery` ). We have to find names of these menu items, first. When we click on `Wordfence`'s top level menu item, the resulting URL will end with `?page=Wordfence`. The part after `?page=` is our name ( `Wordfence` ). For `NextCellent Gallery`, the name will be `nextcellent-gallery-nextgen-legacy`. Now, let's add these items to our array: ``` return array( 'index.php', // Dashboard 'separator1', // First separator 'edit.php', // Posts 'upload.php', // Media 'link-manager.php', // Links 'edit-comments.php', // Comments 'edit.php?post_type=page', // Pages 'separator2', // Second separator 'themes.php', // Appearance 'plugins.php', // Plugins 'users.php', // Users 'tools.php', // Tools 'separator3', // Third separator 'options-general.php', // Settings 'separator-last', // Last separator 'Wordfence', // Wordfence 'nextcellent-gallery-nextgen-legacy', // NextCellent Gallery ); ``` We can, now, move items of this array, up and down, to get the final order. **Note**: you can use [Admin Menu Editor](https://wordpress.org/plugins/admin-menu-editor/) plugin, for easy drag and drop actions, as well.
276,232
<p>My child theme customizer is not working. I have created a child theme from the parent theme called flash. In the parent theme I can use the customizer just fine and change the layout ect. However, when I activate my child theme nothing in in my customizer working in terms of layout.I feel like the issue lies in my style.css comment. I have researched this and everyone kept saying that it had to do with plugins so I deactivated and activated those one by one and nothing was wrong. So I think it has to do with how I am linking the child theme. I am new to child themes so maybe I'm way off by thinking it has anything to do with the style.css comment, but if someone has any idea why please let me know.</p> <p>Here is an example of the comment that I had to put in the style.css. I'll include the author of the flash theme's comment in as well. </p> <p>My child theme style.css comment: </p> <pre><code>/* Theme Name: flash-child Theme URI: https://mywebsite.com/flash-child Author: me Author URI: https://mywebsite.com/flash-child Description: Flash is free responsive multipurpose WordPress theme – truly a versatile theme perfect for any type of website you want. Like never before, it provides multiple pre-built demos which can be imported in seconds using ThemeGrill Demo Importer Plugin. The theme fully integrates with Flash Toolkit and SiteOrigin’s Page Builder Plugin that makes theme more user- friendly and easy. Additionally, theme features multiple blog layouts, WooCommerce support, multiple header styles, multiple color options etc. Version: 1.1.3 License: GNU General Public License v3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Text Domain: flash Template: flash Tags: one-column, two-columns, left-sidebar, right-sidebar, grid-layout, custom-background, custom-colors, custom-menu, custom-logo, featured-images, footer-widgets, full-width-template, theme-options, threaded-comments, translation-ready, blog, e-commerce Flash is based on Underscores http://underscores.me/, (C) 2012-2016 Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2 or later. Normalizing styles have been helped along thanks to the fine work of Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/ */ </code></pre> <p>Flash (parent) theme comment in style.css:</p> <pre><code>/* Theme Name: Flash Theme URI: https://themegrill.com/themes/flash Author: ThemeGrill Author URI: https://themegrill.com Description: Flash is free responsive multipurpose WordPress theme – truly a versatile theme perfect for any type of website you want. Like never before, it provides multiple pre-built demos which can be imported in seconds using ThemeGrill Demo Importer Plugin. The theme fully integrates with Flash Toolkit and SiteOrigin’s Page Builder Plugin that makes theme more user- friendly and easy. Additionally, theme features multiple blog layouts, WooCommerce support, multiple header styles, multiple color options etc. Version: 1.1.3 License: GNU General Public License v3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Text Domain: flash Tags: one-column, two-columns, left-sidebar, right-sidebar, grid-layout, custom-background, custom-colors, custom-menu, custom-logo, featured-images, footer-widgets, full-width-template, theme-options, threaded-comments, translation-ready, blog, e-commerce Flash is based on Underscores http://underscores.me/, (C) 2012-2016 Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2 or later. Normalizing styles have been helped along thanks to the fine work of Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/ */ </code></pre>
[ { "answer_id": 276234, "author": "Cakers", "author_id": 125497, "author_profile": "https://wordpress.stackexchange.com/users/125497", "pm_score": 1, "selected": false, "text": "<p>I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. </p>\n\n<pre><code>&lt;?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the \nTwenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . \n'/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?&gt;\n</code></pre>\n" }, { "answer_id": 302742, "author": "user0815", "author_id": 106623, "author_profile": "https://wordpress.stackexchange.com/users/106623", "pm_score": 0, "selected": false, "text": "<p>In addition to the above, make sure to update the version number in your style.css file when updating its content. It seems that customizer caches the CSS and will not update it when it has the old version number (even though the site will work fine).</p>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276232", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125497/" ]
My child theme customizer is not working. I have created a child theme from the parent theme called flash. In the parent theme I can use the customizer just fine and change the layout ect. However, when I activate my child theme nothing in in my customizer working in terms of layout.I feel like the issue lies in my style.css comment. I have researched this and everyone kept saying that it had to do with plugins so I deactivated and activated those one by one and nothing was wrong. So I think it has to do with how I am linking the child theme. I am new to child themes so maybe I'm way off by thinking it has anything to do with the style.css comment, but if someone has any idea why please let me know. Here is an example of the comment that I had to put in the style.css. I'll include the author of the flash theme's comment in as well. My child theme style.css comment: ``` /* Theme Name: flash-child Theme URI: https://mywebsite.com/flash-child Author: me Author URI: https://mywebsite.com/flash-child Description: Flash is free responsive multipurpose WordPress theme – truly a versatile theme perfect for any type of website you want. Like never before, it provides multiple pre-built demos which can be imported in seconds using ThemeGrill Demo Importer Plugin. The theme fully integrates with Flash Toolkit and SiteOrigin’s Page Builder Plugin that makes theme more user- friendly and easy. Additionally, theme features multiple blog layouts, WooCommerce support, multiple header styles, multiple color options etc. Version: 1.1.3 License: GNU General Public License v3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Text Domain: flash Template: flash Tags: one-column, two-columns, left-sidebar, right-sidebar, grid-layout, custom-background, custom-colors, custom-menu, custom-logo, featured-images, footer-widgets, full-width-template, theme-options, threaded-comments, translation-ready, blog, e-commerce Flash is based on Underscores http://underscores.me/, (C) 2012-2016 Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2 or later. Normalizing styles have been helped along thanks to the fine work of Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/ */ ``` Flash (parent) theme comment in style.css: ``` /* Theme Name: Flash Theme URI: https://themegrill.com/themes/flash Author: ThemeGrill Author URI: https://themegrill.com Description: Flash is free responsive multipurpose WordPress theme – truly a versatile theme perfect for any type of website you want. Like never before, it provides multiple pre-built demos which can be imported in seconds using ThemeGrill Demo Importer Plugin. The theme fully integrates with Flash Toolkit and SiteOrigin’s Page Builder Plugin that makes theme more user- friendly and easy. Additionally, theme features multiple blog layouts, WooCommerce support, multiple header styles, multiple color options etc. Version: 1.1.3 License: GNU General Public License v3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Text Domain: flash Tags: one-column, two-columns, left-sidebar, right-sidebar, grid-layout, custom-background, custom-colors, custom-menu, custom-logo, featured-images, footer-widgets, full-width-template, theme-options, threaded-comments, translation-ready, blog, e-commerce Flash is based on Underscores http://underscores.me/, (C) 2012-2016 Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2 or later. Normalizing styles have been helped along thanks to the fine work of Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/ */ ```
I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. ``` <?php function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ```
276,253
<p>I have a forum system where I created a custom post type, and I would like to have a search system for the topics, but I do not know what the structure would be, for example, how the file will be and the search form action.</p>
[ { "answer_id": 276234, "author": "Cakers", "author_id": 125497, "author_profile": "https://wordpress.stackexchange.com/users/125497", "pm_score": 1, "selected": false, "text": "<p>I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. </p>\n\n<pre><code>&lt;?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the \nTwenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . \n'/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?&gt;\n</code></pre>\n" }, { "answer_id": 302742, "author": "user0815", "author_id": 106623, "author_profile": "https://wordpress.stackexchange.com/users/106623", "pm_score": 0, "selected": false, "text": "<p>In addition to the above, make sure to update the version number in your style.css file when updating its content. It seems that customizer caches the CSS and will not update it when it has the old version number (even though the site will work fine).</p>\n" } ]
2017/08/08
[ "https://wordpress.stackexchange.com/questions/276253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124171/" ]
I have a forum system where I created a custom post type, and I would like to have a search system for the topics, but I do not know what the structure would be, for example, how the file will be and the search form action.
I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. ``` <?php function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ```
276,293
<p>I'm working on a website now and then I want to transfer to other domain. But all I want to transfer is the WordPress Theme and content not included the plugins </p> <p>Is this possible? If yes how?</p> <p>Thanks.</p>
[ { "answer_id": 276234, "author": "Cakers", "author_id": 125497, "author_profile": "https://wordpress.stackexchange.com/users/125497", "pm_score": 1, "selected": false, "text": "<p>I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. </p>\n\n<pre><code>&lt;?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the \nTwenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . \n'/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?&gt;\n</code></pre>\n" }, { "answer_id": 302742, "author": "user0815", "author_id": 106623, "author_profile": "https://wordpress.stackexchange.com/users/106623", "pm_score": 0, "selected": false, "text": "<p>In addition to the above, make sure to update the version number in your style.css file when updating its content. It seems that customizer caches the CSS and will not update it when it has the old version number (even though the site will work fine).</p>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122942/" ]
I'm working on a website now and then I want to transfer to other domain. But all I want to transfer is the WordPress Theme and content not included the plugins Is this possible? If yes how? Thanks.
I realize that I did not know that you needed an extra step for the functions.php. Here is the last step I needed. ``` <?php function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ```
276,298
<p>I added a function that will return the allowed html tags array</p> <pre><code>if ( ! function_exists( 'allowed_html_tags' ) ) { /** * Allowed html tags for wp_kses() function * * @return array Array of allowed html tags. */ function allowed_html_tags() { return array( 'a' =&gt; array( 'href' =&gt; array(), 'title' =&gt; array(), 'class' =&gt; array(), 'data' =&gt; array(), 'rel' =&gt; array(), ), 'br' =&gt; array(), 'em' =&gt; array(), 'ul' =&gt; array( 'class' =&gt; array(), ), 'ol' =&gt; array( 'class' =&gt; array(), ), 'li' =&gt; array( 'class' =&gt; array(), ), 'strong' =&gt; array(), 'div' =&gt; array( 'class' =&gt; array(), 'data' =&gt; array(), 'style' =&gt; array(), ), 'span' =&gt; array( 'class' =&gt; array(), 'style' =&gt; array(), ), 'img' =&gt; array( 'alt' =&gt; array(), 'class' =&gt; array(), 'height' =&gt; array(), 'src' =&gt; array(), 'width' =&gt; array(), ), 'select' =&gt; array( 'id' =&gt; array(), 'class' =&gt; array(), 'name' =&gt; array(), ), 'option' =&gt; array( 'value' =&gt; array(), 'selected' =&gt; array(), ), ); } } </code></pre> <p>But when I have html in a variable that is populated in a <code>foreach</code> loop, my <code>data</code> attributes get stripped out.</p> <pre><code>$my_var = '&lt;div class=&quot;my-class&quot; data-term=&quot;$term_id&quot;&gt;$content&lt;/div&gt;'; wp_kses( $my_var, allowed_html_tags() ); </code></pre> <p>This will return</p> <pre><code>&lt;div class=&quot;my-class&quot;&gt;This is my content... no data attribute...&lt;/div&gt; </code></pre> <p>I tried modifying my array to have <code>data-*</code> but that didn't work.</p> <p>I hope that you don't have to modify the allowed array with the full data name (<code>data-term</code>) for this to work...</p> <h3>EDIT</h3> <p>Check <a href="https://wordpress.stackexchange.com/a/324922/58895">Matt Thomason's</a> answer about the update to the kses data.</p>
[ { "answer_id": 276301, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I hope that you don't have to modify the allowed array with the full data name (data-term) for this to work...</p>\n</blockquote>\n\n<p>It appears to be that way. <code>data-term</code> and <code>data</code> aren't the same attribute after all, and poking around in core I don't think any sort of regular expressions can be used as supported attributes.</p>\n\n<p>You shouldn't need to run <code>wp_kses()</code> on your own markup though, you should know it's safe. <code>wp_kses()</code> is generally just for handling untrusted input from users. Are users going to be submitting data- attributes, and you need to support them all?</p>\n\n<p>You could do something like this instead:</p>\n\n<pre><code>$my_var = '&lt;div class=\"my-class\" data-term=\"' . esc_attr( $term_id ) . '\"&gt;' . wp_kses_post( $content ) . '&lt;/div&gt;';\n</code></pre>\n\n<p>That uses <code>wp_kses_post()</code> which will use the default allowed html for posts, but it's only going to apply to whatever <code>$content</code> is.</p>\n" }, { "answer_id": 324922, "author": "Matt Thomason", "author_id": 158547, "author_profile": "https://wordpress.stackexchange.com/users/158547", "pm_score": 3, "selected": false, "text": "<p>Update for anyone coming here post-Dec 2018:</p>\n\n<p>data-* is now supported in KSES filters, since this commit - <a href=\"https://github.com/markjaquith/WordPress/commit/a0309e80b6a4d805e4f230649be07b4bfb1a56a5#diff-a0e0d196dd71dde453474b0f791828fe\" rel=\"noreferrer\">https://github.com/markjaquith/WordPress/commit/a0309e80b6a4d805e4f230649be07b4bfb1a56a5#diff-a0e0d196dd71dde453474b0f791828fe</a></p>\n\n<p>So you can now do something like this:</p>\n\n<pre><code>add_filter('wp_kses_allowed_html', \"kses_filter_allowed_html\"));\n\nfunction kses_filter_allowed_html( $allowed, $context )\n{\n if (is_array($context))\n {\n return $allowed;\n }\n\n if ($context === 'post')\n {\n $allowed['a']['data-*'] = true;\n $allowed['table']['data-*'] = true; \n // ... keep on doing these for each HTML entity you want to allow data- attributes on\n }\n\n return $allowed;\n}\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I added a function that will return the allowed html tags array ``` if ( ! function_exists( 'allowed_html_tags' ) ) { /** * Allowed html tags for wp_kses() function * * @return array Array of allowed html tags. */ function allowed_html_tags() { return array( 'a' => array( 'href' => array(), 'title' => array(), 'class' => array(), 'data' => array(), 'rel' => array(), ), 'br' => array(), 'em' => array(), 'ul' => array( 'class' => array(), ), 'ol' => array( 'class' => array(), ), 'li' => array( 'class' => array(), ), 'strong' => array(), 'div' => array( 'class' => array(), 'data' => array(), 'style' => array(), ), 'span' => array( 'class' => array(), 'style' => array(), ), 'img' => array( 'alt' => array(), 'class' => array(), 'height' => array(), 'src' => array(), 'width' => array(), ), 'select' => array( 'id' => array(), 'class' => array(), 'name' => array(), ), 'option' => array( 'value' => array(), 'selected' => array(), ), ); } } ``` But when I have html in a variable that is populated in a `foreach` loop, my `data` attributes get stripped out. ``` $my_var = '<div class="my-class" data-term="$term_id">$content</div>'; wp_kses( $my_var, allowed_html_tags() ); ``` This will return ``` <div class="my-class">This is my content... no data attribute...</div> ``` I tried modifying my array to have `data-*` but that didn't work. I hope that you don't have to modify the allowed array with the full data name (`data-term`) for this to work... ### EDIT Check [Matt Thomason's](https://wordpress.stackexchange.com/a/324922/58895) answer about the update to the kses data.
> > I hope that you don't have to modify the allowed array with the full data name (data-term) for this to work... > > > It appears to be that way. `data-term` and `data` aren't the same attribute after all, and poking around in core I don't think any sort of regular expressions can be used as supported attributes. You shouldn't need to run `wp_kses()` on your own markup though, you should know it's safe. `wp_kses()` is generally just for handling untrusted input from users. Are users going to be submitting data- attributes, and you need to support them all? You could do something like this instead: ``` $my_var = '<div class="my-class" data-term="' . esc_attr( $term_id ) . '">' . wp_kses_post( $content ) . '</div>'; ``` That uses `wp_kses_post()` which will use the default allowed html for posts, but it's only going to apply to whatever `$content` is.
276,303
<p>I am trying to change the stylesheet file version using the <code>filemtime()</code> function with the <code>wp_enqueue_style</code> with the following snippet</p> <pre><code>function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory_uri() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); </code></pre> <p>but it is throwing a warning </p> <blockquote> <p>Warning: filemtime(): stat failed for.....</p> </blockquote> <p>While i am sure that the file exists</p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102224/" ]
I am trying to change the stylesheet file version using the `filemtime()` function with the `wp_enqueue_style` with the following snippet ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory_uri() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ``` but it is throwing a warning > > Warning: filemtime(): stat failed for..... > > > While i am sure that the file exists
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,304
<p>I have created a custom taxonomy brands and added some brands to various posts. I also created a file called taxonomy-brands.php and it seems to be working fine. If I visit www.domain.com/brands/adidas then I can see all the adidas branded posts.</p> <p>However when I visit www.domain.com/brands/ I receive a 404 error. I would like this page to show all the available brands. (adidas, nike, asics etc)</p> <p>Please help Richard</p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27593/" ]
I have created a custom taxonomy brands and added some brands to various posts. I also created a file called taxonomy-brands.php and it seems to be working fine. If I visit www.domain.com/brands/adidas then I can see all the adidas branded posts. However when I visit www.domain.com/brands/ I receive a 404 error. I would like this page to show all the available brands. (adidas, nike, asics etc) Please help Richard
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,317
<p>I'm using WordPress social login plugin shortcode <code>[wordpress_social_login]</code>. I want to put it in custom template file inside theme directory.</p> <p>example:</p> <pre><code>&lt;?php /* Template Name: Social Login Page */ echo do_shortcode('[wordpress_social_login]'); </code></pre> <p>so I create a blank page using this template, the rendering is ok but the button href become <code>javascript:void(0);</code> and it won't redirect.</p> <p>i can't figure this out, so please help..</p> <p>Thanks</p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276317", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107171/" ]
I'm using WordPress social login plugin shortcode `[wordpress_social_login]`. I want to put it in custom template file inside theme directory. example: ``` <?php /* Template Name: Social Login Page */ echo do_shortcode('[wordpress_social_login]'); ``` so I create a blank page using this template, the rendering is ok but the button href become `javascript:void(0);` and it won't redirect. i can't figure this out, so please help.. Thanks
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,325
<p>I've been editing a few pages including the URLs. Should I have kept these pages and made a new one and then redirected, or is it fine to just redirect a page that doesn't exist anymore?.</p> <p>Thanks, Andy.</p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125547/" ]
I've been editing a few pages including the URLs. Should I have kept these pages and made a new one and then redirected, or is it fine to just redirect a page that doesn't exist anymore?. Thanks, Andy.
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,343
<p>I created a Forum plugin and would like to have a cystomized search result template, I added the following excerpt in the plugin execution file:</p> <pre><code>add_filter('single_template', 'pagina_topicos'); function pagina_topicos($single) { global $wp_query, $post; /* Informando o Modelo de Página das Aulas */ if ($post-&gt;post_type == "stopicos"){ if(file_exists(plugin_dir_path( __FILE__ ) . '/single-topico.php')) return plugin_dir_path( __FILE__ ) . '/single-topico.php'; } if( $wp_query-&gt;is_search &amp;&amp; $post_type == 'stopicos' ) { return plugin_dir_path( __FILE__ ) . '/archive-stopicos.php'; } return $single; } </code></pre> <p>I use the following form in the search:</p> <pre><code> &lt;form role="search" action="&lt;?php echo site_url('/'); ?&gt;" method="get" id="searchform"&gt; &lt;input type="text" class="submit-search form-control input-lg" placeholder="Buscar" /&gt; &lt;input type="hidden" name="post_type" value="stopicos"/&gt; &lt;span class="input-group-btn"&gt; &lt;button class="btn btn-info btn-lg" type="submit" value="Search"&gt; &lt;i class="glyphicon glyphicon-search"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/form&gt; </code></pre> <p>What can be wrong so that the model I customized is not loaded?</p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124171/" ]
I created a Forum plugin and would like to have a cystomized search result template, I added the following excerpt in the plugin execution file: ``` add_filter('single_template', 'pagina_topicos'); function pagina_topicos($single) { global $wp_query, $post; /* Informando o Modelo de Página das Aulas */ if ($post->post_type == "stopicos"){ if(file_exists(plugin_dir_path( __FILE__ ) . '/single-topico.php')) return plugin_dir_path( __FILE__ ) . '/single-topico.php'; } if( $wp_query->is_search && $post_type == 'stopicos' ) { return plugin_dir_path( __FILE__ ) . '/archive-stopicos.php'; } return $single; } ``` I use the following form in the search: ``` <form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <input type="text" class="submit-search form-control input-lg" placeholder="Buscar" /> <input type="hidden" name="post_type" value="stopicos"/> <span class="input-group-btn"> <button class="btn btn-info btn-lg" type="submit" value="Search"> <i class="glyphicon glyphicon-search"></i> </button> </form> ``` What can be wrong so that the model I customized is not loaded?
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,396
<p>My Seach Page URLs: </p> <blockquote> <p><a href="https://www.example.com/search/keyword/page/2/" rel="nofollow noreferrer">https://www.example.com/search/keyword/page/2/</a></p> </blockquote> <p>Here my custom search page:</p> <pre><code>&lt;?php if($_GET['search_text'] &amp;&amp; !empty($_GET['search_text'])) { $text = $_GET['search_text']; } else { $text = urldecode( get_query_var('search_text') ) ; } ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;div class="searchpage-container"&gt; &lt;div class="searchpage-filter-container"&gt; &lt;span&gt;Arama Sonuçları:&lt;/span&gt; &lt;/div&gt; &lt;div class="product-container"&gt; &lt;?php $my_products = array( 2085, 4094, 2900, 4072, 131 ); global $paged; $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; 'product', 'posts_per_page' =&gt; 2, 'paged' =&gt; $paged, 'post__in' =&gt; $my_products ); $loop = new WP_Query( $args ); if ( $loop-&gt;have_posts() ) { while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); wc_get_template_part( 'content', 'product' ); endwhile; $total_pages = $loop-&gt;max_num_pages; if ($total_pages &gt; 1){ /* $current_page = max(1, get_query_var('paged')); */ $wp_query-&gt;query_vars['paged'] &gt; 1 ? $current_page = $wp_query-&gt;query_vars['paged'] : $current_page = 1; echo $wp_query-&gt;query_vars['paged']; echo paginate_links(array( 'base' =&gt; get_pagenum_link(1) . '%_%', 'format' =&gt; '/page/%#%', 'current' =&gt; $current_page, 'total' =&gt; $total_pages, 'prev_text' =&gt; __('« prev'), 'next_text' =&gt; __('next »'), )); } } wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; </code></pre> <p> <p>My pagination links are created fine, but I always see the page No 1 because somehow <code>query_vars['paged']</code> is emtpy. </p> <p>I have seen <code>Preserving Search Page Results and Pagination</code> section on <a href="https://codex.wordpress.org/Creating_a_Search_Page" rel="nofollow noreferrer">this page</a> , but couldn't figure it out how to use it, but I don't think this is really needed in my case.</p> <p><strong>EDIT 1 (Response to comment from J.D.):</strong></p> <p>That function you mentioned only returns an array of product IDs, to simplify my code, I removed my function add a static array instead. </p>
[ { "answer_id": 276307, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 6, "selected": true, "text": "<p>It's because you're retrieving it via URL, but <code>filemtime()</code> requires a path. Use <code>get_stylesheet_directory()</code> instead. That returns a path:</p>\n\n<pre><code>function pro_styles()\n{\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'pro_styles' );\n</code></pre>\n" }, { "answer_id": 355565, "author": "Marcin Lentner", "author_id": 180482, "author_profile": "https://wordpress.stackexchange.com/users/180482", "pm_score": 2, "selected": false, "text": "<p>Just to expand on Jacob Peattie Answer for people that have CSS file in a custom plugin, you can use</p>\n\n<pre><code>filemtime( plugin_dir_path(dirname(__FILE__)).'plugin-folder/css-file-path.css' )\n</code></pre>\n" } ]
2017/08/09
[ "https://wordpress.stackexchange.com/questions/276396", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112778/" ]
My Seach Page URLs: > > <https://www.example.com/search/keyword/page/2/> > > > Here my custom search page: ``` <?php if($_GET['search_text'] && !empty($_GET['search_text'])) { $text = $_GET['search_text']; } else { $text = urldecode( get_query_var('search_text') ) ; } ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <div class="searchpage-container"> <div class="searchpage-filter-container"> <span>Arama Sonuçları:</span> </div> <div class="product-container"> <?php $my_products = array( 2085, 4094, 2900, 4072, 131 ); global $paged; $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'product', 'posts_per_page' => 2, 'paged' => $paged, 'post__in' => $my_products ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); wc_get_template_part( 'content', 'product' ); endwhile; $total_pages = $loop->max_num_pages; if ($total_pages > 1){ /* $current_page = max(1, get_query_var('paged')); */ $wp_query->query_vars['paged'] > 1 ? $current_page = $wp_query->query_vars['paged'] : $current_page = 1; echo $wp_query->query_vars['paged']; echo paginate_links(array( 'base' => get_pagenum_link(1) . '%_%', 'format' => '/page/%#%', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __('« prev'), 'next_text' => __('next »'), )); } } wp_reset_postdata(); ?> </div> </div> </main><!-- #main --> </div><!-- #primary --> ``` My pagination links are created fine, but I always see the page No 1 because somehow `query_vars['paged']` is emtpy. I have seen `Preserving Search Page Results and Pagination` section on [this page](https://codex.wordpress.org/Creating_a_Search_Page) , but couldn't figure it out how to use it, but I don't think this is really needed in my case. **EDIT 1 (Response to comment from J.D.):** That function you mentioned only returns an array of product IDs, to simplify my code, I removed my function add a static array instead.
It's because you're retrieving it via URL, but `filemtime()` requires a path. Use `get_stylesheet_directory()` instead. That returns a path: ``` function pro_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .'/child-style.css', array(), filemtime(get_stylesheet_directory() .'/child-style.css'), 'all' ); } add_action( 'wp_enqueue_scripts', 'pro_styles' ); ```
276,407
<p>5 of my templates require specific Javascript. Currently the below works great to load Javascript into Page Template A. </p> <pre><code> add_action('wp_enqueue_scripts','css-flags'); function css-flags(){ if ( is_page_template('page-template-a.php') ) { wp_enqueue_style('css-flags', get_template_directory_uri() . '/css/flags.min.css', array(), '1.0.0', false ); } } </code></pre> <p>I thought that I could simply do the following to add the same CSS file to Template B, C and D by just adding the template name to the 'IF' variable.</p> <pre><code> add_action('wp_enqueue_scripts','css-flags'); function css-flags(){ if ( is_page_template('page-template-a.php','page-template-b.php','page-template-b.php') ) { wp_enqueue_style('css-flags', get_template_directory_uri() . '/css/flags.min.css', array(), '1.0.0', false ); } } </code></pre> <p>Thanks for all direction.</p>
[ { "answer_id": 276409, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>In PHP, <code>||</code> is the OR operator so you have to build it that way feeding <code>is_page_template()</code> a single template so your conditional will look like this:</p>\n\n<pre><code>if ( is_page_template('page-template-a.php') || is_page_template('page-template-b.php') || is_page_template('page-template-c.php') ) {\n // Code Here\n}\n</code></pre>\n" }, { "answer_id": 276410, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p><code>is_page_template</code> accepts a single argument, which can be a string or an array. You just need to pass your values as a single <code>array()</code> to make it work:</p>\n\n<pre><code>if ( is_page_template( array('page-template-a.php','page-template-b.php','page-template-b.php') ) ){\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 276412, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 1, "selected": true, "text": "<p>Page template seems like a more obscure thing to base the loading of your CSS on. Maybe not use template name, and use page name instead as it's more apparent to theme users. If interested you could try something more like this:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'load_special_page_styles');\nfunction load_special_page_styles() {\n global $post;\n\n if( is_page() ) {\n\n switch( $post-&gt;post_name ) { // post_name is actually the page slug \n case 'a-page': // if page slug is equal to 'a-page'... \n case 'b-page':\n case 'c-page':\n case 'd-page':\n case 'e-page':\n wp_enqueue_style( 'css-flags', get_stylesheet_directory_uri() . '/css/flags.min.css', array(), '1.0.0', 'all' ); // Note slight differences in use of wp_enqueue_style here\n wp_enqueue_script( 'js-flags', get_template_directory_uri() . '/js/flags.min.js', array('jquery'), '1.0.0', true ); // helpful param #2 loads jquery if not already loaded, and param #4 loads the flags.min.js script in the footer, after page content loads\n break;\n }\n } \n}\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
5 of my templates require specific Javascript. Currently the below works great to load Javascript into Page Template A. ``` add_action('wp_enqueue_scripts','css-flags'); function css-flags(){ if ( is_page_template('page-template-a.php') ) { wp_enqueue_style('css-flags', get_template_directory_uri() . '/css/flags.min.css', array(), '1.0.0', false ); } } ``` I thought that I could simply do the following to add the same CSS file to Template B, C and D by just adding the template name to the 'IF' variable. ``` add_action('wp_enqueue_scripts','css-flags'); function css-flags(){ if ( is_page_template('page-template-a.php','page-template-b.php','page-template-b.php') ) { wp_enqueue_style('css-flags', get_template_directory_uri() . '/css/flags.min.css', array(), '1.0.0', false ); } } ``` Thanks for all direction.
Page template seems like a more obscure thing to base the loading of your CSS on. Maybe not use template name, and use page name instead as it's more apparent to theme users. If interested you could try something more like this: ``` add_action('wp_enqueue_scripts', 'load_special_page_styles'); function load_special_page_styles() { global $post; if( is_page() ) { switch( $post->post_name ) { // post_name is actually the page slug case 'a-page': // if page slug is equal to 'a-page'... case 'b-page': case 'c-page': case 'd-page': case 'e-page': wp_enqueue_style( 'css-flags', get_stylesheet_directory_uri() . '/css/flags.min.css', array(), '1.0.0', 'all' ); // Note slight differences in use of wp_enqueue_style here wp_enqueue_script( 'js-flags', get_template_directory_uri() . '/js/flags.min.js', array('jquery'), '1.0.0', true ); // helpful param #2 loads jquery if not already loaded, and param #4 loads the flags.min.js script in the footer, after page content loads break; } } } ```
276,459
<p>I recently migrated my old website to this domain: <a href="https://thequintessentialmind.com/" rel="nofollow noreferrer">https://thequintessentialmind.com/</a></p> <p>It is a wordpress site and in the articles, example here: <a href="https://thequintessentialmind.com/how-to-never-run-out-of-things-to-say/" rel="nofollow noreferrer">https://thequintessentialmind.com/how-to-never-run-out-of-things-to-say/</a>, in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https.</p> <p><a href="https://i.stack.imgur.com/D2qbP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D2qbP.png" alt="enter image description here"></a></p> <p>I have difficulty locating that part of the code in any of the php files. Any ideas where could it be or which plugin is generating it?</p>
[ { "answer_id": 276464, "author": "joeDaigle", "author_id": 76766, "author_profile": "https://wordpress.stackexchange.com/users/76766", "pm_score": -1, "selected": false, "text": "<p>Have you tried clicking on the filename generating the error? Usually you will see the file/resource in the sources tab of your browser inspector.</p>\n" }, { "answer_id": 276469, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 1, "selected": true, "text": "<p>A quick squint at your site reveals that you're serving it with Nginx, so a simple <code>.htaccess</code> redirect won't work.</p>\n\n<p>The following block in your Nginx config should take care of any stray locally-served files that are still coming over http:</p>\n\n<pre><code>server {\n listen 80 default_server;\n listen [::]:80 default_server;\n server_name _;\n return 301 https://$host$request_uri;\n}\n</code></pre>\n\n<p>If you were running Apache, the following in your <code>.htaccess</code> before the WordPress section would achieve the same thing:</p>\n\n<pre><code># HTTP to HTTPS\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine on\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>The above is presented in lieu of tracking down the specific file, as the page no longer seems to be throwing the mixed content error.</p>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111649/" ]
I recently migrated my old website to this domain: <https://thequintessentialmind.com/> It is a wordpress site and in the articles, example here: <https://thequintessentialmind.com/how-to-never-run-out-of-things-to-say/>, in the console of google inspector it suggest that there is a .gif file that should be renamed from http to https. [![enter image description here](https://i.stack.imgur.com/D2qbP.png)](https://i.stack.imgur.com/D2qbP.png) I have difficulty locating that part of the code in any of the php files. Any ideas where could it be or which plugin is generating it?
A quick squint at your site reveals that you're serving it with Nginx, so a simple `.htaccess` redirect won't work. The following block in your Nginx config should take care of any stray locally-served files that are still coming over http: ``` server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://$host$request_uri; } ``` If you were running Apache, the following in your `.htaccess` before the WordPress section would achieve the same thing: ``` # HTTP to HTTPS <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </IfModule> ``` The above is presented in lieu of tracking down the specific file, as the page no longer seems to be throwing the mixed content error.
276,476
<p>I am trying to develop a plugin for basic SEO purposes, as a lot of people I know don't like using Yoast. I literally just started the plugin, and am building out the activation message displayed to the user when they activate the plugin. I am having trouble with a mix between OOP and built-in Wordpress functions, and not sure where I am going wrong.</p> <p>The only way I can get this to work, is by creating a new instance of the <em>SEO_Plugin_Activation</em> class inside my main files constructor, and then calling the activatePlugin method in that class. I feel like this is unnecessary. I also think how I am executing my functions in the activation class file don't really make much sense either. But it's the only way I can get it to work right now.</p> <p>I am not sure if what I am doing is because I am not grasping OOP techniques 100%, or if I am not utilizing Wordpress API correctly. I have included three code examples in the following order:</p> <ol> <li>Main plugin file</li> <li>Class file that handles my activation requirements</li> <li>What I really was hoping could be done.</li> </ol> <p><strong>seo.php (main plugin file)</strong></p> <pre><code>&lt;?php /* ... generic plugin info */ require_once(dirname(__FILE__) . '/admin/class-plugin-activation.php'); class SEO { function __construct() { $activate = new SEO_Plugin_Activation(); $activate-&gt;activatePlugin(); } } new SEO(); ?&gt; </code></pre> <p><strong>class-plugin-activation.php</strong></p> <pre><code>&lt;?php class SEO_Plugin_Activation { function __construct() { register_activation_hook(__FILE__ . '../seo.php', array($this, 'activatePlugin')); add_action('admin_notices', array($this, 'showSitemapInfo')); } function activatePlugin() { set_transient('show_sitemap_info', true, 5); } function showSitemapInfo() { if(get_transient('show_sitemap_info')) { echo '&lt;div class="updated notice is-dismissible"&gt;' . 'Your sitemap files can be found at these following links: ' . '&lt;/div&gt;'; delete_transient('show_sitemap_info'); } } } ?&gt; </code></pre> <p><strong>seo.php(What I was hoping for)</strong></p> <pre><code>&lt;?php /* ... blah blah blah */ require_once(dirname(__FILE__) . '/admin/class-plugin-activation.php'); class SEO { function __construct() { register_activation_hook(__FILE__, array($this, 'wp_install')); } function wp_install() { $activate = new SEO_Plugin_Activation(); // Execute some method(s) here that would take care // of all of my plugin activation bootstrapping } } new SEO(); ?&gt; </code></pre> <p>I tried doing it the way I outline in the third script, but am having no success. As of right now, the message does display properly, with no error messages.</p>
[ { "answer_id": 276478, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 2, "selected": false, "text": "<p>You really need to be registering your activation/deactivation/uninstall hooks outside of your plugin class as per <a href=\"https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/25979#25979\">kaiser's answer here</a>, which provides a much better rundown on the subject than I could write.</p>\n\n<p>That should cover you if you're looking to write this plugin as a learning exercise. If all you're looking for is an SEO plugin that works well and isn't plastered with tacky ads like Yoast, I can highly recommend The SEO Framework.</p>\n" }, { "answer_id": 276480, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 5, "selected": true, "text": "<p>Having reread your question, I think I see the issue, and it stems from a misunderstanding of how <code>register_activation_hook</code> works, combined with some confusion over how you're bootstrapping your code and what it means to bootstrap</p>\n\n<h2>Part 1: <code>register_activation_hook</code></h2>\n\n<p>This function takes 2 parameters:</p>\n\n<blockquote>\n <p>register_activation_hook( string $file, callable $function )</p>\n</blockquote>\n\n<p>The first parameter, <code>$file</code> is the main plugin file, not the file that contains what you want to run. It's used the same way as <code>plugins_url</code>, so you need the value of <code>__FILE__</code>, specifically its value in the root plugin file with your plugin header.</p>\n\n<p>The second parameter is a callable and works as you expect, but it's really just using <code>add_action</code> internally</p>\n\n<blockquote>\n <p>When a plugin is activated, the action ‘activate_PLUGINNAME’ hook is called. In the name of this hook, PLUGINNAME is replaced with the name of the plugin, including the optional subdirectory. For example, when the plugin is located in wp-content/plugins/sampleplugin/sample.php, then the name of this hook will become ‘activate_sampleplugin/sample.php’.</p>\n</blockquote>\n\n<h2>Part 2: Bootstrapping and <code>__FILE__</code></h2>\n\n<p>A fundamental problem here is that <code>__FILE__</code> will have different values in different locations, and you need a specific value.</p>\n\n<p>You also have a problem, that bootstrapping should assemble the object graph, but you don't do that. All your objects are created as soon as they're defined, or created inside eachother, making it difficult or impossible to pass values to them.</p>\n\n<p>As an example, I could write a plugin like this:</p>\n\n<p><code>plugin.php</code>:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: My Plugin\n * Version: 0.1\n */\n\n// loading step\nrequire_once( 'php/app.php' );\n\n// bootstrapping step\n$app = new App( __FILE__ );\n\n// execution step\n$app-&gt;run();\n</code></pre>\n\n<p>I defined all my classes in the <code>php</code> subfolder, and loaded them all in the same place. PHP now knows what my classes are, their names etc, but nothing has happened yet.</p>\n\n<p>I then create all my objects, passing them what they need, in this case App needs the value of <code>__FILE__</code> so I pass it along. Note that this creates the objects in memory, but doesn't do any work. The plugins application is ready to go, to pounce into action, but it's in the preparation phase.</p>\n\n<p>The next step may be to pipe these objects into a set of unit tests, but now I'm going to run them. I've finished my bootstrapping process, and the application is ready to run, so I trigger the <code>run</code> method. I shouldn't need to pass anything to <code>run</code> as everything necessary has been passed to the constructors. During the <code>run</code> method, I add all my filters and hooks. It's during those hooks that all the other parts of the plugin run.</p>\n\n<p>The important part though is that I have a defined structure, and that I pass in what's necessary during the construction/bootstrapping phase, with a defined life cycle</p>\n" }, { "answer_id": 276487, "author": "Gary D", "author_id": 51921, "author_profile": "https://wordpress.stackexchange.com/users/51921", "pm_score": 1, "selected": false, "text": "<p>Tom McFarlin created a very extensive <a href=\"https://wppb.me/\" rel=\"nofollow noreferrer\">plugin boilerplate</a> (now maintained by Devin Vinson), all written in OOP, that you can use to either create your new plugin, or just study the application flow to answer your question. I have used it for several custom plugins, and I have to say it really opened my eyes to some of the mysteries of OOP.</p>\n" }, { "answer_id": 348100, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 3, "selected": false, "text": "<p>You can set a const who will conation the __FILE__ value and use in wherever you want in you classes.</p>\n\n<p>Example:</p>\n\n<p>main-plugin-file.php</p>\n\n<pre><code>&lt;?php\n/**\n* Plugin Name: Plugin with Classes\n*/\n\ndefine( 'PLUGIN_WITH_CLASSES__FILE__', __FILE__ );\n\ninclude( 'my-class.php' );\n</code></pre>\n\n<p>my-class.php</p>\n\n<pre><code>&lt;?php\nclass myClass {\n function __construct() {\n // Run this on plugin activation\n register_activation_hook( PLUGIN_WITH_CLASSES__FILE__, [ $this, 'create_plugin_database_table' ] );\n }\n\n function create_plugin_database_table(){\n //Create DB Table ...\n }\n}\n\nnew myClass();\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123428/" ]
I am trying to develop a plugin for basic SEO purposes, as a lot of people I know don't like using Yoast. I literally just started the plugin, and am building out the activation message displayed to the user when they activate the plugin. I am having trouble with a mix between OOP and built-in Wordpress functions, and not sure where I am going wrong. The only way I can get this to work, is by creating a new instance of the *SEO\_Plugin\_Activation* class inside my main files constructor, and then calling the activatePlugin method in that class. I feel like this is unnecessary. I also think how I am executing my functions in the activation class file don't really make much sense either. But it's the only way I can get it to work right now. I am not sure if what I am doing is because I am not grasping OOP techniques 100%, or if I am not utilizing Wordpress API correctly. I have included three code examples in the following order: 1. Main plugin file 2. Class file that handles my activation requirements 3. What I really was hoping could be done. **seo.php (main plugin file)** ``` <?php /* ... generic plugin info */ require_once(dirname(__FILE__) . '/admin/class-plugin-activation.php'); class SEO { function __construct() { $activate = new SEO_Plugin_Activation(); $activate->activatePlugin(); } } new SEO(); ?> ``` **class-plugin-activation.php** ``` <?php class SEO_Plugin_Activation { function __construct() { register_activation_hook(__FILE__ . '../seo.php', array($this, 'activatePlugin')); add_action('admin_notices', array($this, 'showSitemapInfo')); } function activatePlugin() { set_transient('show_sitemap_info', true, 5); } function showSitemapInfo() { if(get_transient('show_sitemap_info')) { echo '<div class="updated notice is-dismissible">' . 'Your sitemap files can be found at these following links: ' . '</div>'; delete_transient('show_sitemap_info'); } } } ?> ``` **seo.php(What I was hoping for)** ``` <?php /* ... blah blah blah */ require_once(dirname(__FILE__) . '/admin/class-plugin-activation.php'); class SEO { function __construct() { register_activation_hook(__FILE__, array($this, 'wp_install')); } function wp_install() { $activate = new SEO_Plugin_Activation(); // Execute some method(s) here that would take care // of all of my plugin activation bootstrapping } } new SEO(); ?> ``` I tried doing it the way I outline in the third script, but am having no success. As of right now, the message does display properly, with no error messages.
Having reread your question, I think I see the issue, and it stems from a misunderstanding of how `register_activation_hook` works, combined with some confusion over how you're bootstrapping your code and what it means to bootstrap Part 1: `register_activation_hook` ---------------------------------- This function takes 2 parameters: > > register\_activation\_hook( string $file, callable $function ) > > > The first parameter, `$file` is the main plugin file, not the file that contains what you want to run. It's used the same way as `plugins_url`, so you need the value of `__FILE__`, specifically its value in the root plugin file with your plugin header. The second parameter is a callable and works as you expect, but it's really just using `add_action` internally > > When a plugin is activated, the action ‘activate\_PLUGINNAME’ hook is called. In the name of this hook, PLUGINNAME is replaced with the name of the plugin, including the optional subdirectory. For example, when the plugin is located in wp-content/plugins/sampleplugin/sample.php, then the name of this hook will become ‘activate\_sampleplugin/sample.php’. > > > Part 2: Bootstrapping and `__FILE__` ------------------------------------ A fundamental problem here is that `__FILE__` will have different values in different locations, and you need a specific value. You also have a problem, that bootstrapping should assemble the object graph, but you don't do that. All your objects are created as soon as they're defined, or created inside eachother, making it difficult or impossible to pass values to them. As an example, I could write a plugin like this: `plugin.php`: ``` <?php /** * Plugin Name: My Plugin * Version: 0.1 */ // loading step require_once( 'php/app.php' ); // bootstrapping step $app = new App( __FILE__ ); // execution step $app->run(); ``` I defined all my classes in the `php` subfolder, and loaded them all in the same place. PHP now knows what my classes are, their names etc, but nothing has happened yet. I then create all my objects, passing them what they need, in this case App needs the value of `__FILE__` so I pass it along. Note that this creates the objects in memory, but doesn't do any work. The plugins application is ready to go, to pounce into action, but it's in the preparation phase. The next step may be to pipe these objects into a set of unit tests, but now I'm going to run them. I've finished my bootstrapping process, and the application is ready to run, so I trigger the `run` method. I shouldn't need to pass anything to `run` as everything necessary has been passed to the constructors. During the `run` method, I add all my filters and hooks. It's during those hooks that all the other parts of the plugin run. The important part though is that I have a defined structure, and that I pass in what's necessary during the construction/bootstrapping phase, with a defined life cycle
276,494
<p>It is all started after I updated some of the plugins in my Wordpress site. </p> <p>Right now I'm getting an Http Internal 500 Error when I try to access WordPress dashboard.</p> <p>Error at my error log file in File Manager.</p> <pre><code>PHP Fatal error: Call to a member function locale() on a non-object in /wp-content/themes/my_theme/lib/custom.php at line 25. </code></pre> <p>my custom.php file looks like this.</p> <pre><code>24. global $sitepress; 25. setlocale(LC_TIME, $sitepress-&gt;locale() . '.UTF-8'); 26. $_SESSION['date_format'] = (ICL_LANGUAGE_CODE == 'fr') ? 'le %e %B %G' : '%B %e, %G'; </code></pre> <p>Any suggestions on this issue!!</p>
[ { "answer_id": 276496, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 2, "selected": false, "text": "<p><code>$sitepress</code> is a global set by WPML, IIRC. Change your line 25 as follows:</p>\n\n<pre><code>if(isset($sitepress) &amp;&amp; is_object($sitepress)) {\n setlocale(LC_TIME, $sitepress-&gt;locale() . '.UTF-8');\n}\n</code></pre>\n\n<p>As a general rule you shouldn't assume in a theme that anything included in or set by a plugin will be available, because it's possible to disable the plugin while the theme is still active. Always include some sort of sanity check before attempting to access a variable, class or function from a plugin in your theme.</p>\n\n<p>Edit: based on your discovery that the method you used has been deprecated, I'd suggest the following for your updated file:</p>\n\n<pre><code>if(isset($sitepress) &amp;&amp; method_exists($sitepress, 'get_locale')) {\n setlocale(LC_TIME, $sitepress-&gt;get_locale(ICL_LANGUAGE_CODE) . '.UTF-8');\n}\n</code></pre>\n" }, { "answer_id": 276532, "author": "Mithun Nath", "author_id": 124648, "author_profile": "https://wordpress.stackexchange.com/users/124648", "pm_score": 0, "selected": false, "text": "<p>This fixed the problem!</p>\n\n<p>$sitepress->locale() function was no longer available in new version of the wpml plugin. So a new update of WPML plugin broke the translation function. </p>\n\n<pre><code>global $sitepress;\nsetlocale(LC_TIME, $sitepress-&gt;get_locale(ICL_LANGUAGE_CODE) . '.UTF-8');\n$_SESSION['date_format'] = (ICL_LANGUAGE_CODE == 'fr') ? 'le %e %B %G' : '%B %e, %G';\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276494", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124648/" ]
It is all started after I updated some of the plugins in my Wordpress site. Right now I'm getting an Http Internal 500 Error when I try to access WordPress dashboard. Error at my error log file in File Manager. ``` PHP Fatal error: Call to a member function locale() on a non-object in /wp-content/themes/my_theme/lib/custom.php at line 25. ``` my custom.php file looks like this. ``` 24. global $sitepress; 25. setlocale(LC_TIME, $sitepress->locale() . '.UTF-8'); 26. $_SESSION['date_format'] = (ICL_LANGUAGE_CODE == 'fr') ? 'le %e %B %G' : '%B %e, %G'; ``` Any suggestions on this issue!!
`$sitepress` is a global set by WPML, IIRC. Change your line 25 as follows: ``` if(isset($sitepress) && is_object($sitepress)) { setlocale(LC_TIME, $sitepress->locale() . '.UTF-8'); } ``` As a general rule you shouldn't assume in a theme that anything included in or set by a plugin will be available, because it's possible to disable the plugin while the theme is still active. Always include some sort of sanity check before attempting to access a variable, class or function from a plugin in your theme. Edit: based on your discovery that the method you used has been deprecated, I'd suggest the following for your updated file: ``` if(isset($sitepress) && method_exists($sitepress, 'get_locale')) { setlocale(LC_TIME, $sitepress->get_locale(ICL_LANGUAGE_CODE) . '.UTF-8'); } ```
276,507
<p>I have an extremely frustrating problem where mobile (tested chrome on android &amp; ios, and safari on ios) is always using the largest sized image from the srcset (even if a smaller size is EXPLICITLY chosen in the editor).</p> <p>Here is a summary of the problem:</p> <ul> <li>In Wordpress editor, when inserting an image, I choose LARGE (720px x 480px) as the image size</li> <li>On a mobile device, the full size image from the srcset is being downloaded and shown on the frontend every time</li> </ul> <p>So the problem is two-fold:</p> <ol> <li>Firstly that the full image is somehow being used DESPITE actively selecting the large size (why should this be possible?)</li> <li>Secondly that chrome is not respecting the src set anyway and is downloading the full sized image</li> </ol> <p>This is problematic because I purposefully generate many different image sizes as the original images for this blog are often quite large, often a couple of megabytes. So I have a post with 30 images, each with an elaborate srcset, and yet Chrome on Android is downloading the 1.5Mb version for every one (that's 45Mbs on mobile, even though there are images sizes and a srcset -- and a lightbox and lazy-loading which I've disabled for testing -- for this exact reason).</p> <p>The image below is a screenshot from Chrome inspector using remote USB debugging (so this is actually from a phone, not browser simulation). You can see the image's actual SRC attribute is the correct, smaller version of the image (notice the '-720x480'):</p> <pre><code>http://media.londolozi.com/wp-content/uploads/2017/08/10130833/DSC_3855-720x480.jpg </code></pre> <p><a href="https://i.stack.imgur.com/2d3Xp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2d3Xp.jpg" alt="enter image description here"></a></p> <p>However, Chrome on Android has in fact downloaded and is serving the full image. I know this because:</p> <ol> <li>Images in network tab show status of 200 (not from cache), and are the full sized images</li> </ol> <p><a href="https://i.stack.imgur.com/ySxlK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ySxlK.jpg" alt="enter image description here"></a></p> <ol start="2"> <li>The image (and post) takes a while to load (I can see the images downloading progressively)</li> <li>Pressing and holding to download the image on the phone saves the full image</li> <li>Pressing and opening the image in a new tab opens the full size image</li> </ol> <p>Some other things:</p> <ul> <li>It is correctly only downloading the smaller image on desktop (firefox &amp; chrome)</li> <li>On every test I fully clear the cache</li> <li>The problem still occurs if LINK TO is set to NONE (to rule out the parent <code>a</code> tag's <code>href</code> interfering) </li> <li>The device width is 420px</li> <li>You can see that the 'large' image size has been selected in the Wordpress editor by the 'size-large' class on the image, so the full size should not be downloaded at all </li> <li>I have tested this on another wp site and same issue... selecting image size has no effect on chrome android</li> <li>You can see it yourself in action here: blog.londolozi.com/2017/08/04/the-week-in-pictures-295/</li> </ul> <p>So I don't know how to explain this behaviour.</p> <p><strong>Am I correct in asserting that if I explicitly set a size when inserting an image into a post, that the image downloaded by the browser should not be larger than that size, no matter what? Or else setting a size is redundant.</strong> </p> <p>Any ideas why this is happening?</p>
[ { "answer_id": 276496, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 2, "selected": false, "text": "<p><code>$sitepress</code> is a global set by WPML, IIRC. Change your line 25 as follows:</p>\n\n<pre><code>if(isset($sitepress) &amp;&amp; is_object($sitepress)) {\n setlocale(LC_TIME, $sitepress-&gt;locale() . '.UTF-8');\n}\n</code></pre>\n\n<p>As a general rule you shouldn't assume in a theme that anything included in or set by a plugin will be available, because it's possible to disable the plugin while the theme is still active. Always include some sort of sanity check before attempting to access a variable, class or function from a plugin in your theme.</p>\n\n<p>Edit: based on your discovery that the method you used has been deprecated, I'd suggest the following for your updated file:</p>\n\n<pre><code>if(isset($sitepress) &amp;&amp; method_exists($sitepress, 'get_locale')) {\n setlocale(LC_TIME, $sitepress-&gt;get_locale(ICL_LANGUAGE_CODE) . '.UTF-8');\n}\n</code></pre>\n" }, { "answer_id": 276532, "author": "Mithun Nath", "author_id": 124648, "author_profile": "https://wordpress.stackexchange.com/users/124648", "pm_score": 0, "selected": false, "text": "<p>This fixed the problem!</p>\n\n<p>$sitepress->locale() function was no longer available in new version of the wpml plugin. So a new update of WPML plugin broke the translation function. </p>\n\n<pre><code>global $sitepress;\nsetlocale(LC_TIME, $sitepress-&gt;get_locale(ICL_LANGUAGE_CODE) . '.UTF-8');\n$_SESSION['date_format'] = (ICL_LANGUAGE_CODE == 'fr') ? 'le %e %B %G' : '%B %e, %G';\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276507", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125652/" ]
I have an extremely frustrating problem where mobile (tested chrome on android & ios, and safari on ios) is always using the largest sized image from the srcset (even if a smaller size is EXPLICITLY chosen in the editor). Here is a summary of the problem: * In Wordpress editor, when inserting an image, I choose LARGE (720px x 480px) as the image size * On a mobile device, the full size image from the srcset is being downloaded and shown on the frontend every time So the problem is two-fold: 1. Firstly that the full image is somehow being used DESPITE actively selecting the large size (why should this be possible?) 2. Secondly that chrome is not respecting the src set anyway and is downloading the full sized image This is problematic because I purposefully generate many different image sizes as the original images for this blog are often quite large, often a couple of megabytes. So I have a post with 30 images, each with an elaborate srcset, and yet Chrome on Android is downloading the 1.5Mb version for every one (that's 45Mbs on mobile, even though there are images sizes and a srcset -- and a lightbox and lazy-loading which I've disabled for testing -- for this exact reason). The image below is a screenshot from Chrome inspector using remote USB debugging (so this is actually from a phone, not browser simulation). You can see the image's actual SRC attribute is the correct, smaller version of the image (notice the '-720x480'): ``` http://media.londolozi.com/wp-content/uploads/2017/08/10130833/DSC_3855-720x480.jpg ``` [![enter image description here](https://i.stack.imgur.com/2d3Xp.jpg)](https://i.stack.imgur.com/2d3Xp.jpg) However, Chrome on Android has in fact downloaded and is serving the full image. I know this because: 1. Images in network tab show status of 200 (not from cache), and are the full sized images [![enter image description here](https://i.stack.imgur.com/ySxlK.jpg)](https://i.stack.imgur.com/ySxlK.jpg) 2. The image (and post) takes a while to load (I can see the images downloading progressively) 3. Pressing and holding to download the image on the phone saves the full image 4. Pressing and opening the image in a new tab opens the full size image Some other things: * It is correctly only downloading the smaller image on desktop (firefox & chrome) * On every test I fully clear the cache * The problem still occurs if LINK TO is set to NONE (to rule out the parent `a` tag's `href` interfering) * The device width is 420px * You can see that the 'large' image size has been selected in the Wordpress editor by the 'size-large' class on the image, so the full size should not be downloaded at all * I have tested this on another wp site and same issue... selecting image size has no effect on chrome android * You can see it yourself in action here: blog.londolozi.com/2017/08/04/the-week-in-pictures-295/ So I don't know how to explain this behaviour. **Am I correct in asserting that if I explicitly set a size when inserting an image into a post, that the image downloaded by the browser should not be larger than that size, no matter what? Or else setting a size is redundant.** Any ideas why this is happening?
`$sitepress` is a global set by WPML, IIRC. Change your line 25 as follows: ``` if(isset($sitepress) && is_object($sitepress)) { setlocale(LC_TIME, $sitepress->locale() . '.UTF-8'); } ``` As a general rule you shouldn't assume in a theme that anything included in or set by a plugin will be available, because it's possible to disable the plugin while the theme is still active. Always include some sort of sanity check before attempting to access a variable, class or function from a plugin in your theme. Edit: based on your discovery that the method you used has been deprecated, I'd suggest the following for your updated file: ``` if(isset($sitepress) && method_exists($sitepress, 'get_locale')) { setlocale(LC_TIME, $sitepress->get_locale(ICL_LANGUAGE_CODE) . '.UTF-8'); } ```
276,515
<p>I'm using the following code in WordPress HTML page in Azure:</p> <pre><code> &lt;html&gt; &lt;body&gt; &lt;?php global $wpdb; $result = $wpdb -&gt; get_results ( " SELECT 'VillageLeadersName' FROM wp_villageleaderdb WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100 " ); echo $result; echo $row['VillageLeadersName'] . "&lt;br /&gt;"; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The following image shows the resulting screen: <a href="https://i.stack.imgur.com/vRunY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vRunY.png" alt="enter image description here"></a></p> <p>The query works fine on admin console. The resulting page shows the code instead of results. Where I am going wrong?</p>
[ { "answer_id": 276559, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Your web server has probably some misconfiguration regarding the execution of PHP files, but regardless, what you are trying to do probably falls under \"doing it wrong\". Front end HTML generating files should almost always be part of a theme, what you probably need to do is to develop a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">page template</a> to be used for this specific page.</p>\n" }, { "answer_id": 276578, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>It's very clear that your file is not executing PHP functions, and the problem probably is because you are saving this file as <code>something.html</code>, storing it inside your theme or WordPress installation directory.</p>\n\n<p>What you can do, is to wrap this as a function or shortcode, and then create a page and use that shortcode or function inside it.</p>\n\n<p>Here is a simple example to develop shortcode from your query:</p>\n\n<pre><code>add_shortcode('my-shortcode', 'create_my_shortcode');\nfunction create_my_shortcode(){\n global $wpdb;\n $result = $wpdb -&gt; get_results ( \"\n SELECT 'VillageLeadersName' \n FROM wp_villageleaderdb \n WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100\n \" );\n return $result[0][1] . \"&lt;br /&gt;\";\n}\n</code></pre>\n\n<p>Put this code inside your theme's <code>functions.php</code> file, and then head over to <code>New &gt; Page</code> and create a page. Afterward, you can use this shortcode inside your page:</p>\n\n<pre><code>[my-shortcode]\n</code></pre>\n\n<p>This will execute and output your code. Also note that you can not <code>echo</code> content in a shortcode, you must <code>return</code> it.</p>\n\n<p>Another approach is to simply wrap it as a function without creating a shortcode, and then call that function inside your templates. </p>\n\n<pre><code>function create_my_shortcode(){\n // Your code here\n}\n</code></pre>\n\n<p>Now, make a copy of your theme's <code>page.php</code>, rename it to <code>page-whatever.php</code> and modify it the way you like. After you finished editing, use <code>create_my_shortcode()</code> anywhere you want. In this method you can <code>echo</code> the content too.</p>\n\n<p>Afterward, you can use this template while creating a new page in the back-end.</p>\n\n<h2>UPDATE</h2>\n\n<p>As stated in your comments, the results might be an array. To print the array, you can use a foreach like this:</p>\n\n<pre><code>$data = '';\nforeach( $result as $single_result ){\n $data .= $single_result;\n}\nreturn $data. $row['VillageLeadersName'] . \"&lt;br /&gt;\";\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125656/" ]
I'm using the following code in WordPress HTML page in Azure: ``` <html> <body> <?php global $wpdb; $result = $wpdb -> get_results ( " SELECT 'VillageLeadersName' FROM wp_villageleaderdb WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100 " ); echo $result; echo $row['VillageLeadersName'] . "<br />"; ?> </body> </html> ``` The following image shows the resulting screen: [![enter image description here](https://i.stack.imgur.com/vRunY.png)](https://i.stack.imgur.com/vRunY.png) The query works fine on admin console. The resulting page shows the code instead of results. Where I am going wrong?
It's very clear that your file is not executing PHP functions, and the problem probably is because you are saving this file as `something.html`, storing it inside your theme or WordPress installation directory. What you can do, is to wrap this as a function or shortcode, and then create a page and use that shortcode or function inside it. Here is a simple example to develop shortcode from your query: ``` add_shortcode('my-shortcode', 'create_my_shortcode'); function create_my_shortcode(){ global $wpdb; $result = $wpdb -> get_results ( " SELECT 'VillageLeadersName' FROM wp_villageleaderdb WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100 " ); return $result[0][1] . "<br />"; } ``` Put this code inside your theme's `functions.php` file, and then head over to `New > Page` and create a page. Afterward, you can use this shortcode inside your page: ``` [my-shortcode] ``` This will execute and output your code. Also note that you can not `echo` content in a shortcode, you must `return` it. Another approach is to simply wrap it as a function without creating a shortcode, and then call that function inside your templates. ``` function create_my_shortcode(){ // Your code here } ``` Now, make a copy of your theme's `page.php`, rename it to `page-whatever.php` and modify it the way you like. After you finished editing, use `create_my_shortcode()` anywhere you want. In this method you can `echo` the content too. Afterward, you can use this template while creating a new page in the back-end. UPDATE ------ As stated in your comments, the results might be an array. To print the array, you can use a foreach like this: ``` $data = ''; foreach( $result as $single_result ){ $data .= $single_result; } return $data. $row['VillageLeadersName'] . "<br />"; ```
276,517
<p>How can I view my posts in ascending order by number of views?</p> <p>This is just for internal use so I can see how different posts are performing. Currently if I go to posts in the dashboard I can only filter by date. With over 900 posts I want to be able to see them in order by number of views. Views is a field there but I can't sort by it. </p>
[ { "answer_id": 276559, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Your web server has probably some misconfiguration regarding the execution of PHP files, but regardless, what you are trying to do probably falls under \"doing it wrong\". Front end HTML generating files should almost always be part of a theme, what you probably need to do is to develop a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">page template</a> to be used for this specific page.</p>\n" }, { "answer_id": 276578, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>It's very clear that your file is not executing PHP functions, and the problem probably is because you are saving this file as <code>something.html</code>, storing it inside your theme or WordPress installation directory.</p>\n\n<p>What you can do, is to wrap this as a function or shortcode, and then create a page and use that shortcode or function inside it.</p>\n\n<p>Here is a simple example to develop shortcode from your query:</p>\n\n<pre><code>add_shortcode('my-shortcode', 'create_my_shortcode');\nfunction create_my_shortcode(){\n global $wpdb;\n $result = $wpdb -&gt; get_results ( \"\n SELECT 'VillageLeadersName' \n FROM wp_villageleaderdb \n WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100\n \" );\n return $result[0][1] . \"&lt;br /&gt;\";\n}\n</code></pre>\n\n<p>Put this code inside your theme's <code>functions.php</code> file, and then head over to <code>New &gt; Page</code> and create a page. Afterward, you can use this shortcode inside your page:</p>\n\n<pre><code>[my-shortcode]\n</code></pre>\n\n<p>This will execute and output your code. Also note that you can not <code>echo</code> content in a shortcode, you must <code>return</code> it.</p>\n\n<p>Another approach is to simply wrap it as a function without creating a shortcode, and then call that function inside your templates. </p>\n\n<pre><code>function create_my_shortcode(){\n // Your code here\n}\n</code></pre>\n\n<p>Now, make a copy of your theme's <code>page.php</code>, rename it to <code>page-whatever.php</code> and modify it the way you like. After you finished editing, use <code>create_my_shortcode()</code> anywhere you want. In this method you can <code>echo</code> the content too.</p>\n\n<p>Afterward, you can use this template while creating a new page in the back-end.</p>\n\n<h2>UPDATE</h2>\n\n<p>As stated in your comments, the results might be an array. To print the array, you can use a foreach like this:</p>\n\n<pre><code>$data = '';\nforeach( $result as $single_result ){\n $data .= $single_result;\n}\nreturn $data. $row['VillageLeadersName'] . \"&lt;br /&gt;\";\n</code></pre>\n" } ]
2017/08/10
[ "https://wordpress.stackexchange.com/questions/276517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125659/" ]
How can I view my posts in ascending order by number of views? This is just for internal use so I can see how different posts are performing. Currently if I go to posts in the dashboard I can only filter by date. With over 900 posts I want to be able to see them in order by number of views. Views is a field there but I can't sort by it.
It's very clear that your file is not executing PHP functions, and the problem probably is because you are saving this file as `something.html`, storing it inside your theme or WordPress installation directory. What you can do, is to wrap this as a function or shortcode, and then create a page and use that shortcode or function inside it. Here is a simple example to develop shortcode from your query: ``` add_shortcode('my-shortcode', 'create_my_shortcode'); function create_my_shortcode(){ global $wpdb; $result = $wpdb -> get_results ( " SELECT 'VillageLeadersName' FROM wp_villageleaderdb WHERE VillageID = 'V001' AND VillageLeaderPosition = 'Sarpanch' LIMIT 0, 100 " ); return $result[0][1] . "<br />"; } ``` Put this code inside your theme's `functions.php` file, and then head over to `New > Page` and create a page. Afterward, you can use this shortcode inside your page: ``` [my-shortcode] ``` This will execute and output your code. Also note that you can not `echo` content in a shortcode, you must `return` it. Another approach is to simply wrap it as a function without creating a shortcode, and then call that function inside your templates. ``` function create_my_shortcode(){ // Your code here } ``` Now, make a copy of your theme's `page.php`, rename it to `page-whatever.php` and modify it the way you like. After you finished editing, use `create_my_shortcode()` anywhere you want. In this method you can `echo` the content too. Afterward, you can use this template while creating a new page in the back-end. UPDATE ------ As stated in your comments, the results might be an array. To print the array, you can use a foreach like this: ``` $data = ''; foreach( $result as $single_result ){ $data .= $single_result; } return $data. $row['VillageLeadersName'] . "<br />"; ```
276,556
<p>I am trying to alter a plugin that has this code to display Related Categories names under the post:</p> <pre><code>&lt;?php if ( count( get_the_category() ) ) : ?&gt; &lt;span class="cat-links"&gt; &lt;?php printf( __( '&lt;span class="%1$s"&gt;See related Videos&lt;/span&gt; %2$s', 'posts-in-page' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?&gt; &lt;/span&gt; &lt;?php endif; ?&gt; </code></pre> <p>Can someone please tell me how I can alter this code to exclude one Category name from the list that it generates...?? The category name that I want to exclude is "TopONLY" and its ID is 11.</p>
[ { "answer_id": 276561, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>use <code>wp_list_categories</code> function instead and use 'exclude' argument.</p>\n\n<p>use this code</p>\n\n<pre><code>&lt;?php \n $categories = get_the_category();\n $count=count($categories)\n if($count){\n foreach ( $categories as $category ) { \n if ( $category-&gt;term_id == 11 ) { \n continue;\n }?&gt;\n &lt;span class=\"cat-links\"&gt;\n &lt;?php printf( __( '&lt;span class=\"%1$s\"&gt;See related Videos&lt;/span&gt; %2$s', 'posts-in-page' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?&gt;\n &lt;/span&gt;\n&lt;?php endif; \n}\n?&gt;\n</code></pre>\n\n<p>Hope this will help you.</p>\n" }, { "answer_id": 276564, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 2, "selected": true, "text": "<pre><code>$d = get_the_category();\n$glu = [];\nforeach($d as $rst ):\n //exclude category name\n if($rst-&gt;name != 'Sticky'):\n $glu[]=\"&lt;a href=\".get_category_link( $rst-&gt;cat_ID ).\"&gt;{$rst-&gt;name}&lt;/a&gt;\";\n endif;\nendforeach;\n\n//error_log(print_r($glu, true).'/n', 3, WP_CONTENT_DIR.'/debug.log');\necho \"These are the categories\". implode(', ', $glu);\n</code></pre>\n\n<p>I'm a beginner. Hope this will help!</p>\n" } ]
2017/08/11
[ "https://wordpress.stackexchange.com/questions/276556", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78121/" ]
I am trying to alter a plugin that has this code to display Related Categories names under the post: ``` <?php if ( count( get_the_category() ) ) : ?> <span class="cat-links"> <?php printf( __( '<span class="%1$s">See related Videos</span> %2$s', 'posts-in-page' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?> </span> <?php endif; ?> ``` Can someone please tell me how I can alter this code to exclude one Category name from the list that it generates...?? The category name that I want to exclude is "TopONLY" and its ID is 11.
``` $d = get_the_category(); $glu = []; foreach($d as $rst ): //exclude category name if($rst->name != 'Sticky'): $glu[]="<a href=".get_category_link( $rst->cat_ID ).">{$rst->name}</a>"; endif; endforeach; //error_log(print_r($glu, true).'/n', 3, WP_CONTENT_DIR.'/debug.log'); echo "These are the categories". implode(', ', $glu); ``` I'm a beginner. Hope this will help!
276,637
<pre><code>&lt;?php $args = array( 'post_type' =&gt; 'page', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; $post-&gt;ID, 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order' ); $parent = new WP_Query( $args ); if ( $parent-&gt;have_posts() ) : ?&gt; &lt;?php while ( $parent-&gt;have_posts() ) : $parent-&gt;the_post(); ?&gt; &lt;div id="parent-&lt;?php the_ID(); ?&gt;" class="parent-page"&gt; &lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php // the_advanced_excerpt(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; wp_reset_query(); ?&gt; </code></pre> <p>This is my code. It should display the title of all child pages of any parent page. But, unfortunately, it just displays all the pages in the website including the child of the same and other pages as well. </p> <p>Any suggestions on this?</p>
[ { "answer_id": 276641, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>I just used this in a site! What about something like this:</p>\n\n<pre><code>function rt_list_child_pages() { \nglobal $post; \nif ( is_page() &amp;&amp; $post-&gt;post_parent )\n\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\nelse\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\nif ( $childpages ) {\n $string = '&lt;ul&gt;' . $childpages . '&lt;/ul&gt;';\n}\nreturn $string;\n}\nadd_shortcode('list-childpages', 'rt_list_child_pages');\n</code></pre>\n\n<p>The code above first checks to see if a page has a parent or the page itself is a parent. If it is a parent page, then it displays the child pages associated with it. If it is a child page, then it displays all other child pages of its parent page. Lastly, if this is just a page with no child or parent page, then the code will simply do nothing. In the last line of the code, I have added a shortcode, so you can easily display child pages without modifying your page templates.</p>\n\n<p>To display child pages simply add the following shortcode in a page or text widget in the sidebar:</p>\n\n<p>[rt-childpages]</p>\n\n<p>or you can add the function</p>\n\n<pre><code>rt_list_child_pages()\n</code></pre>\n\n<p>to any page template.</p>\n" }, { "answer_id": 276681, "author": "Abdullah Alemadi", "author_id": 125515, "author_profile": "https://wordpress.stackexchange.com/users/125515", "pm_score": 1, "selected": false, "text": "<p>You should use this attribute in the $args array to get children of specific page by <strong>Parent ID</strong></p>\n\n<pre><code>'child_of' =&gt; 20,\n</code></pre>\n\n<p>More information:\n<a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_pages</a></p>\n" } ]
2017/08/11
[ "https://wordpress.stackexchange.com/questions/276637", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124648/" ]
``` <?php $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order' ); $parent = new WP_Query( $args ); if ( $parent->have_posts() ) : ?> <?php while ( $parent->have_posts() ) : $parent->the_post(); ?> <div id="parent-<?php the_ID(); ?>" class="parent-page"> <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1> <p><?php // the_advanced_excerpt(); ?></p> </div> <?php endwhile; ?> <?php endif; wp_reset_query(); ?> ``` This is my code. It should display the title of all child pages of any parent page. But, unfortunately, it just displays all the pages in the website including the child of the same and other pages as well. Any suggestions on this?
You should use this attribute in the $args array to get children of specific page by **Parent ID** ``` 'child_of' => 20, ``` More information: <https://codex.wordpress.org/Function_Reference/get_pages>
276,644
<p>I am using this code in the functions.php of my theme, in order to add cart information next to the cart menu item.</p> <p>However, this code adds this information outside the <code>&lt;li&gt;</code> and I would like the information to be into the <code>&lt;li&gt;</code>.</p> <p>Can you help me change this code in order to display the info within the <code>&lt;li&gt;</code>?</p> <p>Thanks</p> <pre><code>/** * This function adds the WooCommerce or Easy Digital Downloads cart icons/items to the top_nav menu area as the last item. */ add_filter( 'wp_nav_menu_items', 'my_wp_nav_menu_items', 10, 2 ); function my_wp_nav_menu_items( $items, $args, $ajax = false ) { // Top Navigation Area Only if ( ( isset( $ajax ) &amp;&amp; $ajax ) || ( property_exists( $args, 'theme_location' ) &amp;&amp; $args-&gt;theme_location === 'primary' ) ) { // WooCommerce if ( class_exists( 'woocommerce' ) ) { $css_class = 'menu-item menu-item-type-cart menu-item-type-woocommerce-cart'; // Is this the cart page? if ( is_cart() ) $css_class .= ' current-menu-item'; //$items .= '&lt;li class="' . esc_attr( $css_class ) . '"&gt;'; $items .= '&lt;a class="cart-contents" href="' . esc_url( WC()-&gt;cart-&gt;get_cart_url() ) . '"&gt;'; // $items .= wp_kses_data( WC()-&gt;cart-&gt;get_cart_total() ) . ' - &lt;span class="count"&gt;' . wp_kses_data( sprintf( _n( '%d item', '%d items', WC()-&gt;cart-&gt;get_cart_contents_count(), 'simple-shop' ), WC()-&gt;cart-&gt;get_cart_contents_count() ) ) . '&lt;/span&gt;'; $items .= ' (&lt;span class="count"&gt;' . wp_kses_data( sprintf( _n( '%d', '%d', WC()-&gt;cart-&gt;get_cart_contents_count(), 'simple-shop' ), WC()-&gt;cart-&gt;get_cart_contents_count() ) ) . '&lt;/span&gt;)'; $items .= '&lt;/a&gt;'; //$items .= '&lt;/li&gt;'; } } return $items; } /** * This function updates the Top Navigation WooCommerce cart link contents when an item is added via AJAX. */ add_filter( 'woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments' ); function my_woocommerce_add_to_cart_fragments( $fragments ) { // Add our fragment $fragments['li.menu-item-type-woocommerce-cart'] = my_wp_nav_menu_items( '', new stdClass(), true ); return $fragments; } </code></pre> <p><strong>EDIT (new code)</strong></p> <pre><code> add_filter( 'wp_setup_nav_menu_item','my_item_setup' ); function my_item_setup($item) { if ( class_exists( 'woocommerce' ) ) { global $woocommerce; ?&gt; &lt;!--&lt;pre&gt;&lt;?php //var_dump( $woocommerce-&gt;cart-&gt;get_cart_contents_count() ); ?&gt;&lt;/pre&gt;--&gt; &lt;?php if ( $item-&gt;url == esc_url( wc_get_cart_url() ) ) { //$item-&gt;title = 'MY BAG('. '&lt;span class="count"&gt;' . wp_kses_data( sprintf( _n( '%d', '%d', WC()-&gt;cart-&gt;get_cart_contents_count(), 'simple-shop' ), WC()-&gt;cart-&gt;get_cart_contents_count() ) ) . '&lt;/span&gt;)'; //$item-&gt;title = 'MY BAG('. '&lt;span class="count"&gt;' . wp_kses_data( sprintf( _n( '%d', '%d', $woocommerce-&gt;cart-&gt;cart_contents_count(), 'simple-shop' ), $woocommerce-&gt;cart-&gt;cart_contents_count() ) ) . '&lt;/span&gt;)'; $item-&gt;title = 'MY BAG('. '&lt;span class="count"&gt;' . $woocommerce-&gt;cart-&gt;get_cart_contents_count() . '&lt;/span&gt;)'; //$item-&gt;title = sprintf( _n( '%d', '%d', $woocommerce-&gt;cart-&gt;cart_contents_count();, 'simple-shop' ), $woocommerce-&gt;cart-&gt;cart_contents_count(); ); } } return $item; } </code></pre>
[ { "answer_id": 276641, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>I just used this in a site! What about something like this:</p>\n\n<pre><code>function rt_list_child_pages() { \nglobal $post; \nif ( is_page() &amp;&amp; $post-&gt;post_parent )\n\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\nelse\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\nif ( $childpages ) {\n $string = '&lt;ul&gt;' . $childpages . '&lt;/ul&gt;';\n}\nreturn $string;\n}\nadd_shortcode('list-childpages', 'rt_list_child_pages');\n</code></pre>\n\n<p>The code above first checks to see if a page has a parent or the page itself is a parent. If it is a parent page, then it displays the child pages associated with it. If it is a child page, then it displays all other child pages of its parent page. Lastly, if this is just a page with no child or parent page, then the code will simply do nothing. In the last line of the code, I have added a shortcode, so you can easily display child pages without modifying your page templates.</p>\n\n<p>To display child pages simply add the following shortcode in a page or text widget in the sidebar:</p>\n\n<p>[rt-childpages]</p>\n\n<p>or you can add the function</p>\n\n<pre><code>rt_list_child_pages()\n</code></pre>\n\n<p>to any page template.</p>\n" }, { "answer_id": 276681, "author": "Abdullah Alemadi", "author_id": 125515, "author_profile": "https://wordpress.stackexchange.com/users/125515", "pm_score": 1, "selected": false, "text": "<p>You should use this attribute in the $args array to get children of specific page by <strong>Parent ID</strong></p>\n\n<pre><code>'child_of' =&gt; 20,\n</code></pre>\n\n<p>More information:\n<a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_pages</a></p>\n" } ]
2017/08/11
[ "https://wordpress.stackexchange.com/questions/276644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121787/" ]
I am using this code in the functions.php of my theme, in order to add cart information next to the cart menu item. However, this code adds this information outside the `<li>` and I would like the information to be into the `<li>`. Can you help me change this code in order to display the info within the `<li>`? Thanks ``` /** * This function adds the WooCommerce or Easy Digital Downloads cart icons/items to the top_nav menu area as the last item. */ add_filter( 'wp_nav_menu_items', 'my_wp_nav_menu_items', 10, 2 ); function my_wp_nav_menu_items( $items, $args, $ajax = false ) { // Top Navigation Area Only if ( ( isset( $ajax ) && $ajax ) || ( property_exists( $args, 'theme_location' ) && $args->theme_location === 'primary' ) ) { // WooCommerce if ( class_exists( 'woocommerce' ) ) { $css_class = 'menu-item menu-item-type-cart menu-item-type-woocommerce-cart'; // Is this the cart page? if ( is_cart() ) $css_class .= ' current-menu-item'; //$items .= '<li class="' . esc_attr( $css_class ) . '">'; $items .= '<a class="cart-contents" href="' . esc_url( WC()->cart->get_cart_url() ) . '">'; // $items .= wp_kses_data( WC()->cart->get_cart_total() ) . ' - <span class="count">' . wp_kses_data( sprintf( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count(), 'simple-shop' ), WC()->cart->get_cart_contents_count() ) ) . '</span>'; $items .= ' (<span class="count">' . wp_kses_data( sprintf( _n( '%d', '%d', WC()->cart->get_cart_contents_count(), 'simple-shop' ), WC()->cart->get_cart_contents_count() ) ) . '</span>)'; $items .= '</a>'; //$items .= '</li>'; } } return $items; } /** * This function updates the Top Navigation WooCommerce cart link contents when an item is added via AJAX. */ add_filter( 'woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments' ); function my_woocommerce_add_to_cart_fragments( $fragments ) { // Add our fragment $fragments['li.menu-item-type-woocommerce-cart'] = my_wp_nav_menu_items( '', new stdClass(), true ); return $fragments; } ``` **EDIT (new code)** ``` add_filter( 'wp_setup_nav_menu_item','my_item_setup' ); function my_item_setup($item) { if ( class_exists( 'woocommerce' ) ) { global $woocommerce; ?> <!--<pre><?php //var_dump( $woocommerce->cart->get_cart_contents_count() ); ?></pre>--> <?php if ( $item->url == esc_url( wc_get_cart_url() ) ) { //$item->title = 'MY BAG('. '<span class="count">' . wp_kses_data( sprintf( _n( '%d', '%d', WC()->cart->get_cart_contents_count(), 'simple-shop' ), WC()->cart->get_cart_contents_count() ) ) . '</span>)'; //$item->title = 'MY BAG('. '<span class="count">' . wp_kses_data( sprintf( _n( '%d', '%d', $woocommerce->cart->cart_contents_count(), 'simple-shop' ), $woocommerce->cart->cart_contents_count() ) ) . '</span>)'; $item->title = 'MY BAG('. '<span class="count">' . $woocommerce->cart->get_cart_contents_count() . '</span>)'; //$item->title = sprintf( _n( '%d', '%d', $woocommerce->cart->cart_contents_count();, 'simple-shop' ), $woocommerce->cart->cart_contents_count(); ); } } return $item; } ```
You should use this attribute in the $args array to get children of specific page by **Parent ID** ``` 'child_of' => 20, ``` More information: <https://codex.wordpress.org/Function_Reference/get_pages>
276,653
<p>The package could not be installed. The style.css stylesheet doesn’t contain a valid theme header.</p> <p>What do you guys think went wrong?</p>
[ { "answer_id": 276654, "author": "Kort", "author_id": 74680, "author_profile": "https://wordpress.stackexchange.com/users/74680", "pm_score": 1, "selected": false, "text": "<p>I think the problem is you're trying to upload the entire zip file which also includes documentation and license information. You need to extract the zip to find the theme zip inside. Please check again.</p>\n" }, { "answer_id": 276655, "author": "Swati", "author_id": 123547, "author_profile": "https://wordpress.stackexchange.com/users/123547", "pm_score": 3, "selected": true, "text": "<p>Your theme’s stylesheet must contain a commented-out header with the theme’s name:</p>\n\n<pre><code>/*Theme Name: nameoftheme*/\n</code></pre>\n" }, { "answer_id": 276658, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>First, theme support should be via the theme's WP Support page.</p>\n\n<p>But it seems to me that the theme author didn't set up things correctly (hence the 'required license' problem). Which perhaps means that you didn't get the theme via the WP Theme Repository. Which might be not a good thing to do.</p>\n\n<p>Themes require a certain structure and 'header' info. Themes that are submitted to (and approved by) the WP Theme Repository will be checked for required elements.</p>\n\n<p>IMHO, risky to install themes from a non-WP Repository source. But, you should be asking via the theme support page, not here.</p>\n" } ]
2017/08/11
[ "https://wordpress.stackexchange.com/questions/276653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125729/" ]
The package could not be installed. The style.css stylesheet doesn’t contain a valid theme header. What do you guys think went wrong?
Your theme’s stylesheet must contain a commented-out header with the theme’s name: ``` /*Theme Name: nameoftheme*/ ```
276,666
<blockquote> <p>Fatal error: Allowed memory size of 94371840 bytes exhausted (tried to allocate 42240 bytes) in /home/dh_w7t9sk/morleywines.com/wp-content/plugins/js_composer/include/params/iconpicker/iconpicker.php on line 720</p> </blockquote> <p>I can't seem to get back into my dashboard. Can you help me please</p>
[ { "answer_id": 276672, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>THe error message indicates an issue with the 'js-composer' plugin. Rename that folder to get control of the system. </p>\n" }, { "answer_id": 276691, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 2, "selected": false, "text": "<p>Add below code in <code>wp-config.php</code> file.</p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '256M');\n</code></pre>\n\n<p>For more details check \"Increasing memory allocated to PHP\" here <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php</a></p>\n" } ]
2017/08/12
[ "https://wordpress.stackexchange.com/questions/276666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125735/" ]
> > Fatal error: Allowed memory size of 94371840 bytes exhausted (tried to > allocate 42240 bytes) in > /home/dh\_w7t9sk/morleywines.com/wp-content/plugins/js\_composer/include/params/iconpicker/iconpicker.php > on line 720 > > > I can't seem to get back into my dashboard. Can you help me please
Add below code in `wp-config.php` file. ``` define('WP_MEMORY_LIMIT', '256M'); ``` For more details check "Increasing memory allocated to PHP" here <https://codex.wordpress.org/Editing_wp-config.php>
276,728
<p><strong>*UPDATE - This wasn't showing because of a cache issue. The comment referencing changing the jQuery to :first-child instead of :first was indeed the only issue that needed to be addressed. *</strong></p> <p>I am creating a WordPress theme and the image slider fails to do three things:</p> <p>1) When clicking an indicator it does not do anything.</p> <p>2) The image slider does not slide automatically.</p> <p>3) The first indicator is never on.</p> <p>I know the content is present because if I add a Post with the Category slider the image will display along with the title and a new carousel indicator. I also checked the DOM and all of the data-slides are there but nothing is moving. Any help is appreciated.</p> <p><strong>HTML/PHP</strong></p> <pre><code>&lt;?php $number = 0; query_posts('category_name=slider'); if(have_posts()): ?&gt; &lt;div id="carousel-example-generic" class="carousel slide" data-ride="carousel"&gt; &lt;ol class="carousel-indicators"&gt; &lt;?php while(have_posts()): the_post(); ?&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="&lt;?php echo $number++; ?&gt;"&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ol&gt; &lt;!-- Carousel items --&gt; &lt;div class="carousel-inner"&gt; &lt;?php while(have_posts()): the_post(); ?&gt; &lt;div class="item"&gt; &lt;?php $image = wp_get_attachment_image_src( get_post_thumbnail_id ( $post-&gt;ID ), 'single-post-thumbnail' ); ?&gt;&lt;a href=#"&gt;&lt;img class="img-responsive" src="&lt;?php echo $image[0]; ?&gt;" /&gt; &lt;div class="carousel-caption"&gt; &lt;?php the_title();?&gt; &lt;/div&gt; &lt;/div&gt;&lt;/a&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; wp_reset_query(); ?&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>//Carousel Indicator $(".carousel-indicators li:first-child").addClass("active"); $(".carousel-inner .item:first-child").addClass("active"); </code></pre>
[ { "answer_id": 276672, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>THe error message indicates an issue with the 'js-composer' plugin. Rename that folder to get control of the system. </p>\n" }, { "answer_id": 276691, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 2, "selected": false, "text": "<p>Add below code in <code>wp-config.php</code> file.</p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '256M');\n</code></pre>\n\n<p>For more details check \"Increasing memory allocated to PHP\" here <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php</a></p>\n" } ]
2017/08/12
[ "https://wordpress.stackexchange.com/questions/276728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114269/" ]
**\*UPDATE - This wasn't showing because of a cache issue. The comment referencing changing the jQuery to :first-child instead of :first was indeed the only issue that needed to be addressed. \*** I am creating a WordPress theme and the image slider fails to do three things: 1) When clicking an indicator it does not do anything. 2) The image slider does not slide automatically. 3) The first indicator is never on. I know the content is present because if I add a Post with the Category slider the image will display along with the title and a new carousel indicator. I also checked the DOM and all of the data-slides are there but nothing is moving. Any help is appreciated. **HTML/PHP** ``` <?php $number = 0; query_posts('category_name=slider'); if(have_posts()): ?> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <?php while(have_posts()): the_post(); ?> <li data-target="#carousel-example-generic" data-slide-to="<?php echo $number++; ?>"></li> <?php endwhile; ?> </ol> <!-- Carousel items --> <div class="carousel-inner"> <?php while(have_posts()): the_post(); ?> <div class="item"> <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id ( $post->ID ), 'single-post-thumbnail' ); ?><a href=#"><img class="img-responsive" src="<?php echo $image[0]; ?>" /> <div class="carousel-caption"> <?php the_title();?> </div> </div></a> <?php endwhile; ?> </div> </div> <?php endif; wp_reset_query(); ?> ``` **jQuery** ``` //Carousel Indicator $(".carousel-indicators li:first-child").addClass("active"); $(".carousel-inner .item:first-child").addClass("active"); ```
Add below code in `wp-config.php` file. ``` define('WP_MEMORY_LIMIT', '256M'); ``` For more details check "Increasing memory allocated to PHP" here <https://codex.wordpress.org/Editing_wp-config.php>
276,731
<p>I am working on a Wordpress theme using a template to manage sports team, matches, players, etc.</p> <p>I settled my local wordpress time in French. In the blog part, no problem the post are displaying date in French.</p> <p>But there is a all part with custom post types managed by a plugin. The dates displayed by this plugins remains in English.</p> <p>By checking the code, I can see the date part formatting is managed here :</p> <p>function team_get_match_start($match_id, $format = 'j F Y / G:i') {</p> <pre><code>$date_start = get_post_meta($match_id, '_date_start', true); if (!$date_start || !strtotime($date_start)) { return ''; } $timezone_string = get_option('timezone_string'); $gmt_offset = get_option('gmt_offset'); if ($timezone_string) { $tz = $timezone_string; } else if ($gmt_offset &gt; 0) { $tz = date('+Hi', abs($gmt_offset) * 3600); } else if ($gmt_offset &lt; 0) { $tz = date('-Hi', abs($gmt_offset) * 3600); } else { $tz = 'UTC'; } $datetime = date_create( $date_start, new DateTimeZone($tz)); return $datetime-&gt;format( $format ); </code></pre> <p>So, this displays me 28 JULY 2017 / 13:00. I would like it to be in french.</p> <p>I did many unsuccessful tries with strftime(). I am reading about date_i18n() wordpress function, but I am not sure about what to do with it.</p> <p>Anyone as an idea that could help me ?</p> <p>Cheers guys</p>
[ { "answer_id": 276762, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>You need to grab the WordPress date option on the first parameter of date_i18n function :</p>\n\n<pre><code>date_i18n( get_option( 'date_format' ), strtotime( '11/15-1976' ) ); \n</code></pre>\n\n<p>You can see this example in the function codex page : <a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"nofollow noreferrer\">date_i18n()</a></p>\n" }, { "answer_id": 398221, "author": "Shoaib Ali", "author_id": 214914, "author_profile": "https://wordpress.stackexchange.com/users/214914", "pm_score": 0, "selected": false, "text": "<p>If you have a Unix timestamp, you can use wp_date function to retrieve date in localized format. wp_date is intended to replace date_i18n().</p>\n<pre><code>wp_date( get_option( 'date_format' ), get_post_timestamp() );\n</code></pre>\n<p>Ref: <a href=\"https://developer.wordpress.org/reference/functions/wp_date/\" rel=\"nofollow noreferrer\">wp_date()</a> Credit: <a href=\"https://profiles.wordpress.org/barkerbaggies/\" rel=\"nofollow noreferrer\">Marc Heatley</a></p>\n" } ]
2017/08/12
[ "https://wordpress.stackexchange.com/questions/276731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125770/" ]
I am working on a Wordpress theme using a template to manage sports team, matches, players, etc. I settled my local wordpress time in French. In the blog part, no problem the post are displaying date in French. But there is a all part with custom post types managed by a plugin. The dates displayed by this plugins remains in English. By checking the code, I can see the date part formatting is managed here : function team\_get\_match\_start($match\_id, $format = 'j F Y / G:i') { ``` $date_start = get_post_meta($match_id, '_date_start', true); if (!$date_start || !strtotime($date_start)) { return ''; } $timezone_string = get_option('timezone_string'); $gmt_offset = get_option('gmt_offset'); if ($timezone_string) { $tz = $timezone_string; } else if ($gmt_offset > 0) { $tz = date('+Hi', abs($gmt_offset) * 3600); } else if ($gmt_offset < 0) { $tz = date('-Hi', abs($gmt_offset) * 3600); } else { $tz = 'UTC'; } $datetime = date_create( $date_start, new DateTimeZone($tz)); return $datetime->format( $format ); ``` So, this displays me 28 JULY 2017 / 13:00. I would like it to be in french. I did many unsuccessful tries with strftime(). I am reading about date\_i18n() wordpress function, but I am not sure about what to do with it. Anyone as an idea that could help me ? Cheers guys
You need to grab the WordPress date option on the first parameter of date\_i18n function : ``` date_i18n( get_option( 'date_format' ), strtotime( '11/15-1976' ) ); ``` You can see this example in the function codex page : [date\_i18n()](https://codex.wordpress.org/Function_Reference/date_i18n)
276,732
<p>Is it possible to create a plugin directly from the admin panel?</p> <p>I cannot find any such plugin to create plugins with when searching, and that really makes me curious. Are there security risks with this that simply prevent people from developing such a thing? Or is the file system inaccessible for creating files?</p> <p>As far as I can see, a rather simple plugin could create the fundamental php-files in the right wp directory. And from there on it just must allow you to create more files within this directory. The built-in plugin editor in Wordpress can take it from there.</p> <p>Does such a tool exist? And if not, why?</p>
[ { "answer_id": 276735, "author": "Mihai Papuc", "author_id": 44326, "author_profile": "https://wordpress.stackexchange.com/users/44326", "pm_score": 2, "selected": false, "text": "<p>Why would anybody create such a tool? Creating a plugin <a href=\"https://developer.wordpress.org/plugins/the-basics/\" rel=\"nofollow noreferrer\">is really easy</a>: </p>\n\n<blockquote>\n <p>At its simplest, a WordPress plugin is a PHP file with a WordPress plugin header comment. </p>\n</blockquote>\n\n<p>Here is the plugin header:</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: YOUR PLUGIN NAME\n*/\n</code></pre>\n\n<p>Just save the above text to a new PHP file, upload it to the <strong>plugins</strong> folder in WP and you're done.</p>\n\n<p>Of course, you only succeeded in creating the basic plugin, now you need to put the code that actually does something.</p>\n" }, { "answer_id": 276768, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>What will happen if a website is hacked ? </p>\n\n<p>If anyone can create file it will be a very high security hole.</p>\n\n<p>Some Host simple disabled theme and plugin editor for various reason but the first is security.</p>\n\n<p>As Mihai said, it is very simple to create a plugin file and you can find a lot of plugin to inject PHP code related to theme.</p>\n" } ]
2017/08/12
[ "https://wordpress.stackexchange.com/questions/276732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36207/" ]
Is it possible to create a plugin directly from the admin panel? I cannot find any such plugin to create plugins with when searching, and that really makes me curious. Are there security risks with this that simply prevent people from developing such a thing? Or is the file system inaccessible for creating files? As far as I can see, a rather simple plugin could create the fundamental php-files in the right wp directory. And from there on it just must allow you to create more files within this directory. The built-in plugin editor in Wordpress can take it from there. Does such a tool exist? And if not, why?
Why would anybody create such a tool? Creating a plugin [is really easy](https://developer.wordpress.org/plugins/the-basics/): > > At its simplest, a WordPress plugin is a PHP file with a WordPress plugin header comment. > > > Here is the plugin header: ``` <?php /* Plugin Name: YOUR PLUGIN NAME */ ``` Just save the above text to a new PHP file, upload it to the **plugins** folder in WP and you're done. Of course, you only succeeded in creating the basic plugin, now you need to put the code that actually does something.
276,781
<p>I'm wrapping up a port from Jekyll to WordPress and have several thousand relative URLs I need to remap so they're absolute within my posts.</p> <p><strong>Actual URL examples:</strong></p> <pre><code>/gangs/gangster-disciples /housing-projects/cabrini-green /hoods/bridgeport </code></pre> <p><strong>Expected URL samples:</strong></p> <pre><code>http://example.com/gang/gangster-disciples http://example.com/project/cabrini-green http://example.com/neighborhood/bridgeport </code></pre> <p>Dax isn't turning up anything useful based on my search phrases and I'm not able to find any plugins or similar questions to study.</p> <p>Short of writing some update queries I'm curious to know if there's a more streamlined solution available I may be overlooking, such as a plugin-based solution. What's the easiest way to remap the example relative URLs to absolute?</p>
[ { "answer_id": 276782, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 2, "selected": false, "text": "<p>There are several plugin solutions such as <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search and Replace</a> which will \"bulkly\" update almost whatever you want in DB. This one has a \"Replace a Domain / Url” special feature:</p>\n\n<blockquote>\n <p>Useful for a quick and simple transfer or a migration of an WordPress.</p>\n</blockquote>\n" }, { "answer_id": 276795, "author": "Mihai Papuc", "author_id": 44326, "author_profile": "https://wordpress.stackexchange.com/users/44326", "pm_score": 1, "selected": false, "text": "<p>If you switched from a different system to WP, first you would need a proper redirection set up - either manually in <strong>.htaccess</strong>, or using a plugin like <a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">Simple 301 Redirects</a>.</p>\n\n<p>This would help the search engines find your pages, and it would also take care of your links - at least for starters. </p>\n\n<p>After you're done with this step, if you need simple search and replace, the plugin <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search and Replace</a> (already mentioned by <a href=\"https://wordpress.stackexchange.com/users/73239/clemc\">ClemC</a> in <a href=\"https://wordpress.stackexchange.com/a/276782/44326\">his answer</a>) is good enough for that. But if you need <strong>preg_replace()</strong>, there is no WP plugin offering that, as far as I know. Still, there is a tool offering <strong>preg_replace()</strong>: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search Replace DB</a>. Since the tool offers no authentication, it could be used by anybody who could guess the url of the script. As a precaution, I would use this method to install the script: create a folder with a secret name, <a href=\"http://www.htaccesstools.com/articles/password-protection/\" rel=\"nofollow noreferrer\">protect it with a password using .htaccess</a>, then copy the script to that folder. After you're done with it, delete the script from the server. Don't leave it unprotected on your server, as versions of this script <a href=\"https://www.wordfence.com/blog/2017/07/searchreplacedb2-security/\" rel=\"nofollow noreferrer\">are targeted by hackers</a>, causing <a href=\"https://www.wordfence.com/blog/2017/08/traffictrade-malware/\" rel=\"nofollow noreferrer\">serious problems</a> to WP users.</p>\n" }, { "answer_id": 276824, "author": "Dylan", "author_id": 41351, "author_profile": "https://wordpress.stackexchange.com/users/41351", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://wp-cli.org/\" rel=\"nofollow noreferrer\">WP CLI</a> is a great tool for performing common admin and maintenance tasks on a WordPress install. It has a large <a href=\"https://developer.wordpress.org/cli/commands/\" rel=\"nofollow noreferrer\">range of commands</a> that among other things allow you to install plugins, regenerate thumbnails, and in your case, perform a <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">search and replace</a> on the database.</p>\n\n<p>When migrating from dev to production I'd normally run the following command to update URLs in the database:</p>\n\n<pre><code>wp search-replace '//dev.example.com/' '//www.example.com/'\n</code></pre>\n\n<p>With your existing URL structure you'll probably need to include the <code>href=\"</code> in the search and replace string like so:</p>\n\n<pre><code>wp search-replace 'href=\"/' 'href=\"http://example.com/'\n</code></pre>\n" } ]
2017/08/13
[ "https://wordpress.stackexchange.com/questions/276781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117731/" ]
I'm wrapping up a port from Jekyll to WordPress and have several thousand relative URLs I need to remap so they're absolute within my posts. **Actual URL examples:** ``` /gangs/gangster-disciples /housing-projects/cabrini-green /hoods/bridgeport ``` **Expected URL samples:** ``` http://example.com/gang/gangster-disciples http://example.com/project/cabrini-green http://example.com/neighborhood/bridgeport ``` Dax isn't turning up anything useful based on my search phrases and I'm not able to find any plugins or similar questions to study. Short of writing some update queries I'm curious to know if there's a more streamlined solution available I may be overlooking, such as a plugin-based solution. What's the easiest way to remap the example relative URLs to absolute?
[WP CLI](http://wp-cli.org/) is a great tool for performing common admin and maintenance tasks on a WordPress install. It has a large [range of commands](https://developer.wordpress.org/cli/commands/) that among other things allow you to install plugins, regenerate thumbnails, and in your case, perform a [search and replace](https://developer.wordpress.org/cli/commands/search-replace/) on the database. When migrating from dev to production I'd normally run the following command to update URLs in the database: ``` wp search-replace '//dev.example.com/' '//www.example.com/' ``` With your existing URL structure you'll probably need to include the `href="` in the search and replace string like so: ``` wp search-replace 'href="/' 'href="http://example.com/' ```
276,801
<p>I have a custom search page (<code>searchpage.php</code>) using pagination, and I am tring to add lines like below dynamically to my <code>header.php</code> inside <code>&lt;head&gt;&lt;/head&gt;</code> tag for better <a href="https://www.ayima.com/knowledge/guides/conquering-pagination-guide.html" rel="nofollow noreferrer">pagination SEO</a>.</p> <pre><code>&lt;link rel="prev" href="https://www.example.com/search/cats/page/2/"&gt; &lt;link rel="next" href="https://www.example.com/search/cats/page/4/"&gt; </code></pre> <p>While doing this, I have used below code mentioned <a href="https://wordpress.stackexchange.com/a/36834/112778">here</a> in <strong>functions.php</strong>. </p> <pre><code>&lt;?php function rel_next_prev(){ global $paged; if ( get_previous_posts_link() ) { ?&gt; &lt;link rel="prev" href="&lt;?php echo get_pagenum_link( $paged - 1 ); ?&gt;" /&gt;&lt;?php } if ( get_next_posts_link() ) { ?&gt; &lt;link rel="next" href="&lt;?php echo get_pagenum_link( $paged +1 ); ?&gt;" /&gt;&lt;?php } } add_action( 'wp_head', 'rel_next_prev' ); ?&gt; </code></pre> <p><code>get_previous_posts_link()</code> works fine, but <code>get_next_posts_link</code> doesn't work, after some investigation I believe it requires <code>max_num_pages</code> parameter to work. </p> <p>Now I am not able to get <code>max_num_pages</code> because it is in <code>searchpage.php</code>. </p>
[ { "answer_id": 276782, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 2, "selected": false, "text": "<p>There are several plugin solutions such as <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search and Replace</a> which will \"bulkly\" update almost whatever you want in DB. This one has a \"Replace a Domain / Url” special feature:</p>\n\n<blockquote>\n <p>Useful for a quick and simple transfer or a migration of an WordPress.</p>\n</blockquote>\n" }, { "answer_id": 276795, "author": "Mihai Papuc", "author_id": 44326, "author_profile": "https://wordpress.stackexchange.com/users/44326", "pm_score": 1, "selected": false, "text": "<p>If you switched from a different system to WP, first you would need a proper redirection set up - either manually in <strong>.htaccess</strong>, or using a plugin like <a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">Simple 301 Redirects</a>.</p>\n\n<p>This would help the search engines find your pages, and it would also take care of your links - at least for starters. </p>\n\n<p>After you're done with this step, if you need simple search and replace, the plugin <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search and Replace</a> (already mentioned by <a href=\"https://wordpress.stackexchange.com/users/73239/clemc\">ClemC</a> in <a href=\"https://wordpress.stackexchange.com/a/276782/44326\">his answer</a>) is good enough for that. But if you need <strong>preg_replace()</strong>, there is no WP plugin offering that, as far as I know. Still, there is a tool offering <strong>preg_replace()</strong>: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search Replace DB</a>. Since the tool offers no authentication, it could be used by anybody who could guess the url of the script. As a precaution, I would use this method to install the script: create a folder with a secret name, <a href=\"http://www.htaccesstools.com/articles/password-protection/\" rel=\"nofollow noreferrer\">protect it with a password using .htaccess</a>, then copy the script to that folder. After you're done with it, delete the script from the server. Don't leave it unprotected on your server, as versions of this script <a href=\"https://www.wordfence.com/blog/2017/07/searchreplacedb2-security/\" rel=\"nofollow noreferrer\">are targeted by hackers</a>, causing <a href=\"https://www.wordfence.com/blog/2017/08/traffictrade-malware/\" rel=\"nofollow noreferrer\">serious problems</a> to WP users.</p>\n" }, { "answer_id": 276824, "author": "Dylan", "author_id": 41351, "author_profile": "https://wordpress.stackexchange.com/users/41351", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://wp-cli.org/\" rel=\"nofollow noreferrer\">WP CLI</a> is a great tool for performing common admin and maintenance tasks on a WordPress install. It has a large <a href=\"https://developer.wordpress.org/cli/commands/\" rel=\"nofollow noreferrer\">range of commands</a> that among other things allow you to install plugins, regenerate thumbnails, and in your case, perform a <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">search and replace</a> on the database.</p>\n\n<p>When migrating from dev to production I'd normally run the following command to update URLs in the database:</p>\n\n<pre><code>wp search-replace '//dev.example.com/' '//www.example.com/'\n</code></pre>\n\n<p>With your existing URL structure you'll probably need to include the <code>href=\"</code> in the search and replace string like so:</p>\n\n<pre><code>wp search-replace 'href=\"/' 'href=\"http://example.com/'\n</code></pre>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112778/" ]
I have a custom search page (`searchpage.php`) using pagination, and I am tring to add lines like below dynamically to my `header.php` inside `<head></head>` tag for better [pagination SEO](https://www.ayima.com/knowledge/guides/conquering-pagination-guide.html). ``` <link rel="prev" href="https://www.example.com/search/cats/page/2/"> <link rel="next" href="https://www.example.com/search/cats/page/4/"> ``` While doing this, I have used below code mentioned [here](https://wordpress.stackexchange.com/a/36834/112778) in **functions.php**. ``` <?php function rel_next_prev(){ global $paged; if ( get_previous_posts_link() ) { ?> <link rel="prev" href="<?php echo get_pagenum_link( $paged - 1 ); ?>" /><?php } if ( get_next_posts_link() ) { ?> <link rel="next" href="<?php echo get_pagenum_link( $paged +1 ); ?>" /><?php } } add_action( 'wp_head', 'rel_next_prev' ); ?> ``` `get_previous_posts_link()` works fine, but `get_next_posts_link` doesn't work, after some investigation I believe it requires `max_num_pages` parameter to work. Now I am not able to get `max_num_pages` because it is in `searchpage.php`.
[WP CLI](http://wp-cli.org/) is a great tool for performing common admin and maintenance tasks on a WordPress install. It has a large [range of commands](https://developer.wordpress.org/cli/commands/) that among other things allow you to install plugins, regenerate thumbnails, and in your case, perform a [search and replace](https://developer.wordpress.org/cli/commands/search-replace/) on the database. When migrating from dev to production I'd normally run the following command to update URLs in the database: ``` wp search-replace '//dev.example.com/' '//www.example.com/' ``` With your existing URL structure you'll probably need to include the `href="` in the search and replace string like so: ``` wp search-replace 'href="/' 'href="http://example.com/' ```
276,802
<p>I am trying to do a simple basic shortcode and it fails. I have boiled it down to the most simple test and it still fails.</p> <p>Here is the code:</p> <pre><code>/** My test shortcode */ function bp_basic_shortcode() { return "This is a shortcode doing this!"; } add_shortcode( 'basic_shortcode', 'bp_basic_shortcode'); </code></pre> <p>In trying to figure out what is the reason I have:</p> <p>I have put this in the functions.php file of the stock template twentytwelve</p> <p>I have deactivated all plugins</p> <p>I have added the shortcode [basic-shortcode] in both a post and a page as a test with the same result.</p> <p>I used the "text" tab of the editor to add the shortcode</p> <p>I see just the text of [basic-shortcode] but it is not being processed.</p> <p>I even installed a plugin to show all active shortcodes and it is indeed in the list.</p> <p>I have tried it both on an instance of my MAMP server and one on my VPS</p> <p>This should be really simple. What am I missing??</p>
[ { "answer_id": 276803, "author": "jmcbade", "author_id": 125814, "author_profile": "https://wordpress.stackexchange.com/users/125814", "pm_score": -1, "selected": false, "text": "<p>Silly spell check on the MAC - It's \"shortcodes\" not \"shortcakes\"</p>\n\n<p>But to answer the question - this is SO trivial stupid and I had not seen this mentioned anywhere: You MAY NOT use an underscore in the shortcode tag.</p>\n\n<p>Maybe this will help someone else. I sure hope so.</p>\n" }, { "answer_id": 276806, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>You registered the shortcode <code>basic_shortcode</code>, but you tested the wrong <code>[basic-shortcode]</code>. These are two different things.</p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125814/" ]
I am trying to do a simple basic shortcode and it fails. I have boiled it down to the most simple test and it still fails. Here is the code: ``` /** My test shortcode */ function bp_basic_shortcode() { return "This is a shortcode doing this!"; } add_shortcode( 'basic_shortcode', 'bp_basic_shortcode'); ``` In trying to figure out what is the reason I have: I have put this in the functions.php file of the stock template twentytwelve I have deactivated all plugins I have added the shortcode [basic-shortcode] in both a post and a page as a test with the same result. I used the "text" tab of the editor to add the shortcode I see just the text of [basic-shortcode] but it is not being processed. I even installed a plugin to show all active shortcodes and it is indeed in the list. I have tried it both on an instance of my MAMP server and one on my VPS This should be really simple. What am I missing??
You registered the shortcode `basic_shortcode`, but you tested the wrong `[basic-shortcode]`. These are two different things.
276,805
<p><a href="https://vip.wordpress.com/documentation/performance-improvements-by-removing-usage-of-post__not_in/" rel="nofollow noreferrer">WordPress VIP</a> and other <a href="https://10up.github.io/Engineering-Best-Practices/php/#efficient-database-queries" rel="nofollow noreferrer">development guides</a> I've seen recommend avoiding the use of post__not_in for performance reasons when using WordPress at scale. Their suggestion is to filter out the posts in php:</p> <pre><code>$posts_to_exclude = [ 67, 68, 69 ]; $query = new WP_Query( [ 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 5 + count( $posts_to_exclude ), 'paged' =&gt; get_query_var( 'paged' ), ] ); if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); if ( in_array( get_the_ID(), $posts_to_exclude, true ) ) { continue; } the_title(); endwhile; endif; </code></pre> <p>My question is how do you show the correct number of posts per page when filtering out the posts via php? The example above adds the count of the excluded posts to the posts_per_page variable. However this would result in there being between 5 – 8 posts per page depending on how many posts are excluded for a particular page. Is there a workable solution for making the number of posts per page consistent or is this optimisation only really meant for posts that aren't going to be paginated?</p>
[ { "answer_id": 276803, "author": "jmcbade", "author_id": 125814, "author_profile": "https://wordpress.stackexchange.com/users/125814", "pm_score": -1, "selected": false, "text": "<p>Silly spell check on the MAC - It's \"shortcodes\" not \"shortcakes\"</p>\n\n<p>But to answer the question - this is SO trivial stupid and I had not seen this mentioned anywhere: You MAY NOT use an underscore in the shortcode tag.</p>\n\n<p>Maybe this will help someone else. I sure hope so.</p>\n" }, { "answer_id": 276806, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>You registered the shortcode <code>basic_shortcode</code>, but you tested the wrong <code>[basic-shortcode]</code>. These are two different things.</p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276805", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41351/" ]
[WordPress VIP](https://vip.wordpress.com/documentation/performance-improvements-by-removing-usage-of-post__not_in/) and other [development guides](https://10up.github.io/Engineering-Best-Practices/php/#efficient-database-queries) I've seen recommend avoiding the use of post\_\_not\_in for performance reasons when using WordPress at scale. Their suggestion is to filter out the posts in php: ``` $posts_to_exclude = [ 67, 68, 69 ]; $query = new WP_Query( [ 'post_type' => 'post', 'posts_per_page' => 5 + count( $posts_to_exclude ), 'paged' => get_query_var( 'paged' ), ] ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); if ( in_array( get_the_ID(), $posts_to_exclude, true ) ) { continue; } the_title(); endwhile; endif; ``` My question is how do you show the correct number of posts per page when filtering out the posts via php? The example above adds the count of the excluded posts to the posts\_per\_page variable. However this would result in there being between 5 – 8 posts per page depending on how many posts are excluded for a particular page. Is there a workable solution for making the number of posts per page consistent or is this optimisation only really meant for posts that aren't going to be paginated?
You registered the shortcode `basic_shortcode`, but you tested the wrong `[basic-shortcode]`. These are two different things.
276,825
<p>I developed a Plugin.It automatically creates the video URLs in the database.</p> <p>The table consists of id, title, URL, Thurl. We can send the content to the database using the form from the wp-admin panel(If videos by pk).</p> <p>I want to retrieve the rows from the database and display them.First when the page loads, it should show only 3 URLs and when clicked on load more it should show 3 more and so on.Basically, I need to know how to implement ajax in WordPress.</p> <p><a href="http://demos.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/" rel="nofollow noreferrer">http://demos.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/</a> Wordpress plugin should be making something like the above URL.</p> <p>Please help me to solve this.</p> <p>Below is the code for it.</p> <pre><code> &lt;?php /* Plugin Name: pkvideos Plugin URI: http://pavan.com Author: Pavan Version: 1.0 Description: Videos of IndianFolk. Text Domain: pavan Requires at least: 3.0 Tested up to: 4.7.3 */ add_action('admin_menu', 'test_plugin_setup_menu'); function test_plugin_setup_menu(){ add_menu_page( 'If Videos', 'If Videos by PK', 'manage_options', 'if-videos-by-pk', 'postvideo' ); add_submenu_page('if-videos-by-pk', 'Edit Videos', 'Edit Videos', 'manage_options', 'if-videos-edit' ); add_submenu_page('if-videos-by-pk', 'About Me', 'About Me', 'manage_options', 'if-videos-about' ); } function postvideo(){ echo "&lt;h1&gt;IndianFolk Videos&lt;/h1&gt;"; ?&gt; &lt;form action="" method="post"&gt; Title :&lt;input type="text" name="title" required&gt;&lt;br&gt; Video Url: &lt;input type="text" name="url" required&gt;&lt;br&gt; Thumbnail Url: &lt;input type="text" name="thurl" required&gt;&lt;br&gt; &lt;input type="submit" value="Submit" name="submit"&gt; &lt;/form&gt; &lt;?php if(isset($_POST['submit'])){ //check if form was submitted $title = $_POST['title']; //get input text $url = $_POST['url']; $thurl = $_POST['thurl']; $aData = array( 'title' =&gt; $title, 'url' =&gt; $url, 'thurl'=&gt; $thurl ); global $wpdb; $res = $wpdb-&gt;insert('wp_ifvideos', $aData); $siteurll=get_site_url(); } } function create_plugin_database_table() { global $wpdb; $table_name = $wpdb-&gt;prefix . 'ifvideos'; $sql = "CREATE TABLE $table_name ( id mediumint(9) unsigned NOT NULL AUTO_INCREMENT, title varchar(50) NOT NULL, url longtext NOT NULL, thurl longtext NOT NULL, PRIMARY KEY (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'create_plugin_database_table' ); /*=//This is used for adding form as the shortcode in pages or posts or widgets function wp_first_shortcode(){ echo "Hello, This is your another shortcode!"; ?&gt; &lt;form action="" method="post"&gt; Title :&lt;input type="text" name="title"&gt;&lt;br&gt; Url: &lt;input type="text" name="url"&gt;&lt;br&gt; Thumbnail Url: &lt;input type="text" name="thurl"&gt;&lt;br&gt; &lt;input type="submit" value="Submit" name="submit"&gt; &lt;/form&gt; &lt;?php if(isset($_POST['submit'])){ //check if form was submitted $title = $_POST['title']; //get input text $url = $_POST['url']; $thurl = $_POST['thurl']; $aData = array( 'title' =&gt; $title, 'url' =&gt; $url, 'thurl'=&gt; $thurl ); global $wpdb; $res = $wpdb-&gt;insert('wp_ifvideos', $aData); $siteurll=get_site_url(); } }//this is used for adding short code add_shortcode('first', 'wp_first_shortcode');*/ function videos_info() { global $wpdb; $videos = $wpdb-&gt;get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); foreach ( $videos as $video ) { //Here $user[1], 1 is the column number. echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '&lt;br&gt;'; } ?&gt; &lt;?php } add_shortcode('showinfo','videos_info'); function video_ajax() { ?&gt; &lt;?php } add_shortcode('ajaxvideo','video_ajax'); ?&gt; </code></pre> <p>Please help me making the changes to the below code.</p> <pre><code>$videos = $wpdb-&gt;get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); foreach ( $videos as $video ) { //Here $user[1], 1 is the column number. echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '&lt;br&gt;'; } ?&gt; &lt;?php } add_shortcode('showinfo','videos_info'); function video_ajax() { ?&gt; &lt;?php } </code></pre>
[ { "answer_id": 277011, "author": "Thamaraiselvam", "author_id": 67717, "author_profile": "https://wordpress.stackexchange.com/users/67717", "pm_score": 2, "selected": false, "text": "<p>Here is Codex to make proper ajax calls\n<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>Its very simple add action to your Ajax.</p>\n\n<p>Also read about nonce \n<a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Nonces</a></p>\n" }, { "answer_id": 277468, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": true, "text": "<p>Here is one approach, by using an <code>iframe</code> for the AJAX request it can be much easier to learn and debug your AJAX code... try this:</p>\n\n<pre><code>function videos_info() {\n global $wpdb; \n\n // add LIMIT 3 here\n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3\" , ARRAY_N);\n\n foreach ( $videos as $video ) {\n echo do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n echo $video[1]. '&lt;br&gt;';\n }\n\n $ajaxurl = admin_url('admin-ajax.php');\n echo \"&lt;iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'&gt;&lt;/iframe&gt;\";\n echo \"&lt;script&gt;function loadmorevideos(offset) {\n document.getElementById('loadmorevids').src = '\".$ajaxurl.\"?action=video_ajax&amp;offset='+offset;}&lt;/script&gt;\"; \n echo \"&lt;div id='morevideos-3'&gt;&lt;a href='javascript:void(0);' onclick='loadmorevideos(\\\"3\\\");'&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;\";\n}\n\n// For Logged in Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n// For Logged Out Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n\nfunction video_ajax() {\n\n global $wpdb; \n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC\" , ARRAY_N);\n\n $offset = $_GET['offset']; $html = '';\n foreach ( $videos as $i =&gt; $video ) {\n // limit to 3 videos using offset\n if ( ($i &gt; ($offset-1)) &amp;&amp; ($i &lt; ($offset+2)) ) {\n $html .= do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n $html .= $video[1]. '&lt;br&gt;';\n }\n }\n\n // append the new load more link\n $html .= '&lt;div id=\"morevideos-'.($offset+3).'\"&gt;';\n $html .= '&lt;a href=\"javascript:void(0);\" onclick=\"loadmorevids('.($offset+3).');\"&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;';\n\n // replace any single quotes with escaped ones\n $html = str_replace(\"'\", \"\\\\'\", $html);\n // (or alternatively)\n // $html = str_replace(\"'\", \"&amp;apos;\", $html);\n\n // replace the previous loadmore link with the loaded videos\n echo \"&lt;script&gt;parent.document.getElementById('morevideos-\".$offset.\"').innerHTML = '\".$html.\"';&lt;/script&gt;\";\n exit;\n\n}\n</code></pre>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125822/" ]
I developed a Plugin.It automatically creates the video URLs in the database. The table consists of id, title, URL, Thurl. We can send the content to the database using the form from the wp-admin panel(If videos by pk). I want to retrieve the rows from the database and display them.First when the page loads, it should show only 3 URLs and when clicked on load more it should show 3 more and so on.Basically, I need to know how to implement ajax in WordPress. <http://demos.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/> Wordpress plugin should be making something like the above URL. Please help me to solve this. Below is the code for it. ``` <?php /* Plugin Name: pkvideos Plugin URI: http://pavan.com Author: Pavan Version: 1.0 Description: Videos of IndianFolk. Text Domain: pavan Requires at least: 3.0 Tested up to: 4.7.3 */ add_action('admin_menu', 'test_plugin_setup_menu'); function test_plugin_setup_menu(){ add_menu_page( 'If Videos', 'If Videos by PK', 'manage_options', 'if-videos-by-pk', 'postvideo' ); add_submenu_page('if-videos-by-pk', 'Edit Videos', 'Edit Videos', 'manage_options', 'if-videos-edit' ); add_submenu_page('if-videos-by-pk', 'About Me', 'About Me', 'manage_options', 'if-videos-about' ); } function postvideo(){ echo "<h1>IndianFolk Videos</h1>"; ?> <form action="" method="post"> Title :<input type="text" name="title" required><br> Video Url: <input type="text" name="url" required><br> Thumbnail Url: <input type="text" name="thurl" required><br> <input type="submit" value="Submit" name="submit"> </form> <?php if(isset($_POST['submit'])){ //check if form was submitted $title = $_POST['title']; //get input text $url = $_POST['url']; $thurl = $_POST['thurl']; $aData = array( 'title' => $title, 'url' => $url, 'thurl'=> $thurl ); global $wpdb; $res = $wpdb->insert('wp_ifvideos', $aData); $siteurll=get_site_url(); } } function create_plugin_database_table() { global $wpdb; $table_name = $wpdb->prefix . 'ifvideos'; $sql = "CREATE TABLE $table_name ( id mediumint(9) unsigned NOT NULL AUTO_INCREMENT, title varchar(50) NOT NULL, url longtext NOT NULL, thurl longtext NOT NULL, PRIMARY KEY (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'create_plugin_database_table' ); /*=//This is used for adding form as the shortcode in pages or posts or widgets function wp_first_shortcode(){ echo "Hello, This is your another shortcode!"; ?> <form action="" method="post"> Title :<input type="text" name="title"><br> Url: <input type="text" name="url"><br> Thumbnail Url: <input type="text" name="thurl"><br> <input type="submit" value="Submit" name="submit"> </form> <?php if(isset($_POST['submit'])){ //check if form was submitted $title = $_POST['title']; //get input text $url = $_POST['url']; $thurl = $_POST['thurl']; $aData = array( 'title' => $title, 'url' => $url, 'thurl'=> $thurl ); global $wpdb; $res = $wpdb->insert('wp_ifvideos', $aData); $siteurll=get_site_url(); } }//this is used for adding short code add_shortcode('first', 'wp_first_shortcode');*/ function videos_info() { global $wpdb; $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); foreach ( $videos as $video ) { //Here $user[1], 1 is the column number. echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '<br>'; } ?> <?php } add_shortcode('showinfo','videos_info'); function video_ajax() { ?> <?php } add_shortcode('ajaxvideo','video_ajax'); ?> ``` Please help me making the changes to the below code. ``` $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); foreach ( $videos as $video ) { //Here $user[1], 1 is the column number. echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '<br>'; } ?> <?php } add_shortcode('showinfo','videos_info'); function video_ajax() { ?> <?php } ```
Here is one approach, by using an `iframe` for the AJAX request it can be much easier to learn and debug your AJAX code... try this: ``` function videos_info() { global $wpdb; // add LIMIT 3 here $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3" , ARRAY_N); foreach ( $videos as $video ) { echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '<br>'; } $ajaxurl = admin_url('admin-ajax.php'); echo "<iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'></iframe>"; echo "<script>function loadmorevideos(offset) { document.getElementById('loadmorevids').src = '".$ajaxurl."?action=video_ajax&offset='+offset;}</script>"; echo "<div id='morevideos-3'><a href='javascript:void(0);' onclick='loadmorevideos(\"3\");'>Load More Videos</a></div>"; } // For Logged in Users add_action('wp_ajax_video_ajax', 'video_ajax'); // For Logged Out Users add_action('wp_ajax_video_ajax', 'video_ajax'); function video_ajax() { global $wpdb; $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); $offset = $_GET['offset']; $html = ''; foreach ( $videos as $i => $video ) { // limit to 3 videos using offset if ( ($i > ($offset-1)) && ($i < ($offset+2)) ) { $html .= do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); $html .= $video[1]. '<br>'; } } // append the new load more link $html .= '<div id="morevideos-'.($offset+3).'">'; $html .= '<a href="javascript:void(0);" onclick="loadmorevids('.($offset+3).');">Load More Videos</a></div>'; // replace any single quotes with escaped ones $html = str_replace("'", "\\'", $html); // (or alternatively) // $html = str_replace("'", "&apos;", $html); // replace the previous loadmore link with the loaded videos echo "<script>parent.document.getElementById('morevideos-".$offset."').innerHTML = '".$html."';</script>"; exit; } ```
276,842
<p>I've a custom post type <code>Clinics</code> and <code>Doctors</code>. Each clinic has own clinic_id (through custom fields). Each doctor has the same field <code>clinic_id</code> with numbers of clinics where he works. </p> <p>I need on <code>single-clinic.php</code> to display all doctors, that working here (compare clinic_id of a doctor with clinic_id of current page).</p> <p>To do this I create new <code>WP_Query</code> object with list of all doctors and then if clinic_id (on clinic page) == clinic_id (on doctors page), display them.</p> <p>The thing is that there are a lot of doctors (more 5k pages), so when I try to set <code>'posts_per_page' =&gt; -1</code> it's not working. </p> <pre><code>$args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'doctors', 'orderby' =&gt; "ID", 'nopaging' =&gt; true ); $listDoctors = new WP_Query($args); </code></pre> <p>Have you any idea how to do this working?</p>
[ { "answer_id": 277011, "author": "Thamaraiselvam", "author_id": 67717, "author_profile": "https://wordpress.stackexchange.com/users/67717", "pm_score": 2, "selected": false, "text": "<p>Here is Codex to make proper ajax calls\n<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>Its very simple add action to your Ajax.</p>\n\n<p>Also read about nonce \n<a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Nonces</a></p>\n" }, { "answer_id": 277468, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": true, "text": "<p>Here is one approach, by using an <code>iframe</code> for the AJAX request it can be much easier to learn and debug your AJAX code... try this:</p>\n\n<pre><code>function videos_info() {\n global $wpdb; \n\n // add LIMIT 3 here\n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3\" , ARRAY_N);\n\n foreach ( $videos as $video ) {\n echo do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n echo $video[1]. '&lt;br&gt;';\n }\n\n $ajaxurl = admin_url('admin-ajax.php');\n echo \"&lt;iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'&gt;&lt;/iframe&gt;\";\n echo \"&lt;script&gt;function loadmorevideos(offset) {\n document.getElementById('loadmorevids').src = '\".$ajaxurl.\"?action=video_ajax&amp;offset='+offset;}&lt;/script&gt;\"; \n echo \"&lt;div id='morevideos-3'&gt;&lt;a href='javascript:void(0);' onclick='loadmorevideos(\\\"3\\\");'&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;\";\n}\n\n// For Logged in Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n// For Logged Out Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n\nfunction video_ajax() {\n\n global $wpdb; \n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC\" , ARRAY_N);\n\n $offset = $_GET['offset']; $html = '';\n foreach ( $videos as $i =&gt; $video ) {\n // limit to 3 videos using offset\n if ( ($i &gt; ($offset-1)) &amp;&amp; ($i &lt; ($offset+2)) ) {\n $html .= do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n $html .= $video[1]. '&lt;br&gt;';\n }\n }\n\n // append the new load more link\n $html .= '&lt;div id=\"morevideos-'.($offset+3).'\"&gt;';\n $html .= '&lt;a href=\"javascript:void(0);\" onclick=\"loadmorevids('.($offset+3).');\"&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;';\n\n // replace any single quotes with escaped ones\n $html = str_replace(\"'\", \"\\\\'\", $html);\n // (or alternatively)\n // $html = str_replace(\"'\", \"&amp;apos;\", $html);\n\n // replace the previous loadmore link with the loaded videos\n echo \"&lt;script&gt;parent.document.getElementById('morevideos-\".$offset.\"').innerHTML = '\".$html.\"';&lt;/script&gt;\";\n exit;\n\n}\n</code></pre>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276842", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125831/" ]
I've a custom post type `Clinics` and `Doctors`. Each clinic has own clinic\_id (through custom fields). Each doctor has the same field `clinic_id` with numbers of clinics where he works. I need on `single-clinic.php` to display all doctors, that working here (compare clinic\_id of a doctor with clinic\_id of current page). To do this I create new `WP_Query` object with list of all doctors and then if clinic\_id (on clinic page) == clinic\_id (on doctors page), display them. The thing is that there are a lot of doctors (more 5k pages), so when I try to set `'posts_per_page' => -1` it's not working. ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'doctors', 'orderby' => "ID", 'nopaging' => true ); $listDoctors = new WP_Query($args); ``` Have you any idea how to do this working?
Here is one approach, by using an `iframe` for the AJAX request it can be much easier to learn and debug your AJAX code... try this: ``` function videos_info() { global $wpdb; // add LIMIT 3 here $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3" , ARRAY_N); foreach ( $videos as $video ) { echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '<br>'; } $ajaxurl = admin_url('admin-ajax.php'); echo "<iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'></iframe>"; echo "<script>function loadmorevideos(offset) { document.getElementById('loadmorevids').src = '".$ajaxurl."?action=video_ajax&offset='+offset;}</script>"; echo "<div id='morevideos-3'><a href='javascript:void(0);' onclick='loadmorevideos(\"3\");'>Load More Videos</a></div>"; } // For Logged in Users add_action('wp_ajax_video_ajax', 'video_ajax'); // For Logged Out Users add_action('wp_ajax_video_ajax', 'video_ajax'); function video_ajax() { global $wpdb; $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); $offset = $_GET['offset']; $html = ''; foreach ( $videos as $i => $video ) { // limit to 3 videos using offset if ( ($i > ($offset-1)) && ($i < ($offset+2)) ) { $html .= do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); $html .= $video[1]. '<br>'; } } // append the new load more link $html .= '<div id="morevideos-'.($offset+3).'">'; $html .= '<a href="javascript:void(0);" onclick="loadmorevids('.($offset+3).');">Load More Videos</a></div>'; // replace any single quotes with escaped ones $html = str_replace("'", "\\'", $html); // (or alternatively) // $html = str_replace("'", "&apos;", $html); // replace the previous loadmore link with the loaded videos echo "<script>parent.document.getElementById('morevideos-".$offset."').innerHTML = '".$html."';</script>"; exit; } ```
276,844
<p>I would like to redirect to a post if the taxonomy term it belongs to has only one post assigned to it and so far I have this:</p> <pre><code>$term_id = get_queried_object()-&gt;term_id; $taxonomy_name = 'product_range'; $term_children = get_term_children( $term_id, $taxonomy_name ); foreach ( $term_children as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); if($term-&gt;count &lt;= 1 ) { echo '&lt;a href="'. get_term_link($child, $taxonomy_name) .'" class="thumb" title="'.$term-&gt;name.'"&gt;'.$term-&gt;name.'&lt;/a&gt;'; } } </code></pre> <p>This links through to the archive page but I want it to redirect the user to the relevant post, I am not sure what I need to do to change the permalink to go to the single post page.</p>
[ { "answer_id": 277011, "author": "Thamaraiselvam", "author_id": 67717, "author_profile": "https://wordpress.stackexchange.com/users/67717", "pm_score": 2, "selected": false, "text": "<p>Here is Codex to make proper ajax calls\n<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>Its very simple add action to your Ajax.</p>\n\n<p>Also read about nonce \n<a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Nonces</a></p>\n" }, { "answer_id": 277468, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": true, "text": "<p>Here is one approach, by using an <code>iframe</code> for the AJAX request it can be much easier to learn and debug your AJAX code... try this:</p>\n\n<pre><code>function videos_info() {\n global $wpdb; \n\n // add LIMIT 3 here\n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3\" , ARRAY_N);\n\n foreach ( $videos as $video ) {\n echo do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n echo $video[1]. '&lt;br&gt;';\n }\n\n $ajaxurl = admin_url('admin-ajax.php');\n echo \"&lt;iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'&gt;&lt;/iframe&gt;\";\n echo \"&lt;script&gt;function loadmorevideos(offset) {\n document.getElementById('loadmorevids').src = '\".$ajaxurl.\"?action=video_ajax&amp;offset='+offset;}&lt;/script&gt;\"; \n echo \"&lt;div id='morevideos-3'&gt;&lt;a href='javascript:void(0);' onclick='loadmorevideos(\\\"3\\\");'&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;\";\n}\n\n// For Logged in Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n// For Logged Out Users\nadd_action('wp_ajax_video_ajax', 'video_ajax');\n\nfunction video_ajax() {\n\n global $wpdb; \n $videos = $wpdb-&gt;get_results( \"SELECT * FROM wp_ifvideos ORDER BY id DESC\" , ARRAY_N);\n\n $offset = $_GET['offset']; $html = '';\n foreach ( $videos as $i =&gt; $video ) {\n // limit to 3 videos using offset\n if ( ($i &gt; ($offset-1)) &amp;&amp; ($i &lt; ($offset+2)) ) {\n $html .= do_shortcode(\"[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]\");\n $html .= $video[1]. '&lt;br&gt;';\n }\n }\n\n // append the new load more link\n $html .= '&lt;div id=\"morevideos-'.($offset+3).'\"&gt;';\n $html .= '&lt;a href=\"javascript:void(0);\" onclick=\"loadmorevids('.($offset+3).');\"&gt;Load More Videos&lt;/a&gt;&lt;/div&gt;';\n\n // replace any single quotes with escaped ones\n $html = str_replace(\"'\", \"\\\\'\", $html);\n // (or alternatively)\n // $html = str_replace(\"'\", \"&amp;apos;\", $html);\n\n // replace the previous loadmore link with the loaded videos\n echo \"&lt;script&gt;parent.document.getElementById('morevideos-\".$offset.\"').innerHTML = '\".$html.\"';&lt;/script&gt;\";\n exit;\n\n}\n</code></pre>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38592/" ]
I would like to redirect to a post if the taxonomy term it belongs to has only one post assigned to it and so far I have this: ``` $term_id = get_queried_object()->term_id; $taxonomy_name = 'product_range'; $term_children = get_term_children( $term_id, $taxonomy_name ); foreach ( $term_children as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); if($term->count <= 1 ) { echo '<a href="'. get_term_link($child, $taxonomy_name) .'" class="thumb" title="'.$term->name.'">'.$term->name.'</a>'; } } ``` This links through to the archive page but I want it to redirect the user to the relevant post, I am not sure what I need to do to change the permalink to go to the single post page.
Here is one approach, by using an `iframe` for the AJAX request it can be much easier to learn and debug your AJAX code... try this: ``` function videos_info() { global $wpdb; // add LIMIT 3 here $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC LIMIT 3" , ARRAY_N); foreach ( $videos as $video ) { echo do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); echo $video[1]. '<br>'; } $ajaxurl = admin_url('admin-ajax.php'); echo "<iframe style='display:none;' name='loadmorevids' id='loadmorevids' src='javascript:void(0);'></iframe>"; echo "<script>function loadmorevideos(offset) { document.getElementById('loadmorevids').src = '".$ajaxurl."?action=video_ajax&offset='+offset;}</script>"; echo "<div id='morevideos-3'><a href='javascript:void(0);' onclick='loadmorevideos(\"3\");'>Load More Videos</a></div>"; } // For Logged in Users add_action('wp_ajax_video_ajax', 'video_ajax'); // For Logged Out Users add_action('wp_ajax_video_ajax', 'video_ajax'); function video_ajax() { global $wpdb; $videos = $wpdb->get_results( "SELECT * FROM wp_ifvideos ORDER BY id DESC" , ARRAY_N); $offset = $_GET['offset']; $html = ''; foreach ( $videos as $i => $video ) { // limit to 3 videos using offset if ( ($i > ($offset-1)) && ($i < ($offset+2)) ) { $html .= do_shortcode("[video width='256' height='144' poster='$video[3]' mp4='$video[2]'][/video]"); $html .= $video[1]. '<br>'; } } // append the new load more link $html .= '<div id="morevideos-'.($offset+3).'">'; $html .= '<a href="javascript:void(0);" onclick="loadmorevids('.($offset+3).');">Load More Videos</a></div>'; // replace any single quotes with escaped ones $html = str_replace("'", "\\'", $html); // (or alternatively) // $html = str_replace("'", "&apos;", $html); // replace the previous loadmore link with the loaded videos echo "<script>parent.document.getElementById('morevideos-".$offset."').innerHTML = '".$html."';</script>"; exit; } ```
276,856
<p>I am building a WordPress website with an Underscore theme, it is hosted on flywheel. Everytime I make changes to a page, the styling <code>style.css</code> file is not picked up unless I do a hard reload/ clear cache. </p> <p>Obviously I want it to load on everyone's computer immediately without the need to clear the cache. What is the reason for this? and how can I resolve it?</p> <p>thanks.</p>
[ { "answer_id": 276859, "author": "HOY", "author_id": 112778, "author_profile": "https://wordpress.stackexchange.com/users/112778", "pm_score": 0, "selected": false, "text": "<p>Could be related to changing the expiration period by modifing <code>.htaccess</code>. </p>\n\n<p>For example my .htaccess has <code>access 1 month</code> for this action, and your could be like below:</p>\n\n<pre><code>&lt;IfModule mod_expires.c&gt;\nExpiresActive On\nExpiresByType text/css \"access plus 60 seconds\"\nExpiresDefault \"access 1 month\"\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 276861, "author": "gdaniel", "author_id": 30984, "author_profile": "https://wordpress.stackexchange.com/users/30984", "pm_score": 2, "selected": true, "text": "<p>If the files are being cached, then whatever caching solution you are using is working! That's why there's a clear caching button available. Typically JS and CSS files will be cached. While you are in development I recommend changing the version of the file being cached. This can be done by updating the wp_enqueue_script (js files) and wp_enqueue_style (css files) functions, typically found in functions.php. Taken from the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">codex</a>:</p>\n\n<pre><code>wp_enqueue_style( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, string $media = 'all' )\n</code></pre>\n\n<p>$ver: (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false</p>\n\n<p>In summary, find the function above in your functions.php file, and change the 4th parameter ($ver) to a string. Something like \"0.1\", and then each time you save a new style.css file, update the string to \"0.2\" and so forth. That way, the browser will always request a new file from the server. This is a great solution during development.</p>\n\n<p>You never specified what caching plugin you are using, or if it's something Flywheel does it for you, but you should have setting you can change so that the cache is cleared more often. </p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276856", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123149/" ]
I am building a WordPress website with an Underscore theme, it is hosted on flywheel. Everytime I make changes to a page, the styling `style.css` file is not picked up unless I do a hard reload/ clear cache. Obviously I want it to load on everyone's computer immediately without the need to clear the cache. What is the reason for this? and how can I resolve it? thanks.
If the files are being cached, then whatever caching solution you are using is working! That's why there's a clear caching button available. Typically JS and CSS files will be cached. While you are in development I recommend changing the version of the file being cached. This can be done by updating the wp\_enqueue\_script (js files) and wp\_enqueue\_style (css files) functions, typically found in functions.php. Taken from the [codex](https://developer.wordpress.org/reference/functions/wp_enqueue_style/): ``` wp_enqueue_style( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, string $media = 'all' ) ``` $ver: (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false In summary, find the function above in your functions.php file, and change the 4th parameter ($ver) to a string. Something like "0.1", and then each time you save a new style.css file, update the string to "0.2" and so forth. That way, the browser will always request a new file from the server. This is a great solution during development. You never specified what caching plugin you are using, or if it's something Flywheel does it for you, but you should have setting you can change so that the cache is cleared more often.
276,870
<p>I know this is much common and I did not find the right answer. So to show all possible image sizes I have done:</p> <pre><code>add_filter( 'image_size_names_choose', 'fashmag_image_sizes_choose' ); function fashmag_image_sizes_choose( $sizes ) { $image_sizes = get_intermediate_image_sizes(); return $image_sizes; } </code></pre> <p>This perfectly shows all image sizes but this puts the option value not name. So the generated HTML output </p> <pre><code>&lt;select class="size" name="size" data-setting="size"&gt; &lt;option value="0"&gt;thumbnail&lt;/option&gt; &lt;option value="1"&gt;medium&lt;/option&gt; &lt;option value="2"&gt;medium_large&lt;/option&gt; &lt;/select&gt; </code></pre> <p>In my gallery shortcode instead of putting <code>thumbnail</code> it puts <code>0</code></p> <pre><code>[gallery link="file" size="0" ids="124,125,108,103"] </code></pre> <p>How can I correct this i.e. put <code>thumbnail</code> instead of <code>0</code>? </p>
[ { "answer_id": 276860, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>In your options page each field should be put into an options array. For Example:</p>\n\n<p>When you registered your settings page you should have used a code like this:</p>\n\n<pre><code>register_setting( 'pluginPage', 'rt_fed_settings', 'rt_validate');\n</code></pre>\n\n<p>Once on your page where you want to call settings, use this code:</p>\n\n<pre><code>$options_fed = get_option('rt_fed_settings'); // this is calling your settings array into a variable called options_fed.\n</code></pre>\n\n<p>Now to call items from it you would call them just like any array items:</p>\n\n<pre><code>$options_fed['rt_fed_text_test_billing_field']\n</code></pre>\n\n<p>The array items were set in your plugins page, but if you want see what is in the code you can use print_r. </p>\n" }, { "answer_id": 276878, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 1, "selected": true, "text": "<p>Turns out it a lot simpler than I though. When you use <code>register_setting(\"something\", \"name\")</code> then to get it in the plugin, just use <code>get_option(\"name\")</code>.</p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48294/" ]
I know this is much common and I did not find the right answer. So to show all possible image sizes I have done: ``` add_filter( 'image_size_names_choose', 'fashmag_image_sizes_choose' ); function fashmag_image_sizes_choose( $sizes ) { $image_sizes = get_intermediate_image_sizes(); return $image_sizes; } ``` This perfectly shows all image sizes but this puts the option value not name. So the generated HTML output ``` <select class="size" name="size" data-setting="size"> <option value="0">thumbnail</option> <option value="1">medium</option> <option value="2">medium_large</option> </select> ``` In my gallery shortcode instead of putting `thumbnail` it puts `0` ``` [gallery link="file" size="0" ids="124,125,108,103"] ``` How can I correct this i.e. put `thumbnail` instead of `0`?
Turns out it a lot simpler than I though. When you use `register_setting("something", "name")` then to get it in the plugin, just use `get_option("name")`.
276,887
<p>I entered a header image as a logo to the theme ajaira. Although the image has the right size, it won't fit onto the page.</p> <p>Any help is much appreciated.</p> <p><a href="https://i.stack.imgur.com/nmvak.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nmvak.png" alt="enter image description here"></a></p>
[ { "answer_id": 276895, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you can look at the CSS class used for the header image, you can use some customized CSS to change the height of that class. Assuming class name of 'header_image':</p>\n\n<pre><code>.header_image {height:300px;}\n</code></pre>\n\n<p>Adjusting the value as needed. You would place that CSS in the 'additional CSS' area of the theme customization (if available). There are also plugins that will allow you to add CSS to your theme. Plus the route of creating a Child Theme and putting your custom CSS in there.</p>\n" }, { "answer_id": 276986, "author": "gdaniel", "author_id": 30984, "author_profile": "https://wordpress.stackexchange.com/users/30984", "pm_score": 1, "selected": false, "text": "<p>It looks like the background image was added to the tag inline. You will need to change the following:</p>\n\n<p>Locate your template file (probably header.php) which has the tag Inside style=\"\" remove <code>background-size: cover</code> and replace it with <code>background-size:auto 100%</code> then add <code>background-position: center</code></p>\n\n<p>This will let the background image stretch to the height of the element and adjust it's width automatically, and then it will center the image.</p>\n\n<p>You can achieve the same thing by editing the style.css file, and adding the above to header.site-header but you will need to use the !important tag if you want it to override the inline styles. Something like:</p>\n\n<pre><code>header.site-header{\n background-size:auto 100% !important;\n background-position: center\n}\n</code></pre>\n\n<p>I modified your page in the browser. Here's the result:</p>\n\n<p><a href=\"https://i.stack.imgur.com/KLqjD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KLqjD.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125845/" ]
I entered a header image as a logo to the theme ajaira. Although the image has the right size, it won't fit onto the page. Any help is much appreciated. [![enter image description here](https://i.stack.imgur.com/nmvak.png)](https://i.stack.imgur.com/nmvak.png)
It looks like the background image was added to the tag inline. You will need to change the following: Locate your template file (probably header.php) which has the tag Inside style="" remove `background-size: cover` and replace it with `background-size:auto 100%` then add `background-position: center` This will let the background image stretch to the height of the element and adjust it's width automatically, and then it will center the image. You can achieve the same thing by editing the style.css file, and adding the above to header.site-header but you will need to use the !important tag if you want it to override the inline styles. Something like: ``` header.site-header{ background-size:auto 100% !important; background-position: center } ``` I modified your page in the browser. Here's the result: [![enter image description here](https://i.stack.imgur.com/KLqjD.png)](https://i.stack.imgur.com/KLqjD.png)
276,889
<p>I am developing a website using wampserver on localhost and I am trying to view my site on mobile on my local network. </p> <p>I changed the home and site URL in <code>Settings &gt; General</code> from </p> <blockquote> <p><a href="http://localhost/site/wordpress" rel="nofollow noreferrer">http://localhost/site/wordpress</a></p> </blockquote> <p>To </p> <blockquote> <p><a href="http://ip/site/wordpress" rel="nofollow noreferrer">http://ip/site/wordpress</a></p> </blockquote> <p>I also used the velvet blues URL plugin to update my images etc. from localhost to my ip. </p> <p>All of my images across my site will display on mobile except for the homepage background row images. I have checked the URL in chrome developers tools and the URL path is the same as the images that are displaying. I'm at a loss as how to proceed. </p> <p>Any help would be great.</p>
[ { "answer_id": 276965, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>Relative paths act differently when they are used in a CSS file. The behavior is still the same, and the path is still relative, but to a human it might seem confusing. </p>\n\n<p>When you use a path like this for your image:</p>\n\n<pre><code>&lt;img src=\"/path/image.jpg\"/&gt;\n</code></pre>\n\n<p>The browser will look inside the <code>path</code> folder, located at the root of the current web. But when you use the very same value inside your CSS:</p>\n\n<pre><code>background-image: url( '/path/image.jpg' );\n</code></pre>\n\n<p>The story is different. The browser will look inside the <code>path</code> folder, based on where the <em>stylesheet</em> is located, not the current URL. So, if the stylesheet is located at:</p>\n\n<pre><code>www.example.com/wp-content/themes/twentyseven/\n</code></pre>\n\n<p>Then browser will look for:</p>\n\n<pre><code>www.example.com/wp-content/themes/twentyseven/path/image.jpg\n</code></pre>\n\n<p>Which doesn't exist. So it's important to build your CSS paths relative to the stylesheet's path.</p>\n\n<p>For a further understanding, have a look <a href=\"https://www.w3schools.com/html/html_filepaths.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 277719, "author": "Bravo Foxtrot", "author_id": 125843, "author_profile": "https://wordpress.stackexchange.com/users/125843", "pm_score": 0, "selected": false, "text": "<p>The problem wasn't with the img src or background-image url, it was with Apache and the firewall. I'm still not sure why, but when I changed the http.vhosts.config file and refreshed wamp server and then turned off the firewall settings for Wamp, the images are viewable. If I did it the other way around changing the firewall and then Apache, the images weren't viewable.</p>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125843/" ]
I am developing a website using wampserver on localhost and I am trying to view my site on mobile on my local network. I changed the home and site URL in `Settings > General` from > > <http://localhost/site/wordpress> > > > To > > <http://ip/site/wordpress> > > > I also used the velvet blues URL plugin to update my images etc. from localhost to my ip. All of my images across my site will display on mobile except for the homepage background row images. I have checked the URL in chrome developers tools and the URL path is the same as the images that are displaying. I'm at a loss as how to proceed. Any help would be great.
Relative paths act differently when they are used in a CSS file. The behavior is still the same, and the path is still relative, but to a human it might seem confusing. When you use a path like this for your image: ``` <img src="/path/image.jpg"/> ``` The browser will look inside the `path` folder, located at the root of the current web. But when you use the very same value inside your CSS: ``` background-image: url( '/path/image.jpg' ); ``` The story is different. The browser will look inside the `path` folder, based on where the *stylesheet* is located, not the current URL. So, if the stylesheet is located at: ``` www.example.com/wp-content/themes/twentyseven/ ``` Then browser will look for: ``` www.example.com/wp-content/themes/twentyseven/path/image.jpg ``` Which doesn't exist. So it's important to build your CSS paths relative to the stylesheet's path. For a further understanding, have a look [here](https://www.w3schools.com/html/html_filepaths.asp).
276,890
<p>I have a whole entire <code>js</code> folder of scripts and it would be tedious to have to load them all with <code>wp_enqueue_script()</code> one by one. </p> <p>Is there a way I can just insert the directory they are all in and it do it for me?</p>
[ { "answer_id": 276897, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>There's nothing wrong with enqueuing many files by using <code>wp_enqueue_script</code>. If you are referring to it as frustrating, then there is a simple solution for this.</p>\n\n<p>PHP offers a function that can list files and directories. By using <a href=\"http://php.net/manual/en/function.glob.php\" rel=\"noreferrer\"><code>glob</code></a> you can list every <code>.js</code> file in your directory, and then enqueue them by a loop.</p>\n\n<pre><code>function enqueue_my_scripts(){\n foreach( glob( get_template_directory(). '/path/*.js' ) as $file ) {\n // $file contains the name and extension of the file\n wp_enqueue_script( $file, get_template_directory_uri().'/path/'.$file);\n }\n}\nadd_action('wp_enqueue_scripts', 'enqueue_my_scripts');\n</code></pre>\n\n<p>A side not is that <code>glob</code> uses relative path, but <code>wp_enqueue_script</code> uses URLs. That is why I used different functions to get the folder's path and URI.</p>\n" }, { "answer_id": 289802, "author": "pixelslave", "author_id": 134023, "author_profile": "https://wordpress.stackexchange.com/users/134023", "pm_score": 1, "selected": false, "text": "<p>On WordPress 4.9 using the relative path (get_template_directory) returned $file as the complete path, which is unusable on a shared server. I found I had to use the substr function to return just the file name, and then build the URI from that.</p>\n\n<pre><code>foreach( glob( get_template_directory(). '/path/*.js' ) as $file ) {\n $filename = substr($file, strrpos($file, '/') + 1);\n wp_enqueue_script( $filename, get_template_directory_uri().'/path/'.$filename);\n}\n</code></pre>\n" } ]
2017/08/14
[ "https://wordpress.stackexchange.com/questions/276890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80568/" ]
I have a whole entire `js` folder of scripts and it would be tedious to have to load them all with `wp_enqueue_script()` one by one. Is there a way I can just insert the directory they are all in and it do it for me?
There's nothing wrong with enqueuing many files by using `wp_enqueue_script`. If you are referring to it as frustrating, then there is a simple solution for this. PHP offers a function that can list files and directories. By using [`glob`](http://php.net/manual/en/function.glob.php) you can list every `.js` file in your directory, and then enqueue them by a loop. ``` function enqueue_my_scripts(){ foreach( glob( get_template_directory(). '/path/*.js' ) as $file ) { // $file contains the name and extension of the file wp_enqueue_script( $file, get_template_directory_uri().'/path/'.$file); } } add_action('wp_enqueue_scripts', 'enqueue_my_scripts'); ``` A side not is that `glob` uses relative path, but `wp_enqueue_script` uses URLs. That is why I used different functions to get the folder's path and URI.
276,910
<p>I have 2 area of post to show in each page.</p> <p>first is on the widget (it's on the top of each page).</p> <p>second is on the posts area (it show below the widget).</p> <p>It's separated queries. article on the widget is another query and article on the posts area is main query.</p> <p>So,I don't want it to have same article in both area (not duplicate) and articles on the widget are random to show.</p> <p>I would like to use the article id which i got from the widget to modify the main query.</p> <p>For example: i have article id number 1 , 4 and 10 and i would like to use it to modify the main query to make it not load that article id to show.</p> <p>I got <code>$array_widgetId</code> from another file which has a loop to show the article in the widget(another query) and i set it to global variable and define it in this file which is used for show the article in the posts area(main query here) and also modify the main query to exclude that article id from loading.</p> <pre><code>while(have_posts()){ the_post(); //article to show in the posts area. } </code></pre> <p>How can i reach my point to make it doesn't have duplicate article in both area without using <code>pre_get_posts</code>?</p> <p>because i have tried to pass the array of widget id to use in <code>function.php</code> but it's not possible.</p> <p>More information: I have many file to make this thing work(may be that's why it make me so confused to maintain).</p> <p>I have one file to loop article to generate column.</p> <p>"_posts.php" in warp framework layout</p> <pre><code> $column_order = $this['config']-&gt;get('multicolumns_order', 1); $colcount = is_front_page() ? $this['config']-&gt;get('multicolumns', 1) : 1; $widget_id (this array contains id of article which show on the widget kit) while (have_posts()) { the_post(); if (isset($widget_id) &amp;&amp; !in_array($post-&gt;ID, $widget_id)) { if ($column_order == 0) { // order down if ($row &gt;= $rows) { $column++; $row = 0; $rows = ceil(($count - $i) / ($colcount - $column)); } $row++; } else { // order across $column = $i % $colcount; } if (!isset($columns[$column])) { $columns[$column] = ''; } $columns[$column] .= $this-&gt;render('_post', array('is_column_item' =&gt; ($colcount &gt; 1))); $i++; if ($i == $default_posts_per_page) { break 1; // break out 'while' loop level } } } // render columns if ($count = count($columns)) { echo '&lt;div class="uk-grid" data-uk-grid-match data-uk-grid-margin&gt;'; for ($i = 0; $i &lt; $count; $i++) { echo '&lt;div class="uk-width-medium-1-' . $count . '"&gt;' . $columns[$i] . '&lt;/div&gt;'; } echo '&lt;/div&gt;'; }else{ // generate standard column } </code></pre> <p>Above code will generate column following setting in backend. After this, it will call "_post.php" and that "_post.php" will contain the HTML tag of my custom layout.</p>
[ { "answer_id": 276962, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": true, "text": "<p>Rather than trying to set a global variable, just use the main query for both the widget and the other content. Simply adjust your Loop.</p>\n\n<p>If you share more of your code perhaps we can help specify where this would go, but the general idea is to move the start of the Loop above wherever you need to display the widget. Use a counter to keep track of whether you're looping through the first item (if so, show it in a widget) or not (show it in the main content area).</p>\n\n<pre><code>&lt;?php get_header();\n//\n// your code - perhaps an outer container div, etc.\n//\n$counter=0; // set a counter\nif(have_posts()): // start of normal Loop\nwhile(have_posts()): the_post();\n$counter++; // increment counter at each iteration\nif($counter==1) { // only for first Post\n ?&gt;&lt;div class=\"sidebar\"&gt;\n &lt;div class=\"widget\"&gt;\n &lt;?php the_title(); // add link, etc. as desired ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;&lt;?php\n} else { // now show the rest of the Posts outside of the widget\n ?&gt;\n &lt;div class=\"maincontent\"&gt;\n &lt;?php the_title(); the_content(); // format as desired ?&gt;\n &lt;/div&gt;\n &lt;?php\n}\nendwhile;\nendif; // end Loop\n//\n// your code - perhaps an outer container div, etc.\n//\nget_footer(); ?&gt;\n</code></pre>\n" }, { "answer_id": 276989, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 0, "selected": false, "text": "<p>In your loop, you can just exclude those posts by checking if the post ID is in the array of widget post IDs:</p>\n\n<pre><code>while(have_posts()){\n if(!in_array($post-&gt;ID, $array_widgetId)) {\n the_post();\n }\n}\n</code></pre>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125859/" ]
I have 2 area of post to show in each page. first is on the widget (it's on the top of each page). second is on the posts area (it show below the widget). It's separated queries. article on the widget is another query and article on the posts area is main query. So,I don't want it to have same article in both area (not duplicate) and articles on the widget are random to show. I would like to use the article id which i got from the widget to modify the main query. For example: i have article id number 1 , 4 and 10 and i would like to use it to modify the main query to make it not load that article id to show. I got `$array_widgetId` from another file which has a loop to show the article in the widget(another query) and i set it to global variable and define it in this file which is used for show the article in the posts area(main query here) and also modify the main query to exclude that article id from loading. ``` while(have_posts()){ the_post(); //article to show in the posts area. } ``` How can i reach my point to make it doesn't have duplicate article in both area without using `pre_get_posts`? because i have tried to pass the array of widget id to use in `function.php` but it's not possible. More information: I have many file to make this thing work(may be that's why it make me so confused to maintain). I have one file to loop article to generate column. "\_posts.php" in warp framework layout ``` $column_order = $this['config']->get('multicolumns_order', 1); $colcount = is_front_page() ? $this['config']->get('multicolumns', 1) : 1; $widget_id (this array contains id of article which show on the widget kit) while (have_posts()) { the_post(); if (isset($widget_id) && !in_array($post->ID, $widget_id)) { if ($column_order == 0) { // order down if ($row >= $rows) { $column++; $row = 0; $rows = ceil(($count - $i) / ($colcount - $column)); } $row++; } else { // order across $column = $i % $colcount; } if (!isset($columns[$column])) { $columns[$column] = ''; } $columns[$column] .= $this->render('_post', array('is_column_item' => ($colcount > 1))); $i++; if ($i == $default_posts_per_page) { break 1; // break out 'while' loop level } } } // render columns if ($count = count($columns)) { echo '<div class="uk-grid" data-uk-grid-match data-uk-grid-margin>'; for ($i = 0; $i < $count; $i++) { echo '<div class="uk-width-medium-1-' . $count . '">' . $columns[$i] . '</div>'; } echo '</div>'; }else{ // generate standard column } ``` Above code will generate column following setting in backend. After this, it will call "\_post.php" and that "\_post.php" will contain the HTML tag of my custom layout.
Rather than trying to set a global variable, just use the main query for both the widget and the other content. Simply adjust your Loop. If you share more of your code perhaps we can help specify where this would go, but the general idea is to move the start of the Loop above wherever you need to display the widget. Use a counter to keep track of whether you're looping through the first item (if so, show it in a widget) or not (show it in the main content area). ``` <?php get_header(); // // your code - perhaps an outer container div, etc. // $counter=0; // set a counter if(have_posts()): // start of normal Loop while(have_posts()): the_post(); $counter++; // increment counter at each iteration if($counter==1) { // only for first Post ?><div class="sidebar"> <div class="widget"> <?php the_title(); // add link, etc. as desired ?> </div> </div><?php } else { // now show the rest of the Posts outside of the widget ?> <div class="maincontent"> <?php the_title(); the_content(); // format as desired ?> </div> <?php } endwhile; endif; // end Loop // // your code - perhaps an outer container div, etc. // get_footer(); ?> ```
276,950
<p>I want to track how many views a post has had for every day. So that I can get all kind of interesting trends out of it later. For example most visit last three days.</p> <p>But what is the best way to store this data? Most tutorials on google search is about just storing the total views. Not per day. If I would store the day views in the same way I would probably just make a meta save like this:</p> <pre><code>update_post_meta($post_id, "views_$year-$month-$day", $views + 1); </code></pre> <p>But I'm not sure that is the best way when I easy want to get different kind of stat results from the database? Feels like it gonna be a lot of unnecessary large database requests. And that WP post meta datas are made for other kind of data storing.</p>
[ { "answer_id": 276952, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>When you want to store the data for a specific period of time, you can use the <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">Transients API</a>. But, this API is good for small amount of data, such as theme options or similar data.</p>\n\n<p>What you can do is, to store the post views normally, and then run a cron job each day and clear the views. Let's take a look at a simple example.</p>\n\n<pre><code>// You update the view counts by using post meta\nupdate_post_meta( $post_id, \"view_count\", $views + 1 );\n// Now, let's run a task each day at 00:00 and clear these counts.\n// If the cron is not scheduled, schedule it for 00:00 \nif ( ! wp_next_scheduled( 'clear-post-counts' ) ) {\n wp_schedule_event( strtotime( '00:00:00' ), 'daily', 'clear-post-counts' );\n}\n// Every time this action hook is triggered, the \n// callback function is run to clear the meta data\nadd_action('clear-post-counts', 'clear_post_counts');\nfunction clear_post_counts(){\n // Get a list of all posts\n $posts = get_posts();\n // For each post, set the post views to 0\n foreach( $posts as $post ) {\n update_post_meta( $post-&gt;ID, \"view_count\", 0);\n }\n}\n</code></pre>\n\n<p>The code is just an example of where to get started. You can customize it to fit your specific needs.</p>\n" }, { "answer_id": 276953, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Put simply, <strong>you don't</strong>, and you shouldn't</p>\n\n<h2>The Problems</h2>\n\n<h3>Race Conditions Make the Data Super Unreliable</h3>\n\n<p>Updating post meta, options, terms, etc is not an atomic operation. You need to fetch the view count, add 1 to it, then send it back to the database.</p>\n\n<p>During that process, another page load is occuring which does the same thing, leading to the following situation:</p>\n\n<ul>\n<li>user 1: get_post_meta 5!</li>\n<li>user 2: get_post_meta 5!</li>\n<li>user 1: adds 1, 6!</li>\n<li>user 2: adds 1, 6!</li>\n<li>user 1: saves update_post_meta, 6 views!</li>\n<li>user 2: saves update_post_meta, 6 views!</li>\n</ul>\n\n<p>Now your counter says 6, when it should say 7.</p>\n\n<h3>Huge Performance Costs</h3>\n\n<p>Database writes are a lot more expensive than reads, and this system involves a database write on every page load. This will not scale, and will have significant performance and speed problems.</p>\n\n<h2>So How Do I Track Page Views?</h2>\n\n<p>External services and software. These kinds of systems need to be built in a particular way so that they give reliable information without being super slow. It isn't an easy task.</p>\n\n<p>So instead, use a 3rd party service, and pull that information in at regular intervals. You could make a fresh request every time you view a page to get 100% accurate data, but that would be even slower, you wouldn't be able to cache the pages, and load times could be higher than 10 seconds, which is awful for SEO and UX.</p>\n\n<p>On my own site, I pull Google Analytics data in every hour for the top 10 viewed posts, the 10 most recent, and 10 posts that have not been checked recently ( I save a timestamp for when they were last checked, and use the 10 oldest timestamps )</p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3216/" ]
I want to track how many views a post has had for every day. So that I can get all kind of interesting trends out of it later. For example most visit last three days. But what is the best way to store this data? Most tutorials on google search is about just storing the total views. Not per day. If I would store the day views in the same way I would probably just make a meta save like this: ``` update_post_meta($post_id, "views_$year-$month-$day", $views + 1); ``` But I'm not sure that is the best way when I easy want to get different kind of stat results from the database? Feels like it gonna be a lot of unnecessary large database requests. And that WP post meta datas are made for other kind of data storing.
Put simply, **you don't**, and you shouldn't The Problems ------------ ### Race Conditions Make the Data Super Unreliable Updating post meta, options, terms, etc is not an atomic operation. You need to fetch the view count, add 1 to it, then send it back to the database. During that process, another page load is occuring which does the same thing, leading to the following situation: * user 1: get\_post\_meta 5! * user 2: get\_post\_meta 5! * user 1: adds 1, 6! * user 2: adds 1, 6! * user 1: saves update\_post\_meta, 6 views! * user 2: saves update\_post\_meta, 6 views! Now your counter says 6, when it should say 7. ### Huge Performance Costs Database writes are a lot more expensive than reads, and this system involves a database write on every page load. This will not scale, and will have significant performance and speed problems. So How Do I Track Page Views? ----------------------------- External services and software. These kinds of systems need to be built in a particular way so that they give reliable information without being super slow. It isn't an easy task. So instead, use a 3rd party service, and pull that information in at regular intervals. You could make a fresh request every time you view a page to get 100% accurate data, but that would be even slower, you wouldn't be able to cache the pages, and load times could be higher than 10 seconds, which is awful for SEO and UX. On my own site, I pull Google Analytics data in every hour for the top 10 viewed posts, the 10 most recent, and 10 posts that have not been checked recently ( I save a timestamp for when they were last checked, and use the 10 oldest timestamps )
276,960
<p>I think I've been looking at too much code and have confused myself while trying to get a better understanding of forms in WordPress with AJAX. I set out this week to learn how to create a form for a page and submit it through AJAX. </p> <p>The page is a template and the action I've looked into two solutions of the handling. One through a redirect to a PHP, such as:</p> <pre><code>&lt;form action="&lt;?php echo get_template_directory_uri() . "/validation.php"; ?&gt;" id="contactForm"&gt; &lt;/form&gt; </code></pre> <p>after reading several posts on the topic that a separate validation of the form should be made. Is this correct and why? Then the other issue is if I do want to process the form on the template-page the form action should look like:</p> <pre><code>&lt;form action="#" id="contactForm"&gt; &lt;/form&gt; </code></pre> <p>but outside of WordPress I've seen:</p> <pre><code>&lt;form action="" id="contactForm"&gt; &lt;/form&gt; </code></pre> <p>why is this? On the AJAX portion I've seen a difference of:</p> <pre><code>jQuery.ajax({ type :"post", url: ajaxurl, } }); </code></pre> <p>then a different URL of:</p> <pre><code>jQuery.ajax({ type :"post", dataType:"json", url: MBAjax.admin_url, } }); </code></pre> <p>and lastly:</p> <pre><code>jQuery.ajax({ type :"post", dataType:"json", url: /wp-admin/admin-ajax.php?action=contactForm", } }); </code></pre> <p>So what is the proper way to write the action in WordPress if:</p> <ul> <li>If the form is processed on the same page?</li> <li>If a separate PHP file validates the form?</li> </ul> <p>Then what is the proper AJAX call in WordPress?</p> <p><strong>Reference points:</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/17366903/form-submission-using-ajax-and-handling-response-in-wordpress-website">Form submission using AJAX and handling response in Wordpress Website</a></li> <li><a href="https://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax">Submitting HTML form using Jquery AJAX</a></li> <li><a href="https://wordpress.stackexchange.com/questions/140155/handling-an-ajax-form-submit">Handling an Ajax form submit</a></li> <li><a href="https://wordpress.stackexchange.com/questions/185148/custom-form-with-ajax">Custom Form with Ajax</a></li> <li><a href="https://stackoverflow.com/questions/18777728/submitting-a-form-with-ajax-in-wordpress">Submitting a form with ajax in Wordpress</a></li> <li><a href="https://teamtreehouse.com/community/submitting-a-form-in-wordpress-using-ajax" rel="nofollow noreferrer">submitting a form in wordpress using ajax</a></li> <li><a href="https://premium.wpmudev.org/forums/topic/ajax-form-post-submission-using-wordpress" rel="nofollow noreferrer">Ajax Form Post Submission Using Wordpress</a></li> <li><a href="https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/" rel="nofollow noreferrer">How To Build Your Own WordPress Contact Form and Why</a></li> </ul> <hr> <h2>Edit:</h2> <p>After further reading decided to step into RESTful submissions. I referenced "<a href="https://speakerdeck.com/tarendai/rest-apis-for-absolute-beginners" rel="nofollow noreferrer">REST APIs for Absolute Beginners</a>" but I'm not getting the return I'm hoping for:</p> <p><strong>HTML:</strong></p> <pre><code>&lt;form id="contactForm" action="" method="POST"&gt; &lt;div class="form-group"&gt; &lt;label for="form_email"&gt;&lt;span class="asterisk"&gt;*&lt;/span&gt;Email address:&lt;/label&gt; &lt;input type="email" class="form-control" id="form_email"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;button id="form_submit" class="supportbutton" type="submit"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;div id="testForm"&gt;&lt;/div&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$(document).ready(function() { $('#contactForm').submit(function(e) { e.preventDefault(); jQuery.ajax({ url: '&lt;?php echo home_url(); ?&gt;/wp-json/darthvader/v1/contact', type: 'post', dataType: 'json', data: $('#contactForm').serialize(), success: function(data) { $("#testForm").html(data); }, error: function() { alert("There was an issue"); }, }); }); }); </code></pre> <p><strong>functions.php:</strong></p> <pre><code>add_action('rest_api_init', function() { register_rest_route('darthvader/v1', '/contact/', array( 'methods' =&gt; 'POST', 'callback' =&gt; 'darth_contact_form' )); }); function darth_contact_form(\WP_REST_Request $request) { $email = $request['form_email']; return "Your contact request had the title " . $email; } </code></pre> <p>Why do I only get <code>Your contact request had the title</code> on the return and not the email too?</p>
[ { "answer_id": 276967, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<pre><code>&lt;form action=\"&lt;?php echo get_template_directory_uri() . \"/validation.php\"; ?&gt;\" id=\"contactForm\"&gt;\n</code></pre>\n\n<p></p>\n\n<p>So I'll outline the basic fundamentals, so you have a framework to move forwards with</p>\n\n<h2>Fixing Admin AJAX</h2>\n\n<p>So I'll cover this very briefly as it's not the crux of my answer, but would be useful:</p>\n\n<ul>\n<li>Add a hidden input field named <code>action</code> rather than adding it to the URL</li>\n<li><code>validation.php</code> and any other standalone files should burn with the fire of a thousand suns, do this validation in JS, and again in the form handler. Handling the form and validating it are the same step, else someone could skip validation and go straight to handling</li>\n</ul>\n\n<p>Finally, use a standard form handler for when JS isn't used/possible, check for the existence of something in the form that would only happen if it's been submitted, and submit the form to the same page, by having an empty action attribute e.g.:</p>\n\n<pre><code>if ( !empty( $_POST['form_page'] ) ) {\n $valid = false;\n\n // do validation\n // \n if ( true === $valid ) {\n // yay do whatever submitting the form is meant to do\n // if it's a multipage form, handle that here\n } else {\n get_template_part( 'form' ); // show the form again, but with warnings for validation\n }\n} else {\n get_template_part( 'form' );\n}\n</code></pre>\n\n<h2>RESTful Form Submissions</h2>\n\n<p>Change your form submission jQuery to use a REST endpoint, lets call this <code>darthvader/v1/contact</code>, I used some code from a <a href=\"https://stackoverflow.com/a/1200312/57482\">stackoverflow answer here</a>:</p>\n\n<pre><code>jQuery('input#submitButton').click( function() {\n jQuery.ajax({\n url: '/wp-json/darthvader/v1/contact',\n type: 'post',\n dataType: 'json',\n data: jQuery('form#contactForm').serialize(),\n success: function(data) {\n //... do something with the data...\n }\n });\n});\n</code></pre>\n\n<p>That's pretty much every form submission via REST API you'll ever need, but you still need that endpoint to exist, '/wp-json/darthvader/v1/form' needs creating, so lets tell WP we want an endpoint, that accepts POST's:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'darthvader/v1', '/contact/', array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'darth_contact_form'\n ) );\n} );\n</code></pre>\n\n<p>Then define what will happen when it's called:</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ) {\n //\n}\n</code></pre>\n\n<p>That's where we'll handle our form, e.g.:</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ) {\n $title = $request['title'];\n $message = $request['message'];\n // send an email or create a post, or whatever\n // the contact form does when its submitted\n return \"Your contact request had the title \".$title;\n}\n</code></pre>\n\n<p>The return value gets turned into JSON and sent back to the browser, so that you can handle it in the success function in javascript that you saw earlier in this answer. You can also return other responses, e.g.:</p>\n\n<pre><code>return \\WP_REST_Response( \"Bad request, X Y and Z are empty\", 400);\n</code></pre>\n\n<p>and you can return a <code>WP_Error</code> object to indicate something going wrong or incorrect:</p>\n\n<pre><code>return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' =&gt; 404 ) );\n</code></pre>\n\n<p>You can do your validation inside the endpoint, but you can also make the endpoint do the validation for you by specifying what fields to expect, and a function to validate them, but I leave that as an exercise ( or new question ) for you</p>\n" }, { "answer_id": 277001, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Every AJAX process has 4 fundamental steps:</p>\n\n<ol>\n<li>Send a request to the server asynchronously</li>\n<li>Process the server side tasks</li>\n<li>Retrieve the response from the server</li>\n<li>Make changes to the client side based on the server's response</li>\n</ol>\n\n<h2>Creating a Request to Server</h2>\n\n<p>There are many ways and methods to do this. This can be done both by jQuery and JavaScript. However, since jQuery made it easier, I'm going to use that. jQuery offers 3 different functions with similar functionality. These functions are:</p>\n\n<ul>\n<li><code>$.ajax();</code> - Supports both POST and GET methods</li>\n<li><code>$.get();</code> - Simple GET method</li>\n<li><code>$.post();</code> - Simple POST method</li>\n</ul>\n\n<p>Since I'm not sure which method you are going to use, I will proceed with <code>$.ajax();</code>. I will be posting a sample code to the server, and then show a message based on server's response. Let's declare a jQuery function that handles our submission. </p>\n\n<p>This function will send a username to the server.</p>\n\n<pre><code>function sendMyForm( string ) {\n // Begin an Ajax request\n $.ajax({\n type: 'POST', // Submission method\n url: url_object.url_string + '/wp-json/darthvader/ajax_submission', // I will explain this later\n data: { username : string }, // Data to be sent to server\n dataType: 'json', // You should set this to JSON if you are going to use the REST api\n beforeSend: function(){ // Let's show a message while the request is being processed\n $('#status').html('&lt;span&gt;Processing&lt;/span&gt;');\n },\n success: function ( response ) {\n // The Ajax request is successful. This doesn't mean the\n // sever was able to do the task, it just means that the\n // server did send a response. So, let's check the response\n if( response.success == true ) {\n $('#status').html('&lt;span&gt;Success&lt;/span&gt;');\n $('#message').html('&lt;span&gt;' + response.message + '&lt;/span&gt;');\n } else {\n $('#status').html('&lt;span&gt;Failed&lt;/span&gt;');\n $('#message').html('&lt;span&gt;' + response.message + '&lt;/span&gt;');\n }\n },\n error: function(){ // The request wasn't successful for some reason\n $('#status').html('&lt;span&gt;Unknown error.&lt;/span&gt;');\n }\n });\n};\n</code></pre>\n\n<p>Okay, now we need to bind an action to our button. There are many ways to do this too. For example, prevent form submission, serialization of data, and more. I'm not even going to create a form. </p>\n\n<p>I'm going to create a custom HTML div to demonstrate we don't even need a form. Here is our HTML that looks like a form:</p>\n\n<pre><code>&lt;div&gt;\n &lt;p id=\"status\"&gt;&lt;/p&gt;\n &lt;p id=\"message\"&gt;&lt;/p&gt;\n &lt;input id=\"my-input\" type=\"text\"/&gt;\n &lt;span id=\"button\"&gt;This is our button!&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Now let's bind a clink action to our button, which is actually not a button! Tricked you.</p>\n\n<pre><code>$('#button').on('click',function(){\n // Get the value of our input box\n var username = $('#my-input').val();\n // Call our Ajax function and pass the username to it\n sendMyForm( string );\n});\n</code></pre>\n\n<p>Alright, now the form will be submit on user's click.</p>\n\n<h2>Creating a Route to Process the Request</h2>\n\n<p>Since I've declared the data type as JSON, I'm going to use the REST API that outputs our content as JSON by default. </p>\n\n<p>You can use anything you wish such as admin Ajax, as long as it's a good practice, and doesn't impact performance or cause a security issue. </p>\n\n<p>Let's register a REST route for now.</p>\n\n<pre><code>add_action( 'rest_api_init','my_rest_route' ); \nfunction my_rest_route() {\n register_rest_route( \n 'darthvader', // Base path here\n '/ajax_submission/', // Child path\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'darth_contact_form'\n ) \n );\n}\n</code></pre>\n\n<p>Now it's time for the real fun. Let's handle the received data, shall we?</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ){\n // Get the data that was sent to server\n $data = $request['username'];\n // Check if it's empty and send the response\n if( !empty( $data ) ){\n // Remember these from our Ajax call? This is where we set them\n $response['status'] = true;\n $response['message'] = 'You have entered a username!';\n } else{\n $response['status'] = false;\n $response['message'] = 'Why didn\\'t you enter a username?';\n }\n // Don't forget to return the data\n return $response;\n}\n</code></pre>\n\n<h2>A Final Touch</h2>\n\n<p>Remember this line?</p>\n\n<pre><code>url: url_object.url_string\n</code></pre>\n\n<p>This is the path to our REST route. Since the domain may change, it's wise to form this dynamically, by using <code>wp_localize_script</code>. To do this, we save all our scripts into a file named <code>script.js</code> and then enqueue &amp; localize it.</p>\n\n<pre><code>wp_enqueue_script( 'my-script', get_template_directory_uri().'/js/script.js', array( 'jquery' ), '', true );\n\n$localized = array(\n 'url_string' =&gt; site_url(), // This is where that url_string came from\n);\nwp_localize_script( 'my-script', 'url_object', $localized );\n</code></pre>\n\n<p>Now we can access the <code>site_url();</code> by using <code>url_object.url_string</code> in our script!</p>\n\n<p>That's it for now. Click the button and have fun.</p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
I think I've been looking at too much code and have confused myself while trying to get a better understanding of forms in WordPress with AJAX. I set out this week to learn how to create a form for a page and submit it through AJAX. The page is a template and the action I've looked into two solutions of the handling. One through a redirect to a PHP, such as: ``` <form action="<?php echo get_template_directory_uri() . "/validation.php"; ?>" id="contactForm"> </form> ``` after reading several posts on the topic that a separate validation of the form should be made. Is this correct and why? Then the other issue is if I do want to process the form on the template-page the form action should look like: ``` <form action="#" id="contactForm"> </form> ``` but outside of WordPress I've seen: ``` <form action="" id="contactForm"> </form> ``` why is this? On the AJAX portion I've seen a difference of: ``` jQuery.ajax({ type :"post", url: ajaxurl, } }); ``` then a different URL of: ``` jQuery.ajax({ type :"post", dataType:"json", url: MBAjax.admin_url, } }); ``` and lastly: ``` jQuery.ajax({ type :"post", dataType:"json", url: /wp-admin/admin-ajax.php?action=contactForm", } }); ``` So what is the proper way to write the action in WordPress if: * If the form is processed on the same page? * If a separate PHP file validates the form? Then what is the proper AJAX call in WordPress? **Reference points:** * [Form submission using AJAX and handling response in Wordpress Website](https://stackoverflow.com/questions/17366903/form-submission-using-ajax-and-handling-response-in-wordpress-website) * [Submitting HTML form using Jquery AJAX](https://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax) * [Handling an Ajax form submit](https://wordpress.stackexchange.com/questions/140155/handling-an-ajax-form-submit) * [Custom Form with Ajax](https://wordpress.stackexchange.com/questions/185148/custom-form-with-ajax) * [Submitting a form with ajax in Wordpress](https://stackoverflow.com/questions/18777728/submitting-a-form-with-ajax-in-wordpress) * [submitting a form in wordpress using ajax](https://teamtreehouse.com/community/submitting-a-form-in-wordpress-using-ajax) * [Ajax Form Post Submission Using Wordpress](https://premium.wpmudev.org/forums/topic/ajax-form-post-submission-using-wordpress) * [How To Build Your Own WordPress Contact Form and Why](https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/) --- Edit: ----- After further reading decided to step into RESTful submissions. I referenced "[REST APIs for Absolute Beginners](https://speakerdeck.com/tarendai/rest-apis-for-absolute-beginners)" but I'm not getting the return I'm hoping for: **HTML:** ``` <form id="contactForm" action="" method="POST"> <div class="form-group"> <label for="form_email"><span class="asterisk">*</span>Email address:</label> <input type="email" class="form-control" id="form_email"> </div> <div class="form-group"> <button id="form_submit" class="supportbutton" type="submit">Submit</button> </div> </form> <div id="testForm"></div> ``` **jQuery:** ``` $(document).ready(function() { $('#contactForm').submit(function(e) { e.preventDefault(); jQuery.ajax({ url: '<?php echo home_url(); ?>/wp-json/darthvader/v1/contact', type: 'post', dataType: 'json', data: $('#contactForm').serialize(), success: function(data) { $("#testForm").html(data); }, error: function() { alert("There was an issue"); }, }); }); }); ``` **functions.php:** ``` add_action('rest_api_init', function() { register_rest_route('darthvader/v1', '/contact/', array( 'methods' => 'POST', 'callback' => 'darth_contact_form' )); }); function darth_contact_form(\WP_REST_Request $request) { $email = $request['form_email']; return "Your contact request had the title " . $email; } ``` Why do I only get `Your contact request had the title` on the return and not the email too?
``` <form action="<?php echo get_template_directory_uri() . "/validation.php"; ?>" id="contactForm"> ``` So I'll outline the basic fundamentals, so you have a framework to move forwards with Fixing Admin AJAX ----------------- So I'll cover this very briefly as it's not the crux of my answer, but would be useful: * Add a hidden input field named `action` rather than adding it to the URL * `validation.php` and any other standalone files should burn with the fire of a thousand suns, do this validation in JS, and again in the form handler. Handling the form and validating it are the same step, else someone could skip validation and go straight to handling Finally, use a standard form handler for when JS isn't used/possible, check for the existence of something in the form that would only happen if it's been submitted, and submit the form to the same page, by having an empty action attribute e.g.: ``` if ( !empty( $_POST['form_page'] ) ) { $valid = false; // do validation // if ( true === $valid ) { // yay do whatever submitting the form is meant to do // if it's a multipage form, handle that here } else { get_template_part( 'form' ); // show the form again, but with warnings for validation } } else { get_template_part( 'form' ); } ``` RESTful Form Submissions ------------------------ Change your form submission jQuery to use a REST endpoint, lets call this `darthvader/v1/contact`, I used some code from a [stackoverflow answer here](https://stackoverflow.com/a/1200312/57482): ``` jQuery('input#submitButton').click( function() { jQuery.ajax({ url: '/wp-json/darthvader/v1/contact', type: 'post', dataType: 'json', data: jQuery('form#contactForm').serialize(), success: function(data) { //... do something with the data... } }); }); ``` That's pretty much every form submission via REST API you'll ever need, but you still need that endpoint to exist, '/wp-json/darthvader/v1/form' needs creating, so lets tell WP we want an endpoint, that accepts POST's: ``` add_action( 'rest_api_init', function () { register_rest_route( 'darthvader/v1', '/contact/', array( 'methods' => 'POST', 'callback' => 'darth_contact_form' ) ); } ); ``` Then define what will happen when it's called: ``` function darth_contact_form( \WP_REST_Request $request ) { // } ``` That's where we'll handle our form, e.g.: ``` function darth_contact_form( \WP_REST_Request $request ) { $title = $request['title']; $message = $request['message']; // send an email or create a post, or whatever // the contact form does when its submitted return "Your contact request had the title ".$title; } ``` The return value gets turned into JSON and sent back to the browser, so that you can handle it in the success function in javascript that you saw earlier in this answer. You can also return other responses, e.g.: ``` return \WP_REST_Response( "Bad request, X Y and Z are empty", 400); ``` and you can return a `WP_Error` object to indicate something going wrong or incorrect: ``` return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) ); ``` You can do your validation inside the endpoint, but you can also make the endpoint do the validation for you by specifying what fields to expect, and a function to validate them, but I leave that as an exercise ( or new question ) for you
276,966
<p>I am trying to add custom add to cart link. I am getting product details from product slug. And trying to add, ADD to cart link by product id but no luck so far. Any help will be highly appreciated. </p> <pre><code>if(!empty($tracks[ $k ][ 'buy_link_a' ])){ list($hash, $slug) = explode("product/",$tracks[ $k ][ 'buy_link_a' ]); $product_obj = get_page_by_path( $slug, OBJECT, 'product' ); // this code help me to get product detials by slug $id=$product_obj-&gt;ID; // and here I am getting product id do_action( 'woocommerce_' . $product-&gt;product_type . '_add_to_cart' ); } </code></pre>
[ { "answer_id": 276967, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<pre><code>&lt;form action=\"&lt;?php echo get_template_directory_uri() . \"/validation.php\"; ?&gt;\" id=\"contactForm\"&gt;\n</code></pre>\n\n<p></p>\n\n<p>So I'll outline the basic fundamentals, so you have a framework to move forwards with</p>\n\n<h2>Fixing Admin AJAX</h2>\n\n<p>So I'll cover this very briefly as it's not the crux of my answer, but would be useful:</p>\n\n<ul>\n<li>Add a hidden input field named <code>action</code> rather than adding it to the URL</li>\n<li><code>validation.php</code> and any other standalone files should burn with the fire of a thousand suns, do this validation in JS, and again in the form handler. Handling the form and validating it are the same step, else someone could skip validation and go straight to handling</li>\n</ul>\n\n<p>Finally, use a standard form handler for when JS isn't used/possible, check for the existence of something in the form that would only happen if it's been submitted, and submit the form to the same page, by having an empty action attribute e.g.:</p>\n\n<pre><code>if ( !empty( $_POST['form_page'] ) ) {\n $valid = false;\n\n // do validation\n // \n if ( true === $valid ) {\n // yay do whatever submitting the form is meant to do\n // if it's a multipage form, handle that here\n } else {\n get_template_part( 'form' ); // show the form again, but with warnings for validation\n }\n} else {\n get_template_part( 'form' );\n}\n</code></pre>\n\n<h2>RESTful Form Submissions</h2>\n\n<p>Change your form submission jQuery to use a REST endpoint, lets call this <code>darthvader/v1/contact</code>, I used some code from a <a href=\"https://stackoverflow.com/a/1200312/57482\">stackoverflow answer here</a>:</p>\n\n<pre><code>jQuery('input#submitButton').click( function() {\n jQuery.ajax({\n url: '/wp-json/darthvader/v1/contact',\n type: 'post',\n dataType: 'json',\n data: jQuery('form#contactForm').serialize(),\n success: function(data) {\n //... do something with the data...\n }\n });\n});\n</code></pre>\n\n<p>That's pretty much every form submission via REST API you'll ever need, but you still need that endpoint to exist, '/wp-json/darthvader/v1/form' needs creating, so lets tell WP we want an endpoint, that accepts POST's:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'darthvader/v1', '/contact/', array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'darth_contact_form'\n ) );\n} );\n</code></pre>\n\n<p>Then define what will happen when it's called:</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ) {\n //\n}\n</code></pre>\n\n<p>That's where we'll handle our form, e.g.:</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ) {\n $title = $request['title'];\n $message = $request['message'];\n // send an email or create a post, or whatever\n // the contact form does when its submitted\n return \"Your contact request had the title \".$title;\n}\n</code></pre>\n\n<p>The return value gets turned into JSON and sent back to the browser, so that you can handle it in the success function in javascript that you saw earlier in this answer. You can also return other responses, e.g.:</p>\n\n<pre><code>return \\WP_REST_Response( \"Bad request, X Y and Z are empty\", 400);\n</code></pre>\n\n<p>and you can return a <code>WP_Error</code> object to indicate something going wrong or incorrect:</p>\n\n<pre><code>return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' =&gt; 404 ) );\n</code></pre>\n\n<p>You can do your validation inside the endpoint, but you can also make the endpoint do the validation for you by specifying what fields to expect, and a function to validate them, but I leave that as an exercise ( or new question ) for you</p>\n" }, { "answer_id": 277001, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Every AJAX process has 4 fundamental steps:</p>\n\n<ol>\n<li>Send a request to the server asynchronously</li>\n<li>Process the server side tasks</li>\n<li>Retrieve the response from the server</li>\n<li>Make changes to the client side based on the server's response</li>\n</ol>\n\n<h2>Creating a Request to Server</h2>\n\n<p>There are many ways and methods to do this. This can be done both by jQuery and JavaScript. However, since jQuery made it easier, I'm going to use that. jQuery offers 3 different functions with similar functionality. These functions are:</p>\n\n<ul>\n<li><code>$.ajax();</code> - Supports both POST and GET methods</li>\n<li><code>$.get();</code> - Simple GET method</li>\n<li><code>$.post();</code> - Simple POST method</li>\n</ul>\n\n<p>Since I'm not sure which method you are going to use, I will proceed with <code>$.ajax();</code>. I will be posting a sample code to the server, and then show a message based on server's response. Let's declare a jQuery function that handles our submission. </p>\n\n<p>This function will send a username to the server.</p>\n\n<pre><code>function sendMyForm( string ) {\n // Begin an Ajax request\n $.ajax({\n type: 'POST', // Submission method\n url: url_object.url_string + '/wp-json/darthvader/ajax_submission', // I will explain this later\n data: { username : string }, // Data to be sent to server\n dataType: 'json', // You should set this to JSON if you are going to use the REST api\n beforeSend: function(){ // Let's show a message while the request is being processed\n $('#status').html('&lt;span&gt;Processing&lt;/span&gt;');\n },\n success: function ( response ) {\n // The Ajax request is successful. This doesn't mean the\n // sever was able to do the task, it just means that the\n // server did send a response. So, let's check the response\n if( response.success == true ) {\n $('#status').html('&lt;span&gt;Success&lt;/span&gt;');\n $('#message').html('&lt;span&gt;' + response.message + '&lt;/span&gt;');\n } else {\n $('#status').html('&lt;span&gt;Failed&lt;/span&gt;');\n $('#message').html('&lt;span&gt;' + response.message + '&lt;/span&gt;');\n }\n },\n error: function(){ // The request wasn't successful for some reason\n $('#status').html('&lt;span&gt;Unknown error.&lt;/span&gt;');\n }\n });\n};\n</code></pre>\n\n<p>Okay, now we need to bind an action to our button. There are many ways to do this too. For example, prevent form submission, serialization of data, and more. I'm not even going to create a form. </p>\n\n<p>I'm going to create a custom HTML div to demonstrate we don't even need a form. Here is our HTML that looks like a form:</p>\n\n<pre><code>&lt;div&gt;\n &lt;p id=\"status\"&gt;&lt;/p&gt;\n &lt;p id=\"message\"&gt;&lt;/p&gt;\n &lt;input id=\"my-input\" type=\"text\"/&gt;\n &lt;span id=\"button\"&gt;This is our button!&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Now let's bind a clink action to our button, which is actually not a button! Tricked you.</p>\n\n<pre><code>$('#button').on('click',function(){\n // Get the value of our input box\n var username = $('#my-input').val();\n // Call our Ajax function and pass the username to it\n sendMyForm( string );\n});\n</code></pre>\n\n<p>Alright, now the form will be submit on user's click.</p>\n\n<h2>Creating a Route to Process the Request</h2>\n\n<p>Since I've declared the data type as JSON, I'm going to use the REST API that outputs our content as JSON by default. </p>\n\n<p>You can use anything you wish such as admin Ajax, as long as it's a good practice, and doesn't impact performance or cause a security issue. </p>\n\n<p>Let's register a REST route for now.</p>\n\n<pre><code>add_action( 'rest_api_init','my_rest_route' ); \nfunction my_rest_route() {\n register_rest_route( \n 'darthvader', // Base path here\n '/ajax_submission/', // Child path\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'darth_contact_form'\n ) \n );\n}\n</code></pre>\n\n<p>Now it's time for the real fun. Let's handle the received data, shall we?</p>\n\n<pre><code>function darth_contact_form( \\WP_REST_Request $request ){\n // Get the data that was sent to server\n $data = $request['username'];\n // Check if it's empty and send the response\n if( !empty( $data ) ){\n // Remember these from our Ajax call? This is where we set them\n $response['status'] = true;\n $response['message'] = 'You have entered a username!';\n } else{\n $response['status'] = false;\n $response['message'] = 'Why didn\\'t you enter a username?';\n }\n // Don't forget to return the data\n return $response;\n}\n</code></pre>\n\n<h2>A Final Touch</h2>\n\n<p>Remember this line?</p>\n\n<pre><code>url: url_object.url_string\n</code></pre>\n\n<p>This is the path to our REST route. Since the domain may change, it's wise to form this dynamically, by using <code>wp_localize_script</code>. To do this, we save all our scripts into a file named <code>script.js</code> and then enqueue &amp; localize it.</p>\n\n<pre><code>wp_enqueue_script( 'my-script', get_template_directory_uri().'/js/script.js', array( 'jquery' ), '', true );\n\n$localized = array(\n 'url_string' =&gt; site_url(), // This is where that url_string came from\n);\nwp_localize_script( 'my-script', 'url_object', $localized );\n</code></pre>\n\n<p>Now we can access the <code>site_url();</code> by using <code>url_object.url_string</code> in our script!</p>\n\n<p>That's it for now. Click the button and have fun.</p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125883/" ]
I am trying to add custom add to cart link. I am getting product details from product slug. And trying to add, ADD to cart link by product id but no luck so far. Any help will be highly appreciated. ``` if(!empty($tracks[ $k ][ 'buy_link_a' ])){ list($hash, $slug) = explode("product/",$tracks[ $k ][ 'buy_link_a' ]); $product_obj = get_page_by_path( $slug, OBJECT, 'product' ); // this code help me to get product detials by slug $id=$product_obj->ID; // and here I am getting product id do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' ); } ```
``` <form action="<?php echo get_template_directory_uri() . "/validation.php"; ?>" id="contactForm"> ``` So I'll outline the basic fundamentals, so you have a framework to move forwards with Fixing Admin AJAX ----------------- So I'll cover this very briefly as it's not the crux of my answer, but would be useful: * Add a hidden input field named `action` rather than adding it to the URL * `validation.php` and any other standalone files should burn with the fire of a thousand suns, do this validation in JS, and again in the form handler. Handling the form and validating it are the same step, else someone could skip validation and go straight to handling Finally, use a standard form handler for when JS isn't used/possible, check for the existence of something in the form that would only happen if it's been submitted, and submit the form to the same page, by having an empty action attribute e.g.: ``` if ( !empty( $_POST['form_page'] ) ) { $valid = false; // do validation // if ( true === $valid ) { // yay do whatever submitting the form is meant to do // if it's a multipage form, handle that here } else { get_template_part( 'form' ); // show the form again, but with warnings for validation } } else { get_template_part( 'form' ); } ``` RESTful Form Submissions ------------------------ Change your form submission jQuery to use a REST endpoint, lets call this `darthvader/v1/contact`, I used some code from a [stackoverflow answer here](https://stackoverflow.com/a/1200312/57482): ``` jQuery('input#submitButton').click( function() { jQuery.ajax({ url: '/wp-json/darthvader/v1/contact', type: 'post', dataType: 'json', data: jQuery('form#contactForm').serialize(), success: function(data) { //... do something with the data... } }); }); ``` That's pretty much every form submission via REST API you'll ever need, but you still need that endpoint to exist, '/wp-json/darthvader/v1/form' needs creating, so lets tell WP we want an endpoint, that accepts POST's: ``` add_action( 'rest_api_init', function () { register_rest_route( 'darthvader/v1', '/contact/', array( 'methods' => 'POST', 'callback' => 'darth_contact_form' ) ); } ); ``` Then define what will happen when it's called: ``` function darth_contact_form( \WP_REST_Request $request ) { // } ``` That's where we'll handle our form, e.g.: ``` function darth_contact_form( \WP_REST_Request $request ) { $title = $request['title']; $message = $request['message']; // send an email or create a post, or whatever // the contact form does when its submitted return "Your contact request had the title ".$title; } ``` The return value gets turned into JSON and sent back to the browser, so that you can handle it in the success function in javascript that you saw earlier in this answer. You can also return other responses, e.g.: ``` return \WP_REST_Response( "Bad request, X Y and Z are empty", 400); ``` and you can return a `WP_Error` object to indicate something going wrong or incorrect: ``` return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) ); ``` You can do your validation inside the endpoint, but you can also make the endpoint do the validation for you by specifying what fields to expect, and a function to validate them, but I leave that as an exercise ( or new question ) for you
276,972
<p>When I use <code>get_the_post_thumbnail( NULL, 'entry-fullwidth', NULL );</code> wordpress automatically outputs the <code>srcset</code> data like these:</p> <pre><code>&lt;img width="1000" height="625" src="https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg" class="attachment-entry-fullwidth size-entry-fullwidth wp-post-image" alt="" srcset=" https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg 1000w, https://x.cloudfront.net/wp-content/uploads/2017/08/photo-768x480.jpg 768w" sizes=" (max-width: 767px) 95vw, (max-width: 979px) 80vw, 1200px "&gt; </code></pre> <p>Is there a native wordpress function or another way to output srcset data for images in my custom function below?</p> <pre><code>function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' =&gt; 1, ), $atts)); $no = ( $no != '' ) ? $no : 1; $images = get_field('fl_gallery'); $image = $images[$no]; if ($image) { $credit = get_field('fl_credit', $image['id']); return '&lt;div class="kalim"&gt;&lt;img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" /&gt;&lt;div class="kalca"&gt;' . $image['caption'] . '&lt;/div&gt;' . (!empty($credit) ? '&lt;div class="kalcr"&gt;Credit:' . $credit . '&lt;/div&gt;&lt;/div&gt;': '' ) ; } } add_shortcode('photo', 'photo_shortcode'); </code></pre>
[ { "answer_id": 276975, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>I think <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_srcset/\" rel=\"noreferrer\"><code>wp_get_attachment_srcset()</code></a> is what you are looking for.</p>\n\n<pre><code>$srcset = wp_get_attachment_image_srcset( $image['id'], array( 100, 100 ) );\n</code></pre>\n\n<p>Now you can escape the HTML and use it in your code.</p>\n\n<pre><code>&lt;img src=\"PATH HERE\" srcset=\"&lt;?php echo esc_attr( $srcset ); ?&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 313391, "author": "Alfrex92", "author_id": 147245, "author_profile": "https://wordpress.stackexchange.com/users/147245", "pm_score": -1, "selected": false, "text": "<p>Take a look of this article \n<a href=\"https://alexwright.net/web-design-secrets/responsive-images-wordpress/\" rel=\"nofollow noreferrer\">https://alexwright.net/web-design-secrets/responsive-images-wordpress/</a></p>\n\n<p>It explains how srcset and responsive images work in Wordpress.</p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
When I use `get_the_post_thumbnail( NULL, 'entry-fullwidth', NULL );` wordpress automatically outputs the `srcset` data like these: ``` <img width="1000" height="625" src="https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg" class="attachment-entry-fullwidth size-entry-fullwidth wp-post-image" alt="" srcset=" https://x.cloudfront.net/wp-content/uploads/2017/08/photo.jpg 1000w, https://x.cloudfront.net/wp-content/uploads/2017/08/photo-768x480.jpg 768w" sizes=" (max-width: 767px) 95vw, (max-width: 979px) 80vw, 1200px "> ``` Is there a native wordpress function or another way to output srcset data for images in my custom function below? ``` function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' => 1, ), $atts)); $no = ( $no != '' ) ? $no : 1; $images = get_field('fl_gallery'); $image = $images[$no]; if ($image) { $credit = get_field('fl_credit', $image['id']); return '<div class="kalim"><img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" /><div class="kalca">' . $image['caption'] . '</div>' . (!empty($credit) ? '<div class="kalcr">Credit:' . $credit . '</div></div>': '' ) ; } } add_shortcode('photo', 'photo_shortcode'); ```
I think [`wp_get_attachment_srcset()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_srcset/) is what you are looking for. ``` $srcset = wp_get_attachment_image_srcset( $image['id'], array( 100, 100 ) ); ``` Now you can escape the HTML and use it in your code. ``` <img src="PATH HERE" srcset="<?php echo esc_attr( $srcset ); ?>"> ```
276,980
<p>I have a blog and I make posts daily, and I would like for users to be able to access posts one day before they are published. How can I do that?</p>
[ { "answer_id": 276981, "author": "Swati", "author_id": 123547, "author_profile": "https://wordpress.stackexchange.com/users/123547", "pm_score": 0, "selected": false, "text": "<p>You can just add a post in admin and give post link to user, Like suppose you want to publish post tomorrow then just create post and put publish date for tomorrow.\nSo post will publicly displayed tomorrow. but you can share that post link to anyone.</p>\n" }, { "answer_id": 277006, "author": "Colin Mitchell", "author_id": 125910, "author_profile": "https://wordpress.stackexchange.com/users/125910", "pm_score": 1, "selected": false, "text": "<p>Here are a few plugins that may be useful to you:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/wp-draftsforfriends/\" rel=\"nofollow noreferrer\">WP-DraftsForFriends</a></li>\n<li><a href=\"https://wordpress.org/plugins/public-post-preview/\" rel=\"nofollow noreferrer\">Public Post Preview</a></li>\n</ul>\n\n<p>I prefer <strong>WP-DraftsForFriends</strong> as it has an admin page to control expiration and renew for longer periods of time. It's also nice to see all of your public links in one area rather than Public Post Preview which is only controlled on the post edit screen.</p>\n" }, { "answer_id": 277020, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 2, "selected": true, "text": "<p>You can use this in a template file:</p>\n\n<pre><code>$tomr = getdate(time()+86400); //utc=gmt time in seconds, add 24 hours = 86400 seconds\n$args = array(\n 'post_status' =&gt; 'future',\n 'date_query' =&gt; array(\n array(\n 'year' =&gt; $tomr['year'],\n 'month' =&gt; $tomr['mon'],\n 'day' =&gt; $tomr['mday'],\n 'column' =&gt; 'post_date_gmt' //since we are using the gmt timestamp\n ),\n ),\n);\n$query = new WP_Query($args);\nif($query-&gt;have_posts()) {\n while($query-&gt;have_posts()) {\n $query-&gt;the_post();\n //display post data\n }\n //restore original post data if it's required after this loop\n wp_reset_postdata();\n} else {\n //no posts found\n}\n</code></pre>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276980", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
I have a blog and I make posts daily, and I would like for users to be able to access posts one day before they are published. How can I do that?
You can use this in a template file: ``` $tomr = getdate(time()+86400); //utc=gmt time in seconds, add 24 hours = 86400 seconds $args = array( 'post_status' => 'future', 'date_query' => array( array( 'year' => $tomr['year'], 'month' => $tomr['mon'], 'day' => $tomr['mday'], 'column' => 'post_date_gmt' //since we are using the gmt timestamp ), ), ); $query = new WP_Query($args); if($query->have_posts()) { while($query->have_posts()) { $query->the_post(); //display post data } //restore original post data if it's required after this loop wp_reset_postdata(); } else { //no posts found } ```
276,987
<p>I have a custom meta box in my page admin with 5 checkboxes. If one or more of the checkboxes are checked, I want certain content to display on the page. </p> <p>I have the meta box checkboxes displaying and saving properly in the admin, but what do I need to put in my template file to show content based on whether or not the checkboxes are checked from the admin?</p> <p>For example, if Web Development, Logo Design and Print Design are checked in the admin, then I want the page to show this:</p> <ul><li>Web Development</li><li>Logo Design</li><li>Print Design</li></ul> <p>I have the following in my functions.php file:</p> <pre><code>add_action( 'add_meta_boxes', 'add_custom_box' ); function add_custom_box( $post ) { add_meta_box( 'Meta Box', // ID, should be a string. 'Services', // Meta Box Title. 'services_meta_box', // Your call back function, this is where your form field will go. 'page', // The post type you want this to show up on, can be post, page, or custom post type. 'normal', // The placement of your meta box, can be normal or side. 'core' // The priority in which this will be displayed. ); } function services_meta_box($post) { wp_nonce_field( 'my_awesome_nonce', 'awesome_nonce' ); $checkboxMeta = get_post_meta( $post-&gt;ID ); ?&gt; &lt;input type="checkbox" name="ui-ux-design" id="ui-ux-design" value="yes" &lt;?php if ( isset ( $checkboxMeta['ui-ux-design'] ) ) checked( $checkboxMeta['ui-ux-design'][0], 'yes' ); ?&gt; /&gt;UI/UX Design&lt;br /&gt; &lt;input type="checkbox" name="web-development" id="web-development" value="yes" &lt;?php if ( isset ( $checkboxMeta['web-development'] ) ) checked( $checkboxMeta['web-development'][0], 'yes' ); ?&gt; /&gt;Web Development&lt;br /&gt; &lt;input type="checkbox" name="logo-design" id="logo-design" value="yes" &lt;?php if ( isset ( $checkboxMeta['logo-design'] ) ) checked( $checkboxMeta['logo-design'][0], 'yes' ); ?&gt; /&gt;Logo Design&lt;br /&gt; &lt;input type="checkbox" name="branding" id="branding" value="yes" &lt;?php if ( isset ( $checkboxMeta['branding'] ) ) checked( $checkboxMeta['branding'][0], 'yes' ); ?&gt; /&gt;Branding&lt;br /&gt; &lt;input type="checkbox" name="print-design" id="print-design" value="yes" &lt;?php if ( isset ( $checkboxMeta['print-design'] ) ) checked( $checkboxMeta['print-design'][0], 'yes' ); ?&gt; /&gt;Print Design&lt;br /&gt; &lt;?php } add_action( 'save_post', 'save_services_checkboxes' ); function save_services_checkboxes( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return; if ( ( isset ( $_POST['my_awesome_nonce'] ) ) &amp;&amp; ( ! wp_verify_nonce( $_POST['my_awesome_nonce'], plugin_basename( __FILE__ ) ) ) ) return; if ( ( isset ( $_POST['post_type'] ) ) &amp;&amp; ( 'page' == $_POST['post_type'] ) ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } //saves ui-ux-design's value if( isset( $_POST[ 'ui-ux-design' ] ) ) { update_post_meta( $post_id, 'ui-ux-design', 'yes' ); } else { update_post_meta( $post_id, 'ui-ux-design', 'no' ); } //saves web-development's value if( isset( $_POST[ 'web-development' ] ) ) { update_post_meta( $post_id, 'web-development', 'yes' ); } else { update_post_meta( $post_id, 'web-development', 'no' ); } //saves logo-design's value if( isset( $_POST[ 'logo-design' ] ) ) { update_post_meta( $post_id, 'logo-design', 'yes' ); } else { update_post_meta( $post_id, 'logo-design', 'no' ); } //saves branding's value if( isset( $_POST[ 'branding' ] ) ) { update_post_meta( $post_id, 'branding', 'yes' ); } else { update_post_meta( $post_id, 'branding', 'no' ); } //saves print design's value if( isset( $_POST[ 'print-design' ] ) ) { update_post_meta( $post_id, 'print-design', 'yes' ); } else { update_post_meta( $post_id, 'print-design', 'no' ); } } </code></pre>
[ { "answer_id": 276991, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta</a> to fetch each value and compare against 'yes'. E.g.</p>\n\n<pre><code>if(get_post_meta($post-&gt;ID, 'ui-ux-design', true) == 'yes') {\n //show relevant content\n}\n</code></pre>\n" }, { "answer_id": 276994, "author": "Devin Price", "author_id": 125899, "author_profile": "https://wordpress.stackexchange.com/users/125899", "pm_score": 0, "selected": false, "text": "<pre><code>if ( 'yes' == get_post_meta( get_the_ID(), 'ui-ux-design' ) ) :\n // Display your content\nendif;\n</code></pre>\n\n<p>Codex: <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta()</a></p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/276987", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125898/" ]
I have a custom meta box in my page admin with 5 checkboxes. If one or more of the checkboxes are checked, I want certain content to display on the page. I have the meta box checkboxes displaying and saving properly in the admin, but what do I need to put in my template file to show content based on whether or not the checkboxes are checked from the admin? For example, if Web Development, Logo Design and Print Design are checked in the admin, then I want the page to show this: * Web Development * Logo Design * Print Design I have the following in my functions.php file: ``` add_action( 'add_meta_boxes', 'add_custom_box' ); function add_custom_box( $post ) { add_meta_box( 'Meta Box', // ID, should be a string. 'Services', // Meta Box Title. 'services_meta_box', // Your call back function, this is where your form field will go. 'page', // The post type you want this to show up on, can be post, page, or custom post type. 'normal', // The placement of your meta box, can be normal or side. 'core' // The priority in which this will be displayed. ); } function services_meta_box($post) { wp_nonce_field( 'my_awesome_nonce', 'awesome_nonce' ); $checkboxMeta = get_post_meta( $post->ID ); ?> <input type="checkbox" name="ui-ux-design" id="ui-ux-design" value="yes" <?php if ( isset ( $checkboxMeta['ui-ux-design'] ) ) checked( $checkboxMeta['ui-ux-design'][0], 'yes' ); ?> />UI/UX Design<br /> <input type="checkbox" name="web-development" id="web-development" value="yes" <?php if ( isset ( $checkboxMeta['web-development'] ) ) checked( $checkboxMeta['web-development'][0], 'yes' ); ?> />Web Development<br /> <input type="checkbox" name="logo-design" id="logo-design" value="yes" <?php if ( isset ( $checkboxMeta['logo-design'] ) ) checked( $checkboxMeta['logo-design'][0], 'yes' ); ?> />Logo Design<br /> <input type="checkbox" name="branding" id="branding" value="yes" <?php if ( isset ( $checkboxMeta['branding'] ) ) checked( $checkboxMeta['branding'][0], 'yes' ); ?> />Branding<br /> <input type="checkbox" name="print-design" id="print-design" value="yes" <?php if ( isset ( $checkboxMeta['print-design'] ) ) checked( $checkboxMeta['print-design'][0], 'yes' ); ?> />Print Design<br /> <?php } add_action( 'save_post', 'save_services_checkboxes' ); function save_services_checkboxes( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( ( isset ( $_POST['my_awesome_nonce'] ) ) && ( ! wp_verify_nonce( $_POST['my_awesome_nonce'], plugin_basename( __FILE__ ) ) ) ) return; if ( ( isset ( $_POST['post_type'] ) ) && ( 'page' == $_POST['post_type'] ) ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } //saves ui-ux-design's value if( isset( $_POST[ 'ui-ux-design' ] ) ) { update_post_meta( $post_id, 'ui-ux-design', 'yes' ); } else { update_post_meta( $post_id, 'ui-ux-design', 'no' ); } //saves web-development's value if( isset( $_POST[ 'web-development' ] ) ) { update_post_meta( $post_id, 'web-development', 'yes' ); } else { update_post_meta( $post_id, 'web-development', 'no' ); } //saves logo-design's value if( isset( $_POST[ 'logo-design' ] ) ) { update_post_meta( $post_id, 'logo-design', 'yes' ); } else { update_post_meta( $post_id, 'logo-design', 'no' ); } //saves branding's value if( isset( $_POST[ 'branding' ] ) ) { update_post_meta( $post_id, 'branding', 'yes' ); } else { update_post_meta( $post_id, 'branding', 'no' ); } //saves print design's value if( isset( $_POST[ 'print-design' ] ) ) { update_post_meta( $post_id, 'print-design', 'yes' ); } else { update_post_meta( $post_id, 'print-design', 'no' ); } } ```
Use [get\_post\_meta](https://developer.wordpress.org/reference/functions/get_post_meta/) to fetch each value and compare against 'yes'. E.g. ``` if(get_post_meta($post->ID, 'ui-ux-design', true) == 'yes') { //show relevant content } ```
277,008
<p>please I need help with this code</p> <pre><code>add_action( 'the_title', 'adddd', 10, 2 ); function adddd( $title, $post_id ) { if( has_category( 30, $post_id ) ) { $title = 'Prefix ' . $title; } return $title; } </code></pre> <p>Changing the post title of a specific category.</p> <p>The code above is working fine displaying the prefix but am getting error when I tried adding a word or two after the post title. </p> <p>Please any fix for this? Thanks. </p>
[ { "answer_id": 277010, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>You should use filter not action:</p>\n\n<pre><code>function adddd( $title, $post_id ) {\n if( in_category( 30 ) ) {\n $title = 'Prefix - ' . $title . ' - xxx';\n }\n return $title;\n}\nadd_filter( 'the_title', 'adddd', 10, 2 );\n</code></pre>\n" }, { "answer_id": 277030, "author": "Swaglord07", "author_id": 125912, "author_profile": "https://wordpress.stackexchange.com/users/125912", "pm_score": 0, "selected": false, "text": "<p>It returned an error. So I just edited mine adding <code>. ' xxx'</code> after the title </p>\n\n<pre><code>add_action( 'the_title', 'adddd', 10, 2 );\nfunction adddd( $title, $post_id ) \n{\n if( has_category( 30, $post_id ) ) {\n $title = 'Prefix ' . $title . ' xxx';\n }\n\n return $title;\n}\n</code></pre>\n\n<p>It's working as it should now. Thanks very much for your help. </p>\n" } ]
2017/08/15
[ "https://wordpress.stackexchange.com/questions/277008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125912/" ]
please I need help with this code ``` add_action( 'the_title', 'adddd', 10, 2 ); function adddd( $title, $post_id ) { if( has_category( 30, $post_id ) ) { $title = 'Prefix ' . $title; } return $title; } ``` Changing the post title of a specific category. The code above is working fine displaying the prefix but am getting error when I tried adding a word or two after the post title. Please any fix for this? Thanks.
You should use filter not action: ``` function adddd( $title, $post_id ) { if( in_category( 30 ) ) { $title = 'Prefix - ' . $title . ' - xxx'; } return $title; } add_filter( 'the_title', 'adddd', 10, 2 ); ```
277,012
<p>How can I make all the css in the <code>twentyseventeen</code> theme appear inline? I already tried putting the following in header.php:</p> <pre><code>&lt;style&gt; &lt;?php include("/wp-content/themes/twentyseventeen/style.css");?&gt; &lt;/style&gt; </code></pre> <p>and it did not work. </p>
[ { "answer_id": 277019, "author": "Berat Çakır", "author_id": 125911, "author_profile": "https://wordpress.stackexchange.com/users/125911", "pm_score": 0, "selected": false, "text": "<p>Use <code>wp_register_style()</code></p>\n\n<pre><code>// Include stylesheets\nfunction stylename() {\n wp_register_style( 'stylename', '/wp-content/themes/twentyseventeen/style.css' );\n wp_enqueue_style( 'stylename' );\n}\nadd_action( 'wp_enqueue_scripts', 'stylename' );\n</code></pre>\n" }, { "answer_id": 279471, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>For some reason, taking out the beginning <code>/</code> solved my issue:</p>\n\n<pre><code>&lt;style&gt;\n &lt;?php include(\"wp-content/themes/twentyseventeen/style.css\");?&gt;\n&lt;/style&gt;\n</code></pre>\n\n<p>After doing this, I removed it because I realized how much slower it made the page load.</p>\n" }, { "answer_id": 279483, "author": "Luan Cuba", "author_id": 127497, "author_profile": "https://wordpress.stackexchange.com/users/127497", "pm_score": 0, "selected": false, "text": "<p>If you want to make it inline:</p>\n\n<pre><code> &lt;style&gt;\n &lt;?php $css_file = file_get_contents( 'http://yoursite.com/wp-content/themes/twentyseventeen/style.css' );\n echo '&lt;style type=\"text/css\"&gt;' . $css_file . '&lt;/style&gt;';\n &lt;/style&gt;\n</code></pre>\n" } ]
2017/08/16
[ "https://wordpress.stackexchange.com/questions/277012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
How can I make all the css in the `twentyseventeen` theme appear inline? I already tried putting the following in header.php: ``` <style> <?php include("/wp-content/themes/twentyseventeen/style.css");?> </style> ``` and it did not work.
For some reason, taking out the beginning `/` solved my issue: ``` <style> <?php include("wp-content/themes/twentyseventeen/style.css");?> </style> ``` After doing this, I removed it because I realized how much slower it made the page load.
277,027
<p>I'm not sure why but I tried to place Google Fonts at the bottom of the page (in the Javascript section) but it doesn't want to load the font.</p> <p>What should I be looking for that might be preventing that?</p> <p>My logic is that I need so speed up my site and placing the fonts at the bottom of the page I am sure will be better....</p>
[ { "answer_id": 277019, "author": "Berat Çakır", "author_id": 125911, "author_profile": "https://wordpress.stackexchange.com/users/125911", "pm_score": 0, "selected": false, "text": "<p>Use <code>wp_register_style()</code></p>\n\n<pre><code>// Include stylesheets\nfunction stylename() {\n wp_register_style( 'stylename', '/wp-content/themes/twentyseventeen/style.css' );\n wp_enqueue_style( 'stylename' );\n}\nadd_action( 'wp_enqueue_scripts', 'stylename' );\n</code></pre>\n" }, { "answer_id": 279471, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>For some reason, taking out the beginning <code>/</code> solved my issue:</p>\n\n<pre><code>&lt;style&gt;\n &lt;?php include(\"wp-content/themes/twentyseventeen/style.css\");?&gt;\n&lt;/style&gt;\n</code></pre>\n\n<p>After doing this, I removed it because I realized how much slower it made the page load.</p>\n" }, { "answer_id": 279483, "author": "Luan Cuba", "author_id": 127497, "author_profile": "https://wordpress.stackexchange.com/users/127497", "pm_score": 0, "selected": false, "text": "<p>If you want to make it inline:</p>\n\n<pre><code> &lt;style&gt;\n &lt;?php $css_file = file_get_contents( 'http://yoursite.com/wp-content/themes/twentyseventeen/style.css' );\n echo '&lt;style type=\"text/css\"&gt;' . $css_file . '&lt;/style&gt;';\n &lt;/style&gt;\n</code></pre>\n" } ]
2017/08/16
[ "https://wordpress.stackexchange.com/questions/277027", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I'm not sure why but I tried to place Google Fonts at the bottom of the page (in the Javascript section) but it doesn't want to load the font. What should I be looking for that might be preventing that? My logic is that I need so speed up my site and placing the fonts at the bottom of the page I am sure will be better....
For some reason, taking out the beginning `/` solved my issue: ``` <style> <?php include("wp-content/themes/twentyseventeen/style.css");?> </style> ``` After doing this, I removed it because I realized how much slower it made the page load.
277,035
<p>I recognized that site is not responsive and media.css file is not working, i inspected with dev tools what kind of styles are included in header and i found that there is min version<code>/css/media.min.css?ver=4.8.1</code>, but i include media.css without min, What can be the problem that media.css is not working?</p> <p>This is how i included my scripts and styles</p> <pre><code>function wpb_adding_scripts() { wp_deregister_script('jquery'); wp_register_script('jquery', get_template_directory_uri().'/js/jquery.min.js', array(), null,true); wp_register_script('bootstrap_js', get_template_directory_uri().'/js/bootstrap.min.js', array(), null,true); wp_register_script('mixitup_js', get_template_directory_uri().'/js/mixitup.min.js', array(), null,true); wp_register_script('fancybox_js', get_template_directory_uri().'/js/fancybox/dist/jquery.fancybox.js', array(), null,true); wp_register_script('main_js', get_template_directory_uri().'/js/main.js', array(), null,true); wp_enqueue_script('jquery'); wp_enqueue_script('bootstrap_js'); wp_enqueue_script('main_js'); wp_enqueue_style('bootstrap', get_template_directory_uri().'/css/bootstrap.min.css'); wp_enqueue_style('style', get_template_directory_uri().'/style.css'); wp_enqueue_style('media', get_template_directory_uri().'/css/media.css'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); </code></pre>
[ { "answer_id": 277019, "author": "Berat Çakır", "author_id": 125911, "author_profile": "https://wordpress.stackexchange.com/users/125911", "pm_score": 0, "selected": false, "text": "<p>Use <code>wp_register_style()</code></p>\n\n<pre><code>// Include stylesheets\nfunction stylename() {\n wp_register_style( 'stylename', '/wp-content/themes/twentyseventeen/style.css' );\n wp_enqueue_style( 'stylename' );\n}\nadd_action( 'wp_enqueue_scripts', 'stylename' );\n</code></pre>\n" }, { "answer_id": 279471, "author": "NerdOfLinux", "author_id": 123649, "author_profile": "https://wordpress.stackexchange.com/users/123649", "pm_score": 2, "selected": true, "text": "<p>For some reason, taking out the beginning <code>/</code> solved my issue:</p>\n\n<pre><code>&lt;style&gt;\n &lt;?php include(\"wp-content/themes/twentyseventeen/style.css\");?&gt;\n&lt;/style&gt;\n</code></pre>\n\n<p>After doing this, I removed it because I realized how much slower it made the page load.</p>\n" }, { "answer_id": 279483, "author": "Luan Cuba", "author_id": 127497, "author_profile": "https://wordpress.stackexchange.com/users/127497", "pm_score": 0, "selected": false, "text": "<p>If you want to make it inline:</p>\n\n<pre><code> &lt;style&gt;\n &lt;?php $css_file = file_get_contents( 'http://yoursite.com/wp-content/themes/twentyseventeen/style.css' );\n echo '&lt;style type=\"text/css\"&gt;' . $css_file . '&lt;/style&gt;';\n &lt;/style&gt;\n</code></pre>\n" } ]
2017/08/16
[ "https://wordpress.stackexchange.com/questions/277035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124458/" ]
I recognized that site is not responsive and media.css file is not working, i inspected with dev tools what kind of styles are included in header and i found that there is min version`/css/media.min.css?ver=4.8.1`, but i include media.css without min, What can be the problem that media.css is not working? This is how i included my scripts and styles ``` function wpb_adding_scripts() { wp_deregister_script('jquery'); wp_register_script('jquery', get_template_directory_uri().'/js/jquery.min.js', array(), null,true); wp_register_script('bootstrap_js', get_template_directory_uri().'/js/bootstrap.min.js', array(), null,true); wp_register_script('mixitup_js', get_template_directory_uri().'/js/mixitup.min.js', array(), null,true); wp_register_script('fancybox_js', get_template_directory_uri().'/js/fancybox/dist/jquery.fancybox.js', array(), null,true); wp_register_script('main_js', get_template_directory_uri().'/js/main.js', array(), null,true); wp_enqueue_script('jquery'); wp_enqueue_script('bootstrap_js'); wp_enqueue_script('main_js'); wp_enqueue_style('bootstrap', get_template_directory_uri().'/css/bootstrap.min.css'); wp_enqueue_style('style', get_template_directory_uri().'/style.css'); wp_enqueue_style('media', get_template_directory_uri().'/css/media.css'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); ```
For some reason, taking out the beginning `/` solved my issue: ``` <style> <?php include("wp-content/themes/twentyseventeen/style.css");?> </style> ``` After doing this, I removed it because I realized how much slower it made the page load.
277,092
<p>I'm trying to insert a <code>wp_editor()</code> into a page on the front-end with AJAX. The code I have right now inserts the wp_editor elements and the needed JavaScript and CSS files, but none of the settings I used initially in <code>wp_editor()</code> are used when creating this TinyMCE element.</p> <p><strong>How do I pass the <code>$settings</code> set in PHP into the dynamically created TinyMCE instance?</strong></p> <p>I found an old question that seems to answer my question, but I don't understand how it works, and the code gives a PHP Depreciated error.</p> <blockquote> <p><a href="https://wordpress.stackexchange.com/questions/70548/load-tinymce-wp-editor-via-ajax">Load tinyMCE / wp_editor() via AJAX</a></p> </blockquote> <hr> <p><strong>PHP</strong></p> <pre><code>function insert_wp_editor_callback() { // Empty variable $html = ''; // Define the editor settings $content = ''; $editor_id = 'frontend_wp_editor'; $settings = array( 'media_buttons' =&gt; false, 'textarea_rows' =&gt; 1, 'quicktags' =&gt; false, 'tinymce' =&gt; array( 'toolbar1' =&gt; 'bold,italic,undo,redo', 'statusbar' =&gt; false, 'resize' =&gt; 'both', 'paste_as_text' =&gt; true ) ); // Hack to put wp_editor inside variable ob_start(); wp_editor($content, $editor_id, $settings); $html .= ob_get_contents(); ob_end_clean(); // Get the necessary scripts to launch tinymce $baseurl = includes_url( 'js/tinymce' ); $cssurl = includes_url('css/'); global $tinymce_version, $concatenate_scripts, $compress_scripts; $version = 'ver=' . $tinymce_version; $css = $cssurl . 'editor.css'; $compressed = $compress_scripts &amp;&amp; $concatenate_scripts &amp;&amp; isset($_SERVER['HTTP_ACCEPT_ENCODING']) &amp;&amp; false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'); if ( $compressed ) { $html .= "&lt;script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;amp;$version'&gt;&lt;/script&gt;\n"; } else { $html .= "&lt;script type='text/javascript' src='{$baseurl}/tinymce.min.js?$version'&gt;&lt;/script&gt;\n"; $html .= "&lt;script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin.min.js?$version'&gt;&lt;/script&gt;\n"; } add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50 ); add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'enqueue_scripts' ), 1 ); wp_register_style('tinymce_css', $css); wp_enqueue_style('tinymce_css'); // Send data wp_send_json_success($html); wp_die(); } add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' ); add_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' ); </code></pre> <hr> <p><strong>JavaScript</strong></p> <pre><code>$('#insert_wp_editor').on('click', function() { // Data to send to function var data = { 'action': 'insert_wp_editor_callback' }; $.ajax({ url: ajaxURL, type: 'POST', data: data, success: function(response) { if ( response.success === true ) { // Replace element with editor $('#editor-placeholder').replaceWith(response.data); // Init TinyMCE tinymce.init({ selector: '#frontend_wp_editor' }); } } }); }); </code></pre>
[ { "answer_id": 277214, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 4, "selected": true, "text": "<p>So, after doing some more digging, I answered my own question by \"connecting the dots\", so to speak. There's a lot of bits and pieces of info on this topic on StackOverflow and StackExchange, but none of them really answered my question.</p>\n\n<p>So here is the full working code to loading a <code>wp_editor</code> instance with AJAX on the front-end, <strong>including</strong> the settings provided to <code>wp_editor</code>.</p>\n\n<p>I think there might be an even better solution, as right now, I'm having to call <code>wp_print_footer_scripts()</code>, which <em>might</em> add some unnessacary stuff, but doesn't (in my case).</p>\n\n<hr>\n\n<p><strong>PHP</strong></p>\n\n<pre><code>function insert_wp_editor_callback() {\n $html = '';\n\n // Define the editor settings\n $content = ''; \n $editor_id = 'frontend_wp_editor';\n\n $settings = array(\n 'media_buttons' =&gt; false,\n 'textarea_rows' =&gt; 1,\n 'quicktags' =&gt; false,\n\n 'tinymce' =&gt; array( \n 'toolbar1' =&gt; 'bold,italic,undo,redo',\n 'statusbar' =&gt; false,\n 'resize' =&gt; 'both',\n 'paste_as_text' =&gt; true\n )\n );\n\n // Grab content to put inside a variable\n ob_start();\n\n // Create the editor\n wp_editor($content, $editor_id, $settings); \n\n // IMPORTANT\n // Adding the required scripts, styles, and wp_editor configuration\n _WP_Editors::enqueue_scripts();\n _WP_Editors::editor_js();\n print_footer_scripts();\n\n $html .= ob_get_contents();\n\n ob_end_clean();\n\n // Send everything to JavaScript function\n wp_send_json_success($html); \n\n wp_die(); \n\n} add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' );\nadd_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' );\n</code></pre>\n" }, { "answer_id": 404571, "author": "John Dorner", "author_id": 20453, "author_profile": "https://wordpress.stackexchange.com/users/20453", "pm_score": 0, "selected": false, "text": "<pre><code>tinymce.execCommand( 'mceAddEditor', true, element.id );\n</code></pre>\n<p>did the trick for me.\nThanks to Goran Jakovljevic's answer on: <a href=\"https://wordpress.stackexchange.com/questions/106639/how-to-load-wp-editor-via-ajax\">How to load wp_editor via AJAX</a></p>\n" } ]
2017/08/16
[ "https://wordpress.stackexchange.com/questions/277092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
I'm trying to insert a `wp_editor()` into a page on the front-end with AJAX. The code I have right now inserts the wp\_editor elements and the needed JavaScript and CSS files, but none of the settings I used initially in `wp_editor()` are used when creating this TinyMCE element. **How do I pass the `$settings` set in PHP into the dynamically created TinyMCE instance?** I found an old question that seems to answer my question, but I don't understand how it works, and the code gives a PHP Depreciated error. > > [Load tinyMCE / wp\_editor() via AJAX](https://wordpress.stackexchange.com/questions/70548/load-tinymce-wp-editor-via-ajax) > > > --- **PHP** ``` function insert_wp_editor_callback() { // Empty variable $html = ''; // Define the editor settings $content = ''; $editor_id = 'frontend_wp_editor'; $settings = array( 'media_buttons' => false, 'textarea_rows' => 1, 'quicktags' => false, 'tinymce' => array( 'toolbar1' => 'bold,italic,undo,redo', 'statusbar' => false, 'resize' => 'both', 'paste_as_text' => true ) ); // Hack to put wp_editor inside variable ob_start(); wp_editor($content, $editor_id, $settings); $html .= ob_get_contents(); ob_end_clean(); // Get the necessary scripts to launch tinymce $baseurl = includes_url( 'js/tinymce' ); $cssurl = includes_url('css/'); global $tinymce_version, $concatenate_scripts, $compress_scripts; $version = 'ver=' . $tinymce_version; $css = $cssurl . 'editor.css'; $compressed = $compress_scripts && $concatenate_scripts && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'); if ( $compressed ) { $html .= "<script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;$version'></script>\n"; } else { $html .= "<script type='text/javascript' src='{$baseurl}/tinymce.min.js?$version'></script>\n"; $html .= "<script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin.min.js?$version'></script>\n"; } add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50 ); add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'enqueue_scripts' ), 1 ); wp_register_style('tinymce_css', $css); wp_enqueue_style('tinymce_css'); // Send data wp_send_json_success($html); wp_die(); } add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' ); add_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' ); ``` --- **JavaScript** ``` $('#insert_wp_editor').on('click', function() { // Data to send to function var data = { 'action': 'insert_wp_editor_callback' }; $.ajax({ url: ajaxURL, type: 'POST', data: data, success: function(response) { if ( response.success === true ) { // Replace element with editor $('#editor-placeholder').replaceWith(response.data); // Init TinyMCE tinymce.init({ selector: '#frontend_wp_editor' }); } } }); }); ```
So, after doing some more digging, I answered my own question by "connecting the dots", so to speak. There's a lot of bits and pieces of info on this topic on StackOverflow and StackExchange, but none of them really answered my question. So here is the full working code to loading a `wp_editor` instance with AJAX on the front-end, **including** the settings provided to `wp_editor`. I think there might be an even better solution, as right now, I'm having to call `wp_print_footer_scripts()`, which *might* add some unnessacary stuff, but doesn't (in my case). --- **PHP** ``` function insert_wp_editor_callback() { $html = ''; // Define the editor settings $content = ''; $editor_id = 'frontend_wp_editor'; $settings = array( 'media_buttons' => false, 'textarea_rows' => 1, 'quicktags' => false, 'tinymce' => array( 'toolbar1' => 'bold,italic,undo,redo', 'statusbar' => false, 'resize' => 'both', 'paste_as_text' => true ) ); // Grab content to put inside a variable ob_start(); // Create the editor wp_editor($content, $editor_id, $settings); // IMPORTANT // Adding the required scripts, styles, and wp_editor configuration _WP_Editors::enqueue_scripts(); _WP_Editors::editor_js(); print_footer_scripts(); $html .= ob_get_contents(); ob_end_clean(); // Send everything to JavaScript function wp_send_json_success($html); wp_die(); } add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' ); add_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' ); ```
277,098
<p>I have the following I'm trying to enqueue in <code>functions.php</code></p> <pre><code>wp_enqueue_script( 'param-example', 'https://domain.com/example?f=j&amp;s=w&amp;c=t', array(), null ); </code></pre> <p>Except WordPress is escaping the ampersands in the HTML which is breaking the script.</p> <p>How can I prevent WordPress from escaping the URL in <code>wp_enqueue_script</code>? </p> <p>The other examples that seem close to this question haven't worked.</p>
[ { "answer_id": 277214, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 4, "selected": true, "text": "<p>So, after doing some more digging, I answered my own question by \"connecting the dots\", so to speak. There's a lot of bits and pieces of info on this topic on StackOverflow and StackExchange, but none of them really answered my question.</p>\n\n<p>So here is the full working code to loading a <code>wp_editor</code> instance with AJAX on the front-end, <strong>including</strong> the settings provided to <code>wp_editor</code>.</p>\n\n<p>I think there might be an even better solution, as right now, I'm having to call <code>wp_print_footer_scripts()</code>, which <em>might</em> add some unnessacary stuff, but doesn't (in my case).</p>\n\n<hr>\n\n<p><strong>PHP</strong></p>\n\n<pre><code>function insert_wp_editor_callback() {\n $html = '';\n\n // Define the editor settings\n $content = ''; \n $editor_id = 'frontend_wp_editor';\n\n $settings = array(\n 'media_buttons' =&gt; false,\n 'textarea_rows' =&gt; 1,\n 'quicktags' =&gt; false,\n\n 'tinymce' =&gt; array( \n 'toolbar1' =&gt; 'bold,italic,undo,redo',\n 'statusbar' =&gt; false,\n 'resize' =&gt; 'both',\n 'paste_as_text' =&gt; true\n )\n );\n\n // Grab content to put inside a variable\n ob_start();\n\n // Create the editor\n wp_editor($content, $editor_id, $settings); \n\n // IMPORTANT\n // Adding the required scripts, styles, and wp_editor configuration\n _WP_Editors::enqueue_scripts();\n _WP_Editors::editor_js();\n print_footer_scripts();\n\n $html .= ob_get_contents();\n\n ob_end_clean();\n\n // Send everything to JavaScript function\n wp_send_json_success($html); \n\n wp_die(); \n\n} add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' );\nadd_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' );\n</code></pre>\n" }, { "answer_id": 404571, "author": "John Dorner", "author_id": 20453, "author_profile": "https://wordpress.stackexchange.com/users/20453", "pm_score": 0, "selected": false, "text": "<pre><code>tinymce.execCommand( 'mceAddEditor', true, element.id );\n</code></pre>\n<p>did the trick for me.\nThanks to Goran Jakovljevic's answer on: <a href=\"https://wordpress.stackexchange.com/questions/106639/how-to-load-wp-editor-via-ajax\">How to load wp_editor via AJAX</a></p>\n" } ]
2017/08/16
[ "https://wordpress.stackexchange.com/questions/277098", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125976/" ]
I have the following I'm trying to enqueue in `functions.php` ``` wp_enqueue_script( 'param-example', 'https://domain.com/example?f=j&s=w&c=t', array(), null ); ``` Except WordPress is escaping the ampersands in the HTML which is breaking the script. How can I prevent WordPress from escaping the URL in `wp_enqueue_script`? The other examples that seem close to this question haven't worked.
So, after doing some more digging, I answered my own question by "connecting the dots", so to speak. There's a lot of bits and pieces of info on this topic on StackOverflow and StackExchange, but none of them really answered my question. So here is the full working code to loading a `wp_editor` instance with AJAX on the front-end, **including** the settings provided to `wp_editor`. I think there might be an even better solution, as right now, I'm having to call `wp_print_footer_scripts()`, which *might* add some unnessacary stuff, but doesn't (in my case). --- **PHP** ``` function insert_wp_editor_callback() { $html = ''; // Define the editor settings $content = ''; $editor_id = 'frontend_wp_editor'; $settings = array( 'media_buttons' => false, 'textarea_rows' => 1, 'quicktags' => false, 'tinymce' => array( 'toolbar1' => 'bold,italic,undo,redo', 'statusbar' => false, 'resize' => 'both', 'paste_as_text' => true ) ); // Grab content to put inside a variable ob_start(); // Create the editor wp_editor($content, $editor_id, $settings); // IMPORTANT // Adding the required scripts, styles, and wp_editor configuration _WP_Editors::enqueue_scripts(); _WP_Editors::editor_js(); print_footer_scripts(); $html .= ob_get_contents(); ob_end_clean(); // Send everything to JavaScript function wp_send_json_success($html); wp_die(); } add_action( 'wp_ajax_insert_wp_editor_callback', 'insert_wp_editor_callback' ); add_action( 'wp_ajax_nopriv_insert_wp_editor_callback', 'insert_wp_editor_callback' ); ```
277,133
<p>I'm trying to add the category to the post-meta.php file so the blog page will not only show the author and date, but also the category for each post. However, I can't seem to find any correct way to do so. The current code is the following:</p> <pre><code>&lt;span class="post-meta"&gt; &lt;?php $author = "&lt;a href='" . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . "'&gt;" . esc_html( get_the_author() ) . "&lt;/a&gt;"; $date = "&lt;a href='" . esc_url( get_month_link( get_the_date( 'Y' ), get_the_date( 'n' ) ) ) . "'&gt;" . date_i18n( get_option( 'date_format' ), strtotime( get_the_date( 'r' ) ) ) . "&lt;/a&gt;"; ?&gt; &lt;?php printf( _x( 'Published by %1$s on %2$s', 'This blog post was published by some author on some date', 'author' ), $author, $date ); ?&gt; </code></pre> <p></p> <p>Could someone please help me do this? Thanks!</p>
[ { "answer_id": 277137, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 1, "selected": false, "text": "<p>you can use <code>get_the_category_list()</code> it will show a list of the categories of the post, you can also use <code>get_the_category()</code> it will return an array, you can iterate it to format it, you can find examples <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 277150, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 0, "selected": false, "text": "<p><code>&lt;?php foreach((get_the_category()) as $category) { ?&gt;\n &lt;a href=\"&lt;?php echo $category-&gt;name; ?&gt;\"&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/a&gt;</code></p>\n\n<p>use <code>echo $category-&gt;name</code> to get category name Or use <code>echo $category-&gt;category_nicename</code> to get class name</p>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125997/" ]
I'm trying to add the category to the post-meta.php file so the blog page will not only show the author and date, but also the category for each post. However, I can't seem to find any correct way to do so. The current code is the following: ``` <span class="post-meta"> <?php $author = "<a href='" . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . "'>" . esc_html( get_the_author() ) . "</a>"; $date = "<a href='" . esc_url( get_month_link( get_the_date( 'Y' ), get_the_date( 'n' ) ) ) . "'>" . date_i18n( get_option( 'date_format' ), strtotime( get_the_date( 'r' ) ) ) . "</a>"; ?> <?php printf( _x( 'Published by %1$s on %2$s', 'This blog post was published by some author on some date', 'author' ), $author, $date ); ?> ``` Could someone please help me do this? Thanks!
you can use `get_the_category_list()` it will show a list of the categories of the post, you can also use `get_the_category()` it will return an array, you can iterate it to format it, you can find examples [here](https://developer.wordpress.org/reference/functions/get_the_category/).
277,179
<p>I've created two taxonomies:</p> <ul> <li>Make</li> <li>Model</li> </ul> <p>This is for a CPT Vehicles. It goes without saying, Make would be your make (Honda / Toyota / Ford / etc) and then one would select the Model based on the Make.</p> <p>How do I setup the relationship between Make and Model? Or have I gone about this all wrong and it should in fact be a single taxonomy 'Make &amp; Model'?</p> <p>Im not looking for:</p> <pre><code>Vehicle CPT |-&gt; Make |-&gt; Model </code></pre> <p>Im looking for:</p> <pre><code>Vehicle CPT |-&gt; Make |--&gt; Model </code></pre>
[ { "answer_id": 277180, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Taxonomies are not child of each other unlike terms, which can be. Take a look at this flowchart:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dYJob.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dYJob.png\" alt=\"Taxonomy relationship\"></a></p>\n\n<p>Model is a child of Make, and should not be registered as a new taxonomy. What you are trying to do, is something like setting Ford as a child of Honda, which is not right. Instead, register 1 single Make taxonomy, and then create sub-taxonomies, just like what we do in categories.</p>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\"><code>register_taxonomy()</code></a> function at the codex, and register your taxonomy as hierarchical, then create sub taxonomies as model.</p>\n" }, { "answer_id": 277208, "author": "Amos Lee", "author_id": 73995, "author_profile": "https://wordpress.stackexchange.com/users/73995", "pm_score": 0, "selected": false, "text": "<p>You can use term meta to set a Model is a Make`s child, let us assume a Make \"Honda\" has term_id 3, </p>\n\n<pre><code>// when add terms to taxonomy Model\nadd_term_meta($term_id, 'make_id', '3');\n</code></pre>\n\n<p>So when add a connection to taxonomy \"Make\" and \"\"Model. when can add metabox to taxonomy term creation page.</p>\n\n<p>Even so, We also need change the taxonomy select ui as chained, it is a little complex.</p>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277179", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77729/" ]
I've created two taxonomies: * Make * Model This is for a CPT Vehicles. It goes without saying, Make would be your make (Honda / Toyota / Ford / etc) and then one would select the Model based on the Make. How do I setup the relationship between Make and Model? Or have I gone about this all wrong and it should in fact be a single taxonomy 'Make & Model'? Im not looking for: ``` Vehicle CPT |-> Make |-> Model ``` Im looking for: ``` Vehicle CPT |-> Make |--> Model ```
Taxonomies are not child of each other unlike terms, which can be. Take a look at this flowchart: [![Taxonomy relationship](https://i.stack.imgur.com/dYJob.png)](https://i.stack.imgur.com/dYJob.png) Model is a child of Make, and should not be registered as a new taxonomy. What you are trying to do, is something like setting Ford as a child of Honda, which is not right. Instead, register 1 single Make taxonomy, and then create sub-taxonomies, just like what we do in categories. Take a look at [`register_taxonomy()`](https://codex.wordpress.org/Function_Reference/register_taxonomy) function at the codex, and register your taxonomy as hierarchical, then create sub taxonomies as model.
277,182
<p>I am developing a plugin which uses options API.</p> <p>I defined a class that uses a function to sanitize the inputs, but when I submit the options form, It displays errors and info twice.</p> <p>And also I didn't succeed at displaying the error messages.</p> <p>What is the proper way to display the successful and error messages on validation of options form?</p> <p>Thank you.</p> <pre><code>register_setting( $this-&gt;plugin_slug, // option_group $this-&gt;plugin_slug, // option_name, for name property of tags [$this, 'process_inputs'] // sanitize_callback ); public function process_inputs( $input ){ // sanitize functions: // sanitize_email(), sanitize_file_name(), sanitize_html_class(), sanitize_key(), sanitize_meta(), sanitize_mime_type(), // sanitize_option(), sanitize_sql_orderby(), sanitize_text_field(), sanitize_textarea_field(), sanitize_title(), // sanitize_title_for_query(), sanitize_title_with_dashes(), sanitize_user() $options = []; if( isset( $input['frontend-font'] ) and $input['frontend-font'] == true ) { $options['frontend-font'] = true; }else{ $options['frontend-font'] = false; } if( isset( $input['backend-font'] ) and $input['backend-font'] == true ){ $options['backend-font'] = true; }else{ $options['backend-font'] = false; } // add error/update messages // check if the user have submitted the settings // wordpress will add the "settings-updated" $_GET parameter to the url if ( isset( $_GET['settings-updated'] ) ) { // add settings saved message with the class of "updated"*/ add_settings_error( 'persianfont_messages', // Slug title of setting 'wporg_message', // Slug-name , Used as part of 'id' attribute in HTML output. __( 'settings saved.', 'persianfont' ), // message text, will be shown inside styled &lt;div&gt; and &lt;p&gt; tags 'error' // Message type, controls HTML class. Accepts 'error' or 'updated'. ); } return $options; } /** * Settings page display callback. */ function settings_page_content() { // check user capabilities if ( ! current_user_can( 'manage_options' ) ) { return; } //var_dump( wp_load_alloptions() ); // print all options // show error/update messages settings_errors( 'persianfont_messages' ); ?&gt; &lt;div class="wrap"&gt; &lt;h1 class="wp-heading-inline"&gt;&lt;?php echo esc_html($this-&gt;page_title); ?&gt;&lt;/h1&gt; &lt;form method="post" action="options.php"&gt; &lt;?php submit_button(); settings_fields( $this-&gt;plugin_slug ); // This prints out all hidden setting fields do_settings_sections( $this-&gt;plugin_slug ); submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } </code></pre>
[ { "answer_id": 277180, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Taxonomies are not child of each other unlike terms, which can be. Take a look at this flowchart:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dYJob.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dYJob.png\" alt=\"Taxonomy relationship\"></a></p>\n\n<p>Model is a child of Make, and should not be registered as a new taxonomy. What you are trying to do, is something like setting Ford as a child of Honda, which is not right. Instead, register 1 single Make taxonomy, and then create sub-taxonomies, just like what we do in categories.</p>\n\n<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\"><code>register_taxonomy()</code></a> function at the codex, and register your taxonomy as hierarchical, then create sub taxonomies as model.</p>\n" }, { "answer_id": 277208, "author": "Amos Lee", "author_id": 73995, "author_profile": "https://wordpress.stackexchange.com/users/73995", "pm_score": 0, "selected": false, "text": "<p>You can use term meta to set a Model is a Make`s child, let us assume a Make \"Honda\" has term_id 3, </p>\n\n<pre><code>// when add terms to taxonomy Model\nadd_term_meta($term_id, 'make_id', '3');\n</code></pre>\n\n<p>So when add a connection to taxonomy \"Make\" and \"\"Model. when can add metabox to taxonomy term creation page.</p>\n\n<p>Even so, We also need change the taxonomy select ui as chained, it is a little complex.</p>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114465/" ]
I am developing a plugin which uses options API. I defined a class that uses a function to sanitize the inputs, but when I submit the options form, It displays errors and info twice. And also I didn't succeed at displaying the error messages. What is the proper way to display the successful and error messages on validation of options form? Thank you. ``` register_setting( $this->plugin_slug, // option_group $this->plugin_slug, // option_name, for name property of tags [$this, 'process_inputs'] // sanitize_callback ); public function process_inputs( $input ){ // sanitize functions: // sanitize_email(), sanitize_file_name(), sanitize_html_class(), sanitize_key(), sanitize_meta(), sanitize_mime_type(), // sanitize_option(), sanitize_sql_orderby(), sanitize_text_field(), sanitize_textarea_field(), sanitize_title(), // sanitize_title_for_query(), sanitize_title_with_dashes(), sanitize_user() $options = []; if( isset( $input['frontend-font'] ) and $input['frontend-font'] == true ) { $options['frontend-font'] = true; }else{ $options['frontend-font'] = false; } if( isset( $input['backend-font'] ) and $input['backend-font'] == true ){ $options['backend-font'] = true; }else{ $options['backend-font'] = false; } // add error/update messages // check if the user have submitted the settings // wordpress will add the "settings-updated" $_GET parameter to the url if ( isset( $_GET['settings-updated'] ) ) { // add settings saved message with the class of "updated"*/ add_settings_error( 'persianfont_messages', // Slug title of setting 'wporg_message', // Slug-name , Used as part of 'id' attribute in HTML output. __( 'settings saved.', 'persianfont' ), // message text, will be shown inside styled <div> and <p> tags 'error' // Message type, controls HTML class. Accepts 'error' or 'updated'. ); } return $options; } /** * Settings page display callback. */ function settings_page_content() { // check user capabilities if ( ! current_user_can( 'manage_options' ) ) { return; } //var_dump( wp_load_alloptions() ); // print all options // show error/update messages settings_errors( 'persianfont_messages' ); ?> <div class="wrap"> <h1 class="wp-heading-inline"><?php echo esc_html($this->page_title); ?></h1> <form method="post" action="options.php"> <?php submit_button(); settings_fields( $this->plugin_slug ); // This prints out all hidden setting fields do_settings_sections( $this->plugin_slug ); submit_button(); ?> </form> </div> <?php } ```
Taxonomies are not child of each other unlike terms, which can be. Take a look at this flowchart: [![Taxonomy relationship](https://i.stack.imgur.com/dYJob.png)](https://i.stack.imgur.com/dYJob.png) Model is a child of Make, and should not be registered as a new taxonomy. What you are trying to do, is something like setting Ford as a child of Honda, which is not right. Instead, register 1 single Make taxonomy, and then create sub-taxonomies, just like what we do in categories. Take a look at [`register_taxonomy()`](https://codex.wordpress.org/Function_Reference/register_taxonomy) function at the codex, and register your taxonomy as hierarchical, then create sub taxonomies as model.
277,197
<p>With WP.SE's help I've learned how to send data from a form to WP_REST but now I'm having an issue with returning a custom error. I can successfully pass information to the <code>WP_REST_Response</code> and I've added a check in <code>WP_REST_Response</code> and want it to return the error message back to the AJAX error function but I'm having issues.</p> <p>For example on my local box the IP is <code>::1</code> and if I create a function in PHP:</p> <pre><code>function ipAddress() { if (isset($_SERVER['REMOTE_ADDR'])) : $ip_address = clean($_SERVER['REMOTE_ADDR']); else : $ip_address = "undefined"; endif; return $ip_address; } </code></pre> <p>and after researching how to return the check I ran across:</p> <ul> <li><a href="https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script">Returning JSON from a PHP Script</a></li> <li><a href="https://stackoverflow.com/questions/12693423/clean-way-to-throw-php-exception-through-jquery-ajax-and-json">Clean way to throw php exception through jquery/ajax and json</a></li> <li><a href="https://stackoverflow.com/questions/682260/returning-json-from-php-to-javascript">Returning JSON from PHP to JavaScript?</a></li> </ul> <p>so I added to my <code>WP_REST_Response</code>:</p> <pre><code>function vader(\WP_REST_Request $request) { if (ipAddress() == "::1") : return json_encode(array( 'error' =&gt; 'you are localhost' )); endif; } </code></pre> <p>and in my vader.js if I use:</p> <pre><code>error: function(data) { throw data.error; }, </code></pre> <p>but I have no errors in the console and it shows <code>{"error":"you are localhost"}</code> but I'm just wanting the value to go to the error function. </p> <p>Looking at <a href="http://api.jquery.com/jquery.ajax/" rel="nofollow noreferrer">jQuery.ajax() documentation</a> I found <code>statusCode</code> and I can get:</p> <pre><code>if (ek_ip_address() == "::1") : return new WP_Error('foo', 'bar', array('status' =&gt; 404)); endif; </code></pre> <p>and:</p> <pre><code>statusCode: { 404: function() { $('#testForm').append("thrown 404s"); } } </code></pre> <p>Is there a way to get <code>error</code> to show or am I misunderstanding AJAX <code>error</code>? What am I doing wrong and how can I get the JSON value return from <code>WP_REST_REQUEST</code> to go to the <code>error</code> function?</p>
[ { "answer_id": 277200, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>An Ajax call can be sent to anywhere. It can be a server running a PHP, a virtual local route that is simulated using C#, or anything else. So, Ajax does not care what the response is, since it can't understand it.</p>\n<p>When you are sending <em>any</em> data back from your server, as long as the status is 200 ( or anything but an error ), the Ajax script considers this a <em>successful</em> request. Afterward, it's up to you to handle the situation based on your response.</p>\n<h2>A Simple Example</h2>\n<p>I'm a novice at English language. I use the <em>&quot;error&quot;</em> word instead of <em>&quot;success&quot;</em> and return it as a response.</p>\n<pre><code>$data['status'] = 'error';\n$data['message'] = 'Nice! Request has been done.';\nreturn $data;\n</code></pre>\n<p>The server did successfully run the task, but has sent the wrong status. How would Ajax know that?</p>\n<p>So, the error section of an Ajax call is for when there is a problem making the request, before it's finished, not after. After the response has been sent, Ajax did its job, it's considered a successful request.</p>\n<h2>Real Life Example</h2>\n<ol>\n<li>Let's say you write a letter for a friend, and ask him do join you in\na business. You are the <em>&quot;user&quot;</em> here.</li>\n<li>You give your letter to the post man for delivery. The post man is\nthe <em>&quot;Ajax&quot;</em> function here.</li>\n<li>Your friend write a very big <em>&quot;NO&quot;</em> in his response (how rude),\nseals the letter and passes it back to the post man. Your friend is the <em>&quot;server&quot;</em> here.</li>\n<li>The post man delivers the letter back to you. The post man did his job, no matter what the response was. So he is considered a <em>&quot;successful&quot;</em> one at his job. (don't forget his tip)</li>\n<li>It's up to you to choose whether to scream, shout or cry because of\nyour friend's strict <em>&quot;NO&quot;</em> (Error handling). It's not the post\nman's problem.</li>\n</ol>\n" }, { "answer_id": 277201, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 1, "selected": false, "text": "<p>As Jack correctly points out, since the request was successful, you will never end up in the <code>error</code> callback. You'd rather need to process whatever your server returned inside the <code>success</code> callback of <code>jQuery.ajax()</code>:</p>\n\n<pre><code>success: (data) =&gt; {\n if('error' in data) {\n // server returned `error` property in payload - something is wrong!\n }\n}\n</code></pre>\n\n<p>If you're not using ES6:</p>\n\n<pre><code>success:function(data) {\n if(data &amp;&amp; typeof data.error !== 'undefined') {\n // show error message to user\n }\n}\n</code></pre>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277197", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
With WP.SE's help I've learned how to send data from a form to WP\_REST but now I'm having an issue with returning a custom error. I can successfully pass information to the `WP_REST_Response` and I've added a check in `WP_REST_Response` and want it to return the error message back to the AJAX error function but I'm having issues. For example on my local box the IP is `::1` and if I create a function in PHP: ``` function ipAddress() { if (isset($_SERVER['REMOTE_ADDR'])) : $ip_address = clean($_SERVER['REMOTE_ADDR']); else : $ip_address = "undefined"; endif; return $ip_address; } ``` and after researching how to return the check I ran across: * [Returning JSON from a PHP Script](https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script) * [Clean way to throw php exception through jquery/ajax and json](https://stackoverflow.com/questions/12693423/clean-way-to-throw-php-exception-through-jquery-ajax-and-json) * [Returning JSON from PHP to JavaScript?](https://stackoverflow.com/questions/682260/returning-json-from-php-to-javascript) so I added to my `WP_REST_Response`: ``` function vader(\WP_REST_Request $request) { if (ipAddress() == "::1") : return json_encode(array( 'error' => 'you are localhost' )); endif; } ``` and in my vader.js if I use: ``` error: function(data) { throw data.error; }, ``` but I have no errors in the console and it shows `{"error":"you are localhost"}` but I'm just wanting the value to go to the error function. Looking at [jQuery.ajax() documentation](http://api.jquery.com/jquery.ajax/) I found `statusCode` and I can get: ``` if (ek_ip_address() == "::1") : return new WP_Error('foo', 'bar', array('status' => 404)); endif; ``` and: ``` statusCode: { 404: function() { $('#testForm').append("thrown 404s"); } } ``` Is there a way to get `error` to show or am I misunderstanding AJAX `error`? What am I doing wrong and how can I get the JSON value return from `WP_REST_REQUEST` to go to the `error` function?
An Ajax call can be sent to anywhere. It can be a server running a PHP, a virtual local route that is simulated using C#, or anything else. So, Ajax does not care what the response is, since it can't understand it. When you are sending *any* data back from your server, as long as the status is 200 ( or anything but an error ), the Ajax script considers this a *successful* request. Afterward, it's up to you to handle the situation based on your response. A Simple Example ---------------- I'm a novice at English language. I use the *"error"* word instead of *"success"* and return it as a response. ``` $data['status'] = 'error'; $data['message'] = 'Nice! Request has been done.'; return $data; ``` The server did successfully run the task, but has sent the wrong status. How would Ajax know that? So, the error section of an Ajax call is for when there is a problem making the request, before it's finished, not after. After the response has been sent, Ajax did its job, it's considered a successful request. Real Life Example ----------------- 1. Let's say you write a letter for a friend, and ask him do join you in a business. You are the *"user"* here. 2. You give your letter to the post man for delivery. The post man is the *"Ajax"* function here. 3. Your friend write a very big *"NO"* in his response (how rude), seals the letter and passes it back to the post man. Your friend is the *"server"* here. 4. The post man delivers the letter back to you. The post man did his job, no matter what the response was. So he is considered a *"successful"* one at his job. (don't forget his tip) 5. It's up to you to choose whether to scream, shout or cry because of your friend's strict *"NO"* (Error handling). It's not the post man's problem.
277,234
<p>I know this is going to be a little strange because it's seemingly counter-intuitive. How do I add code to my WP multisite without adding a new plugin, and keeping it out of functions.php?</p> <p>Purpose: I run a WP multisite instance that uses some custom code for sending emails using a self-signed certificate. I don't want anyone to know the code even exists. I don't want it to show in a menu, and I don't want it to be deleted during an update.</p> <p>What I've Tried: I tried removing the header from the custom plugin I'm using now for this code, but that just deactivated the plugin.</p> <p>I tried moving the file out of it's directory and placing it directly in the plugins folder, but that doesn't load it. I know because I lose email function.</p> <p>I want to do the same for some custom shortcodes I have ready to go.</p> <p>I know you might be asking why? It's easy to add the plugins and limit who can see them. I know this as well, but it would be even easier to add code without the need for creating a plugin. It also adds the benefit of completely hiding the code from customer/admin eyes. Sometimes admins can be a bigger problem than the customers.</p> <p>For example, the email plugin I use has more lines of code in the header for the plugin, than the functional code itself.</p> <p>Being able to add code snippets without the need for creating plugins would make my life much easier.</p> <p>What I would like for a solution: A sub-directory within wp-content/ that will parse any code files included in this sub-directory.</p> <p>Is WP presently capable of this?</p> <p>Thank you.</p>
[ { "answer_id": 277200, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>An Ajax call can be sent to anywhere. It can be a server running a PHP, a virtual local route that is simulated using C#, or anything else. So, Ajax does not care what the response is, since it can't understand it.</p>\n<p>When you are sending <em>any</em> data back from your server, as long as the status is 200 ( or anything but an error ), the Ajax script considers this a <em>successful</em> request. Afterward, it's up to you to handle the situation based on your response.</p>\n<h2>A Simple Example</h2>\n<p>I'm a novice at English language. I use the <em>&quot;error&quot;</em> word instead of <em>&quot;success&quot;</em> and return it as a response.</p>\n<pre><code>$data['status'] = 'error';\n$data['message'] = 'Nice! Request has been done.';\nreturn $data;\n</code></pre>\n<p>The server did successfully run the task, but has sent the wrong status. How would Ajax know that?</p>\n<p>So, the error section of an Ajax call is for when there is a problem making the request, before it's finished, not after. After the response has been sent, Ajax did its job, it's considered a successful request.</p>\n<h2>Real Life Example</h2>\n<ol>\n<li>Let's say you write a letter for a friend, and ask him do join you in\na business. You are the <em>&quot;user&quot;</em> here.</li>\n<li>You give your letter to the post man for delivery. The post man is\nthe <em>&quot;Ajax&quot;</em> function here.</li>\n<li>Your friend write a very big <em>&quot;NO&quot;</em> in his response (how rude),\nseals the letter and passes it back to the post man. Your friend is the <em>&quot;server&quot;</em> here.</li>\n<li>The post man delivers the letter back to you. The post man did his job, no matter what the response was. So he is considered a <em>&quot;successful&quot;</em> one at his job. (don't forget his tip)</li>\n<li>It's up to you to choose whether to scream, shout or cry because of\nyour friend's strict <em>&quot;NO&quot;</em> (Error handling). It's not the post\nman's problem.</li>\n</ol>\n" }, { "answer_id": 277201, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 1, "selected": false, "text": "<p>As Jack correctly points out, since the request was successful, you will never end up in the <code>error</code> callback. You'd rather need to process whatever your server returned inside the <code>success</code> callback of <code>jQuery.ajax()</code>:</p>\n\n<pre><code>success: (data) =&gt; {\n if('error' in data) {\n // server returned `error` property in payload - something is wrong!\n }\n}\n</code></pre>\n\n<p>If you're not using ES6:</p>\n\n<pre><code>success:function(data) {\n if(data &amp;&amp; typeof data.error !== 'undefined') {\n // show error message to user\n }\n}\n</code></pre>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126052/" ]
I know this is going to be a little strange because it's seemingly counter-intuitive. How do I add code to my WP multisite without adding a new plugin, and keeping it out of functions.php? Purpose: I run a WP multisite instance that uses some custom code for sending emails using a self-signed certificate. I don't want anyone to know the code even exists. I don't want it to show in a menu, and I don't want it to be deleted during an update. What I've Tried: I tried removing the header from the custom plugin I'm using now for this code, but that just deactivated the plugin. I tried moving the file out of it's directory and placing it directly in the plugins folder, but that doesn't load it. I know because I lose email function. I want to do the same for some custom shortcodes I have ready to go. I know you might be asking why? It's easy to add the plugins and limit who can see them. I know this as well, but it would be even easier to add code without the need for creating a plugin. It also adds the benefit of completely hiding the code from customer/admin eyes. Sometimes admins can be a bigger problem than the customers. For example, the email plugin I use has more lines of code in the header for the plugin, than the functional code itself. Being able to add code snippets without the need for creating plugins would make my life much easier. What I would like for a solution: A sub-directory within wp-content/ that will parse any code files included in this sub-directory. Is WP presently capable of this? Thank you.
An Ajax call can be sent to anywhere. It can be a server running a PHP, a virtual local route that is simulated using C#, or anything else. So, Ajax does not care what the response is, since it can't understand it. When you are sending *any* data back from your server, as long as the status is 200 ( or anything but an error ), the Ajax script considers this a *successful* request. Afterward, it's up to you to handle the situation based on your response. A Simple Example ---------------- I'm a novice at English language. I use the *"error"* word instead of *"success"* and return it as a response. ``` $data['status'] = 'error'; $data['message'] = 'Nice! Request has been done.'; return $data; ``` The server did successfully run the task, but has sent the wrong status. How would Ajax know that? So, the error section of an Ajax call is for when there is a problem making the request, before it's finished, not after. After the response has been sent, Ajax did its job, it's considered a successful request. Real Life Example ----------------- 1. Let's say you write a letter for a friend, and ask him do join you in a business. You are the *"user"* here. 2. You give your letter to the post man for delivery. The post man is the *"Ajax"* function here. 3. Your friend write a very big *"NO"* in his response (how rude), seals the letter and passes it back to the post man. Your friend is the *"server"* here. 4. The post man delivers the letter back to you. The post man did his job, no matter what the response was. So he is considered a *"successful"* one at his job. (don't forget his tip) 5. It's up to you to choose whether to scream, shout or cry because of your friend's strict *"NO"* (Error handling). It's not the post man's problem.
277,263
<p>I've been trying to achieve this for a bit now, and having no success. I have a custom post type "Contributor" where I've disabled the default title field, and I'm trying to figure out how to set a custom title based on four values from Advanced Custom Fields:</p> <ul> <li>a "Corporate?" checkbox;</li> <li>a Corporate Name text field (if Corporate is checked);</li> <li>a combination of Given Names and Surnames text fields (if Corporate is unchecked).</li> </ul> <p>I'm using this function to put together the full name for the Admin columns, for example:</p> <pre><code>function biwp_contributor_name($post_id) { $corporate = get_field('biwp_corporate', $post_id ); //get Corporate checkbox value if ($corporate) { //if Corporate is checked, use biwp_cname (Corportate Name) $name = get_field('biwp_cname', $post_id ); } else { //if Corporate is unchecked, use biwp_gnames (Given Names) and biwp_snames (Surnames) $gnames = get_field('biwp_gnames', $post_id ); $snames = get_field('biwp_snames', $post_id ); $name = $gnames .' '. $snames; } return $name; } </code></pre> <p>And that works great for display purposes. But the problem is that a lot of things in WP rely on the default title, so it would be much better to use that function to actually create the post title (and slug) instead.</p> <p>I've seen a few other threads on this topic, tried a few different solutions, but to no avail. This one is derived from posts in <a href="https://support.advancedcustomfields.com/forums/topic/replacing-custom-post-type-post-title-with-an-acf/" rel="nofollow noreferrer">this ACF forum thread</a>:</p> <pre><code>add_filter('acf/update_value', 'biwp_fix_contributor_title', 10, 3); function biwp_fix_contributor_title( $value, $post_id, $field ) { if (get_post_type($post_id) == 'contributor') { $name = biwp_contributor_name($post_id); $new_title = $name; $new_slug = sanitize_title( $new_title ); // update post $biwp_contributor = array( 'ID' =&gt; $post_id, 'post_title' =&gt; $new_title, 'post_name' =&gt; $new_slug, ); if ( ! wp_is_post_revision( $post_id ) ){ // unhook this function so it doesn't loop infinitely remove_action('save_post', 'biwp_fix_contributor_title'); // update the post, which calls save_post again wp_update_post( $biwp_contributor ); // re-hook this function add_action('save_post', 'biwp_fix_contributor_title'); } } return $value; } </code></pre> <p>And this one is from <a href="https://wordpress.stackexchange.com/questions/73511/using-save-post-to-replace-the-posts-title">this SE thread</a>:</p> <pre><code>add_action('save_post', 'biwp_fix_contributor_title', 12); function biwp_fix_contributor_title ($post_id) { if ( $post_id == null || empty($_POST) ) return; if ( !isset( $_POST['post_type'] ) || $_POST['post_type']!='contributor' ) return; if ( wp_is_post_revision( $post_id ) ) $post_id = wp_is_post_revision( $post_id ); global $post; if ( empty( $post ) ) $post = get_post($post_id); if ($_POST['biwp_corporate']!='') { global $wpdb; $name = biwp_contributor_name($post_id); $where = array( 'ID' =&gt; $post_id ); $wpdb-&gt;update( $wpdb-&gt;posts, array( 'post_title' =&gt; $name ), $where ); } } </code></pre> <p>But neither seems to actually do anything—not even a negative, undesired effect—which really makes me wonder.</p> <p>Thanks in advance for any help.</p>
[ { "answer_id": 277297, "author": "Dylan", "author_id": 41351, "author_profile": "https://wordpress.stackexchange.com/users/41351", "pm_score": 1, "selected": false, "text": "<p>The <code>acf/update_value</code> filter won't work as it's meant for modifying the acf value and not the post it's associated with. Try using the <a href=\"https://www.advancedcustomfields.com/resources/acf-save_post/\" rel=\"nofollow noreferrer\">acf/save_post</a> action instead. Here's a simplified example of how I'd normally set the post title from first and last name fields in acf.</p>\n\n<pre><code>add_action( 'acf/save_post', 'biwp_set_title_from_first_last_name', 20 );\n\nfunction biwp_set_title_from_first_last_name( $post_id ) {\n $post_type = get_post_type( $post_id );\n\n if ( 'contributor' == $post_type ) {\n $first_name = get_field( 'biwp_first_name', $post_id );\n $last_name = get_field( 'biwp_last_name', $post_id );\n\n $title = $first_name . ' ' . $last_name; \n\n $data = array(\n 'ID' =&gt; $post_id,\n 'post_title' =&gt; $title,\n 'post_name' =&gt; sanitize_title( $title ),\n );\n\n wp_update_post( $data );\n }\n}\n</code></pre>\n\n<p>Note the priority of 20 used in the action. A priority of less than 10 will hook into the <code>acf/save_post</code> action before ACF has saved the $_POST data. While a priority greater than 10 will hook into the <code>acf/save_post</code> action after ACF has saved the $_POST data. I'm using 20 so I can access the acf data that's been saved.</p>\n\n<p>Looking at the docs, Version 5.6.0 of acf has just added a parameter called $values which is an array containing the field values. You could use this to get the acf values directly instead of using <code>get_field</code>.</p>\n" }, { "answer_id": 391345, "author": "Tiffany Tyree", "author_id": 208513, "author_profile": "https://wordpress.stackexchange.com/users/208513", "pm_score": 0, "selected": false, "text": "<p>I went off of Dylan's answer and modified the pieces that you said were not working for you. This checks to make sure that the post has value for the acf field you are using to populate values rather than checking the post type. This solution worked for me and I hope it does for you as well.</p>\n<pre><code>add_action( 'acf/save_post', 'set_title', 20 );\n\nfunction set_title( $post_id ) {\n\n if (get_post_meta( $post_id, 'contributor', true )) {\n\n $title = get_post_meta( $post_id, 'contributor', true );\n\n $data = array(\n 'ID' =&gt; $post_id,\n 'post_title' =&gt; $title,\n 'post_name' =&gt; sanitize_title( $title ),\n );\n\n wp_update_post( $data );\n }\n}\n</code></pre>\n" } ]
2017/08/17
[ "https://wordpress.stackexchange.com/questions/277263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57588/" ]
I've been trying to achieve this for a bit now, and having no success. I have a custom post type "Contributor" where I've disabled the default title field, and I'm trying to figure out how to set a custom title based on four values from Advanced Custom Fields: * a "Corporate?" checkbox; * a Corporate Name text field (if Corporate is checked); * a combination of Given Names and Surnames text fields (if Corporate is unchecked). I'm using this function to put together the full name for the Admin columns, for example: ``` function biwp_contributor_name($post_id) { $corporate = get_field('biwp_corporate', $post_id ); //get Corporate checkbox value if ($corporate) { //if Corporate is checked, use biwp_cname (Corportate Name) $name = get_field('biwp_cname', $post_id ); } else { //if Corporate is unchecked, use biwp_gnames (Given Names) and biwp_snames (Surnames) $gnames = get_field('biwp_gnames', $post_id ); $snames = get_field('biwp_snames', $post_id ); $name = $gnames .' '. $snames; } return $name; } ``` And that works great for display purposes. But the problem is that a lot of things in WP rely on the default title, so it would be much better to use that function to actually create the post title (and slug) instead. I've seen a few other threads on this topic, tried a few different solutions, but to no avail. This one is derived from posts in [this ACF forum thread](https://support.advancedcustomfields.com/forums/topic/replacing-custom-post-type-post-title-with-an-acf/): ``` add_filter('acf/update_value', 'biwp_fix_contributor_title', 10, 3); function biwp_fix_contributor_title( $value, $post_id, $field ) { if (get_post_type($post_id) == 'contributor') { $name = biwp_contributor_name($post_id); $new_title = $name; $new_slug = sanitize_title( $new_title ); // update post $biwp_contributor = array( 'ID' => $post_id, 'post_title' => $new_title, 'post_name' => $new_slug, ); if ( ! wp_is_post_revision( $post_id ) ){ // unhook this function so it doesn't loop infinitely remove_action('save_post', 'biwp_fix_contributor_title'); // update the post, which calls save_post again wp_update_post( $biwp_contributor ); // re-hook this function add_action('save_post', 'biwp_fix_contributor_title'); } } return $value; } ``` And this one is from [this SE thread](https://wordpress.stackexchange.com/questions/73511/using-save-post-to-replace-the-posts-title): ``` add_action('save_post', 'biwp_fix_contributor_title', 12); function biwp_fix_contributor_title ($post_id) { if ( $post_id == null || empty($_POST) ) return; if ( !isset( $_POST['post_type'] ) || $_POST['post_type']!='contributor' ) return; if ( wp_is_post_revision( $post_id ) ) $post_id = wp_is_post_revision( $post_id ); global $post; if ( empty( $post ) ) $post = get_post($post_id); if ($_POST['biwp_corporate']!='') { global $wpdb; $name = biwp_contributor_name($post_id); $where = array( 'ID' => $post_id ); $wpdb->update( $wpdb->posts, array( 'post_title' => $name ), $where ); } } ``` But neither seems to actually do anything—not even a negative, undesired effect—which really makes me wonder. Thanks in advance for any help.
The `acf/update_value` filter won't work as it's meant for modifying the acf value and not the post it's associated with. Try using the [acf/save\_post](https://www.advancedcustomfields.com/resources/acf-save_post/) action instead. Here's a simplified example of how I'd normally set the post title from first and last name fields in acf. ``` add_action( 'acf/save_post', 'biwp_set_title_from_first_last_name', 20 ); function biwp_set_title_from_first_last_name( $post_id ) { $post_type = get_post_type( $post_id ); if ( 'contributor' == $post_type ) { $first_name = get_field( 'biwp_first_name', $post_id ); $last_name = get_field( 'biwp_last_name', $post_id ); $title = $first_name . ' ' . $last_name; $data = array( 'ID' => $post_id, 'post_title' => $title, 'post_name' => sanitize_title( $title ), ); wp_update_post( $data ); } } ``` Note the priority of 20 used in the action. A priority of less than 10 will hook into the `acf/save_post` action before ACF has saved the $\_POST data. While a priority greater than 10 will hook into the `acf/save_post` action after ACF has saved the $\_POST data. I'm using 20 so I can access the acf data that's been saved. Looking at the docs, Version 5.6.0 of acf has just added a parameter called $values which is an array containing the field values. You could use this to get the acf values directly instead of using `get_field`.
277,266
<p>I know i'll get bombarded for this question but the truth is I researched and found nothing.</p> <p>I'm not a WP expert or anything, i just found my ways to design WP themes. But there is something i never got straight. </p> <p><strong><em>WHY IN HECK SHORT-CODES DON'T WORK FOR ME.</em></strong></p> <p>When i mean shortcodes i mean the ones provided by a plugin, not created by myself what it makes it probably dumber. </p> <p><strong>Example:</strong> </p> <p>I write in a page or a post:</p> <pre><code>[audio src="http://my_url.com/my_track.mp3"] </code></pre> <p>I see the audio controls in the WP editor, but in the browser i see the text, not the audio. </p> <p><strong>2nd example:</strong> </p> <p>I just tried to use a WPForms shortcode in order to display a contact form.... I see the text, not what the shortcode should be doing.</p> <p>Up to this point my solution if I need to run a shortcode is creating a page/post template and do:</p> <pre><code>&lt;?php echo do_shortcode('[My_shortcode]'); ?&gt; </code></pre> <p>Thanks a lot and sorry for the dumbest question. </p>
[ { "answer_id": 277271, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Take a look at the syntax of do_shortcode (here: <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/do_shortcode/</a> ), and the examples shown on that page.</p>\n\n<p>Also, this page <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a> on how to use shortcodes in your plugin.</p>\n" }, { "answer_id": 277272, "author": "Rei", "author_id": 109614, "author_profile": "https://wordpress.stackexchange.com/users/109614", "pm_score": 0, "selected": false, "text": "<p><code>[audio src=\"http://my_url.com/my_track.mp3\"]</code> add shortcode into the content of a post or page\n<code>&lt;?php echo do_shortcode('[My_shortcode]'); ?&gt;</code> put code in file <code>.php</code> eg:<code>content.php</code>,<code>single-post.php</code> where you want to display\nYou should learn how to <i>make shortcode</i> and <i>using shortcode</i> in wordpress page clearly</p>\n" }, { "answer_id": 277278, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 1, "selected": true, "text": "<p>It looks like theme issue. Switch to default WordPress theme and check it. I have tested it on WordPress Twenty Seventeen theme.</p>\n\n<p>For testing:</p>\n\n<p>1) Add below code in theme <code>functions.php</code></p>\n\n<pre><code>// Sample shortcode [testme]\nfunction testme_cb( $atts ) {\n return 'Working? Maybe.';\n}\nadd_shortcode( 'testme', 'testme_cb' );\n\n// Enable shortcodes in text widgets\nadd_filter('widget_text','do_shortcode');\n</code></pre>\n\n<hr>\n\n<p>2) Goto <code>Appearance -&gt; Widgets</code> and add shortcode <code>[testme]</code> in Text Widget.</p>\n\n<p><a href=\"https://i.stack.imgur.com/A2Wdz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A2Wdz.png\" alt=\"Shortcode\"></a></p>\n\n<hr>\n\n<p>3) Check it on frontend.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tlOrn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tlOrn.png\" alt=\"Front End\"></a></p>\n" } ]
2017/08/18
[ "https://wordpress.stackexchange.com/questions/277266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124731/" ]
I know i'll get bombarded for this question but the truth is I researched and found nothing. I'm not a WP expert or anything, i just found my ways to design WP themes. But there is something i never got straight. ***WHY IN HECK SHORT-CODES DON'T WORK FOR ME.*** When i mean shortcodes i mean the ones provided by a plugin, not created by myself what it makes it probably dumber. **Example:** I write in a page or a post: ``` [audio src="http://my_url.com/my_track.mp3"] ``` I see the audio controls in the WP editor, but in the browser i see the text, not the audio. **2nd example:** I just tried to use a WPForms shortcode in order to display a contact form.... I see the text, not what the shortcode should be doing. Up to this point my solution if I need to run a shortcode is creating a page/post template and do: ``` <?php echo do_shortcode('[My_shortcode]'); ?> ``` Thanks a lot and sorry for the dumbest question.
It looks like theme issue. Switch to default WordPress theme and check it. I have tested it on WordPress Twenty Seventeen theme. For testing: 1) Add below code in theme `functions.php` ``` // Sample shortcode [testme] function testme_cb( $atts ) { return 'Working? Maybe.'; } add_shortcode( 'testme', 'testme_cb' ); // Enable shortcodes in text widgets add_filter('widget_text','do_shortcode'); ``` --- 2) Goto `Appearance -> Widgets` and add shortcode `[testme]` in Text Widget. [![Shortcode](https://i.stack.imgur.com/A2Wdz.png)](https://i.stack.imgur.com/A2Wdz.png) --- 3) Check it on frontend. [![Front End](https://i.stack.imgur.com/tlOrn.png)](https://i.stack.imgur.com/tlOrn.png)
277,343
<p>I have a fresh WP install and for purposes of keeping things simple I currently just have a simple action as follows in my <code>functions.php</code>:</p> <pre><code>function getFruits() { return json_encode( ['fruits' =&gt; ['apples', 'pears']]); } function my_enqueue() { wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') ); wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'my_enqueue' ); </code></pre> <p>Now, my objective is to use JQuery / JavaScript to make an AJAX call to my wordpress endpoint and get the fruits json object back and print it console simply when rendering the landing page.</p> <p>This is what I tried:</p> <p><code>twentyseventeen\js\my-ajax-script.js</code>:</p> <pre><code>$(document).ready(function() { $.ajax( { type: "get", data : { action: 'getFruits' }, dataType: "json", url: my_ajax_object.ajax_url, success: function(msg){ console.log(msg); //output fruits to console } }); }); </code></pre> <p>Currently, I am getting a JQuery is not defined error, although it seems to be enqueued. Second, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.</p> <p>Thank you </p>
[ { "answer_id": 277346, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>WordPress AJAX uses actions to connect your jQuery <code>action</code> with a traditional WordPress action. Take a look at the <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">example WordPress provides in their docs</a>. There's 2 hooks:</p>\n\n<pre><code>add_action( \"wp_ajax_{$jquery_action_string}\", \"callback_function_name\" );\n</code></pre>\n\n<p>The above will only work for authenticated ( logged in ) users. For non-logged-in users we use <code>nopriv</code>:</p>\n\n<pre><code>add_action( \"wp_ajax_nopriv_{$jquery_action_string}\", \"callback_function_name\" );\n</code></pre>\n\n<p>So in our case we would use both:</p>\n\n<pre><code>function return_fruits() {\n echo json_encode( ['fruits' =&gt; ['apples', 'pears']]);\n exit();\n}\nadd_action( 'wp_ajax_getFruits', 'return_fruits' );\nadd_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' );\n</code></pre>\n\n<p>Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to <strong>echo</strong> this data instead of return it.</p>\n" }, { "answer_id": 277355, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 0, "selected": false, "text": "<p>You have to use ajax action hook to perform your jquery action.</p>\n\n<p>for login user: </p>\n\n<pre><code>add_action('wp_ajax_getFruits', 'getFruits);\n</code></pre>\n\n<p>for not login user:</p>\n\n<pre><code>add_action('wp_ajax_nopriv_getFruits', 'getFruits');\n\nfunction get_fruits(){\n$response = array('Fruits'=&gt; ['banana', 'apple']);\n//use this function and make a response then send the response\nwp_send_json_success(array('response'=&gt;$response));\n// by using wp_send_json_success() you don't need to exit and parse response\n}\n</code></pre>\n" } ]
2017/08/18
[ "https://wordpress.stackexchange.com/questions/277343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75012/" ]
I have a fresh WP install and for purposes of keeping things simple I currently just have a simple action as follows in my `functions.php`: ``` function getFruits() { return json_encode( ['fruits' => ['apples', 'pears']]); } function my_enqueue() { wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') ); wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'my_enqueue' ); ``` Now, my objective is to use JQuery / JavaScript to make an AJAX call to my wordpress endpoint and get the fruits json object back and print it console simply when rendering the landing page. This is what I tried: `twentyseventeen\js\my-ajax-script.js`: ``` $(document).ready(function() { $.ajax( { type: "get", data : { action: 'getFruits' }, dataType: "json", url: my_ajax_object.ajax_url, success: function(msg){ console.log(msg); //output fruits to console } }); }); ``` Currently, I am getting a JQuery is not defined error, although it seems to be enqueued. Second, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this. Thank you
WordPress AJAX uses actions to connect your jQuery `action` with a traditional WordPress action. Take a look at the [example WordPress provides in their docs](https://codex.wordpress.org/AJAX_in_Plugins). There's 2 hooks: ``` add_action( "wp_ajax_{$jquery_action_string}", "callback_function_name" ); ``` The above will only work for authenticated ( logged in ) users. For non-logged-in users we use `nopriv`: ``` add_action( "wp_ajax_nopriv_{$jquery_action_string}", "callback_function_name" ); ``` So in our case we would use both: ``` function return_fruits() { echo json_encode( ['fruits' => ['apples', 'pears']]); exit(); } add_action( 'wp_ajax_getFruits', 'return_fruits' ); add_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' ); ``` Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to **echo** this data instead of return it.
277,349
<p>In the Velux theme <code>functions.php</code> there is this:</p> <pre><code>if ( is_front_page() &amp;&amp; is_active_sidebar( 'hero' ) ) </code></pre> <p>Which apparently means the Hero widget only functions on the home page. I used that widget to add custom HTML that needs to be in the header on all pages. </p> <p>I tried the following mod to <code>functions.php</code> and cleared the cache, but cannot see the custom HTML on other site pages. Site is not yet public.</p> <pre><code>if ( is_page() &amp;&amp; is_active_sidebar( 'hero' ) ) </code></pre>
[ { "answer_id": 277346, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>WordPress AJAX uses actions to connect your jQuery <code>action</code> with a traditional WordPress action. Take a look at the <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">example WordPress provides in their docs</a>. There's 2 hooks:</p>\n\n<pre><code>add_action( \"wp_ajax_{$jquery_action_string}\", \"callback_function_name\" );\n</code></pre>\n\n<p>The above will only work for authenticated ( logged in ) users. For non-logged-in users we use <code>nopriv</code>:</p>\n\n<pre><code>add_action( \"wp_ajax_nopriv_{$jquery_action_string}\", \"callback_function_name\" );\n</code></pre>\n\n<p>So in our case we would use both:</p>\n\n<pre><code>function return_fruits() {\n echo json_encode( ['fruits' =&gt; ['apples', 'pears']]);\n exit();\n}\nadd_action( 'wp_ajax_getFruits', 'return_fruits' );\nadd_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' );\n</code></pre>\n\n<p>Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to <strong>echo</strong> this data instead of return it.</p>\n" }, { "answer_id": 277355, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 0, "selected": false, "text": "<p>You have to use ajax action hook to perform your jquery action.</p>\n\n<p>for login user: </p>\n\n<pre><code>add_action('wp_ajax_getFruits', 'getFruits);\n</code></pre>\n\n<p>for not login user:</p>\n\n<pre><code>add_action('wp_ajax_nopriv_getFruits', 'getFruits');\n\nfunction get_fruits(){\n$response = array('Fruits'=&gt; ['banana', 'apple']);\n//use this function and make a response then send the response\nwp_send_json_success(array('response'=&gt;$response));\n// by using wp_send_json_success() you don't need to exit and parse response\n}\n</code></pre>\n" } ]
2017/08/18
[ "https://wordpress.stackexchange.com/questions/277349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121627/" ]
In the Velux theme `functions.php` there is this: ``` if ( is_front_page() && is_active_sidebar( 'hero' ) ) ``` Which apparently means the Hero widget only functions on the home page. I used that widget to add custom HTML that needs to be in the header on all pages. I tried the following mod to `functions.php` and cleared the cache, but cannot see the custom HTML on other site pages. Site is not yet public. ``` if ( is_page() && is_active_sidebar( 'hero' ) ) ```
WordPress AJAX uses actions to connect your jQuery `action` with a traditional WordPress action. Take a look at the [example WordPress provides in their docs](https://codex.wordpress.org/AJAX_in_Plugins). There's 2 hooks: ``` add_action( "wp_ajax_{$jquery_action_string}", "callback_function_name" ); ``` The above will only work for authenticated ( logged in ) users. For non-logged-in users we use `nopriv`: ``` add_action( "wp_ajax_nopriv_{$jquery_action_string}", "callback_function_name" ); ``` So in our case we would use both: ``` function return_fruits() { echo json_encode( ['fruits' => ['apples', 'pears']]); exit(); } add_action( 'wp_ajax_getFruits', 'return_fruits' ); add_action( 'wp_ajax_nopriv_getFruits', 'return_fruits' ); ``` Note, I changed your call back function name to identify that the ajax action and the callback name do not need to be identical. Also note, you would want to **echo** this data instead of return it.
277,418
<p>I'm faced with a situation where I need to fetch meta_value of a specific meta_key from ALL the posts available in WordPress database. Obviously, this results into large number of database queries. Here's how it looks : </p> <pre><code>foreach ( $quiz_takers as $competitor ) { $quizzes_user_has_taken = get_post_meta( $competitor, 'quiz_results', true ); // More stuff happens here. } </code></pre> <p>I was wondering if there's a way to reduce the number of queries happening via the <code>get_post_meta()</code> above. </p> <p>The only solution I could think of was to directly query the <code>wp_postmeta</code> table directly; but not sure what's the right way to do it. </p> <p>Would really appreciate if you could point me in the right direction. I thank you for your time in advance.</p>
[ { "answer_id": 277419, "author": "zedejose", "author_id": 34514, "author_profile": "https://wordpress.stackexchange.com/users/34514", "pm_score": 0, "selected": false, "text": "<p>Not tested, but a meta-only <code>WP_Query</code> should do the trick, no?</p>\n\n<p>As in:</p>\n\n<pre><code>$args = array(\n 'meta_key'=&gt;'quiz_results',\n);\n\n$your_query_name = new WP_Query( $args );\n</code></pre>\n\n<p>And then use the standard WP loop to retrieve the posts.</p>\n" }, { "answer_id": 277426, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>Querying wp_postmeta would be the way to go:</p>\n\n<pre><code>global $wpdb;\n$results = $wpdb-&gt;get_col(\"SELECT meta_value FROM $wpdb-&gt;postmeta WHERE meta_key = 'quiz_results'\");\n</code></pre>\n\n<p>That will get you an array of values for quiz_results across all posts.</p>\n" } ]
2017/08/19
[ "https://wordpress.stackexchange.com/questions/277418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21100/" ]
I'm faced with a situation where I need to fetch meta\_value of a specific meta\_key from ALL the posts available in WordPress database. Obviously, this results into large number of database queries. Here's how it looks : ``` foreach ( $quiz_takers as $competitor ) { $quizzes_user_has_taken = get_post_meta( $competitor, 'quiz_results', true ); // More stuff happens here. } ``` I was wondering if there's a way to reduce the number of queries happening via the `get_post_meta()` above. The only solution I could think of was to directly query the `wp_postmeta` table directly; but not sure what's the right way to do it. Would really appreciate if you could point me in the right direction. I thank you for your time in advance.
Querying wp\_postmeta would be the way to go: ``` global $wpdb; $results = $wpdb->get_col("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'quiz_results'"); ``` That will get you an array of values for quiz\_results across all posts.
277,465
<p>Looking for a code which could potentially help me get the list of gallery images present in product in woocommerce.</p> <p>Need them so i can use them in a custom single page design for woocommerce product page.</p>
[ { "answer_id": 277467, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>The <code>get_gallery_image_ids()</code> method on the product will return an array of image IDs.</p>\n\n<pre><code>global $product;\n$gallery_images = $product-&gt;get_gallery_image_ids();\n</code></pre>\n\n<p>Then you can use functions like <code>wp_get_attachment_image()</code> for each ID to get HTML/URLs etc.</p>\n" }, { "answer_id": 311359, "author": "user91030", "author_id": 148676, "author_profile": "https://wordpress.stackexchange.com/users/148676", "pm_score": 3, "selected": false, "text": "<p>This is the complete function if you want all the images from the gallery, including the main image:</p>\n\n<pre><code> public function getAllProducts( $request ){\n $products = new WP_Query([\n 'post_type' =&gt; 'post'//,\n //'show_product_on_only_premium' =&gt; 'yes',\n ]);\n\n $args = array(\n 'status' =&gt; 'publish',\n );\n $products = wc_get_products( $args );\n $tempArr = [];\n foreach($products as $product){\n $product_obj = json_decode($product-&gt; __toString());\n $product_obj-&gt;img_src = wp_get_attachment_image_src($product_obj-&gt;image_id)[0];\n $images_ids = $product-&gt; get_gallery_image_ids();\n\n $images_arr = [];\n for($i = 0, $j = count($images_ids); $i &lt; $j;$i++ ){\n $image_query = wp_get_attachment_image_src($images_ids[$i]);\n $img = new StdClass;\n $img-&gt;src = $image_query[0];\n array_push($images_arr, $img);\n }\n $product_obj-&gt;gallery = $images_arr;\n array_push($tempArr, $product_obj);\n }\n return $tempArr;\n} \n</code></pre>\n\n<p>And if you want the variations: from: <a href=\"https://gist.github.com/Niloys7/17b88d36c1c38844a6cf2127c15dee63\" rel=\"noreferrer\">https://gist.github.com/Niloys7/17b88d36c1c38844a6cf2127c15dee63</a></p>\n\n<pre><code>&lt;?php\nglobal $product;\n$attachment_ids = $product-&gt;get_gallery_attachment_ids();\n\nforeach( $attachment_ids as $attachment_id ) \n{\n //Get URL of Gallery Images - default wordpress image sizes\n echo $Original_image_url = wp_get_attachment_url( $attachment_id );\n echo $full_url = wp_get_attachment_image_src( $attachment_id, 'full' )[0];\n echo $medium_url = wp_get_attachment_image_src( $attachment_id, 'medium' )[0];\n echo $thumbnail_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail' )[0];\n\n //Get URL of Gallery Images - WooCommerce specific image sizes\n echo $shop_thumbnail_image_url = wp_get_attachment_image_src( $attachment_id, 'shop_thumbnail' )[0];\n echo $shop_catalog_image_url = wp_get_attachment_image_src( $attachment_id, 'shop_catalog' )[0];\n echo $shop_single_image_url = wp_get_attachment_image_src( $attachment_id, 'shop_single' )[0];\n\n //echo Image instead of URL\n echo wp_get_attachment_image($attachment_id, 'full');\n echo wp_get_attachment_image($attachment_id, 'medium');\n echo wp_get_attachment_image($attachment_id, 'thumbnail');\n echo wp_get_attachment_image($attachment_id, 'shop_thumbnail');\n echo wp_get_attachment_image($attachment_id, 'shop_catalog');\n echo wp_get_attachment_image($attachment_id, 'shop_single');\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 353706, "author": "Md.Mehedi hasan", "author_id": 179168, "author_profile": "https://wordpress.stackexchange.com/users/179168", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;?php\n$product_id = '14';\n$product = new WC_product($product_id);\n$attachment_ids = $product-&gt;get_gallery_image_ids();\n\nforeach( $attachment_ids as $attachment_id ) \n {\n // Display the image URL\n echo $Original_image_url = wp_get_attachment_url( $attachment_id );\n\n // Display Image instead of URL\n echo wp_get_attachment_image($attachment_id, 'full');\n\n }?&gt;\n</code></pre>\n" } ]
2017/08/20
[ "https://wordpress.stackexchange.com/questions/277465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125791/" ]
Looking for a code which could potentially help me get the list of gallery images present in product in woocommerce. Need them so i can use them in a custom single page design for woocommerce product page.
``` <?php $product_id = '14'; $product = new WC_product($product_id); $attachment_ids = $product->get_gallery_image_ids(); foreach( $attachment_ids as $attachment_id ) { // Display the image URL echo $Original_image_url = wp_get_attachment_url( $attachment_id ); // Display Image instead of URL echo wp_get_attachment_image($attachment_id, 'full'); }?> ```
277,474
<p>I am busy moving all sites to HTTPS (using ZeroSSL/Letsencrypt) on a Hetzner.de managed hosting server. I have this working for a single site but my <strong>multisite installation</strong> is giving me issues.</p> <p>My main site (top-node.com) works without an issue (frontend and backend), however, I cannot log into the <strong>network admin</strong> options to install new plugins, etc. (kind of a deal breaker right there).</p> <p>When I'm logged into the main site's admin backend, the link to the network admin should be <a href="https://top-node.com/wp-admin/network/" rel="nofollow noreferrer">https://top-node.com/wp-admin/network/</a>. However, this is rewritten to <a href="https://http//top-node.com/wp-admin/network/" rel="nofollow noreferrer">https://http//top-node.com/wp-admin/network/</a> - there seems to be some (.htaccess) magic happening here.</p> <p>In my quest to solve this, I have resorted to downloading the complete site and database and searching for any references of <em>http//</em> and other variations, but this is not stored anywhere.</p> <p>I have also tried various .htaccess adaptations but this did not solve the problem either. Here is my current version:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ wp/$1 [L] RewriteRule . index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I'm at my wits end, so I'll appreciate any suggestions.</p>
[ { "answer_id": 313535, "author": "Ryan M", "author_id": 71096, "author_profile": "https://wordpress.stackexchange.com/users/71096", "pm_score": 1, "selected": false, "text": "<p>For me, it was removing <code>http://</code> from DOMAIN_CURRENT_SITE in my wp-config.php.</p>\n\n<p>before\n<code>\ndefine( 'DOMAIN_CURRENT_SITE', 'http://example.com' );\n</code></p>\n\n<p>after\n<code>\ndefine( 'DOMAIN_CURRENT_SITE', 'example.com' );\n</code></p>\n" }, { "answer_id": 313540, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>For HTTPS rewrite, use this:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} (?!^www\\.)^(.+)$ [OR]\nRewriteCond %{HTTPS} off\nRewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>For WordPress rewrite, use the appropriate one shown here: <a href=\"https://codex.wordpress.org/htaccess\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/htaccess</a> . Go with the Basic one first, adjust if a subdirectory.</p>\n\n<p>For the URLs used in the wp-options table, use the full HTTPS URL for your site (in two places). Entry in wp-config.php is not needed.</p>\n" } ]
2017/08/20
[ "https://wordpress.stackexchange.com/questions/277474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117438/" ]
I am busy moving all sites to HTTPS (using ZeroSSL/Letsencrypt) on a Hetzner.de managed hosting server. I have this working for a single site but my **multisite installation** is giving me issues. My main site (top-node.com) works without an issue (frontend and backend), however, I cannot log into the **network admin** options to install new plugins, etc. (kind of a deal breaker right there). When I'm logged into the main site's admin backend, the link to the network admin should be <https://top-node.com/wp-admin/network/>. However, this is rewritten to <https://http//top-node.com/wp-admin/network/> - there seems to be some (.htaccess) magic happening here. In my quest to solve this, I have resorted to downloading the complete site and database and searching for any references of *http//* and other variations, but this is not stored anywhere. I have also tried various .htaccess adaptations but this did not solve the problem either. Here is my current version: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ wp/$1 [L] RewriteRule . index.php [L] </IfModule> # END WordPress ``` I'm at my wits end, so I'll appreciate any suggestions.
For me, it was removing `http://` from DOMAIN\_CURRENT\_SITE in my wp-config.php. before `define( 'DOMAIN_CURRENT_SITE', 'http://example.com' );` after `define( 'DOMAIN_CURRENT_SITE', 'example.com' );`
277,515
<p>By default, when you click on the author in a post, WP directs you to:</p> <blockquote> <p>example.com/author/sample-user/</p> </blockquote> <p>However, for BuddyPress users, it makes much more sense that it directs the user to the author's BuddyPress profile page: </p> <blockquote> <p>example.com/members/sample-user/</p> </blockquote> <p>Does anyone know how to do this? Thanks!</p> <p>UPDATE I'm trying with the following codes</p> <pre><code>add_filter( 'author_link', 'change_author_link', 10, 1 ); function change_author_link($link) { $link = 'http://asiaforum.club/members/' . $author_ID; return $link; } </code></pre> <p>But I can't seem to get wordpress to retrieve the author's user ID. Any idea on how to do that (or if this method will work)?</p>
[ { "answer_id": 277534, "author": "Ashley Liu", "author_id": 126220, "author_profile": "https://wordpress.stackexchange.com/users/126220", "pm_score": 1, "selected": false, "text": "<p>The following codes worked. I added to my child theme's functions.php</p>\n\n<pre><code> add_filter( 'author_link', 'change_author_link', 10, 1 );\n\n function change_author_link($link) {\n $username=get_the_author_meta('user_nicename');\n\n\n $link = 'http://example.com/members/' . $username;\n return $link;\n }\n</code></pre>\n" }, { "answer_id": 277616, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>A more robust approach: </p>\n\n<pre><code>function change_author_link($link) {\n\n $user_id = get_the_author_meta('ID');\n\n return bp_core_get_user_domain( $user_id );\n}\nadd_filter( 'author_link', 'change_author_link', 10, 1 );\n</code></pre>\n" } ]
2017/08/20
[ "https://wordpress.stackexchange.com/questions/277515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126220/" ]
By default, when you click on the author in a post, WP directs you to: > > example.com/author/sample-user/ > > > However, for BuddyPress users, it makes much more sense that it directs the user to the author's BuddyPress profile page: > > example.com/members/sample-user/ > > > Does anyone know how to do this? Thanks! UPDATE I'm trying with the following codes ``` add_filter( 'author_link', 'change_author_link', 10, 1 ); function change_author_link($link) { $link = 'http://asiaforum.club/members/' . $author_ID; return $link; } ``` But I can't seem to get wordpress to retrieve the author's user ID. Any idea on how to do that (or if this method will work)?
The following codes worked. I added to my child theme's functions.php ``` add_filter( 'author_link', 'change_author_link', 10, 1 ); function change_author_link($link) { $username=get_the_author_meta('user_nicename'); $link = 'http://example.com/members/' . $username; return $link; } ```
277,525
<p>I just imported a bunch of posts to my WordPress site, from Tumblr, using the </p> <pre><code>Tools -&gt; Import </code></pre> <p>menu. All my content is pulled into WordPress. Yay!</p> <p>Next -- I want to drop all the posts from this Tumblr site into a new category. There doesn't appear to be a way to do this via the UI that isn't incredibly tedious (short of visually inspecting a title, selecting it in the Posts grid, doing an edit, etc). </p> <p>Is there some way I can mass select just the recently imported posts? Or some way I can programmatically do this is I know the post's database ID? (since all the imported posts are the most recent items in the database, I can get their IDs pretty easily). Is there a way I can, at import time, say "put all the posts you're going to import into this category"? Is there some solution I'm not thinking of</p>
[ { "answer_id": 277534, "author": "Ashley Liu", "author_id": 126220, "author_profile": "https://wordpress.stackexchange.com/users/126220", "pm_score": 1, "selected": false, "text": "<p>The following codes worked. I added to my child theme's functions.php</p>\n\n<pre><code> add_filter( 'author_link', 'change_author_link', 10, 1 );\n\n function change_author_link($link) {\n $username=get_the_author_meta('user_nicename');\n\n\n $link = 'http://example.com/members/' . $username;\n return $link;\n }\n</code></pre>\n" }, { "answer_id": 277616, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>A more robust approach: </p>\n\n<pre><code>function change_author_link($link) {\n\n $user_id = get_the_author_meta('ID');\n\n return bp_core_get_user_domain( $user_id );\n}\nadd_filter( 'author_link', 'change_author_link', 10, 1 );\n</code></pre>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277525", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33566/" ]
I just imported a bunch of posts to my WordPress site, from Tumblr, using the ``` Tools -> Import ``` menu. All my content is pulled into WordPress. Yay! Next -- I want to drop all the posts from this Tumblr site into a new category. There doesn't appear to be a way to do this via the UI that isn't incredibly tedious (short of visually inspecting a title, selecting it in the Posts grid, doing an edit, etc). Is there some way I can mass select just the recently imported posts? Or some way I can programmatically do this is I know the post's database ID? (since all the imported posts are the most recent items in the database, I can get their IDs pretty easily). Is there a way I can, at import time, say "put all the posts you're going to import into this category"? Is there some solution I'm not thinking of
The following codes worked. I added to my child theme's functions.php ``` add_filter( 'author_link', 'change_author_link', 10, 1 ); function change_author_link($link) { $username=get_the_author_meta('user_nicename'); $link = 'http://example.com/members/' . $username; return $link; } ```
277,539
<pre><code>&lt;?php if (!is_user_logged_in()) { ?&gt; &lt;p class="text-center"&gt; برای ارسال نظر باید &lt;a href="https://www. .com/login?redirect_to=&lt;?php echo the_permalink();?&gt;"&gt;&lt;i class="fa fa-fw fa-sign-in"&gt;&lt;/i&gt; وارد حساب کاربریتان شوید&lt;/a&gt; یا &lt;a href="/register"&gt;&lt;i class="fa fa-fw fa-user-plus"&gt;&lt;/i&gt; عضو سایت شوید&lt;/a&gt; &lt;/p&gt; &lt;?php } ?&gt; &lt;?php $comments = get_comments(array( 'post_id' =&gt; get_the_ID(), 'orderby' =&gt; 'comment_date', )); echo wp_list_comments("callback=wpsaz_comment&amp;end-callback=dubfa_div&amp;per_page=5",$comments); ?&gt; </code></pre> <p>what is wrong with this code?</p> <p>comments returns only when user is logged in.</p> <p>how can i fix it?</p>
[ { "answer_id": 277568, "author": "Shahzaib Khan", "author_id": 125791, "author_profile": "https://wordpress.stackexchange.com/users/125791", "pm_score": 0, "selected": false, "text": "<p>If it is for the post, then check whether in the post settings have you allowed the comments should be displayed?</p>\n\n<p>Also do check the settings at: /wp-admin/options-discussion.php</p>\n" }, { "answer_id": 277681, "author": "RadioTunes.in", "author_id": 125908, "author_profile": "https://wordpress.stackexchange.com/users/125908", "pm_score": -1, "selected": false, "text": "<p>Fixed!</p>\n\n<p>the problem was because of $comments, i removed that and fixed.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125908/" ]
``` <?php if (!is_user_logged_in()) { ?> <p class="text-center"> برای ارسال نظر باید <a href="https://www. .com/login?redirect_to=<?php echo the_permalink();?>"><i class="fa fa-fw fa-sign-in"></i> وارد حساب کاربریتان شوید</a> یا <a href="/register"><i class="fa fa-fw fa-user-plus"></i> عضو سایت شوید</a> </p> <?php } ?> <?php $comments = get_comments(array( 'post_id' => get_the_ID(), 'orderby' => 'comment_date', )); echo wp_list_comments("callback=wpsaz_comment&end-callback=dubfa_div&per_page=5",$comments); ?> ``` what is wrong with this code? comments returns only when user is logged in. how can i fix it?
If it is for the post, then check whether in the post settings have you allowed the comments should be displayed? Also do check the settings at: /wp-admin/options-discussion.php
277,546
<p>before happening this error i go to the general setting and on the place of HTTP i did HTTPS by mistake. but now i am unable to login into my <code>wp-admin</code> panel</p> <p>Whenever i type <code>www.mydomain.com/wp-admin/</code> the privacy error comes:</p> <blockquote> <p>Your connection is not private</p> <p>Attackers might be trying to steal your information from www.mydomain.com (for example, passwords, messages, or credit cards). Learn more NET::ERR_CERT_COMMON_NAME_INVALID</p> <p>Automatically send some system information and page content to Google to help detect dangerous apps and sites. Privacy policy</p> </blockquote> <p>How can i fix this problem?</p>
[ { "answer_id": 277548, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 1, "selected": false, "text": "<p>You can fix this by changes <code>site_url</code> and <code>home_url</code> in your database.</p>\n\n<p>If you have access to your database(phpmyadmin) go to <code>options</code> table and change <code>site_url</code> and <code>home_url</code> from HTTPS to HTTP.</p>\n\n<p>You can also change it through <code>wp-config</code> file. </p>\n\n<pre><code>define('WP_HOME','http://www.example.com');\ndefine('WP_SITEURL','http://www.example.com');\n</code></pre>\n\n<p>See: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a> for possible methods.\nHope this helps.</p>\n" }, { "answer_id": 277567, "author": "Shahzaib Khan", "author_id": 125791, "author_profile": "https://wordpress.stackexchange.com/users/125791", "pm_score": 1, "selected": false, "text": "<p>Best way to fix this problem real quick is via the database, within 10 seconds it be fixed.</p>\n\n<p>Open phpmyadmin via your cPanel and then run the following queries to update the site urls and home url:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"siteurl\"\n</code></pre>\n\n<p>and also run another query:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"home\"\n</code></pre>\n\n<p>Note: </p>\n\n<ul>\n<li><p>Replace <a href=\"http://www.example.com/\" rel=\"nofollow noreferrer\">http://www.example.com/</a> with your domain URLS</p></li>\n<li><p>Above queries will 100% function if you have your databsae extension as wp_ set.</p></li>\n</ul>\n" }, { "answer_id": 390348, "author": "Stanley", "author_id": 203842, "author_profile": "https://wordpress.stackexchange.com/users/203842", "pm_score": 0, "selected": false, "text": "<p>Access your website using HTTP protocol. You will not face this error.\n<a href=\"http://www.yourdomainname.com/wp-admin/\" rel=\"nofollow noreferrer\">http://www.yourdomainname.com/wp-admin/</a></p>\n<p>SSL is not installed on domain hence you are facing this issue.</p>\n<p>If you have added HTTPS instead of HTTP for WP_HOME and WP_SITEURL then please update it on web.config file. You will have to use HTTP.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277546", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126236/" ]
before happening this error i go to the general setting and on the place of HTTP i did HTTPS by mistake. but now i am unable to login into my `wp-admin` panel Whenever i type `www.mydomain.com/wp-admin/` the privacy error comes: > > Your connection is not private > > > Attackers might be trying to steal your information from > www.mydomain.com (for example, passwords, messages, or credit cards). > Learn more NET::ERR\_CERT\_COMMON\_NAME\_INVALID > > > Automatically send some system information and page content to > Google to help detect dangerous apps and sites. Privacy policy > > > How can i fix this problem?
You can fix this by changes `site_url` and `home_url` in your database. If you have access to your database(phpmyadmin) go to `options` table and change `site_url` and `home_url` from HTTPS to HTTP. You can also change it through `wp-config` file. ``` define('WP_HOME','http://www.example.com'); define('WP_SITEURL','http://www.example.com'); ``` See: <https://codex.wordpress.org/Changing_The_Site_URL> for possible methods. Hope this helps.