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
213,986
<p>I know this is a big ask for you guys, but i can't seem to figure this out.</p> <p>I found this page : <a href="http://www.bobz.co/ajax-filter-posts-tag/#comment-28112" rel="nofollow">http://www.bobz.co/ajax-filter-posts-tag/#comment-28112</a></p> <p>it shows how to make a dynamic filter for post tags. </p> <p>I wanted to change it to post categories, but i can't seem to get it working.</p> <p>I placed this code in my functions.php</p> <pre><code>function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' =&gt; wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request 'afp_ajax_url' =&gt; admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'category_name' =&gt; $taxonomy, 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 10, ); // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['category_name'] ); } $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;h2&gt;No posts found&lt;/h2&gt; &lt;?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); </code></pre> <p>and then in my actual page template i put this code:</p> <pre><code>//in my template file &lt;?php $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 10, ); $query = new WP_Query( $args ); function tags_filter() { $tax = 'category'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count &gt; 0 ): ?&gt; &lt;div class="post-tags"&gt; &lt;?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '&lt;a href="' . $term_link . '" class="tax-filter" title="' . $term-&gt;slug . '"&gt;' . $term-&gt;name . '&lt;/a&gt; '; } ?&gt; &lt;/div&gt; &lt;?php endif; } </code></pre> <p>when i load my page template the site loads my content and shows category filter buttons, but when i click any of the buttons, returns "No Posts found".</p> <p>This leads me to believe i did something wrong with my functions file, but i can't figure it out.</p> <p>Can anyone see something i've done wrong here?</p>
[ { "answer_id": 237485, "author": "Daniel Griffiths", "author_id": 101849, "author_profile": "https://wordpress.stackexchange.com/users/101849", "pm_score": 3, "selected": true, "text": "<p>Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. </p>\n\n<p>I got this working so it displays all categories and the posts related. Put that in <code>functions.php</code></p>\n\n<pre><code>function ajax_filter_posts_scripts() {\n // Enqueue script\n wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);\n wp_enqueue_script('afp_script');\n\n wp_localize_script( 'afp_script', 'afp_vars', array(\n 'afp_nonce' =&gt; wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request\n 'afp_ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n )\n );\n}\nadd_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);\n\n// Script for getting posts\nfunction ajax_filter_get_posts( $taxonomy ) {\n\n // Verify nonce\n if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )\n die('Permission denied');\n\n $taxonomy = $_POST['taxonomy'];\n\n // WP Query\n $args = array(\n 'category_name' =&gt; $taxonomy,\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n echo $taxonomy;\n // If taxonomy is not set, remove key from array and get all posts\n if( !$taxonomy ) {\n unset( $args['tag'] );\n }\n\n $query = new WP_Query( $args );\n\n if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php else: ?&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;?php endif;\n\n die();\n}\n\nadd_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');\nadd_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');\n</code></pre>\n\n<p>Then, add this in your page template:</p>\n\n<pre><code>&lt;?php $args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n\n $query = new WP_Query( $args );\n\n $tax = 'category';\n $terms = get_terms( $tax );\n $count = count( $terms );\n\n if ( $count &gt; 0 ): ?&gt;\n &lt;div class=\"post-tags\"&gt;\n &lt;?php\n foreach ( $terms as $term ) {\n $term_link = get_term_link( $term, $tax );\n echo '&lt;a href=\"' . $term_link . '\" class=\"tax-filter\" title=\"' . $term-&gt;slug . '\"&gt;' . $term-&gt;name . '&lt;/a&gt; ';\n } ?&gt;\n &lt;/div&gt;\n &lt;?php endif;\n if ( $query-&gt;have_posts() ): ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;/div&gt;\n\n &lt;?php else: ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Hope that helps solve your problems! </p>\n" }, { "answer_id": 292609, "author": "Droid Sheep", "author_id": 110152, "author_profile": "https://wordpress.stackexchange.com/users/110152", "pm_score": 1, "selected": false, "text": "<p>In the tags_filter change this \n <strong>$tax = 'post_tag';</strong>\nto this\n <strong>$tax = 'category';</strong></p>\n\n<p>Then in the WP Query change this\n <strong>'tag' => $taxonomy,</strong>\nto this\n <strong>'category' => $taxonomy,</strong></p>\n\n<p>Works fine for me... </p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I know this is a big ask for you guys, but i can't seem to figure this out. I found this page : <http://www.bobz.co/ajax-filter-posts-tag/#comment-28112> it shows how to make a dynamic filter for post tags. I wanted to change it to post categories, but i can't seem to get it working. I placed this code in my functions.php ``` function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request 'afp_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'category_name' => $taxonomy, 'post_type' => 'post', 'posts_per_page' => 10, ); // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['category_name'] ); } $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> <?php else: ?> <h2>No posts found</h2> <?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); ``` and then in my actual page template i put this code: ``` //in my template file <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 10, ); $query = new WP_Query( $args ); function tags_filter() { $tax = 'category'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count > 0 ): ?> <div class="post-tags"> <?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> '; } ?> </div> <?php endif; } ``` when i load my page template the site loads my content and shows category filter buttons, but when i click any of the buttons, returns "No Posts found". This leads me to believe i did something wrong with my functions file, but i can't figure it out. Can anyone see something i've done wrong here?
Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. I got this working so it displays all categories and the posts related. Put that in `functions.php` ``` function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request 'afp_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'category_name' => $taxonomy, 'post_type' => 'post', 'posts_per_page' => 10, ); echo $taxonomy; // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['tag'] ); } $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> <?php else: ?> <h2>No posts found</h2> <?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); ``` Then, add this in your page template: ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 10, ); $query = new WP_Query( $args ); $tax = 'category'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count > 0 ): ?> <div class="post-tags"> <?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> '; } ?> </div> <?php endif; if ( $query->have_posts() ): ?> <div class="tagged-posts"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> </div> <?php else: ?> <div class="tagged-posts"> <h2>No posts found</h2> </div> <?php endif; ?> ``` Hope that helps solve your problems!
213,987
<p>I saw <a href="https://wordpress.stackexchange.com/questions/3029/how-to-retrieve-image-from-url-and-set-as-featured-image-post-thumbnail?rq=1">this code</a> as how to set a featured image for a post: </p> <pre><code>// required libraries for media_sideload_image require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // $post_id == the post you want the image to be attached to // $video_thumb_url == the vimeo video's thumb url // $description == optional description // load the image $result = media_sideload_image($video_thumb_url, $description); // then find the last image added to the post attachments $attachments = get_posts(array('numberposts' =&gt; '1', 'post_parent' =&gt; $post_id, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC')); if(sizeof($attachments) &gt; 0){ // set image as the post thumbnail set_post_thumbnail($post_id, $attachments[0]-&gt;ID); } </code></pre> <p>But how do I get that information when I retrieve a post? Is there a property or method that I use? </p>
[ { "answer_id": 237485, "author": "Daniel Griffiths", "author_id": 101849, "author_profile": "https://wordpress.stackexchange.com/users/101849", "pm_score": 3, "selected": true, "text": "<p>Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. </p>\n\n<p>I got this working so it displays all categories and the posts related. Put that in <code>functions.php</code></p>\n\n<pre><code>function ajax_filter_posts_scripts() {\n // Enqueue script\n wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);\n wp_enqueue_script('afp_script');\n\n wp_localize_script( 'afp_script', 'afp_vars', array(\n 'afp_nonce' =&gt; wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request\n 'afp_ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n )\n );\n}\nadd_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);\n\n// Script for getting posts\nfunction ajax_filter_get_posts( $taxonomy ) {\n\n // Verify nonce\n if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )\n die('Permission denied');\n\n $taxonomy = $_POST['taxonomy'];\n\n // WP Query\n $args = array(\n 'category_name' =&gt; $taxonomy,\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n echo $taxonomy;\n // If taxonomy is not set, remove key from array and get all posts\n if( !$taxonomy ) {\n unset( $args['tag'] );\n }\n\n $query = new WP_Query( $args );\n\n if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php else: ?&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;?php endif;\n\n die();\n}\n\nadd_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');\nadd_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');\n</code></pre>\n\n<p>Then, add this in your page template:</p>\n\n<pre><code>&lt;?php $args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n\n $query = new WP_Query( $args );\n\n $tax = 'category';\n $terms = get_terms( $tax );\n $count = count( $terms );\n\n if ( $count &gt; 0 ): ?&gt;\n &lt;div class=\"post-tags\"&gt;\n &lt;?php\n foreach ( $terms as $term ) {\n $term_link = get_term_link( $term, $tax );\n echo '&lt;a href=\"' . $term_link . '\" class=\"tax-filter\" title=\"' . $term-&gt;slug . '\"&gt;' . $term-&gt;name . '&lt;/a&gt; ';\n } ?&gt;\n &lt;/div&gt;\n &lt;?php endif;\n if ( $query-&gt;have_posts() ): ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;/div&gt;\n\n &lt;?php else: ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Hope that helps solve your problems! </p>\n" }, { "answer_id": 292609, "author": "Droid Sheep", "author_id": 110152, "author_profile": "https://wordpress.stackexchange.com/users/110152", "pm_score": 1, "selected": false, "text": "<p>In the tags_filter change this \n <strong>$tax = 'post_tag';</strong>\nto this\n <strong>$tax = 'category';</strong></p>\n\n<p>Then in the WP Query change this\n <strong>'tag' => $taxonomy,</strong>\nto this\n <strong>'category' => $taxonomy,</strong></p>\n\n<p>Works fine for me... </p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213987", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29247/" ]
I saw [this code](https://wordpress.stackexchange.com/questions/3029/how-to-retrieve-image-from-url-and-set-as-featured-image-post-thumbnail?rq=1) as how to set a featured image for a post: ``` // required libraries for media_sideload_image require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // $post_id == the post you want the image to be attached to // $video_thumb_url == the vimeo video's thumb url // $description == optional description // load the image $result = media_sideload_image($video_thumb_url, $description); // then find the last image added to the post attachments $attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC')); if(sizeof($attachments) > 0){ // set image as the post thumbnail set_post_thumbnail($post_id, $attachments[0]->ID); } ``` But how do I get that information when I retrieve a post? Is there a property or method that I use?
Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. I got this working so it displays all categories and the posts related. Put that in `functions.php` ``` function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request 'afp_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'category_name' => $taxonomy, 'post_type' => 'post', 'posts_per_page' => 10, ); echo $taxonomy; // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['tag'] ); } $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> <?php else: ?> <h2>No posts found</h2> <?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); ``` Then, add this in your page template: ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 10, ); $query = new WP_Query( $args ); $tax = 'category'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count > 0 ): ?> <div class="post-tags"> <?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> '; } ?> </div> <?php endif; if ( $query->have_posts() ): ?> <div class="tagged-posts"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> </div> <?php else: ?> <div class="tagged-posts"> <h2>No posts found</h2> </div> <?php endif; ?> ``` Hope that helps solve your problems!
214,052
<p>I have recently redone a site that was originally created in 2011. Of course there were a few big development issues and one of them is the usage of an old audio shortcode:</p> <p>[audio:<a href="http://localhost:8888/lusa/audio/1310seg02.mp3]" rel="nofollow">http://localhost:8888/lusa/audio/1310seg02.mp3]</a></p> <p>I have not seen any documentation of the native Wordpress audio shortcode ever using a colon. I have also not been able to find a plugin that uses it in this way.</p> <p>Does anyone know how I can get this shortcode functioning? I believe my options are.</p> <ol> <li>Create a script that turns this audio shortcode into the newer format [audio src="http://localhost:8888/lusa/audio/1310seg02.mp3] <a href="https://codex.wordpress.org/Audio_Shortcode" rel="nofollow">https://codex.wordpress.org/Audio_Shortcode</a>.</li> <li>Find the plugin that originally made the shortcode this way.</li> <li>?</li> </ol> <p>/<em>======== Progress ========</em>/</p> <p>@gmazzap got me on the right track! The issue is that with the shortcode_atts_audio hook the $atts variable doesn't output strings outside of the predefined attributes (src, loop, autoplay, preload.) After some digging I found that I can use the wp_audio_shortcode_override to access my url. That is what I'm doing in the code below. But now I'm having trouble passing that attribute back into the shortcode and outputting it. </p> <pre><code>function legacy_audio_shortcode_converter( $html, $attr ) { $colon_src = $attr[0]; //get the url string with the colon included. $attr['src'] = substr($colon_src, 1); //filter out the colon $new_audio_src = $attr['src']; //save the url as the official audio src var_dump($new_audio_src); //this is currently outputing the exact url I need but not sure how to make sure the player shows up with this new src. } add_filter( 'wp_audio_shortcode_override', 'legacy_audio_shortcode_converter', 10, 2 ); </code></pre>
[ { "answer_id": 237485, "author": "Daniel Griffiths", "author_id": 101849, "author_profile": "https://wordpress.stackexchange.com/users/101849", "pm_score": 3, "selected": true, "text": "<p>Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. </p>\n\n<p>I got this working so it displays all categories and the posts related. Put that in <code>functions.php</code></p>\n\n<pre><code>function ajax_filter_posts_scripts() {\n // Enqueue script\n wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);\n wp_enqueue_script('afp_script');\n\n wp_localize_script( 'afp_script', 'afp_vars', array(\n 'afp_nonce' =&gt; wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request\n 'afp_ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n )\n );\n}\nadd_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);\n\n// Script for getting posts\nfunction ajax_filter_get_posts( $taxonomy ) {\n\n // Verify nonce\n if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )\n die('Permission denied');\n\n $taxonomy = $_POST['taxonomy'];\n\n // WP Query\n $args = array(\n 'category_name' =&gt; $taxonomy,\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n echo $taxonomy;\n // If taxonomy is not set, remove key from array and get all posts\n if( !$taxonomy ) {\n unset( $args['tag'] );\n }\n\n $query = new WP_Query( $args );\n\n if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php else: ?&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;?php endif;\n\n die();\n}\n\nadd_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');\nadd_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');\n</code></pre>\n\n<p>Then, add this in your page template:</p>\n\n<pre><code>&lt;?php $args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n );\n\n $query = new WP_Query( $args );\n\n $tax = 'category';\n $terms = get_terms( $tax );\n $count = count( $terms );\n\n if ( $count &gt; 0 ): ?&gt;\n &lt;div class=\"post-tags\"&gt;\n &lt;?php\n foreach ( $terms as $term ) {\n $term_link = get_term_link( $term, $tax );\n echo '&lt;a href=\"' . $term_link . '\" class=\"tax-filter\" title=\"' . $term-&gt;slug . '\"&gt;' . $term-&gt;name . '&lt;/a&gt; ';\n } ?&gt;\n &lt;/div&gt;\n &lt;?php endif;\n if ( $query-&gt;have_posts() ): ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;/div&gt;\n\n &lt;?php else: ?&gt;\n &lt;div class=\"tagged-posts\"&gt;\n &lt;h2&gt;No posts found&lt;/h2&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Hope that helps solve your problems! </p>\n" }, { "answer_id": 292609, "author": "Droid Sheep", "author_id": 110152, "author_profile": "https://wordpress.stackexchange.com/users/110152", "pm_score": 1, "selected": false, "text": "<p>In the tags_filter change this \n <strong>$tax = 'post_tag';</strong>\nto this\n <strong>$tax = 'category';</strong></p>\n\n<p>Then in the WP Query change this\n <strong>'tag' => $taxonomy,</strong>\nto this\n <strong>'category' => $taxonomy,</strong></p>\n\n<p>Works fine for me... </p>\n" } ]
2016/01/08
[ "https://wordpress.stackexchange.com/questions/214052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60029/" ]
I have recently redone a site that was originally created in 2011. Of course there were a few big development issues and one of them is the usage of an old audio shortcode: [audio:<http://localhost:8888/lusa/audio/1310seg02.mp3]> I have not seen any documentation of the native Wordpress audio shortcode ever using a colon. I have also not been able to find a plugin that uses it in this way. Does anyone know how I can get this shortcode functioning? I believe my options are. 1. Create a script that turns this audio shortcode into the newer format [audio src="http://localhost:8888/lusa/audio/1310seg02.mp3] <https://codex.wordpress.org/Audio_Shortcode>. 2. Find the plugin that originally made the shortcode this way. 3. ? /*======== Progress ========*/ @gmazzap got me on the right track! The issue is that with the shortcode\_atts\_audio hook the $atts variable doesn't output strings outside of the predefined attributes (src, loop, autoplay, preload.) After some digging I found that I can use the wp\_audio\_shortcode\_override to access my url. That is what I'm doing in the code below. But now I'm having trouble passing that attribute back into the shortcode and outputting it. ``` function legacy_audio_shortcode_converter( $html, $attr ) { $colon_src = $attr[0]; //get the url string with the colon included. $attr['src'] = substr($colon_src, 1); //filter out the colon $new_audio_src = $attr['src']; //save the url as the official audio src var_dump($new_audio_src); //this is currently outputing the exact url I need but not sure how to make sure the player shows up with this new src. } add_filter( 'wp_audio_shortcode_override', 'legacy_audio_shortcode_converter', 10, 2 ); ```
Not sure if you've solved this or not but I was looking for a way to embed this within a page and filter posts by category. I got this working so it displays all categories and the posts related. Put that in `functions.php` ``` function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request 'afp_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'category_name' => $taxonomy, 'post_type' => 'post', 'posts_per_page' => 10, ); echo $taxonomy; // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['tag'] ); } $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> <?php else: ?> <h2>No posts found</h2> <?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); ``` Then, add this in your page template: ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 10, ); $query = new WP_Query( $args ); $tax = 'category'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count > 0 ): ?> <div class="post-tags"> <?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> '; } ?> </div> <?php endif; if ( $query->have_posts() ): ?> <div class="tagged-posts"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> </div> <?php else: ?> <div class="tagged-posts"> <h2>No posts found</h2> </div> <?php endif; ?> ``` Hope that helps solve your problems!
214,066
<p>The WordPress 4.4 adds multiple image sizes with <code>srcset</code> when using <code>the_post_thumbnail</code> function. Is it possible to get only one image size without srcset ?</p> <p>I understand that it is possible to add a filter to disable <code>srcset</code> from all images, but I want to disable the <code>srcset</code> only when calling a specific thumbnail size (for example only when calling full image size).</p>
[ { "answer_id": 214071, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>I want to disable the srcset only when calling a specific thumbnail\n size (for example only when calling full image size).</p>\n</blockquote>\n\n<p>Here are two ideas (if I understand you correctly):</p>\n\n<h2>Approach #1</h2>\n\n<p>Let's check the size from the <code>post_thumbnail_size</code> filter. If it matches a corresponding size (e.g. <code>full</code>) then we make sure the <code>$image_meta</code> is empty, with the <code>wp_calculate_image_srcset_meta</code> filter. That way we can bail out early from the <code>wp_calculate_image_srcset()</code> function (earlier than using the <code>max_srcset_image_width</code> or <code>wp_calculate_image_srcset</code> filters to disable it):</p>\n\n<pre><code>/**\n * Remove the srcset attribute from post thumbnails \n * that are called with the 'full' size string: the_post_thumbnail( 'full' )\n *\n * @link http://wordpress.stackexchange.com/a/214071/26350\n */\n add_filter( 'post_thumbnail_size', function( $size )\n {\n if( is_string( $size ) &amp;&amp; 'full' === $size )\n add_filter( \n 'wp_calculate_image_srcset_meta', \n '__return_null_and_remove_current_filter' \n ); \n return $size;\n } );\n\n// Would be handy, in this example, to have this as a core function ;-)\nfunction __return_null_and_remove_current_filter ( $var )\n{\n remove_filter( current_filter(), __FUNCTION__ );\n return null;\n}\n</code></pre>\n\n<p>If we have:</p>\n\n<pre><code>the_post_thumbnail( 'full' );\n</code></pre>\n\n<p>then the generated <code>&lt;img&gt;</code> tag will not contain the <code>srcset</code> attribute.</p>\n\n<p>For the case:</p>\n\n<pre><code>the_post_thumbnail();\n</code></pre>\n\n<p>we could match the <code>'post-thumbnail'</code> size string.</p>\n\n<h2>Approach #2</h2>\n\n<p>We could also add/remove the filter manually with:</p>\n\n<pre><code>// Add a filter to remove srcset attribute from generated &lt;img&gt; tag\nadd_filter( 'wp_calculate_image_srcset_meta', '__return_null' );\n\n// Display post thumbnail\nthe_post_thumbnail();\n\n// Remove that filter again\nremove_filter( 'wp_calculate_image_srcset_meta', '__return_null' );\n</code></pre>\n" }, { "answer_id": 400762, "author": "Dario Zadro", "author_id": 17126, "author_profile": "https://wordpress.stackexchange.com/users/17126", "pm_score": 1, "selected": false, "text": "<p>No filters are necessary. The most simple solution is below:</p>\n<pre><code>// exclude any attribute you want to keep from the list\n// choose any defined image size, ie. large, medium, etc\necho preg_replace( '/(width|height|srcset|sizes)=&quot;[^&quot;]*&quot;/', '', get_the_post_thumbnail( get_the_ID(), 'large') );\n</code></pre>\n" } ]
2016/01/08
[ "https://wordpress.stackexchange.com/questions/214066", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86476/" ]
The WordPress 4.4 adds multiple image sizes with `srcset` when using `the_post_thumbnail` function. Is it possible to get only one image size without srcset ? I understand that it is possible to add a filter to disable `srcset` from all images, but I want to disable the `srcset` only when calling a specific thumbnail size (for example only when calling full image size).
> > I want to disable the srcset only when calling a specific thumbnail > size (for example only when calling full image size). > > > Here are two ideas (if I understand you correctly): Approach #1 ----------- Let's check the size from the `post_thumbnail_size` filter. If it matches a corresponding size (e.g. `full`) then we make sure the `$image_meta` is empty, with the `wp_calculate_image_srcset_meta` filter. That way we can bail out early from the `wp_calculate_image_srcset()` function (earlier than using the `max_srcset_image_width` or `wp_calculate_image_srcset` filters to disable it): ``` /** * Remove the srcset attribute from post thumbnails * that are called with the 'full' size string: the_post_thumbnail( 'full' ) * * @link http://wordpress.stackexchange.com/a/214071/26350 */ add_filter( 'post_thumbnail_size', function( $size ) { if( is_string( $size ) && 'full' === $size ) add_filter( 'wp_calculate_image_srcset_meta', '__return_null_and_remove_current_filter' ); return $size; } ); // Would be handy, in this example, to have this as a core function ;-) function __return_null_and_remove_current_filter ( $var ) { remove_filter( current_filter(), __FUNCTION__ ); return null; } ``` If we have: ``` the_post_thumbnail( 'full' ); ``` then the generated `<img>` tag will not contain the `srcset` attribute. For the case: ``` the_post_thumbnail(); ``` we could match the `'post-thumbnail'` size string. Approach #2 ----------- We could also add/remove the filter manually with: ``` // Add a filter to remove srcset attribute from generated <img> tag add_filter( 'wp_calculate_image_srcset_meta', '__return_null' ); // Display post thumbnail the_post_thumbnail(); // Remove that filter again remove_filter( 'wp_calculate_image_srcset_meta', '__return_null' ); ```
214,084
<p>I have a taxonomy archive page where I display everything under the term 'techno' I want to be able to limit this to 20 posts to a page until it paginates. At the moment it displays 10 on one page and then 10 on another. This works fine on my main page where I give the posts per page limit to 20. Can anyone see why? Here is my code</p> <pre><code>&lt;?php /* Template Name: Genre */ //Protect against arbitrary paged values $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; get_header(); $object = get_queried_object(); $taxonomy = "genre"; // can be category, post_tag, or custom taxonomy name // Using Term Slug $term_slug = $object-&gt;slug; $term = get_term_by('slug', $term_slug, $taxonomy); // Fetch the count $number = $term-&gt;count / 20; ?&gt; &lt;header class="intro-archive"&gt; &lt;div class="intro-body"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8 col-md-offset-2"&gt; &lt;h1 class="brand-heading"&gt;&lt;?php echo $object-&gt;name; ?&gt;&lt;/h1&gt; &lt;p class="intro-text"&gt;An archive of all the &lt;?php echo $object-&gt;name; ?&gt; posted on the site&lt;/p&gt;&lt;a class="btn btn-circle page-scroll fa fa-angle-double-down animated" href="#latest" style="font-size:54px;"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt;&lt;!-- About Section --&gt; &lt;section class="container content-section text-center" id="latest"&gt; &lt;?php $j = 0; if ( have_posts() ) : while ( have_posts() ) : the_post(); // standard WordPress loop. $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, '370x250' ); $thumb_url = $thumb_url_array[0]; // Grab the artist ID from the post meta $artist = get_post_meta(get_the_ID(), '_artist'); // seperate each artist id $explodeArray = array_filter(explode(' ', $artist[0])); $arrayLength = count($explodeArray); $i = 0; // If there is more than one artist attached to song loop through if ($arrayLength &gt; 1) { foreach ($explodeArray as $array) { $artist_meta[$i] = get_the_title($array); $i++; } } else { $artist_name = get_the_title($explodeArray[0]); } // If the current counter dividied by 4 leaves no remainder add a row // This splits our archive into rows with 4 elements in if($j % 4 == 0) { ?&gt; &lt;div class="row "&gt; &lt;?php } ?&gt; &lt;div class="col-md-3 col-sm-12" style="margin-top:100px;"&gt; &lt;div class="ih-item square effect3 bottom_to_top"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="img"&gt; &lt;img alt="" class="image-responsive" src="&lt;?php echo $thumb_url ?&gt;"&gt; &lt;/div&gt; &lt;div class="info"&gt; &lt;h3&gt;&lt;?php if ($artist_meta) { foreach($artist_meta as $meta) { echo $meta; echo '&lt;br /&gt;'; } } else { echo $artist_name; } ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $j++; if ( $j != 0 &amp;&amp; $j % 4 == 0 ) { ?&gt; &lt;/div&gt;&lt;!--/.row--&gt; &lt;?php } endwhile; endif; ?&gt; &lt;div class="col-md-12"&gt; &lt;?php dem_pagination($number); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt;&lt;!-- Footer --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 214096, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 3, "selected": true, "text": "<p>Maybe a very quick and (simplified)dirty way I show here, but would this function not solve it without the need to make changes for/in the templates?<br />\n<em>(Yes I know I also make queries in my templates but wanted to help out before leaving office)</em></p>\n\n<pre><code>function wpse214084_max_post_queries( $query ) {\n\n if(is_tax('genre')){ // change genre into your taxonomy or leave out for all\n // show 20 posts\n $query-&gt;set('posts_per_page', 20);\n }\n}\nadd_action( 'pre_get_posts', 'wpse214084_max_post_queries' );\n</code></pre>\n\n<blockquote>\n <p>FYI: Maybe you take a look at\n <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a>in\n the codex and also at\n <a href=\"https://codex.wordpress.org/Function_Reference/is_tax\" rel=\"nofollow\"><code>is_tax</code></a>.\n What you probably where/am looking for is <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">query\n posts</a>\n <strong>post_per_page</strong>.</p>\n</blockquote>\n\n<p>I hope this helps you out or at least gives some guidelines.</p>\n" }, { "answer_id": 214097, "author": "Vasu Chawla", "author_id": 40625, "author_profile": "https://wordpress.stackexchange.com/users/40625", "pm_score": 0, "selected": false, "text": "<p>i back @Charles answer, along with that another workaround is to create new object of WP_Query class, and use that object's loop instead of default loop, </p>\n\n<p>Dont forget to use </p>\n\n<blockquote>\n <p>$wp_query->query_vars['taxonomy_name']</p>\n</blockquote>\n\n<p>to get the current taxanomy and load it into WP_Query's object parameters.\nwith that you can use posts_per_page.</p>\n\n<p>more details <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">here</a></p>\n" } ]
2016/01/08
[ "https://wordpress.stackexchange.com/questions/214084", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64115/" ]
I have a taxonomy archive page where I display everything under the term 'techno' I want to be able to limit this to 20 posts to a page until it paginates. At the moment it displays 10 on one page and then 10 on another. This works fine on my main page where I give the posts per page limit to 20. Can anyone see why? Here is my code ``` <?php /* Template Name: Genre */ //Protect against arbitrary paged values $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; get_header(); $object = get_queried_object(); $taxonomy = "genre"; // can be category, post_tag, or custom taxonomy name // Using Term Slug $term_slug = $object->slug; $term = get_term_by('slug', $term_slug, $taxonomy); // Fetch the count $number = $term->count / 20; ?> <header class="intro-archive"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1 class="brand-heading"><?php echo $object->name; ?></h1> <p class="intro-text">An archive of all the <?php echo $object->name; ?> posted on the site</p><a class="btn btn-circle page-scroll fa fa-angle-double-down animated" href="#latest" style="font-size:54px;"></a> </div> </div> </div> </div> </header><!-- About Section --> <section class="container content-section text-center" id="latest"> <?php $j = 0; if ( have_posts() ) : while ( have_posts() ) : the_post(); // standard WordPress loop. $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, '370x250' ); $thumb_url = $thumb_url_array[0]; // Grab the artist ID from the post meta $artist = get_post_meta(get_the_ID(), '_artist'); // seperate each artist id $explodeArray = array_filter(explode(' ', $artist[0])); $arrayLength = count($explodeArray); $i = 0; // If there is more than one artist attached to song loop through if ($arrayLength > 1) { foreach ($explodeArray as $array) { $artist_meta[$i] = get_the_title($array); $i++; } } else { $artist_name = get_the_title($explodeArray[0]); } // If the current counter dividied by 4 leaves no remainder add a row // This splits our archive into rows with 4 elements in if($j % 4 == 0) { ?> <div class="row "> <?php } ?> <div class="col-md-3 col-sm-12" style="margin-top:100px;"> <div class="ih-item square effect3 bottom_to_top"> <a href="<?php the_permalink(); ?>"> <div class="img"> <img alt="" class="image-responsive" src="<?php echo $thumb_url ?>"> </div> <div class="info"> <h3><?php if ($artist_meta) { foreach($artist_meta as $meta) { echo $meta; echo '<br />'; } } else { echo $artist_name; } ?></h3> <p><?php the_title(); ?></p> </div> </a> </div> </div> <?php $j++; if ( $j != 0 && $j % 4 == 0 ) { ?> </div><!--/.row--> <?php } endwhile; endif; ?> <div class="col-md-12"> <?php dem_pagination($number); ?> </div> </div> </section><!-- Footer --> <?php get_footer(); ?> ```
Maybe a very quick and (simplified)dirty way I show here, but would this function not solve it without the need to make changes for/in the templates? *(Yes I know I also make queries in my templates but wanted to help out before leaving office)* ``` function wpse214084_max_post_queries( $query ) { if(is_tax('genre')){ // change genre into your taxonomy or leave out for all // show 20 posts $query->set('posts_per_page', 20); } } add_action( 'pre_get_posts', 'wpse214084_max_post_queries' ); ``` > > FYI: Maybe you take a look at > [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)in > the codex and also at > [`is_tax`](https://codex.wordpress.org/Function_Reference/is_tax). > What you probably where/am looking for is [query > posts](https://codex.wordpress.org/Function_Reference/query_posts) > **post\_per\_page**. > > > I hope this helps you out or at least gives some guidelines.
214,098
<p>How can i create an custom post template for an specific post category in Wordpress?</p>
[ { "answer_id": 214096, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 3, "selected": true, "text": "<p>Maybe a very quick and (simplified)dirty way I show here, but would this function not solve it without the need to make changes for/in the templates?<br />\n<em>(Yes I know I also make queries in my templates but wanted to help out before leaving office)</em></p>\n\n<pre><code>function wpse214084_max_post_queries( $query ) {\n\n if(is_tax('genre')){ // change genre into your taxonomy or leave out for all\n // show 20 posts\n $query-&gt;set('posts_per_page', 20);\n }\n}\nadd_action( 'pre_get_posts', 'wpse214084_max_post_queries' );\n</code></pre>\n\n<blockquote>\n <p>FYI: Maybe you take a look at\n <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a>in\n the codex and also at\n <a href=\"https://codex.wordpress.org/Function_Reference/is_tax\" rel=\"nofollow\"><code>is_tax</code></a>.\n What you probably where/am looking for is <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">query\n posts</a>\n <strong>post_per_page</strong>.</p>\n</blockquote>\n\n<p>I hope this helps you out or at least gives some guidelines.</p>\n" }, { "answer_id": 214097, "author": "Vasu Chawla", "author_id": 40625, "author_profile": "https://wordpress.stackexchange.com/users/40625", "pm_score": 0, "selected": false, "text": "<p>i back @Charles answer, along with that another workaround is to create new object of WP_Query class, and use that object's loop instead of default loop, </p>\n\n<p>Dont forget to use </p>\n\n<blockquote>\n <p>$wp_query->query_vars['taxonomy_name']</p>\n</blockquote>\n\n<p>to get the current taxanomy and load it into WP_Query's object parameters.\nwith that you can use posts_per_page.</p>\n\n<p>more details <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">here</a></p>\n" } ]
2016/01/08
[ "https://wordpress.stackexchange.com/questions/214098", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86490/" ]
How can i create an custom post template for an specific post category in Wordpress?
Maybe a very quick and (simplified)dirty way I show here, but would this function not solve it without the need to make changes for/in the templates? *(Yes I know I also make queries in my templates but wanted to help out before leaving office)* ``` function wpse214084_max_post_queries( $query ) { if(is_tax('genre')){ // change genre into your taxonomy or leave out for all // show 20 posts $query->set('posts_per_page', 20); } } add_action( 'pre_get_posts', 'wpse214084_max_post_queries' ); ``` > > FYI: Maybe you take a look at > [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)in > the codex and also at > [`is_tax`](https://codex.wordpress.org/Function_Reference/is_tax). > What you probably where/am looking for is [query > posts](https://codex.wordpress.org/Function_Reference/query_posts) > **post\_per\_page**. > > > I hope this helps you out or at least gives some guidelines.
214,109
<p>I'm querying a custom field of users based on a city they are in. I am able to display their profile photo and display name, however I can't seem to get the link to their actual author url to work.</p> <p>It just keeps linking to the same page it's currently on. Any help would be greatly appreciated.</p> <pre><code>&lt;?php $london_args = array( 'meta_value' =&gt; 'London', ); // The Query $london_user_query = new WP_User_Query( $london_args ); // User Loop if ( ! empty( $london_user_query-&gt;results ) ) { foreach ( $london_user_query-&gt;results as $user ) { ?&gt; &lt;li&gt; &lt;?php if($user-&gt;user_cover_pic == '') { ?&gt; Photo coming soon &lt;?php } else { ?&gt; &lt;a href="&lt;?php $user-&gt;url; ?&gt;"&gt; &lt;img src="&lt;?php echo $user-&gt;user_cover_pic; ?&gt;" alt="&lt;?php echo $user-&gt;display_name; ?&gt;"&gt; &lt;/a&gt; &lt;?php }; ?&gt;&lt;br&gt; &lt;a href="&lt;?php $user-&gt;url; ?&gt;"&gt;&lt;?php echo $user-&gt;display_name; ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php } } else { echo 'No Lawyers found in London.'; } ?&gt; </code></pre>
[ { "answer_id": 214111, "author": "terminator", "author_id": 55034, "author_profile": "https://wordpress.stackexchange.com/users/55034", "pm_score": 2, "selected": false, "text": "<p>I am not sure too much about the code but i think you forgot to <code>echo</code> $user->url</p>\n\n<p>So just replace all <code>$user-&gt;url</code> with <code>echo $user-&gt;url</code></p>\n" }, { "answer_id": 214294, "author": "Robert Allen Baker", "author_id": 86499, "author_profile": "https://wordpress.stackexchange.com/users/86499", "pm_score": -1, "selected": false, "text": "<p>Solved it!</p>\n\n<pre><code>echo get_author_posts_url( $user-&gt;ID );\n</code></pre>\n\n<p>Thank you for replying, terminator. :) You at least got me in the right direction.</p>\n" } ]
2016/01/08
[ "https://wordpress.stackexchange.com/questions/214109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86499/" ]
I'm querying a custom field of users based on a city they are in. I am able to display their profile photo and display name, however I can't seem to get the link to their actual author url to work. It just keeps linking to the same page it's currently on. Any help would be greatly appreciated. ``` <?php $london_args = array( 'meta_value' => 'London', ); // The Query $london_user_query = new WP_User_Query( $london_args ); // User Loop if ( ! empty( $london_user_query->results ) ) { foreach ( $london_user_query->results as $user ) { ?> <li> <?php if($user->user_cover_pic == '') { ?> Photo coming soon <?php } else { ?> <a href="<?php $user->url; ?>"> <img src="<?php echo $user->user_cover_pic; ?>" alt="<?php echo $user->display_name; ?>"> </a> <?php }; ?><br> <a href="<?php $user->url; ?>"><?php echo $user->display_name; ?></a> </li> <?php } } else { echo 'No Lawyers found in London.'; } ?> ```
I am not sure too much about the code but i think you forgot to `echo` $user->url So just replace all `$user->url` with `echo $user->url`
214,134
<p>I know there is many solutions how to rename attachment while upload files to postid. I got correct solutions that really works fine is: <a href="https://wordpress.stackexchange.com/a/30767/86517">https://wordpress.stackexchange.com/a/30767/86517</a> <strong><em>(I'm new and I can't comments there. So I ask this question.)</em></strong></p> <p><strong>The code is:</strong> </p> <pre><code>add_action('add_attachment', 'rename_attacment'); function rename_attacment($post_ID){ $post = get_post($post_ID); $file = get_attached_file($post_ID); $path = pathinfo($file); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename $newfilename = "NEW FILE NAME HERE"; $newfile = $path['dirname']."/".$newfilename.".".$path['extension']; rename($file, $newfile); update_attached_file( $post_ID, $newfile ); } </code></pre> <p>But Problem is, I want this changes only for 3 custom post types. Currently my site have 6 custom post type. So Only 3 custom post type need this. There is any way to allow to run this function only for those custom post type?</p> <p>Thanks</p>
[ { "answer_id": 214111, "author": "terminator", "author_id": 55034, "author_profile": "https://wordpress.stackexchange.com/users/55034", "pm_score": 2, "selected": false, "text": "<p>I am not sure too much about the code but i think you forgot to <code>echo</code> $user->url</p>\n\n<p>So just replace all <code>$user-&gt;url</code> with <code>echo $user-&gt;url</code></p>\n" }, { "answer_id": 214294, "author": "Robert Allen Baker", "author_id": 86499, "author_profile": "https://wordpress.stackexchange.com/users/86499", "pm_score": -1, "selected": false, "text": "<p>Solved it!</p>\n\n<pre><code>echo get_author_posts_url( $user-&gt;ID );\n</code></pre>\n\n<p>Thank you for replying, terminator. :) You at least got me in the right direction.</p>\n" } ]
2016/01/09
[ "https://wordpress.stackexchange.com/questions/214134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86517/" ]
I know there is many solutions how to rename attachment while upload files to postid. I got correct solutions that really works fine is: <https://wordpress.stackexchange.com/a/30767/86517> ***(I'm new and I can't comments there. So I ask this question.)*** **The code is:** ``` add_action('add_attachment', 'rename_attacment'); function rename_attacment($post_ID){ $post = get_post($post_ID); $file = get_attached_file($post_ID); $path = pathinfo($file); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename $newfilename = "NEW FILE NAME HERE"; $newfile = $path['dirname']."/".$newfilename.".".$path['extension']; rename($file, $newfile); update_attached_file( $post_ID, $newfile ); } ``` But Problem is, I want this changes only for 3 custom post types. Currently my site have 6 custom post type. So Only 3 custom post type need this. There is any way to allow to run this function only for those custom post type? Thanks
I am not sure too much about the code but i think you forgot to `echo` $user->url So just replace all `$user->url` with `echo $user->url`
214,206
<p>I've a website currently running in CI and it has a user table. I'm making a WordPress website and need it to use the user table of the CI database for users to login in WordPress. How can I use only that table of different database? Both DBs are on same server. Also I have to differentiate between admin and normal users, as admins can enter the dashboard. I've tried <a href="https://wordpress.org/plugins/external-db-auth-reloaded/" rel="nofollow noreferrer">this plugin</a> but as soon as I activate this plugin my login page stops working and displays a 500 server error.</p>
[ { "answer_id": 214207, "author": "Lionel Ritchie the Manatee", "author_id": 94990, "author_profile": "https://wordpress.stackexchange.com/users/94990", "pm_score": 0, "selected": false, "text": "<p>You don't need a plugin to make multiple db connections in CI. Just do this:</p>\n\n<h3>Connection 1 - /application/config/database.php</h3>\n\n<p>This is your default CI database config</p>\n\n<pre><code>$db['default']['hostname'] = 'DB_HOST';\n$db['default']['username'] = 'DB_USER';\n$db['default']['password'] = 'DB_PASSWORD';\n$db['default']['database'] = 'DB_NAME';\n\n$db['default']['dbdriver'] = 'mysql';\n$db['default']['dbprefix'] = '';\n$db['default']['pconnect'] = TRUE;\n$db['default']['db_debug'] = TRUE;\n$db['default']['cache_on'] = FALSE;\n$db['default']['cachedir'] = '';\n$db['default']['char_set'] = 'utf8';\n$db['default']['dbcollat'] = 'utf8_general_ci';\n$db['default']['swap_pre'] = '';\n$db['default']['autoinit'] = TRUE;\n$db['default']['stricton'] = FALSE;\n</code></pre>\n\n<h3>Connection 2 - /application/config/database.php</h3>\n\n<p>Duplicate that chunk of code, renaming the <code>$db['default']</code> with something like <code>$db['secondary']</code></p>\n\n<pre><code>$db['secondary']['hostname'] = 'SECONDARY_DB_HOST';\n$db['secondary']['username'] = 'SECONDARY_DB_USER';\n$db['secondary']['password'] = 'SECONDARY_DB_PASSWORD';\n$db['secondary']['database'] = 'SECONDARY_DB_NAME';\n\n$db['secondary']['dbdriver'] = 'mysql';\n$db['secondary']['dbprefix'] = '';\n$db['secondary']['pconnect'] = TRUE;\n$db['secondary']['db_debug'] = TRUE;\n$db['secondary']['cache_on'] = FALSE;\n$db['secondary']['cachedir'] = '';\n$db['secondary']['char_set'] = 'utf8';\n$db['secondary']['dbcollat'] = 'utf8_general_ci';\n$db['secondary']['swap_pre'] = '';\n$db['secondary']['autoinit'] = TRUE;\n$db['secondary']['stricton'] = FALSE;\n</code></pre>\n\n<h3>Initiate and use Connection 2</h3>\n\n<pre><code>function getWordpressUsers() {\n\n $secondaryDb = $this-&gt;load-&gt;database('secondary', TRUE);\n\n $query = $secondaryDb-&gt;select('user_email, display_name')-&gt;get('wp_users');\n var_dump($query);\n\n}\n</code></pre>\n\n<p>For more info about it, check this out: <a href=\"https://codeigniter.com/user_guide/database/connecting.html\" rel=\"nofollow\">https://codeigniter.com/user_guide/database/connecting.html</a></p>\n" }, { "answer_id": 281277, "author": "PayteR", "author_id": 122916, "author_profile": "https://wordpress.stackexchange.com/users/122916", "pm_score": 0, "selected": false, "text": "<p>It's not possible in Wordpress to have shared users between 2 separates installations on 2 separated databases. </p>\n\n<p>It could be possible just by hardcoding:</p>\n\n<ol>\n<li>hardcode WP_User class connect to other database and retrieve users\nfrom there </li>\n<li>hardcode get_metadata() function, that for wp_usermeta table connect to other database and retrieve users from there </li>\n</ol>\n\n<p>but mentioned solution is not recommended of course, because it's not updateproof.</p>\n" }, { "answer_id": 326117, "author": "Loren Rosen", "author_id": 158993, "author_profile": "https://wordpress.stackexchange.com/users/158993", "pm_score": 2, "selected": false, "text": "<p>It might work to use a view as essentially a table alias, by doing the something like the following with the WordPress instance mysql database</p>\n\n<pre><code> DROP TABLE wp_users\n CREATE VIEW wp_users AS SELECT * FROM CI.users;\n</code></pre>\n\n<p>However</p>\n\n<ul>\n<li>will probably need to tweak the view creation to map the columns</li>\n<li>the password encoding may well be different, so you might have hack WP core anyway to handle this</li>\n<li>you probably need to manually modify the <code>wp_usermeta</code> table to properly signify admins.</li>\n</ul>\n" } ]
2015/12/29
[ "https://wordpress.stackexchange.com/questions/214206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I've a website currently running in CI and it has a user table. I'm making a WordPress website and need it to use the user table of the CI database for users to login in WordPress. How can I use only that table of different database? Both DBs are on same server. Also I have to differentiate between admin and normal users, as admins can enter the dashboard. I've tried [this plugin](https://wordpress.org/plugins/external-db-auth-reloaded/) but as soon as I activate this plugin my login page stops working and displays a 500 server error.
It might work to use a view as essentially a table alias, by doing the something like the following with the WordPress instance mysql database ``` DROP TABLE wp_users CREATE VIEW wp_users AS SELECT * FROM CI.users; ``` However * will probably need to tweak the view creation to map the columns * the password encoding may well be different, so you might have hack WP core anyway to handle this * you probably need to manually modify the `wp_usermeta` table to properly signify admins.
214,210
<p>My WordPress site currently displays users' identifying information by their FIRSTNAME + LASTNAME.</p> <p>The vast majority prefer to be known by their usernames. I've instructed how to change their "Display Name Publicly As" manually (i.e. via their User settings) but this is less than ideal.</p> <p>I would like new users to be shown by their usernames as the default. Note that I want this to reflect in several plugins that refer to the "Display Name Publicly As" property.</p> <p>How can this be done?</p>
[ { "answer_id": 214214, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you want this for all future users then hook into the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\"><code>user_register</code></a> event and update it there.</p>\n\n<p>Pull the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow\"><code>WP_User</code></a> using <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow\"><code>get_userdata</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow\"><code>wp_update_user</code></a> info with the new display name.</p>\n\n<pre><code>add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 );\n\nfunction wpse_20160110_user_register ( $user_id ) {\n\n // get the user data\n\n $user_info = get_userdata( $user_id );\n\n // pick our default display name\n\n $display_publicly_as = $user_info-&gt;user_login;\n\n // update the display name\n\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $display_publicly_as));\n}\n</code></pre>\n\n<p>If you want to set this every login then hook <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow\"><code>wp_login</code></a> using <a href=\"http://php.net/manual/en/reserved.constants.php#constant.php-int-max\" rel=\"nofollow\"><code>PHP_INT_MAX</code></a>.</p>\n\n<pre><code>function wpse_20160110_wp_login ( $user_login, $user ) {\n\n wp_update_user(array('ID' =&gt; $user-&gt;ID, 'display_name' =&gt; $user_login));\n\n}\n\nadd_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2);\n</code></pre>\n" }, { "answer_id": 338974, "author": "UAU", "author_id": 168963, "author_profile": "https://wordpress.stackexchange.com/users/168963", "pm_score": 1, "selected": false, "text": "<p>To programmatically set the display name both on registration and profile update, avoiding the infinite loop Betty experienced, you have to check if the display name is already set as needed.</p>\n\n<pre><code>add_action( 'user_register', 'set_login_as_displayname' );\nadd_action( 'profile_update', 'set_login_as_displayname' );\n\nfunction set_login_as_displayname( $user_id )\n{\n $data = get_userdata( $user_id );\n\n if ($data-&gt;user_login != $data-&gt;display_name) {\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $data-&gt;user_login));\n }\n}\n</code></pre>\n" } ]
2016/01/10
[ "https://wordpress.stackexchange.com/questions/214210", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86585/" ]
My WordPress site currently displays users' identifying information by their FIRSTNAME + LASTNAME. The vast majority prefer to be known by their usernames. I've instructed how to change their "Display Name Publicly As" manually (i.e. via their User settings) but this is less than ideal. I would like new users to be shown by their usernames as the default. Note that I want this to reflect in several plugins that refer to the "Display Name Publicly As" property. How can this be done?
If you want this for all future users then hook into the [`user_register`](https://codex.wordpress.org/Plugin_API/Action_Reference/user_register) event and update it there. Pull the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) using [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) and [`wp_update_user`](https://codex.wordpress.org/Function_Reference/wp_update_user) info with the new display name. ``` add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 ); function wpse_20160110_user_register ( $user_id ) { // get the user data $user_info = get_userdata( $user_id ); // pick our default display name $display_publicly_as = $user_info->user_login; // update the display name wp_update_user( array ('ID' => $user_id, 'display_name' => $display_publicly_as)); } ``` If you want to set this every login then hook [`wp_login`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login) using [`PHP_INT_MAX`](http://php.net/manual/en/reserved.constants.php#constant.php-int-max). ``` function wpse_20160110_wp_login ( $user_login, $user ) { wp_update_user(array('ID' => $user->ID, 'display_name' => $user_login)); } add_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2); ```
214,224
<p>I have Radio with programs and they are associated to day of the weak.</p> <p><em>Example:</em></p> <p>1-Program Disco Nights plays at Monday and Friday</p> <p>2-Pragram Crazy weekends play only at Sunday</p> <p>3-etc</p> <p>4-etc</p> <p><strong>Objective:</strong> List All the programs without repeating the ones are associated to multiple days based on current day and the next ones.</p> <p>If today is Saturday have to list Saturday programs them sunday, monday etc etc but can't only be listed once the same program. (THE CLOSEST ONE)</p> <p>How to achieve this?</p> <p>On the back-office I have a multi select option which allow user to select multiple days based on plugin framework it stores the meta_value in a serialized array and can not be changed so I have to work with it.</p> <pre><code>a:3:{i:0;s:1:"3";i:1;s:1:"4";i:2;s:1:"6";} </code></pre> <p>Each day correspond to a value.</p> <p>0 - Sunday</p> <p>1 - Monday</p> <p>2 - Tuesday</p> <p>3 - Wednesday</p> <p>4 - Thursday</p> <p>5 - Friday</p> <p>6 - Saturday</p> <p>Now the hardest part to list it on-front office.</p> <pre><code>$today = date('w'); $args = array( 'post_type' =&gt; 'programas', 'meta_key' =&gt; 'audio_date', 'orderby' =&gt; ' ?? closest one ??', $the_query = new WP_Query( $args ); ); </code></pre> <p>Remember meta key returns a serialized array like this </p> <pre><code> a:3:{i:0;s:1:"3";i:1;s:1:"4";i:2;s:1:"6";} </code></pre> <p>I don't know how to compare the most closest programs to that day</p> <pre><code>while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); $items = get_post_meta( $post-&gt;ID, 'audio_date', true ); the_title(); if ( is_array($items) ) { foreach ( $items as $item) : echo $item; endforeach; } } </code></pre> <p>Any ideas???? I tried also use post_type categories and make one category for each day but its not working also.</p>
[ { "answer_id": 214214, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you want this for all future users then hook into the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\"><code>user_register</code></a> event and update it there.</p>\n\n<p>Pull the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow\"><code>WP_User</code></a> using <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow\"><code>get_userdata</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow\"><code>wp_update_user</code></a> info with the new display name.</p>\n\n<pre><code>add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 );\n\nfunction wpse_20160110_user_register ( $user_id ) {\n\n // get the user data\n\n $user_info = get_userdata( $user_id );\n\n // pick our default display name\n\n $display_publicly_as = $user_info-&gt;user_login;\n\n // update the display name\n\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $display_publicly_as));\n}\n</code></pre>\n\n<p>If you want to set this every login then hook <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow\"><code>wp_login</code></a> using <a href=\"http://php.net/manual/en/reserved.constants.php#constant.php-int-max\" rel=\"nofollow\"><code>PHP_INT_MAX</code></a>.</p>\n\n<pre><code>function wpse_20160110_wp_login ( $user_login, $user ) {\n\n wp_update_user(array('ID' =&gt; $user-&gt;ID, 'display_name' =&gt; $user_login));\n\n}\n\nadd_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2);\n</code></pre>\n" }, { "answer_id": 338974, "author": "UAU", "author_id": 168963, "author_profile": "https://wordpress.stackexchange.com/users/168963", "pm_score": 1, "selected": false, "text": "<p>To programmatically set the display name both on registration and profile update, avoiding the infinite loop Betty experienced, you have to check if the display name is already set as needed.</p>\n\n<pre><code>add_action( 'user_register', 'set_login_as_displayname' );\nadd_action( 'profile_update', 'set_login_as_displayname' );\n\nfunction set_login_as_displayname( $user_id )\n{\n $data = get_userdata( $user_id );\n\n if ($data-&gt;user_login != $data-&gt;display_name) {\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $data-&gt;user_login));\n }\n}\n</code></pre>\n" } ]
2016/01/11
[ "https://wordpress.stackexchange.com/questions/214224", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86598/" ]
I have Radio with programs and they are associated to day of the weak. *Example:* 1-Program Disco Nights plays at Monday and Friday 2-Pragram Crazy weekends play only at Sunday 3-etc 4-etc **Objective:** List All the programs without repeating the ones are associated to multiple days based on current day and the next ones. If today is Saturday have to list Saturday programs them sunday, monday etc etc but can't only be listed once the same program. (THE CLOSEST ONE) How to achieve this? On the back-office I have a multi select option which allow user to select multiple days based on plugin framework it stores the meta\_value in a serialized array and can not be changed so I have to work with it. ``` a:3:{i:0;s:1:"3";i:1;s:1:"4";i:2;s:1:"6";} ``` Each day correspond to a value. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday Now the hardest part to list it on-front office. ``` $today = date('w'); $args = array( 'post_type' => 'programas', 'meta_key' => 'audio_date', 'orderby' => ' ?? closest one ??', $the_query = new WP_Query( $args ); ); ``` Remember meta key returns a serialized array like this ``` a:3:{i:0;s:1:"3";i:1;s:1:"4";i:2;s:1:"6";} ``` I don't know how to compare the most closest programs to that day ``` while ( $the_query->have_posts() ) { $the_query->the_post(); $items = get_post_meta( $post->ID, 'audio_date', true ); the_title(); if ( is_array($items) ) { foreach ( $items as $item) : echo $item; endforeach; } } ``` Any ideas???? I tried also use post\_type categories and make one category for each day but its not working also.
If you want this for all future users then hook into the [`user_register`](https://codex.wordpress.org/Plugin_API/Action_Reference/user_register) event and update it there. Pull the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) using [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) and [`wp_update_user`](https://codex.wordpress.org/Function_Reference/wp_update_user) info with the new display name. ``` add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 ); function wpse_20160110_user_register ( $user_id ) { // get the user data $user_info = get_userdata( $user_id ); // pick our default display name $display_publicly_as = $user_info->user_login; // update the display name wp_update_user( array ('ID' => $user_id, 'display_name' => $display_publicly_as)); } ``` If you want to set this every login then hook [`wp_login`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login) using [`PHP_INT_MAX`](http://php.net/manual/en/reserved.constants.php#constant.php-int-max). ``` function wpse_20160110_wp_login ( $user_login, $user ) { wp_update_user(array('ID' => $user->ID, 'display_name' => $user_login)); } add_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2); ```
214,250
<p>I have developed on theme which have integrated framework for theme options, visual composer and slider, it make the theme size nearly 11mb after compressed(zip) but while i want to upload the theme by wp-admin area it provides the upload error but if upload using ftp(live site) it works. How can i make the upload from admin area on live site? (The integration are compulsory on theme)</p>
[ { "answer_id": 214214, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you want this for all future users then hook into the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\"><code>user_register</code></a> event and update it there.</p>\n\n<p>Pull the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow\"><code>WP_User</code></a> using <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow\"><code>get_userdata</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow\"><code>wp_update_user</code></a> info with the new display name.</p>\n\n<pre><code>add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 );\n\nfunction wpse_20160110_user_register ( $user_id ) {\n\n // get the user data\n\n $user_info = get_userdata( $user_id );\n\n // pick our default display name\n\n $display_publicly_as = $user_info-&gt;user_login;\n\n // update the display name\n\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $display_publicly_as));\n}\n</code></pre>\n\n<p>If you want to set this every login then hook <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow\"><code>wp_login</code></a> using <a href=\"http://php.net/manual/en/reserved.constants.php#constant.php-int-max\" rel=\"nofollow\"><code>PHP_INT_MAX</code></a>.</p>\n\n<pre><code>function wpse_20160110_wp_login ( $user_login, $user ) {\n\n wp_update_user(array('ID' =&gt; $user-&gt;ID, 'display_name' =&gt; $user_login));\n\n}\n\nadd_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2);\n</code></pre>\n" }, { "answer_id": 338974, "author": "UAU", "author_id": 168963, "author_profile": "https://wordpress.stackexchange.com/users/168963", "pm_score": 1, "selected": false, "text": "<p>To programmatically set the display name both on registration and profile update, avoiding the infinite loop Betty experienced, you have to check if the display name is already set as needed.</p>\n\n<pre><code>add_action( 'user_register', 'set_login_as_displayname' );\nadd_action( 'profile_update', 'set_login_as_displayname' );\n\nfunction set_login_as_displayname( $user_id )\n{\n $data = get_userdata( $user_id );\n\n if ($data-&gt;user_login != $data-&gt;display_name) {\n wp_update_user( array ('ID' =&gt; $user_id, 'display_name' =&gt; $data-&gt;user_login));\n }\n}\n</code></pre>\n" } ]
2016/01/11
[ "https://wordpress.stackexchange.com/questions/214250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65450/" ]
I have developed on theme which have integrated framework for theme options, visual composer and slider, it make the theme size nearly 11mb after compressed(zip) but while i want to upload the theme by wp-admin area it provides the upload error but if upload using ftp(live site) it works. How can i make the upload from admin area on live site? (The integration are compulsory on theme)
If you want this for all future users then hook into the [`user_register`](https://codex.wordpress.org/Plugin_API/Action_Reference/user_register) event and update it there. Pull the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) using [`get_userdata`](https://codex.wordpress.org/Function_Reference/get_userdata) and [`wp_update_user`](https://codex.wordpress.org/Function_Reference/wp_update_user) info with the new display name. ``` add_action( 'user_register', 'wpse_20160110_user_register', 10, 1 ); function wpse_20160110_user_register ( $user_id ) { // get the user data $user_info = get_userdata( $user_id ); // pick our default display name $display_publicly_as = $user_info->user_login; // update the display name wp_update_user( array ('ID' => $user_id, 'display_name' => $display_publicly_as)); } ``` If you want to set this every login then hook [`wp_login`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login) using [`PHP_INT_MAX`](http://php.net/manual/en/reserved.constants.php#constant.php-int-max). ``` function wpse_20160110_wp_login ( $user_login, $user ) { wp_update_user(array('ID' => $user->ID, 'display_name' => $user_login)); } add_action('wp_login', 'wpse_20160110_wp_login', PHP_INT_MAX, 2); ```
214,254
<p>I can select posts via my custom taxonomy as explained <a href="https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters" rel="nofollow">in the codex</a>. But I am not sure, how I have to set up the tax_query if I want to get only posts which have no relation in the custom taxonomy at all. Any suggestion? </p>
[ { "answer_id": 214255, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>The only way is to get all the terms and exclude posts which belongs to those terms</p>\n\n<pre><code>$taxonomy = 'my_tax';\n$terms = get_terms( \n $taxonomy,\n ['fields' =&gt; 'ids'] // Get only IDS\n);\n\n// Setup your query args \n$args = [\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $terms,\n 'operator' =&gt; 'NOT IN' // Skip posts belonging to the passed terms\n ]\n ],\n // any other args\n];\n$q = new WP_Query( $args );\n</code></pre>\n\n<p>You would want to make sure that you actually have terms and not an empty array or a <code>WP_Error</code> object as this might lead to unexpected output </p>\n" }, { "answer_id": 214261, "author": "Paflow", "author_id": 34176, "author_profile": "https://wordpress.stackexchange.com/users/34176", "pm_score": 4, "selected": true, "text": "<p>I have found an answer by myself, for those landing here by google:</p>\n\n<pre><code>$taxq = array(\n array(\n 'taxonomy' =&gt; 'story_lng',\n 'field' =&gt; 'id',\n 'operator' =&gt; 'NOT EXISTS',\n )\n);\n</code></pre>\n\n<p>That results in</p>\n\n<pre><code>AND (NOT EXISTS( SELECT \n 1 \nFROM \n wp_term_relationships \n INNER JOIN \n wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id \nWHERE \n wp_term_taxonomy.taxonomy = 'story_lng' \n AND wp_term_relationships.object_id = wp_posts.ID)) \nAND wp_posts.post_type = 'story' \nAND (wp_posts.post_status = 'publish' \nOR wp_posts.post_author = 1 \nAND wp_posts.post_status = 'private')\n</code></pre>\n\n<p>wich is basically the same as Pieter Goosen suggested, but merged in one query (and fewer lines of code).</p>\n" } ]
2016/01/11
[ "https://wordpress.stackexchange.com/questions/214254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34176/" ]
I can select posts via my custom taxonomy as explained [in the codex](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters). But I am not sure, how I have to set up the tax\_query if I want to get only posts which have no relation in the custom taxonomy at all. Any suggestion?
I have found an answer by myself, for those landing here by google: ``` $taxq = array( array( 'taxonomy' => 'story_lng', 'field' => 'id', 'operator' => 'NOT EXISTS', ) ); ``` That results in ``` AND (NOT EXISTS( SELECT 1 FROM wp_term_relationships INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id WHERE wp_term_taxonomy.taxonomy = 'story_lng' AND wp_term_relationships.object_id = wp_posts.ID)) AND wp_posts.post_type = 'story' AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') ``` wich is basically the same as Pieter Goosen suggested, but merged in one query (and fewer lines of code).
214,285
<p>So I am trying to display a working version of the default wordpress login form on one of my pages. There is code in the functions.php file that creates the shortcode and as far as I know it works successfully, however after submitting the form, it simply refreshes the page and doesn't redirect to the url I am specifying...can anyone see why it might not work as it should?</p> <p>This is the function I put in the functions.php file:</p> <pre><code>//Login form Shortcode add_shortcode( 'login-form', 'my_login_form_shortcode' ); /** * Displays a login form. * * @since 0.1.0 * @uses wp_login_form() Displays the login form. */ function my_login_form_shortcode( $atts, $content = null ) { $defaults = array( "redirect" =&gt; site_url( $_SERVER['REQUEST_URI'] ) ); extract(shortcode_atts($defaults, $atts)); if (!is_user_logged_in()) { $content = wp_login_form( array( 'echo' =&gt; false, 'redirect' =&gt; $redirect ) ); } return $content; } </code></pre> <p>I am then placing it in the desired page like so:</p> <pre><code>[login-form redirect="https://myurl.com"] </code></pre> <p>but instead of redirecting me to the right page, it is instead refreshing the page even though I am now successfully logged in...any ideas?</p>
[ { "answer_id": 214255, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>The only way is to get all the terms and exclude posts which belongs to those terms</p>\n\n<pre><code>$taxonomy = 'my_tax';\n$terms = get_terms( \n $taxonomy,\n ['fields' =&gt; 'ids'] // Get only IDS\n);\n\n// Setup your query args \n$args = [\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $terms,\n 'operator' =&gt; 'NOT IN' // Skip posts belonging to the passed terms\n ]\n ],\n // any other args\n];\n$q = new WP_Query( $args );\n</code></pre>\n\n<p>You would want to make sure that you actually have terms and not an empty array or a <code>WP_Error</code> object as this might lead to unexpected output </p>\n" }, { "answer_id": 214261, "author": "Paflow", "author_id": 34176, "author_profile": "https://wordpress.stackexchange.com/users/34176", "pm_score": 4, "selected": true, "text": "<p>I have found an answer by myself, for those landing here by google:</p>\n\n<pre><code>$taxq = array(\n array(\n 'taxonomy' =&gt; 'story_lng',\n 'field' =&gt; 'id',\n 'operator' =&gt; 'NOT EXISTS',\n )\n);\n</code></pre>\n\n<p>That results in</p>\n\n<pre><code>AND (NOT EXISTS( SELECT \n 1 \nFROM \n wp_term_relationships \n INNER JOIN \n wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id \nWHERE \n wp_term_taxonomy.taxonomy = 'story_lng' \n AND wp_term_relationships.object_id = wp_posts.ID)) \nAND wp_posts.post_type = 'story' \nAND (wp_posts.post_status = 'publish' \nOR wp_posts.post_author = 1 \nAND wp_posts.post_status = 'private')\n</code></pre>\n\n<p>wich is basically the same as Pieter Goosen suggested, but merged in one query (and fewer lines of code).</p>\n" } ]
2016/01/11
[ "https://wordpress.stackexchange.com/questions/214285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84655/" ]
So I am trying to display a working version of the default wordpress login form on one of my pages. There is code in the functions.php file that creates the shortcode and as far as I know it works successfully, however after submitting the form, it simply refreshes the page and doesn't redirect to the url I am specifying...can anyone see why it might not work as it should? This is the function I put in the functions.php file: ``` //Login form Shortcode add_shortcode( 'login-form', 'my_login_form_shortcode' ); /** * Displays a login form. * * @since 0.1.0 * @uses wp_login_form() Displays the login form. */ function my_login_form_shortcode( $atts, $content = null ) { $defaults = array( "redirect" => site_url( $_SERVER['REQUEST_URI'] ) ); extract(shortcode_atts($defaults, $atts)); if (!is_user_logged_in()) { $content = wp_login_form( array( 'echo' => false, 'redirect' => $redirect ) ); } return $content; } ``` I am then placing it in the desired page like so: ``` [login-form redirect="https://myurl.com"] ``` but instead of redirecting me to the right page, it is instead refreshing the page even though I am now successfully logged in...any ideas?
I have found an answer by myself, for those landing here by google: ``` $taxq = array( array( 'taxonomy' => 'story_lng', 'field' => 'id', 'operator' => 'NOT EXISTS', ) ); ``` That results in ``` AND (NOT EXISTS( SELECT 1 FROM wp_term_relationships INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id WHERE wp_term_taxonomy.taxonomy = 'story_lng' AND wp_term_relationships.object_id = wp_posts.ID)) AND wp_posts.post_type = 'story' AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') ``` wich is basically the same as Pieter Goosen suggested, but merged in one query (and fewer lines of code).
214,291
<p>All theme dev who follows the wp guidelines properly, now uses ability of default wp customizer to customize their themes, instead of making a different theme option section the admin panel.</p> <p>But what I was unable to figure out is that how to use shortcode within that wp customizer.</p> <p>For example: In one of the theme I saw a section in the customizer called <strong>copyright text</strong>. Now I could manually put Copyright 2016, but what I wanted to do is to take advantage of wp shortcode. So I created a simple shortcode called <strong>year</strong> to auto fetch the current year.</p> <pre><code>add_shortcode('year', function() { return date( 'Y' ); }); </code></pre> <p>But when I use <code>[year]</code> within wp customizer, it doesn't recognize the shortcode. I know there is a way to enable shortcode for <code>widget</code> area, but I was thinking if there is something similar for the wp theme customizer are too.</p> <p>Any help will be great...</p>
[ { "answer_id": 214301, "author": "setterGetter", "author_id": 8756, "author_profile": "https://wordpress.stackexchange.com/users/8756", "pm_score": 2, "selected": false, "text": "<p>wrap whatever you are outputting the shortcode in around <code>do_shortcode()</code></p>\n" }, { "answer_id": 215910, "author": "user1645213", "author_id": 81714, "author_profile": "https://wordpress.stackexchange.com/users/81714", "pm_score": 2, "selected": false, "text": "<p>@setterGetter is right, you need to wrap it with <code>do_shortcode()</code> but you need to do it where the customizer field is called not inside the field within the customizer. In your case try looking in footer.php then if you're able to find where they output the code wrap it with <code>echo do_shortcode()</code></p>\n\n<p>But that doesn't mean your shortcode will display properly, you also need to consider what type of sanitize_callback they used when they create that customizer setting. It might happen that they use some sanitize callback that will prevent your shortcode to run. </p>\n" }, { "answer_id": 257414, "author": "Richy", "author_id": 112961, "author_profile": "https://wordpress.stackexchange.com/users/112961", "pm_score": 0, "selected": false, "text": "<p>Kirki customizer plugin seems to have a type 'code' control which appears to accept shortcodes and output them out raw through the get_theme_mod()</p>\n\n<p>you will need to learn a bit of how to integrate the plugin into your theme. </p>\n" } ]
2016/01/11
[ "https://wordpress.stackexchange.com/questions/214291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50584/" ]
All theme dev who follows the wp guidelines properly, now uses ability of default wp customizer to customize their themes, instead of making a different theme option section the admin panel. But what I was unable to figure out is that how to use shortcode within that wp customizer. For example: In one of the theme I saw a section in the customizer called **copyright text**. Now I could manually put Copyright 2016, but what I wanted to do is to take advantage of wp shortcode. So I created a simple shortcode called **year** to auto fetch the current year. ``` add_shortcode('year', function() { return date( 'Y' ); }); ``` But when I use `[year]` within wp customizer, it doesn't recognize the shortcode. I know there is a way to enable shortcode for `widget` area, but I was thinking if there is something similar for the wp theme customizer are too. Any help will be great...
wrap whatever you are outputting the shortcode in around `do_shortcode()`
214,302
<p>I recently had to script the adding of a number of roles to a selection of the users in my database. In order to do so I put together a script like this:</p> <pre><code>error_reporting(E_ALL); require("../../wp-load.php"); $source_file = 'role_source'; if(($source_handle = fopen($source_file, "r")) !== false) { while(($row = fgetcsv($source_handle)) !== false) { if(count($row) &gt; 2) { if(($user = get_user_by('id', $row[1])) !== false) { for($i = 2; $i &lt; count($row); $i++) { if(!$user-&gt;has_cap($row[$i])) { $user-&gt;add_role($row[$i]); } } } } } fclose($source_handle); } </code></pre> <p>This runs against source data that looks like this:</p> <pre><code>[email protected],2,role-slug-1,role-slug-2 </code></pre> <p>And serves to add each of the listed roles that the user doesn't already have to their set. Thing is, it doesn't quite work. If I look in the <code>wp_usermeta</code> table, at the <code>wp_capabilities</code> row I can see the roles listed correctly, and all subsequent calls to <code>WP_User-&gt;has_cap(&lt;role name&gt;)</code> return true, but they're the only things that act as if that user has that role. Calling <code>current_user_can()</code> returns false, and any of the plugins that let you manage users and grant them multiple roles deny that this user has those capabilities. Am I missing something here? From the documentation it looks like calling <code>WP_User-&gt;add_role()</code> should be all I need to do.</p>
[ { "answer_id": 214501, "author": "Saikat", "author_id": 28168, "author_profile": "https://wordpress.stackexchange.com/users/28168", "pm_score": 1, "selected": false, "text": "<p>I am not sure why you have written codes this way to add user role. And <code>wp_usermeta</code> table does not contain capabilities. It holds only roles assigned to that specific user. Capabilities are stored into <code>wp_options</code> table.</p>\n\n<p>To add role into Wordpress, just use <code>add_role()</code> function. <a href=\"https://codex.wordpress.org/Function_Reference/add_role\" rel=\"nofollow noreferrer\">Here</a> is the documentation. If you want to remove/change any user's role, you can use <code>remove_role()</code> then <code>add_role()</code> or simply <code>set_role()</code> method of <code>WP_User</code> class. <a href=\"https://wordpress.stackexchange.com/questions/4725/how-to-change-a-users-role\">Here</a> is the similar topic.</p>\n\n<p>To check user's capability, you must have to pass the role name or capability name as a parameter of <code>current_user_can()</code> function. Please see the documentation <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 214670, "author": "urka_mazurka", "author_id": 51568, "author_profile": "https://wordpress.stackexchange.com/users/51568", "pm_score": 2, "selected": false, "text": "<p>This would be best as a comment, but no reputation :)</p>\n\n<p>In the <a href=\"https://codex.wordpress.org/Function_Reference/add_role\" rel=\"nofollow\">codex</a> they say </p>\n\n<p>\"If you are defining a custom role, and adding capabilities to the role using add_role(), be aware that modifying the capabilities array and re-executing add_role() will not necessarily update the role with the new capabilities list. The add_role() function short-circuits if the role already exists in the database.\nThe workaround in this case is to precede your add_role() call with a remove_role() call that targets the role you are adding.\"</p>\n\n<p>i suspect you could be inside this short-circuit</p>\n\n<p>I say this cause it seems (just from your pasted code, it could be different) that your script could be running more than once (differently as it would do with plugin activation hook). But this is a guess. In this case, just hooking once (and making first remove_role() and then add_role() ) could do the trick</p>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214302", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54988/" ]
I recently had to script the adding of a number of roles to a selection of the users in my database. In order to do so I put together a script like this: ``` error_reporting(E_ALL); require("../../wp-load.php"); $source_file = 'role_source'; if(($source_handle = fopen($source_file, "r")) !== false) { while(($row = fgetcsv($source_handle)) !== false) { if(count($row) > 2) { if(($user = get_user_by('id', $row[1])) !== false) { for($i = 2; $i < count($row); $i++) { if(!$user->has_cap($row[$i])) { $user->add_role($row[$i]); } } } } } fclose($source_handle); } ``` This runs against source data that looks like this: ``` [email protected],2,role-slug-1,role-slug-2 ``` And serves to add each of the listed roles that the user doesn't already have to their set. Thing is, it doesn't quite work. If I look in the `wp_usermeta` table, at the `wp_capabilities` row I can see the roles listed correctly, and all subsequent calls to `WP_User->has_cap(<role name>)` return true, but they're the only things that act as if that user has that role. Calling `current_user_can()` returns false, and any of the plugins that let you manage users and grant them multiple roles deny that this user has those capabilities. Am I missing something here? From the documentation it looks like calling `WP_User->add_role()` should be all I need to do.
This would be best as a comment, but no reputation :) In the [codex](https://codex.wordpress.org/Function_Reference/add_role) they say "If you are defining a custom role, and adding capabilities to the role using add\_role(), be aware that modifying the capabilities array and re-executing add\_role() will not necessarily update the role with the new capabilities list. The add\_role() function short-circuits if the role already exists in the database. The workaround in this case is to precede your add\_role() call with a remove\_role() call that targets the role you are adding." i suspect you could be inside this short-circuit I say this cause it seems (just from your pasted code, it could be different) that your script could be running more than once (differently as it would do with plugin activation hook). But this is a guess. In this case, just hooking once (and making first remove\_role() and then add\_role() ) could do the trick
214,333
<p>I'm developing a plugin that relies pretty heavily on AJAX calls. It works well in a single-install version of WordPress, but when I ported it into a Network WP my AJAX functions stopped working (always return 0).</p> <p>Simplified, my plugin setup looks like this:</p> <pre><code>// plugin.php /* Plugin Name: My plugin */ defined( 'ABSPATH' ) or die( 'No direct access.' ); add_action("wp_ajax_test_ajax", "test_ajax"); add_action("wp_ajax_nopriv_test_ajax", "test_ajax"); function test_ajax() { echo "Works"; die(); } add_action( 'wp_enqueue_scripts', 'cms_load_head_scripts2' ); function cms_load_head_scripts2() { $path = get_plugin_path(); wp_enqueue_script('cmsAJAX', $path . 'js/script.js', array('jquery'), '1.98' ); wp_localize_script( 'cmsAJAX', 'myAjax', array( 'ajaxurl' =&gt; get_admin_ajax_path()) ); } // script.js (function($) { $(document).ready( function(){ $.ajax({ type : "post", dataType : "html", url : myAjax.ajaxurl, data : { 'action' : 'test_ajax' }, success : function(response) { console.log( "success", response ); }, error : function(xhr, ajaxOptions, thrownError) { } }); </code></pre> <p>The plugin otherwise works as expected; content loads, functions run etc. It's just the wp_ajax_ actions that don't run.</p> <p>Through testing, I've determined <strong>when I place my <code>add_actions('wp_ajax_</code> inside the theme's functions.php file, the calls work as expected</strong> (even with the ajax call still in the plugin file). I do need them all to be in the plugin though.</p> <p>I followed admin-ajax.php through and everything is functioning correctly up through the <code>do_action('wp_ajax_</code> call - no errors here, it just doesn't run my <code>test_ajax</code> action/function.</p> <p>After writing this I've figured out that the AJAX calls works perfectly in the plugin <strong>if the plugin is activated across the entire network</strong>. It'd certainly be possible to only activate this plugin on on or two of the network sites individually though, so I'm still trying to figure out what's going wrong with these ajax calls in a single-site-of-a-network-site plugin.</p> <p><strong>Also</strong></p> <p>Here's the two custom <code>get_</code> functions I used above, they simply return the corresponding paths.</p> <pre><code>function get_plugin_path(){ return plugin_dir_url(__FILE__); } function get_admin_ajax_path(){ return "http://domain.com/wp-admin/admin-ajax.php"; } </code></pre>
[ { "answer_id": 283066, "author": "mj_azani", "author_id": 98670, "author_profile": "https://wordpress.stackexchange.com/users/98670", "pm_score": 1, "selected": false, "text": "<p>Instead of using <code>get_admin_ajax_path()</code> use <code>self_admin_url( 'admin-ajax.php' )</code> which retrieves the URL to the ajax address for either the current site or the network. </p>\n" }, { "answer_id": 332495, "author": "Jose", "author_id": 147484, "author_profile": "https://wordpress.stackexchange.com/users/147484", "pm_score": 0, "selected": false, "text": "<p>If you have a multisite installation, better to use the inbuilt WordPress core function <a href=\"https://codex.wordpress.org/Function_Reference/network_admin_url\" rel=\"nofollow noreferrer\">network_admin_url</a> to retrieve the admin-ajax.php url</p>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31367/" ]
I'm developing a plugin that relies pretty heavily on AJAX calls. It works well in a single-install version of WordPress, but when I ported it into a Network WP my AJAX functions stopped working (always return 0). Simplified, my plugin setup looks like this: ``` // plugin.php /* Plugin Name: My plugin */ defined( 'ABSPATH' ) or die( 'No direct access.' ); add_action("wp_ajax_test_ajax", "test_ajax"); add_action("wp_ajax_nopriv_test_ajax", "test_ajax"); function test_ajax() { echo "Works"; die(); } add_action( 'wp_enqueue_scripts', 'cms_load_head_scripts2' ); function cms_load_head_scripts2() { $path = get_plugin_path(); wp_enqueue_script('cmsAJAX', $path . 'js/script.js', array('jquery'), '1.98' ); wp_localize_script( 'cmsAJAX', 'myAjax', array( 'ajaxurl' => get_admin_ajax_path()) ); } // script.js (function($) { $(document).ready( function(){ $.ajax({ type : "post", dataType : "html", url : myAjax.ajaxurl, data : { 'action' : 'test_ajax' }, success : function(response) { console.log( "success", response ); }, error : function(xhr, ajaxOptions, thrownError) { } }); ``` The plugin otherwise works as expected; content loads, functions run etc. It's just the wp\_ajax\_ actions that don't run. Through testing, I've determined **when I place my `add_actions('wp_ajax_` inside the theme's functions.php file, the calls work as expected** (even with the ajax call still in the plugin file). I do need them all to be in the plugin though. I followed admin-ajax.php through and everything is functioning correctly up through the `do_action('wp_ajax_` call - no errors here, it just doesn't run my `test_ajax` action/function. After writing this I've figured out that the AJAX calls works perfectly in the plugin **if the plugin is activated across the entire network**. It'd certainly be possible to only activate this plugin on on or two of the network sites individually though, so I'm still trying to figure out what's going wrong with these ajax calls in a single-site-of-a-network-site plugin. **Also** Here's the two custom `get_` functions I used above, they simply return the corresponding paths. ``` function get_plugin_path(){ return plugin_dir_url(__FILE__); } function get_admin_ajax_path(){ return "http://domain.com/wp-admin/admin-ajax.php"; } ```
Instead of using `get_admin_ajax_path()` use `self_admin_url( 'admin-ajax.php' )` which retrieves the URL to the ajax address for either the current site or the network.
214,351
<p>I am developing a custom theme with custom post types involved. Custom post types have been defined via plugin 'Pods' (<a href="http://pods.io" rel="nofollow">http://pods.io</a>).</p> <p>When writing a category.php, I realized, that the standard loop does not retrieve custom post types (CPT) posts which belong to a certain category. Is that right? If not, are there any template tags available to render CPT posts of a specific category?</p> <p>Or is the right way to rather retrieve CPT posts via WP_Query?</p>
[ { "answer_id": 214398, "author": "terminator", "author_id": 55034, "author_profile": "https://wordpress.stackexchange.com/users/55034", "pm_score": 0, "selected": false, "text": "<p>You need to use <code>taxonomy.php</code> instead of category.php </p>\n\n<p>Give little reading to template heirarchy on <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n\n<p>All your custom posts will use <code>taxonomy.php</code> if you have some custom taxonomy defined. </p>\n\n<p>For eg: lets suppose there are two taxonomies i.e <code>tax1 &amp; tax2</code></p>\n\n<p>If you want the same template for both taxonomies then go with <code>taxonomy.php</code></p>\n\n<p>But if you want different templates for <code>tax1 &amp; tax2</code> then use </p>\n\n<p><code>taxonomy-tax1.php</code> &amp; <code>taxonomy-tax2.php</code> accordingly</p>\n\n<p>I hope i was able to clear out few things for you .</p>\n\n<p>All the best</p>\n" }, { "answer_id": 214724, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>Custom post types are by default excluded from the main query except on taxonomy pages and custom post type archives. </p>\n\n<p>You can simply use <code>pre_get_posts</code> to correctly alter the main query (<em>alter the query variables before the SQL query is build and executed</em>) to your needs.</p>\n\n<p>Just a few notes on <code>pre_get_posts</code></p>\n\n<ul>\n<li><p><code>pre_get_posts</code> runs front end and back end queries, so it is very important to do the <code>is_admin()</code> check for queries only meant to run front end or back end</p></li>\n<li><p><code>pre_get_posts</code> alters all custom instances of <code>WP_Query</code>, <code>get_posts()</code> (<em>which uses <code>WP_Query</code></em>) and the main query (<em>which also uses <code>WP_Query</code></em>). You would want to use the <code>is_main_query()</code> check to specifically only alter the main query.</p></li>\n</ul>\n\n<p>You can do the following in a plugin or your theme's functions.php</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target front end queries\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n &amp;&amp; $q-&gt;is_category() // Only target category archives\n ) {\n $q-&gt;set( 'post_type', ['post', 'custom_post_type'] ); // Adjust as needed\n }\n)};\n</code></pre>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63707/" ]
I am developing a custom theme with custom post types involved. Custom post types have been defined via plugin 'Pods' (<http://pods.io>). When writing a category.php, I realized, that the standard loop does not retrieve custom post types (CPT) posts which belong to a certain category. Is that right? If not, are there any template tags available to render CPT posts of a specific category? Or is the right way to rather retrieve CPT posts via WP\_Query?
Custom post types are by default excluded from the main query except on taxonomy pages and custom post type archives. You can simply use `pre_get_posts` to correctly alter the main query (*alter the query variables before the SQL query is build and executed*) to your needs. Just a few notes on `pre_get_posts` * `pre_get_posts` runs front end and back end queries, so it is very important to do the `is_admin()` check for queries only meant to run front end or back end * `pre_get_posts` alters all custom instances of `WP_Query`, `get_posts()` (*which uses `WP_Query`*) and the main query (*which also uses `WP_Query`*). You would want to use the `is_main_query()` check to specifically only alter the main query. You can do the following in a plugin or your theme's functions.php ``` add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() // Only target front end queries && $q->is_main_query() // Only target the main query && $q->is_category() // Only target category archives ) { $q->set( 'post_type', ['post', 'custom_post_type'] ); // Adjust as needed } )}; ```
214,370
<p>The append result is 0, instead of a list with the title ass a link. If I check this locally (<a href="http://localhost/wordpress/wp-admin/admin-ajax.php?action=lateral_fluid" rel="nofollow">http://localhost/wordpress/wp-admin/admin-ajax.php?action=lateral_fluid</a>), I get the titles ass a link. I don't know why I get the appended 0. What am I missing?</p> <p>FUNCTIONS.PHP</p> <pre><code>// Your actual AJAX script wp_enqueue_script('lateral-fluid', get_template_directory_uri().'/js/lateral-fluid-ajax.js', array('jquery')); // This will localize the link for the ajax url to your 'my-script' js file (above). You can retreive it in 'lateral-fluid.js' with 'lateral-fluid.ajaxurl' wp_localize_script( 'lateral-fluid', 'ajaxFluid', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); </code></pre> <p>PHP FILE</p> <pre><code>add_action( 'wp_ajax_nopriv_lateral_fluid', 'my_lateral_fluid' ); add_action( 'wp_ajax_lateral_fluid', 'my_lateral_fluid' ); function my_lateral_fluid() { $args = array( "post_type" =&gt; "portfolio", "posts_per_page" =&gt; -1 ); $posts_array = get_posts($args); echo '&lt;nav role="navigation"&gt;'; echo '&lt;h2&gt;Latest News&lt;/h2&gt;'; echo '&lt;ul&gt;'; foreach ($posts_array as $post): setup_postdata($post); echo '&lt;li&gt;&lt;a class="' . esc_attr("side-section__link") . '" href="' . esc_attr(get_page_link($post-&gt;ID)) . '"&gt;' . $post-&gt;post_title . '&lt;/a&gt;'; endforeach; echo '&lt;/ul&gt;'; echo '&lt;/nav&gt;'; wp_die(); } </code></pre> <p>JS FILE</p> <pre><code>jQuery.ajax({ type: 'get', url: ajaxFluid.ajaxurl, data: { action: 'my_lateral_fluid', // the PHP function to run }, success: function(data, textStatus, XMLHttpRequest) { jQuery('#portfolio').html(''); // empty an element jQuery('#portfolio').append(data); // put our list of links into it }, error: function(XMLHttpRequest, textStatus, errorThrown) { if(typeof console === "undefined") { console = { log: function() { }, debug: function() { }, }; } if (XMLHttpRequest.status == 404) { console.log('Element not found.'); } else { console.log('Error: ' + errorThrown); } } }); </code></pre>
[ { "answer_id": 214376, "author": "urka_mazurka", "author_id": 51568, "author_profile": "https://wordpress.stackexchange.com/users/51568", "pm_score": 1, "selected": false, "text": "<p>The codex says here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\">that</a> The wp_ajax_ hook follows the format \"wp_ajax_$youraction\", where $youraction is your AJAX request's 'action' property.</p>\n\n<p>I suppose in your js file you should go for:</p>\n\n<pre><code>data: {\n action: 'lateral_fluid', // the $action to run\n }\n</code></pre>\n" }, { "answer_id": 214377, "author": "Pablo Levin", "author_id": 84865, "author_profile": "https://wordpress.stackexchange.com/users/84865", "pm_score": 1, "selected": false, "text": "<p>This was wrong:</p>\n\n<p>Replace this:</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_lateral_fluid', 'my_lateral_fluid' );\nadd_action( 'wp_ajax_lateral_fluid', 'my_lateral_fluid' );\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_my_lateral_fluid', 'my_lateral_fluid' );\nadd_action( 'wp_ajax_my_lateral_fluid', 'my_lateral_fluid' );\n</code></pre>\n" }, { "answer_id": 308315, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 0, "selected": false, "text": "<p>The <code>action</code> parameter in data array is NOT the function to run, it's the action where you hook your function. So, basically changing </p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_lateral_fluid', 'my_lateral_fluid' );\nadd_action( 'wp_ajax_lateral_fluid', 'my_lateral_fluid' ); \n</code></pre>\n\n<p>to </p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_my_lateral_fluid', 'my_lateral_fluid' );\nadd_action( 'wp_ajax_my_lateral_fluid', 'my_lateral_fluid' ); \n</code></pre>\n\n<p>Will do the trick. <strong>NOTE</strong> the change in the hook names. For more information on how ajax works in WordPress please check <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84865/" ]
The append result is 0, instead of a list with the title ass a link. If I check this locally (<http://localhost/wordpress/wp-admin/admin-ajax.php?action=lateral_fluid>), I get the titles ass a link. I don't know why I get the appended 0. What am I missing? FUNCTIONS.PHP ``` // Your actual AJAX script wp_enqueue_script('lateral-fluid', get_template_directory_uri().'/js/lateral-fluid-ajax.js', array('jquery')); // This will localize the link for the ajax url to your 'my-script' js file (above). You can retreive it in 'lateral-fluid.js' with 'lateral-fluid.ajaxurl' wp_localize_script( 'lateral-fluid', 'ajaxFluid', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); ``` PHP FILE ``` add_action( 'wp_ajax_nopriv_lateral_fluid', 'my_lateral_fluid' ); add_action( 'wp_ajax_lateral_fluid', 'my_lateral_fluid' ); function my_lateral_fluid() { $args = array( "post_type" => "portfolio", "posts_per_page" => -1 ); $posts_array = get_posts($args); echo '<nav role="navigation">'; echo '<h2>Latest News</h2>'; echo '<ul>'; foreach ($posts_array as $post): setup_postdata($post); echo '<li><a class="' . esc_attr("side-section__link") . '" href="' . esc_attr(get_page_link($post->ID)) . '">' . $post->post_title . '</a>'; endforeach; echo '</ul>'; echo '</nav>'; wp_die(); } ``` JS FILE ``` jQuery.ajax({ type: 'get', url: ajaxFluid.ajaxurl, data: { action: 'my_lateral_fluid', // the PHP function to run }, success: function(data, textStatus, XMLHttpRequest) { jQuery('#portfolio').html(''); // empty an element jQuery('#portfolio').append(data); // put our list of links into it }, error: function(XMLHttpRequest, textStatus, errorThrown) { if(typeof console === "undefined") { console = { log: function() { }, debug: function() { }, }; } if (XMLHttpRequest.status == 404) { console.log('Element not found.'); } else { console.log('Error: ' + errorThrown); } } }); ```
The codex says here [that](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) The wp\_ajax\_ hook follows the format "wp\_ajax\_$youraction", where $youraction is your AJAX request's 'action' property. I suppose in your js file you should go for: ``` data: { action: 'lateral_fluid', // the $action to run } ```
214,384
<p>I'm trying to include my parents themes functions.php include into my child theme functions.php.</p> <p>I have a standard setup for a functions.php in my parent.</p> <p>This is what i have in my child themes functions.php</p> <pre><code>&lt;?php /** * Base functions and definitions. * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package Base */ locate_template( array( '/vendor/autoload.php', '/functions.php' ), true, false ); </code></pre> <p>the autoload.php file contains things like timber framework which works, it it doesn't seem to bring in the parent functions.php</p> <p>Any help would be much appreciated.</p> <p>Thanks Jake.</p>
[ { "answer_id": 240445, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>As per @toscho's comments, the parent theme is always loaded after the child theme's. In this way, if you want to override a parent theme's function you can rewrite it and the original will be ignored, whereas any functions you didn't rewrite are loaded and available.</p>\n\n<p>There is no need to do it the other way around. If you are just loading additional files and defining actions and filters (as you should) there is no reason to worry about the order in which both function files are loaded, because at this point WP is just making an inventory of code to execute, not actually executing.</p>\n\n<p>So, that gives you plenty of freedom to define additional settings in your child theme's <code>functions.php</code>, even if the parent's one has not been loaded yet.</p>\n" }, { "answer_id": 284685, "author": "Jesse Vlasveld", "author_id": 87884, "author_profile": "https://wordpress.stackexchange.com/users/87884", "pm_score": 0, "selected": false, "text": "<p>I'm not entirely sure what you're trying to achieve, but it sounds like you're trying to overwrite functions from your parent theme in your child theme.</p>\n\n<p>If this is the case you should make the parent function pluggable:</p>\n\n<pre><code>if ( ! function_exists( 'your_function' ) ) {\n\n function your_function() {\n }\n\n}\n</code></pre>\n\n<p>Then you are able to define a function in your child theme with the same name. \nIn this case, the child function will be used since it's loaded first, and the parent checks if the function exists.</p>\n\n<pre><code>function your_function() {\n}\n</code></pre>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214384", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54516/" ]
I'm trying to include my parents themes functions.php include into my child theme functions.php. I have a standard setup for a functions.php in my parent. This is what i have in my child themes functions.php ``` <?php /** * Base functions and definitions. * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package Base */ locate_template( array( '/vendor/autoload.php', '/functions.php' ), true, false ); ``` the autoload.php file contains things like timber framework which works, it it doesn't seem to bring in the parent functions.php Any help would be much appreciated. Thanks Jake.
As per @toscho's comments, the parent theme is always loaded after the child theme's. In this way, if you want to override a parent theme's function you can rewrite it and the original will be ignored, whereas any functions you didn't rewrite are loaded and available. There is no need to do it the other way around. If you are just loading additional files and defining actions and filters (as you should) there is no reason to worry about the order in which both function files are loaded, because at this point WP is just making an inventory of code to execute, not actually executing. So, that gives you plenty of freedom to define additional settings in your child theme's `functions.php`, even if the parent's one has not been loaded yet.
214,388
<p>I am trying to produce a list of posts and display a report which shows both some meta_values for each post, but also a list of all categories to which each post is attached. </p> <p>I am using the nifty Exports and Reports module to format the results of my query, and the data I am trying to pull out is a list of Woocommerce products. </p> <p>I got as far as:</p> <pre><code>SELECT wp_posts.ID, wp_posts.post_title AS Product, m2.meta_value AS _retail_price, m4.meta_value AS _stock FROM wp_posts LEFT JOIN wp_postmeta AS m2 ON m2.post_id = wp_posts.ID AND m2.meta_key = '_price' LEFT JOIN wp_postmeta AS m4 ON m4.post_id = wp_posts.ID AND m4.meta_key = '_stock' WHERE wp_posts.post_type IN ('product', 'product_variation') AND wp_posts.post_status = 'publish' ORDER BY wp_posts.ID ASC </code></pre> <p>That works, I get a list of posts (products) with the relevant meta values populated. </p> <p>But I would now like to add a list of categories that each post is listed in, ideally with a column per category. But each post is in multiple categories, and I am stumped as to how to pull out the categories for each one. </p> <p>I did: </p> <pre><code>SELECT wp_posts.ID AS ProdId, wp_posts.post_title AS Product, m1.meta_value AS _retail_price, m2.meta_value AS _stock, wp_term_relationships.*, wp_terms.* FROM wp_posts, wp_term_relationships, wp_terms LEFT JOIN wp_postmeta AS m1 ON m1.post_id = wp_posts.ID AND m1.meta_key = '_price' LEFT JOIN wp_postmeta AS m2 ON m2.post_id = wp_posts.ID AND m2.meta_key = '_stock' LEFT JOIN wp_posts posts2 ON wp_term_relationships.object_id = wp_posts.ID LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id LEFT JOIN wp_terms terms2 ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id WHERE wp_posts.post_type IN ('product', 'product_variation') AND wp_posts.post_status = 'publish' AND taxonomy = 'product_cat' ORDER BY wp_posts.ID ASC </code></pre> <p>but that gives me an #1054 - Unknown column 'wp_posts.ID' in 'on clause' and I think I have my joins in a tangle :-( </p>
[ { "answer_id": 215176, "author": "Sterling Hamilton", "author_id": 10075, "author_profile": "https://wordpress.stackexchange.com/users/10075", "pm_score": 2, "selected": false, "text": "<p><strong>cracks knuckles</strong></p>\n\n<p>Alright -- so first thing is first.</p>\n\n<h1>Working w/ WordPress Databases</h1>\n\n<ol>\n<li>Read this: <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/wpdb</a></li>\n<li>Avoid write SQL statements outside of the $wpdb object.</li>\n</ol>\n\n<p>Avoid writing SQL statements like <code>wp_users</code> instead do this:</p>\n\n<pre><code>$users = $wpdb-&gt;get_results( \"SELECT FROM $wpdb-&gt;users\" );\n</code></pre>\n\n<p>This will help if you ever change the database prefix.</p>\n\n<h1>Doing this outside of WPDB</h1>\n\n<p>Your pseudo code could read like this:</p>\n\n<p>GET POSTS > GET EACH POSTS CATEGORIES > GET EACH POSTS META FIELD NAMED X.</p>\n\n<p>Let's store all the things in something called ... <code>$all_the_things = array();</code></p>\n\n<p>Getting posts: </p>\n\n<pre><code>&lt;?php\n $arguments = array(\n 'posts_per_page' =&gt; -1, // This is a bad idea if you run this on trafficked pages. \n 'post_type' =&gt; array('product', 'product_variation'),\n 'post_status' =&gt; 'publish'\n );\n $query = WP_Query( $arguments );\n?&gt;\n</code></pre>\n\n<p>Now you need to loop:</p>\n\n<pre><code>&lt;?php\n while( $query-&gt;have_posts() ) {\n $categories = get_the_category();\n $price = get_post_meta( get_the_ID(), '_price' ); ?&gt;\n $stock = get_post_meta( get_the_ID(), '_stock' ); ?&gt;\n $all_the_things[get_the_ID()] = array($categories, $price, $stock);\n }\n?&gt;\n</code></pre>\n\n<hr>\n\n<p>Now if you want... I can do this within SQL -- but it's not ideal. You cannot bank on the database structure staying the exact same, or that filters that should be ran being executed on data and so on. Things can get complicated.</p>\n\n<p>Let me know how this works out and I can provide more detail if needed.</p>\n" }, { "answer_id": 215184, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 3, "selected": true, "text": "<p>SQL-wise, you only need to join to the wp_posts table once. Joining to the terms stuff will give you multiple rows, so it's probably easiest to group these and then use GROUP_CONCAT() to flatten the terms into a comma-separated string (<strong>updated to use LEFT joins</strong>):</p>\n\n<pre><code>global $wpdb;\n$sql = $wpdb-&gt;prepare(\n 'SELECT p.ID, p.post_title AS Product, pm1.meta_value AS _retail_price, pm2.meta_value AS _stock'\n . ', GROUP_CONCAT(t.name ORDER BY t.name) AS Categories'\n . ' FROM ' . $wpdb-&gt;posts . ' p'\n . ' LEFT JOIN ' . $wpdb-&gt;postmeta . ' pm1 ON pm1.post_id = p.ID AND pm1.meta_key = %s'\n . ' LEFT JOIN ' . $wpdb-&gt;postmeta . ' pm2 ON pm2.post_id = p.ID AND pm2.meta_key = %s'\n . ' LEFT JOIN ' . $wpdb-&gt;term_relationships . ' AS tr ON tr.object_id = p.ID'\n . ' LEFT JOIN ' . $wpdb-&gt;term_taxonomy . ' AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = %s'\n . ' LEFT JOIN ' . $wpdb-&gt;terms . ' AS t ON tt.term_id = t.term_id'\n . ' WHERE p.post_type in (%s, %s) AND p.post_status = %s'\n . ' GROUP BY p.ID'\n . ' ORDER BY p.ID ASC'\n , '_price', '_stock', 'product_cat', 'product', 'product_variation', 'publish'\n);\n$ret = $wpdb-&gt;get_results( $sql );\n</code></pre>\n" }, { "answer_id": 215309, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 0, "selected": false, "text": "<p>You can put together a very finite query with the <code>get_posts()</code> function. I tried to understand your SQL query and define it the way I would with native WP functionality, but could have missed some details. <strong>I have no clue if this is where you are going, or if this works</strong>, but WordPress is supposed to make things easier for you. <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">Explore this page for more info</a>. Hope this gets you closer to your goal with more ease! Ideally this gets all the possible posts you need to put in columns, and you could sort the <code>$posts</code> as needed.</p>\n\n<pre><code>// Argument array for get_posts\n$args = array(\n 'post_type' =&gt; array(\n 'product',\n 'product_variation',\n ),\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array('key' =&gt; '_price'),\n array('key' =&gt; '_stock'),\n ),\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'product_cat',\n )\n )\n);\n\n// The posts delivered\n$posts = get_posts( $args );\n</code></pre>\n" } ]
2016/01/12
[ "https://wordpress.stackexchange.com/questions/214388", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37897/" ]
I am trying to produce a list of posts and display a report which shows both some meta\_values for each post, but also a list of all categories to which each post is attached. I am using the nifty Exports and Reports module to format the results of my query, and the data I am trying to pull out is a list of Woocommerce products. I got as far as: ``` SELECT wp_posts.ID, wp_posts.post_title AS Product, m2.meta_value AS _retail_price, m4.meta_value AS _stock FROM wp_posts LEFT JOIN wp_postmeta AS m2 ON m2.post_id = wp_posts.ID AND m2.meta_key = '_price' LEFT JOIN wp_postmeta AS m4 ON m4.post_id = wp_posts.ID AND m4.meta_key = '_stock' WHERE wp_posts.post_type IN ('product', 'product_variation') AND wp_posts.post_status = 'publish' ORDER BY wp_posts.ID ASC ``` That works, I get a list of posts (products) with the relevant meta values populated. But I would now like to add a list of categories that each post is listed in, ideally with a column per category. But each post is in multiple categories, and I am stumped as to how to pull out the categories for each one. I did: ``` SELECT wp_posts.ID AS ProdId, wp_posts.post_title AS Product, m1.meta_value AS _retail_price, m2.meta_value AS _stock, wp_term_relationships.*, wp_terms.* FROM wp_posts, wp_term_relationships, wp_terms LEFT JOIN wp_postmeta AS m1 ON m1.post_id = wp_posts.ID AND m1.meta_key = '_price' LEFT JOIN wp_postmeta AS m2 ON m2.post_id = wp_posts.ID AND m2.meta_key = '_stock' LEFT JOIN wp_posts posts2 ON wp_term_relationships.object_id = wp_posts.ID LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id LEFT JOIN wp_terms terms2 ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id WHERE wp_posts.post_type IN ('product', 'product_variation') AND wp_posts.post_status = 'publish' AND taxonomy = 'product_cat' ORDER BY wp_posts.ID ASC ``` but that gives me an #1054 - Unknown column 'wp\_posts.ID' in 'on clause' and I think I have my joins in a tangle :-(
SQL-wise, you only need to join to the wp\_posts table once. Joining to the terms stuff will give you multiple rows, so it's probably easiest to group these and then use GROUP\_CONCAT() to flatten the terms into a comma-separated string (**updated to use LEFT joins**): ``` global $wpdb; $sql = $wpdb->prepare( 'SELECT p.ID, p.post_title AS Product, pm1.meta_value AS _retail_price, pm2.meta_value AS _stock' . ', GROUP_CONCAT(t.name ORDER BY t.name) AS Categories' . ' FROM ' . $wpdb->posts . ' p' . ' LEFT JOIN ' . $wpdb->postmeta . ' pm1 ON pm1.post_id = p.ID AND pm1.meta_key = %s' . ' LEFT JOIN ' . $wpdb->postmeta . ' pm2 ON pm2.post_id = p.ID AND pm2.meta_key = %s' . ' LEFT JOIN ' . $wpdb->term_relationships . ' AS tr ON tr.object_id = p.ID' . ' LEFT JOIN ' . $wpdb->term_taxonomy . ' AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = %s' . ' LEFT JOIN ' . $wpdb->terms . ' AS t ON tt.term_id = t.term_id' . ' WHERE p.post_type in (%s, %s) AND p.post_status = %s' . ' GROUP BY p.ID' . ' ORDER BY p.ID ASC' , '_price', '_stock', 'product_cat', 'product', 'product_variation', 'publish' ); $ret = $wpdb->get_results( $sql ); ```
214,395
<p>I'm trying to tailor an RSS feed so that it can be used to generate a newsletter via Digesto/Marketo. I've tried adding a custom RSS template to the site's theme - and it worked - but I can't seem to lose the site link that is added below each post. The post links are really all we need.</p> <p>The link is being inserting just inside of the closing description tag. The code in my template that adds the description is:</p> <pre><code>&lt;description&gt;&lt;![CDATA[&lt;?php the_excerpt_rss(); ?&gt;]]&gt;&lt;/description&gt; </code></pre> <p>My RSS template is a variation of wp-includes/feed-rss2.php, which uses the same code snippet.</p> <p>There doesn't seem to be a way to edit the output of the_excerpt_rss - if that's even the culprit. Any help would be greatly appreciated!</p>
[ { "answer_id": 214397, "author": "terminator", "author_id": 55034, "author_profile": "https://wordpress.stackexchange.com/users/55034", "pm_score": 0, "selected": false, "text": "<p>you can use the filter to edit the output of the_excerpt_rss()</p>\n\n<p>May be the following code will help you, not sure but give it a try</p>\n\n<pre><code>function removersslink( $content ) {\n $content = '&lt;p&gt;' . $content. '&lt;/p&gt;';\n return $content;\n}\nadd_filter( 'the_excerpt_rss', 'removersslink' );\n</code></pre>\n" }, { "answer_id": 214922, "author": "heytricia", "author_id": 57514, "author_profile": "https://wordpress.stackexchange.com/users/57514", "pm_score": 2, "selected": false, "text": "<p>After doing a search of all folders in the site for \"the_excerpt_rss\", I found a Yoast plugin file that was adding the link to each post item. In the end it was as simple as accessing a field via the dashboard > SEO > advanced and clicking the RSS tab. I emptied the field \"Content to put after each post in the feed\", refreshed the feed, and the link was gone. I can't believe it was as simple as that... </p>\n" } ]
2016/01/13
[ "https://wordpress.stackexchange.com/questions/214395", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57514/" ]
I'm trying to tailor an RSS feed so that it can be used to generate a newsletter via Digesto/Marketo. I've tried adding a custom RSS template to the site's theme - and it worked - but I can't seem to lose the site link that is added below each post. The post links are really all we need. The link is being inserting just inside of the closing description tag. The code in my template that adds the description is: ``` <description><![CDATA[<?php the_excerpt_rss(); ?>]]></description> ``` My RSS template is a variation of wp-includes/feed-rss2.php, which uses the same code snippet. There doesn't seem to be a way to edit the output of the\_excerpt\_rss - if that's even the culprit. Any help would be greatly appreciated!
After doing a search of all folders in the site for "the\_excerpt\_rss", I found a Yoast plugin file that was adding the link to each post item. In the end it was as simple as accessing a field via the dashboard > SEO > advanced and clicking the RSS tab. I emptied the field "Content to put after each post in the feed", refreshed the feed, and the link was gone. I can't believe it was as simple as that...
214,443
<p>I followed the common advise to use wp_head() in header.php and wp_enqueue_scripts() instead of hard linking css and js files in header.php.</p> <p>However, I realized that wp_head() outputs lots of stuff I'm not sure if I really want it to be there. E.g. there is some CSS stylesheet stuff dealing with emotiis and smileys ... for whatever reason.</p> <p>//UPDATE</p> <p>Despite my writing above, I am pretty aware of what parts of wp_head() I want to have in my HTML Head section. </p> <p>//UPDATE II</p> <p>I am developing my own theme and I have only a single plugin in use which is Pods.io.</p> <p>I did some research but found solutions only that suggest to subsequently alter wp_head() output via output buffering methods (see <a href="https://wordpress.stackexchange.com/questions/75130/remove-an-action-from-an-external-class/75168#75168">Remove an action from an external Class</a>). To me, that appears to be a rather dirty solution.</p> <p>Hence, my question is, how can I exactly define the default output of wp_head()? What hooks are available to trigger certain output parts? Pls note, I am aware of how to <em>add</em> content to wp_head() via hooks but not how to <em>precisely remove</em> unwanted output.</p>
[ { "answer_id": 214446, "author": "panos", "author_id": 33435, "author_profile": "https://wordpress.stackexchange.com/users/33435", "pm_score": 0, "selected": false, "text": "<p>The wp_head hook is simply a hook.</p>\n\n<p>Themes and plugins use this hook to add stuff they need in the header, like css and js. Very often they enqueue unnecessary scripts in every page instead of limiting them in specific pages.</p>\n\n<p>So you can either check your plugins and theme where it enques the scripts and edit them or use the remove_action to remove them.</p>\n" }, { "answer_id": 214447, "author": "Mayur Chauhan", "author_id": 85001, "author_profile": "https://wordpress.stackexchange.com/users/85001", "pm_score": 0, "selected": false, "text": "<p>You are not suppose to remove default WordPress styles (which are included from wp-includes, they are all there for some reasons). </p>\n\n<p>You can remove styles which are included from theme by creating child theme.</p>\n" }, { "answer_id": 214449, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p><a href=\"https://github.com/WordPress/WordPress/blob/9fb5c540bb7888faec05670bd70a93e0593dcfb1/wp-includes/default-filters.php#L224\" rel=\"noreferrer\">Here</a> is the current list of actions that is currently hooked by default to <code>wp_head</code></p>\n\n<p>Reposted here to avoid unnecessary opening multiple browser windows</p>\n\n<pre><code>add_action( 'wp_head', '_wp_render_title_tag', 1 );\nadd_action( 'wp_head', 'wp_enqueue_scripts', 1 );\nadd_action( 'wp_head', 'feed_links', 2 );\nadd_action( 'wp_head', 'feed_links_extra', 3 );\nadd_action( 'wp_head', 'rsd_link' );\nadd_action( 'wp_head', 'wlwmanifest_link' );\nadd_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );\nadd_action( 'wp_head', 'locale_stylesheet' );\nadd_action( 'wp_head', 'noindex', 1 );\nadd_action( 'wp_head', 'print_emoji_detection_script', 7 );\nadd_action( 'wp_head', 'wp_print_styles', 8 );\nadd_action( 'wp_head', 'wp_print_head_scripts', 9 );\nadd_action( 'wp_head', 'wp_generator' );\nadd_action( 'wp_head', 'rel_canonical' );\nadd_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );\nadd_action( 'wp_head', 'wp_site_icon', 99 );\n\nif ( isset( $_GET['replytocom'] ) )\n add_action( 'wp_head', 'wp_no_robots' );\n</code></pre>\n\n<p>You can remove any action with <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"noreferrer\"><code>remove_action()</code></a></p>\n\n<pre><code>remove_action( 'wp_head', 'wp_print_styles, 8 );\n</code></pre>\n\n<p>Just remember, an action need to be removed with the same priority it was added. </p>\n\n<p>As bonus, check <a href=\"https://wordpress.stackexchange.com/q/185577/31545\">this epic post from @ChristineCooper</a> on how to remove emojicons</p>\n\n<h2>EDIT</h2>\n\n<p>An important note here. The foillowing actions should not be removed as this causes serious issues with how stylesheets and scripts are loaded</p>\n\n<ul>\n<li><p><code>locate_stylesheet</code></p></li>\n<li><p><code>wp_print_styles</code></p></li>\n<li><p><code>wp_generator</code></p></li>\n<li><p><code>wp_enqueue_scripts</code></p></li>\n</ul>\n\n<p>If you need something specific removed, rather remove the call back function with <code>remove_action</code> or use the specific functions allocated to remove styles and scripts </p>\n" } ]
2016/01/13
[ "https://wordpress.stackexchange.com/questions/214443", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63707/" ]
I followed the common advise to use wp\_head() in header.php and wp\_enqueue\_scripts() instead of hard linking css and js files in header.php. However, I realized that wp\_head() outputs lots of stuff I'm not sure if I really want it to be there. E.g. there is some CSS stylesheet stuff dealing with emotiis and smileys ... for whatever reason. //UPDATE Despite my writing above, I am pretty aware of what parts of wp\_head() I want to have in my HTML Head section. //UPDATE II I am developing my own theme and I have only a single plugin in use which is Pods.io. I did some research but found solutions only that suggest to subsequently alter wp\_head() output via output buffering methods (see [Remove an action from an external Class](https://wordpress.stackexchange.com/questions/75130/remove-an-action-from-an-external-class/75168#75168)). To me, that appears to be a rather dirty solution. Hence, my question is, how can I exactly define the default output of wp\_head()? What hooks are available to trigger certain output parts? Pls note, I am aware of how to *add* content to wp\_head() via hooks but not how to *precisely remove* unwanted output.
[Here](https://github.com/WordPress/WordPress/blob/9fb5c540bb7888faec05670bd70a93e0593dcfb1/wp-includes/default-filters.php#L224) is the current list of actions that is currently hooked by default to `wp_head` Reposted here to avoid unnecessary opening multiple browser windows ``` add_action( 'wp_head', '_wp_render_title_tag', 1 ); add_action( 'wp_head', 'wp_enqueue_scripts', 1 ); add_action( 'wp_head', 'feed_links', 2 ); add_action( 'wp_head', 'feed_links_extra', 3 ); add_action( 'wp_head', 'rsd_link' ); add_action( 'wp_head', 'wlwmanifest_link' ); add_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); add_action( 'wp_head', 'locale_stylesheet' ); add_action( 'wp_head', 'noindex', 1 ); add_action( 'wp_head', 'print_emoji_detection_script', 7 ); add_action( 'wp_head', 'wp_print_styles', 8 ); add_action( 'wp_head', 'wp_print_head_scripts', 9 ); add_action( 'wp_head', 'wp_generator' ); add_action( 'wp_head', 'rel_canonical' ); add_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); add_action( 'wp_head', 'wp_site_icon', 99 ); if ( isset( $_GET['replytocom'] ) ) add_action( 'wp_head', 'wp_no_robots' ); ``` You can remove any action with [`remove_action()`](https://codex.wordpress.org/Function_Reference/remove_action) ``` remove_action( 'wp_head', 'wp_print_styles, 8 ); ``` Just remember, an action need to be removed with the same priority it was added. As bonus, check [this epic post from @ChristineCooper](https://wordpress.stackexchange.com/q/185577/31545) on how to remove emojicons EDIT ---- An important note here. The foillowing actions should not be removed as this causes serious issues with how stylesheets and scripts are loaded * `locate_stylesheet` * `wp_print_styles` * `wp_generator` * `wp_enqueue_scripts` If you need something specific removed, rather remove the call back function with `remove_action` or use the specific functions allocated to remove styles and scripts
214,450
<h1>Disabling Password Resets</h1> <p>I've come across numerous security hardening articles relating to various measures for disabling password resets (i.e. lost password retrieval).</p> <p><a href="https://www.google.com/search?q=wordpress+disable+lost+password" rel="nofollow">https://www.google.com/search?q=wordpress+disable+lost+password</a></p> <h1>SQL Injection</h1> <p>I've read that SQL injection can be used to obtain the user email etc. and ultimately to gain control of the site by intercepting the password reset email is automatically sent to a user.</p> <p><a href="https://hackertarget.com/attacking-wordpress/" rel="nofollow">https://hackertarget.com/attacking-wordpress/</a></p> <h1>Serious Vulnerability?</h1> <p>If I'm already protected against SQL injections (via security plugin), do I need to disable the password reset feature? Is it really a serious vulnerability?</p> <p>Brute force attacks are on the rise. I've encountered several instances myself in recent months.</p>
[ { "answer_id": 214446, "author": "panos", "author_id": 33435, "author_profile": "https://wordpress.stackexchange.com/users/33435", "pm_score": 0, "selected": false, "text": "<p>The wp_head hook is simply a hook.</p>\n\n<p>Themes and plugins use this hook to add stuff they need in the header, like css and js. Very often they enqueue unnecessary scripts in every page instead of limiting them in specific pages.</p>\n\n<p>So you can either check your plugins and theme where it enques the scripts and edit them or use the remove_action to remove them.</p>\n" }, { "answer_id": 214447, "author": "Mayur Chauhan", "author_id": 85001, "author_profile": "https://wordpress.stackexchange.com/users/85001", "pm_score": 0, "selected": false, "text": "<p>You are not suppose to remove default WordPress styles (which are included from wp-includes, they are all there for some reasons). </p>\n\n<p>You can remove styles which are included from theme by creating child theme.</p>\n" }, { "answer_id": 214449, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p><a href=\"https://github.com/WordPress/WordPress/blob/9fb5c540bb7888faec05670bd70a93e0593dcfb1/wp-includes/default-filters.php#L224\" rel=\"noreferrer\">Here</a> is the current list of actions that is currently hooked by default to <code>wp_head</code></p>\n\n<p>Reposted here to avoid unnecessary opening multiple browser windows</p>\n\n<pre><code>add_action( 'wp_head', '_wp_render_title_tag', 1 );\nadd_action( 'wp_head', 'wp_enqueue_scripts', 1 );\nadd_action( 'wp_head', 'feed_links', 2 );\nadd_action( 'wp_head', 'feed_links_extra', 3 );\nadd_action( 'wp_head', 'rsd_link' );\nadd_action( 'wp_head', 'wlwmanifest_link' );\nadd_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );\nadd_action( 'wp_head', 'locale_stylesheet' );\nadd_action( 'wp_head', 'noindex', 1 );\nadd_action( 'wp_head', 'print_emoji_detection_script', 7 );\nadd_action( 'wp_head', 'wp_print_styles', 8 );\nadd_action( 'wp_head', 'wp_print_head_scripts', 9 );\nadd_action( 'wp_head', 'wp_generator' );\nadd_action( 'wp_head', 'rel_canonical' );\nadd_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );\nadd_action( 'wp_head', 'wp_site_icon', 99 );\n\nif ( isset( $_GET['replytocom'] ) )\n add_action( 'wp_head', 'wp_no_robots' );\n</code></pre>\n\n<p>You can remove any action with <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"noreferrer\"><code>remove_action()</code></a></p>\n\n<pre><code>remove_action( 'wp_head', 'wp_print_styles, 8 );\n</code></pre>\n\n<p>Just remember, an action need to be removed with the same priority it was added. </p>\n\n<p>As bonus, check <a href=\"https://wordpress.stackexchange.com/q/185577/31545\">this epic post from @ChristineCooper</a> on how to remove emojicons</p>\n\n<h2>EDIT</h2>\n\n<p>An important note here. The foillowing actions should not be removed as this causes serious issues with how stylesheets and scripts are loaded</p>\n\n<ul>\n<li><p><code>locate_stylesheet</code></p></li>\n<li><p><code>wp_print_styles</code></p></li>\n<li><p><code>wp_generator</code></p></li>\n<li><p><code>wp_enqueue_scripts</code></p></li>\n</ul>\n\n<p>If you need something specific removed, rather remove the call back function with <code>remove_action</code> or use the specific functions allocated to remove styles and scripts </p>\n" } ]
2016/01/13
[ "https://wordpress.stackexchange.com/questions/214450", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41545/" ]
Disabling Password Resets ========================= I've come across numerous security hardening articles relating to various measures for disabling password resets (i.e. lost password retrieval). <https://www.google.com/search?q=wordpress+disable+lost+password> SQL Injection ============= I've read that SQL injection can be used to obtain the user email etc. and ultimately to gain control of the site by intercepting the password reset email is automatically sent to a user. <https://hackertarget.com/attacking-wordpress/> Serious Vulnerability? ====================== If I'm already protected against SQL injections (via security plugin), do I need to disable the password reset feature? Is it really a serious vulnerability? Brute force attacks are on the rise. I've encountered several instances myself in recent months.
[Here](https://github.com/WordPress/WordPress/blob/9fb5c540bb7888faec05670bd70a93e0593dcfb1/wp-includes/default-filters.php#L224) is the current list of actions that is currently hooked by default to `wp_head` Reposted here to avoid unnecessary opening multiple browser windows ``` add_action( 'wp_head', '_wp_render_title_tag', 1 ); add_action( 'wp_head', 'wp_enqueue_scripts', 1 ); add_action( 'wp_head', 'feed_links', 2 ); add_action( 'wp_head', 'feed_links_extra', 3 ); add_action( 'wp_head', 'rsd_link' ); add_action( 'wp_head', 'wlwmanifest_link' ); add_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); add_action( 'wp_head', 'locale_stylesheet' ); add_action( 'wp_head', 'noindex', 1 ); add_action( 'wp_head', 'print_emoji_detection_script', 7 ); add_action( 'wp_head', 'wp_print_styles', 8 ); add_action( 'wp_head', 'wp_print_head_scripts', 9 ); add_action( 'wp_head', 'wp_generator' ); add_action( 'wp_head', 'rel_canonical' ); add_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); add_action( 'wp_head', 'wp_site_icon', 99 ); if ( isset( $_GET['replytocom'] ) ) add_action( 'wp_head', 'wp_no_robots' ); ``` You can remove any action with [`remove_action()`](https://codex.wordpress.org/Function_Reference/remove_action) ``` remove_action( 'wp_head', 'wp_print_styles, 8 ); ``` Just remember, an action need to be removed with the same priority it was added. As bonus, check [this epic post from @ChristineCooper](https://wordpress.stackexchange.com/q/185577/31545) on how to remove emojicons EDIT ---- An important note here. The foillowing actions should not be removed as this causes serious issues with how stylesheets and scripts are loaded * `locate_stylesheet` * `wp_print_styles` * `wp_generator` * `wp_enqueue_scripts` If you need something specific removed, rather remove the call back function with `remove_action` or use the specific functions allocated to remove styles and scripts
214,455
<p>I added some actions to <code>wp_enqueue_scripts</code> to load my custom css and js files in the header section by using <code>wp_head();</code> right before the closing <code>&lt;/head&gt;</code> tag.</p> <pre><code>function mytheme_scripts(){ // Load our main stylesheet wp_enqueue_style( 'mytheme-css', get_template_directory_uri() . '/css/styles.min.css', false); // Load concatenated vendors JavaScript file wp_enqueue_script( 'vendors-js', get_template_directory_uri() . '/js/vendors.min.js'); // Load our main JavaScript file wp_enqueue_script( 'mytheme-js', get_template_directory_uri() . '/js/app.min.js', array( 'vendors-js' )); } add_action( 'wp_enqueue_scripts', 'mytheme_scripts', false); </code></pre> <p>While both <code>*.js</code> files are loaded in the HTML <code>&lt;head&gt;</code> section the custom <code>*.css</code> file is loaded in the footer of the page (probably triggered by <code>wp_footer()</code>). </p> <p>I have read about the fact that <code>wp_enqueue_scripts()</code> could be placed anywhere in the source code since any earlier WP version. I've also read that <code>wp_enqueue_script()</code> has a parameter <code>$in_footer</code> to control the output location. However, <code>wp_enqueue_style()</code> doesn't have such an option.</p> <p>Now, how can I have my custom stylesheet link be placed in HTML head section without hard-coding it into <code>header.php</code>?</p>
[ { "answer_id": 254889, "author": "Diego Betto", "author_id": 96955, "author_profile": "https://wordpress.stackexchange.com/users/96955", "pm_score": -1, "selected": false, "text": "<p>You can change the hook to <code>get_footer</code> so files are inserted in the footer</p>\n\n<p>try changing </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'mytheme_scripts', false);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>add_action( 'get_footer', 'mytheme_scripts', false);\n</code></pre>\n" }, { "answer_id": 374218, "author": "miftah al rasyid", "author_id": 194075, "author_profile": "https://wordpress.stackexchange.com/users/194075", "pm_score": 0, "selected": false, "text": "<p>hook into init action on your initial plugin function</p>\n<pre><code>add_action('init', array(__CLASS__, 'your_function_within_class'));\n</code></pre>\n<p>and add the function</p>\n<pre><code>public static function your_function_within_class()\n{\n \n wp_register_style('myfirstplugin-admin-css', '/wp-content/plugins/myfirstplugin/assets/style.css', false);\n \n wp_enqueue_style('myfirstplugin-admin-css');\n}\n</code></pre>\n<p>hope this help</p>\n" } ]
2016/01/13
[ "https://wordpress.stackexchange.com/questions/214455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63707/" ]
I added some actions to `wp_enqueue_scripts` to load my custom css and js files in the header section by using `wp_head();` right before the closing `</head>` tag. ``` function mytheme_scripts(){ // Load our main stylesheet wp_enqueue_style( 'mytheme-css', get_template_directory_uri() . '/css/styles.min.css', false); // Load concatenated vendors JavaScript file wp_enqueue_script( 'vendors-js', get_template_directory_uri() . '/js/vendors.min.js'); // Load our main JavaScript file wp_enqueue_script( 'mytheme-js', get_template_directory_uri() . '/js/app.min.js', array( 'vendors-js' )); } add_action( 'wp_enqueue_scripts', 'mytheme_scripts', false); ``` While both `*.js` files are loaded in the HTML `<head>` section the custom `*.css` file is loaded in the footer of the page (probably triggered by `wp_footer()`). I have read about the fact that `wp_enqueue_scripts()` could be placed anywhere in the source code since any earlier WP version. I've also read that `wp_enqueue_script()` has a parameter `$in_footer` to control the output location. However, `wp_enqueue_style()` doesn't have such an option. Now, how can I have my custom stylesheet link be placed in HTML head section without hard-coding it into `header.php`?
hook into init action on your initial plugin function ``` add_action('init', array(__CLASS__, 'your_function_within_class')); ``` and add the function ``` public static function your_function_within_class() { wp_register_style('myfirstplugin-admin-css', '/wp-content/plugins/myfirstplugin/assets/style.css', false); wp_enqueue_style('myfirstplugin-admin-css'); } ``` hope this help
214,456
<p>While configuring Ctags to recognize WordPress functions, I came across the <a href="https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/noop.php" rel="nofollow noreferrer">noop.php</a> file. Here is an excerpt:</p> <pre><code>/** * @ignore */ function add_action() {} /** * @ignore */ function did_action() {} /** * @ignore */ function do_action_ref_array() {} </code></pre> <p><strong>Why does this file exist?</strong> Can I remove it to let VIM better navigate the code?</p>
[ { "answer_id": 214457, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 4, "selected": true, "text": "<p>The description on top of the page you have linked gives an explanation:</p>\n\n<blockquote>\n <p>Create a new file, <code>wp-admin/includes/noop.php</code>, which loads all of the noop functions for <code>load-script|styles.php</code> and is only loaded by those files. DRYs in the process. See <a href=\"https://core.trac.wordpress.org/ticket/33813\" rel=\"nofollow noreferrer\">#33813</a>.</p>\n</blockquote>\n\n<p>Additionally there is the trac ticket <a href=\"https://core.trac.wordpress.org/ticket/33813\" rel=\"nofollow noreferrer\">#33813</a> linked, which gives some additional insight. You generally shouldn't delete core files so consider <code>noop.php</code> as a necessary file.</p>\n" }, { "answer_id": 367659, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<h2>Why <code>noop.php</code>?</h2>\n\n<p>Previously <code>noop</code> functions were duplicated across core in multiple places, and an effort was made to co-locate them to avoid this duplication. This was done in <a href=\"https://core.trac.wordpress.org/ticket/33813\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/33813</a> as part of an organisation effort.</p>\n\n<h2>What Are Noop functions?</h2>\n\n<p>Noop, or <strong><em>No</em></strong> <strong><em>Op</em></strong>-eration functions, are useful for testing and mocking. They're also a way to implement the null pattern, of presenting APIs that don't do anything to act as placeholders for ones that do.</p>\n\n<h2>Can I remove it to let VIM better navigate the code?</h2>\n\n<p><strong>I would not modify core</strong>, instead you should tell ctags to ignore that file. This question/answer on stackoverflow will help:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/7736656/vim-and-ctags-ignoring-certain-files-while-generating-tags\">https://stackoverflow.com/questions/7736656/vim-and-ctags-ignoring-certain-files-while-generating-tags</a></p>\n" } ]
2016/01/13
[ "https://wordpress.stackexchange.com/questions/214456", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34330/" ]
While configuring Ctags to recognize WordPress functions, I came across the [noop.php](https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/noop.php) file. Here is an excerpt: ``` /** * @ignore */ function add_action() {} /** * @ignore */ function did_action() {} /** * @ignore */ function do_action_ref_array() {} ``` **Why does this file exist?** Can I remove it to let VIM better navigate the code?
The description on top of the page you have linked gives an explanation: > > Create a new file, `wp-admin/includes/noop.php`, which loads all of the noop functions for `load-script|styles.php` and is only loaded by those files. DRYs in the process. See [#33813](https://core.trac.wordpress.org/ticket/33813). > > > Additionally there is the trac ticket [#33813](https://core.trac.wordpress.org/ticket/33813) linked, which gives some additional insight. You generally shouldn't delete core files so consider `noop.php` as a necessary file.
214,498
<p>When is <code>wp_loaded</code> initiated?</p> <p>Im trying to add function that downloads a big file for the plugin DB, and I need it to be executed whenever user/admin/unknown user get in the frontend, after the site is fully loaded, so that it would not be any delay with the site speed, and user experience.</p> <p>I use this script:</p> <pre><code>// add update check when admin login if (is_admin()) { function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'admin_init', 'wp_shabbat_update' ); } // add update check when user enter the site after footer loaded if (!(is_admin() )) { function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'wp_loaded', 'wp_plugin_update' ); } </code></pre> <p>Can I only use this and it will work with admin and when user enter the site? :</p> <pre><code>function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'wp_loaded', 'wp_plugin_update' ); </code></pre>
[ { "answer_id": 214499, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded</code></a> fires for both the front-end and admin section of the site.</p>\n\n<blockquote>\n <p>This action hook is fired once WordPress, all plugins, and the theme are fully loaded and instantiated.</p>\n</blockquote>\n\n<p>Since you're checking for plugin updates, it might be best to hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\"><code>admin_init</code></a> instead of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded</code></a> -- assuming you want to know if a <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\"><code>user</code></a> is logged in and viewing the <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\">admin</a> section of the site.</p>\n\n<pre><code>function wpse_20160114_admin_init_update_plugin() {\n\n // don't run on ajax calls\n if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ) {\n return;\n }\n\n // only administrators can trigger this event\n if(is_user_logged_in() &amp;&amp; current_user_can('manage_options')) \n {\n @include(plugin_dir_path(__FILE__) . 'wp-plugin-update.php');\n }\n}\n\nadd_action('admin_init', 'wpse_20160114_admin_init_update_plugin');\n</code></pre>\n\n<p>In the case that you want to run on the front-end for all users</p>\n\n<pre><code>function wpse_20160114_update_plugin() {\n\n // don't run on ajax calls\n if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ) {\n return;\n }\n\n // only run on front-end\n if( is_admin() ) {\n return;\n }\n\n include(plugin_dir_path(__FILE__) . 'wp-plugin-update.php');\n}\n\nadd_action('wp_loaded', 'wpse_20160114_update_plugin');\n</code></pre>\n\n<hr>\n\n<p>As far as my tests are concerned, <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded</code></a> fires after <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\"><code>init</code></a> but before <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\"><code>admin_init</code></a>.</p>\n\n<p>Front-End</p>\n\n<ul>\n<li>[ <code>init</code> ]</li>\n<li>[ <code>widgets_init</code> ]</li>\n<li>[ <code>wp_loaded</code> ]</li>\n</ul>\n\n<p>Admin</p>\n\n<ul>\n<li>[ <code>init</code> ]</li>\n<li>[ <code>widgets_init</code> ]</li>\n<li>[ <code>wp_loaded</code> ] </li>\n<li>[ <code>admin_menu</code> ]</li>\n<li>[ <code>admin_init</code> ]</li>\n</ul>\n\n<hr>\n\n<p><a href=\"http://www.rarst.net/wordpress/wordpress-core-load/\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g32aY.png\" alt=\"\"></a></p>\n" }, { "answer_id": 214516, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p><code>wp_loaded</code> runs front end and back end regardless of user and page. Whenever a page is requested <code>wp_loaded</code> will run. </p>\n\n<p>Typically, by the time <code>wp_loaded</code> executes, Wordpress is done loading and it is also the first hook available to use after WordPress is fully loaded. Users have already being validated/authenticated (<em>users was already authenticated on <code>init</code>, this happens front end and back end</em>) by this time, so that data is already availble.</p>\n\n<p>You should look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">action hook execution sequence</a> for both front end and back end actions and determine which hook will be best for the specific application you need to run. Note that certain actions like <code>init</code> and <code>wp_loaded</code> executes on both front end and back end, so you would need to do the <code>is_admin()</code> check to specifically target the front end or back end according to your needs. </p>\n\n<p>Sorry that I cannot be more specific, but your question is lacking very specific info, but in general you would do something like the following on <code>wp_loaded</code> on the front end only</p>\n\n<pre><code>add_action( 'wp_loaded', function ()\n{\n if ( !is_admin() ) { // Only target the front end\n // Do what you need to do\n }\n});\n</code></pre>\n" }, { "answer_id": 214519, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p><code>wp_loaded</code> is being triggered after the core initialization is done and before any output is emitted. user authentication is also done at this stage. </p>\n\n<p>In general, you will need to hook on it, or earlier hooks, only if you need to change any of the globals initiated by core before any actual output is done. If you are interested only in changing the output this hook is too early and you better find a more specialized hook that is triggered later. For admin it can be <code>admin_init</code> while for front-end it can be <code>template_redirect</code> which is triggered when wordpress decides which template to use or <code>wp_head</code> that is (almost) the first hook that is triggered as part of the front-end output itself.</p>\n" } ]
2016/01/14
[ "https://wordpress.stackexchange.com/questions/214498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41168/" ]
When is `wp_loaded` initiated? Im trying to add function that downloads a big file for the plugin DB, and I need it to be executed whenever user/admin/unknown user get in the frontend, after the site is fully loaded, so that it would not be any delay with the site speed, and user experience. I use this script: ``` // add update check when admin login if (is_admin()) { function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'admin_init', 'wp_shabbat_update' ); } // add update check when user enter the site after footer loaded if (!(is_admin() )) { function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'wp_loaded', 'wp_plugin_update' ); } ``` Can I only use this and it will work with admin and when user enter the site? : ``` function wp_plugin_update() { include( plugin_dir_path( __FILE__ ) . 'wp-plugin-update.php'); } add_action( 'wp_loaded', 'wp_plugin_update' ); ```
[`wp_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded) fires for both the front-end and admin section of the site. > > This action hook is fired once WordPress, all plugins, and the theme are fully loaded and instantiated. > > > Since you're checking for plugin updates, it might be best to hook into [`admin_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init) instead of [`wp_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded) -- assuming you want to know if a [`user`](https://codex.wordpress.org/Roles_and_Capabilities) is logged in and viewing the [admin](https://codex.wordpress.org/Function_Reference/is_admin) section of the site. ``` function wpse_20160114_admin_init_update_plugin() { // don't run on ajax calls if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return; } // only administrators can trigger this event if(is_user_logged_in() && current_user_can('manage_options')) { @include(plugin_dir_path(__FILE__) . 'wp-plugin-update.php'); } } add_action('admin_init', 'wpse_20160114_admin_init_update_plugin'); ``` In the case that you want to run on the front-end for all users ``` function wpse_20160114_update_plugin() { // don't run on ajax calls if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return; } // only run on front-end if( is_admin() ) { return; } include(plugin_dir_path(__FILE__) . 'wp-plugin-update.php'); } add_action('wp_loaded', 'wpse_20160114_update_plugin'); ``` --- As far as my tests are concerned, [`wp_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded) fires after [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) but before [`admin_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init). Front-End * [ `init` ] * [ `widgets_init` ] * [ `wp_loaded` ] Admin * [ `init` ] * [ `widgets_init` ] * [ `wp_loaded` ] * [ `admin_menu` ] * [ `admin_init` ] --- [![](https://i.stack.imgur.com/g32aY.png)](http://www.rarst.net/wordpress/wordpress-core-load/)
214,503
<p>I'm using <code>wp_dropdown_categories()</code> with <code>multiple="multiple"</code> <a href="https://wordpress.stackexchange.com/q/183292/22728">in this way</a>, bypassing WordPress core. Till now (WP 4.4.1) doesn't support <code>multiple</code> on that select field. <sup>(<a href="https://core.trac.wordpress.org/ticket/31909" rel="nofollow noreferrer">Core Ticket</a>)</sup></p> <p>I'm struggling with the <code>selected</code> parameter. How can I pass multiple values so that the <code>selected</code> parameter can understand which multiple options to be selected?</p> <p>I think it's possible only by writing own function supporting array values for selection.</p> <p>Any easy way?</p>
[ { "answer_id": 214505, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>As the core tickets (for example <a href=\"https://core.trac.wordpress.org/ticket/16734\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/16734</a>) say the point of the api is to provide a dropdown and not a multiselect. IIRC in the quick edit of posts no API is being used for the category and tags multiselct. </p>\n\n<p>In other words, just ignore the API and write your own.</p>\n" }, { "answer_id": 214506, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": true, "text": "<p>Thanks @markkaplun. I solved it writing my own:</p>\n\n<pre><code>&lt;?php\n/**\n * Dropdown for 'my_tax'\n * @since 1.0.0 Using wp_dropdown_categories().\n * @since 2.0.3 Custom code, as wp_dropdown_categories() doesn't provide\n * 'selected' field for multiple=\"multiple\"\n */\n$my_tax_terms = get_terms( 'my_tax', array('hide_empty'=&gt;false) );\necho '&lt;select required multiple=\"multiple\" name=\"my_tax[]\" id=\"my-tax\" class=\"postform\"&gt;';\n foreach ($my_tax_terms as $tax_term) {\n $selected = !empty($_POST['my_tax']) &amp;&amp; in_array( $tax_term-&gt;term_id, $_POST['my_tax'] ) ? ' selected=\"selected\" ' : '';\n echo '&lt;option value=\"'. $tax_term-&gt;term_id .'\" '. $selected .'&gt;'. $tax_term-&gt;name .'&lt;/option&gt;';\n }\necho '&lt;/select&gt;';\n</code></pre>\n" }, { "answer_id": 214508, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>You should be able to do a similar thing as described in that answer and filter the output from <code>wp_category_dropdown</code> using <code>wp_dropdown_cats</code>, but for the options instead of select eg.</p>\n\n<pre><code>add_filter('wp_dropdown_cats', 'wp_dropdown_categories_multiselect');\nfunction wp_dropdown_categories_multiselect($output) {\n $valuekey = 'valuekey'; // set to 'name' argument passed\n // check this is the correct dropdown\n if (strstr($output,'name=\"'.$valuekey.'\"')) {\n // add multiple to select (you may already have this)\n $output = str_replace('&lt;select ','&lt;select multiple ',$output);\n // add square brackets to the name key\n $output = str_replace('name=\"'.$valuekey.'\"','name=\"'.$valuekey.'[]\"',$output);\n $selectedvalues = get_option($valuekey);\n // make sure there is a selected value\n if (count($selectedvalues) &gt; 0) {\n // loop through the selected values\n foreach ($selectedvalues as $value) {\n // add the selected to each selected value\n $output = str_replace( \n '&lt;option value=\"'.$value.'\"',\n '&lt;option value=\"'.$value.'\" selected=\"selected\"',\n $output \n );\n }\n }\n }\n return $output;\n}\n</code></pre>\n\n<p>Note: assumes you are saving the value as an array of selected values to the options table. eg.</p>\n\n<pre><code>$valuekey = 'valuekey';\nif (isset($_REQUEST[$valuekey])) {\n $selectedvalues = $_REQUEST[$valuekey];\n if (!add_option('valuekey',$selectedvalues)) {\n update_option('valuekey',$selectedvalues);\n }\n}\n</code></pre>\n\n<p>Of course with the use of <code>str_replace</code> the first value of each occurrence would have to exactly match to the output, so there may be some debugging required there to get this to work.</p>\n" } ]
2016/01/14
[ "https://wordpress.stackexchange.com/questions/214503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm using `wp_dropdown_categories()` with `multiple="multiple"` [in this way](https://wordpress.stackexchange.com/q/183292/22728), bypassing WordPress core. Till now (WP 4.4.1) doesn't support `multiple` on that select field. ([Core Ticket](https://core.trac.wordpress.org/ticket/31909)) I'm struggling with the `selected` parameter. How can I pass multiple values so that the `selected` parameter can understand which multiple options to be selected? I think it's possible only by writing own function supporting array values for selection. Any easy way?
Thanks @markkaplun. I solved it writing my own: ``` <?php /** * Dropdown for 'my_tax' * @since 1.0.0 Using wp_dropdown_categories(). * @since 2.0.3 Custom code, as wp_dropdown_categories() doesn't provide * 'selected' field for multiple="multiple" */ $my_tax_terms = get_terms( 'my_tax', array('hide_empty'=>false) ); echo '<select required multiple="multiple" name="my_tax[]" id="my-tax" class="postform">'; foreach ($my_tax_terms as $tax_term) { $selected = !empty($_POST['my_tax']) && in_array( $tax_term->term_id, $_POST['my_tax'] ) ? ' selected="selected" ' : ''; echo '<option value="'. $tax_term->term_id .'" '. $selected .'>'. $tax_term->name .'</option>'; } echo '</select>'; ```
214,540
<p>I have created a shortcode for a custom post type query but when I add meta_query values to it, it throws an error:</p> <pre><code>Notice: Undefined variable: my in E:\xampp\htdocs\test\wp-content\themes\test-theme\functions.php on line 182 </code></pre> <p>Here is the shortcode code:</p> <pre><code>function list_unit( $atts ) { $args = array( 'post_type' =&gt; 'unit', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; '0', 'orderby' =&gt; 'menu_order', 'meta_query' =&gt; array( array( 'key' =&gt; 'first_item_key', 'value' =&gt; 'false', 'compare' =&gt; '=' ) ), ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) { $my = '&lt;table&gt;'; while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); $my .= '&lt;tr&gt;&lt;td&gt;&lt;a href="'. get_the_permalink() .'"&gt;'; $my .= get_the_title() ; $my .= '&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;'; } $my .= '&lt;/table&gt;'; } else { // no posts found } return $my; } add_shortcode( 'unit', 'list_unit' ); </code></pre> <p>Not sure what's going wrong. </p>
[ { "answer_id": 214541, "author": "Nefro", "author_id": 86801, "author_profile": "https://wordpress.stackexchange.com/users/86801", "pm_score": -1, "selected": false, "text": "<p>try change </p>\n\n<pre><code>return $my;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (isset($my)) return $my;\n\nreturn 'Not found post';\n</code></pre>\n" }, { "answer_id": 214542, "author": "Sladix", "author_id": 27423, "author_profile": "https://wordpress.stackexchange.com/users/27423", "pm_score": 2, "selected": true, "text": "<p>As the error states, your $my variable is not defined.</p>\n\n<p>The reason behind it is that you only defines $my when $the_query->have_posts().</p>\n\n<p>Adding</p>\n\n<pre><code>$my = 'No results found';\n</code></pre>\n\n<p>right after</p>\n\n<pre><code>$the_query = new WP_Query( $args );\n</code></pre>\n\n<p>would solve your problem. $my would then be redefined if results are found.</p>\n" } ]
2016/01/14
[ "https://wordpress.stackexchange.com/questions/214540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58787/" ]
I have created a shortcode for a custom post type query but when I add meta\_query values to it, it throws an error: ``` Notice: Undefined variable: my in E:\xampp\htdocs\test\wp-content\themes\test-theme\functions.php on line 182 ``` Here is the shortcode code: ``` function list_unit( $atts ) { $args = array( 'post_type' => 'unit', 'posts_per_page' => -1, 'post_parent' => '0', 'orderby' => 'menu_order', 'meta_query' => array( array( 'key' => 'first_item_key', 'value' => 'false', 'compare' => '=' ) ), ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $my = '<table>'; while ( $the_query->have_posts() ) { $the_query->the_post(); $my .= '<tr><td><a href="'. get_the_permalink() .'">'; $my .= get_the_title() ; $my .= '</a></td></tr>'; } $my .= '</table>'; } else { // no posts found } return $my; } add_shortcode( 'unit', 'list_unit' ); ``` Not sure what's going wrong.
As the error states, your $my variable is not defined. The reason behind it is that you only defines $my when $the\_query->have\_posts(). Adding ``` $my = 'No results found'; ``` right after ``` $the_query = new WP_Query( $args ); ``` would solve your problem. $my would then be redefined if results are found.
214,580
<p>I receive this error while debug mode is enabled:</p> <blockquote> <p>Notice: load_plugin_textdomain was called with an argument that is deprecated since version 2.7 with no alternative available. in /home/xyz/public_html/wp-includes/functions.php on line 3739</p> </blockquote> <p>I found that is related to this plugin: <a href="https://wordpress.org/plugins/custom-smilies-se/" rel="nofollow">https://wordpress.org/plugins/custom-smilies-se/</a></p> <p>I really need to have this plugin and would not ignore it; Also plugin author had not responded about this issue. Could you please guide me to modify it?</p>
[ { "answer_id": 214633, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": true, "text": "<p>The plugin calling <code>load_plugin_textdomain()</code> <a href=\"https://wordpress.stackexchange.com/a/97928/73\">the wrong way</a>:</p>\n\n<pre><code>load_plugin_textdomain(\n 'custom_smilies', \n PLUGINDIR . '/' . dirname(plugin_basename(__FILE__)) . '/lang'\n);\n</code></pre>\n\n<p>You have to change the code to:</p>\n\n<pre><code>load_plugin_textdomain(\n 'custom_smilies', \n false,\n plugin_dir_path(__FILE__) . '/lang'\n);\n</code></pre>\n" }, { "answer_id": 214750, "author": "Omid Toraby", "author_id": 62437, "author_profile": "https://wordpress.stackexchange.com/users/62437", "pm_score": 0, "selected": false, "text": "<p>I changed </p>\n\n<pre><code>function clcs_add_pages() {\n add_options_page(__('Smilies Options', 'custom_smilies'), __('Smilies', 'custom_smilies'), 8, CLCSABSFILE, 'clcs_options_admin_page');\n}\n</code></pre>\n\n<p>to this code </p>\n\n<pre><code>function clcs_add_pages() {\n add_options_page(__('Smilies Options', 'custom_smilies'), __('Smilies', 'custom_smilies'), 'manage_network_plugins', CLCSABSFILE, 'clcs_options_admin_page');\n} \n</code></pre>\n\n<p>and solved! @toscho</p>\n" } ]
2016/01/14
[ "https://wordpress.stackexchange.com/questions/214580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62437/" ]
I receive this error while debug mode is enabled: > > Notice: load\_plugin\_textdomain was called with an argument that is > deprecated since version 2.7 with no alternative available. in > /home/xyz/public\_html/wp-includes/functions.php on line 3739 > > > I found that is related to this plugin: <https://wordpress.org/plugins/custom-smilies-se/> I really need to have this plugin and would not ignore it; Also plugin author had not responded about this issue. Could you please guide me to modify it?
The plugin calling `load_plugin_textdomain()` [the wrong way](https://wordpress.stackexchange.com/a/97928/73): ``` load_plugin_textdomain( 'custom_smilies', PLUGINDIR . '/' . dirname(plugin_basename(__FILE__)) . '/lang' ); ``` You have to change the code to: ``` load_plugin_textdomain( 'custom_smilies', false, plugin_dir_path(__FILE__) . '/lang' ); ```
214,587
<p>I found 2 ways to block direct access to php files (although it's not always necessary, see <a href="https://wordpress.stackexchange.com/a/63004/60539">https://wordpress.stackexchange.com/a/63004/60539</a>) The first one is:</p> <pre><code>defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); </code></pre> <p>And the other:</p> <pre><code>if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) &amp;&amp; basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) { die ( 'You do not have sufficient permissions to access this page!' ); } </code></pre> <p>Are they doing the same thing? Shall I prefer one to the other?</p>
[ { "answer_id": 214598, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The logic of the first one is based on wordpress setting <code>ABSPATH</code> as part of the initialization, and therefor if it was not set you are not accessing the site via the \"official\" wordpress end points.</p>\n\n<p>The second seems to be a general PHP technique.</p>\n\n<p>The best way is to just write code without side effects (or if you are the owner of the site block access to any php file in htaccess), but if you must I would say go with the first one as it is assumes some wordpress specific execution path.</p>\n" }, { "answer_id": 214617, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>In my opinion, the <strong>only</strong> way to do this (within the context of WordPress) is:</p>\n\n<pre><code>if ( ! defined( 'ABSPATH' ) ) // Or some other WordPress constant\n exit;\n</code></pre>\n\n<p>The second technique is vague and does give the same level of checking (it only checks that the filename of the main PHP file matches itself, not whether WordPress is loaded, nor if it's another file of the same name).</p>\n\n<p>And this <code>No script kiddies please!</code> is pointless, I wish this fad would die - just exit silently.</p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60539/" ]
I found 2 ways to block direct access to php files (although it's not always necessary, see <https://wordpress.stackexchange.com/a/63004/60539>) The first one is: ``` defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); ``` And the other: ``` if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) { die ( 'You do not have sufficient permissions to access this page!' ); } ``` Are they doing the same thing? Shall I prefer one to the other?
In my opinion, the **only** way to do this (within the context of WordPress) is: ``` if ( ! defined( 'ABSPATH' ) ) // Or some other WordPress constant exit; ``` The second technique is vague and does give the same level of checking (it only checks that the filename of the main PHP file matches itself, not whether WordPress is loaded, nor if it's another file of the same name). And this `No script kiddies please!` is pointless, I wish this fad would die - just exit silently.
214,588
<p>This is pretty much an exact duplicate of: <a href="https://wordpress.stackexchange.com/q/158525/9802">How to make Wordpress and TinyMCE accept &lt;a&gt; tags wrapping block-level elements as allowed in HTML5?</a> and <a href="https://wordpress.stackexchange.com/q/96725/9802">HTML5, WordPress and Tiny MCE issue - wrapping anchor tag around div results in funky output</a></p> <p>My problem is that the suggested solution (<code>tiny_mce_before_init</code> filter) doesn't seem to solve my problem. I have HTML that looks like this:</p> <pre><code>&lt;a href="#"&gt; &lt;img src="path/to/file.jpg" /&gt; &lt;p&gt;Some amazing descriptive text&lt;/p&gt; &lt;/a&gt; </code></pre> <p>The is perfectly legal in HTML5. However, the WP editor doesn't like it and transforms it to:</p> <pre><code>&lt;a href="#"&gt; &lt;img src="path/to/file.jpg" /&gt; &lt;/a&gt; &lt;p&gt;Some amazing descriptive text&lt;/p&gt; </code></pre> <p>This, of course, breaks my layout. Does anyone know of a way I can prevent this behavior? I can't give up the <em>Visual</em> component of the editor and stick to plain text. Any suggestions are welcome.</p> <p>Just to be clear, when I use the code below (<a href="https://wordpress.stackexchange.com/a/96751/9802">suggested here</a>), the <code>&lt;p&gt;</code> tags are allowed to remain inside the anchors but a lot of extra space is added along with an <code>&amp;nbsp;</code> entity which multiplies every time you switch between Visual and Text mode.</p> <pre><code>add_filter('tiny_mce_before_init', 'modify_valid_children'); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|h2|h3|h4|h5|h5|h6]"; return $settings; } </code></pre>
[ { "answer_id": 214591, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 5, "selected": true, "text": "<p>Regardless of what you have configured as valid children, WordPress handles p tags as well as line breaks in a very unique way. You'll probably notice eventually, if you haven't already, that when switching from the text editor to the visual editor and back that your <code>&lt;p&gt;</code> tags get stripped, similar to what occurs on the frontend. A way to block this from happening is by giving the <code>&lt;p&gt;</code> tags a custom class.</p>\n\n<p><code>&lt;p class=\"text\"&gt;This p tag won't get removed\"&lt;/p&gt;</code>.</p>\n\n<p>While <strong>↑</strong> this <strong>↑</strong> will keep your p tag from getting stripped, it won't fix your issue as your markup on the frontend still gets mucked up. You could <strong>DISABLE</strong> wpautop. If you do that AND have p included in valid children, this <em>WILL FIX YOUR ISSSUE</em>.</p>\n\n<p><strong>OPTION 1 : <em>Disable Autop and Set Valid Children</em></strong></p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter('tiny_mce_before_init', 'modify_valid_children', 99);\nfunction modify_valid_children($settings){ \n $settings['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n return $settings;\n}\n</code></pre>\n\n<p>I should warn you though that the second you switch from the <em>HTML</em> editor back to <strong>TinyMCE</strong> your HTML will get destroyed. A workaround is to disable <em>TinyMCE</em> altogether for certain post types as in option 2 below.</p>\n\n<hr>\n\n<p><strong>OPTION 2 : <em>Disable Auto P, TinyMCE, and Set Valid Children</em></strong></p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter('tiny_mce_before_init', 'modify_valid_children', 99);\nfunction modify_valid_children($settings){ \n $settings['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n return $settings;\n}\nadd_filter('user_can_richedit', 'disable_wyswyg_to_preserve_my_markup');\nfunction disable_wyswyg_to_preserve_my_markup( $default ){\n if( get_post_type() === 'post') return false;\n return $default;\n}\n</code></pre>\n\n<p><em>For most people though <strong>↑</strong> this <strong>↑</strong> is not an option.</em></p>\n\n<hr>\n\n<p>So what other options are there? One workaround I've noticed works is to use a <strong><em>span tag with a class</em></strong> and make sure there <strong><em>is no white space between your HTML tags</em></strong>. If you do this you can use option one above and avoid having to disable TinyMCE all together. Just remember that you'll also have to add some CSS to your stylesheet to display the span correctly. </p>\n\n<p><strong><em>OPTION 3: Option 1 + Styled Span Tags</em></strong> </p>\n\n<p><em>HTML</em></p>\n\n<pre><code>&lt;a href=\"#\"&gt;&lt;img src=\"https://placehold.it/300x200?text=Don%27t+P+On+Me\" alt=\"\" /&gt;&lt;span class=\"noautop\"&gt;Some amazing descriptive text&lt;/span&gt;&lt;/a&gt;\n</code></pre>\n\n<p><em>CSS in Stylesheet</em></p>\n\n<pre><code>.noautop {\n display: block;\n}\n</code></pre>\n\n<hr>\n\n<p><strong><em>Option 4: Use the built in media uploader shortcode</em></strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/glosr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/glosr.png\" alt=\"shortcode media uploader\"></a></p>\n\n<p><em>I initially forgot this one, but the <a href=\"https://github.com/WordPress/WordPress/blob/fdb6bbfa10c2acca0074c4c741f6dff122e3ce1d/wp-includes/media.php#L1433\" rel=\"nofollow noreferrer\">[caption]</a> shortcode will look like this:</em></p>\n\n<pre><code>[caption id=\"attachment_167\" align=\"alignnone\" width=\"169\"]\n &lt;img class=\"size-medium wp-image-167\" src=\"http://example.com/example.png\" alt=\"\" width=\"169\" height=\"300\" /&gt;\n awesome caption\n[/caption]\n</code></pre>\n\n<p><em>The output will look like this:</em></p>\n\n<pre><code>&lt;figure id=\"attachment_167\" style=\"width: 169px\" class=\"wp-caption alignnone\"&gt;\n &lt;img class=\"size-medium wp-image-167\" src=\"http://example.com/example.png\" alt=\"\" width=\"169\" height=\"300\" /&gt;\n &lt;figcaption class=\"wp-caption-text\"&gt;Some amazing descriptive text&lt;/figcaption&gt;\n&lt;/figure&gt;\n</code></pre>\n\n<p>If you don't want figure tags you could use a plugin like <a href=\"https://wordpress.org/plugins/custom-content-shortcode/\" rel=\"nofollow noreferrer\">custom content shortcode</a> that allows you to do this:</p>\n\n<pre><code>[raw] &lt;p&gt;this content will not get filtered by wordpress&lt;/p&gt; [/raw]\n</code></pre>\n\n<hr>\n\n<p><strong><em>Why can't the editor just work how I want though?</em></strong></p>\n\n<p>I've spent countless hours trying to get this to work well over the past couple years. Occasionally I'll come up with a solution that works perfectly, but then WordPress will push an update that messes everything up again. The only solution I've ever found to completely work how it should, leads me to the best answer I have.</p>\n\n<p><strong><em><a href=\"http://wordpress.org/plugins/preserved-html-editor-markup-plus\" rel=\"nofollow noreferrer\">Option 5 : Preserved HTML Editor Markup Plus</a></em></strong></p>\n\n<p>So save yourself the headache and just go with this. By default, <em>Preserved HTML Editor Markup Plus</em> only affects new pages. If you want to change pages already created, you have to go to <strong>www.example.com/wp-admin/options-writing.php</strong> and edit the plugin settings. You'll also be able to change the default newline behavior.</p>\n\n<blockquote>\n <p><em>Note: If you do decide to use this make sure you check the support thread when a new WordPress update gets launched. Occasionally, an\n change will mess things up so it's best to make sure the plugin works\n on the newer versions.</em></p>\n</blockquote>\n\n<hr>\n\n<p><strong><em>Extra Credit: Debugging Your Problem / Editing Other TinyMCE Options</em></strong></p>\n\n<p>If you want to inspect and easily <em>edit</em> your TinyMCE configurations manually, like you do with filters, you can install <a href=\"https://wordpress.org/plugins/advanced-tinymce-configuration/\" rel=\"nofollow noreferrer\">advanced TinyMCE config</a>. It lets you view <strong>ALL</strong> of the configured TinyMCE options and edit them from a simple interface. You can also add new options just like you would with the filters. It makes things a whole lot easier to understand.</p>\n\n<p>For example, I have both that and Preserved HTML Editor Markup Plus. The screenshot below is of the Advanced TinyMCE Config admin page. While the screenshot is cutting off 90% of what's really there, you can see it shows the valid children available to edit and which ones <strong>Preserved HTML Editor Markup Plus</strong> added. </p>\n\n<p><a href=\"https://i.stack.imgur.com/wziWi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wziWi.png\" alt=\"TinyMCE editor\"></a></p>\n\n<p>This is an extremely helpful way of not only completely customizing your editor, but also seeing what's going on. You might be even able to figure out what was causing your issue then. After looking over the parameters myself while Preserved HTML Editor Markup was enabled I saw some additional options that could be added to a custom filter.</p>\n\n<pre><code>function fix_tiny_mce_before_init( $in ) {\n\n // You can actually debug this without actually needing Advanced Tinymce Config enabled:\n // print_r( $in );\n // exit();\n\n $in['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n $in[ 'force_p_newlines' ] = FALSE;\n $in[ 'remove_linebreaks' ] = FALSE;\n $in[ 'force_br_newlines' ] = FALSE;\n $in[ 'remove_trailing_nbsp' ] = FALSE;\n $in[ 'apply_source_formatting' ] = FALSE;\n $in[ 'convert_newlines_to_brs' ] = FALSE;\n $in[ 'verify_html' ] = FALSE;\n $in[ 'remove_redundant_brs' ] = FALSE;\n $in[ 'validate_children' ] = FALSE;\n $in[ 'forced_root_block' ]= FALSE;\n\n return $in;\n}\nadd_filter( 'tiny_mce_before_init', 'fix_tiny_mce_before_init' );\n</code></pre>\n\n<p>Unfortunately this method didn't work. There is probably some regex or JavaScript that is happening when updating the post and/or switching between editors. If you take a look at the Preserved HTML Editor source code you can see that it does some JavaScript work on the admin side so my last bit of advice would be to check <a href=\"http://plugins.svn.wordpress.org/preserved-html-editor-markup-plus/trunk/\" rel=\"nofollow noreferrer\">how the plugin works</a> if you want to add this functionality in your theme.</p>\n\n<p>Anyway, sorry for anyone who has gotten this far in my answer. Just thought I'd share my own experiences dealing with the WordPress editor, so others hopefully won't have to spend hours trying to figure this out like I did!</p>\n" }, { "answer_id": 398631, "author": "Rob", "author_id": 215310, "author_profile": "https://wordpress.stackexchange.com/users/215310", "pm_score": 0, "selected": false, "text": "<p>First of all: Many thanks for Bryans excellent answer, which documents as well the difficulties he encountered.</p>\n<p>Just as a result of own experimenting (including a bit of Bryan's suggestions), I think that the following plugin could vastly aid in <strong>consistency when swithing between html and visual editor</strong>: Advanced Editor Tools (previously TinyMCE Advanced) - <a href=\"https://wordpress.org/plugins/tinymce-advanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/tinymce-advanced/</a>.</p>\n<p>At first sight, the plugin didn't do what I expected it to do. On a second turn, I found a settings parameter &quot;preserve paragraph tags&quot;. The visual editor no longer removes <code>&lt;p&gt;</code> and <code>&lt;br&gt;</code> tags from the html editor. Even more: After switching between both editors, I found that almost all empty lines were gone and that instead many <code>&lt;p&gt;</code> and <code>&lt;/p&gt;</code> are put in instead.\nThe downside is that the visual representation in the visual editor shows some minor quirks, but that's considered a minor problem. For me counts this: You know exactly where you are with the cursor, because of nearly WYSIWYG. After all: Also without this specific setting, the visual editor <em>has</em> rendering flaws compared to preview/final result.</p>\n<p>I feel that I have quite full control over spacing in text now. Even when I hit Return in the visual editor (or shift Return), the extra tags are generated. Again a downside: You only see that in the html view (and the final view) - the visual editor does not show the extra space. So what? It counts is no longer <strong>breaking my beautiful HTML</strong>!</p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214588", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9802/" ]
This is pretty much an exact duplicate of: [How to make Wordpress and TinyMCE accept <a> tags wrapping block-level elements as allowed in HTML5?](https://wordpress.stackexchange.com/q/158525/9802) and [HTML5, WordPress and Tiny MCE issue - wrapping anchor tag around div results in funky output](https://wordpress.stackexchange.com/q/96725/9802) My problem is that the suggested solution (`tiny_mce_before_init` filter) doesn't seem to solve my problem. I have HTML that looks like this: ``` <a href="#"> <img src="path/to/file.jpg" /> <p>Some amazing descriptive text</p> </a> ``` The is perfectly legal in HTML5. However, the WP editor doesn't like it and transforms it to: ``` <a href="#"> <img src="path/to/file.jpg" /> </a> <p>Some amazing descriptive text</p> ``` This, of course, breaks my layout. Does anyone know of a way I can prevent this behavior? I can't give up the *Visual* component of the editor and stick to plain text. Any suggestions are welcome. Just to be clear, when I use the code below ([suggested here](https://wordpress.stackexchange.com/a/96751/9802)), the `<p>` tags are allowed to remain inside the anchors but a lot of extra space is added along with an `&nbsp;` entity which multiplies every time you switch between Visual and Text mode. ``` add_filter('tiny_mce_before_init', 'modify_valid_children'); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|h2|h3|h4|h5|h5|h6]"; return $settings; } ```
Regardless of what you have configured as valid children, WordPress handles p tags as well as line breaks in a very unique way. You'll probably notice eventually, if you haven't already, that when switching from the text editor to the visual editor and back that your `<p>` tags get stripped, similar to what occurs on the frontend. A way to block this from happening is by giving the `<p>` tags a custom class. `<p class="text">This p tag won't get removed"</p>`. While **↑** this **↑** will keep your p tag from getting stripped, it won't fix your issue as your markup on the frontend still gets mucked up. You could **DISABLE** wpautop. If you do that AND have p included in valid children, this *WILL FIX YOUR ISSSUE*. **OPTION 1 : *Disable Autop and Set Valid Children*** ``` remove_filter( 'the_content', 'wpautop' ); add_filter('tiny_mce_before_init', 'modify_valid_children', 99); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; return $settings; } ``` I should warn you though that the second you switch from the *HTML* editor back to **TinyMCE** your HTML will get destroyed. A workaround is to disable *TinyMCE* altogether for certain post types as in option 2 below. --- **OPTION 2 : *Disable Auto P, TinyMCE, and Set Valid Children*** ``` remove_filter( 'the_content', 'wpautop' ); add_filter('tiny_mce_before_init', 'modify_valid_children', 99); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; return $settings; } add_filter('user_can_richedit', 'disable_wyswyg_to_preserve_my_markup'); function disable_wyswyg_to_preserve_my_markup( $default ){ if( get_post_type() === 'post') return false; return $default; } ``` *For most people though **↑** this **↑** is not an option.* --- So what other options are there? One workaround I've noticed works is to use a ***span tag with a class*** and make sure there ***is no white space between your HTML tags***. If you do this you can use option one above and avoid having to disable TinyMCE all together. Just remember that you'll also have to add some CSS to your stylesheet to display the span correctly. ***OPTION 3: Option 1 + Styled Span Tags*** *HTML* ``` <a href="#"><img src="https://placehold.it/300x200?text=Don%27t+P+On+Me" alt="" /><span class="noautop">Some amazing descriptive text</span></a> ``` *CSS in Stylesheet* ``` .noautop { display: block; } ``` --- ***Option 4: Use the built in media uploader shortcode*** [![shortcode media uploader](https://i.stack.imgur.com/glosr.png)](https://i.stack.imgur.com/glosr.png) *I initially forgot this one, but the [[caption]](https://github.com/WordPress/WordPress/blob/fdb6bbfa10c2acca0074c4c741f6dff122e3ce1d/wp-includes/media.php#L1433) shortcode will look like this:* ``` [caption id="attachment_167" align="alignnone" width="169"] <img class="size-medium wp-image-167" src="http://example.com/example.png" alt="" width="169" height="300" /> awesome caption [/caption] ``` *The output will look like this:* ``` <figure id="attachment_167" style="width: 169px" class="wp-caption alignnone"> <img class="size-medium wp-image-167" src="http://example.com/example.png" alt="" width="169" height="300" /> <figcaption class="wp-caption-text">Some amazing descriptive text</figcaption> </figure> ``` If you don't want figure tags you could use a plugin like [custom content shortcode](https://wordpress.org/plugins/custom-content-shortcode/) that allows you to do this: ``` [raw] <p>this content will not get filtered by wordpress</p> [/raw] ``` --- ***Why can't the editor just work how I want though?*** I've spent countless hours trying to get this to work well over the past couple years. Occasionally I'll come up with a solution that works perfectly, but then WordPress will push an update that messes everything up again. The only solution I've ever found to completely work how it should, leads me to the best answer I have. ***[Option 5 : Preserved HTML Editor Markup Plus](http://wordpress.org/plugins/preserved-html-editor-markup-plus)*** So save yourself the headache and just go with this. By default, *Preserved HTML Editor Markup Plus* only affects new pages. If you want to change pages already created, you have to go to **www.example.com/wp-admin/options-writing.php** and edit the plugin settings. You'll also be able to change the default newline behavior. > > *Note: If you do decide to use this make sure you check the support thread when a new WordPress update gets launched. Occasionally, an > change will mess things up so it's best to make sure the plugin works > on the newer versions.* > > > --- ***Extra Credit: Debugging Your Problem / Editing Other TinyMCE Options*** If you want to inspect and easily *edit* your TinyMCE configurations manually, like you do with filters, you can install [advanced TinyMCE config](https://wordpress.org/plugins/advanced-tinymce-configuration/). It lets you view **ALL** of the configured TinyMCE options and edit them from a simple interface. You can also add new options just like you would with the filters. It makes things a whole lot easier to understand. For example, I have both that and Preserved HTML Editor Markup Plus. The screenshot below is of the Advanced TinyMCE Config admin page. While the screenshot is cutting off 90% of what's really there, you can see it shows the valid children available to edit and which ones **Preserved HTML Editor Markup Plus** added. [![TinyMCE editor](https://i.stack.imgur.com/wziWi.png)](https://i.stack.imgur.com/wziWi.png) This is an extremely helpful way of not only completely customizing your editor, but also seeing what's going on. You might be even able to figure out what was causing your issue then. After looking over the parameters myself while Preserved HTML Editor Markup was enabled I saw some additional options that could be added to a custom filter. ``` function fix_tiny_mce_before_init( $in ) { // You can actually debug this without actually needing Advanced Tinymce Config enabled: // print_r( $in ); // exit(); $in['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; $in[ 'force_p_newlines' ] = FALSE; $in[ 'remove_linebreaks' ] = FALSE; $in[ 'force_br_newlines' ] = FALSE; $in[ 'remove_trailing_nbsp' ] = FALSE; $in[ 'apply_source_formatting' ] = FALSE; $in[ 'convert_newlines_to_brs' ] = FALSE; $in[ 'verify_html' ] = FALSE; $in[ 'remove_redundant_brs' ] = FALSE; $in[ 'validate_children' ] = FALSE; $in[ 'forced_root_block' ]= FALSE; return $in; } add_filter( 'tiny_mce_before_init', 'fix_tiny_mce_before_init' ); ``` Unfortunately this method didn't work. There is probably some regex or JavaScript that is happening when updating the post and/or switching between editors. If you take a look at the Preserved HTML Editor source code you can see that it does some JavaScript work on the admin side so my last bit of advice would be to check [how the plugin works](http://plugins.svn.wordpress.org/preserved-html-editor-markup-plus/trunk/) if you want to add this functionality in your theme. Anyway, sorry for anyone who has gotten this far in my answer. Just thought I'd share my own experiences dealing with the WordPress editor, so others hopefully won't have to spend hours trying to figure this out like I did!
214,627
<p>I have to add a row that (containing the content of post) below the post thumbnail on clicking thumbnail. I have done it by using this but it affects the adjacent post thumbnail.I want that a complete row to be add below every post without affecting other posts. Thumbnail of each post should be remain same.</p> <pre><code>&lt;?php $args = array('post_type' =&gt; 'team', 'category_name' =&gt; $a); $query = new WP_Query($args); if ($query-&gt;have_posts()) { while ($query-&gt;have_posts()) { $query-&gt;the_post(); ?&gt; &lt;div class="tab_heading col-md-4"&gt; &lt;div class="wrapper"&gt; &lt;a href="#tab-&lt;?php echo get_the_id(); ?&gt;"&gt; &lt;div class="bg_image"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/div&gt; &lt;/a&gt; &lt;p class="title-post"&gt; &lt;?php the_title(); ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="tab" style=""&gt; &lt;div id="tab-&lt;?php echo get_the_ID(); ?&gt;" class="tab-content"&gt; &lt;div class="row"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } } wp_reset_query(); ?&gt; </code></pre> <p>Here is picture showing my desired design. <a href="https://i.stack.imgur.com/umsxL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/umsxL.png" alt="enter image description here"></a></p> <p>i want that when i click <code>sofia</code> i add a row containing the_contentof specific post. sory for my english .</p>
[ { "answer_id": 214591, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 5, "selected": true, "text": "<p>Regardless of what you have configured as valid children, WordPress handles p tags as well as line breaks in a very unique way. You'll probably notice eventually, if you haven't already, that when switching from the text editor to the visual editor and back that your <code>&lt;p&gt;</code> tags get stripped, similar to what occurs on the frontend. A way to block this from happening is by giving the <code>&lt;p&gt;</code> tags a custom class.</p>\n\n<p><code>&lt;p class=\"text\"&gt;This p tag won't get removed\"&lt;/p&gt;</code>.</p>\n\n<p>While <strong>↑</strong> this <strong>↑</strong> will keep your p tag from getting stripped, it won't fix your issue as your markup on the frontend still gets mucked up. You could <strong>DISABLE</strong> wpautop. If you do that AND have p included in valid children, this <em>WILL FIX YOUR ISSSUE</em>.</p>\n\n<p><strong>OPTION 1 : <em>Disable Autop and Set Valid Children</em></strong></p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter('tiny_mce_before_init', 'modify_valid_children', 99);\nfunction modify_valid_children($settings){ \n $settings['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n return $settings;\n}\n</code></pre>\n\n<p>I should warn you though that the second you switch from the <em>HTML</em> editor back to <strong>TinyMCE</strong> your HTML will get destroyed. A workaround is to disable <em>TinyMCE</em> altogether for certain post types as in option 2 below.</p>\n\n<hr>\n\n<p><strong>OPTION 2 : <em>Disable Auto P, TinyMCE, and Set Valid Children</em></strong></p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter('tiny_mce_before_init', 'modify_valid_children', 99);\nfunction modify_valid_children($settings){ \n $settings['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n return $settings;\n}\nadd_filter('user_can_richedit', 'disable_wyswyg_to_preserve_my_markup');\nfunction disable_wyswyg_to_preserve_my_markup( $default ){\n if( get_post_type() === 'post') return false;\n return $default;\n}\n</code></pre>\n\n<p><em>For most people though <strong>↑</strong> this <strong>↑</strong> is not an option.</em></p>\n\n<hr>\n\n<p>So what other options are there? One workaround I've noticed works is to use a <strong><em>span tag with a class</em></strong> and make sure there <strong><em>is no white space between your HTML tags</em></strong>. If you do this you can use option one above and avoid having to disable TinyMCE all together. Just remember that you'll also have to add some CSS to your stylesheet to display the span correctly. </p>\n\n<p><strong><em>OPTION 3: Option 1 + Styled Span Tags</em></strong> </p>\n\n<p><em>HTML</em></p>\n\n<pre><code>&lt;a href=\"#\"&gt;&lt;img src=\"https://placehold.it/300x200?text=Don%27t+P+On+Me\" alt=\"\" /&gt;&lt;span class=\"noautop\"&gt;Some amazing descriptive text&lt;/span&gt;&lt;/a&gt;\n</code></pre>\n\n<p><em>CSS in Stylesheet</em></p>\n\n<pre><code>.noautop {\n display: block;\n}\n</code></pre>\n\n<hr>\n\n<p><strong><em>Option 4: Use the built in media uploader shortcode</em></strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/glosr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/glosr.png\" alt=\"shortcode media uploader\"></a></p>\n\n<p><em>I initially forgot this one, but the <a href=\"https://github.com/WordPress/WordPress/blob/fdb6bbfa10c2acca0074c4c741f6dff122e3ce1d/wp-includes/media.php#L1433\" rel=\"nofollow noreferrer\">[caption]</a> shortcode will look like this:</em></p>\n\n<pre><code>[caption id=\"attachment_167\" align=\"alignnone\" width=\"169\"]\n &lt;img class=\"size-medium wp-image-167\" src=\"http://example.com/example.png\" alt=\"\" width=\"169\" height=\"300\" /&gt;\n awesome caption\n[/caption]\n</code></pre>\n\n<p><em>The output will look like this:</em></p>\n\n<pre><code>&lt;figure id=\"attachment_167\" style=\"width: 169px\" class=\"wp-caption alignnone\"&gt;\n &lt;img class=\"size-medium wp-image-167\" src=\"http://example.com/example.png\" alt=\"\" width=\"169\" height=\"300\" /&gt;\n &lt;figcaption class=\"wp-caption-text\"&gt;Some amazing descriptive text&lt;/figcaption&gt;\n&lt;/figure&gt;\n</code></pre>\n\n<p>If you don't want figure tags you could use a plugin like <a href=\"https://wordpress.org/plugins/custom-content-shortcode/\" rel=\"nofollow noreferrer\">custom content shortcode</a> that allows you to do this:</p>\n\n<pre><code>[raw] &lt;p&gt;this content will not get filtered by wordpress&lt;/p&gt; [/raw]\n</code></pre>\n\n<hr>\n\n<p><strong><em>Why can't the editor just work how I want though?</em></strong></p>\n\n<p>I've spent countless hours trying to get this to work well over the past couple years. Occasionally I'll come up with a solution that works perfectly, but then WordPress will push an update that messes everything up again. The only solution I've ever found to completely work how it should, leads me to the best answer I have.</p>\n\n<p><strong><em><a href=\"http://wordpress.org/plugins/preserved-html-editor-markup-plus\" rel=\"nofollow noreferrer\">Option 5 : Preserved HTML Editor Markup Plus</a></em></strong></p>\n\n<p>So save yourself the headache and just go with this. By default, <em>Preserved HTML Editor Markup Plus</em> only affects new pages. If you want to change pages already created, you have to go to <strong>www.example.com/wp-admin/options-writing.php</strong> and edit the plugin settings. You'll also be able to change the default newline behavior.</p>\n\n<blockquote>\n <p><em>Note: If you do decide to use this make sure you check the support thread when a new WordPress update gets launched. Occasionally, an\n change will mess things up so it's best to make sure the plugin works\n on the newer versions.</em></p>\n</blockquote>\n\n<hr>\n\n<p><strong><em>Extra Credit: Debugging Your Problem / Editing Other TinyMCE Options</em></strong></p>\n\n<p>If you want to inspect and easily <em>edit</em> your TinyMCE configurations manually, like you do with filters, you can install <a href=\"https://wordpress.org/plugins/advanced-tinymce-configuration/\" rel=\"nofollow noreferrer\">advanced TinyMCE config</a>. It lets you view <strong>ALL</strong> of the configured TinyMCE options and edit them from a simple interface. You can also add new options just like you would with the filters. It makes things a whole lot easier to understand.</p>\n\n<p>For example, I have both that and Preserved HTML Editor Markup Plus. The screenshot below is of the Advanced TinyMCE Config admin page. While the screenshot is cutting off 90% of what's really there, you can see it shows the valid children available to edit and which ones <strong>Preserved HTML Editor Markup Plus</strong> added. </p>\n\n<p><a href=\"https://i.stack.imgur.com/wziWi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wziWi.png\" alt=\"TinyMCE editor\"></a></p>\n\n<p>This is an extremely helpful way of not only completely customizing your editor, but also seeing what's going on. You might be even able to figure out what was causing your issue then. After looking over the parameters myself while Preserved HTML Editor Markup was enabled I saw some additional options that could be added to a custom filter.</p>\n\n<pre><code>function fix_tiny_mce_before_init( $in ) {\n\n // You can actually debug this without actually needing Advanced Tinymce Config enabled:\n // print_r( $in );\n // exit();\n\n $in['valid_children']=\"+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]\";\n $in[ 'force_p_newlines' ] = FALSE;\n $in[ 'remove_linebreaks' ] = FALSE;\n $in[ 'force_br_newlines' ] = FALSE;\n $in[ 'remove_trailing_nbsp' ] = FALSE;\n $in[ 'apply_source_formatting' ] = FALSE;\n $in[ 'convert_newlines_to_brs' ] = FALSE;\n $in[ 'verify_html' ] = FALSE;\n $in[ 'remove_redundant_brs' ] = FALSE;\n $in[ 'validate_children' ] = FALSE;\n $in[ 'forced_root_block' ]= FALSE;\n\n return $in;\n}\nadd_filter( 'tiny_mce_before_init', 'fix_tiny_mce_before_init' );\n</code></pre>\n\n<p>Unfortunately this method didn't work. There is probably some regex or JavaScript that is happening when updating the post and/or switching between editors. If you take a look at the Preserved HTML Editor source code you can see that it does some JavaScript work on the admin side so my last bit of advice would be to check <a href=\"http://plugins.svn.wordpress.org/preserved-html-editor-markup-plus/trunk/\" rel=\"nofollow noreferrer\">how the plugin works</a> if you want to add this functionality in your theme.</p>\n\n<p>Anyway, sorry for anyone who has gotten this far in my answer. Just thought I'd share my own experiences dealing with the WordPress editor, so others hopefully won't have to spend hours trying to figure this out like I did!</p>\n" }, { "answer_id": 398631, "author": "Rob", "author_id": 215310, "author_profile": "https://wordpress.stackexchange.com/users/215310", "pm_score": 0, "selected": false, "text": "<p>First of all: Many thanks for Bryans excellent answer, which documents as well the difficulties he encountered.</p>\n<p>Just as a result of own experimenting (including a bit of Bryan's suggestions), I think that the following plugin could vastly aid in <strong>consistency when swithing between html and visual editor</strong>: Advanced Editor Tools (previously TinyMCE Advanced) - <a href=\"https://wordpress.org/plugins/tinymce-advanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/tinymce-advanced/</a>.</p>\n<p>At first sight, the plugin didn't do what I expected it to do. On a second turn, I found a settings parameter &quot;preserve paragraph tags&quot;. The visual editor no longer removes <code>&lt;p&gt;</code> and <code>&lt;br&gt;</code> tags from the html editor. Even more: After switching between both editors, I found that almost all empty lines were gone and that instead many <code>&lt;p&gt;</code> and <code>&lt;/p&gt;</code> are put in instead.\nThe downside is that the visual representation in the visual editor shows some minor quirks, but that's considered a minor problem. For me counts this: You know exactly where you are with the cursor, because of nearly WYSIWYG. After all: Also without this specific setting, the visual editor <em>has</em> rendering flaws compared to preview/final result.</p>\n<p>I feel that I have quite full control over spacing in text now. Even when I hit Return in the visual editor (or shift Return), the extra tags are generated. Again a downside: You only see that in the html view (and the final view) - the visual editor does not show the extra space. So what? It counts is no longer <strong>breaking my beautiful HTML</strong>!</p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86863/" ]
I have to add a row that (containing the content of post) below the post thumbnail on clicking thumbnail. I have done it by using this but it affects the adjacent post thumbnail.I want that a complete row to be add below every post without affecting other posts. Thumbnail of each post should be remain same. ``` <?php $args = array('post_type' => 'team', 'category_name' => $a); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); ?> <div class="tab_heading col-md-4"> <div class="wrapper"> <a href="#tab-<?php echo get_the_id(); ?>"> <div class="bg_image"> <?php the_post_thumbnail(); ?> </div> </a> <p class="title-post"> <?php the_title(); ?> </p> </div> </div> <div class="tab" style=""> <div id="tab-<?php echo get_the_ID(); ?>" class="tab-content"> <div class="row"> <?php the_content(); ?> </div> </div> </div> <?php } } wp_reset_query(); ?> ``` Here is picture showing my desired design. [![enter image description here](https://i.stack.imgur.com/umsxL.png)](https://i.stack.imgur.com/umsxL.png) i want that when i click `sofia` i add a row containing the\_contentof specific post. sory for my english .
Regardless of what you have configured as valid children, WordPress handles p tags as well as line breaks in a very unique way. You'll probably notice eventually, if you haven't already, that when switching from the text editor to the visual editor and back that your `<p>` tags get stripped, similar to what occurs on the frontend. A way to block this from happening is by giving the `<p>` tags a custom class. `<p class="text">This p tag won't get removed"</p>`. While **↑** this **↑** will keep your p tag from getting stripped, it won't fix your issue as your markup on the frontend still gets mucked up. You could **DISABLE** wpautop. If you do that AND have p included in valid children, this *WILL FIX YOUR ISSSUE*. **OPTION 1 : *Disable Autop and Set Valid Children*** ``` remove_filter( 'the_content', 'wpautop' ); add_filter('tiny_mce_before_init', 'modify_valid_children', 99); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; return $settings; } ``` I should warn you though that the second you switch from the *HTML* editor back to **TinyMCE** your HTML will get destroyed. A workaround is to disable *TinyMCE* altogether for certain post types as in option 2 below. --- **OPTION 2 : *Disable Auto P, TinyMCE, and Set Valid Children*** ``` remove_filter( 'the_content', 'wpautop' ); add_filter('tiny_mce_before_init', 'modify_valid_children', 99); function modify_valid_children($settings){ $settings['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; return $settings; } add_filter('user_can_richedit', 'disable_wyswyg_to_preserve_my_markup'); function disable_wyswyg_to_preserve_my_markup( $default ){ if( get_post_type() === 'post') return false; return $default; } ``` *For most people though **↑** this **↑** is not an option.* --- So what other options are there? One workaround I've noticed works is to use a ***span tag with a class*** and make sure there ***is no white space between your HTML tags***. If you do this you can use option one above and avoid having to disable TinyMCE all together. Just remember that you'll also have to add some CSS to your stylesheet to display the span correctly. ***OPTION 3: Option 1 + Styled Span Tags*** *HTML* ``` <a href="#"><img src="https://placehold.it/300x200?text=Don%27t+P+On+Me" alt="" /><span class="noautop">Some amazing descriptive text</span></a> ``` *CSS in Stylesheet* ``` .noautop { display: block; } ``` --- ***Option 4: Use the built in media uploader shortcode*** [![shortcode media uploader](https://i.stack.imgur.com/glosr.png)](https://i.stack.imgur.com/glosr.png) *I initially forgot this one, but the [[caption]](https://github.com/WordPress/WordPress/blob/fdb6bbfa10c2acca0074c4c741f6dff122e3ce1d/wp-includes/media.php#L1433) shortcode will look like this:* ``` [caption id="attachment_167" align="alignnone" width="169"] <img class="size-medium wp-image-167" src="http://example.com/example.png" alt="" width="169" height="300" /> awesome caption [/caption] ``` *The output will look like this:* ``` <figure id="attachment_167" style="width: 169px" class="wp-caption alignnone"> <img class="size-medium wp-image-167" src="http://example.com/example.png" alt="" width="169" height="300" /> <figcaption class="wp-caption-text">Some amazing descriptive text</figcaption> </figure> ``` If you don't want figure tags you could use a plugin like [custom content shortcode](https://wordpress.org/plugins/custom-content-shortcode/) that allows you to do this: ``` [raw] <p>this content will not get filtered by wordpress</p> [/raw] ``` --- ***Why can't the editor just work how I want though?*** I've spent countless hours trying to get this to work well over the past couple years. Occasionally I'll come up with a solution that works perfectly, but then WordPress will push an update that messes everything up again. The only solution I've ever found to completely work how it should, leads me to the best answer I have. ***[Option 5 : Preserved HTML Editor Markup Plus](http://wordpress.org/plugins/preserved-html-editor-markup-plus)*** So save yourself the headache and just go with this. By default, *Preserved HTML Editor Markup Plus* only affects new pages. If you want to change pages already created, you have to go to **www.example.com/wp-admin/options-writing.php** and edit the plugin settings. You'll also be able to change the default newline behavior. > > *Note: If you do decide to use this make sure you check the support thread when a new WordPress update gets launched. Occasionally, an > change will mess things up so it's best to make sure the plugin works > on the newer versions.* > > > --- ***Extra Credit: Debugging Your Problem / Editing Other TinyMCE Options*** If you want to inspect and easily *edit* your TinyMCE configurations manually, like you do with filters, you can install [advanced TinyMCE config](https://wordpress.org/plugins/advanced-tinymce-configuration/). It lets you view **ALL** of the configured TinyMCE options and edit them from a simple interface. You can also add new options just like you would with the filters. It makes things a whole lot easier to understand. For example, I have both that and Preserved HTML Editor Markup Plus. The screenshot below is of the Advanced TinyMCE Config admin page. While the screenshot is cutting off 90% of what's really there, you can see it shows the valid children available to edit and which ones **Preserved HTML Editor Markup Plus** added. [![TinyMCE editor](https://i.stack.imgur.com/wziWi.png)](https://i.stack.imgur.com/wziWi.png) This is an extremely helpful way of not only completely customizing your editor, but also seeing what's going on. You might be even able to figure out what was causing your issue then. After looking over the parameters myself while Preserved HTML Editor Markup was enabled I saw some additional options that could be added to a custom filter. ``` function fix_tiny_mce_before_init( $in ) { // You can actually debug this without actually needing Advanced Tinymce Config enabled: // print_r( $in ); // exit(); $in['valid_children']="+a[div|p|ul|ol|li|h1|span|h2|h3|h4|h5|h5|h6]"; $in[ 'force_p_newlines' ] = FALSE; $in[ 'remove_linebreaks' ] = FALSE; $in[ 'force_br_newlines' ] = FALSE; $in[ 'remove_trailing_nbsp' ] = FALSE; $in[ 'apply_source_formatting' ] = FALSE; $in[ 'convert_newlines_to_brs' ] = FALSE; $in[ 'verify_html' ] = FALSE; $in[ 'remove_redundant_brs' ] = FALSE; $in[ 'validate_children' ] = FALSE; $in[ 'forced_root_block' ]= FALSE; return $in; } add_filter( 'tiny_mce_before_init', 'fix_tiny_mce_before_init' ); ``` Unfortunately this method didn't work. There is probably some regex or JavaScript that is happening when updating the post and/or switching between editors. If you take a look at the Preserved HTML Editor source code you can see that it does some JavaScript work on the admin side so my last bit of advice would be to check [how the plugin works](http://plugins.svn.wordpress.org/preserved-html-editor-markup-plus/trunk/) if you want to add this functionality in your theme. Anyway, sorry for anyone who has gotten this far in my answer. Just thought I'd share my own experiences dealing with the WordPress editor, so others hopefully won't have to spend hours trying to figure this out like I did!
214,640
<p>Basically in the <code>wp-admin</code> section I have a page where I attempt to export some records from a grid. I have an Export link which leads to something like <code>admin.php?page=download&amp;selected_ids=1,2,4</code>. But when I click it I get the following error:</p> <blockquote> <p>You do not have sufficient permissions to access this page.</p> </blockquote> <p>I think I need to first somehow register this page into WordPress before I can reach it through the URL. The page is just a download script called <code>download.php</code> so I don't want it to appear anywhere. It's only there to allow me to export some things and it's located in <code>my-plugin-directory/lib/download.php</code>.</p>
[ { "answer_id": 214650, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 1, "selected": false, "text": "<p>I believe you will need to add it via <code>add_menu_page</code> - but in the callback function you register that displays the page, you could re-direct away from it (or just display your own message), as needed. </p>\n\n<p>You could also remove it from showing up on the admin menu by calling <code>remove_menu_page</code> right after you add it. That ought to leave the page registered (with the access permissions needed, etc.) but simply keep it from appearing on the menu.</p>\n" }, { "answer_id": 214654, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>You can use <code>admin.php?action=my_action</code> and WordPress will fire the equivalent action hook:</p>\n\n<pre><code>// How to get the URL\n$url = admin_url( \"admin.php?action=wpse_21460_export&amp;any_other_arguments\" );\n\n// How to handle the URL\nfunction wpse_21460_export() {\n // Do your export and exit\n}\n\nadd_action( 'admin_action_wpse_21460_export', 'wpse_21460_export' );\n</code></pre>\n\n<p>See how WordPress formats the hook name to <code>admin_action_{value_of_action_param}</code></p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214640", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55042/" ]
Basically in the `wp-admin` section I have a page where I attempt to export some records from a grid. I have an Export link which leads to something like `admin.php?page=download&selected_ids=1,2,4`. But when I click it I get the following error: > > You do not have sufficient permissions to access this page. > > > I think I need to first somehow register this page into WordPress before I can reach it through the URL. The page is just a download script called `download.php` so I don't want it to appear anywhere. It's only there to allow me to export some things and it's located in `my-plugin-directory/lib/download.php`.
You can use `admin.php?action=my_action` and WordPress will fire the equivalent action hook: ``` // How to get the URL $url = admin_url( "admin.php?action=wpse_21460_export&any_other_arguments" ); // How to handle the URL function wpse_21460_export() { // Do your export and exit } add_action( 'admin_action_wpse_21460_export', 'wpse_21460_export' ); ``` See how WordPress formats the hook name to `admin_action_{value_of_action_param}`
214,641
<p>Assuming a website where page header and footer elements remain constant in every view: Due to WP's template hierarchy system, I could hard-code the general website layout in index.php. Then, I could use conditional tags in index.php to determine which inner content templates to render.</p> <p>On the other hand, I could write the basic layout in each of the main templates repeatedly. Thus, I would write some more lines of code and introduce slightly more redundancy. However, maybe I save some file I/O operations, if, say, single.php can be rendered completely without having to fall back to index.php?</p> <p><strong>Option 1</strong> without single.php, category.php, archive.php and so forth but with content-post.php, content-category.php ...</p> <pre><code>&lt;?php /** * The index.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : if (is_front_page()){ ... // some front page specific markup and settings } elseif(is_category()){ ... // some category specific markup and settings } elseif (is_singular()) { ... // some singular post specific markup and settings } elseif (is_archive()) { ... // some general archive specific markup and settings } else{ ... // defaults } while (have_posts()) : the_post(); get_template_part( 'content', get_post_format()); endwhile; endif; get_footer(); ?&gt; </code></pre> <p><strong>Option 2</strong>: Each main template file contains the whole lot, like so</p> <pre><code>&lt;?php /** * The single.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : while (have_posts()) : the_post(); ... // single post markup endwhile; endif; get_footer(); ?&gt; </code></pre> <p>And another main template file</p> <pre><code>&lt;?php /** * The category.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : while (have_posts()) : the_post(); ... // category archive markup endwhile; endif; get_footer(); ?&gt; </code></pre> <p>So, are there any performance issues involved in either option? Is it just a matter of individual taste?</p>
[ { "answer_id": 214643, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>Short and painless, I would recommend going with Option 2. </p>\n\n<p>Why? Because that is what the WordPress <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a> is there for. I can't see a reason from your question to differ from the template hierarchy concept. </p>\n\n<p>Last but not least, in some projects it might be worth considering to even get the template files loop part via <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part()</code></a>. </p>\n" }, { "answer_id": 214680, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 2, "selected": false, "text": "<p><em>Saving file I/O operations</em>.<br />\nYou can save as much as possible on that level if you wish but in the end all will come on your coding/server configuration and so on.<br />\nThe static/dynamic files can/would/should also be cached (possible on server level or by plugin/own code) and that also will help you having less worries if it is about minor things like files 'full with code' or amount of templates.\n<br /></p>\n\n<p><em>Template reducing</em><br />\nAbout your approach to reduce the use of templates, it is not always 'less is more'.<br />\nHere another example (also mentioned by ialocin):<br /> Use a standard loop (for <code>front-page.php/index.php/page.php/single.php</code> and other templates of course)\n<br /></p>\n\n<pre><code>&lt;?php\nif ( have_posts() ) : \n\n // Start the Loop.\n while ( have_posts() ) : the_post();\n\n // Include format-specific template for the content.\n get_template_part( 'content', get_post_format() );\n\n // End the loop.\n endwhile;\nelse :\n // If no content, include the \"No posts found\" template part.\n get_template_part( 'content', 'none' );\n\nendif;\n?&gt;\n</code></pre>\n\n<p>And use this example for <code>content.php</code> (which should be in the theme folder)\n<br /></p>\n\n<pre><code> &lt;?php\n if ( is_front_page() ) { get_template_part( 'include/content', 'front' ); }\n if ( is_single() ) { get_template_part( 'include/content', 'single' ); }\n if ( is_page() ) { get_template_part( 'include/content', 'page' ); }\n// and so on\n?&gt;\n</code></pre>\n\n<p>And (in the include folder) you can use files like <code>content-front.php / content-single.php</code> and so on.<br /></p>\n\n<p>These <code>template_parts</code> (which will be include in the <code>loop</code>, as mentioned in the above named files) contain the code you want to have for those template files.\n<br /></p>\n\n<blockquote>\n <p>For reference:<br /><br>\n <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow\">The loop</a><br />\n <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template-hierarchy</a><br />\n <a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">Get template part</a><br />\n <a href=\"https://developer.wordpress.org/themes/basics/organizing-theme-files/\" rel=\"nofollow\">Organizing theme files</a><br />\n <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/\" rel=\"nofollow\">Page templates</a></p>\n</blockquote>\n\n<p><br />\nThis approach <em>seems</em> 'less sensitive' for a site when making just one little mistake. Because ppl will work mainly in the template parts(in that subfolder). <em>Ofcourse all depends on the kind of mistake but I think you know what is meant.</em></p>\n\n<p>Imho is it this way also faster/easier to trigger down errors and a little more easy-reference.</p>\n" }, { "answer_id": 214720, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>Option 2 is the best option. To know why, one needs to look at the <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/template-loader.php#L58\">template loader</a>.</p>\n\n<p>(<em>The <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\">template hierarchy</a> means nothing, if you do not know how it really works or come from</em>)</p>\n\n<pre><code> if ( defined('WP_USE_THEMES') &amp;&amp; WP_USE_THEMES ) :\n59 $template = false;\n60 if ( is_404() &amp;&amp; $template = get_404_template() ) :\n61 elseif ( is_search() &amp;&amp; $template = get_search_template() ) :\n62 elseif ( is_front_page() &amp;&amp; $template = get_front_page_template() ) :\n63 elseif ( is_home() &amp;&amp; $template = get_home_template() ) :\n64 elseif ( is_post_type_archive() &amp;&amp; $template = get_post_type_archive_template() ) :\n65 elseif ( is_tax() &amp;&amp; $template = get_taxonomy_template() ) :\n66 elseif ( is_attachment() &amp;&amp; $template = get_attachment_template() ) :\n67 remove_filter('the_content', 'prepend_attachment');\n68 elseif ( is_single() &amp;&amp; $template = get_single_template() ) :\n69 elseif ( is_page() &amp;&amp; $template = get_page_template() ) :\n70 elseif ( is_singular() &amp;&amp; $template = get_singular_template() ) :\n71 elseif ( is_category() &amp;&amp; $template = get_category_template() ) :\n72 elseif ( is_tag() &amp;&amp; $template = get_tag_template() ) :\n73 elseif ( is_author() &amp;&amp; $template = get_author_template() ) :\n74 elseif ( is_date() &amp;&amp; $template = get_date_template() ) :\n75 elseif ( is_archive() &amp;&amp; $template = get_archive_template() ) :\n76 elseif ( is_comments_popup() &amp;&amp; $template = get_comments_popup_template() ) :\n77 elseif ( is_paged() &amp;&amp; $template = get_paged_template() ) :\n78 else :\n79 $template = get_index_template();\n80 endif;\n</code></pre>\n\n<p>This template loader runs on each and every page load on the front end regardless. As you can see, WordPress goes through a list and validates the conditions against the page being requested. Lets use a category page as example with the category being the <em>Uncategorized</em> category.</p>\n\n<p>An if/else statement executes the first condition that returns true, and on category pages it will be the <code>is_category()</code> conditional statement. This statement executes <a href=\"https://developer.wordpress.org/reference/functions/get_category_template/\"><code>get_category_template()</code></a> and also valuates the statement. If this statement also ring true (<em>a valid category page is available</em>), the template is loaded accordingly to what was found, if this statement return a false, the template loader carries on to find the next true statement which I will tackle a bit later.</p>\n\n<p>What happens inside <code>get_category_template()</code> is important. The function creates three template names according to the category page being requested. As example, the following is created in order, <code>category-uncategorized.php</code>, <code>category-1.php</code> and <code>category.php</code>. This template names are stored in an array and passed to <a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\"><code>get_query_template()</code></a>. This is the function that has the task to search for the template names passed to it and to return the first template that exists and are available. This is done with <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\"><code>locate_template()</code></a>.</p>\n\n<p>So what this is saying is, WordPress (<em>actually <code>locate_template()</code> if you want to get technical</em>) starts by looking for <code>category-uncategorized.php</code>, if it is found, the template is returned and loaded. If not found, WordPress moves on tries <code>category-1.php</code> and if that fails it lastly tries <code>category.php</code>. If none are found, as I said, our </p>\n\n<pre><code>elseif ( is_category() &amp;&amp; $template = get_category_template() \n</code></pre>\n\n<p>condition returns false and the conditions further down are evaluated. The next condition that rings true will be <code>is_archive()</code> (<em>remember, <code>is_archive()</code> returns true on category, tag, taxonomy, custom post type archives, author and date related pages</em>). The same process as above happens but this time with <code>archive.php</code> being looked for and loaded if it exists. If <code>archive.php</code> does not exist, the whole conditional statements valuates to it's default which loads <code>index.php</code> through <code>get_index_template()</code>. This is the ultimate fallback for every page</p>\n\n<h2>CONCLUSION AND FINAL ANSWER</h2>\n\n<p>Even though you might think that having <code>category.php</code> will result in a big overhead, it does not. By the time that <code>index.php</code> is loaded on your category page, (<em>lets use our example again</em>) for the <em>uncategorized</em> category, WordPress has already looked and tried to load <code>category-uncategorized.php</code>, <code>category-1.php</code>, <code>category.php</code> and <code>archive.php</code>. So go on and have your nice-to-have templates (<em>all templates except <code>index.php</code></em>)(<em>which is your <strong>OPTION 2</em></strong>). Having 10 nice-to-have templates is better than an <code>index.php</code> which is as long as the Nile river and have more logic crammed into it than what Albert Einstein had in his brain (<em>which is your <strong>OPTION 1</em></strong>)</p>\n\n<p>It is also very important, coming back to <em>Option1</em> that you keep templates as short as possible, maintainable and readable. It is really of no use having a template, which might be 0.0000001 seconds faster, but is a total mess and a real nightmare to maintain. </p>\n\n<p>At the end, option 2 has much much more pro's than option 1.</p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63707/" ]
Assuming a website where page header and footer elements remain constant in every view: Due to WP's template hierarchy system, I could hard-code the general website layout in index.php. Then, I could use conditional tags in index.php to determine which inner content templates to render. On the other hand, I could write the basic layout in each of the main templates repeatedly. Thus, I would write some more lines of code and introduce slightly more redundancy. However, maybe I save some file I/O operations, if, say, single.php can be rendered completely without having to fall back to index.php? **Option 1** without single.php, category.php, archive.php and so forth but with content-post.php, content-category.php ... ``` <?php /** * The index.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : if (is_front_page()){ ... // some front page specific markup and settings } elseif(is_category()){ ... // some category specific markup and settings } elseif (is_singular()) { ... // some singular post specific markup and settings } elseif (is_archive()) { ... // some general archive specific markup and settings } else{ ... // defaults } while (have_posts()) : the_post(); get_template_part( 'content', get_post_format()); endwhile; endif; get_footer(); ?> ``` **Option 2**: Each main template file contains the whole lot, like so ``` <?php /** * The single.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : while (have_posts()) : the_post(); ... // single post markup endwhile; endif; get_footer(); ?> ``` And another main template file ``` <?php /** * The category.php file * */ get_header(); get_template_part('partials/layout-block-01'); get_template_part('partials/layout-block-02'); if (have_posts()) : while (have_posts()) : the_post(); ... // category archive markup endwhile; endif; get_footer(); ?> ``` So, are there any performance issues involved in either option? Is it just a matter of individual taste?
Option 2 is the best option. To know why, one needs to look at the [template loader](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/template-loader.php#L58). (*The [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) means nothing, if you do not know how it really works or come from*) ``` if ( defined('WP_USE_THEMES') && WP_USE_THEMES ) : 59 $template = false; 60 if ( is_404() && $template = get_404_template() ) : 61 elseif ( is_search() && $template = get_search_template() ) : 62 elseif ( is_front_page() && $template = get_front_page_template() ) : 63 elseif ( is_home() && $template = get_home_template() ) : 64 elseif ( is_post_type_archive() && $template = get_post_type_archive_template() ) : 65 elseif ( is_tax() && $template = get_taxonomy_template() ) : 66 elseif ( is_attachment() && $template = get_attachment_template() ) : 67 remove_filter('the_content', 'prepend_attachment'); 68 elseif ( is_single() && $template = get_single_template() ) : 69 elseif ( is_page() && $template = get_page_template() ) : 70 elseif ( is_singular() && $template = get_singular_template() ) : 71 elseif ( is_category() && $template = get_category_template() ) : 72 elseif ( is_tag() && $template = get_tag_template() ) : 73 elseif ( is_author() && $template = get_author_template() ) : 74 elseif ( is_date() && $template = get_date_template() ) : 75 elseif ( is_archive() && $template = get_archive_template() ) : 76 elseif ( is_comments_popup() && $template = get_comments_popup_template() ) : 77 elseif ( is_paged() && $template = get_paged_template() ) : 78 else : 79 $template = get_index_template(); 80 endif; ``` This template loader runs on each and every page load on the front end regardless. As you can see, WordPress goes through a list and validates the conditions against the page being requested. Lets use a category page as example with the category being the *Uncategorized* category. An if/else statement executes the first condition that returns true, and on category pages it will be the `is_category()` conditional statement. This statement executes [`get_category_template()`](https://developer.wordpress.org/reference/functions/get_category_template/) and also valuates the statement. If this statement also ring true (*a valid category page is available*), the template is loaded accordingly to what was found, if this statement return a false, the template loader carries on to find the next true statement which I will tackle a bit later. What happens inside `get_category_template()` is important. The function creates three template names according to the category page being requested. As example, the following is created in order, `category-uncategorized.php`, `category-1.php` and `category.php`. This template names are stored in an array and passed to [`get_query_template()`](https://developer.wordpress.org/reference/functions/get_query_template/). This is the function that has the task to search for the template names passed to it and to return the first template that exists and are available. This is done with [`locate_template()`](https://developer.wordpress.org/reference/functions/locate_template/). So what this is saying is, WordPress (*actually `locate_template()` if you want to get technical*) starts by looking for `category-uncategorized.php`, if it is found, the template is returned and loaded. If not found, WordPress moves on tries `category-1.php` and if that fails it lastly tries `category.php`. If none are found, as I said, our ``` elseif ( is_category() && $template = get_category_template() ``` condition returns false and the conditions further down are evaluated. The next condition that rings true will be `is_archive()` (*remember, `is_archive()` returns true on category, tag, taxonomy, custom post type archives, author and date related pages*). The same process as above happens but this time with `archive.php` being looked for and loaded if it exists. If `archive.php` does not exist, the whole conditional statements valuates to it's default which loads `index.php` through `get_index_template()`. This is the ultimate fallback for every page CONCLUSION AND FINAL ANSWER --------------------------- Even though you might think that having `category.php` will result in a big overhead, it does not. By the time that `index.php` is loaded on your category page, (*lets use our example again*) for the *uncategorized* category, WordPress has already looked and tried to load `category-uncategorized.php`, `category-1.php`, `category.php` and `archive.php`. So go on and have your nice-to-have templates (*all templates except `index.php`*)(*which is your **OPTION 2***). Having 10 nice-to-have templates is better than an `index.php` which is as long as the Nile river and have more logic crammed into it than what Albert Einstein had in his brain (*which is your **OPTION 1***) It is also very important, coming back to *Option1* that you keep templates as short as possible, maintainable and readable. It is really of no use having a template, which might be 0.0000001 seconds faster, but is a total mess and a real nightmare to maintain. At the end, option 2 has much much more pro's than option 1.
214,652
<p>I am trying to create dynamic listbox values but getting this error in console: Uncaught TypeError: Cannot assign to read only property 'active' of [</p> <p>Here's my code( pasting only the code for listbox ):</p> <pre><code> body: [ { type: 'listbox', name: 'type', label: 'Panel Type', value: type, 'values': get_author_list(), tooltip: 'Select the type of panel you want' }, ] ..... </code></pre> <p>And I am calling this function to get dynamic list...</p> <pre><code> function get_author_list() { var d = "[{text: 'Default', value: 'default'}]"; return d; } </code></pre> <p>I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?</p> <p>Thanks, in advance!! </p>
[ { "answer_id": 215570, "author": "Jeroen", "author_id": 83390, "author_profile": "https://wordpress.stackexchange.com/users/83390", "pm_score": 0, "selected": false, "text": "<p>If you make a reference to another function in Javascript I don't think you need the () after get_author_list.</p>\n\n<pre><code> body: [\n {\n type: 'listbox',\n name: 'type',\n label: 'Panel Type',\n value: type,\n 'values': get_author_list,\n tooltip: 'Select the type of panel you want'\n },\n ]\n</code></pre>\n\n<p>Also, I don't think you need the quotes around the object.</p>\n\n<pre><code> function get_author_list() {\n var d = [{text: 'Default', value: 'default'}];\n\n return d;\n}\n</code></pre>\n" }, { "answer_id": 215573, "author": "Parth Kumar", "author_id": 43572, "author_profile": "https://wordpress.stackexchange.com/users/43572", "pm_score": 2, "selected": true, "text": "<p>So the problem with the values helper was that it will only take array of objects and i was passing a string...I have corrected the code by passing an array of objects..Below is the corrected code..</p>\n\n<pre><code>body: [\n {\n type: 'listbox',\n name: 'type',\n label: 'Panel Type',\n value: type,\n 'values': get_author_list(),\n tooltip: 'Select the type of panel you want'\n },\n]\n.....\n\nfunction get_authors_list() {\n var result = [];\n var d = {};\n d['text'] = 'Default';\n d['value'] = 'default';\n result.push(d);\n return result;\n}\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43572/" ]
I am trying to create dynamic listbox values but getting this error in console: Uncaught TypeError: Cannot assign to read only property 'active' of [ Here's my code( pasting only the code for listbox ): ``` body: [ { type: 'listbox', name: 'type', label: 'Panel Type', value: type, 'values': get_author_list(), tooltip: 'Select the type of panel you want' }, ] ..... ``` And I am calling this function to get dynamic list... ``` function get_author_list() { var d = "[{text: 'Default', value: 'default'}]"; return d; } ``` I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax? Thanks, in advance!!
So the problem with the values helper was that it will only take array of objects and i was passing a string...I have corrected the code by passing an array of objects..Below is the corrected code.. ``` body: [ { type: 'listbox', name: 'type', label: 'Panel Type', value: type, 'values': get_author_list(), tooltip: 'Select the type of panel you want' }, ] ..... function get_authors_list() { var result = []; var d = {}; d['text'] = 'Default'; d['value'] = 'default'; result.push(d); return result; } ```
214,673
<p>I have a new install of WordPress on my Mac mini server. The site uses SSL and has a valid up to date certificate from StartCom. </p> <p>The site loads, but with no CSS or theme.</p> <p>Mainly, I can't get into wp-admin (or wp-login.php) as it redirects with two 301 redirects and then multiple 302 redirects. I used <a href="http://redirectdetective.com" rel="nofollow">http://redirectdetective.com</a> to find out what was happening, but now I don't know how to fix the redirects.</p> <p>Here is my .htaccess</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre>
[ { "answer_id": 215570, "author": "Jeroen", "author_id": 83390, "author_profile": "https://wordpress.stackexchange.com/users/83390", "pm_score": 0, "selected": false, "text": "<p>If you make a reference to another function in Javascript I don't think you need the () after get_author_list.</p>\n\n<pre><code> body: [\n {\n type: 'listbox',\n name: 'type',\n label: 'Panel Type',\n value: type,\n 'values': get_author_list,\n tooltip: 'Select the type of panel you want'\n },\n ]\n</code></pre>\n\n<p>Also, I don't think you need the quotes around the object.</p>\n\n<pre><code> function get_author_list() {\n var d = [{text: 'Default', value: 'default'}];\n\n return d;\n}\n</code></pre>\n" }, { "answer_id": 215573, "author": "Parth Kumar", "author_id": 43572, "author_profile": "https://wordpress.stackexchange.com/users/43572", "pm_score": 2, "selected": true, "text": "<p>So the problem with the values helper was that it will only take array of objects and i was passing a string...I have corrected the code by passing an array of objects..Below is the corrected code..</p>\n\n<pre><code>body: [\n {\n type: 'listbox',\n name: 'type',\n label: 'Panel Type',\n value: type,\n 'values': get_author_list(),\n tooltip: 'Select the type of panel you want'\n },\n]\n.....\n\nfunction get_authors_list() {\n var result = [];\n var d = {};\n d['text'] = 'Default';\n d['value'] = 'default';\n result.push(d);\n return result;\n}\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214673", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86889/" ]
I have a new install of WordPress on my Mac mini server. The site uses SSL and has a valid up to date certificate from StartCom. The site loads, but with no CSS or theme. Mainly, I can't get into wp-admin (or wp-login.php) as it redirects with two 301 redirects and then multiple 302 redirects. I used <http://redirectdetective.com> to find out what was happening, but now I don't know how to fix the redirects. Here is my .htaccess ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ```
So the problem with the values helper was that it will only take array of objects and i was passing a string...I have corrected the code by passing an array of objects..Below is the corrected code.. ``` body: [ { type: 'listbox', name: 'type', label: 'Panel Type', value: type, 'values': get_author_list(), tooltip: 'Select the type of panel you want' }, ] ..... function get_authors_list() { var result = []; var d = {}; d['text'] = 'Default'; d['value'] = 'default'; result.push(d); return result; } ```
214,674
<h3>The scenario</h3> <p>I'm developing a plugin, and part of it requires lots of text content (help descriptions) that I would prefer to keep as separate text files (in a subdirectory within the plugin) for organisational and version control purposes. The obvious candidate would be <code>file_get_contents()</code>, but its usage with WordPress is generally frowned upon. I've looked at some alternatives, such as <code>wp_remote_get()</code> (not the right one as the files are <em>in</em> the plugin) and the <code>WP_Filesystem</code> API (which seems overkill for a simple reading of text files). <strong>Is there a simple, but secure alternative?</strong> I have the nagging feeling I'm missing something very obvious.</p> <h3>The spec</h3> <p>I'm looking for a solution to:</p> <ol> <li>Read the contents of a HTML/text file into a variable</li> <li>That won't flag as insecure when used with Theme Check or similar plugins</li> <li>Doesn't require any writing to the files whatsoever</li> </ol>
[ { "answer_id": 214675, "author": "Jim Maguire", "author_id": 63669, "author_profile": "https://wordpress.stackexchange.com/users/63669", "pm_score": -1, "selected": false, "text": "<p>Put this in your plugin file:</p>\n\n<pre><code>add_action('init', 'captureFileToVariable');\n\nfunction captureFileToVariable(){\n $fileName = \"FileIWantToLoad.txt\";\n $pluginDirectory = plugin_dir_path( __FILE__ );\n $filePath = $pluginDirectory . $fileName;\n $fileContents = file_get_contents($filePath);\n //die($fileContents);\n}\n</code></pre>\n" }, { "answer_id": 306765, "author": "rfair404", "author_id": 291, "author_profile": "https://wordpress.stackexchange.com/users/291", "pm_score": 1, "selected": false, "text": "<p>I had to dig pretty deep for this too, and eventually figured out some way to do this. </p>\n\n<p>in my solution I used the following:</p>\n\n<pre><code>WP_Filesystem();\nglobal $wp_filesystem;\n$wp_filesystem-&gt;exists( '/path/to/file' ); //use any other functions available in the Filesystem API: @see https://developer.wordpress.org/reference/classes/wp_filesystem_direct/\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214674", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60767/" ]
### The scenario I'm developing a plugin, and part of it requires lots of text content (help descriptions) that I would prefer to keep as separate text files (in a subdirectory within the plugin) for organisational and version control purposes. The obvious candidate would be `file_get_contents()`, but its usage with WordPress is generally frowned upon. I've looked at some alternatives, such as `wp_remote_get()` (not the right one as the files are *in* the plugin) and the `WP_Filesystem` API (which seems overkill for a simple reading of text files). **Is there a simple, but secure alternative?** I have the nagging feeling I'm missing something very obvious. ### The spec I'm looking for a solution to: 1. Read the contents of a HTML/text file into a variable 2. That won't flag as insecure when used with Theme Check or similar plugins 3. Doesn't require any writing to the files whatsoever
I had to dig pretty deep for this too, and eventually figured out some way to do this. in my solution I used the following: ``` WP_Filesystem(); global $wp_filesystem; $wp_filesystem->exists( '/path/to/file' ); //use any other functions available in the Filesystem API: @see https://developer.wordpress.org/reference/classes/wp_filesystem_direct/ ```
214,686
<p>I'm trying to obtain all orders for particular day/time and then order products using SQL (MySQL) as seen in the query below:</p> <pre><code>select p.ID as order_id, p.post_date, i.order_item_name, max( CASE WHEN im.meta_key = '_product_id' and p.ID = im.order_item_id THEN im.meta_value END ) as Prod_ID from wp_posts as p, wp_postmeta as pm, wp_woocommerce_order_items as i, wp_woocommerce_order_itemmeta as im where p.post_type = 'shop_order' and p.ID = pm.post_id and p.ID = i.order_id and p.post_date BETWEEN '2016-01-14 00:00:00' AND '2016-01-14 23:59:59' and p.post_status = 'wc-processing' </code></pre> <p>It looks like when I try to query <code>wp_woocommerce_order_itemmeta</code> table for ordered products data I'm loosing connection to a database (connection timed out during a query).</p> <p>Any clue what is going on?</p>
[ { "answer_id": 214675, "author": "Jim Maguire", "author_id": 63669, "author_profile": "https://wordpress.stackexchange.com/users/63669", "pm_score": -1, "selected": false, "text": "<p>Put this in your plugin file:</p>\n\n<pre><code>add_action('init', 'captureFileToVariable');\n\nfunction captureFileToVariable(){\n $fileName = \"FileIWantToLoad.txt\";\n $pluginDirectory = plugin_dir_path( __FILE__ );\n $filePath = $pluginDirectory . $fileName;\n $fileContents = file_get_contents($filePath);\n //die($fileContents);\n}\n</code></pre>\n" }, { "answer_id": 306765, "author": "rfair404", "author_id": 291, "author_profile": "https://wordpress.stackexchange.com/users/291", "pm_score": 1, "selected": false, "text": "<p>I had to dig pretty deep for this too, and eventually figured out some way to do this. </p>\n\n<p>in my solution I used the following:</p>\n\n<pre><code>WP_Filesystem();\nglobal $wp_filesystem;\n$wp_filesystem-&gt;exists( '/path/to/file' ); //use any other functions available in the Filesystem API: @see https://developer.wordpress.org/reference/classes/wp_filesystem_direct/\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28491/" ]
I'm trying to obtain all orders for particular day/time and then order products using SQL (MySQL) as seen in the query below: ``` select p.ID as order_id, p.post_date, i.order_item_name, max( CASE WHEN im.meta_key = '_product_id' and p.ID = im.order_item_id THEN im.meta_value END ) as Prod_ID from wp_posts as p, wp_postmeta as pm, wp_woocommerce_order_items as i, wp_woocommerce_order_itemmeta as im where p.post_type = 'shop_order' and p.ID = pm.post_id and p.ID = i.order_id and p.post_date BETWEEN '2016-01-14 00:00:00' AND '2016-01-14 23:59:59' and p.post_status = 'wc-processing' ``` It looks like when I try to query `wp_woocommerce_order_itemmeta` table for ordered products data I'm loosing connection to a database (connection timed out during a query). Any clue what is going on?
I had to dig pretty deep for this too, and eventually figured out some way to do this. in my solution I used the following: ``` WP_Filesystem(); global $wp_filesystem; $wp_filesystem->exists( '/path/to/file' ); //use any other functions available in the Filesystem API: @see https://developer.wordpress.org/reference/classes/wp_filesystem_direct/ ```
214,687
<p>I'm making a category archive template that works for <em>all</em> my categories. I need to dynamically set the <code>'category'</code> parameter of <code>WP_Query</code> inside of this template to make it work. </p> <p>How do I dynamically get a string of the current category page name to feed into the WP_Query? All the methods I've seen presupposed that I know my <code>ID</code> or <code>slug</code>. As this is an archive page, most WP functions will not return the archive page title but rather a post title.</p> <p>The best option I've see is: <code>$current_category = single_cat_title("", false);</code></p> <p>But it still displays the title on my <code>category.php</code> page - maybe I'm doing something wrong with this?</p>
[ { "answer_id": 214691, "author": "serraosays", "author_id": 59627, "author_profile": "https://wordpress.stackexchange.com/users/59627", "pm_score": 2, "selected": false, "text": "<p>This is the only option I have found:</p>\n\n<pre><code>$current_category = single_cat_title(\"\", false);\n</code></pre>\n" }, { "answer_id": 214695, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>To answer your question, <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow\"><code>get_queried_object</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object_id/\" rel=\"nofollow\"><code>get_queried_object_id</code></a> will give you all the info you need about most types of pages.</p>\n\n<p>However- if you're creating a new query in the template to change some query parameters, then you should instead be using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> to alter the main query before it's run. Then you can just run the regular loop in your template.</p>\n\n<p>For example, changing <code>posts_per_page</code> on a category archive:</p>\n\n<pre><code>function wpd_category_query( $query ) {\n if ( $query-&gt;is_category() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'posts_per_page', 15 );\n }\n}\nadd_action( 'pre_get_posts','wpd_category_query' );\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214687", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59627/" ]
I'm making a category archive template that works for *all* my categories. I need to dynamically set the `'category'` parameter of `WP_Query` inside of this template to make it work. How do I dynamically get a string of the current category page name to feed into the WP\_Query? All the methods I've seen presupposed that I know my `ID` or `slug`. As this is an archive page, most WP functions will not return the archive page title but rather a post title. The best option I've see is: `$current_category = single_cat_title("", false);` But it still displays the title on my `category.php` page - maybe I'm doing something wrong with this?
This is the only option I have found: ``` $current_category = single_cat_title("", false); ```
214,688
<p>I have to add <code>itemprop="url"</code> to the links of the links in the navbar of <a href="http://www.anahatatantra.com/" rel="nofollow">this site</a>.</p> <p>In the settings I found the function <code>wp_nav_menu()</code>. Even after reading the WP codex, I am not able to make the necessary changes by myself.</p> <p>Here is the code:</p> <pre><code>&lt;!-- BEGIN MAIN NAVIGATION --&gt; &lt;nav class="nav nav__primary clearfix"&gt; &lt;?php if (has_nav_menu('header_menu')) { wp_nav_menu( array( 'container' =&gt; 'ul', 'menu_class' =&gt; 'sf-menu', 'menu_id' =&gt; 'topnav', 'depth' =&gt; 0, 'theme_location' =&gt; 'header_menu', 'walker' =&gt; new description_walker() )); } else { echo '&lt;ul class="sf-menu"&gt;'; $ex_page = get_page_by_title( 'Privacy Policy' ); if ($ex_page === NULL) { $ex_page_id = ''; } else { $ex_page_id = $ex_page-&gt;ID; } wp_list_pages( array( 'depth' =&gt; 0, 'title_li' =&gt; '', 'exclude' =&gt; $ex_page_id ) ); echo '&lt;/ul&gt;'; } ?&gt; &lt;/nav&gt;&lt;!-- END MAIN NAVIGATION --&gt; </code></pre> <p>And here is the Walker class:</p> <pre><code>/* * Navigation with description * */ if (! class_exists('description_walker')) { class description_walker extends Walker_Nav_Menu { function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names = ' class="'. esc_attr( $class_names ) . '"'; $output .= $indent . '&lt;li id="menu-item-'. $item-&gt;ID . '"' . $value . $class_names .'&gt;'; // $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr( $item-&gt;attr_title ) .'"' : ''; // $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr( $item-&gt;target ) .'"' : ''; // $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr( $item-&gt;xfn ) .'"' : ''; // $attributes .= ! empty( $item-&gt;url ) ? ' href="' . esc_attr( $item-&gt;url ) .'"' : ''; $atts = array(); $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : ''; $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : ''; $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : ''; $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : ''; /** * Filter the HTML attributes applied to a menu item's &lt;a&gt;. * * @since 3.6.0 * * @see wp_nav_menu() * * @param array $atts { * The HTML attributes applied to the menu item's &lt;a&gt;, empty strings are ignored. * * @type string $title Title attribute. * @type string $target Target attribute. * @type string $rel The rel attribute. * @type string $href The href attribute. * } * @param object $item The current menu item. * @param array $args An array of wp_nav_menu() arguments. */ $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; foreach ( $atts as $attr =&gt; $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $description = ! empty( $item-&gt;description ) ? '&lt;span class="desc"&gt;'.esc_attr( $item-&gt;description ).'&lt;/span&gt;' : ''; if($depth != 0) { $description = $append = $prepend = ""; } $item_output = $args-&gt;before; $item_output .= '&lt;a'. $attributes .'&gt;'; $item_output .= $args-&gt;link_before; if (isset($prepend)) $item_output .= $prepend; $item_output .= apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ); if (isset($append)) $item_output .= $append; $item_output .= $description.$args-&gt;link_after; $item_output .= '&lt;/a&gt;'; $item_output .= $args-&gt;after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } } </code></pre> <p>So the final links will look like this:</p> <pre><code>&lt;li id="menu-item-2005" class="menu-item menu-item-type-post_type menu-item-object-page"&gt;&lt;a itemprop="url" title="thetitle" href="http://thesite.com/about-us/"&gt;About Us&lt;/a&gt;&lt;/li&gt; </code></pre> <p>How can I achieve it?</p>
[ { "answer_id": 214693, "author": "Pikk", "author_id": 41456, "author_profile": "https://wordpress.stackexchange.com/users/41456", "pm_score": 0, "selected": false, "text": "<p>The change to be done is to change:</p>\n\n<pre><code>$item_output .= '&lt;a'. $attributes .'&gt;';\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$item_output .= '&lt;a itemprop=url'. $attributes .'&gt;';\n</code></pre>\n" }, { "answer_id": 214759, "author": "Maqk", "author_id": 86885, "author_profile": "https://wordpress.stackexchange.com/users/86885", "pm_score": 1, "selected": false, "text": "<p>To add a new attribute to your anchor link for the nav items concatenate $attribute variable with your required attribute. You have commended code just uncomment the code and use those</p>\n\n<pre><code> $attributes = ! empty( $item-&gt;attr_title ) ? ' title=\"' . esc_atta( $item-&gt;attr_title ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;target ) ? ' target=\"' . esc_atto( $item-&gt;target ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;xfn ) ? ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' href=\"' . esc_attr( $item-&gt;url ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' itemprop=\"' . esc_attr( $item-&gt;url ) .'\"' : '';\n\n //$atts = array();\n //$atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n //$atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n //$atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n //$atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n</code></pre>\n\n<p>Hope this works for you.</p>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41456/" ]
I have to add `itemprop="url"` to the links of the links in the navbar of [this site](http://www.anahatatantra.com/). In the settings I found the function `wp_nav_menu()`. Even after reading the WP codex, I am not able to make the necessary changes by myself. Here is the code: ``` <!-- BEGIN MAIN NAVIGATION --> <nav class="nav nav__primary clearfix"> <?php if (has_nav_menu('header_menu')) { wp_nav_menu( array( 'container' => 'ul', 'menu_class' => 'sf-menu', 'menu_id' => 'topnav', 'depth' => 0, 'theme_location' => 'header_menu', 'walker' => new description_walker() )); } else { echo '<ul class="sf-menu">'; $ex_page = get_page_by_title( 'Privacy Policy' ); if ($ex_page === NULL) { $ex_page_id = ''; } else { $ex_page_id = $ex_page->ID; } wp_list_pages( array( 'depth' => 0, 'title_li' => '', 'exclude' => $ex_page_id ) ); echo '</ul>'; } ?> </nav><!-- END MAIN NAVIGATION --> ``` And here is the Walker class: ``` /* * Navigation with description * */ if (! class_exists('description_walker')) { class description_walker extends Walker_Nav_Menu { function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names = ' class="'. esc_attr( $class_names ) . '"'; $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>'; // $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; // $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; // $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; // $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; /** * Filter the HTML attributes applied to a menu item's <a>. * * @since 3.6.0 * * @see wp_nav_menu() * * @param array $atts { * The HTML attributes applied to the menu item's <a>, empty strings are ignored. * * @type string $title Title attribute. * @type string $target Target attribute. * @type string $rel The rel attribute. * @type string $href The href attribute. * } * @param object $item The current menu item. * @param array $args An array of wp_nav_menu() arguments. */ $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $description = ! empty( $item->description ) ? '<span class="desc">'.esc_attr( $item->description ).'</span>' : ''; if($depth != 0) { $description = $append = $prepend = ""; } $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before; if (isset($prepend)) $item_output .= $prepend; $item_output .= apply_filters( 'the_title', $item->title, $item->ID ); if (isset($append)) $item_output .= $append; $item_output .= $description.$args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } } ``` So the final links will look like this: ``` <li id="menu-item-2005" class="menu-item menu-item-type-post_type menu-item-object-page"><a itemprop="url" title="thetitle" href="http://thesite.com/about-us/">About Us</a></li> ``` How can I achieve it?
To add a new attribute to your anchor link for the nav items concatenate $attribute variable with your required attribute. You have commended code just uncomment the code and use those ``` $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_atta( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_atto( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' itemprop="' . esc_attr( $item->url ) .'"' : ''; //$atts = array(); //$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; //$atts['target'] = ! empty( $item->target ) ? $item->target : ''; //$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; //$atts['href'] = ! empty( $item->url ) ? $item->url : ''; ``` Hope this works for you.
214,699
<p>I have a WP_Query loop that gets posts of a certain type. These posts have custom post meta so I need to be able to get the ID of the post without echoing it so I can display that post's meta. How can I get the ID of the post without echoing it? This is my code:</p> <pre><code>$menu_id = get_the_id(); $category_args = array( 'post_type' =&gt; 'category', 'post_parent' =&gt; $menu_id ); $menu_categories = new WP_Query($category_args); while($menu_categories-&gt;have_posts()) : $menu_categories-&gt;the_post(); $category_id = ??????; ?&gt; &lt;h4&gt;&lt;?php echo the_title(); ?&gt;&lt;/h4&gt;&lt;?php $dish_args = array( 'post_type' =&gt; 'dish', 'post_parent' =&gt; $category_id ); $category_dishes = new WP_Query($dish_args); while($category_dishes-&gt;have_posts()) : $category_dishes-&gt;the_post(); $dish_meta = get_post_meta(???????);?&gt; &lt;h6&gt;&lt;?php echo the_title(); ?&gt; - &lt;?php echo $dish_meta[0]['price']; ?&gt;&lt;/h6&gt; &lt;p&gt;&lt;?php echo the_content(); ?&gt;&lt;/p&gt;&lt;?php endwhile; endwhile; </code></pre>
[ { "answer_id": 214718, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 5, "selected": false, "text": "<p><code>get_the_ID()</code> can <em>(only)</em> be used within the loop. </p>\n\n<p>This retrieves the <code>ID</code> of the current post handled by the loop.</p>\n\n<hr>\n\n<p>You can use it on it's own if you need it only once:</p>\n\n<pre><code>$dish_meta = get_post_meta( get_the_ID(), 'dish_meta', true );\n</code></pre>\n\n<p>You can also store it as a variable if you need it more than once:</p>\n\n<pre><code>$post_id = get_the_ID();\n\n$dish_meta = get_post_meta( $post_id, 'dish_meta', true );\n\n$drink_meta = get_post_meta( $post_id, 'drink_meta', true );\n\nprint_r( $post_id );\n\n//etc\n</code></pre>\n\n<hr>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_the_ID\" rel=\"noreferrer\">get_the_ID()</a></p>\n" }, { "answer_id": 312982, "author": "YoJey Thilipan", "author_id": 149667, "author_profile": "https://wordpress.stackexchange.com/users/149667", "pm_score": 3, "selected": false, "text": "<p>get_the_ID() function will give you post ID..,</p>\n\n<pre><code> $args = array(\n\n 's' =&gt; $_POST['search_text'],\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'address'\n\n );\n\n $query = new WP_Query( $args );\n\n if ( $query-&gt;have_posts() ) {\n\n while ( $query-&gt;have_posts() ) {\n\n $query-&gt;the_post();\n\n $address_post_id = get_the_ID() ;\n }\n }\n</code></pre>\n" } ]
2016/01/15
[ "https://wordpress.stackexchange.com/questions/214699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86835/" ]
I have a WP\_Query loop that gets posts of a certain type. These posts have custom post meta so I need to be able to get the ID of the post without echoing it so I can display that post's meta. How can I get the ID of the post without echoing it? This is my code: ``` $menu_id = get_the_id(); $category_args = array( 'post_type' => 'category', 'post_parent' => $menu_id ); $menu_categories = new WP_Query($category_args); while($menu_categories->have_posts()) : $menu_categories->the_post(); $category_id = ??????; ?> <h4><?php echo the_title(); ?></h4><?php $dish_args = array( 'post_type' => 'dish', 'post_parent' => $category_id ); $category_dishes = new WP_Query($dish_args); while($category_dishes->have_posts()) : $category_dishes->the_post(); $dish_meta = get_post_meta(???????);?> <h6><?php echo the_title(); ?> - <?php echo $dish_meta[0]['price']; ?></h6> <p><?php echo the_content(); ?></p><?php endwhile; endwhile; ```
`get_the_ID()` can *(only)* be used within the loop. This retrieves the `ID` of the current post handled by the loop. --- You can use it on it's own if you need it only once: ``` $dish_meta = get_post_meta( get_the_ID(), 'dish_meta', true ); ``` You can also store it as a variable if you need it more than once: ``` $post_id = get_the_ID(); $dish_meta = get_post_meta( $post_id, 'dish_meta', true ); $drink_meta = get_post_meta( $post_id, 'drink_meta', true ); print_r( $post_id ); //etc ``` --- Reference: [get\_the\_ID()](https://codex.wordpress.org/Function_Reference/get_the_ID)
214,700
<p>I just imported a Blogger site to Wordpress, and it put the category "Uncategorized" on all posts. I ended up converting all of the tags (which did come over from Blogger) to categories, but now I still have "Uncategorized" also set for all of my posts.</p> <p>I'm trying to find out how to remove the "Uncategorized" category from all of my posts.</p>
[ { "answer_id": 214711, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>You can make use of <a href=\"https://codex.wordpress.org/Function_Reference/wp_remove_object_terms\" rel=\"noreferrer\"><code>wp_remove_object_terms()</code></a> to remove the desired category from a post. </p>\n\n<p>What we will do is, run a custom query to get all the post with the associated category, and then loop through the posts and use <code>wp_remove_object_terms()</code> to remove the category</p>\n\n<h2>FEW NOTES:</h2>\n\n<ul>\n<li><p>The code is untested and might be buggy. Be sure to test this locally first</p></li>\n<li><p>If you have a huge amount of posts, this might lead to a fatal error due to timing out. To avoid this, run the function a couple of times with a smaller amount of posts till the whole operation is complete</p></li>\n</ul>\n\n<h2>THE CODE:</h2>\n\n<pre><code>add_action( 'init', function()\n{\n // Get all the posts which is assigned to the uncategorized category\n $args = [\n 'posts_per_page' =&gt; -1, // Adjust as needed\n 'cat' =&gt; 1, // Category ID for uncategorized category\n 'fields' =&gt; 'ids', // Only get post ID's for performance\n // Add any additional args here, see WP_Query\n ];\n $q = get_posts( $args );\n\n // Make sure we have posts\n if ( !$q )\n return;\n\n // We have posts, lets loop through them and remove the category\n foreach ( $q as $id )\n wp_remove_object_terms(\n $id, // Post ID\n 1, // Term ID to remove\n 'category' // The taxonomy the term belongs to\n );\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>You can just simply drop this into your functions file and then load any page back end or front end. You can then remove the code from your functions file</p>\n" }, { "answer_id": 214715, "author": "Huy Nguyen", "author_id": 86851, "author_profile": "https://wordpress.stackexchange.com/users/86851", "pm_score": 2, "selected": false, "text": "<p>I already have the same problem.\nSo i write the function to remove <code>uncategorized</code> for all post.</p>\n\n<p>You can embed this function to plugins or themes and call it.</p>\n\n<pre>\n<code>\nfunction deleteUnCategoryForAllPost(){ \n global $wpdb;\n $result = $wpdb->query( $wpdb->prepare(\"delete FROM $wpdb->term_relationships where term_taxonomy_id =1 \") );\n return $result;\n} \n</code></pre>\n" } ]
2016/01/16
[ "https://wordpress.stackexchange.com/questions/214700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75134/" ]
I just imported a Blogger site to Wordpress, and it put the category "Uncategorized" on all posts. I ended up converting all of the tags (which did come over from Blogger) to categories, but now I still have "Uncategorized" also set for all of my posts. I'm trying to find out how to remove the "Uncategorized" category from all of my posts.
You can make use of [`wp_remove_object_terms()`](https://codex.wordpress.org/Function_Reference/wp_remove_object_terms) to remove the desired category from a post. What we will do is, run a custom query to get all the post with the associated category, and then loop through the posts and use `wp_remove_object_terms()` to remove the category FEW NOTES: ---------- * The code is untested and might be buggy. Be sure to test this locally first * If you have a huge amount of posts, this might lead to a fatal error due to timing out. To avoid this, run the function a couple of times with a smaller amount of posts till the whole operation is complete THE CODE: --------- ``` add_action( 'init', function() { // Get all the posts which is assigned to the uncategorized category $args = [ 'posts_per_page' => -1, // Adjust as needed 'cat' => 1, // Category ID for uncategorized category 'fields' => 'ids', // Only get post ID's for performance // Add any additional args here, see WP_Query ]; $q = get_posts( $args ); // Make sure we have posts if ( !$q ) return; // We have posts, lets loop through them and remove the category foreach ( $q as $id ) wp_remove_object_terms( $id, // Post ID 1, // Term ID to remove 'category' // The taxonomy the term belongs to ); }, PHP_INT_MAX ); ``` You can just simply drop this into your functions file and then load any page back end or front end. You can then remove the code from your functions file
214,719
<p>I'm not very good with computers/codes etc. I use a plugin that makes a registration form thingy and in that form I added country, age group, gender and so on. I click the option that will add the registerer into the wordpress user thingy. But when I try it, only the username and email show on the Users section on the backend.. Is there a way for the other fields to show on the users section?</p> <p>I need them to show for statistical uses.</p>
[ { "answer_id": 214723, "author": "Arpita Hunka", "author_id": 86864, "author_profile": "https://wordpress.stackexchange.com/users/86864", "pm_score": 7, "selected": false, "text": "<p>You need to use the <code>show_user_profile</code>, <code>edit_user_profile</code>, <code>personal_options_update</code>, and <code>edit_user_profile_update</code> hooks.</p>\n<p>You can use the following code for adding additional fields in User section</p>\n<p><strong>Code for adding extra fields in Edit User Section:</strong></p>\n<pre><code>add_action( 'show_user_profile', 'extra_user_profile_fields' );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields' );\n\nfunction extra_user_profile_fields( $user ) { ?&gt;\n &lt;h3&gt;&lt;?php _e(&quot;Extra profile information&quot;, &quot;blank&quot;); ?&gt;&lt;/h3&gt;\n\n &lt;table class=&quot;form-table&quot;&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=&quot;address&quot;&gt;&lt;?php _e(&quot;Address&quot;); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;text&quot; name=&quot;address&quot; id=&quot;address&quot; value=&quot;&lt;?php echo esc_attr( get_the_author_meta( 'address', $user-&gt;ID ) ); ?&gt;&quot; class=&quot;regular-text&quot; /&gt;&lt;br /&gt;\n &lt;span class=&quot;description&quot;&gt;&lt;?php _e(&quot;Please enter your address.&quot;); ?&gt;&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=&quot;city&quot;&gt;&lt;?php _e(&quot;City&quot;); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;text&quot; name=&quot;city&quot; id=&quot;city&quot; value=&quot;&lt;?php echo esc_attr( get_the_author_meta( 'city', $user-&gt;ID ) ); ?&gt;&quot; class=&quot;regular-text&quot; /&gt;&lt;br /&gt;\n &lt;span class=&quot;description&quot;&gt;&lt;?php _e(&quot;Please enter your city.&quot;); ?&gt;&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=&quot;postalcode&quot;&gt;&lt;?php _e(&quot;Postal Code&quot;); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;text&quot; name=&quot;postalcode&quot; id=&quot;postalcode&quot; value=&quot;&lt;?php echo esc_attr( get_the_author_meta( 'postalcode', $user-&gt;ID ) ); ?&gt;&quot; class=&quot;regular-text&quot; /&gt;&lt;br /&gt;\n &lt;span class=&quot;description&quot;&gt;&lt;?php _e(&quot;Please enter your postal code.&quot;); ?&gt;&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;?php }\n</code></pre>\n<p><strong>Code for saving extra fields details in database</strong>:</p>\n<pre><code>add_action( 'personal_options_update', 'save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );\n\nfunction save_extra_user_profile_fields( $user_id ) {\n if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) {\n return;\n }\n \n if ( !current_user_can( 'edit_user', $user_id ) ) { \n return false; \n }\n update_user_meta( $user_id, 'address', $_POST['address'] );\n update_user_meta( $user_id, 'city', $_POST['city'] );\n update_user_meta( $user_id, 'postalcode', $_POST['postalcode'] );\n}\n</code></pre>\n<p>There are also several blog posts available on the subject that might be helpful:</p>\n<ul>\n<li><a href=\"http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields\" rel=\"noreferrer\">Adding and using custom user profile fields</a></li>\n<li><a href=\"http://bavotasan.com/2009/adding-extra-fields-to-the-wordpress-user-profile/\" rel=\"noreferrer\">Adding Extra Fields to the WordPress User Profile</a></li>\n</ul>\n" }, { "answer_id": 280512, "author": "squarecandy", "author_id": 41488, "author_profile": "https://wordpress.stackexchange.com/users/41488", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://www.advancedcustomfields.com/pro/\" rel=\"noreferrer\">Advanced Custom Fields Pro</a> plugin will allow you to add fields to user profiles without any coding.</p>\n" }, { "answer_id": 320960, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 3, "selected": false, "text": "<p>You'd better use <strong><code>get_user_meta</code></strong> (instead of <strong><code>get_the_author_meta</code></strong>):</p>\n\n<pre><code>function extra_user_profile_fields( $user ) {\n $meta = get_user_meta($user-&gt;ID, 'meta_key_name', false);\n}\n</code></pre>\n" }, { "answer_id": 413588, "author": "Talk Nerdy To Me", "author_id": 122776, "author_profile": "https://wordpress.stackexchange.com/users/122776", "pm_score": 0, "selected": false, "text": "<p>You can also easily add additional fields to the existing &quot;Contact Info&quot; section of the user profile edit screen, and it doesn't require set up of other hooks to update the meta fields.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_user_profile_contact_fields( $methods ) {\n $methods['phone'] = 'Phone number';\n $methods['location'] = 'Location';\n return $methods;\n}\nadd_action( 'user_contactmethods', 'custom_user_profile_contact_fields' );\n</code></pre>\n" } ]
2016/01/16
[ "https://wordpress.stackexchange.com/questions/214719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86910/" ]
I'm not very good with computers/codes etc. I use a plugin that makes a registration form thingy and in that form I added country, age group, gender and so on. I click the option that will add the registerer into the wordpress user thingy. But when I try it, only the username and email show on the Users section on the backend.. Is there a way for the other fields to show on the users section? I need them to show for statistical uses.
You need to use the `show_user_profile`, `edit_user_profile`, `personal_options_update`, and `edit_user_profile_update` hooks. You can use the following code for adding additional fields in User section **Code for adding extra fields in Edit User Section:** ``` add_action( 'show_user_profile', 'extra_user_profile_fields' ); add_action( 'edit_user_profile', 'extra_user_profile_fields' ); function extra_user_profile_fields( $user ) { ?> <h3><?php _e("Extra profile information", "blank"); ?></h3> <table class="form-table"> <tr> <th><label for="address"><?php _e("Address"); ?></label></th> <td> <input type="text" name="address" id="address" value="<?php echo esc_attr( get_the_author_meta( 'address', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description"><?php _e("Please enter your address."); ?></span> </td> </tr> <tr> <th><label for="city"><?php _e("City"); ?></label></th> <td> <input type="text" name="city" id="city" value="<?php echo esc_attr( get_the_author_meta( 'city', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description"><?php _e("Please enter your city."); ?></span> </td> </tr> <tr> <th><label for="postalcode"><?php _e("Postal Code"); ?></label></th> <td> <input type="text" name="postalcode" id="postalcode" value="<?php echo esc_attr( get_the_author_meta( 'postalcode', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description"><?php _e("Please enter your postal code."); ?></span> </td> </tr> </table> <?php } ``` **Code for saving extra fields details in database**: ``` add_action( 'personal_options_update', 'save_extra_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' ); function save_extra_user_profile_fields( $user_id ) { if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) { return; } if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } update_user_meta( $user_id, 'address', $_POST['address'] ); update_user_meta( $user_id, 'city', $_POST['city'] ); update_user_meta( $user_id, 'postalcode', $_POST['postalcode'] ); } ``` There are also several blog posts available on the subject that might be helpful: * [Adding and using custom user profile fields](http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields) * [Adding Extra Fields to the WordPress User Profile](http://bavotasan.com/2009/adding-extra-fields-to-the-wordpress-user-profile/)
214,727
<p>I have a wordpress website that i have added custom meta boxes to the post.</p> <p>Custom meta boxes have an editor using wp_editor(), but the editor is refusing to show the visual/text tabs on the editor panel. </p> <p>I have deactivating all plugins on my development, and the issue persisted.</p> <p>Anyone can help me ?</p>
[ { "answer_id": 236180, "author": "Peter Jan Michael Porras", "author_id": 101149, "author_profile": "https://wordpress.stackexchange.com/users/101149", "pm_score": 0, "selected": false, "text": "<p>You should assign a <strong>textarea_name</strong> and your editor ID should not contain other symbols other than dash ( - ) and underscores ( _ ).</p>\n\n<pre><code>wp_editor( 'Lorem Ipsum', 'editor-id', array('textarea_name'=&gt;'message') );\n</code></pre>\n" }, { "answer_id": 323201, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>Without seeing your code I can't say whats wrong but here is a working (tested) example of a metabox with an editor inside that has the visual/text tabs.</p>\n\n<pre><code>add_action( 'add_meta_boxes', function() { \n add_meta_box('html_myid_61_section', 'Meta Box Title', 'my_custom_meta_function');\n});\n\nfunction my_custom_meta_function( $post ) {\n $text= get_post_meta($post, 'my_custom_meta' , true );\n wp_editor( htmlspecialchars_decode($text), 'mettaabox_ID', $settings = array('textarea_name'=&gt;'inputName') );\n}\n\nadd_action( 'save_post', function($post_id) {\n if (!empty($_POST['inputName'])) {\n $data=htmlspecialchars($_POST['inputName']); \n update_post_meta($post_id, 'my_custom_meta', $datta );\n }\n}); \n</code></pre>\n\n<hr>\n\n<p><strong>Consider This...</strong></p>\n\n<p>I don't often recommend plugins BUT I would STRONGLY suggest using <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">Advanced Custom Fields</a> for stuff like this. Its easy to learn and will save you time and frustration! You can make professional admin layouts very fast.</p>\n" } ]
2016/01/16
[ "https://wordpress.stackexchange.com/questions/214727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86918/" ]
I have a wordpress website that i have added custom meta boxes to the post. Custom meta boxes have an editor using wp\_editor(), but the editor is refusing to show the visual/text tabs on the editor panel. I have deactivating all plugins on my development, and the issue persisted. Anyone can help me ?
Without seeing your code I can't say whats wrong but here is a working (tested) example of a metabox with an editor inside that has the visual/text tabs. ``` add_action( 'add_meta_boxes', function() { add_meta_box('html_myid_61_section', 'Meta Box Title', 'my_custom_meta_function'); }); function my_custom_meta_function( $post ) { $text= get_post_meta($post, 'my_custom_meta' , true ); wp_editor( htmlspecialchars_decode($text), 'mettaabox_ID', $settings = array('textarea_name'=>'inputName') ); } add_action( 'save_post', function($post_id) { if (!empty($_POST['inputName'])) { $data=htmlspecialchars($_POST['inputName']); update_post_meta($post_id, 'my_custom_meta', $datta ); } }); ``` --- **Consider This...** I don't often recommend plugins BUT I would STRONGLY suggest using [Advanced Custom Fields](https://www.advancedcustomfields.com/) for stuff like this. Its easy to learn and will save you time and frustration! You can make professional admin layouts very fast.
214,847
<p>I have the searchform.php set up to search a custom post type and a category. So far so good. However, a savvy user could edit the URL to remove "post_type=film" and search all pages and posts.</p> <p>I don't want it to do this! I'd essentially like the search hardcoded to only search the specific CPT regardless of what is in the URL slug. Is this possible?</p> <p>search.php contains this:</p> <pre><code>&lt;h1&gt;&lt;?php echo sprintf( __( '%s Search Results for ', 'site' ), $wp_query-&gt;found_posts ); echo get_search_query(); ?&gt;&lt;/h1&gt; &lt;?php get_template_part('loop'); ?&gt; &lt;?php get_template_part('pagination'); ?&gt; </code></pre>
[ { "answer_id": 214848, "author": "Jeroen", "author_id": 83390, "author_profile": "https://wordpress.stackexchange.com/users/83390", "pm_score": 0, "selected": false, "text": "<p>You can do this by editing the <code>Search.php</code> file in your theme.</p>\n\n<p>This file will contain something along the lines of this:</p>\n\n<pre><code>&lt;?php\nglobal $query_string;\n\n$query_args = explode(\"&amp;\", $query_string);\n$search_query = array();\n\nforeach($query_args as $key =&gt; $string) {\n $query_split = explode(\"=\", $string);\n $search_query[$query_split[0]] = urldecode($query_split[1]);\n} // foreach\n\n$search = new WP_Query($search_query);\n?&gt;\n</code></pre>\n\n<p>If you add $search_query['post_type'] = 'film'; above of $search = new ... then the searchresults only contain items from the post_type \"film\".</p>\n" }, { "answer_id": 214855, "author": "yomisimie", "author_id": 66259, "author_profile": "https://wordpress.stackexchange.com/users/66259", "pm_score": 1, "selected": false, "text": "<p>You can add another <code>loop.php</code> with a different name: <code>loop-film.php</code> and edit it's query so as to retrieve only the <code>film</code> post type. Afterwards in your <code>search.php</code> call on your new loop:</p>\n\n<pre><code>&lt;h1&gt;&lt;?php echo sprintf( __( '%s Search Results for ', 'site' ), $wp_query-&gt;found_posts ); echo get_search_query(); ?&gt;&lt;/h1&gt;\n\n &lt;?php get_template_part('loop-film'); ?&gt;\n\n &lt;?php get_template_part('pagination'); ?&gt;\n</code></pre>\n\n<p>Also, I think you might need to duplicate <code>pagination.php</code> also and edit it. I don't know what files your theme has so this is only base on what you provided.</p>\n" }, { "answer_id": 214864, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I guess you mean overriding the post type of the main search query on the front-end. You could try:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( WP_Query $q )\n{\n if ( \n ! is_admin() \n &amp;&amp; $q-&gt;is_main_query() \n &amp;&amp; $q-&gt;is_search()\n )\n $q-&gt;set( 'post_type', 'film' );\n} );\n</code></pre>\n\n<p>This way you don't need a secondary search query or mess directly with the globals. </p>\n" }, { "answer_id": 214865, "author": "tim daniels", "author_id": 60291, "author_profile": "https://wordpress.stackexchange.com/users/60291", "pm_score": 0, "selected": false, "text": "<p>Found a solution that should work with all themes.</p>\n\n<pre><code>function update_my_custom_type() {\nglobal $wp_post_types;\n\nif ( post_type_exists( 'post' ) ) {\n\n // exclude from search results\n $wp_post_types['post']-&gt;exclude_from_search = true;\n}\n}\n</code></pre>\n\n<p>Found it from <a href=\"http://www.webtipblog.com/exclude-custom-post-type-search-wordpress/\" rel=\"nofollow\">http://www.webtipblog.com/exclude-custom-post-type-search-wordpress/</a></p>\n" } ]
2016/01/18
[ "https://wordpress.stackexchange.com/questions/214847", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60291/" ]
I have the searchform.php set up to search a custom post type and a category. So far so good. However, a savvy user could edit the URL to remove "post\_type=film" and search all pages and posts. I don't want it to do this! I'd essentially like the search hardcoded to only search the specific CPT regardless of what is in the URL slug. Is this possible? search.php contains this: ``` <h1><?php echo sprintf( __( '%s Search Results for ', 'site' ), $wp_query->found_posts ); echo get_search_query(); ?></h1> <?php get_template_part('loop'); ?> <?php get_template_part('pagination'); ?> ```
I guess you mean overriding the post type of the main search query on the front-end. You could try: ``` add_action( 'pre_get_posts', function ( WP_Query $q ) { if ( ! is_admin() && $q->is_main_query() && $q->is_search() ) $q->set( 'post_type', 'film' ); } ); ``` This way you don't need a secondary search query or mess directly with the globals.
214,867
<p>I've been using Bedrock (<a href="https://roots.io/bedrock/" rel="nofollow">https://roots.io/bedrock/</a>) for a while to deploy WordPress websites, but have encountered some issues when deploying to a Siteground.com shared server.</p> <p>The issue is with composer. I can run composer globaly with no problem, but when I run it using Capistrano, it executes the command, but nothing actually happens.</p> <p>If I run Capistrano on debug mode, the composer command returns a weird message. Something like this: Content Type: Text/HTML []?</p> <p>It must be really simple to fix, but I'm a bit lost. Any ideas?</p>
[ { "answer_id": 217513, "author": "solosik", "author_id": 45301, "author_profile": "https://wordpress.stackexchange.com/users/45301", "pm_score": 0, "selected": false, "text": "<p>You can try to use something like <strong>Codeship</strong> instead. </p>\n\n<p>Unfortunately I didn't try it with Bedrock, but with Sage based themes it's working pretty well. </p>\n\n<p>And the bonus here is that you can have up to 5 private projects for free, + make some automated tests.</p>\n\n<p>Please let me know what is your exact workflow for deploying with Siteground? It can be quite interesting to know, how you did this on shared hosting.</p>\n" }, { "answer_id": 224535, "author": "Felipe Rinaldi", "author_id": 82491, "author_profile": "https://wordpress.stackexchange.com/users/82491", "pm_score": 2, "selected": false, "text": "<p>The solution was pretty simple, actually. I just needed to specify the path of the php-cli that I wanted to use and where the composer.phar file was located. So I added the following to my depoly.rb script for Capistrano:</p>\n\n<pre><code>SSHKit.config.command_map[:composer] = \"/usr/local/php56/bin/php-cli ~/composer.phar\"\n</code></pre>\n" }, { "answer_id": 224546, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 0, "selected": false, "text": "<p>This is an usual part of my capistrano setups.</p>\n\n<p><code>composer.phar</code> is renamed/moved to just <code>$HOME/bin/composer</code> </p>\n\n<p>Then make sure it's executable</p>\n\n<pre><code>$ chmod +x $HOME/bin/composer\n</code></pre>\n\n<p>You can override session vars easily easily using capistrano's <code>:default_env</code> variable.</p>\n\n<pre><code>set :default_env, { path: '$HOME/bin:/usr/local/php56/bin:$PATH' }\n</code></pre>\n\n<p><code>execute :composer</code> should be using php56 and just working.</p>\n" } ]
2016/01/18
[ "https://wordpress.stackexchange.com/questions/214867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82491/" ]
I've been using Bedrock (<https://roots.io/bedrock/>) for a while to deploy WordPress websites, but have encountered some issues when deploying to a Siteground.com shared server. The issue is with composer. I can run composer globaly with no problem, but when I run it using Capistrano, it executes the command, but nothing actually happens. If I run Capistrano on debug mode, the composer command returns a weird message. Something like this: Content Type: Text/HTML []? It must be really simple to fix, but I'm a bit lost. Any ideas?
The solution was pretty simple, actually. I just needed to specify the path of the php-cli that I wanted to use and where the composer.phar file was located. So I added the following to my depoly.rb script for Capistrano: ``` SSHKit.config.command_map[:composer] = "/usr/local/php56/bin/php-cli ~/composer.phar" ```
214,868
<p>I'm developing an order management system that hooks into <a href="https://docs.woothemes.com/documentation/plugins/woocommerce/" rel="noreferrer">WooCommerce</a> but the <a href="https://docs.woothemes.com/document/webhooks/" rel="noreferrer">Webhook</a> behaves irregularly. The <a href="https://docs.woothemes.com/document/webhooks/" rel="noreferrer">Webhook</a> gets disabled on its own.</p> <p>I've investigated with the users - none of them have privileges. The administrator hasn't touched this section and hasn't updated any of the plugins.</p> <p>Are there any reasons this would happen? Maybe returning http errors from my side?</p> <pre><code>WordPress: 4.4.1 WooCommerce: 2.3.8 </code></pre>
[ { "answer_id": 215482, "author": "Alex Seif", "author_id": 62682, "author_profile": "https://wordpress.stackexchange.com/users/62682", "pm_score": 4, "selected": true, "text": "<p>Apparently a WooCommerce Webhook will automatically disable due to delivery failure. \n<a href=\"https://docs.woothemes.com/document/webhooks/#section-3\" rel=\"noreferrer\">https://docs.woothemes.com/document/webhooks/#section-3</a></p>\n\n<blockquote>\n <p>β€œDisabled” (does not deliver due delivery failures).</p>\n</blockquote>\n" }, { "answer_id": 258635, "author": "Jakub Mucha", "author_id": 114592, "author_profile": "https://wordpress.stackexchange.com/users/114592", "pm_score": 2, "selected": false, "text": "<p>Automatically disabled due to delivery failures (as mentioned above).</p>\n\n<p>Because I'm depending on them a lot and never wants them disabled (no matter what), you can change function called <code>failed_delivery()</code> in this file:\n<code>plugins/woocommerce/includes/class-wc-webhook.php</code>\nto this:</p>\n\n<pre><code>private function failed_delivery() {\n\n $failures = $this-&gt;get_failure_count();\n\n if ( $failures &gt; apply_filters( 'woocommerce_max_webhook_delivery_failures', 5 ) ) {\n\n //$this-&gt;update_status( 'disabled' );\n update_post_meta( $this-&gt;id, '_failure_count', ++$failures );\n\n } else {\n\n update_post_meta( $this-&gt;id, '_failure_count', ++$failures );\n }\n}\n</code></pre>\n\n<p>and they will never be automagically disabled again.</p>\n" }, { "answer_id": 271779, "author": "Phobos", "author_id": 122833, "author_profile": "https://wordpress.stackexchange.com/users/122833", "pm_score": 3, "selected": false, "text": "<p>If you don't want to fix this every time WooCommerce updates, just create a filter in your child-theme:</p>\n\n<pre><code>function overrule_webhook_disable_limit( $number ) {\n return 999999999999; //very high number hopefully you'll never reach.\n}\nadd_filter( 'woocommerce_max_webhook_delivery_failures', 'overrule_webhook_disable_limit' );\n</code></pre>\n" } ]
2016/01/18
[ "https://wordpress.stackexchange.com/questions/214868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62682/" ]
I'm developing an order management system that hooks into [WooCommerce](https://docs.woothemes.com/documentation/plugins/woocommerce/) but the [Webhook](https://docs.woothemes.com/document/webhooks/) behaves irregularly. The [Webhook](https://docs.woothemes.com/document/webhooks/) gets disabled on its own. I've investigated with the users - none of them have privileges. The administrator hasn't touched this section and hasn't updated any of the plugins. Are there any reasons this would happen? Maybe returning http errors from my side? ``` WordPress: 4.4.1 WooCommerce: 2.3.8 ```
Apparently a WooCommerce Webhook will automatically disable due to delivery failure. <https://docs.woothemes.com/document/webhooks/#section-3> > > β€œDisabled” (does not deliver due delivery failures). > > >
214,910
<p>In the <strong>thankyou.php</strong> template there is an action showing the section marked in red in the image. The problem is the caption/title "<strong>Our Bank Detals</strong>" should be above the description not beneath.</p> <p><img src="https://i.stack.imgur.com/Ll936.jpg" alt="screen-dump"></p> <p>The code in <strong>thankyou.php</strong> that create this section is:</p> <pre><code>&lt;?php do_action( 'woocommerce_thankyou_' . $order-&gt;payment_method, $order-&gt;id ); ?&gt; </code></pre> <p>The above action must point to some code in some other file, which I hope I can modify using a hook in my funcitons.php. I need help :-)</p> <p><strong>thankyou.php</strong> is located:</p> <blockquote> <p>..wp-content/plugins/woocommerce/templates/checkout/thankyou.php</p> </blockquote> <p>I've copied it to my child-theme folder I it is necessary to edit it directly</p>
[ { "answer_id": 214981, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Unfortunately there is no hook available to remove that \"Our Bank Details\" text. But, you can hide the default which is added and un-intended area by placing following rule in your theme's style.css file:</p>\n\n<pre><code>.woocommerce-order-received .woocommerce h2:nth-of-type(2) {\n display: none;\n}\n</code></pre>\n\n<p>Then to have \"Our Bank Details\" at intended place, simply go to <strong>WooCommerce > Settings > Checkout > BACS</strong> and in that add <code>&lt;h2&gt;Our Bank Details&lt;/h2&gt;</code> in the <strong>Instructions</strong> text area. </p>\n\n<p>Let me know how it goes :)</p>\n" }, { "answer_id": 215168, "author": "MrCalvin", "author_id": 87041, "author_profile": "https://wordpress.stackexchange.com/users/87041", "pm_score": 3, "selected": true, "text": "<p>I ended up inserting the payment description.<br>\n(the one you specify in the woocommerce settings in the Wordpress backend)</p>\n\n<p>The \"native\" build-in woocommerce payment-text is static and doesn't relates to the actual selected payment method. :-(</p>\n\n<p>I did this by modifying the woocommerce template file:</p>\n\n<p>1: Copy this template file:</p>\n\n<blockquote>\n <p>..wp-content/plugins/woocommerce/templates/checkout/thankyou.php</p>\n</blockquote>\n\n<p>to </p>\n\n<blockquote>\n <p><em>your-theme-folder</em>/woocommerce/checkout/thankyou.php</p>\n</blockquote>\n\n<p>2: Replace this line\n<img src=\"https://i.stack.imgur.com/tZ9Yg.jpg\" alt=\"removeline\"></p>\n\n<p>with this code:</p>\n\n<pre><code>&lt;?php\n if ( $available_gateways = WC()-&gt;payment_gateways-&gt;get_available_payment_gateways() ) {\n foreach ( $available_gateways as $gateway ) {\n if ( $gateway-&gt;title == $order-&gt;payment_method_title) { \n echo '&lt;div&gt; &lt;h2&gt;Payment&lt;h2/&gt; &lt;/div&gt;';\n echo $gateway-&gt;payment_fields();\n }\n }\n }\n?&gt;\n</code></pre>\n\n<p>(my first real PHP code, so I wouldn't be surprised if you could be done smarter ;-))</p>\n\n<p>Result (page in danish):\n<img src=\"https://i.stack.imgur.com/QjANv.jpg\" alt=\"screendump\"></p>\n\n<p>The downside of this approach is that if WooCommerce one day update this template you need to remember to update it yourself!</p>\n" } ]
2016/01/18
[ "https://wordpress.stackexchange.com/questions/214910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87041/" ]
In the **thankyou.php** template there is an action showing the section marked in red in the image. The problem is the caption/title "**Our Bank Detals**" should be above the description not beneath. ![screen-dump](https://i.stack.imgur.com/Ll936.jpg) The code in **thankyou.php** that create this section is: ``` <?php do_action( 'woocommerce_thankyou_' . $order->payment_method, $order->id ); ?> ``` The above action must point to some code in some other file, which I hope I can modify using a hook in my funcitons.php. I need help :-) **thankyou.php** is located: > > ..wp-content/plugins/woocommerce/templates/checkout/thankyou.php > > > I've copied it to my child-theme folder I it is necessary to edit it directly
I ended up inserting the payment description. (the one you specify in the woocommerce settings in the Wordpress backend) The "native" build-in woocommerce payment-text is static and doesn't relates to the actual selected payment method. :-( I did this by modifying the woocommerce template file: 1: Copy this template file: > > ..wp-content/plugins/woocommerce/templates/checkout/thankyou.php > > > to > > *your-theme-folder*/woocommerce/checkout/thankyou.php > > > 2: Replace this line ![removeline](https://i.stack.imgur.com/tZ9Yg.jpg) with this code: ``` <?php if ( $available_gateways = WC()->payment_gateways->get_available_payment_gateways() ) { foreach ( $available_gateways as $gateway ) { if ( $gateway->title == $order->payment_method_title) { echo '<div> <h2>Payment<h2/> </div>'; echo $gateway->payment_fields(); } } } ?> ``` (my first real PHP code, so I wouldn't be surprised if you could be done smarter ;-)) Result (page in danish): ![screendump](https://i.stack.imgur.com/QjANv.jpg) The downside of this approach is that if WooCommerce one day update this template you need to remember to update it yourself!
214,911
<p>The problem I'm having is that <code>the_excerpt()</code> isn't returning the content from the post's "Excerpt" field. Instead, it's returning the first 55 words of the post, as though the "Excerpt" field is empty.</p> <p>My code is very simple - inside the loop, I have:</p> <pre><code>if( has_excerpt() ) { the_excerpt(); } else { the_content(); } </code></pre> <p>Is there something that needs to be done to tell wordpress to use the "Excerpt" field.</p>
[ { "answer_id": 214981, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Unfortunately there is no hook available to remove that \"Our Bank Details\" text. But, you can hide the default which is added and un-intended area by placing following rule in your theme's style.css file:</p>\n\n<pre><code>.woocommerce-order-received .woocommerce h2:nth-of-type(2) {\n display: none;\n}\n</code></pre>\n\n<p>Then to have \"Our Bank Details\" at intended place, simply go to <strong>WooCommerce > Settings > Checkout > BACS</strong> and in that add <code>&lt;h2&gt;Our Bank Details&lt;/h2&gt;</code> in the <strong>Instructions</strong> text area. </p>\n\n<p>Let me know how it goes :)</p>\n" }, { "answer_id": 215168, "author": "MrCalvin", "author_id": 87041, "author_profile": "https://wordpress.stackexchange.com/users/87041", "pm_score": 3, "selected": true, "text": "<p>I ended up inserting the payment description.<br>\n(the one you specify in the woocommerce settings in the Wordpress backend)</p>\n\n<p>The \"native\" build-in woocommerce payment-text is static and doesn't relates to the actual selected payment method. :-(</p>\n\n<p>I did this by modifying the woocommerce template file:</p>\n\n<p>1: Copy this template file:</p>\n\n<blockquote>\n <p>..wp-content/plugins/woocommerce/templates/checkout/thankyou.php</p>\n</blockquote>\n\n<p>to </p>\n\n<blockquote>\n <p><em>your-theme-folder</em>/woocommerce/checkout/thankyou.php</p>\n</blockquote>\n\n<p>2: Replace this line\n<img src=\"https://i.stack.imgur.com/tZ9Yg.jpg\" alt=\"removeline\"></p>\n\n<p>with this code:</p>\n\n<pre><code>&lt;?php\n if ( $available_gateways = WC()-&gt;payment_gateways-&gt;get_available_payment_gateways() ) {\n foreach ( $available_gateways as $gateway ) {\n if ( $gateway-&gt;title == $order-&gt;payment_method_title) { \n echo '&lt;div&gt; &lt;h2&gt;Payment&lt;h2/&gt; &lt;/div&gt;';\n echo $gateway-&gt;payment_fields();\n }\n }\n }\n?&gt;\n</code></pre>\n\n<p>(my first real PHP code, so I wouldn't be surprised if you could be done smarter ;-))</p>\n\n<p>Result (page in danish):\n<img src=\"https://i.stack.imgur.com/QjANv.jpg\" alt=\"screendump\"></p>\n\n<p>The downside of this approach is that if WooCommerce one day update this template you need to remember to update it yourself!</p>\n" } ]
2016/01/18
[ "https://wordpress.stackexchange.com/questions/214911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76191/" ]
The problem I'm having is that `the_excerpt()` isn't returning the content from the post's "Excerpt" field. Instead, it's returning the first 55 words of the post, as though the "Excerpt" field is empty. My code is very simple - inside the loop, I have: ``` if( has_excerpt() ) { the_excerpt(); } else { the_content(); } ``` Is there something that needs to be done to tell wordpress to use the "Excerpt" field.
I ended up inserting the payment description. (the one you specify in the woocommerce settings in the Wordpress backend) The "native" build-in woocommerce payment-text is static and doesn't relates to the actual selected payment method. :-( I did this by modifying the woocommerce template file: 1: Copy this template file: > > ..wp-content/plugins/woocommerce/templates/checkout/thankyou.php > > > to > > *your-theme-folder*/woocommerce/checkout/thankyou.php > > > 2: Replace this line ![removeline](https://i.stack.imgur.com/tZ9Yg.jpg) with this code: ``` <?php if ( $available_gateways = WC()->payment_gateways->get_available_payment_gateways() ) { foreach ( $available_gateways as $gateway ) { if ( $gateway->title == $order->payment_method_title) { echo '<div> <h2>Payment<h2/> </div>'; echo $gateway->payment_fields(); } } } ?> ``` (my first real PHP code, so I wouldn't be surprised if you could be done smarter ;-)) Result (page in danish): ![screendump](https://i.stack.imgur.com/QjANv.jpg) The downside of this approach is that if WooCommerce one day update this template you need to remember to update it yourself!
214,927
<p>I have the following snippet that allows me to auto generate the post title. I'd like to change the <code>$post_type</code> of the <code>'post_title' =&gt; $post_type . ' Job #' . $post_id</code> line to some other post property like <code>post_date</code> and <code>post_author</code>.</p> <pre><code>function save_post_func_2134( $post_id ) { $post_type = 'post'; //Change your post_type here if ( $post_type == get_post_type ( $post_id ) ) { //Check and update for the specific $post_type $my_post = array( 'ID' =&gt; $post_id, 'post_title' =&gt; $post_type . ' Job #' . $post_id //Construct post_title ); remove_action('save_post', 'save_post_func_2134'); //Avoid the infinite loop // Update the post into the database wp_update_post( $my_post ); } } add_action( 'save_post', 'save_post_func_2134' ); </code></pre>
[ { "answer_id": 214929, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 0, "selected": false, "text": "<p>Use the function <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow\"><code>get_post_meta($post_id)</code></a> to get the post meta data.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 214935, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>The post object is passed by reference as the second parameter of the <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow\"><code>save_post</code> action (<em><code>do_action ( 'save_post', int $post_ID, WP_Post $post, bool $update )</code></a></em>. You can use this post object to get the post date and author from.</p>\n\n<p>You can try the following: (<em>NOTE: The code is untested</em>)</p>\n\n<pre><code>add_action( 'save_post', 'wpse_214927_alter_title', 10, 2 );\nfunction wpse_214927_alter_title ( $post_id, $post_object )\n{\n // Target only specific post type\n if ( 'my_specific_post_type' !== $post_object-&gt;post_type\n &amp;&amp; 'my_other_specific_post_type' !== $post_object-&gt;post_type\n )\n return;\n\n // Remove the current action\n remove_action( current_filter(), __FUNCTION__ );\n\n $post_date = $post_object-&gt;post_date;\n $format_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $post_date );\n $date_formatted = $format_date-&gt;format( 'Y-m-d' ); // Set correct to display here\n $post_author = $post_object-&gt;post_author;\n $author_name = get_the_author_meta( 'display_name', $post_author ); // Adjust as needed\n\n $my_post = [\n 'ID' =&gt; $post_id,\n 'post_title' =&gt; $author_name . ' Job ' . $date_formatted // Change as needed\n ];\n wp_update_post( $my_post );\n}\n</code></pre>\n\n<p>Just an important note, you should add validation and sanitation where needed</p>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/214927", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37346/" ]
I have the following snippet that allows me to auto generate the post title. I'd like to change the `$post_type` of the `'post_title' => $post_type . ' Job #' . $post_id` line to some other post property like `post_date` and `post_author`. ``` function save_post_func_2134( $post_id ) { $post_type = 'post'; //Change your post_type here if ( $post_type == get_post_type ( $post_id ) ) { //Check and update for the specific $post_type $my_post = array( 'ID' => $post_id, 'post_title' => $post_type . ' Job #' . $post_id //Construct post_title ); remove_action('save_post', 'save_post_func_2134'); //Avoid the infinite loop // Update the post into the database wp_update_post( $my_post ); } } add_action( 'save_post', 'save_post_func_2134' ); ```
The post object is passed by reference as the second parameter of the [`save_post` action (*`do_action ( 'save_post', int $post_ID, WP_Post $post, bool $update )`*](https://developer.wordpress.org/reference/hooks/save_post/). You can use this post object to get the post date and author from. You can try the following: (*NOTE: The code is untested*) ``` add_action( 'save_post', 'wpse_214927_alter_title', 10, 2 ); function wpse_214927_alter_title ( $post_id, $post_object ) { // Target only specific post type if ( 'my_specific_post_type' !== $post_object->post_type && 'my_other_specific_post_type' !== $post_object->post_type ) return; // Remove the current action remove_action( current_filter(), __FUNCTION__ ); $post_date = $post_object->post_date; $format_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $post_date ); $date_formatted = $format_date->format( 'Y-m-d' ); // Set correct to display here $post_author = $post_object->post_author; $author_name = get_the_author_meta( 'display_name', $post_author ); // Adjust as needed $my_post = [ 'ID' => $post_id, 'post_title' => $author_name . ' Job ' . $date_formatted // Change as needed ]; wp_update_post( $my_post ); } ``` Just an important note, you should add validation and sanitation where needed
214,977
<p>I would like to receive datas from an external client to a Wordpress website. Example: I send an email to someone and I would like to send a copy (to archive it) to the website/smtp server. </p> <p>Is there an easy solution in?</p> <p>Email send to <code>[email protected]</code> copy to <code>[email protected]</code></p>
[ { "answer_id": 214979, "author": "Jenis Patel", "author_id": 65707, "author_profile": "https://wordpress.stackexchange.com/users/65707", "pm_score": -1, "selected": false, "text": "<p>Hope the below mentioned plugin will help you : </p>\n\n<p><a href=\"https://wordpress.org/plugins/easy-wp-smtp/\" rel=\"nofollow\">WP Easy SMTP</a> </p>\n\n<p>Then you will need to configure the SMTP settings with it.</p>\n" }, { "answer_id": 214982, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>By default, WordPress is not equipped to be an email server. It can <strong><em>send</em></strong> email but does not <strong><em>receive</em></strong> email.</p>\n\n<p>If you want to <strong><em>send</em></strong> mail to multiple recipients then <a href=\"https://codex.wordpress.org/Function_Reference/wp_mail\" rel=\"nofollow\"><code>wp_mail</code></a> will allow you to specify multiple addresses.</p>\n\n<pre><code>&lt;?php\n\n$multiple_recipients = array(\n '[email protected]',\n '[email protected]'\n);\n$subj = 'The email subject';\n$body = 'This is the body of the email';\n\nwp_mail( $multiple_recipients, $subj, $body ); \n</code></pre>\n\n<p>But if you want to check your email through the admin panel then you really need a plugin to <strong><em>read</em></strong> email from an external source -- not specific to WordPress.</p>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/214977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87076/" ]
I would like to receive datas from an external client to a Wordpress website. Example: I send an email to someone and I would like to send a copy (to archive it) to the website/smtp server. Is there an easy solution in? Email send to `[email protected]` copy to `[email protected]`
By default, WordPress is not equipped to be an email server. It can ***send*** email but does not ***receive*** email. If you want to ***send*** mail to multiple recipients then [`wp_mail`](https://codex.wordpress.org/Function_Reference/wp_mail) will allow you to specify multiple addresses. ``` <?php $multiple_recipients = array( '[email protected]', '[email protected]' ); $subj = 'The email subject'; $body = 'This is the body of the email'; wp_mail( $multiple_recipients, $subj, $body ); ``` But if you want to check your email through the admin panel then you really need a plugin to ***read*** email from an external source -- not specific to WordPress.
214,986
<p>I am listing custom taxonomy names. The list is displaying and the table structure is:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Name 1&lt;/td&gt; &lt;td&gt;Name 2&lt;/td&gt; &lt;td&gt;Name 3&lt;/td&gt; &lt;td&gt;Name 4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; ..... &lt;/table&gt; </code></pre> <p>The fourth name doesn't display, skipping to to the 5th. If I don't use second loop all taxonomies listing here is the my code:</p> <pre><code>&lt;?php // no default values. using these as examples $i = 0; $taxonomies = array( 'urun-kategorileri' ); $args = array( 'orderby' =&gt; 'menu-order', 'order' =&gt; 'ASC', ); $tax_terms = get_terms( $taxonomies, $args ); echo '&lt;table class="table table-hover"&gt;&lt;tr&gt;'; foreach( $tax_terms as $tax_term ) { { $i++; if( $i &lt;= 4 ) { echo '&lt;td&gt;&lt;a href="' . esc_attr( get_term_link( $tax_term, $taxonomy ) ) . '" title="' . sprintf( __( "Profilleri GΓΆrΓΌntΓΌle %s" ), $tax_term-&gt;name ) . '" ' . '&gt;' . $tax_term-&gt;name . '&lt;/a&gt;&lt;/td&gt;'; echo ("\n"); } else { echo '&lt;/tr&gt;&lt;tr&gt;'; $i = 0; } } } ?&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 214979, "author": "Jenis Patel", "author_id": 65707, "author_profile": "https://wordpress.stackexchange.com/users/65707", "pm_score": -1, "selected": false, "text": "<p>Hope the below mentioned plugin will help you : </p>\n\n<p><a href=\"https://wordpress.org/plugins/easy-wp-smtp/\" rel=\"nofollow\">WP Easy SMTP</a> </p>\n\n<p>Then you will need to configure the SMTP settings with it.</p>\n" }, { "answer_id": 214982, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>By default, WordPress is not equipped to be an email server. It can <strong><em>send</em></strong> email but does not <strong><em>receive</em></strong> email.</p>\n\n<p>If you want to <strong><em>send</em></strong> mail to multiple recipients then <a href=\"https://codex.wordpress.org/Function_Reference/wp_mail\" rel=\"nofollow\"><code>wp_mail</code></a> will allow you to specify multiple addresses.</p>\n\n<pre><code>&lt;?php\n\n$multiple_recipients = array(\n '[email protected]',\n '[email protected]'\n);\n$subj = 'The email subject';\n$body = 'This is the body of the email';\n\nwp_mail( $multiple_recipients, $subj, $body ); \n</code></pre>\n\n<p>But if you want to check your email through the admin panel then you really need a plugin to <strong><em>read</em></strong> email from an external source -- not specific to WordPress.</p>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/214986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37320/" ]
I am listing custom taxonomy names. The list is displaying and the table structure is: ``` <table> <tr> <td>Name 1</td> <td>Name 2</td> <td>Name 3</td> <td>Name 4</td> </tr> <tr> ..... </table> ``` The fourth name doesn't display, skipping to to the 5th. If I don't use second loop all taxonomies listing here is the my code: ``` <?php // no default values. using these as examples $i = 0; $taxonomies = array( 'urun-kategorileri' ); $args = array( 'orderby' => 'menu-order', 'order' => 'ASC', ); $tax_terms = get_terms( $taxonomies, $args ); echo '<table class="table table-hover"><tr>'; foreach( $tax_terms as $tax_term ) { { $i++; if( $i <= 4 ) { echo '<td><a href="' . esc_attr( get_term_link( $tax_term, $taxonomy ) ) . '" title="' . sprintf( __( "Profilleri GΓΆrΓΌntΓΌle %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name . '</a></td>'; echo ("\n"); } else { echo '</tr><tr>'; $i = 0; } } } ?> </table> ```
By default, WordPress is not equipped to be an email server. It can ***send*** email but does not ***receive*** email. If you want to ***send*** mail to multiple recipients then [`wp_mail`](https://codex.wordpress.org/Function_Reference/wp_mail) will allow you to specify multiple addresses. ``` <?php $multiple_recipients = array( '[email protected]', '[email protected]' ); $subj = 'The email subject'; $body = 'This is the body of the email'; wp_mail( $multiple_recipients, $subj, $body ); ``` But if you want to check your email through the admin panel then you really need a plugin to ***read*** email from an external source -- not specific to WordPress.
215,032
<p>I'm upgrading my website and it's using WordPress. I'm using sub-domain <code>cdn</code> for CDN and it needs to be cookieless.</p> <p>Currently my website is a multi-network of multisites (both are subdirectory installs), with the subdomain <code>www</code> hosting my main music project, and subdomain <code>photo</code> hosting my photography project.</p> <p>The plugin I'm using for that kind of multi-network is: <a href="https://github.com/stuttter/wp-multi-network" rel="nofollow">https://github.com/stuttter/wp-multi-network</a></p> <p>I need to use Single Sign-on. And this leads me to a confusion while setting <code>COOKIE_DOMAIN</code> in <code>wp-config.php</code>. I can set like the plugin's documentation said:</p> <pre><code>define( 'COOKIE_DOMAIN', 'mydomain.com' ); </code></pre> <p>but I know this would make cookies served from <code>cdn.mydomain.com</code>.</p> <p>How can I set <code>COOKIE_DOMAIN</code> in order to serve cookies from only two subdomains <code>www</code> and <code>photo</code>?</p> <p>Or do I have to use another domain name just for CDN?</p>
[ { "answer_id": 215108, "author": "David", "author_id": 31323, "author_profile": "https://wordpress.stackexchange.com/users/31323", "pm_score": 4, "selected": true, "text": "<p>As <code>cdn.mydomain.com</code> is not part of your WordPress network, it wont be affected by your settings. </p>\n\n<p>The <code>COOKIE_DOMAIN</code> constant should only be used if you want to serve cookies from a single domain <em>for all your sites in the network</em>. If you omit the constant or set it to an empty value, cookies will belong to the domain their requested from. Thats the configuration you want to use for multisite/network environments especially when it comes to different domains.</p>\n" }, { "answer_id": 257750, "author": "Wayne Brian Pearsall", "author_id": 114081, "author_profile": "https://wordpress.stackexchange.com/users/114081", "pm_score": 3, "selected": false, "text": "<p>I have been struggling with using the multisite domains of native 4.x wordpress.</p>\n\n<p>Despite finding references, saying these lines corrected the error, neither of these setting worked:</p>\n\n<pre><code>//define('COOKIE_DOMAIN', false);\n//define( β€˜COOKIE_DOMAIN’, $_SERVER[ β€˜HTTP_HOST’ ] );\n</code></pre>\n\n<p>In the end, I added the following lines of code instead, and it worked marvellously...</p>\n\n<pre><code>define('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', '');\n</code></pre>\n\n<p>Not sure if this will be good for you? </p>\n\n<ul>\n<li>I'm posting this mainly for future searchers who are having troubles.</li>\n</ul>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/215032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67721/" ]
I'm upgrading my website and it's using WordPress. I'm using sub-domain `cdn` for CDN and it needs to be cookieless. Currently my website is a multi-network of multisites (both are subdirectory installs), with the subdomain `www` hosting my main music project, and subdomain `photo` hosting my photography project. The plugin I'm using for that kind of multi-network is: <https://github.com/stuttter/wp-multi-network> I need to use Single Sign-on. And this leads me to a confusion while setting `COOKIE_DOMAIN` in `wp-config.php`. I can set like the plugin's documentation said: ``` define( 'COOKIE_DOMAIN', 'mydomain.com' ); ``` but I know this would make cookies served from `cdn.mydomain.com`. How can I set `COOKIE_DOMAIN` in order to serve cookies from only two subdomains `www` and `photo`? Or do I have to use another domain name just for CDN?
As `cdn.mydomain.com` is not part of your WordPress network, it wont be affected by your settings. The `COOKIE_DOMAIN` constant should only be used if you want to serve cookies from a single domain *for all your sites in the network*. If you omit the constant or set it to an empty value, cookies will belong to the domain their requested from. Thats the configuration you want to use for multisite/network environments especially when it comes to different domains.
215,041
<p>I am building a single author blog that will include multiple categories. One main category is "Movie Reviews."</p> <p>The author will leave a short review every time they watch a movie - even if they've seen the movie in the past and reviewed it on their site in the past.</p> <p>For the "Movie Reviews" category (only this category), I need to setup a permalink structure such as:</p> <ul> <li>/%category%/%postname%-%day%%monthnum%%year%/</li> <li>/movie-review/the-hateful-eight-01192016/</li> </ul> <p>This will give a unique URL to each review of the same movie.</p> <p>The rest of the categories will simply use /%postname%/</p> <p>I am 99% positive that I did this exact thing a few years ago, but that site is no longer active, I don't have anything about the process in my notes, and I cannot seem to find any direction via Google search, WordPress.org forums, or WordPress Answers.</p>
[ { "answer_id": 215794, "author": "Ρ‚Π½Ρ” Sufi", "author_id": 28744, "author_profile": "https://wordpress.stackexchange.com/users/28744", "pm_score": 3, "selected": false, "text": "<p>I am not sure if this is the best solution or not, but it works:</p>\n\n<pre><code>function movie_review_permalink( $url, $post, $leavename ) {\n $category = get_the_category($post-&gt;ID); \n if ( !empty($category) &amp;&amp; $category[0]-&gt;slug == \"test\" ) { //change 'test' to your category slug\n $date=date_create($post-&gt;post_date);\n $my_date = date_format($date,\"dmY\");\n $url= trailingslashit( home_url('/'. $category[0]-&gt;slug .'/'. $post-&gt;post_name .'-'. $my_date .'/' ) );\n }\n return $url;\n}\nadd_filter( 'post_link', 'movie_review_permalink', 10, 3 );\n</code></pre>\n\n<p>Above code will make your post permalink for category <strong>test</strong> to <code><a href=\"http://wpHomeURL/test/post-name-ddmmyyyy\">http://wpHomeURL/test/post-name-ddmmyyyy</a></code> structure.</p>\n\n<p>Now you will need to add rewrite rule o make this work. </p>\n\n<pre><code>function movie_review_rewrite_rules( $wp_rewrite ) {\n $new_rules['^test/([^/]+)-([0-9]+)/?'] = 'index.php?name=$matches[1]'; //change 'test' to your category slug\n $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules;\n return $wp_rewrite;\n}\nadd_action('generate_rewrite_rules', 'movie_review_rewrite_rules');\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 216125, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>I want ot give you an \"alternate\" approach. I'm pretty sure you're not going to follow this, but I thinks is interesting to read.</p>\n\n<h1>OOP \"routing\" approach</h1>\n\n<p>In WordPress, \"pretty\" urls are mathed to \"ugly\" urls.</p>\n\n<p>But most web frameworks (not only PHP) uses the concept of \"routing\": to match an url to an \"action\" (or a controller).</p>\n\n<p>I want to give you an idea how to apply this rotuing technique to WordPress, using an OOP approach.</p>\n\n<h1>The interface</h1>\n\n<p>First of all, we will write an interface to make clear what a route object should do:</p>\n\n<pre><code>namespace MySite;\n\ninterface RouteInterface\n{\n /**\n * Returns true when the route matches for the given url\n *\n * @return bool\n */\n public function matched();\n\n /**\n * Returns the WP_Query variables connected to the route for current url.\n * Should be empty if route not matched\n *\n * @return array\n */\n public function getQueryArgs();\n\n /**\n * Return the url for the route.\n * Variable parts of the url should be provided via $args param.\n *\n * @param array $args\n * @return string\n */\n public function getUrl(array $args = []);\n}\n</code></pre>\n\n<p>Very simple.</p>\n\n<p>Pleasee read the documentation blocks for details.</p>\n\n<h1>The url object</h1>\n\n<p>To \"match\" an url, we need first to know it. WordPress does not provida a function or am methods for that.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\"><code>add_query_arg()</code></a>, when used passing an empty array, is close enough.</p>\n\n<p>However, when WordPress is installed in a sub folder the subfolder path is also returned.., we should remove it, because it is not part of the url we want to match.</p>\n\n<p>Let's write an object for the scope.</p>\n\n<pre><code>namespace MySite;\n\nclass WordPressUri\n{\n\n public function getUrl()\n {\n $url = trim(esc_url_raw(add_query_arg([])), '/');\n // check if wp is in a sub folder\n $homePath = trim(parse_url(home_url(), PHP_URL_PATH), '/');\n // remove WordPress subfolder if any\n if ($homePath) {\n $url = preg_replace('~^('.preg_quote($homePath, '~').'){1}~', '', $url);\n }\n\n return trim($url, '/');\n }\n}\n</code></pre>\n\n<p>Quite simple again, I think.</p>\n\n<h1>The concrete route object</h1>\n\n<p>Now, we have everything to start writing the concrete route object that implements the route interface.</p>\n\n<pre><code>namespace MySite;\n\nfinal class MovieReviewRoute implements RouteInterface {\n\n const REGEX = '^movie-review/([\\w]+)-([0-9]{2})([0-9]{2})([0-9]{4})$';\n\n private $uri;\n private $postname = '';\n\n public function __construct(WordPressUri $uri = null) {\n $this-&gt;uri = $uri ? : new WordPressUri();\n }\n\n public function matched() {\n $matches = [];\n if (preg_match(self::REGEX, $this-&gt;uri-&gt;getUrl(), $matches) !== 1) {\n return false;\n }\n list(, , $day, $month, $year) = array_map('intval', $matches);\n if (checkdate($month, $day, $year)) {\n $this-&gt;postname = $matches[1];\n return true;\n }\n return false;\n }\n\n public function getQueryArgs() {\n return $this-&gt;postname ? ['name' =&gt; $this-&gt;postname] : [];\n }\n\n public function getUrl(array $args = []) {\n // check if postname was given, or as alternative a post object / post id\n $post = empty($args['post']) ? '' : get_post($args['post']);\n $postname = empty($args['postname']) ? '' : $args['postname'];\n if ( ! $postname &amp;&amp; $post instanceof \\WP_Post) {\n $postname = $post-&gt;post_name;\n }\n // if no date given, use post date if post was given, or just today\n if (empty($args['date'])) {\n $timestamp = $post instanceof \\WP_Post\n ? strtotime($post-&gt;post_date)\n : current_time('timestamp');\n $args['date'] = date('dmY', $timestamp);\n }\n return home_url(\"movie-review/{$postname}-{$args['date']}\");\n }\n}\n</code></pre>\n\n<p>Sorry if is a lot of code in one place, but it doesn't do nothing \"special\".</p>\n\n<p>It just do what the interfaces dictates, for the specific case.</p>\n\n<h3>Some details on the methods:</h3>\n\n<ul>\n<li><p><code>matched()</code> uses a regex to match the url against the wanted format. It also check that the matched date is a valid date. In the process, it saves the <code>postname</code> object variable, so it can be used to know which is the post that matched.</p></li>\n<li><p><code>getQueryArgs()</code> just returns the query var \"name\", that is enough to find a post</p></li>\n<li><p><code>getUrl()</code> combines the array of arguments given, to create an url that would match the route. Just what interface wants.</p></li>\n</ul>\n\n<h1>The right hook</h1>\n\n<p>We are almost done. We have all the objects, now we need to use them. The first thing we need is an hook, to intercept the request.</p>\n\n<p>The right place is <a href=\"https://developer.wordpress.org/reference/hooks/do_parse_request/\">'do_parse_request'</a>. </p>\n\n<p>Returning false on that hook, we can prevent WordPress to parse the url using rewrite rules. Moreover, the hook passes as second argument an instance of <code>WP</code> class: we can use it to set the query variables we need, and that our route can provide when matched.</p>\n\n<h1>In action</h1>\n\n<p>The code we need to match the route:</p>\n\n<pre><code>namespace MySite;\n\nadd_filter('do_parse_request', function ($bool, \\WP $wp) {\n\n $movieRoute = new MovieReviewRoute();\n // if route matched, let's set query vars and stop WP to parse rules\n if ($movieRoute-&gt;matched()) {\n $wp-&gt;query_vars = $movieRoute-&gt;getQueryArgs();\n $wp-&gt;matched_rule = MovieReviewRoute::REGEX;\n\n // avoid WordPress to apply canonical redirect\n remove_action('template_redirect', 'redirect_canonical');\n\n // returning false WP will not parse the url\n return false;\n }\n\n return $bool;\n}, 10, 2);\n</code></pre>\n\n<p>I think that it should be pretty easy to understand.</p>\n\n<p>Two things to note:</p>\n\n<ul>\n<li><p>I removed \"redirect_canonical\" function from <code>'template_redirect'</code> otherwise WordPress (that knows nothing about our routes) can redirect the post to its \"canonical\" url, that is the one that is set in standard permalink structure.</p></li>\n<li><p>I set <code>$wp-&gt;matched_rule</code> to something predictable: this allows us to know when the we set query arguments via our route object.</p></li>\n</ul>\n\n<h1>Generating urls</h1>\n\n<p>We have the route working, but we need to send users to our route. So we need to filter permalinks. The rote object has a method that generates the url, that we can leverage for the scope.</p>\n\n<pre><code>namespace MySite;\n\nadd_filter('post_link', function ($permalink, \\WP_Post $post) {\n\n if (has_category('movie-review', $post)) {\n $movieRoute = new MovieReviewRoute();\n $permalink = $movieRoute-&gt;getUrl(['post' =&gt; $post]);\n }\n\n return $permalink;\n\n}, 10, 2);\n</code></pre>\n\n<p>With this code, any post that has the \"movie-review\" category will get the url that matches our route.</p>\n\n<h1>Final touches</h1>\n\n<p>At the moment, the post in \"movie-review\" category can be viewed with 2 different urls, the standard one, and the one the matches our route.</p>\n\n<p>We should prevent that, it is very bad for SEO, among other things.</p>\n\n<pre><code>namespace MySite;\n\nadd_action('template_redirect', function() {\n if (\n is_single()\n &amp;&amp; has_category('movie-review', get_queried_object())\n &amp;&amp; $GLOBALS['wp']-&gt;matched_rule !== MovieReviewRoute::REGEX\n ) {\n $movieRoute = new MovieReviewRoute();\n wp_redirect($movieRoute-&gt;getUrl(['post' =&gt; get_queried_object()]), 301);\n exit();\n }\n});\n</code></pre>\n\n<p>Thanks to the variable we set on <code>WP</code> class when our route matches, we are able to recognize when a movie review post is viewed with standard url.</p>\n\n<p>If that happen, we just redirect to the route url.</p>\n\n<h1>Notes</h1>\n\n<p>The main question is: \"Does it worth the <em>trouble</em>\"? I can say that this approach does not suffer of any problems you have with the rewrite rule approach.</p>\n\n<p>For example, you can freely change the post slug in admin interface, and still have 2 different url structure for post in that specific category.</p>\n\n<p>Of course is more code than just 2 functions hooked into 2 hooks. And more code, is never a good thing.</p>\n\n<p>However, you should note that after you put this method in place, adding more and more routes is much easier, you just need to write a class, because the interface and the matching \"mechanism\" are already there.</p>\n\n<p>So, to answer the question: probably <strong>no</strong>: for just one route it probably doesn't worth the trouble, but if you have a few, maybe it does.</p>\n\n<p>Consider that out there exist <a href=\"https://github.com/nikic/FastRoute\">cool libraries</a> you can integrate in this approach to make the matching mechanism much easier and more powerful.</p>\n\n<h1>Gotcha</h1>\n\n<p>The code is <strong>completely untested</strong>. And it requires PHP 5.4+ because of short array syntax.</p>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/215041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14558/" ]
I am building a single author blog that will include multiple categories. One main category is "Movie Reviews." The author will leave a short review every time they watch a movie - even if they've seen the movie in the past and reviewed it on their site in the past. For the "Movie Reviews" category (only this category), I need to setup a permalink structure such as: * /%category%/%postname%-%day%%monthnum%%year%/ * /movie-review/the-hateful-eight-01192016/ This will give a unique URL to each review of the same movie. The rest of the categories will simply use /%postname%/ I am 99% positive that I did this exact thing a few years ago, but that site is no longer active, I don't have anything about the process in my notes, and I cannot seem to find any direction via Google search, WordPress.org forums, or WordPress Answers.
I am not sure if this is the best solution or not, but it works: ``` function movie_review_permalink( $url, $post, $leavename ) { $category = get_the_category($post->ID); if ( !empty($category) && $category[0]->slug == "test" ) { //change 'test' to your category slug $date=date_create($post->post_date); $my_date = date_format($date,"dmY"); $url= trailingslashit( home_url('/'. $category[0]->slug .'/'. $post->post_name .'-'. $my_date .'/' ) ); } return $url; } add_filter( 'post_link', 'movie_review_permalink', 10, 3 ); ``` Above code will make your post permalink for category **test** to `<http://wpHomeURL/test/post-name-ddmmyyyy>` structure. Now you will need to add rewrite rule o make this work. ``` function movie_review_rewrite_rules( $wp_rewrite ) { $new_rules['^test/([^/]+)-([0-9]+)/?'] = 'index.php?name=$matches[1]'; //change 'test' to your category slug $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; return $wp_rewrite; } add_action('generate_rewrite_rules', 'movie_review_rewrite_rules'); ``` Hope this helps!
215,053
<p>I cannot load <code>admin-ajax.php</code> and I keep getting this error message:</p> <blockquote> <p>XMLHttpRequest cannot load ..../wp-admin/admin-ajax.php.,. No 'Access-Control-Allow-Origin' header is present on...</p> </blockquote> <p>On local WAMP it worked just to add this:</p> <pre><code>header("Access-Control-Allow-Origin: *"); </code></pre> <p>(Even if this seems very stupid because next time WordPress updates I guess this would disappear.)</p> <p>When I upload this to my production server it's still the same message:</p> <blockquote> <p>XMLHttpRequest cannot load ..../wp-admin/admin-ajax.php.,. No 'Access-Control-Allow-Origin' header is present on...</p> </blockquote> <p>I've tried to modify the <code>.htaccess</code> file and that seemed to activate CORS, but that won't affect <code>admin-ajax.php</code>:</p> <pre><code>&lt;IfModule mod_headers.c&gt; Header add Access-Control-Allow-Origin: * &lt;/IfModule&gt; </code></pre> <p>I've also tried to install <a href="https://wordpress.org/plugins/wp-cors/" rel="nofollow noreferrer">WP-CORS</a> plugin without success.</p>
[ { "answer_id": 248729, "author": "ben", "author_id": 108609, "author_profile": "https://wordpress.stackexchange.com/users/108609", "pm_score": 4, "selected": true, "text": "<p>There are filters for <code>allowed_http_origins</code> and <code>add_allowed_origins</code>.\nYou can use them to set the proper Access-Control-Allow-Origin header in the response to your AJAX call.</p>\n\n<p>Add this to your theme's <code>functions.php</code> file:</p>\n\n<pre><code>add_filter('allowed_http_origins', 'add_allowed_origins');\n\nfunction add_allowed_origins($origins) {\n $origins[] = 'https://www.yourdomain.com';\n return $origins;\n}\n</code></pre>\n" }, { "answer_id": 268434, "author": "bnassim", "author_id": 120669, "author_profile": "https://wordpress.stackexchange.com/users/120669", "pm_score": -1, "selected": false, "text": "<p>Add this to your <code>.htaccess</code> file:</p>\n\n<pre><code>&lt;IfModule mod_headers.c&gt;\n Header set Access-Control-Allow-Origin \"*\"\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2016/01/19
[ "https://wordpress.stackexchange.com/questions/215053", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38848/" ]
I cannot load `admin-ajax.php` and I keep getting this error message: > > XMLHttpRequest cannot load ..../wp-admin/admin-ajax.php.,. No > 'Access-Control-Allow-Origin' header is present on... > > > On local WAMP it worked just to add this: ``` header("Access-Control-Allow-Origin: *"); ``` (Even if this seems very stupid because next time WordPress updates I guess this would disappear.) When I upload this to my production server it's still the same message: > > XMLHttpRequest cannot load ..../wp-admin/admin-ajax.php.,. No > 'Access-Control-Allow-Origin' header is present on... > > > I've tried to modify the `.htaccess` file and that seemed to activate CORS, but that won't affect `admin-ajax.php`: ``` <IfModule mod_headers.c> Header add Access-Control-Allow-Origin: * </IfModule> ``` I've also tried to install [WP-CORS](https://wordpress.org/plugins/wp-cors/) plugin without success.
There are filters for `allowed_http_origins` and `add_allowed_origins`. You can use them to set the proper Access-Control-Allow-Origin header in the response to your AJAX call. Add this to your theme's `functions.php` file: ``` add_filter('allowed_http_origins', 'add_allowed_origins'); function add_allowed_origins($origins) { $origins[] = 'https://www.yourdomain.com'; return $origins; } ```
215,063
<p>I am using the following filter to run a function that generates a CSS file after a plugin gets updated. Currently the CSS gets generated when any plugin gets updated. Is there a simple way to limit this running to a particular plugin?</p> <pre><code>add_filter('upgrader_post_install', 'generate_my_css', 100, 0); function generate_my_css() { $ss_dir = get_stylesheet_directory(); $pi_dir = plugin_dir_path( __FILE__ ); ob_start(); require($pi_dir . 'includes/css/mycss.php'); $css = ob_get_clean(); file_put_contents($ss_dir . '/css/mycss.css', $css, LOCK_EX); } </code></pre> <p>Ideally the above code would live in the plugin that was being updated but could just as easily live in the functions.php</p>
[ { "answer_id": 215097, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/hooks/upgrader_post_install/\" rel=\"nofollow\"><code>upgrader_post_install</code></a> has three parameters <code>$response</code>, <code>$hook_extra</code> and <code>$result</code> which give you extra information. At the moment I can't take a look myself, but I'm assuming that especially the <code>$result</code> variable should give you additional information to differentiate. </p>\n" }, { "answer_id": 400527, "author": "Humberto Herrador", "author_id": 217141, "author_profile": "https://wordpress.stackexchange.com/users/217141", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter('upgrader_post_install','upgrader_post_install_func',10,3);\n\nfunction upgrader_post_install_func($response,$hook_extra,$result){\n /*\n visualizar $result y $hook_extra, se guarda en carpeta wp-content.\n */\n \n #file_put_contents(WP_CONTENT_DIR . '/test.txt', serialize($result).&quot;\\r\\n&quot;, FILE_APPEND);\n\n /* renombrar complemento actualizado desde github zipball, para mantener \n actualizaciones dado que github al descargar zip y descomprimirlo lo pone en \n este formato: &lt;usuario github&gt;-&lt;nombre repo&gt;-&lt;codigo version&gt;\n y se necesita &lt;nombre repo&gt;-&lt;main | master&gt;\n */\n $plugin = explode('/', $hook_extra['plugin']); \n rename(WP_PLUGIN_DIR .'/'. $result['destination_name'],WP_PLUGIN_DIR .'/'.$plugin[0]);\n return $result;\n}\n</code></pre>\n<p>Espero ser de ayuda.</p>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81133/" ]
I am using the following filter to run a function that generates a CSS file after a plugin gets updated. Currently the CSS gets generated when any plugin gets updated. Is there a simple way to limit this running to a particular plugin? ``` add_filter('upgrader_post_install', 'generate_my_css', 100, 0); function generate_my_css() { $ss_dir = get_stylesheet_directory(); $pi_dir = plugin_dir_path( __FILE__ ); ob_start(); require($pi_dir . 'includes/css/mycss.php'); $css = ob_get_clean(); file_put_contents($ss_dir . '/css/mycss.css', $css, LOCK_EX); } ``` Ideally the above code would live in the plugin that was being updated but could just as easily live in the functions.php
[`upgrader_post_install`](https://developer.wordpress.org/reference/hooks/upgrader_post_install/) has three parameters `$response`, `$hook_extra` and `$result` which give you extra information. At the moment I can't take a look myself, but I'm assuming that especially the `$result` variable should give you additional information to differentiate.
215,119
<p>The <code>is_page()</code> with post id, post slug isn't working. Below is the code i have been using in divi child theme at the end of the <code>functions.php</code> file.</p> <pre><code>function addingcattocatlist($cat_list){ if ( is_page('blog') ) { $cat_list = 'blog: '. '' .$cat_list; } return $cat_list; } add_filter('the_category' , 'addingcattocatlist', 10); </code></pre>
[ { "answer_id": 215122, "author": "Lorraine", "author_id": 87158, "author_profile": "https://wordpress.stackexchange.com/users/87158", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>if ( is_front_page() &amp;&amp; is_home() ) {\n // Default homepage\n} elseif ( is_front_page() ) {\n // static homepage\n} elseif ( is_home() ) {\n // blog page\n} else {\n //everything else\n}\n</code></pre>\n\n<p>Source: <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">http://codex.wordpress.org/Conditional_Tags</a></p>\n" }, { "answer_id": 215185, "author": "Sagive", "author_id": 7990, "author_profile": "https://wordpress.stackexchange.com/users/7990", "pm_score": 1, "selected": false, "text": "<p>OK @Muyassir S. - we are missing some information to understand the problem. </p>\n\n<p>We basicly dont know if the \"page\" you are talking about is a category page, Your home page or a custom page - meaning: which file is being used to show that blog?</p>\n\n<p>here are two possible solutions.</p>\n\n<p><strong>If we are talking about a category / page with slug:</strong></p>\n\n<pre><code>if(is_category('blog')) {\n // add whatever you want here\n}\n</code></pre>\n\n<ul>\n<li>should be placed inside category.php template</li>\n</ul>\n\n<p><strong>If you went to: Settings > Reading</strong><br>\nand set the posts page over there then its a page and can be accesses like this.</p>\n\n<pre><code>$blogPgid = get_option('page_for_posts');\n\nif(get_the_ID() == $blogPgid) {\n // add whatever you want here\n}\n</code></pre>\n\n<ul>\n<li>should be placed inside page.php template.</li>\n</ul>\n\n<p>Let me know if this helps</p>\n\n<p>EDIT 1:\nhere is what i would do. </p>\n\n<p>1st. Just copy page.php in your theme and name the new copy page-blog.php Now, add a in the top of that page these tag (above everything). </p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: Blog Page\n*/\n?&gt;\n</code></pre>\n\n<p>2nd. go back to that page in WP admin and pick that page template. Now you have a page / file that you can control and add whichever specific stuff you'd like.</p>\n" }, { "answer_id": 215328, "author": "Muyassir S.", "author_id": 87172, "author_profile": "https://wordpress.stackexchange.com/users/87172", "pm_score": 0, "selected": false, "text": "<p>functions.php is processed way before you can know which page is being loaded. Instead of assigning value to variable put your code into function and use that function in page.php template.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/21418/why-isnt-is-page-working-when-i-put-it-in-the-functions-php-file\">Why isn&#39;t is_page working when I put it in the functions.php file?</a></p>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215119", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87172/" ]
The `is_page()` with post id, post slug isn't working. Below is the code i have been using in divi child theme at the end of the `functions.php` file. ``` function addingcattocatlist($cat_list){ if ( is_page('blog') ) { $cat_list = 'blog: '. '' .$cat_list; } return $cat_list; } add_filter('the_category' , 'addingcattocatlist', 10); ```
Try this: ``` if ( is_front_page() && is_home() ) { // Default homepage } elseif ( is_front_page() ) { // static homepage } elseif ( is_home() ) { // blog page } else { //everything else } ``` Source: <http://codex.wordpress.org/Conditional_Tags>
215,124
<p>I'd like to remove the link from the Woocommerce product listings. I don't need the user to see the product detail pages, we are going to use Quick View instead. Anywho, I have been searching and everything I've found is outdated. This is the current <code>content-product.php</code> file: <a href="https://github.com/woothemes/woocommerce/blob/master/templates/content-product.php" rel="nofollow">https://github.com/woothemes/woocommerce/blob/master/templates/content-product.php</a> and there are no anchor tags to simply remove.</p> <p>I might need a hook but I'm not sure what to do. I tried a few but the link was still there. For example this didn't work when added to my functions.php:</p> <pre><code> add_filter('woocommerce_template_loop_product_link_open','mbc_remove_link_on_thumbnail' ); function mbc_remove_link_on_thumbnail($html){ return strip_tags($html,'&lt;img&gt;'); } </code></pre> <p>I also tried this which didn't work but I feel is close:</p> <pre><code> remove_action ('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10); remove_action ('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5); </code></pre> <p>I'm not sure if I'm even on the right track. Any help would be appreciated!</p>
[ { "answer_id": 215127, "author": "MrFox", "author_id": 69240, "author_profile": "https://wordpress.stackexchange.com/users/69240", "pm_score": 1, "selected": true, "text": "<p>The way I've done this was to take a copy of content-product.php and paste it into the root of your theme folder.</p>\n\n<p>Comment out </p>\n\n<p><code>do_action( 'woocommerce_before_shop_loop_item_title' );</code></p>\n\n<p>and</p>\n\n<p><code>do_action( 'woocommerce_after_shop_loop_item' );</code></p>\n\n<p>Quick and dirty, but it worked for me.</p>\n" }, { "answer_id": 231222, "author": "Gabriel Darezzo", "author_id": 97679, "author_profile": "https://wordpress.stackexchange.com/users/97679", "pm_score": 0, "selected": false, "text": "<p>I found this.</p>\n\n<pre><code>/**\n * @snippet Disable Link to Products @ Loop\n * @how-to Watch tutorial @ http://businessbloomer.com/?p=19055\n * @sourcecode http://businessbloomer.com/?p=19916\n * @author Rodolfo Melogli\n * @testedwith WooCommerce 2.5.2\n */\n// Close &lt;/a&gt; tag just after it opens before product item\n\nadd_action( 'woocommerce_before_shop_loop_item_title','bbloomer_close_permalink', 10 );\nfunction bbloomer_close_permalink() {\n?&gt;\n&lt;/a&gt;\n&lt;?php\n}\n\n// Open &lt;a&gt; tag just before it closes after product item\n\nadd_action( 'woocommerce_after_shop_loop_item_title','bbloomer_open_atag', 11);\nfunction bbloomer_open_atag() {\n?&gt;\n&lt;a&gt;\n&lt;?php\n}\n\n/**\n * Explanation for the hack!\n *\n * Before the loop item, a link opens...\n * After the loop item, a link closes...\n * We're basically adding a close and open so that\n * no content gets wrapped into &lt;a&gt;link&lt;/a&gt;\n * \n * Check wc-template-functions.php lines 545-556:\n *\n * function woocommerce_template_loop_product_link_open() {\n * echo '&lt;a href=\"' . get_the_permalink() . '\"&gt;';\n * }\n *\n * function woocommerce_template_loop_product_link_close() {\n * echo '&lt;/a&gt;';\n * }\n *\n */\n</code></pre>\n\n<p>Font Source:\n<a href=\"http://businessbloomer.com/woocommerce-disable-link-to-product-loop/\" rel=\"nofollow\">http://businessbloomer.com/woocommerce-disable-link-to-product-loop/</a></p>\n" }, { "answer_id": 279072, "author": "ralrom", "author_id": 127215, "author_profile": "https://wordpress.stackexchange.com/users/127215", "pm_score": 4, "selected": false, "text": "<p>A better &amp; safer way to do this is by removing the open &amp; close link actions. This will prevent side effects such as the add to cart button disappearing.</p>\n\n<pre><code>remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );\nremove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );\n</code></pre>\n\n<p>You can add this code to your functions.php</p>\n" }, { "answer_id": 352376, "author": "D. Pal", "author_id": 178202, "author_profile": "https://wordpress.stackexchange.com/users/178202", "pm_score": 0, "selected": false, "text": "<p>The best practice would be by a single line of code in your <code>functions.php</code> file.</p>\n\n<pre><code>remove_action('woocommerce_before_shop_loop_item' , \n'woocommerce_template_loop_product_link_open' , 10);\n</code></pre>\n\n<p>Put it into any function file. The link to the product will be gone.</p>\n" }, { "answer_id": 388736, "author": "Χ‘ΧŸ Χ›Χ”ΧŸ", "author_id": 206925, "author_profile": "https://wordpress.stackexchange.com/users/206925", "pm_score": 1, "selected": false, "text": "<p>I just removed it with jQuery like this:</p>\n<pre><code>&lt;script&gt;\njQuery(document).ready(function(){\n jQuery('li.product a.woocommerce-loop-product__link').removeAttr('href');\n});\n&lt;/script&gt;\n</code></pre>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73662/" ]
I'd like to remove the link from the Woocommerce product listings. I don't need the user to see the product detail pages, we are going to use Quick View instead. Anywho, I have been searching and everything I've found is outdated. This is the current `content-product.php` file: <https://github.com/woothemes/woocommerce/blob/master/templates/content-product.php> and there are no anchor tags to simply remove. I might need a hook but I'm not sure what to do. I tried a few but the link was still there. For example this didn't work when added to my functions.php: ``` add_filter('woocommerce_template_loop_product_link_open','mbc_remove_link_on_thumbnail' ); function mbc_remove_link_on_thumbnail($html){ return strip_tags($html,'<img>'); } ``` I also tried this which didn't work but I feel is close: ``` remove_action ('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10); remove_action ('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5); ``` I'm not sure if I'm even on the right track. Any help would be appreciated!
The way I've done this was to take a copy of content-product.php and paste it into the root of your theme folder. Comment out `do_action( 'woocommerce_before_shop_loop_item_title' );` and `do_action( 'woocommerce_after_shop_loop_item' );` Quick and dirty, but it worked for me.
215,128
<p>I've shut down password resets for all users.</p> <p>I now need to prevent <code>/wp-login.php?action=lostpassword</code> from doing anything should anyone manually input the URL into their browser.</p> <p>i.e. I don't want the password reset form to show.</p> <p>Can I disable the action that's being passed by the URL or can I redirect <code>/wp-login.php?action=lostpassword</code> to <code>/wp-login.php</code>?</p>
[ { "answer_id": 215136, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 4, "selected": true, "text": "<p>Hi Please try to use this in your functions.php it will redirect user to login form when user try to access lost password page:</p>\n\n<pre><code>add_action('init','possibly_redirect'); \nfunction possibly_redirect(){ \n if (isset( $_GET['action'] )){ \n if ( in_array( $_GET['action'], array('lostpassword', 'retrievepassword') ) ) {\n wp_redirect( '/wp-login.php' ); exit;\n }\n }\n}\n</code></pre>\n\n<p>Or Please follow below approach used from this answer <a href=\"https://stackoverflow.com/questions/34905812/redirecting-a-url-with-an-action-parameter/34906203#34906203\"> answered here with some details</a> based on comments of @Clarus Dignus</p>\n\n<pre><code>function disable_lost_password() {\n if (isset( $_GET['action'] )){\n if ( in_array( $_GET['action'], array('lostpassword', 'retrievepassword') ) ) {\n wp_redirect( wp_login_url(), 301 );\n exit;\n }\n }\n}\nadd_action( \"login_init\", \"disable_lost_password\" );\n</code></pre>\n" }, { "answer_id": 251931, "author": "rocknrollcanneverdie", "author_id": 22460, "author_profile": "https://wordpress.stackexchange.com/users/22460", "pm_score": 1, "selected": false, "text": "<p>You can use <em>.htaccess</em> and <em>mod_rewrite</em>.</p>\n\n<p>Forbidden response:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^action=lostpassword$ [NC]\nRewriteRule ^wp-login.php$ - [F,NC]\n</code></pre>\n\n<p>Redirect to wp-login.php:</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^action=lostpassword$ [NC]\nRewriteRule ^wp-login.php$ wp-login.php [R=301,NC,QSD,L]\n</code></pre>\n\n<p>(for QSD flag you need Apache 2.4.0+)</p>\n" }, { "answer_id": 305480, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 1, "selected": false, "text": "<p>I know this is an older thread, but I have a couple of improvements. First, since they can use GET or POST, I would be checking for $_REQUEST instead of $_GET</p>\n\n<p>Second, redirect them somewhere useless, instead of back to your site. Like '<a href=\"http://127.0.0.1\" rel=\"nofollow noreferrer\">http://127.0.0.1</a>' If they don't have a web server there, the bot will at least stall for a few seconds waiting for a reply. Anything we can do to hinder these a-holes.</p>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41545/" ]
I've shut down password resets for all users. I now need to prevent `/wp-login.php?action=lostpassword` from doing anything should anyone manually input the URL into their browser. i.e. I don't want the password reset form to show. Can I disable the action that's being passed by the URL or can I redirect `/wp-login.php?action=lostpassword` to `/wp-login.php`?
Hi Please try to use this in your functions.php it will redirect user to login form when user try to access lost password page: ``` add_action('init','possibly_redirect'); function possibly_redirect(){ if (isset( $_GET['action'] )){ if ( in_array( $_GET['action'], array('lostpassword', 'retrievepassword') ) ) { wp_redirect( '/wp-login.php' ); exit; } } } ``` Or Please follow below approach used from this answer [answered here with some details](https://stackoverflow.com/questions/34905812/redirecting-a-url-with-an-action-parameter/34906203#34906203) based on comments of @Clarus Dignus ``` function disable_lost_password() { if (isset( $_GET['action'] )){ if ( in_array( $_GET['action'], array('lostpassword', 'retrievepassword') ) ) { wp_redirect( wp_login_url(), 301 ); exit; } } } add_action( "login_init", "disable_lost_password" ); ```
215,150
<p>I'm trying to remove the Category URI from the WordPress URL and have a custom pagination rewrite. I'll explain exactly what's happening below:</p> <p>So I have a blog.</p> <p>We have two (main) categories: "bar-talk" and "tutorials". I'll use "Bar Talk" for the example.</p> <p>I've found with WordPress, I can actually visit both of these URLs without doing anything custom:</p> <pre><code>- Current: https://scotch.io/category/bar-talk - Want: https://scotch.io/bar-talk </code></pre> <p>However, the pagination that is automatically created breaks:</p> <pre><code>- Current: https://scotch.io/category/bar-talk/page/2 (works) - Want: https://scotch.io/bar-talk/page/2 (doesn't work) </code></pre> <p>This makes sense as we haven't done any custom rewrite yet. How do I get the second structure though? Then, following this, I'd like to do a rewrite on "page" so that we can do:</p> <pre><code>- Super want: https://scotch.io/bar-talk/drink-number/2 </code></pre> <p>Some additional notes:</p> <ul> <li>We've successfully previously done a rewrite to have "<a href="https://scotch.io/category/bar-talk/drink-number/2" rel="nofollow">https://scotch.io/category/bar-talk/drink-number/2</a>" work. But we really don't want that category param as part of pagination anymore</li> <li>Anything with tags works fine: "<a href="https://scotch.io/tag/javascript/drink-number/2" rel="nofollow">https://scotch.io/tag/javascript/drink-number/2</a>"</li> <li>Current permalink structure is "/%category%/%postname%"</li> </ul> <p>Thanks!</p>
[ { "answer_id": 215155, "author": "DrizzlyOwl", "author_id": 31627, "author_profile": "https://wordpress.stackexchange.com/users/31627", "pm_score": 2, "selected": false, "text": "<p>Hm. Have you thought about doing some URL rewrites in .htaccess?\n<code>\nRewriteRule ^category/bar-talk/page/([0-9]+)$ /bar-talk/drink-number/$1 [L,R=301]\nRewriteRule ^bar-talk/drink-number/([0-9]+)$ /index.php?category_name=bar-talk&amp;page=$1 [L]\n</code></p>\n\n<p>// @drizzlyowl</p>\n" }, { "answer_id": 215156, "author": "envysea", "author_id": 38881, "author_profile": "https://wordpress.stackexchange.com/users/38881", "pm_score": 0, "selected": false, "text": "<p>Okay, currently using this craziness. A combination of the \"page\" rewrite and modified <a href=\"https://wordpress.org/plugins/wp-no-category-base/\" rel=\"nofollow\">WP No Category Base</a> plugin. Seems to be working perfectly.</p>\n\n<pre><code>/*===========================================================\n= REMOVE CATEGORY / CUSTOM PAGINATION =\n===========================================================*/\nregister_activation_hook(__FILE__, 'no_category_base_refresh_rules');\nadd_action('created_category', 'no_category_base_refresh_rules');\nadd_action('edited_category', 'no_category_base_refresh_rules');\nadd_action('delete_category', 'no_category_base_refresh_rules');\nfunction no_category_base_refresh_rules() {\n global $wp_rewrite;\n $wp_rewrite -&gt; flush_rules();\n}\n\nregister_deactivation_hook(__FILE__, 'no_category_base_deactivate');\nfunction no_category_base_deactivate() {\n remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');\n // We don't want to insert our custom rules again\n no_category_base_refresh_rules();\n}\n\n// Remove category base\nadd_action('init', 'no_category_base_permastruct');\nfunction no_category_base_permastruct() {\n global $wp_rewrite, $wp_version;\n if (version_compare($wp_version, '3.4', '&lt;')) {\n // For pre-3.4 support\n $wp_rewrite -&gt; extra_permastructs['category'][0] = '%category%';\n } else {\n $wp_rewrite -&gt; extra_permastructs['category']['struct'] = '%category%';\n }\n}\n\n// Add our custom category rewrite rules\nadd_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');\nfunction no_category_base_rewrite_rules($category_rewrite) {\n //var_dump($category_rewrite); // For Debugging\n\n $category_rewrite = array();\n $categories = get_categories(array('hide_empty' =&gt; false));\n foreach ($categories as $category) {\n $category_nicename = $category -&gt; slug;\n if ($category -&gt; parent == $category -&gt; cat_ID)// recursive recursion\n $category -&gt; parent = 0;\n elseif ($category -&gt; parent != 0)\n $category_nicename = get_category_parents($category -&gt; parent, false, '/', true) . $category_nicename;\n $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]';\n $category_rewrite['(' . $category_nicename . ')/drink-number/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]';\n $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';\n }\n // Redirect support from Old Category Base\n global $wp_rewrite;\n $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';\n $old_category_base = trim($old_category_base, '/');\n $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';\n\n //var_dump($category_rewrite); // For Debugging\n return $category_rewrite;\n}\n\n// Add 'category_redirect' query variable\nadd_filter('query_vars', 'no_category_base_query_vars');\nfunction no_category_base_query_vars($public_query_vars) {\n $public_query_vars[] = 'category_redirect';\n return $public_query_vars;\n}\n\n// Redirect if 'category_redirect' is set\nadd_filter('request', 'no_category_base_request');\nfunction no_category_base_request($query_vars) {\n //print_r($query_vars); // For Debugging\n if (isset($query_vars['category_redirect'])) {\n $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');\n status_header(301);\n header(\"Location: $catlink\");\n exit();\n }\n return $query_vars;\n}\n\n\nregister_activation_hook( __FILE__ , 'pagination_flush' );\nregister_deactivation_hook( __FILE__ , 'pagination_flush' );\n\nadd_action('init', function() {\n $GLOBALS['wp_rewrite']-&gt;pagination_base = 'drink-number';\n});\n\nfunction pagination_flush() {\n add_action( 'init', 'flush_rewrite_rules', 11 );\n}\n</code></pre>\n" }, { "answer_id": 353345, "author": "chaithra", "author_id": 178927, "author_profile": "https://wordpress.stackexchange.com/users/178927", "pm_score": 0, "selected": false, "text": "<p>No need to write any code u can just install Remove CPT base plugin and do some settings in this plugin and activate.\nlink: <a href=\"https://wordpress.org/plugins/remove-cpt-base/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/remove-cpt-base/</a></p>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215150", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38881/" ]
I'm trying to remove the Category URI from the WordPress URL and have a custom pagination rewrite. I'll explain exactly what's happening below: So I have a blog. We have two (main) categories: "bar-talk" and "tutorials". I'll use "Bar Talk" for the example. I've found with WordPress, I can actually visit both of these URLs without doing anything custom: ``` - Current: https://scotch.io/category/bar-talk - Want: https://scotch.io/bar-talk ``` However, the pagination that is automatically created breaks: ``` - Current: https://scotch.io/category/bar-talk/page/2 (works) - Want: https://scotch.io/bar-talk/page/2 (doesn't work) ``` This makes sense as we haven't done any custom rewrite yet. How do I get the second structure though? Then, following this, I'd like to do a rewrite on "page" so that we can do: ``` - Super want: https://scotch.io/bar-talk/drink-number/2 ``` Some additional notes: * We've successfully previously done a rewrite to have "<https://scotch.io/category/bar-talk/drink-number/2>" work. But we really don't want that category param as part of pagination anymore * Anything with tags works fine: "<https://scotch.io/tag/javascript/drink-number/2>" * Current permalink structure is "/%category%/%postname%" Thanks!
Hm. Have you thought about doing some URL rewrites in .htaccess? `RewriteRule ^category/bar-talk/page/([0-9]+)$ /bar-talk/drink-number/$1 [L,R=301] RewriteRule ^bar-talk/drink-number/([0-9]+)$ /index.php?category_name=bar-talk&page=$1 [L]` // @drizzlyowl
215,157
<p>Here's the code we're using to set an image file as an option for the site's logo via WordPress' theme customizer:</p> <pre><code>/* Logo &gt; Image -------------------------------------------------- */ $wp_customize-&gt;add_setting( 'themeslug_logo' ); $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'themeslug_logo', array( 'label' =&gt; __( 'Logo', 'themeslug', 'themeslug' ), 'section' =&gt; 'themeslug_header', 'settings' =&gt; 'themeslug_logo', 'description' =&gt; 'Upload a logo to replace the default site name in the header.', ) ) ); </code></pre> <p>Accordingly, we're displaying the logo like this:</p> <pre><code>&lt;img src='&lt;?php echo esc_url( get_theme_mod( 'themeslug_logo' ) ); ?&gt;' alt='&lt;?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?&gt; Logo' class="img-responsive"&gt; </code></pre> <p>However, in doing so, we realized that we're not setting the image height/ width attributes.</p> <p>So, what we want to accomplish is to pull the image height/width from the uploaded media file, store them as a variable, and then execute them, like:</p> <pre><code>&lt;?php $logo = get_theme_mod( 'themeslug_logo' ); $logoatts = wp_get_attachment_metadata($logo); // obviously doesn't work $logoheight = ; // don't know how to get this $logowidth = ; // don't know how to get this ?&gt; &lt;img src='&lt;?php echo esc_url( get_theme_mod( 'themeslug_logo' ) ); ?&gt;' alt='&lt;?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?&gt; Logo' class="img-responsive" height="&lt;?php echo($logoheight);?&gt;" width="&lt;?php echo($logowidth);?&gt;" &gt; </code></pre> <p>Essentially, where we're running into issues is: we want to get the image width from the file as set per WP_Customize_Image_Control() instead of just the URL.</p> <p>Thanks in advance</p>
[ { "answer_id": 215161, "author": "Ryan Dorn", "author_id": 47880, "author_profile": "https://wordpress.stackexchange.com/users/47880", "pm_score": 1, "selected": false, "text": "<p>OK, well, we found a quick and perhaps a bit dirty solution using PHP's <a href=\"http://php.net/manual/en/function.getimagesize.php\" rel=\"nofollow\">getimagesize () function</a>.</p>\n\n<p>Specifically, this is the code:</p>\n\n<pre><code>&lt;?php if ( get_theme_mod( 'themeslug_logo' ) ) : \n $themelogo = get_theme_mod( 'themeslug_logo' );\n $themelogo_size = getimagesize($themelogo);\n $themelogo_width = $themelogo_size[0];\n $themelogo_height = $themelogo_size[1];\n?&gt;\n&lt;img src='&lt;?php echo esc_url( get_theme_mod( 'themeslug_logo' ) ); ?&gt;' alt='&lt;?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?&gt; Logo' class=\"img-responsive full\" height=\"&lt;?php echo($themelogo_height);?&gt;\" width=\"&lt;?php echo($themelogo_width);?&gt;\"&gt;\n</code></pre>\n\n<p>I'm not sure if this is the best method or not, so if anyone else has a bright idea, I'd love to hear it!</p>\n" }, { "answer_id": 364310, "author": "Vinicius Garcia", "author_id": 54025, "author_profile": "https://wordpress.stackexchange.com/users/54025", "pm_score": 2, "selected": false, "text": "<p>Modern answer to this question:</p>\n\n<p>We have <code>WP_Customize_Media_Control</code> control in WP since <strong>4.2</strong> that gives you the attachment id.</p>\n\n<p>This answer was posted on I <a href=\"https://wordpress.stackexchange.com/a/259845/54025\">similar question</a>.\nYou can see the documentation for <code>WP_Customize_Media_Control</code> <a href=\"https://developer.wordpress.org/reference/classes/wp_customize_media_control/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Exemple of use:</p>\n\n<pre><code>$wp_customize-&gt;add_setting( 'my_menu_image' );\n $wp_customize-&gt;add_control( new \\WP_Customize_Media_Control(\n $wp_customize,\n 'storms_menu_image_ctrl',\n array(\n 'priority' =&gt; 10,\n 'mime_type' =&gt; 'image',\n 'settings' =&gt; 'my_menu_image',\n 'label' =&gt; __( 'Image on menu bar', 'my' ),\n 'section' =&gt; 'title_tagline',\n )\n ) );\n</code></pre>\n\n<p>When retrieving the info, you can do this:</p>\n\n<pre><code>$image_id = get_theme_mod( \"my_menu_image\" );\nif ( ! empty( $image_id ) ) {\n $url = esc_url_raw( wp_get_attachment_url( $image_id ) );\n $image_data = wp_get_attachment_metadata( $image_id );\n $width = $image_data['width'];\n $height = $image_data['height'];\n}\n</code></pre>\n" }, { "answer_id": 369550, "author": "user1503606", "author_id": 83641, "author_profile": "https://wordpress.stackexchange.com/users/83641", "pm_score": 0, "selected": false, "text": "<p>The above answer is definitely the best to get image sizes via the customized here is a bit of extra information.</p>\n<pre><code> // Add your customizer block\n $wp_customize-&gt;add_setting(\n 'logo'\n );\n\n $wp_customize-&gt;add_control(\n new WP_Customize_Media_Control(\n $wp_customize, \n 'logo', \n array(\n 'label' =&gt; __('Logo', 'theme'),\n 'section' =&gt; 'styles',\n 'settings' =&gt; 'logo',\n )\n )\n );\n\n // Add your image size to your function.php file\n add_image_size('logo_image_size', 100, 9999, false);\n\n // Output your media anywhere in your theme\n $logo = get_theme_mod( &quot;logo&quot; );\n\n if ( !empty($logo) ) { \n\n echo wp_get_attachment_image( $logo, 'logo_image_size' ) ;\n\n } \n</code></pre>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47880/" ]
Here's the code we're using to set an image file as an option for the site's logo via WordPress' theme customizer: ``` /* Logo > Image -------------------------------------------------- */ $wp_customize->add_setting( 'themeslug_logo' ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'themeslug_logo', array( 'label' => __( 'Logo', 'themeslug', 'themeslug' ), 'section' => 'themeslug_header', 'settings' => 'themeslug_logo', 'description' => 'Upload a logo to replace the default site name in the header.', ) ) ); ``` Accordingly, we're displaying the logo like this: ``` <img src='<?php echo esc_url( get_theme_mod( 'themeslug_logo' ) ); ?>' alt='<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> Logo' class="img-responsive"> ``` However, in doing so, we realized that we're not setting the image height/ width attributes. So, what we want to accomplish is to pull the image height/width from the uploaded media file, store them as a variable, and then execute them, like: ``` <?php $logo = get_theme_mod( 'themeslug_logo' ); $logoatts = wp_get_attachment_metadata($logo); // obviously doesn't work $logoheight = ; // don't know how to get this $logowidth = ; // don't know how to get this ?> <img src='<?php echo esc_url( get_theme_mod( 'themeslug_logo' ) ); ?>' alt='<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> Logo' class="img-responsive" height="<?php echo($logoheight);?>" width="<?php echo($logowidth);?>" > ``` Essentially, where we're running into issues is: we want to get the image width from the file as set per WP\_Customize\_Image\_Control() instead of just the URL. Thanks in advance
Modern answer to this question: We have `WP_Customize_Media_Control` control in WP since **4.2** that gives you the attachment id. This answer was posted on I [similar question](https://wordpress.stackexchange.com/a/259845/54025). You can see the documentation for `WP_Customize_Media_Control` [here](https://developer.wordpress.org/reference/classes/wp_customize_media_control/). Exemple of use: ``` $wp_customize->add_setting( 'my_menu_image' ); $wp_customize->add_control( new \WP_Customize_Media_Control( $wp_customize, 'storms_menu_image_ctrl', array( 'priority' => 10, 'mime_type' => 'image', 'settings' => 'my_menu_image', 'label' => __( 'Image on menu bar', 'my' ), 'section' => 'title_tagline', ) ) ); ``` When retrieving the info, you can do this: ``` $image_id = get_theme_mod( "my_menu_image" ); if ( ! empty( $image_id ) ) { $url = esc_url_raw( wp_get_attachment_url( $image_id ) ); $image_data = wp_get_attachment_metadata( $image_id ); $width = $image_data['width']; $height = $image_data['height']; } ```
215,164
<p>I have the following in a child theme's functions.php file:</p> <pre><code>&lt;?php function theme_child_add_scripts() { wp_register_script( 'script', get_stylesheet_directory_uri() . '/js/script.js', array( 'jquery' ), null, false ); wp_enqueue_script( 'script' ) } add_action('wp_enqueue_scripts', 'theme_child_add_scripts'); </code></pre> <p>script.js isn't included on the page and there's no network request going out to get it. What could be going wrong? It's unclear whether the child theme's functions.php file is even being executed.</p> <p>edit: It seems that the functions.php file is not being executed <em>at all</em>, because I put a die('foo') at the top of the file and the page loaded normally. Why would this be happening?</p> <p>In styles.css:</p> <pre><code>/* Theme Name: Theme-child Template: Theme */ </code></pre>
[ { "answer_id": 215351, "author": "twsmith", "author_id": 87192, "author_profile": "https://wordpress.stackexchange.com/users/87192", "pm_score": 2, "selected": true, "text": "<p>Our problem was that our style.css file was in a css folder inside the child theme directory, not at the root of the child theme. When we placed a style.css file at the root and included the comment block with theme name and template it picked up the functions.php file as expected.</p>\n" }, { "answer_id": 379262, "author": "Matt", "author_id": 198471, "author_profile": "https://wordpress.stackexchange.com/users/198471", "pm_score": 0, "selected": false, "text": "<p>I had a problem with a code that executed perfectly in the theme functions.php but not in the child theme's (that's how I found this page). I found a non-tech solution, using the free plug in Code Snippets the code executed perfectly. I was looking for a php solution, but this has saved me a bit of time.</p>\n" } ]
2016/01/20
[ "https://wordpress.stackexchange.com/questions/215164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87192/" ]
I have the following in a child theme's functions.php file: ``` <?php function theme_child_add_scripts() { wp_register_script( 'script', get_stylesheet_directory_uri() . '/js/script.js', array( 'jquery' ), null, false ); wp_enqueue_script( 'script' ) } add_action('wp_enqueue_scripts', 'theme_child_add_scripts'); ``` script.js isn't included on the page and there's no network request going out to get it. What could be going wrong? It's unclear whether the child theme's functions.php file is even being executed. edit: It seems that the functions.php file is not being executed *at all*, because I put a die('foo') at the top of the file and the page loaded normally. Why would this be happening? In styles.css: ``` /* Theme Name: Theme-child Template: Theme */ ```
Our problem was that our style.css file was in a css folder inside the child theme directory, not at the root of the child theme. When we placed a style.css file at the root and included the comment block with theme name and template it picked up the functions.php file as expected.
215,181
<p>So I've set up my site to use static pages for the front page and the posts page. Now I'm creating my posts page template. I wanted to grab some content from the actual page I made for the posts page (even though it's no longer really considered a page) and I figured out how to do it...sort of.</p> <pre><code>$posts_page = get_option( 'page_for_posts' ); $title = get_post( $posts_page )-&gt;post_title; echo $title; </code></pre> <p>So this will display the title of the "page" in the header area instead of the title of the post. What I need and can't figure out now is how to grab the featured image URL, with a custom thumbnail size with this method. </p> <p>Any ideas?</p>
[ { "answer_id": 215351, "author": "twsmith", "author_id": 87192, "author_profile": "https://wordpress.stackexchange.com/users/87192", "pm_score": 2, "selected": true, "text": "<p>Our problem was that our style.css file was in a css folder inside the child theme directory, not at the root of the child theme. When we placed a style.css file at the root and included the comment block with theme name and template it picked up the functions.php file as expected.</p>\n" }, { "answer_id": 379262, "author": "Matt", "author_id": 198471, "author_profile": "https://wordpress.stackexchange.com/users/198471", "pm_score": 0, "selected": false, "text": "<p>I had a problem with a code that executed perfectly in the theme functions.php but not in the child theme's (that's how I found this page). I found a non-tech solution, using the free plug in Code Snippets the code executed perfectly. I was looking for a php solution, but this has saved me a bit of time.</p>\n" } ]
2016/01/21
[ "https://wordpress.stackexchange.com/questions/215181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87200/" ]
So I've set up my site to use static pages for the front page and the posts page. Now I'm creating my posts page template. I wanted to grab some content from the actual page I made for the posts page (even though it's no longer really considered a page) and I figured out how to do it...sort of. ``` $posts_page = get_option( 'page_for_posts' ); $title = get_post( $posts_page )->post_title; echo $title; ``` So this will display the title of the "page" in the header area instead of the title of the post. What I need and can't figure out now is how to grab the featured image URL, with a custom thumbnail size with this method. Any ideas?
Our problem was that our style.css file was in a css folder inside the child theme directory, not at the root of the child theme. When we placed a style.css file at the root and included the comment block with theme name and template it picked up the functions.php file as expected.
215,193
<p>I'm using URL parameters as actions links within a custom WP_List_Table for users like so:</p> <pre><code>http://domain.com/wp-admin/users.php?page=account-expiration-status&amp;do_action_xyz&amp;email=email%40domain.com&amp;_wpnonce=xyz </code></pre> <p>Within the parent class, I'm checking for the existence of</p> <pre><code>array_key_exists( 'do_action_xyz', $_GET ) </code></pre> <p>to trigger the appropriate functions.</p> <p>This works fine, but unfortunately the $_GET-parameters get added to the paginations links of the table as well. This causes the action to get triggered twice when using the tablenav to browse forward or backward in the table. </p> <p>I've tried removing the $_GET-parameters right after executing the desired action with both:</p> <pre><code>unset( $_GET['do_action_xyz'] ); </code></pre> <p>and</p> <pre><code>remove_query_arg( 'do_action_xyz' ); </code></pre> <p>but WordPress still adds them to the pagination links of the table.</p> <p>Can anyone help me to remove the query arg correctly after executing the action? </p>
[ { "answer_id": 215201, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>You should consider the POST request method for your action.</p>\n\n<p>Otherwise you might try to hijack the <code>set_url_scheme</code> filter with:</p>\n\n<pre><code>add_filter( 'set_url_scheme', 'wpse_remove_arg' );\n\nfunction wpse_remove_arg( $url )\n{ \n return remove_query_arg( 'do_action_xyz', $url );\n}\n</code></pre>\n\n<p>Then you could try to narrow the scope and only run this on the corresponding table page. Further you could limit it's affect by adding it as close to the table pagination list as possible and then remove it with:</p>\n\n<pre><code>remove_filter( 'set_url_scheme', 'wpse_remove_arg' );\n</code></pre>\n\n<p>as soon as possible.</p>\n" }, { "answer_id": 330123, "author": "Walf", "author_id": 27856, "author_profile": "https://wordpress.stackexchange.com/users/27856", "pm_score": 0, "selected": false, "text": "<p>I add this filter within my page's <code>load-{$plugin_page}</code> action hook. I add my equivalent of your <code>do_action_xyz</code> parameter to a <code>wp_redirect()</code> which executes after that filter is added, but the redirect URL seems unaffected by it.</p>\n\n<p>I also \"remove\" the query parameter on the page for which it's used to display a message to the user using the <code>history</code> API.</p>\n\n<pre><code>$param = 'do_action_xyz';\nif (isset($_REQUEST[$param])) {\n add_filter('removable_query_args', function($rqa) use ($param) {\n $rqa[] = $param;\n return $rqa;\n });\n add_action('admin_notices', function() use ($param) {\n # show message here\n\n ?&gt;&lt;script&gt;\n if (history.replaceState) {\n history.replaceState(\n {}\n , document.title\n , location.pathname +\n location.search.replace(/&amp;&lt;?= $param ?&gt;=[^&amp;]+/g, '') +\n location.hash\n );\n }\n &lt;/script&gt;\n &lt;?php\n });\n}\n</code></pre>\n" } ]
2016/01/21
[ "https://wordpress.stackexchange.com/questions/215193", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73917/" ]
I'm using URL parameters as actions links within a custom WP\_List\_Table for users like so: ``` http://domain.com/wp-admin/users.php?page=account-expiration-status&do_action_xyz&email=email%40domain.com&_wpnonce=xyz ``` Within the parent class, I'm checking for the existence of ``` array_key_exists( 'do_action_xyz', $_GET ) ``` to trigger the appropriate functions. This works fine, but unfortunately the $\_GET-parameters get added to the paginations links of the table as well. This causes the action to get triggered twice when using the tablenav to browse forward or backward in the table. I've tried removing the $\_GET-parameters right after executing the desired action with both: ``` unset( $_GET['do_action_xyz'] ); ``` and ``` remove_query_arg( 'do_action_xyz' ); ``` but WordPress still adds them to the pagination links of the table. Can anyone help me to remove the query arg correctly after executing the action?
You should consider the POST request method for your action. Otherwise you might try to hijack the `set_url_scheme` filter with: ``` add_filter( 'set_url_scheme', 'wpse_remove_arg' ); function wpse_remove_arg( $url ) { return remove_query_arg( 'do_action_xyz', $url ); } ``` Then you could try to narrow the scope and only run this on the corresponding table page. Further you could limit it's affect by adding it as close to the table pagination list as possible and then remove it with: ``` remove_filter( 'set_url_scheme', 'wpse_remove_arg' ); ``` as soon as possible.
215,199
<p>I am writing my custom theme from scratch and I have a custom post type 'my_frontpage' and want to declare one of it's posts as front-page. I want to do this via admin, hence simply add my cpt to the <em>Front Page</em> select box in <em>Appearance >> Customize >> Static Front Page</em>. </p> <p>This issue has been discussed quite a few times in the internet. However, I could not find how to instructions that comprehensively explain all the steps to reach that goal. </p> <p>So far, I understand that I need to use some kind of hook to expand the choice of available front page 'pages' with posts from my cpt. But which hook to use? I wouldn't even know, if I have to use an action or a filter hook? So, could someone please guide me through this issue in laymen's terms?</p> <p>The closest result I could find was <a href="https://wordpress.stackexchange.com/questions/42461/is-it-possible-to-use-a-single-custom-post-as-the-site-front-page">This question</a>. However, I am not yet able to fully understand what happens there...</p>
[ { "answer_id": 215445, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I had time to look at your issue and the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/options-reading.php\" rel=\"nofollow\"><em>options-reading.php</em></a> page which is the template used to render the reading settings page in backend.</p>\n\n<p>There are unfortunately no filters to filter or add custom posts as sticky posts in a selectable dropdown. There are two hidden filters though which we can use, they are</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/wp_dropdown_pages/\" rel=\"nofollow\"><code>wp_dropdown_pages</code></a> inside the <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow\"><code>wp_dropdown_pages() function</code></a> which is used by the dropdown which display the list of pages which can be set as static front page</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/get_pages/\" rel=\"nofollow\"><code>get_pages</code></a> inside the <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow\"><code>get_pages()</code> function</a> which is the function responsible to return the pages which is used by <code>wp_dropdown_pages()</code></p></li>\n</ul>\n\n<p>IMHO, I think <code>get_pages</code> here is a better option. This way we will let <code>wp_dropdown_pages()</code> to take care of all the markup. We need to take care here though when we use the <code>get_pages</code> filter</p>\n\n<ul>\n<li>We will need to make sure we only target the admin area and in particular the reading settings page otherwise we will alter any function/page that uses the <code>get_pages()</code> function</li>\n</ul>\n\n<p>You need to decide whether you would need pages to show with the custom post type posts or just need the custom post types</p>\n\n<p>You can try the following:</p>\n\n<pre><code>add_filter( 'get_pages', function ( $pages, $args )\n{\n // First make sure this is an admin page, if not, bail\n if ( !is_admin() )\n return $pages;\n\n // Make sure that we are on the reading settings page, if not, bail\n global $pagenow;\n if ( 'options-reading.php' !== $pagenow )\n return $pages;\n\n // Remove the filter to avoid infinite loop\n remove_filter( current_filter(), __FUNCTION__ );\n\n $args = [\n 'post_type' =&gt; 'my_frontpage',\n 'posts_per_page' =&gt; -1\n ];\n // Get the post type posts with get_posts to allow non hierarchical post types\n $new_pages = get_posts( $args ); \n\n /**\n * You need to decide if you want to add custom post type posts to the pages\n * already in the dropdown, or just want the custom post type posts in\n * the dropdown. I will handle both, just remove what is not needed\n */\n // If we only need custom post types\n $pages = $new_pages;\n\n // If we need to add custom post type posts to the pages\n // $pages = array_merge( $new_pages, $pages );\n\n return $pages;\n}, 10, 2 );\n</code></pre>\n\n<p>You should now see your custom post type posts in the dropdown. Take note, this code will affect the dropdown for the blog page as well.</p>\n\n<p>To avoid that, you can use a static counter to count the amount of times the filter has run and then bail just before the filter is applied to the blogpage dropdown. The filter will run a total of 3 times as <code>get_pages()</code> runs 3 times:</p>\n\n<ul>\n<li><p>first to check if we actually have pages to set as a static front page. </p></li>\n<li><p>second run will be inside <code>wp_dropdown_pages()</code> which is used by the static front page dropdown</p></li>\n<li><p>the last run will be inside <code>wp_dropdown_pages()</code> which is used by the blogpage dropdown</p></li>\n</ul>\n\n<p>So, based on this, we can try</p>\n\n<pre><code>add_filter( 'get_pages', function ( $pages, $args )\n{\n // First make sure this is an admin page, if not, bail\n if ( !is_admin() )\n return $pages;\n\n // Make sure that we are on the reading settings page, if not, bail\n global $pagenow;\n if ( 'options-reading.php' !== $pagenow )\n return $pages;\n\n // Remove the filter to avoid infinite loop\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Setup our static counter\n static $counter = 0;\n\n // Bail on the third run all runs after this. The third run will be 2\n if ( 2 &lt;= $counter )\n return $pages;\n\n // Update our counter\n $counter++;\n\n $args = [\n 'post_type' =&gt; 'my_frontpage',\n 'posts_per_page' =&gt; -1\n ];\n // Get the post type posts with get_posts to allow non hierarchical post types\n $new_pages = get_posts( $args ); \n\n /**\n * You need to decide if you want to add custom post type posts to the pages\n * already in the dropdown, or just want the custom post type posts in\n * the dropdown. I will handle both, just remove what is not needed\n */\n // If we only need custom post types\n $pages = $new_pages;\n\n // If we need to add custom post type posts to the pages\n // $pages = array_merge( $new_pages, $pages );\n\n return $pages;\n}, 10, 2 );\n</code></pre>\n\n<p>If you visit the front end and visit the front page, you'll find that it will redirect to the single post page. That is because, by default, the main query on a static front page is set to query the <code>page</code> post type. This causes a 404 being returned and <code>redirect_canonical()</code> then redirects to the single post page. This is easy to solve, all we must do is to adjust the main query on the static front page. </p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target the front end\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n &amp;&amp; 'page' === get_option( 'show_on_front' ) // Only target the static front page\n ) {\n $q-&gt;set( 'post_type', 'my_frontpage' );\n }\n});\n</code></pre>\n\n<p>You will now have your static front page displaying correctly.</p>\n\n<p>All you are left to do is to set a template. You can simply create a <code>front-page.php</code>, WordPress will automatically use it</p>\n" }, { "answer_id": 215887, "author": "Bunjip", "author_id": 63707, "author_profile": "https://wordpress.stackexchange.com/users/63707", "pm_score": 0, "selected": false, "text": "<p>While Pieter solved the issue elegant and comprehensively with no doubt, I finally went with another solution, which I want to share here, too. Maybe some folks are facing similiar issues in the time to come.</p>\n\n<p>For custom post type definition as described in my question I used a plugin called <a href=\"http://pods.io\" rel=\"nofollow\">Pods</a>. As the plugin devs and community are likely to handle custom post types regularly, I thought it might be helpful to ask my question in their support channel, too. </p>\n\n<p>It was a very helpful guy from the Pods development team who pointed me in the direction, I finally went with. So, instead of defining a custom post type for the purpose of creating a highly individual static front page, he recommended to rather add custom fields to a standard page, which should become the front page. That's what I did to reach my goal and that's what I also recommend to other users. </p>\n\n<p>From a data modelling point of view, there is no reason to define a complete data type or, say, class, if you only want to apply it to a single item - in my case a single front page. I used another plugin called <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow\">Advanced Custom Fields</a>, as this allows for more advanced data types for your custom fields than Wordpress offers out of the box. You could add your custom fields via functions.php as well. Hope, that helps.</p>\n" }, { "answer_id": 291371, "author": "cruzquer", "author_id": 115634, "author_profile": "https://wordpress.stackexchange.com/users/115634", "pm_score": 0, "selected": false, "text": "<p>Well there’s also an additional way to avoid using a page template and let Wordpress load the front page by using the right post type template. This helps to avoid duplicading code if you want to let the front page look the same to the single post itself:</p>\n\n<pre><code>add_filter( 'template_include', 'add_front_page_template_path', 10, 1);\n\nfunction add_front_page_template_path( $template_path ) {\n if (\n is_front_page() \n &amp;&amp; get_option( 'show_on_front' ) == 'page' \n &amp;&amp; ( $post_id = get_option( 'page_on_front' ) )\n &amp;&amp; ( $post_type = get_post_type( $post_id ) ) != 'page' \n ) {\n $_template_path = get_single_template( $post_type );\n\n /* In case there’s no template */\n $template_path = ( $template_path == '' ) ? $template_path : $_template_path;\n }\n\n return $template_path; \n}\n</code></pre>\n" } ]
2016/01/21
[ "https://wordpress.stackexchange.com/questions/215199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63707/" ]
I am writing my custom theme from scratch and I have a custom post type 'my\_frontpage' and want to declare one of it's posts as front-page. I want to do this via admin, hence simply add my cpt to the *Front Page* select box in *Appearance >> Customize >> Static Front Page*. This issue has been discussed quite a few times in the internet. However, I could not find how to instructions that comprehensively explain all the steps to reach that goal. So far, I understand that I need to use some kind of hook to expand the choice of available front page 'pages' with posts from my cpt. But which hook to use? I wouldn't even know, if I have to use an action or a filter hook? So, could someone please guide me through this issue in laymen's terms? The closest result I could find was [This question](https://wordpress.stackexchange.com/questions/42461/is-it-possible-to-use-a-single-custom-post-as-the-site-front-page). However, I am not yet able to fully understand what happens there...
I had time to look at your issue and the [*options-reading.php*](https://github.com/WordPress/WordPress/blob/master/wp-admin/options-reading.php) page which is the template used to render the reading settings page in backend. There are unfortunately no filters to filter or add custom posts as sticky posts in a selectable dropdown. There are two hidden filters though which we can use, they are * [`wp_dropdown_pages`](https://developer.wordpress.org/reference/hooks/wp_dropdown_pages/) inside the [`wp_dropdown_pages() function`](https://developer.wordpress.org/reference/functions/wp_dropdown_pages/) which is used by the dropdown which display the list of pages which can be set as static front page * [`get_pages`](https://developer.wordpress.org/reference/hooks/get_pages/) inside the [`get_pages()` function](https://developer.wordpress.org/reference/functions/get_pages/) which is the function responsible to return the pages which is used by `wp_dropdown_pages()` IMHO, I think `get_pages` here is a better option. This way we will let `wp_dropdown_pages()` to take care of all the markup. We need to take care here though when we use the `get_pages` filter * We will need to make sure we only target the admin area and in particular the reading settings page otherwise we will alter any function/page that uses the `get_pages()` function You need to decide whether you would need pages to show with the custom post type posts or just need the custom post types You can try the following: ``` add_filter( 'get_pages', function ( $pages, $args ) { // First make sure this is an admin page, if not, bail if ( !is_admin() ) return $pages; // Make sure that we are on the reading settings page, if not, bail global $pagenow; if ( 'options-reading.php' !== $pagenow ) return $pages; // Remove the filter to avoid infinite loop remove_filter( current_filter(), __FUNCTION__ ); $args = [ 'post_type' => 'my_frontpage', 'posts_per_page' => -1 ]; // Get the post type posts with get_posts to allow non hierarchical post types $new_pages = get_posts( $args ); /** * You need to decide if you want to add custom post type posts to the pages * already in the dropdown, or just want the custom post type posts in * the dropdown. I will handle both, just remove what is not needed */ // If we only need custom post types $pages = $new_pages; // If we need to add custom post type posts to the pages // $pages = array_merge( $new_pages, $pages ); return $pages; }, 10, 2 ); ``` You should now see your custom post type posts in the dropdown. Take note, this code will affect the dropdown for the blog page as well. To avoid that, you can use a static counter to count the amount of times the filter has run and then bail just before the filter is applied to the blogpage dropdown. The filter will run a total of 3 times as `get_pages()` runs 3 times: * first to check if we actually have pages to set as a static front page. * second run will be inside `wp_dropdown_pages()` which is used by the static front page dropdown * the last run will be inside `wp_dropdown_pages()` which is used by the blogpage dropdown So, based on this, we can try ``` add_filter( 'get_pages', function ( $pages, $args ) { // First make sure this is an admin page, if not, bail if ( !is_admin() ) return $pages; // Make sure that we are on the reading settings page, if not, bail global $pagenow; if ( 'options-reading.php' !== $pagenow ) return $pages; // Remove the filter to avoid infinite loop remove_filter( current_filter(), __FUNCTION__ ); // Setup our static counter static $counter = 0; // Bail on the third run all runs after this. The third run will be 2 if ( 2 <= $counter ) return $pages; // Update our counter $counter++; $args = [ 'post_type' => 'my_frontpage', 'posts_per_page' => -1 ]; // Get the post type posts with get_posts to allow non hierarchical post types $new_pages = get_posts( $args ); /** * You need to decide if you want to add custom post type posts to the pages * already in the dropdown, or just want the custom post type posts in * the dropdown. I will handle both, just remove what is not needed */ // If we only need custom post types $pages = $new_pages; // If we need to add custom post type posts to the pages // $pages = array_merge( $new_pages, $pages ); return $pages; }, 10, 2 ); ``` If you visit the front end and visit the front page, you'll find that it will redirect to the single post page. That is because, by default, the main query on a static front page is set to query the `page` post type. This causes a 404 being returned and `redirect_canonical()` then redirects to the single post page. This is easy to solve, all we must do is to adjust the main query on the static front page. ``` add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() // Only target the front end && $q->is_main_query() // Only target the main query && 'page' === get_option( 'show_on_front' ) // Only target the static front page ) { $q->set( 'post_type', 'my_frontpage' ); } }); ``` You will now have your static front page displaying correctly. All you are left to do is to set a template. You can simply create a `front-page.php`, WordPress will automatically use it
215,219
<p>currently i add a custom billing field in woocommerce by </p> <pre><code>function custom_override_checkout_fields( $fields ) { $fields['billing']['billing_phone_new'] = array( 'label' =&gt; __('Phone 2', 'woocommerce'), 'placeholder' =&gt; _x('Phone 2', 'placeholder', 'woocommerce'), 'required' =&gt; false, 'class' =&gt; array('form-row-wide'), 'clear' =&gt; true ); return $fields; } add_filter('woocommerce_checkout_fields','custom_override_checkout_fields'); </code></pre> <p>i need to edit this field value in admin side . Currently i can edit all other values in billing address but this value is not appearing in admin section . I use the following code only for to see the value in admin section .</p> <pre><code>function order_phone_backend($order){ echo "&lt;p&gt;&lt;strong&gt;Billing phone 2:&lt;/strong&gt; " . get_post_meta( $order-&gt;id, '_billing_phone_new', true ) . "&lt;/p&gt;&lt;br&gt;"; } add_action( 'woocommerce_admin_order_data_after_billing_address', 'order_phone_backend', 10, 1 ); </code></pre> <p>I read the documentation <a href="https://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/" rel="noreferrer">https://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/</a> . But everything in this document working correct expect billing_phone/Phone is note see under Custom field . I check the screen option but i already ticked custom field . Other custom field and its value are visible and editable .</p> <p>How can i edit this value in back end . Please help .</p>
[ { "answer_id": 215447, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 6, "selected": true, "text": "<p>The code you have provided is incomplete. Not sure if that is the only code you are using to achieve what you want. So, besides first code block which you have provided, bellow I am adding all rest of the code which is required to show the new field on backend in 'Order Details' box and make it editable through custom fields. Please note, in your second code block you have named the field key as <code>_billing_new_phone</code>. Any custom field key name which starts with _ (underscore) is a hidden custom field &amp; won't show up on backend under \"Custom Fields\".</p>\n\n<pre><code>/**\n * Process the checkout\n */\nadd_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');\n\nfunction my_custom_checkout_field_process() {\n // Check if set, if its not set add an error.\n if ( ! $_POST['billing_phone_new'] )\n wc_add_notice( __( 'Phone 2 is compulsory. Please enter a value' ), 'error' );\n}\n\n\n/**\n * Update the order meta with field value\n */\nadd_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );\n\nfunction my_custom_checkout_field_update_order_meta( $order_id ) {\n if ( ! empty( $_POST['billing_phone_new'] ) ) {\n update_post_meta( $order_id, 'billing_phone_new', sanitize_text_field( $_POST['billing_phone_new'] ) );\n }\n}\n\n\n/**\n * Display field value on the order edit page\n */\nadd_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );\n\nfunction my_custom_checkout_field_display_admin_order_meta($order){\n echo '&lt;p&gt;&lt;strong&gt;'.__('Phone 2').':&lt;/strong&gt; &lt;br/&gt;' . get_post_meta( $order-&gt;get_id(), 'billing_phone_new', true ) . '&lt;/p&gt;';\n}\n</code></pre>\n\n<p>WooCommerce does not make the new checkout field editable under its standard 'Order Details' box. It will be available as 'view only' mode in that box but you can edit the same through WordPress' standard custom fields block. See below screenshot.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HlCqA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HlCqA.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 288557, "author": "GaΓ«l", "author_id": 133238, "author_profile": "https://wordpress.stackexchange.com/users/133238", "pm_score": 0, "selected": false, "text": "<p>Here is the solution :\nAccessing directly product data is not allowed, e.g. </p>\n\n<pre><code>$product-&gt;id\n</code></pre>\n\n<p>The correct method going forward is:</p>\n\n<pre><code>$product-&gt;get_id()\n</code></pre>\n" } ]
2016/01/21
[ "https://wordpress.stackexchange.com/questions/215219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86219/" ]
currently i add a custom billing field in woocommerce by ``` function custom_override_checkout_fields( $fields ) { $fields['billing']['billing_phone_new'] = array( 'label' => __('Phone 2', 'woocommerce'), 'placeholder' => _x('Phone 2', 'placeholder', 'woocommerce'), 'required' => false, 'class' => array('form-row-wide'), 'clear' => true ); return $fields; } add_filter('woocommerce_checkout_fields','custom_override_checkout_fields'); ``` i need to edit this field value in admin side . Currently i can edit all other values in billing address but this value is not appearing in admin section . I use the following code only for to see the value in admin section . ``` function order_phone_backend($order){ echo "<p><strong>Billing phone 2:</strong> " . get_post_meta( $order->id, '_billing_phone_new', true ) . "</p><br>"; } add_action( 'woocommerce_admin_order_data_after_billing_address', 'order_phone_backend', 10, 1 ); ``` I read the documentation <https://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/> . But everything in this document working correct expect billing\_phone/Phone is note see under Custom field . I check the screen option but i already ticked custom field . Other custom field and its value are visible and editable . How can i edit this value in back end . Please help .
The code you have provided is incomplete. Not sure if that is the only code you are using to achieve what you want. So, besides first code block which you have provided, bellow I am adding all rest of the code which is required to show the new field on backend in 'Order Details' box and make it editable through custom fields. Please note, in your second code block you have named the field key as `_billing_new_phone`. Any custom field key name which starts with \_ (underscore) is a hidden custom field & won't show up on backend under "Custom Fields". ``` /** * Process the checkout */ add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { // Check if set, if its not set add an error. if ( ! $_POST['billing_phone_new'] ) wc_add_notice( __( 'Phone 2 is compulsory. Please enter a value' ), 'error' ); } /** * Update the order meta with field value */ add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' ); function my_custom_checkout_field_update_order_meta( $order_id ) { if ( ! empty( $_POST['billing_phone_new'] ) ) { update_post_meta( $order_id, 'billing_phone_new', sanitize_text_field( $_POST['billing_phone_new'] ) ); } } /** * Display field value on the order edit page */ add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 ); function my_custom_checkout_field_display_admin_order_meta($order){ echo '<p><strong>'.__('Phone 2').':</strong> <br/>' . get_post_meta( $order->get_id(), 'billing_phone_new', true ) . '</p>'; } ``` WooCommerce does not make the new checkout field editable under its standard 'Order Details' box. It will be available as 'view only' mode in that box but you can edit the same through WordPress' standard custom fields block. See below screenshot. [![enter image description here](https://i.stack.imgur.com/HlCqA.png)](https://i.stack.imgur.com/HlCqA.png)
215,239
<p>I'm trying to make a menu that automatically populates from a custom post type I have and I'm having some trouble getting it right If someone could point me in the right direction I would greatly appreciate it. Here is the code. The PHP in the <code>&lt;img src&gt;</code> is pulling the right info and sticking it in the right spot, <code>the_permalink</code> pulls the correct url but then it is putting the url above the <code>&lt;li&gt;</code> tag instead of in the href. </p> <pre><code>&lt;ul class="product-menu"&gt; &lt;?php $products = new WP_Query( $args = array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', ) ); while ( $products-&gt;have_posts() ) { $products-&gt;the_post(); $post_thumbnail_id = get_post_thumbnail_id(); $post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id ); echo '&lt;li&gt; &lt;a href="' . the_permalink() . '"&gt; &lt;img src="' . $post_thumbnail_url . '" alt="' . get_the_title() . '"&gt; &lt;/a&gt; &lt;/li&gt;'; } /* Restore original Post Data */ wp_reset_postdata();?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 215241, "author": "ScheRas", "author_id": 87069, "author_profile": "https://wordpress.stackexchange.com/users/87069", "pm_score": 4, "selected": true, "text": "<p><code>the_permalink()</code> <strong>prints</strong> url immediately and returns nothing, you should use <code>get_the_permalink()</code> function, which <strong>returns</strong> current post url.</p>\n" }, { "answer_id": 215242, "author": "Chris Morris", "author_id": 39242, "author_profile": "https://wordpress.stackexchange.com/users/39242", "pm_score": 2, "selected": false, "text": "<p>You were using the_permalink which echos out, so you echoed out in an echo. You want to sue get_the_permalink to return the url which can then be echoed out into the code. Most wordpress functions starting with the_ directly echo out onto the page, those with get_ return the result.</p>\n\n<p>This should work for you. I've also used the_post_thumbnail to bring out a wordpress formatted thumbnail image and update the issue with the hyperlink.</p>\n\n<pre><code>&lt;ul class=\"product-menu\"&gt;\n &lt;?php\n\n $args = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n )\n\n $products = new WP_Query($args);\n\n while ( $products-&gt;have_posts() ) {\n $products-&gt;the_post();\n\n echo '&lt;li&gt;&lt;a href=\"' . get_the_permalink() . '\"&gt;';\n\n // check if the post has a Post Thumbnail assigned to it.\n if ( has_post_thumbnail() ) {\n the_post_thumbnail();\n }\n\n echo '&lt;/a&gt;&lt;/li&gt;';\n } \n /* Restore original Post Data */\n wp_reset_postdata();\n\n ?&gt;\n&lt;/ul&gt;\n</code></pre>\n" } ]
2016/01/21
[ "https://wordpress.stackexchange.com/questions/215239", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84703/" ]
I'm trying to make a menu that automatically populates from a custom post type I have and I'm having some trouble getting it right If someone could point me in the right direction I would greatly appreciate it. Here is the code. The PHP in the `<img src>` is pulling the right info and sticking it in the right spot, `the_permalink` pulls the correct url but then it is putting the url above the `<li>` tag instead of in the href. ``` <ul class="product-menu"> <?php $products = new WP_Query( $args = array( 'post_type' => 'product', 'post_status' => 'publish', ) ); while ( $products->have_posts() ) { $products->the_post(); $post_thumbnail_id = get_post_thumbnail_id(); $post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id ); echo '<li> <a href="' . the_permalink() . '"> <img src="' . $post_thumbnail_url . '" alt="' . get_the_title() . '"> </a> </li>'; } /* Restore original Post Data */ wp_reset_postdata();?> </ul> ```
`the_permalink()` **prints** url immediately and returns nothing, you should use `get_the_permalink()` function, which **returns** current post url.
215,289
<p>I want to wrap <code>&lt;strong&gt;&lt;/strong&gt;</code> around the words "logged out":</p> <pre><code>add_filter( 'gettext', 'wpse17709_gettext', 10, 2 ); function wpse17709_gettext( $custom_translation, $login_texts ) { // Messages if ( 'You are now logged out.' == $login_texts ) { return ''; } // Log out message return $translation } </code></pre> <p>...however adding HTML elements to the text string breaks my page.</p> <p>How can I add <code>&lt;strong&gt;&lt;/strong&gt;</code> to this message text? Is there a means other than <code>gettext</code>?</p>
[ { "answer_id": 215294, "author": "Clarus Dignus", "author_id": 41545, "author_profile": "https://wordpress.stackexchange.com/users/41545", "pm_score": 1, "selected": false, "text": "<p>Based on Sven's recommended solution and Tom J Nowell's warning about <code>gettext()</code> (see comments for both), I've fashioned the following solution:</p>\n\n<pre><code>add_filter( 'login_message', 'wpse_215289_custom_logout_message' );\nadd_action( 'login_head','wpse_215289_custom_login_head' );\n\n// Detect logout and add custom message.\nfunction wpse_215289_custom_logout_message() \n{\n //check to see if it's the logout screen\n if ( isset($_GET['loggedout']) &amp;&amp; TRUE == $_GET['loggedout'] ){\n $message = \"&lt;p class='message'&gt;Custom log-out message.&lt;/p&gt;\";\n }\n return $message;\n} \n\n// Remove original message via CSS.\nfunction wpse_215289_custom_login_head() \n{\n ?&gt;\n &lt;style type=\"text/css\"&gt;\n .message:nth-child(2) { display:none; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 215298, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 3, "selected": true, "text": "<p>This allows for the message to be overwritten specifically for the <code>loggedout</code> message while leaving all other messages alone. <a href=\"https://developer.wordpress.org/reference/hooks/wp_login_errors/\" rel=\"nofollow\">Here is more documentation on the filter</a>.</p>\n\n<pre><code>add_filter( 'wp_login_errors', 'my_logout_message' );\n\nfunction my_logout_message( $errors ){\n\n if ( isset( $errors-&gt;errors['loggedout'] ) ){\n $errors-&gt;errors['loggedout'][0] = 'This is the &lt;strong style=\"color:red;\"&gt;logged out&lt;/strong&gt; message.';\n }\n\n return $errors;\n}\n</code></pre>\n" }, { "answer_id": 289500, "author": "Billu", "author_id": 133699, "author_profile": "https://wordpress.stackexchange.com/users/133699", "pm_score": 1, "selected": false, "text": "<p>Change β€œYou are now logged out” text using filter <strong>login_messages</strong></p>\n\n<pre><code>function custom_logout_message(){\n return 'You are not login!';\n}\nadd_filter( 'login_messages', 'custom_logout_message' );\n</code></pre>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215289", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41545/" ]
I want to wrap `<strong></strong>` around the words "logged out": ``` add_filter( 'gettext', 'wpse17709_gettext', 10, 2 ); function wpse17709_gettext( $custom_translation, $login_texts ) { // Messages if ( 'You are now logged out.' == $login_texts ) { return ''; } // Log out message return $translation } ``` ...however adding HTML elements to the text string breaks my page. How can I add `<strong></strong>` to this message text? Is there a means other than `gettext`?
This allows for the message to be overwritten specifically for the `loggedout` message while leaving all other messages alone. [Here is more documentation on the filter](https://developer.wordpress.org/reference/hooks/wp_login_errors/). ``` add_filter( 'wp_login_errors', 'my_logout_message' ); function my_logout_message( $errors ){ if ( isset( $errors->errors['loggedout'] ) ){ $errors->errors['loggedout'][0] = 'This is the <strong style="color:red;">logged out</strong> message.'; } return $errors; } ```
215,297
<p><a href="https://wordpress.org/plugins/tabulate/" rel="nofollow">A plugin</a> I maintain uses Twig templates to produce HTML (and some other outputs). I've tried using <code>__()</code> within these (first adding the i18n functions with <code>$twig-&gt;addFunction()</code>) but it doesn't work. The strings are output correctly, but not picked up for inclusion in the <code>.pot</code> file.</p> <p>For <a href="https://github.com/tabulate/tabulate/blob/master/templates/base.html#L9" rel="nofollow">example</a> the following in <code>base.twig</code> should be translatable:</p> <pre><code>{{__('Search', 'tabulate')}} </code></pre> <p>I'm obviously off on the wrong track here. Anyone got any pointers for doing this?</p>
[ { "answer_id": 215294, "author": "Clarus Dignus", "author_id": 41545, "author_profile": "https://wordpress.stackexchange.com/users/41545", "pm_score": 1, "selected": false, "text": "<p>Based on Sven's recommended solution and Tom J Nowell's warning about <code>gettext()</code> (see comments for both), I've fashioned the following solution:</p>\n\n<pre><code>add_filter( 'login_message', 'wpse_215289_custom_logout_message' );\nadd_action( 'login_head','wpse_215289_custom_login_head' );\n\n// Detect logout and add custom message.\nfunction wpse_215289_custom_logout_message() \n{\n //check to see if it's the logout screen\n if ( isset($_GET['loggedout']) &amp;&amp; TRUE == $_GET['loggedout'] ){\n $message = \"&lt;p class='message'&gt;Custom log-out message.&lt;/p&gt;\";\n }\n return $message;\n} \n\n// Remove original message via CSS.\nfunction wpse_215289_custom_login_head() \n{\n ?&gt;\n &lt;style type=\"text/css\"&gt;\n .message:nth-child(2) { display:none; }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 215298, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 3, "selected": true, "text": "<p>This allows for the message to be overwritten specifically for the <code>loggedout</code> message while leaving all other messages alone. <a href=\"https://developer.wordpress.org/reference/hooks/wp_login_errors/\" rel=\"nofollow\">Here is more documentation on the filter</a>.</p>\n\n<pre><code>add_filter( 'wp_login_errors', 'my_logout_message' );\n\nfunction my_logout_message( $errors ){\n\n if ( isset( $errors-&gt;errors['loggedout'] ) ){\n $errors-&gt;errors['loggedout'][0] = 'This is the &lt;strong style=\"color:red;\"&gt;logged out&lt;/strong&gt; message.';\n }\n\n return $errors;\n}\n</code></pre>\n" }, { "answer_id": 289500, "author": "Billu", "author_id": 133699, "author_profile": "https://wordpress.stackexchange.com/users/133699", "pm_score": 1, "selected": false, "text": "<p>Change β€œYou are now logged out” text using filter <strong>login_messages</strong></p>\n\n<pre><code>function custom_logout_message(){\n return 'You are not login!';\n}\nadd_filter( 'login_messages', 'custom_logout_message' );\n</code></pre>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58142/" ]
[A plugin](https://wordpress.org/plugins/tabulate/) I maintain uses Twig templates to produce HTML (and some other outputs). I've tried using `__()` within these (first adding the i18n functions with `$twig->addFunction()`) but it doesn't work. The strings are output correctly, but not picked up for inclusion in the `.pot` file. For [example](https://github.com/tabulate/tabulate/blob/master/templates/base.html#L9) the following in `base.twig` should be translatable: ``` {{__('Search', 'tabulate')}} ``` I'm obviously off on the wrong track here. Anyone got any pointers for doing this?
This allows for the message to be overwritten specifically for the `loggedout` message while leaving all other messages alone. [Here is more documentation on the filter](https://developer.wordpress.org/reference/hooks/wp_login_errors/). ``` add_filter( 'wp_login_errors', 'my_logout_message' ); function my_logout_message( $errors ){ if ( isset( $errors->errors['loggedout'] ) ){ $errors->errors['loggedout'][0] = 'This is the <strong style="color:red;">logged out</strong> message.'; } return $errors; } ```
215,321
<p>I have a custom php page and i need to override the global posts variables, but i cant get it to work. When going through the main loop im able to override the global posts, but i cant override whatever have_posts() is using to obtain the count. Im obtaining data from a 3rd party API so i need to build the WP object on the fly and then override the default objects returned from the default query. I have the following code and its working, but the problem is that i get a result that contains the post and then several null objects afterwards.</p> <pre><code>require_once('../../../wp-blog-header.php'); global $post, $posts, $found_posts, $post_count; $post-&gt;ID = 99999999999; $post-&gt;post_content = "TEST PAGE content"; $post-&gt;post_title = "Page Title"; $post-&gt;post_name = "test"; $posts = array($post); $post_count = 1; $found_posts = 1; if ( have_posts() ) { while ( have_posts() ) { the_post(); var_dump($post); } } </code></pre> <p>The above code generates the following output. I need to get rid of the NULLs. To do this i need to make it so have_posts() only returns true once.</p> <blockquote> <p>object(WP_Post)#2975 (24) { ["ID"]=> int(99999999999) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2016-01-21 19:50:24" ["post_date_gmt"]=> string(19) "2016-01-21 19:50:24" ["post_content"]=> string(17) "TEST PAGE content" ["post_title"]=> string(10) "Page Title" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(6) "closed" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(4) "test" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2016-01-21 19:50:24" ["post_modified_gmt"]=> string(19) "2016-01-21 19:50:24" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(36) "" ["menu_order"]=> int(0) ["post_type"]=> string(4) "page" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } NULL NULL NULL NULL NULL NULL NULL NULL NULL</p> </blockquote>
[ { "answer_id": 215329, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>It is quite hard to understand what you need to do here, but you need to look at the following</p>\n\n<ul>\n<li><p>Do not use the global variables as local variables, it breaks the global variables and causes issues with the loop. It is also quite hard to debug when you run into issues. The only global variable that should be used as a local variable is when you work with <code>setup_postdata()</code>. <code>setup_postdata()</code> requires the <code>$post</code> global. You just need to remember to reset the <code>$post</code> global afterwards.</p></li>\n<li><p>Use the actions and filters available inside <code>WP_Query</code> to change the result from a specific query object</p></li>\n</ul>\n\n<p>In general, the <code>$post_count</code> property is calculated from the amount of posts inside <code>$posts</code>. Just before posts are counted, we get the <code>the_posts</code> filter. This allows us to add/remove post objects (<em>or rearrange the post order</em>) from the <code>$posts</code> array. Any alteration here in the amount of posts will result in the `$post_count property being altered</p>\n\n<p>Here is the relevant code from the <code>WP_Query</code> class</p>\n\n<pre><code>if ( ! $q['suppress_filters'] ) {\n /**\n * Filter the array of retrieved posts after they've been fetched and\n * internally processed.\n *\n * @since 1.5.0\n *\n * @param array $posts The array of retrieved posts.\n * @param WP_Query &amp;$this The WP_Query instance (passed by reference).\n */\n $this-&gt;posts = apply_filters_ref_array( 'the_posts', array( $this-&gt;posts, &amp;$this ) );\n}\n// Ensure that any posts added/modified via one of the filters above are\n// of the type WP_Post and are filtered.\nif ( $this-&gt;posts ) {\n $this-&gt;post_count = count( $this-&gt;posts );\n $this-&gt;posts = array_map( 'get_post', $this-&gt;posts );\n if ( $q['cache_results'] )\n update_post_caches($this-&gt;posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);\n $this-&gt;post = reset( $this-&gt;posts );\n} else {\n $this-&gt;post_count = 0;\n $this-&gt;posts = array();\n}\n</code></pre>\n\n<p>If you want to add a post into the array of posts returned, this will be the place to do it</p>\n\n<pre><code>add_filter( 'the_posts', function ( $posts, \\WP_Query $q )\n{\n if ( !$q-&gt;is_main_query ) // Only target the main query, return if not. Add any additional conditions\n return $posts;\n\n $post_to_add = [\n // Valid post properties\n ]; \n\n $post_to_add = array_map( 'get_post', $post_to_add );\n\n // Add some checks to make sure our $post_to_inject is a valid.\n\n // Add $post_to_add in front of $posts array\n $posts = array_merge( $post_to_add, $posts );\n\n // If you need to replace $posts with your object\n //$posts = [$post_to_add];\n\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<p><code>$post</code> gets set from the first post in the <code>$posts</code> array, so there is also no need to fiddle with that.</p>\n\n<p>As for <code>$found_posts</code> you can make use of the <code>found_posts</code> filter to adjust the amount of posts found</p>\n\n<pre><code>add_filter( 'found_posts', function ( $found_posts, \\WP_Query $q )\n{\n if ( !$q-&gt;is_main_query ) // Only target the main query, return if not. Add any additional conditions\n return $found_posts;\n\n $found_posts = 1; // Taken info from your question\n\n return $found_posts;\n}): \n</code></pre>\n\n<p>As I said, I'm not particulary sure what you need to do, but I hope I did touch the point you are after</p>\n" }, { "answer_id": 216236, "author": "user1889580", "author_id": 190834, "author_profile": "https://wordpress.stackexchange.com/users/190834", "pm_score": 1, "selected": true, "text": "<p>I found the solution to this was in the $wp_query variable. By getting the global variable for this and overriding the values within it i was able to have full control over what displayed on the page. This allowed me to generate a WP post object that came from a database outside of wordpress, but didnt have to do anything difficult to make it display.</p>\n\n<p>Here is a full guide that explains how to do it <a href=\"http://yomotherboard.com/how-to-add-a-custom-php-page-to-wordpress-using-a-plugin/\" rel=\"nofollow\">http://yomotherboard.com/how-to-add-a-custom-php-page-to-wordpress-using-a-plugin/</a> </p>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have a custom php page and i need to override the global posts variables, but i cant get it to work. When going through the main loop im able to override the global posts, but i cant override whatever have\_posts() is using to obtain the count. Im obtaining data from a 3rd party API so i need to build the WP object on the fly and then override the default objects returned from the default query. I have the following code and its working, but the problem is that i get a result that contains the post and then several null objects afterwards. ``` require_once('../../../wp-blog-header.php'); global $post, $posts, $found_posts, $post_count; $post->ID = 99999999999; $post->post_content = "TEST PAGE content"; $post->post_title = "Page Title"; $post->post_name = "test"; $posts = array($post); $post_count = 1; $found_posts = 1; if ( have_posts() ) { while ( have_posts() ) { the_post(); var_dump($post); } } ``` The above code generates the following output. I need to get rid of the NULLs. To do this i need to make it so have\_posts() only returns true once. > > object(WP\_Post)#2975 (24) { ["ID"]=> int(99999999999) > ["post\_author"]=> string(1) "1" ["post\_date"]=> string(19) "2016-01-21 > 19:50:24" ["post\_date\_gmt"]=> string(19) "2016-01-21 19:50:24" > ["post\_content"]=> string(17) "TEST PAGE content" ["post\_title"]=> > string(10) "Page Title" ["post\_excerpt"]=> string(0) "" > ["post\_status"]=> string(7) "publish" ["comment\_status"]=> string(6) > "closed" ["ping\_status"]=> string(6) "closed" ["post\_password"]=> > string(0) "" ["post\_name"]=> string(4) "test" ["to\_ping"]=> string(0) > "" ["pinged"]=> string(0) "" ["post\_modified"]=> string(19) > "2016-01-21 19:50:24" ["post\_modified\_gmt"]=> string(19) "2016-01-21 > 19:50:24" ["post\_content\_filtered"]=> string(0) "" ["post\_parent"]=> > int(0) ["guid"]=> string(36) "" ["menu\_order"]=> int(0) > ["post\_type"]=> string(4) "page" ["post\_mime\_type"]=> string(0) "" > ["comment\_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } NULL > NULL NULL NULL NULL NULL NULL NULL NULL > > >
I found the solution to this was in the $wp\_query variable. By getting the global variable for this and overriding the values within it i was able to have full control over what displayed on the page. This allowed me to generate a WP post object that came from a database outside of wordpress, but didnt have to do anything difficult to make it display. Here is a full guide that explains how to do it <http://yomotherboard.com/how-to-add-a-custom-php-page-to-wordpress-using-a-plugin/>
215,343
<p>I have running a wordpress site on - lets say - "site.com" and another site "input.com" hosted in completely different locations. As the name suggests, "input.com" should be used as a input site with a very simple form (for example: title and content). The entered information should then be sent to "site.com" and posted as a blogpost, just like somebody entered the information using the wp-admin panel.</p> <p>Usually I would use cURL for this, but since wp-admin panel is pretty complicated (login and stuff) I looked for other ways to do it. Unfortunatly the wordpress rest API seems to be limited to getting data from "site.com" but offers no option to send data to it. All other APIs I found did not work properly (or at all) because they were either outdated or badly documented.</p> <p>Is there any simple way to do this without coding a cURL programm? The most promising thing I found so far is this: <a href="https://github.com/HarriBellThomas/Wordpress_PostController" rel="nofollow">https://github.com/HarriBellThomas/Wordpress_PostController</a> But I was not able to make it work yet. I would really appreciate your help!</p> <p>Edit:</p> <pre><code>&lt;?php set_time_limit(0); error_reporting(E_ALL); ini_set('display_errors', 1); include("./wp-includes/post.php"); // Create post object $my_post = array( 'post_title' =&gt; "test",//wp_strip_all_tags( $_POST['post_title'] ), 'post_content' =&gt; "teeeeeeeessssssssssttttttttttt",// $_POST['post_content'], 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_category' =&gt; array( 1,2 ) ); // Insert the post into the database wp_insert_post( $my_post ); ?&gt; </code></pre>
[ { "answer_id": 215347, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 0, "selected": false, "text": "<p>Setup a script on site.com to receive the data from input.com and use <code>wp_insert_post()</code> to create the post on site.com.</p>\n\n<p>The title, content and other post details are sent using the following array structure:</p>\n\n<pre><code>$post = array(\n 'ID' =&gt; [ &lt;post id&gt; ] // Are you updating an existing post?\n 'post_content' =&gt; [ &lt;string&gt; ] // The full text of the post.\n 'post_name' =&gt; [ &lt;string&gt; ] // The name (slug) for your post\n 'post_title' =&gt; [ &lt;string&gt; ] // The title of your post.\n 'post_status' =&gt; [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] // Default 'draft'.\n 'post_type' =&gt; [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] // Default 'post'.\n 'post_author' =&gt; [ &lt;user ID&gt; ] // The user ID number of the author. Default is the current user ID.\n 'ping_status' =&gt; [ 'closed' | 'open' ] // Pingbacks or trackbacks allowed. Default is the option 'default_ping_status'.\n 'post_parent' =&gt; [ &lt;post ID&gt; ] // Sets the parent of the new post, if any. Default 0.\n 'menu_order' =&gt; [ &lt;order&gt; ] // If new post is a page, sets the order in which it should appear in supported menus. Default 0.\n 'to_ping' =&gt; // Space or carriage return-separated list of URLs to ping. Default empty string.\n 'pinged' =&gt; // Space or carriage return-separated list of URLs that have been pinged. Default empty string.\n 'post_password' =&gt; [ &lt;string&gt; ] // Password for post, if any. Default empty string.\n 'guid' =&gt; // Skip this and let Wordpress handle it, usually.\n 'post_content_filtered' =&gt; // Skip this and let Wordpress handle it, usually.\n 'post_excerpt' =&gt; [ &lt;string&gt; ] // For all your post excerpt needs.\n 'post_date' =&gt; [ Y-m-d H:i:s ] // The time post was made.\n 'post_date_gmt' =&gt; [ Y-m-d H:i:s ] // The time post was made, in GMT.\n 'comment_status' =&gt; [ 'closed' | 'open' ] // Default is the option 'default_comment_status', or 'closed'.\n 'post_category' =&gt; [ array(&lt;category id&gt;, ...) ] // Default empty.\n 'tags_input' =&gt; [ '&lt;tag&gt;, &lt;tag&gt;, ...' | array ] // Default empty.\n 'tax_input' =&gt; [ array( &lt;taxonomy&gt; =&gt; &lt;array | string&gt;, &lt;taxonomy_other&gt; =&gt; &lt;array | string&gt; ) ] // For custom taxonomies. Default empty.\n 'page_template' =&gt; [ &lt;string&gt; ] // Requires name of template file, eg template.php. Default empty.\n); \n</code></pre>\n\n<p>Leave the ID blank to create a new post.</p>\n\n<p>Detailed documentation on the WP Codex:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_insert_post</a></p>\n" }, { "answer_id": 215448, "author": "Julian F", "author_id": 87300, "author_profile": "https://wordpress.stackexchange.com/users/87300", "pm_score": 2, "selected": true, "text": "<p>I finally managed to accomplish the task using XML-RPC as suggested by denis.stoyanov. If xmlrpc is installed on your Server simply use the\n<a href=\"https://stackoverflow.com/questions/24264761/how-to-add-posts-in-wordpress-without-admin-login-using-xml-rpc-and-curl\">wpPostXMLRPC function</a> from stackoverflow. But keep in mind that the used <a href=\"http://php.net/manual/de/function.xmlrpc-encode-request.php\" rel=\"nofollow noreferrer\">xmlrpc_encode_request()</a> is an experimental function you usually would try to avoid.</p>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87300/" ]
I have running a wordpress site on - lets say - "site.com" and another site "input.com" hosted in completely different locations. As the name suggests, "input.com" should be used as a input site with a very simple form (for example: title and content). The entered information should then be sent to "site.com" and posted as a blogpost, just like somebody entered the information using the wp-admin panel. Usually I would use cURL for this, but since wp-admin panel is pretty complicated (login and stuff) I looked for other ways to do it. Unfortunatly the wordpress rest API seems to be limited to getting data from "site.com" but offers no option to send data to it. All other APIs I found did not work properly (or at all) because they were either outdated or badly documented. Is there any simple way to do this without coding a cURL programm? The most promising thing I found so far is this: <https://github.com/HarriBellThomas/Wordpress_PostController> But I was not able to make it work yet. I would really appreciate your help! Edit: ``` <?php set_time_limit(0); error_reporting(E_ALL); ini_set('display_errors', 1); include("./wp-includes/post.php"); // Create post object $my_post = array( 'post_title' => "test",//wp_strip_all_tags( $_POST['post_title'] ), 'post_content' => "teeeeeeeessssssssssttttttttttt",// $_POST['post_content'], 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 1,2 ) ); // Insert the post into the database wp_insert_post( $my_post ); ?> ```
I finally managed to accomplish the task using XML-RPC as suggested by denis.stoyanov. If xmlrpc is installed on your Server simply use the [wpPostXMLRPC function](https://stackoverflow.com/questions/24264761/how-to-add-posts-in-wordpress-without-admin-login-using-xml-rpc-and-curl) from stackoverflow. But keep in mind that the used [xmlrpc\_encode\_request()](http://php.net/manual/de/function.xmlrpc-encode-request.php) is an experimental function you usually would try to avoid.
215,375
<p>I'm using some private posts for intern purposes. When an editor changes something on these posts, its status turns to pending "review" and I have to publish it again as a private post.</p> <p>When an editor changes something on a normal page/post - that has already been published for public - the status doesn't change, so I'm a bit confused. </p> <p>Is it possible, to force wordpress, to let the private <em>status</em> untouched, when an editor works on these posts?</p> <p>Thanks a lot!</p> <p><strong>Edit:</strong></p> <p>For everyone dealing with the same problem: I was able to fix it with a code snippet of another thread: <a href="https://wordpress.stackexchange.com/a/172556/87321">https://wordpress.stackexchange.com/a/172556/87321</a></p> <p>Just had to add the post status "pending", so the working solution is:</p> <pre><code>add_filter('wp_insert_post_data', 'mark_post_private'); function mark_post_private($data) { if(($data['post_type'] == 'your_post_type_goes_here') &amp;&amp; ( $data['post_status'] == 'pending')) { $data['post_status'] = 'private'; } return $data; } </code></pre>
[ { "answer_id": 216389, "author": "jhcorsair", "author_id": 73025, "author_profile": "https://wordpress.stackexchange.com/users/73025", "pm_score": -1, "selected": false, "text": "<p>I would check that your users have the same capability. It sounds like this is happening: </p>\n\n<p>\"Internally, WordPress sets the post status to publish when you click the \"Publish\" button, and WordPress sets the post status to draft when you click the \"Save Draft\" button. Similarly, if your website has users granted the edit_posts capability but not the publish_posts capability, then when those users start writing a new post, WordPress will display a \"Submit for Review\" button instead of a \"Publish\" button. Likewise, WordPress then assigns the post that user created the pending status when they press that button. \"</p>\n\n<p>Found here <a href=\"https://codex.wordpress.org/Post_Status\" rel=\"nofollow\">Wordpress Post Status</a></p>\n" }, { "answer_id": 235025, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 1, "selected": false, "text": "<p>As it doesn't look as though the OP is coming back, I'm adding their answer as an answer rather than leaving it in the question:</p>\n\n<blockquote>\n <p>For everyone dealing with the same problem: I was able to fix it with\n a code snippet of another thread:\n <a href=\"https://wordpress.stackexchange.com/a/172556/87321\">https://wordpress.stackexchange.com/a/172556/87321</a></p>\n \n <p>Just had to add the post status \"pending\", so the working solution is:</p>\n</blockquote>\n\n<pre><code>add_filter('wp_insert_post_data', 'mark_post_private'); \nfunction mark_post_private($data)\n{\n if(($data['post_type'] == 'your_post_type_goes_here') &amp;&amp; ( $data['post_status'] == 'pending'))\n {\n $data['post_status'] = 'private';\n }\n\n return $data;\n}\n</code></pre>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87321/" ]
I'm using some private posts for intern purposes. When an editor changes something on these posts, its status turns to pending "review" and I have to publish it again as a private post. When an editor changes something on a normal page/post - that has already been published for public - the status doesn't change, so I'm a bit confused. Is it possible, to force wordpress, to let the private *status* untouched, when an editor works on these posts? Thanks a lot! **Edit:** For everyone dealing with the same problem: I was able to fix it with a code snippet of another thread: <https://wordpress.stackexchange.com/a/172556/87321> Just had to add the post status "pending", so the working solution is: ``` add_filter('wp_insert_post_data', 'mark_post_private'); function mark_post_private($data) { if(($data['post_type'] == 'your_post_type_goes_here') && ( $data['post_status'] == 'pending')) { $data['post_status'] = 'private'; } return $data; } ```
As it doesn't look as though the OP is coming back, I'm adding their answer as an answer rather than leaving it in the question: > > For everyone dealing with the same problem: I was able to fix it with > a code snippet of another thread: > <https://wordpress.stackexchange.com/a/172556/87321> > > > Just had to add the post status "pending", so the working solution is: > > > ``` add_filter('wp_insert_post_data', 'mark_post_private'); function mark_post_private($data) { if(($data['post_type'] == 'your_post_type_goes_here') && ( $data['post_status'] == 'pending')) { $data['post_status'] = 'private'; } return $data; } ```
215,386
<p>I'm registering my javascript files for Wordpress in my functions file as so:</p> <pre><code>if( !function_exists( "theme_js" ) ) { function theme_js(){ wp_register_script('wpbs-scripts', get_template_directory_uri() . '/library/js/min/scripts.min.js', array('jquery'), '1.43', 'true' ); wp_enqueue_script('wpbs-scripts'); } } add_action( 'wp_enqueue_scripts', 'theme_js' ); </code></pre> <p>In my production environment they are executing properly with the version number as you would expect "scripts.min.js/?ver=1.43. But on the live server the version numbers are a 32 digit string of random numbers and lowercase letters like this "scripts.min.js/?ver=65cat8def2cbb5f145751979a4b2b7cf".</p> <p>I have no idea what is causing this and it seems to have happened only recently. I started noticing that people needed to refresh the site to see changes. </p>
[ { "answer_id": 215388, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>Don't you need to be using wp_enqueue_script instead of wp_register_script? What I get from the <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script codex page</a> the correct way to add scripts dependant on jQuery is:</p>\n\n<pre><code>&lt;?php\n\n function my_scripts_method() {\n wp_enqueue_script(\n 'custom-script',\n get_stylesheet_directory_uri() . '/js/custom_script.js',\n array( 'jquery' )\n );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_scripts_method' );\n\n?&gt;\n</code></pre>\n\n<p>This may be what's causing you issues.</p>\n" }, { "answer_id": 215398, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 1, "selected": false, "text": "<p>I have not directly an answer to solve your issue as it <em>(please take a look at the <strong>edit</strong> part I add)</em>, <br />but this codesnippet (<code>function</code>) could maybe help you to solve the version issues for .js as well for .css files.</p>\n\n<pre><code>/**\n * Remove query (output)string from .js / .css\n * Using filters\n */\nfunction wpse215386_remove_script_version( $src ){\n $parts = explode( '?ver', $src );\n return $parts[0];\n}\n// for .js files\nadd_filter( 'script_loader_src', 'wpse215386_remove_script_version', 15, 1 );\n// for .css files\nadd_filter( 'style_loader_src', 'wpse215386_remove_script_version', 15, 1 );\n</code></pre>\n\n<p>Please leave version numbers away when you use <code>enqueue</code> if there is no specific reason to use them. Add .js filles to the footer to help your pages loading faster, for reference see <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script#Parameters\" rel=\"nofollow noreferrer\">$in_footer</a>.<br /></p>\n\n<p>Think about updates/upgrades and what can/will happen when versions change and not match with the version(s) you use in your function(s).</p>\n\n<p>The function above has also another effect(a positive one), namely helping to make files easier cacheable. <em>See my answer <a href=\"https://wordpress.stackexchange.com/a/195253/15605\">here</a> for some explanation.</em> <br /></p>\n\n<blockquote>\n <p>Codex:\n <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\">register</a>\n and\n <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\">enqueue</a>\n the correct way to prevent issues.</p>\n</blockquote>\n\n<p><hr>\n<strong>Edit</strong><br /></p>\n\n<blockquote>\n <p>One of the reasons could be a security or cache pluging (or maybe even\n both), so disabling plugins to see which could cause the problem. Enable\n <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\"><code>debug</code></a>\n in <code>wp-config.php</code> to see if it drops error messages in the\n logfile.(if correct configurated the log file will be in the\n <code>wp-content</code> folder.</p>\n</blockquote>\n" }, { "answer_id": 216623, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 0, "selected": false, "text": "<p>The WordPress plugin Wordfence(ver. 6.0.22) was causing this issue. To fix this, go to \"Options\" and uncheck \"Hide WordPress Version\".</p>\n" } ]
2016/01/22
[ "https://wordpress.stackexchange.com/questions/215386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I'm registering my javascript files for Wordpress in my functions file as so: ``` if( !function_exists( "theme_js" ) ) { function theme_js(){ wp_register_script('wpbs-scripts', get_template_directory_uri() . '/library/js/min/scripts.min.js', array('jquery'), '1.43', 'true' ); wp_enqueue_script('wpbs-scripts'); } } add_action( 'wp_enqueue_scripts', 'theme_js' ); ``` In my production environment they are executing properly with the version number as you would expect "scripts.min.js/?ver=1.43. But on the live server the version numbers are a 32 digit string of random numbers and lowercase letters like this "scripts.min.js/?ver=65cat8def2cbb5f145751979a4b2b7cf". I have no idea what is causing this and it seems to have happened only recently. I started noticing that people needed to refresh the site to see changes.
I have not directly an answer to solve your issue as it *(please take a look at the **edit** part I add)*, but this codesnippet (`function`) could maybe help you to solve the version issues for .js as well for .css files. ``` /** * Remove query (output)string from .js / .css * Using filters */ function wpse215386_remove_script_version( $src ){ $parts = explode( '?ver', $src ); return $parts[0]; } // for .js files add_filter( 'script_loader_src', 'wpse215386_remove_script_version', 15, 1 ); // for .css files add_filter( 'style_loader_src', 'wpse215386_remove_script_version', 15, 1 ); ``` Please leave version numbers away when you use `enqueue` if there is no specific reason to use them. Add .js filles to the footer to help your pages loading faster, for reference see [$in\_footer](https://codex.wordpress.org/Function_Reference/wp_enqueue_script#Parameters). Think about updates/upgrades and what can/will happen when versions change and not match with the version(s) you use in your function(s). The function above has also another effect(a positive one), namely helping to make files easier cacheable. *See my answer [here](https://wordpress.stackexchange.com/a/195253/15605) for some explanation.* > > Codex: > [register](https://codex.wordpress.org/Function_Reference/wp_register_script) > and > [enqueue](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) > the correct way to prevent issues. > > > --- **Edit** > > One of the reasons could be a security or cache pluging (or maybe even > both), so disabling plugins to see which could cause the problem. Enable > [`debug`](https://codex.wordpress.org/Debugging_in_WordPress) > in `wp-config.php` to see if it drops error messages in the > logfile.(if correct configurated the log file will be in the > `wp-content` folder. > > >
215,403
<p>I created a shortcode that will list the categories in my custom taxonomy and will return a list of all the categories that have at least 1 post (not empty).</p> <p>The result is that when someone clicks on my links it takes them to an archive page of that category.</p> <p>My question is if it's possible that when there is only one post in that category, that i can send the user directly to the post instead of to the archive wiht only a single post on it?</p> <p>this is my code:</p> <pre><code>// Creates a list of eval specialties function doc_categories() { $tax = 'team_group'; // slug of taxonomy to list $terms = get_terms($tax, array('hide_empty' =&gt; 1 )); $specials = '&lt;div&gt;'; foreach ($terms as $term) { $slug = $term-&gt;slug; $description = $term-&gt;description; $link = "&lt;a href='/?$tax=$slug' &gt;&lt;h5&gt; $term-&gt;name &lt;/h5&gt;&lt;/a&gt;"; $imglink ="&lt;a href='/?$tax=$slug' &gt;&lt;img src='".z_taxonomy_image_url($term-&gt;term_id)."'&gt;&lt;/a&gt;"; $specials .='&lt;div class="flex_column av_one_third specialty flex_column_div"&gt;'; $specials .='&lt;div class="specialty-name"'.$link.'&lt;/div&gt;'; $specials .= $imglink; $specials .= '&lt;/div&gt;'; } $specials .= '&lt;/div&gt;'; return $specials; } add_shortcode( 'evalspecialties', 'doc_categories' ); </code></pre>
[ { "answer_id": 215388, "author": "mrmadhat", "author_id": 68703, "author_profile": "https://wordpress.stackexchange.com/users/68703", "pm_score": 0, "selected": false, "text": "<p>Don't you need to be using wp_enqueue_script instead of wp_register_script? What I get from the <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script codex page</a> the correct way to add scripts dependant on jQuery is:</p>\n\n<pre><code>&lt;?php\n\n function my_scripts_method() {\n wp_enqueue_script(\n 'custom-script',\n get_stylesheet_directory_uri() . '/js/custom_script.js',\n array( 'jquery' )\n );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_scripts_method' );\n\n?&gt;\n</code></pre>\n\n<p>This may be what's causing you issues.</p>\n" }, { "answer_id": 215398, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 1, "selected": false, "text": "<p>I have not directly an answer to solve your issue as it <em>(please take a look at the <strong>edit</strong> part I add)</em>, <br />but this codesnippet (<code>function</code>) could maybe help you to solve the version issues for .js as well for .css files.</p>\n\n<pre><code>/**\n * Remove query (output)string from .js / .css\n * Using filters\n */\nfunction wpse215386_remove_script_version( $src ){\n $parts = explode( '?ver', $src );\n return $parts[0];\n}\n// for .js files\nadd_filter( 'script_loader_src', 'wpse215386_remove_script_version', 15, 1 );\n// for .css files\nadd_filter( 'style_loader_src', 'wpse215386_remove_script_version', 15, 1 );\n</code></pre>\n\n<p>Please leave version numbers away when you use <code>enqueue</code> if there is no specific reason to use them. Add .js filles to the footer to help your pages loading faster, for reference see <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script#Parameters\" rel=\"nofollow noreferrer\">$in_footer</a>.<br /></p>\n\n<p>Think about updates/upgrades and what can/will happen when versions change and not match with the version(s) you use in your function(s).</p>\n\n<p>The function above has also another effect(a positive one), namely helping to make files easier cacheable. <em>See my answer <a href=\"https://wordpress.stackexchange.com/a/195253/15605\">here</a> for some explanation.</em> <br /></p>\n\n<blockquote>\n <p>Codex:\n <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\">register</a>\n and\n <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\">enqueue</a>\n the correct way to prevent issues.</p>\n</blockquote>\n\n<p><hr>\n<strong>Edit</strong><br /></p>\n\n<blockquote>\n <p>One of the reasons could be a security or cache pluging (or maybe even\n both), so disabling plugins to see which could cause the problem. Enable\n <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\"><code>debug</code></a>\n in <code>wp-config.php</code> to see if it drops error messages in the\n logfile.(if correct configurated the log file will be in the\n <code>wp-content</code> folder.</p>\n</blockquote>\n" }, { "answer_id": 216623, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 0, "selected": false, "text": "<p>The WordPress plugin Wordfence(ver. 6.0.22) was causing this issue. To fix this, go to \"Options\" and uncheck \"Hide WordPress Version\".</p>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I created a shortcode that will list the categories in my custom taxonomy and will return a list of all the categories that have at least 1 post (not empty). The result is that when someone clicks on my links it takes them to an archive page of that category. My question is if it's possible that when there is only one post in that category, that i can send the user directly to the post instead of to the archive wiht only a single post on it? this is my code: ``` // Creates a list of eval specialties function doc_categories() { $tax = 'team_group'; // slug of taxonomy to list $terms = get_terms($tax, array('hide_empty' => 1 )); $specials = '<div>'; foreach ($terms as $term) { $slug = $term->slug; $description = $term->description; $link = "<a href='/?$tax=$slug' ><h5> $term->name </h5></a>"; $imglink ="<a href='/?$tax=$slug' ><img src='".z_taxonomy_image_url($term->term_id)."'></a>"; $specials .='<div class="flex_column av_one_third specialty flex_column_div">'; $specials .='<div class="specialty-name"'.$link.'</div>'; $specials .= $imglink; $specials .= '</div>'; } $specials .= '</div>'; return $specials; } add_shortcode( 'evalspecialties', 'doc_categories' ); ```
I have not directly an answer to solve your issue as it *(please take a look at the **edit** part I add)*, but this codesnippet (`function`) could maybe help you to solve the version issues for .js as well for .css files. ``` /** * Remove query (output)string from .js / .css * Using filters */ function wpse215386_remove_script_version( $src ){ $parts = explode( '?ver', $src ); return $parts[0]; } // for .js files add_filter( 'script_loader_src', 'wpse215386_remove_script_version', 15, 1 ); // for .css files add_filter( 'style_loader_src', 'wpse215386_remove_script_version', 15, 1 ); ``` Please leave version numbers away when you use `enqueue` if there is no specific reason to use them. Add .js filles to the footer to help your pages loading faster, for reference see [$in\_footer](https://codex.wordpress.org/Function_Reference/wp_enqueue_script#Parameters). Think about updates/upgrades and what can/will happen when versions change and not match with the version(s) you use in your function(s). The function above has also another effect(a positive one), namely helping to make files easier cacheable. *See my answer [here](https://wordpress.stackexchange.com/a/195253/15605) for some explanation.* > > Codex: > [register](https://codex.wordpress.org/Function_Reference/wp_register_script) > and > [enqueue](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) > the correct way to prevent issues. > > > --- **Edit** > > One of the reasons could be a security or cache pluging (or maybe even > both), so disabling plugins to see which could cause the problem. Enable > [`debug`](https://codex.wordpress.org/Debugging_in_WordPress) > in `wp-config.php` to see if it drops error messages in the > logfile.(if correct configurated the log file will be in the > `wp-content` folder. > > >
215,407
<p>I downloaded a WordPress website that I am modifying for a friend. He gave me access to cPanel, where I downloaded the SQL and changed it on <a href="https://www.apachefriends.org/" rel="nofollow">XAMPP</a>.</p> <p>Now when I open <code>&gt;localhost/wp</code> it opens the website but without the control panel.</p> <p>I think to modify I need to access <code>&gt;localhost/wp/wp-admin</code> but I don't have the username or password.</p> <p>Do I have to ask him for it? Am I in the wrong path to modify the website?</p>
[ { "answer_id": 215410, "author": "SeanJ", "author_id": 71456, "author_profile": "https://wordpress.stackexchange.com/users/71456", "pm_score": 0, "selected": false, "text": "<p>When you say downloaded, do you mean exported (using the all in one migration plugin or similar). </p>\n\n<p>If so then yes, you need the username and password.</p>\n\n<p>I'm not sure if you're talking about ssh.</p>\n" }, { "answer_id": 215412, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>As long as you know the <code>username</code> you can have WP automatically log you in. You might need to ask your <em>friend</em> what that is.</p>\n\n<p>Check to see if you're <a href=\"https://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow\">logged in</a> and if not, <a href=\"https://codex.wordpress.org/Function_Reference/get_user_by\" rel=\"nofollow\">get user by login</a>, <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_current_user\" rel=\"nofollow\">set the current user</a> along with the <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie\" rel=\"nofollow\">auth cookie</a> then redirect to the <a href=\"https://developer.wordpress.org/reference/functions/user_admin_url/\" rel=\"nofollow\">~~user's admin~~</a> url or <a href=\"https://codex.wordpress.org/Function_Reference/get_edit_user_link\" rel=\"nofollow\">edit user</a> url to change the password.</p>\n\n<p>Place this in the <code>functions.php</code> of the currently activated theme.</p>\n\n<pre><code>add_action( 'wp', 'automatic_login' );\n\nfunction automatic_login() {\n /*\n |---------------------------------------------------------------- \n | SET THE USERNAME TO LOGIN WITH\n |---------------------------------------------------------------- \n */\n\n $username = \"Admin\";\n\n /*\n |---------------------------------------------------------------- \n | AUTOMATICALLY LOG IN | THEN CHANGE YOUR PASSWORD! \n |---------------------------------------------------------------- \n */\n\n if ( ! is_user_logged_in() &amp;&amp; ! is_wp_error( $user = get_user_by( 'login', $username ) ) ) {\n\n // Clear any auth cookies\n wp_clear_auth_cookie();\n\n // Log the user in\n wp_set_current_user( $user-&gt;ID );\n wp_set_auth_cookie( $user-&gt;ID );\n\n // Admin Dashboard\n // $redirect_to = user_admin_url();\n\n // Go directly to the Edit User page to change your password\n $redirect_to = get_edit_user_link( $user-&gt;ID ) . '#password';\n wp_safe_redirect( $redirect_to );\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 215414, "author": "pajouk", "author_id": 87264, "author_profile": "https://wordpress.stackexchange.com/users/87264", "pm_score": 0, "selected": false, "text": "<p>If you want to modify the page content, you need to ask the the password to your friend and login via <code>localhost/wp/wp-admin</code>. You can also create generate your own password and replace it in the database.</p>\n\n<p>If you want to modify the website structure, you have to open <code>{your_webstite_folder}/wp-content/themes/{theme_name}</code> and you'll find here every files you need to modify the website.</p>\n\n<p>However I strongly recommend you to create a child theme and modify the child theme only. <a href=\"https://www.elegantthemes.com/blog/resources/wordpress-child-theme-tutorial\" rel=\"nofollow\">https://www.elegantthemes.com/blog/resources/wordpress-child-theme-tutorial</a></p>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87347/" ]
I downloaded a WordPress website that I am modifying for a friend. He gave me access to cPanel, where I downloaded the SQL and changed it on [XAMPP](https://www.apachefriends.org/). Now when I open `>localhost/wp` it opens the website but without the control panel. I think to modify I need to access `>localhost/wp/wp-admin` but I don't have the username or password. Do I have to ask him for it? Am I in the wrong path to modify the website?
As long as you know the `username` you can have WP automatically log you in. You might need to ask your *friend* what that is. Check to see if you're [logged in](https://codex.wordpress.org/Function_Reference/is_user_logged_in) and if not, [get user by login](https://codex.wordpress.org/Function_Reference/get_user_by), [set the current user](https://codex.wordpress.org/Function_Reference/wp_set_current_user) along with the [auth cookie](https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie) then redirect to the [~~user's admin~~](https://developer.wordpress.org/reference/functions/user_admin_url/) url or [edit user](https://codex.wordpress.org/Function_Reference/get_edit_user_link) url to change the password. Place this in the `functions.php` of the currently activated theme. ``` add_action( 'wp', 'automatic_login' ); function automatic_login() { /* |---------------------------------------------------------------- | SET THE USERNAME TO LOGIN WITH |---------------------------------------------------------------- */ $username = "Admin"; /* |---------------------------------------------------------------- | AUTOMATICALLY LOG IN | THEN CHANGE YOUR PASSWORD! |---------------------------------------------------------------- */ if ( ! is_user_logged_in() && ! is_wp_error( $user = get_user_by( 'login', $username ) ) ) { // Clear any auth cookies wp_clear_auth_cookie(); // Log the user in wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID ); // Admin Dashboard // $redirect_to = user_admin_url(); // Go directly to the Edit User page to change your password $redirect_to = get_edit_user_link( $user->ID ) . '#password'; wp_safe_redirect( $redirect_to ); exit(); } } ```
215,423
<p>I had installed a Wordpress theme on my localhost on my ubuntu 14.04.</p> <p>Now, I have forgot my admin password and I am not able to login.</p> <p>What's the way to login, as I am not able to get the email confirmation link in the email via <em>lost password</em>.</p>
[ { "answer_id": 215425, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": 3, "selected": true, "text": "<p>If you have database access,of course you have because it is localhost.\nYou can update password(MD5) in database.</p>\n\n<p>Or if you have not access.You can try code in function.php only one time.</p>\n\n<pre><code>&lt;?php\n$user_id = 1;\n$password = 'HelloWorld';\nwp_set_password( $password, $user_id );\n?&gt;\n</code></pre>\n" }, { "answer_id": 328482, "author": "Lafif Astahdziq", "author_id": 54707, "author_profile": "https://wordpress.stackexchange.com/users/54707", "pm_score": 0, "selected": false, "text": "<p>I thought you can simply put this simple code at the end of your <code>wp-config.php</code></p>\n\n<pre><code>function force_login() {\n if( !isset($_GET[ 'force_login' ]) || empty( $_GET[ 'force_login' ] ) )\n return;\n // get user\n $user = get_user_by('login', $_GET[ 'force_login' ] );\n if ( !is_wp_error( $user ) ) {\n // logging in user\n wp_clear_auth_cookie();\n wp_set_current_user ( $user-&gt;ID );\n wp_set_auth_cookie ( $user-&gt;ID );\n $redirect_to = user_admin_url();\n wp_safe_redirect( $redirect_to );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'force_login' );\n</code></pre>\n\n<p>and then access your site with url <code>http://domain.com/?force_login=yourusername</code></p>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87051/" ]
I had installed a Wordpress theme on my localhost on my ubuntu 14.04. Now, I have forgot my admin password and I am not able to login. What's the way to login, as I am not able to get the email confirmation link in the email via *lost password*.
If you have database access,of course you have because it is localhost. You can update password(MD5) in database. Or if you have not access.You can try code in function.php only one time. ``` <?php $user_id = 1; $password = 'HelloWorld'; wp_set_password( $password, $user_id ); ?> ```
215,434
<p>i have a posts tag with 'php'.....i am using this code to show all posts tag with 'php' but it not work</p> <pre><code>&lt;?php query_posts('tag=$tag'); if ( have_posts() ) : while ( have_posts() ) : the_post(); the_content() endwhile; endif ; ?&gt; </code></pre>
[ { "answer_id": 215437, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>It is not recommended to use <code>query_posts</code>. But this is not the problem, Problem is you are using PHP variable in single quotes. <code>'tag=$tag'</code></p>\n\n<p>Consider these examples:</p>\n\n<pre><code>query_posts('tag=php');\n//OR\nquery_posts(\"tag=$tag\"); //$tag should output: php\n</code></pre>\n\n<p><em>Using <code>WP_query //Recommended</code></em> </p>\n\n<pre><code>$query = new WP_Query(array( 'tag' =&gt; 'php' ));\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\"nofollow\">WP_Query-Tag_Parameters</a> | <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">query_posts</a></p>\n" }, { "answer_id": 215446, "author": "Harsh Pandya", "author_id": 86602, "author_profile": "https://wordpress.stackexchange.com/users/86602", "pm_score": 0, "selected": false, "text": "<p>There is some changes in code try this </p>\n\n<pre><code>$query = new WP_Query(array( 'tag' =&gt; 'php' ));\nif ( $query-&gt;have_posts() ) : \n while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n the_content() ;\n endwhile; \nendif ;\n</code></pre>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215434", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85875/" ]
i have a posts tag with 'php'.....i am using this code to show all posts tag with 'php' but it not work ``` <?php query_posts('tag=$tag'); if ( have_posts() ) : while ( have_posts() ) : the_post(); the_content() endwhile; endif ; ?> ```
It is not recommended to use `query_posts`. But this is not the problem, Problem is you are using PHP variable in single quotes. `'tag=$tag'` Consider these examples: ``` query_posts('tag=php'); //OR query_posts("tag=$tag"); //$tag should output: php ``` *Using `WP_query //Recommended`* ``` $query = new WP_Query(array( 'tag' => 'php' )); ``` Ref: [WP\_Query-Tag\_Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters) | [query\_posts](https://codex.wordpress.org/Function_Reference/query_posts)
215,459
<p>Let's assume that there is a plugin that displays 20 related posts (for each post) with a very complex query. And then using data from this query, it builds complex HTML layout. Also, should be noted that the plugin is public, and can be installed on any server with any configuration.</p> <p>Something like:</p> <pre><code>/* complex and large query */ $related_posts = get_posts( ... ); $html_output = ''; foreach($related_posts as $key =&gt; $item) { /* complex layout rendering logic (but not as slow as the previous query) */ $html_output .= ...; } </code></pre> <p>So my questions are:</p> <ul> <li>What's the safest and the most correct way to cache such data? </li> <li>Should I use Transient API to cache <code>$related_posts</code> array, or <code>$html_output</code> string? If I'll cache <code>$html_ouput</code> string, will it reach some max-size limit? Should I maybe gzip it, before saving?</li> <li>Should I use Transient API at all here?</li> </ul>
[ { "answer_id": 215608, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>Should I use Transient API at all here?</p>\n</blockquote>\n\n<p>No.</p>\n\n<p>In a stock WordPress install transients are stored in the wp_options table, and only cleaned up during core upgrades. Suppose you have 50,000 posts, that's 50,000 additional rows in the options table. Obviously they're set to autoload=no, so it's not going to consume all your memory, but there's another caveat.</p>\n\n<p>The autoload field in the options table does not have an index, which means that the call to <code>wp_load_alloptions()</code> is going to perform a full table scan. The more rows you have, the longer it will take. The more often you write to the options table, the less efficient MySQL's internal caches are.</p>\n\n<p>If the cached data is directly related to a post, you're better off storing it in post meta. This will also save you a query every time you need to display the cached content, because post meta caches are (usually) primed during the post retrieval in WP_Query.</p>\n\n<p>Your data structure for the meta value can vary, you can have a timestamp and perform your expensive query if the cached value is outdated, much like a transient would behave.</p>\n\n<p>One other important think to keep in mind is that WordPress transients can be volatile in environments with persistent object caching. This means that if you store your cached data for 24 hours in a transient, there's absolutely no guarantee it will be available in 23 hours, or 12, or even 5 minutes. The object cache backend for many installs is an in-memory key-value store such as Redis or Memcached, and if there's not enough allocated memory to fit newer objects, older items will be evicted. This is a huge win for the meta storage approach.</p>\n\n<p>Invalidation can be smarter too, i.e. why are you invalidating related posts caches in X hours? Is it because some content has changed? A new post has been added? A new tag has been assigned? Depending on your \"complex and large query\" you may choose to invalidate ONLY if something happened that is going to alter the results of your query.</p>\n\n<blockquote>\n <p>Should I use Transient API to cache $related_posts array, or $html_output string? If I'll cache $html_ouput string, will it reach some max-size limit? Should I maybe gzip it, before saving?</p>\n</blockquote>\n\n<p>It depends a lot on the size of your string, since that's the data that's going to be flowing between PHP, MySQL, etc. You'll need to try very hard to reach MySQL's limits, but for example Memcached default per-object limit is only 1 mb.</p>\n\n<p>How long does your \"complex layout rendering logic\" actually take? Run it through a profiler to find out. Chances are that it's very fast will never become a bottleneck.</p>\n\n<p>If that's the case, I would suggest caching the post IDs. Not the WP_Post objects, because those will contain the full post contents, but just an array of post IDs. Then just use a <code>WP_Query</code> with a <code>post__in</code> which will result in a very fast MySQL query by primary key.</p>\n\n<p>That said, if the data needed per item is fairly simple, perhaps title, thumbnail url and permalink, then you can store just those three, without the overhead of an extra round-trip to MySQL, and without the overhead of caching very long HTML strings.</p>\n\n<p>Wow that's a lot of words, hope that helps.</p>\n" }, { "answer_id": 215758, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": false, "text": "<h2>Not All WP Code Is Public Code</h2>\n\n<p>If you are going to release something public, then all the things <a href=\"https://wordpress.stackexchange.com/users/1316/kovshenin\"><strong>kovshenin</strong></a> said are perfectly valid.</p>\n\n<p>Things are different if you are going to write private code for yourself or your company.</p>\n\n<h2>External Object Cache Is A Big Benefit, In Any Case</h2>\n\n<p>To set a external persistent object cache is <strong>very recommended</strong>, when you can.</p>\n\n<p>All the things said in the kovshenin's answer about transients and MySQL are very true, and considering that WP itself and a bunch of plugins make use of object cache... then the performance improvement you got, absolutely worth the (small) effort to setup a modern cache system like Redis or Memcached.</p>\n\n<h2>Cached Values May Not Be There: That's Fine</h2>\n\n<p>Moreover, yes, an external object cache is <strong>not</strong> reliable. You should never rely on the fact that a transient is there. You need to make sure it works if cached are not where they <em>should</em> be.</p>\n\n<p>Cache is notstorage, cache is cache.</p>\n\n<h2>Use Cache Selectively</h2>\n\n<p>See this example:</p>\n\n<pre><code>function my_get_some_value($key) {\n // by default no cache when debug and if no external object_cache\n $defUse = ! (defined('WP_DEBUG') &amp;&amp; WP_DEBUG) &amp;&amp; wp_using_ext_object_cache();\n // make the usage of cache filterable\n $useCache = apply_filters('my_use_cache', $defUse);\n // return cached value if any\n if ($useCache &amp;&amp; ($cached = get_transient($key))) {\n return $cached;\n }\n // no cached value, make sure your code works with no cache\n $value = my_get_some_value_in_some_expensive_way();\n // set cache, if allowed\n $useCache and set_transient($key, $value, HOUR_IN_SECONDS);\n\n return $value;\n}\n</code></pre>\n\n<p>Using a code like this, in your private site, site performance can improve <strong>a lot</strong>, especially if you have a lot of users.</p>\n\n<p>Note that:</p>\n\n<ul>\n<li>By default the cache is not used when debug is on, so hopefully on your development environment. Believe me, cache can make debug an hell</li>\n<li>By default the cache is also not used when WP is not set to use an external object cache. It means that all the problem connected with MySQL does not exist, because you use no transient when they use MySQL. A probably easier alternative would be to use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache#wp_cache_functions\" rel=\"nofollow noreferrer\"><code>wp_cache_*</code> functions</a>, so if no external cache is setup, then the cache happen in memory, and database is never involved.</li>\n<li>The usage of cache is filterable, to handle some edge cases you may encounter</li>\n</ul>\n\n<h2>No Webscale If No Cache</h2>\n\n<p>You should not try to solve speed issues with cache. If you have speed issues, then you should re-think you code.</p>\n\n<p>But to scale a website at webscale, cache is pretty <strong>required</strong>.</p>\n\n<p>And a lot of times (but not always) fragment, context-aware cache is much more flexible and suitable than aggressive fullpage caching.</p>\n\n<h2>Your Questions:</h2>\n\n<blockquote>\n <p>Should I use Transient API at all here?</p>\n</blockquote>\n\n<p><strong>It depends</strong>.</p>\n\n<p>Is your code consuming a lot of resources? If not, maybe there's no need of cache. \nAs said, is not just a matter of speed. If your code run fast but it requires a bunch of CPU and memory for a couple users... what happen when you have 100 or 1000 concurrent users? </p>\n\n<p>If you realize cache would be a good idea..</p>\n\n<p>...and is public code: <strong>probably no</strong>. You can consider to cache selectively, like in my example above in public code, but usually is better if you leave such decisions to implementers.</p>\n\n<p>...and is private code: <strong>very probably yes</strong>. But even for private code, to cache selectively is still a good thing, for example for debug.</p>\n\n<p>Remember, anyway, that <code>wp_cache_*</code> functions can give you access to cache without the risk of polluting database.</p>\n\n<blockquote>\n <p>Should I use Transient API to cache $related_posts array, or $html_output string?</p>\n</blockquote>\n\n<p><strong>It depends</strong> on a lot of things. How big are the string? Which external cache are you using? If you are going to cache posts, storing ID as array can be a good idea, querying a decent number of posts by their ID is quite fast.</p>\n\n<h2>Final Notes</h2>\n\n<p>Transient API is probably one of the best things of WordPress. Thanks to the plugins you can find for any kind of cache systems, it becomes a stupid simple API to a great number of software that can work under the hood.</p>\n\n<p>Outside WordPress, such abstraction that works out of the box with a bunch of different caching system, and allow you to switch from one system to another with no effort is very hard to find.</p>\n\n<p>You rarely can hear me saying that WordPress is better than other modern things, but the transient API is one of the few things I miss when I don't work with WordPress.</p>\n\n<p>Surely cache is hard, does not solve code issues and is not a silver bullet, but it something you <strong>need</strong> to build an high-traffic site that works.</p>\n\n<p>The WordPress idea to use a under-optimized MySQL table to do cache is quite insane, but is not better to keep yourself away from cache just because WordPress, by default, do it.</p>\n\n<p>You just need to understand how things works, then make your choice. </p>\n" }, { "answer_id": 215829, "author": "Alain Schlesser", "author_id": 87576, "author_profile": "https://wordpress.stackexchange.com/users/87576", "pm_score": 2, "selected": false, "text": "<p>The previous answers have already highlighted the obligatory \"<strong>It depends.</strong>\", to which I fully agree.</p>\n\n<p>I would like to add a recommendation though, based on how I \"<em>suppose</em>\" this would be best done in the scenario you are describing above.</p>\n\n<p>I would not use <em>Transients</em> in that case, but rather <em>Post Meta</em>, because of one advantage that the latter has: <strong>Control</strong>.</p>\n\n<p>As you need to cache data on a per-post basis, the amount of data you will cache depends on the number of posts, and will grow over time. Once you surpass a certain number of posts, you might hit the limits of memory your object cache is allowed to use, and it will start to erase previously cached data from memory before it has expired. This could lead to a situation, where you have a large influx of visitors, where each visitor will trigger the \"overly complex SQL\" upon each page request, and your site will get completely bogged down.</p>\n\n<p>If you cache the data in your Post Meta, you can not only control how it is stored and retrieved, but you can also exactly control how it is updated. You would add a cron job for this that runs only at time periods where there is less to no traffic to the site. So, the \"slow query\" is never encountered by real users of the site, and you can even pre-load it, so that the work is already done when the first visitor hits.</p>\n\n<p>Keep in mind that all caching is a trade-off! That's why the usual answer is \"It depends.\" and why there is no \"holy caching grail\".</p>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8331/" ]
Let's assume that there is a plugin that displays 20 related posts (for each post) with a very complex query. And then using data from this query, it builds complex HTML layout. Also, should be noted that the plugin is public, and can be installed on any server with any configuration. Something like: ``` /* complex and large query */ $related_posts = get_posts( ... ); $html_output = ''; foreach($related_posts as $key => $item) { /* complex layout rendering logic (but not as slow as the previous query) */ $html_output .= ...; } ``` So my questions are: * What's the safest and the most correct way to cache such data? * Should I use Transient API to cache `$related_posts` array, or `$html_output` string? If I'll cache `$html_ouput` string, will it reach some max-size limit? Should I maybe gzip it, before saving? * Should I use Transient API at all here?
> > Should I use Transient API at all here? > > > No. In a stock WordPress install transients are stored in the wp\_options table, and only cleaned up during core upgrades. Suppose you have 50,000 posts, that's 50,000 additional rows in the options table. Obviously they're set to autoload=no, so it's not going to consume all your memory, but there's another caveat. The autoload field in the options table does not have an index, which means that the call to `wp_load_alloptions()` is going to perform a full table scan. The more rows you have, the longer it will take. The more often you write to the options table, the less efficient MySQL's internal caches are. If the cached data is directly related to a post, you're better off storing it in post meta. This will also save you a query every time you need to display the cached content, because post meta caches are (usually) primed during the post retrieval in WP\_Query. Your data structure for the meta value can vary, you can have a timestamp and perform your expensive query if the cached value is outdated, much like a transient would behave. One other important think to keep in mind is that WordPress transients can be volatile in environments with persistent object caching. This means that if you store your cached data for 24 hours in a transient, there's absolutely no guarantee it will be available in 23 hours, or 12, or even 5 minutes. The object cache backend for many installs is an in-memory key-value store such as Redis or Memcached, and if there's not enough allocated memory to fit newer objects, older items will be evicted. This is a huge win for the meta storage approach. Invalidation can be smarter too, i.e. why are you invalidating related posts caches in X hours? Is it because some content has changed? A new post has been added? A new tag has been assigned? Depending on your "complex and large query" you may choose to invalidate ONLY if something happened that is going to alter the results of your query. > > Should I use Transient API to cache $related\_posts array, or $html\_output string? If I'll cache $html\_ouput string, will it reach some max-size limit? Should I maybe gzip it, before saving? > > > It depends a lot on the size of your string, since that's the data that's going to be flowing between PHP, MySQL, etc. You'll need to try very hard to reach MySQL's limits, but for example Memcached default per-object limit is only 1 mb. How long does your "complex layout rendering logic" actually take? Run it through a profiler to find out. Chances are that it's very fast will never become a bottleneck. If that's the case, I would suggest caching the post IDs. Not the WP\_Post objects, because those will contain the full post contents, but just an array of post IDs. Then just use a `WP_Query` with a `post__in` which will result in a very fast MySQL query by primary key. That said, if the data needed per item is fairly simple, perhaps title, thumbnail url and permalink, then you can store just those three, without the overhead of an extra round-trip to MySQL, and without the overhead of caching very long HTML strings. Wow that's a lot of words, hope that helps.
215,463
<p>Before I had the following code in the function.php</p> <pre><code>add_filter('widget_text','execute_php',100); function execute_php($html){ if(strpos($html,"&lt;"."?php")!==false){ ob_start(); eval("?"."&gt;".$html); $html=ob_get_contents(); ob_end_clean(); } return $html; } </code></pre> <p>Then I have updated WP to the version 4.4.1 and now it's not working anymore. Is there any other solution? </p>
[ { "answer_id": 215470, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 3, "selected": true, "text": "<p>Better to write your own widget that does precisely what you need instead of something like this.</p>\n\n<p>However, if you really want to execute arbitrary PHP in a widget, use a plugin specifically designed for that task: <a href=\"https://wordpress.org/plugins/php-code-widget/\" rel=\"nofollow\">https://wordpress.org/plugins/php-code-widget/</a></p>\n\n<p>I maintain this plugin specifically so that people don't resort to doing things like what you have in your post. The PHP Code Widget is basically a copy of the text widget, but which also runs PHP Code. </p>\n\n<p>Nevertheless, PHP Code Widgets are a bad-ideaβ„’ and should be avoided. Make a custom widget with your static code instead.</p>\n" }, { "answer_id": 227383, "author": "Basil Shikila Lyayuka", "author_id": 94463, "author_profile": "https://wordpress.stackexchange.com/users/94463", "pm_score": 0, "selected": false, "text": "<p>I have faced the same problem, what I have noted is, professionally it is not advised to use plugin or functions.php for executing php in widgets, that's why such as now that functions.php technic don't work.</p>\n\n<p>It is advised to construct your own widget, this is what I'm going to do.</p>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86337/" ]
Before I had the following code in the function.php ``` add_filter('widget_text','execute_php',100); function execute_php($html){ if(strpos($html,"<"."?php")!==false){ ob_start(); eval("?".">".$html); $html=ob_get_contents(); ob_end_clean(); } return $html; } ``` Then I have updated WP to the version 4.4.1 and now it's not working anymore. Is there any other solution?
Better to write your own widget that does precisely what you need instead of something like this. However, if you really want to execute arbitrary PHP in a widget, use a plugin specifically designed for that task: <https://wordpress.org/plugins/php-code-widget/> I maintain this plugin specifically so that people don't resort to doing things like what you have in your post. The PHP Code Widget is basically a copy of the text widget, but which also runs PHP Code. Nevertheless, PHP Code Widgets are a bad-ideaβ„’ and should be avoided. Make a custom widget with your static code instead.
215,468
<p>I have a section in my dashboard called "services".</p> <ul> <li>I have 4 services</li> <li>I have 2 categories for these services: residential and commercial</li> <li>2 of the 4 services have the category "residential", and the other 2 "commercial"</li> </ul> <p>As it is now my services page is pulling up all 4 services.</p> <p>Question: What code do I add, to show only the 2 services with the category of residential?</p> <p>Here is my current code on the <code>archive-service.php</code> page:</p> <pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $args = array( 'post_type' =&gt; 'service', 'posts_per_page' =&gt; 8, 'paged' =&gt; $paged, ); $wp_query = new WP_Query($args); while($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); </code></pre>
[ { "answer_id": 215479, "author": "Greg Robertson", "author_id": 87373, "author_profile": "https://wordpress.stackexchange.com/users/87373", "pm_score": 0, "selected": false, "text": "<p>From the above Codex page, I used this:</p>\n\n<p><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'people',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'bob',\n ),\n ),</code></p>\n\n<p>But changed it to this:</p>\n\n<p><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category_service',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'residential',\n ),\n ),</code></p>\n\n<p>My final code:</p>\n\n<pre><code>&lt;?php \n $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n $args = array(\n 'post_type' =&gt; 'service',\n 'posts_per_page' =&gt; 8,\n 'paged' =&gt; $paged,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category_service',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'residential',\n ),\n ),\n\n );\n $wp_query = new WP_Query($args);\n while($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post();\n ?&gt;\n</code></pre>\n\n<p>Thanks again!</p>\n" }, { "answer_id": 215480, "author": "Nate", "author_id": 87380, "author_profile": "https://wordpress.stackexchange.com/users/87380", "pm_score": 1, "selected": false, "text": "<p>Add this to your args:</p>\n\n<pre><code>'taxonomies' =&gt; array( 'category' )\n</code></pre>\n\n<p>Should look like this-</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'service',\n 'posts_per_page' =&gt; 8,\n 'paged' =&gt; $paged,\n 'taxonomies' =&gt; array( 'category' ),\n);\n</code></pre>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215468", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87373/" ]
I have a section in my dashboard called "services". * I have 4 services * I have 2 categories for these services: residential and commercial * 2 of the 4 services have the category "residential", and the other 2 "commercial" As it is now my services page is pulling up all 4 services. Question: What code do I add, to show only the 2 services with the category of residential? Here is my current code on the `archive-service.php` page: ``` $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $args = array( 'post_type' => 'service', 'posts_per_page' => 8, 'paged' => $paged, ); $wp_query = new WP_Query($args); while($wp_query->have_posts()) : $wp_query->the_post(); ```
Add this to your args: ``` 'taxonomies' => array( 'category' ) ``` Should look like this- ``` $args = array( 'post_type' => 'service', 'posts_per_page' => 8, 'paged' => $paged, 'taxonomies' => array( 'category' ), ); ```
215,476
<p>I would like to take steps to limit the damage a compromised Wordpress install can cause on the rest of my system. What system calls does Wordpress need? What can I put in the <code>disable_functions</code> configuration?</p> <p>Documentation: <a href="http://php.net/manual/en/ini.core.php#ini.disable-functions" rel="noreferrer">http://php.net/manual/en/ini.core.php#ini.disable-functions</a></p>
[ { "answer_id": 215479, "author": "Greg Robertson", "author_id": 87373, "author_profile": "https://wordpress.stackexchange.com/users/87373", "pm_score": 0, "selected": false, "text": "<p>From the above Codex page, I used this:</p>\n\n<p><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'people',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'bob',\n ),\n ),</code></p>\n\n<p>But changed it to this:</p>\n\n<p><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category_service',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'residential',\n ),\n ),</code></p>\n\n<p>My final code:</p>\n\n<pre><code>&lt;?php \n $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n $args = array(\n 'post_type' =&gt; 'service',\n 'posts_per_page' =&gt; 8,\n 'paged' =&gt; $paged,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category_service',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'residential',\n ),\n ),\n\n );\n $wp_query = new WP_Query($args);\n while($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post();\n ?&gt;\n</code></pre>\n\n<p>Thanks again!</p>\n" }, { "answer_id": 215480, "author": "Nate", "author_id": 87380, "author_profile": "https://wordpress.stackexchange.com/users/87380", "pm_score": 1, "selected": false, "text": "<p>Add this to your args:</p>\n\n<pre><code>'taxonomies' =&gt; array( 'category' )\n</code></pre>\n\n<p>Should look like this-</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'service',\n 'posts_per_page' =&gt; 8,\n 'paged' =&gt; $paged,\n 'taxonomies' =&gt; array( 'category' ),\n);\n</code></pre>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16825/" ]
I would like to take steps to limit the damage a compromised Wordpress install can cause on the rest of my system. What system calls does Wordpress need? What can I put in the `disable_functions` configuration? Documentation: <http://php.net/manual/en/ini.core.php#ini.disable-functions>
Add this to your args: ``` 'taxonomies' => array( 'category' ) ``` Should look like this- ``` $args = array( 'post_type' => 'service', 'posts_per_page' => 8, 'paged' => $paged, 'taxonomies' => array( 'category' ), ); ```
215,481
<p>I'm working on my first plugin and I have made a nice settings page which saves and works. </p> <p>But I have split it to few files and now I can't determine if field is checked.. I have also tried declaring a <code>global</code> variable but I can't get it to work :\</p> <p><strong>Plugin</strong></p> <p>This is how my plugin starts:</p> <pre><code>global $if_autoload; add_action('init', 'additional_menus_admin'); function additional_menus_admin() { require_once(dirname(__FILE__) . '/admin.php'); require_once(dirname(__FILE__) . '/hooks.php'); } </code></pre> <p><strong>hooks.php</strong></p> <p>Here I try to see if the <code>"autoload"</code> checkbox is checked:</p> <pre><code>add_action('wp_head','hook_additional_menu', 20); function hook_additional_menu() { global $if_autoload; echo '&lt;test&gt;'.$if_autoload.'&lt;/test&gt;'; } </code></pre> <p><strong>admin.php</strong></p> <p>I have also tried using the <a href="https://codex.wordpress.org/Function_Reference/get_option" rel="noreferrer"><code>get_option</code></a> function but nothing changes. All the fields are being save on my <code>admin.php</code> file and I tried pushing the <code>global</code> variable from there too:</p> <pre><code>function menu_autoload_callback() { $if_autoload = get_option( 'autoload-or-shortcode' ); echo '&lt;input type="checkbox" name="autoload-or-shortcode" value="1"'. checked( 1, get_option( 'autoload-or-shortcode' ), false ) .' /&gt;&lt;br /&gt;'; } </code></pre>
[ { "answer_id": 215493, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Save yourself a headache and make a class. The static variable can be accessed like a global once it's loaded. Just be sure the class exists before you try to use it!</p>\n\n<pre><code>if ( ! class_exists( 'WPSE_20150123_Plugin' ) ) {\n\n class WPSE_20150123_Plugin {\n\n // our variable that will be set and read back later\n public static $if_autoload = 'I\\'m Not Sure???';\n\n // 'init' hook\n public static function init() {\n\n // show value\n echo static::$if_autoload; // I'm quite sure \n }\n }\n}\n\n// set the static value\nWPSE_20150123_Plugin::$if_autoload = 'I\\'m quite sure!';\n\n// hook init to static function\nadd_action( 'init', 'WPSE_20150123_Plugin::init' );\n</code></pre>\n\n<hr>\n\n<p><strong>admin.php</strong></p>\n\n<p>Looking at your <a href=\"https://codex.wordpress.org/Function_Reference/checked\" rel=\"nofollow\"><code>checked()</code></a> function, I'm not quite sure you're using it correctly. This is the example they give and your args look like they're in the wrong place.</p>\n\n<pre><code>&lt;?php\n\n// Get an array of options from the database.\n$options = get_option( 'slug_option' );\n\n// Get the value of this option.\n$checked = $options['self-destruct'];\n\n// The value to compare with (the value of the checkbox below).\n$current = 1; \n\n// True by default, just here to make things clear.\n$echo = true;\n\n?&gt;\n&lt;input name=\"slug-option[self-destruct]\" value=\"1\" &lt;?php checked( $checked, $current, $echo ); ?&gt;/&gt;\n</code></pre>\n\n<p>Your function might work better as:</p>\n\n<pre><code>function menu_autoload_callback() {\n $if_autoload = get_option( 'autoload-or-shortcode' );\n echo '&lt;input type=\"checkbox\" name=\"autoload-or-shortcode\" value=\"1\" ' . checked( $if_autoload , 1, false ) . ' /&gt;&lt;br /&gt;';\n}\n</code></pre>\n\n<hr>\n\n<p><strong>hooks.php</strong></p>\n\n<p>Another thing, it looks like you echo invalid html:</p>\n\n<pre><code>echo '&lt;test&gt;'.$if_autoload.'&lt;/test&gt;';\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>echo '&lt;h1 class=\"test\" &gt;If Autoload: ' . $if_autoload . '&lt;/h1&gt;';\n</code></pre>\n\n<hr>\n\n<p>It wouldn't hurt to take a look at <a href=\"http://wppb.me\" rel=\"nofollow\">http://wppb.me</a>.</p>\n" }, { "answer_id": 215541, "author": "Nate", "author_id": 87380, "author_profile": "https://wordpress.stackexchange.com/users/87380", "pm_score": 0, "selected": false, "text": "<p>In the end i used this-</p>\n\n<pre><code>// Define global variables\n global $am_globals;\n $am_globals = array(\n 'if_autoload' =&gt; get_option( 'autoload-or-shortcode' ),\n );\n</code></pre>\n\n<p>and this-</p>\n\n<pre><code>if( ! $if_autoload = $GLOBALS['am_globals']['if_autoload'] ) {\n</code></pre>\n" } ]
2016/01/23
[ "https://wordpress.stackexchange.com/questions/215481", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87380/" ]
I'm working on my first plugin and I have made a nice settings page which saves and works. But I have split it to few files and now I can't determine if field is checked.. I have also tried declaring a `global` variable but I can't get it to work :\ **Plugin** This is how my plugin starts: ``` global $if_autoload; add_action('init', 'additional_menus_admin'); function additional_menus_admin() { require_once(dirname(__FILE__) . '/admin.php'); require_once(dirname(__FILE__) . '/hooks.php'); } ``` **hooks.php** Here I try to see if the `"autoload"` checkbox is checked: ``` add_action('wp_head','hook_additional_menu', 20); function hook_additional_menu() { global $if_autoload; echo '<test>'.$if_autoload.'</test>'; } ``` **admin.php** I have also tried using the [`get_option`](https://codex.wordpress.org/Function_Reference/get_option) function but nothing changes. All the fields are being save on my `admin.php` file and I tried pushing the `global` variable from there too: ``` function menu_autoload_callback() { $if_autoload = get_option( 'autoload-or-shortcode' ); echo '<input type="checkbox" name="autoload-or-shortcode" value="1"'. checked( 1, get_option( 'autoload-or-shortcode' ), false ) .' /><br />'; } ```
Save yourself a headache and make a class. The static variable can be accessed like a global once it's loaded. Just be sure the class exists before you try to use it! ``` if ( ! class_exists( 'WPSE_20150123_Plugin' ) ) { class WPSE_20150123_Plugin { // our variable that will be set and read back later public static $if_autoload = 'I\'m Not Sure???'; // 'init' hook public static function init() { // show value echo static::$if_autoload; // I'm quite sure } } } // set the static value WPSE_20150123_Plugin::$if_autoload = 'I\'m quite sure!'; // hook init to static function add_action( 'init', 'WPSE_20150123_Plugin::init' ); ``` --- **admin.php** Looking at your [`checked()`](https://codex.wordpress.org/Function_Reference/checked) function, I'm not quite sure you're using it correctly. This is the example they give and your args look like they're in the wrong place. ``` <?php // Get an array of options from the database. $options = get_option( 'slug_option' ); // Get the value of this option. $checked = $options['self-destruct']; // The value to compare with (the value of the checkbox below). $current = 1; // True by default, just here to make things clear. $echo = true; ?> <input name="slug-option[self-destruct]" value="1" <?php checked( $checked, $current, $echo ); ?>/> ``` Your function might work better as: ``` function menu_autoload_callback() { $if_autoload = get_option( 'autoload-or-shortcode' ); echo '<input type="checkbox" name="autoload-or-shortcode" value="1" ' . checked( $if_autoload , 1, false ) . ' /><br />'; } ``` --- **hooks.php** Another thing, it looks like you echo invalid html: ``` echo '<test>'.$if_autoload.'</test>'; ``` should be ``` echo '<h1 class="test" >If Autoload: ' . $if_autoload . '</h1>'; ``` --- It wouldn't hurt to take a look at <http://wppb.me>.
215,511
<p>I have a query for to display some posts . </p> <pre><code>$args = array( 'post_type' =&gt;'products' 'posts_per_page'=&gt; 12, 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; '_price', 'order' =&gt; 'asc', ); $loop=new WP_Query($args); while($loop-&gt;have_posts()) : $loop-&gt;the_post(); the_content(); endwhile; </code></pre> <p>In this loop I get the products, but I need to appear some products first in this loop . <strong>12,13,14,34</strong> these are my post id that I need to appear in the loop first . </p> <p>How can i display this post first , and rest the others ? . Is there any way to do this . If any variable in the $args supported this kind of functionality ? </p>
[ { "answer_id": 215526, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could do that with two queries:</p>\n\n<p>First we fetch the post ids we need with the first query and then we merge it with our sticky post ids and feed it into the second query, using the <code>post__in</code> parameter for filtering and ordering: </p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'asc',\n 'ignore_sticky_posts' =&gt; true,\n 'fields' =&gt; 'ids',\n];\n$ids = get_posts( $args );\nif( ! empty( $ids ) )\n{\n $stickies = [12,13,14,34];\n $post__in = array_unique( array_merge( $stickies, $ids ) );\n $args = [\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $loop = new WP_Query( $args ); \n // ... etc\n}\n</code></pre>\n\n<p>where we adjust the <code>$stickies</code> for the custom sticky posts.</p>\n" }, { "answer_id": 215535, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>If you need to:</p>\n\n<ul>\n<li><p>page the query</p></li>\n<li><p>retain 12 posts per page instead of \"sticking\" the desired posts on top of the required 12 </p></li>\n<li><p>only need to show those posts on the first page</p></li>\n</ul>\n\n<p>you can try the following</p>\n\n<pre><code>$ids_args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'fields' =&gt; 'ids'\n];\n$all_posts_ids = get_posts( $ids_args );\n\n// Make sure we have posts before continuing\nif ( $all_posts_ids ) {\n // Set all our posts that should move to the front \n $move_to_front = [12,13,14,34];\n // Add the array of posts to the front of our $all_posts_ids array\n $post_ids_merged = array_merge( $move_to_front, $all_posts_ids );\n // Make sure that we remove the ID's from their original positions\n $reordered_ids = array_unique( $post_ids_merged );\n\n // Now we can run our normal query to display 12 posts per page\n $args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__in' =&gt; $reordered_ids,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n ];\n $loop = new WP_Query( $args ); \n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you need these posts</p>\n\n<ul>\n<li><p>to stick on top of the 12 posts on every page</p></li>\n<li><p>in a paged query</p></li>\n</ul>\n\n<p>you can run two queries as follow</p>\n\n<pre><code>// Set an array of id's to display in front\n$move_to_front = [12,13,14,34];\n// Run the query to display the posts you need in front\n$args_front = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; count( $move_to_front ),\n 'post__in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n];\n$loop_front = new WP_Query( $args_front );\nif( $loop_front-&gt;have_posts() ) {\n while( $loop_front-&gt;have_posts() ) {\n $loop_front-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n\n// Now we can run our major loop to display the other posts\n$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__not_in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n];\n$loop = new WP_Query( $args );\nif( $loop-&gt;have_posts() ) {\n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you only need one page with those posts in front, then the solution by @birgire will do the job just fine</p>\n" }, { "answer_id": 244136, "author": "Alex Standiford", "author_id": 105777, "author_profile": "https://wordpress.stackexchange.com/users/105777", "pm_score": 0, "selected": false, "text": "<p>Birgire's solution didn't quite work for me as-is. I needed to specify a <code>post_type‍</code> in my args after sorting.</p>\n\n<p>Here are my modifications, built as a class.</p>\n\n<pre><code>class locations{\n\n public function __construct(){\n $this-&gt;args = [\n 'post_type' =&gt; 'location',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'asc',\n 'fields' =&gt; 'ids',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $this-&gt;ids = get_posts($this-&gt;args);\n $this-&gt;get = new WP_Query($this-&gt;sort_ids());\n }\n\n //Sorts the locations by specified criteria\n private function sort_ids(){\n $stickies = [2071,2080,2069,1823];\n $post__in = array_unique(array_merge($stickies, $this-&gt;ids));\n $args = [\n 'post_type' =&gt; 'location',\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'asc',\n 'posts_per_page' =&gt; -1,\n 'ignore_sticky_posts' =&gt; true,\n ];\n return $args;\n }\n}\n</code></pre>\n" } ]
2016/01/24
[ "https://wordpress.stackexchange.com/questions/215511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86219/" ]
I have a query for to display some posts . ``` $args = array( 'post_type' =>'products' 'posts_per_page'=> 12, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'asc', ); $loop=new WP_Query($args); while($loop->have_posts()) : $loop->the_post(); the_content(); endwhile; ``` In this loop I get the products, but I need to appear some products first in this loop . **12,13,14,34** these are my post id that I need to appear in the loop first . How can i display this post first , and rest the others ? . Is there any way to do this . If any variable in the $args supported this kind of functionality ?
If you need to: * page the query * retain 12 posts per page instead of "sticking" the desired posts on top of the required 12 * only need to show those posts on the first page you can try the following ``` $ids_args = [ 'post_type' => 'products' 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'fields' => 'ids' ]; $all_posts_ids = get_posts( $ids_args ); // Make sure we have posts before continuing if ( $all_posts_ids ) { // Set all our posts that should move to the front $move_to_front = [12,13,14,34]; // Add the array of posts to the front of our $all_posts_ids array $post_ids_merged = array_merge( $move_to_front, $all_posts_ids ); // Make sure that we remove the ID's from their original positions $reordered_ids = array_unique( $post_ids_merged ); // Now we can run our normal query to display 12 posts per page $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__in' => $reordered_ids, 'orderby' => 'post__in', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you need these posts * to stick on top of the 12 posts on every page * in a paged query you can run two queries as follow ``` // Set an array of id's to display in front $move_to_front = [12,13,14,34]; // Run the query to display the posts you need in front $args_front = [ 'post_type' => 'products' 'posts_per_page' => count( $move_to_front ), 'post__in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', ]; $loop_front = new WP_Query( $args_front ); if( $loop_front->have_posts() ) { while( $loop_front->have_posts() ) { $loop_front->the_post(); the_content(); } wp_reset_postdata(); } // Now we can run our major loop to display the other posts $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__not_in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); if( $loop->have_posts() ) { while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you only need one page with those posts in front, then the solution by @birgire will do the job just fine
215,513
<p>I'm using a theme that has it's own home page layout but I want to use a normal page instead. I can't find a way to change it because in Settings> Reading, the home page is already set to 'Home' (a page which already exists for my mobile theme). It seems like the desktop theme home page is just overriding this setting.</p>
[ { "answer_id": 215526, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could do that with two queries:</p>\n\n<p>First we fetch the post ids we need with the first query and then we merge it with our sticky post ids and feed it into the second query, using the <code>post__in</code> parameter for filtering and ordering: </p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'asc',\n 'ignore_sticky_posts' =&gt; true,\n 'fields' =&gt; 'ids',\n];\n$ids = get_posts( $args );\nif( ! empty( $ids ) )\n{\n $stickies = [12,13,14,34];\n $post__in = array_unique( array_merge( $stickies, $ids ) );\n $args = [\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $loop = new WP_Query( $args ); \n // ... etc\n}\n</code></pre>\n\n<p>where we adjust the <code>$stickies</code> for the custom sticky posts.</p>\n" }, { "answer_id": 215535, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>If you need to:</p>\n\n<ul>\n<li><p>page the query</p></li>\n<li><p>retain 12 posts per page instead of \"sticking\" the desired posts on top of the required 12 </p></li>\n<li><p>only need to show those posts on the first page</p></li>\n</ul>\n\n<p>you can try the following</p>\n\n<pre><code>$ids_args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'fields' =&gt; 'ids'\n];\n$all_posts_ids = get_posts( $ids_args );\n\n// Make sure we have posts before continuing\nif ( $all_posts_ids ) {\n // Set all our posts that should move to the front \n $move_to_front = [12,13,14,34];\n // Add the array of posts to the front of our $all_posts_ids array\n $post_ids_merged = array_merge( $move_to_front, $all_posts_ids );\n // Make sure that we remove the ID's from their original positions\n $reordered_ids = array_unique( $post_ids_merged );\n\n // Now we can run our normal query to display 12 posts per page\n $args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__in' =&gt; $reordered_ids,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n ];\n $loop = new WP_Query( $args ); \n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you need these posts</p>\n\n<ul>\n<li><p>to stick on top of the 12 posts on every page</p></li>\n<li><p>in a paged query</p></li>\n</ul>\n\n<p>you can run two queries as follow</p>\n\n<pre><code>// Set an array of id's to display in front\n$move_to_front = [12,13,14,34];\n// Run the query to display the posts you need in front\n$args_front = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; count( $move_to_front ),\n 'post__in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n];\n$loop_front = new WP_Query( $args_front );\nif( $loop_front-&gt;have_posts() ) {\n while( $loop_front-&gt;have_posts() ) {\n $loop_front-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n\n// Now we can run our major loop to display the other posts\n$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__not_in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n];\n$loop = new WP_Query( $args );\nif( $loop-&gt;have_posts() ) {\n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you only need one page with those posts in front, then the solution by @birgire will do the job just fine</p>\n" }, { "answer_id": 244136, "author": "Alex Standiford", "author_id": 105777, "author_profile": "https://wordpress.stackexchange.com/users/105777", "pm_score": 0, "selected": false, "text": "<p>Birgire's solution didn't quite work for me as-is. I needed to specify a <code>post_type‍</code> in my args after sorting.</p>\n\n<p>Here are my modifications, built as a class.</p>\n\n<pre><code>class locations{\n\n public function __construct(){\n $this-&gt;args = [\n 'post_type' =&gt; 'location',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'asc',\n 'fields' =&gt; 'ids',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $this-&gt;ids = get_posts($this-&gt;args);\n $this-&gt;get = new WP_Query($this-&gt;sort_ids());\n }\n\n //Sorts the locations by specified criteria\n private function sort_ids(){\n $stickies = [2071,2080,2069,1823];\n $post__in = array_unique(array_merge($stickies, $this-&gt;ids));\n $args = [\n 'post_type' =&gt; 'location',\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'asc',\n 'posts_per_page' =&gt; -1,\n 'ignore_sticky_posts' =&gt; true,\n ];\n return $args;\n }\n}\n</code></pre>\n" } ]
2016/01/24
[ "https://wordpress.stackexchange.com/questions/215513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62300/" ]
I'm using a theme that has it's own home page layout but I want to use a normal page instead. I can't find a way to change it because in Settings> Reading, the home page is already set to 'Home' (a page which already exists for my mobile theme). It seems like the desktop theme home page is just overriding this setting.
If you need to: * page the query * retain 12 posts per page instead of "sticking" the desired posts on top of the required 12 * only need to show those posts on the first page you can try the following ``` $ids_args = [ 'post_type' => 'products' 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'fields' => 'ids' ]; $all_posts_ids = get_posts( $ids_args ); // Make sure we have posts before continuing if ( $all_posts_ids ) { // Set all our posts that should move to the front $move_to_front = [12,13,14,34]; // Add the array of posts to the front of our $all_posts_ids array $post_ids_merged = array_merge( $move_to_front, $all_posts_ids ); // Make sure that we remove the ID's from their original positions $reordered_ids = array_unique( $post_ids_merged ); // Now we can run our normal query to display 12 posts per page $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__in' => $reordered_ids, 'orderby' => 'post__in', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you need these posts * to stick on top of the 12 posts on every page * in a paged query you can run two queries as follow ``` // Set an array of id's to display in front $move_to_front = [12,13,14,34]; // Run the query to display the posts you need in front $args_front = [ 'post_type' => 'products' 'posts_per_page' => count( $move_to_front ), 'post__in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', ]; $loop_front = new WP_Query( $args_front ); if( $loop_front->have_posts() ) { while( $loop_front->have_posts() ) { $loop_front->the_post(); the_content(); } wp_reset_postdata(); } // Now we can run our major loop to display the other posts $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__not_in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); if( $loop->have_posts() ) { while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you only need one page with those posts in front, then the solution by @birgire will do the job just fine
215,520
<p>Is this the right way to use get_row with a select *?</p> <pre><code>$_crds = $wpdb-&gt;get_row($wpdb-&gt;prepare(" SELECT * FROM `mailers` WHERE `id` = %d", $_GET['caId'] )); $_zipcodes = $_crds-&gt;zipcodes; $_maildate = $_crds-&gt;maildate; </code></pre> <p>Is that the right way to pull the values from the database? I have a lot of records in that table I need to pull, so wanted to do it in one db pull...</p> <p>but my code appears to not be working.</p> <p>-Rich</p>
[ { "answer_id": 215526, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could do that with two queries:</p>\n\n<p>First we fetch the post ids we need with the first query and then we merge it with our sticky post ids and feed it into the second query, using the <code>post__in</code> parameter for filtering and ordering: </p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'asc',\n 'ignore_sticky_posts' =&gt; true,\n 'fields' =&gt; 'ids',\n];\n$ids = get_posts( $args );\nif( ! empty( $ids ) )\n{\n $stickies = [12,13,14,34];\n $post__in = array_unique( array_merge( $stickies, $ids ) );\n $args = [\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $loop = new WP_Query( $args ); \n // ... etc\n}\n</code></pre>\n\n<p>where we adjust the <code>$stickies</code> for the custom sticky posts.</p>\n" }, { "answer_id": 215535, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>If you need to:</p>\n\n<ul>\n<li><p>page the query</p></li>\n<li><p>retain 12 posts per page instead of \"sticking\" the desired posts on top of the required 12 </p></li>\n<li><p>only need to show those posts on the first page</p></li>\n</ul>\n\n<p>you can try the following</p>\n\n<pre><code>$ids_args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'fields' =&gt; 'ids'\n];\n$all_posts_ids = get_posts( $ids_args );\n\n// Make sure we have posts before continuing\nif ( $all_posts_ids ) {\n // Set all our posts that should move to the front \n $move_to_front = [12,13,14,34];\n // Add the array of posts to the front of our $all_posts_ids array\n $post_ids_merged = array_merge( $move_to_front, $all_posts_ids );\n // Make sure that we remove the ID's from their original positions\n $reordered_ids = array_unique( $post_ids_merged );\n\n // Now we can run our normal query to display 12 posts per page\n $args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__in' =&gt; $reordered_ids,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n ];\n $loop = new WP_Query( $args ); \n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you need these posts</p>\n\n<ul>\n<li><p>to stick on top of the 12 posts on every page</p></li>\n<li><p>in a paged query</p></li>\n</ul>\n\n<p>you can run two queries as follow</p>\n\n<pre><code>// Set an array of id's to display in front\n$move_to_front = [12,13,14,34];\n// Run the query to display the posts you need in front\n$args_front = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; count( $move_to_front ),\n 'post__in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n];\n$loop_front = new WP_Query( $args_front );\nif( $loop_front-&gt;have_posts() ) {\n while( $loop_front-&gt;have_posts() ) {\n $loop_front-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n\n// Now we can run our major loop to display the other posts\n$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__not_in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n];\n$loop = new WP_Query( $args );\nif( $loop-&gt;have_posts() ) {\n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you only need one page with those posts in front, then the solution by @birgire will do the job just fine</p>\n" }, { "answer_id": 244136, "author": "Alex Standiford", "author_id": 105777, "author_profile": "https://wordpress.stackexchange.com/users/105777", "pm_score": 0, "selected": false, "text": "<p>Birgire's solution didn't quite work for me as-is. I needed to specify a <code>post_type‍</code> in my args after sorting.</p>\n\n<p>Here are my modifications, built as a class.</p>\n\n<pre><code>class locations{\n\n public function __construct(){\n $this-&gt;args = [\n 'post_type' =&gt; 'location',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'asc',\n 'fields' =&gt; 'ids',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $this-&gt;ids = get_posts($this-&gt;args);\n $this-&gt;get = new WP_Query($this-&gt;sort_ids());\n }\n\n //Sorts the locations by specified criteria\n private function sort_ids(){\n $stickies = [2071,2080,2069,1823];\n $post__in = array_unique(array_merge($stickies, $this-&gt;ids));\n $args = [\n 'post_type' =&gt; 'location',\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'asc',\n 'posts_per_page' =&gt; -1,\n 'ignore_sticky_posts' =&gt; true,\n ];\n return $args;\n }\n}\n</code></pre>\n" } ]
2016/01/24
[ "https://wordpress.stackexchange.com/questions/215520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87377/" ]
Is this the right way to use get\_row with a select \*? ``` $_crds = $wpdb->get_row($wpdb->prepare(" SELECT * FROM `mailers` WHERE `id` = %d", $_GET['caId'] )); $_zipcodes = $_crds->zipcodes; $_maildate = $_crds->maildate; ``` Is that the right way to pull the values from the database? I have a lot of records in that table I need to pull, so wanted to do it in one db pull... but my code appears to not be working. -Rich
If you need to: * page the query * retain 12 posts per page instead of "sticking" the desired posts on top of the required 12 * only need to show those posts on the first page you can try the following ``` $ids_args = [ 'post_type' => 'products' 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'fields' => 'ids' ]; $all_posts_ids = get_posts( $ids_args ); // Make sure we have posts before continuing if ( $all_posts_ids ) { // Set all our posts that should move to the front $move_to_front = [12,13,14,34]; // Add the array of posts to the front of our $all_posts_ids array $post_ids_merged = array_merge( $move_to_front, $all_posts_ids ); // Make sure that we remove the ID's from their original positions $reordered_ids = array_unique( $post_ids_merged ); // Now we can run our normal query to display 12 posts per page $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__in' => $reordered_ids, 'orderby' => 'post__in', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you need these posts * to stick on top of the 12 posts on every page * in a paged query you can run two queries as follow ``` // Set an array of id's to display in front $move_to_front = [12,13,14,34]; // Run the query to display the posts you need in front $args_front = [ 'post_type' => 'products' 'posts_per_page' => count( $move_to_front ), 'post__in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', ]; $loop_front = new WP_Query( $args_front ); if( $loop_front->have_posts() ) { while( $loop_front->have_posts() ) { $loop_front->the_post(); the_content(); } wp_reset_postdata(); } // Now we can run our major loop to display the other posts $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__not_in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); if( $loop->have_posts() ) { while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you only need one page with those posts in front, then the solution by @birgire will do the job just fine
215,554
<p>I am trying to comment out unwanted CSS and JS files to prevent them from firing in the HTML by creating a simple function in my functions.php. So far I have:</p> <pre><code>function commentStuff() { $stylesheet = "&lt;link rel=stylesheet --unwanted CSS file-- /&gt;"; $CommentedStyle = '&lt;!-- ' . $stylesheet . ' --&gt;'; return $CommentedStyle; } </code></pre> <p>Not sure why this isn't working as I am hoping.</p> <p>I am trying to find ways to allow my friend's website to run faster, and noticed there are several unnecessary CSS and scripts that load automatically. I have blocked some of these from triggering in the plugin/theme files by commenting them out, but a better way to get the same results without having to dig through files would be to just comment out the unwanted CSS and scripts in the HTML from my functions.php.</p> <p>I have tried using echo instead of return with no results.</p>
[ { "answer_id": 215526, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could do that with two queries:</p>\n\n<p>First we fetch the post ids we need with the first query and then we merge it with our sticky post ids and feed it into the second query, using the <code>post__in</code> parameter for filtering and ordering: </p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'asc',\n 'ignore_sticky_posts' =&gt; true,\n 'fields' =&gt; 'ids',\n];\n$ids = get_posts( $args );\nif( ! empty( $ids ) )\n{\n $stickies = [12,13,14,34];\n $post__in = array_unique( array_merge( $stickies, $ids ) );\n $args = [\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $loop = new WP_Query( $args ); \n // ... etc\n}\n</code></pre>\n\n<p>where we adjust the <code>$stickies</code> for the custom sticky posts.</p>\n" }, { "answer_id": 215535, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>If you need to:</p>\n\n<ul>\n<li><p>page the query</p></li>\n<li><p>retain 12 posts per page instead of \"sticking\" the desired posts on top of the required 12 </p></li>\n<li><p>only need to show those posts on the first page</p></li>\n</ul>\n\n<p>you can try the following</p>\n\n<pre><code>$ids_args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'fields' =&gt; 'ids'\n];\n$all_posts_ids = get_posts( $ids_args );\n\n// Make sure we have posts before continuing\nif ( $all_posts_ids ) {\n // Set all our posts that should move to the front \n $move_to_front = [12,13,14,34];\n // Add the array of posts to the front of our $all_posts_ids array\n $post_ids_merged = array_merge( $move_to_front, $all_posts_ids );\n // Make sure that we remove the ID's from their original positions\n $reordered_ids = array_unique( $post_ids_merged );\n\n // Now we can run our normal query to display 12 posts per page\n $args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__in' =&gt; $reordered_ids,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n ];\n $loop = new WP_Query( $args ); \n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you need these posts</p>\n\n<ul>\n<li><p>to stick on top of the 12 posts on every page</p></li>\n<li><p>in a paged query</p></li>\n</ul>\n\n<p>you can run two queries as follow</p>\n\n<pre><code>// Set an array of id's to display in front\n$move_to_front = [12,13,14,34];\n// Run the query to display the posts you need in front\n$args_front = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; count( $move_to_front ),\n 'post__in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n];\n$loop_front = new WP_Query( $args_front );\nif( $loop_front-&gt;have_posts() ) {\n while( $loop_front-&gt;have_posts() ) {\n $loop_front-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n\n// Now we can run our major loop to display the other posts\n$args = [\n 'post_type' =&gt; 'products'\n 'posts_per_page' =&gt; 12,\n 'post__not_in' =&gt; $move_to_front,\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; '_price',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; get_query_var( 'paged', 1 ),\n];\n$loop = new WP_Query( $args );\nif( $loop-&gt;have_posts() ) {\n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>If you only need one page with those posts in front, then the solution by @birgire will do the job just fine</p>\n" }, { "answer_id": 244136, "author": "Alex Standiford", "author_id": 105777, "author_profile": "https://wordpress.stackexchange.com/users/105777", "pm_score": 0, "selected": false, "text": "<p>Birgire's solution didn't quite work for me as-is. I needed to specify a <code>post_type‍</code> in my args after sorting.</p>\n\n<p>Here are my modifications, built as a class.</p>\n\n<pre><code>class locations{\n\n public function __construct(){\n $this-&gt;args = [\n 'post_type' =&gt; 'location',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'asc',\n 'fields' =&gt; 'ids',\n 'ignore_sticky_posts' =&gt; true,\n ];\n $this-&gt;ids = get_posts($this-&gt;args);\n $this-&gt;get = new WP_Query($this-&gt;sort_ids());\n }\n\n //Sorts the locations by specified criteria\n private function sort_ids(){\n $stickies = [2071,2080,2069,1823];\n $post__in = array_unique(array_merge($stickies, $this-&gt;ids));\n $args = [\n 'post_type' =&gt; 'location',\n 'post__in' =&gt; $post__in,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'asc',\n 'posts_per_page' =&gt; -1,\n 'ignore_sticky_posts' =&gt; true,\n ];\n return $args;\n }\n}\n</code></pre>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87430/" ]
I am trying to comment out unwanted CSS and JS files to prevent them from firing in the HTML by creating a simple function in my functions.php. So far I have: ``` function commentStuff() { $stylesheet = "<link rel=stylesheet --unwanted CSS file-- />"; $CommentedStyle = '<!-- ' . $stylesheet . ' -->'; return $CommentedStyle; } ``` Not sure why this isn't working as I am hoping. I am trying to find ways to allow my friend's website to run faster, and noticed there are several unnecessary CSS and scripts that load automatically. I have blocked some of these from triggering in the plugin/theme files by commenting them out, but a better way to get the same results without having to dig through files would be to just comment out the unwanted CSS and scripts in the HTML from my functions.php. I have tried using echo instead of return with no results.
If you need to: * page the query * retain 12 posts per page instead of "sticking" the desired posts on top of the required 12 * only need to show those posts on the first page you can try the following ``` $ids_args = [ 'post_type' => 'products' 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'fields' => 'ids' ]; $all_posts_ids = get_posts( $ids_args ); // Make sure we have posts before continuing if ( $all_posts_ids ) { // Set all our posts that should move to the front $move_to_front = [12,13,14,34]; // Add the array of posts to the front of our $all_posts_ids array $post_ids_merged = array_merge( $move_to_front, $all_posts_ids ); // Make sure that we remove the ID's from their original positions $reordered_ids = array_unique( $post_ids_merged ); // Now we can run our normal query to display 12 posts per page $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__in' => $reordered_ids, 'orderby' => 'post__in', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you need these posts * to stick on top of the 12 posts on every page * in a paged query you can run two queries as follow ``` // Set an array of id's to display in front $move_to_front = [12,13,14,34]; // Run the query to display the posts you need in front $args_front = [ 'post_type' => 'products' 'posts_per_page' => count( $move_to_front ), 'post__in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', ]; $loop_front = new WP_Query( $args_front ); if( $loop_front->have_posts() ) { while( $loop_front->have_posts() ) { $loop_front->the_post(); the_content(); } wp_reset_postdata(); } // Now we can run our major loop to display the other posts $args = [ 'post_type' => 'products' 'posts_per_page' => 12, 'post__not_in' => $move_to_front, 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC', 'paged' => get_query_var( 'paged', 1 ), ]; $loop = new WP_Query( $args ); if( $loop->have_posts() ) { while( $loop->have_posts() ) { $loop->the_post(); the_content(); } wp_reset_postdata(); } ``` If you only need one page with those posts in front, then the solution by @birgire will do the job just fine
215,569
<p>For starters, I'm aware of the concerns generally brought up by many when someone looks for a way to skip duplicate e-mail checks for creating new user accounts.</p> <p>However, In my case, I believe the reason for needing this is justified if I can explain it.</p> <p>I'm building an extensive vendor directory on my site using a membership plugin with public member directory (Ultimate Member). The problem is, Not all vendors are to register an account on their own. There are vendors I'd like to include in our directory purely for their public contact info for other users to search from the directory. </p> <p>For these vendors whom we can categorize as (unmanaged vendors), I'd like to use some catch-all e-mail such as [email protected] to register multiple accounts. These accounts will never be logged into, thus making issues with password recovery not an issue. I also cannot create a new e-mail address every single time to add each of these unmanaged vendors, nor can I just use fake e-mail addresses each time due to email bounces.</p> <p>Up until last week, I was using this plugin called "Multiple Accounts" to allow only a specifically designated e-mail address to be allowed multiple registration.</p> <p>However, I've moved my site to Multisite, and this plugin seemed to have stopped working.</p> <p>Upon web search, I've seen some function snippets people have suggested to bypass e-mail checks, but for reasons frowned upon by many, I cannot simply allow any and all e-mails to bypass this. I'd like to create a bypass for only 1 e-mail address (e.g. [email protected]).</p> <p>Would this be doable with a snippet for multisite install?</p> <p>By coding logic, I'm thinking along the lines of If registration email is [email protected], then allow registration without email duplicate check. All Else standard registration.</p> <p>I'd appreciate anyone to shed some light into this. Thanks in advance!</p>
[ { "answer_id": 215578, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 0, "selected": false, "text": "<p>That is not possible in an easy way, as WordPress always checks if the Emailadress is already used.</p>\n\n<pre><code>function email_exists( $email ) {\n if ( $user = get_user_by( 'email', $email) ) {\n return $user-&gt;ID;\n }\n return false;\n}\n</code></pre>\n\n<p>This function is also not filterable, so there is no way around in this direction.</p>\n\n<p>What you could do, however, is something much easier just insert the user without an emailadress, as this is not a required field.</p>\n\n<pre><code>$userdata = array(\n 'user_login' =&gt; 'login_name' . rand( 0, 1000 ), // randomize the login to test for multiple users. This is the field where you can insert your usernames.\n 'user_pass' =&gt; NULL, // When creating an user, `user_pass` is expected.\n 'role' =&gt; 'subscriber' // do not forget to restrict capabilities for those users.\n);\n\n$user_id = wp_insert_user( $userdata );\n</code></pre>\n\n<p>If you REALLY need to have the Emailadress stored with each of those users (I do not see the point in this), you can add it manually to the database. <em>I would highly recommend not to do that.</em></p>\n\n<p>You can not know how future updates might compromise this.</p>\n\n<p>Anyway, if you like playing with fire:</p>\n\n<pre><code>global $wpdb;\n\n$query = \"UPDATE $wpdb-&gt;users SET user_email = %s WHERE ID = %d\";\n$wpdb-&gt;get_results( $wpdb-&gt;prepare( $query, '[email protected]', $user_id ) );\n</code></pre>\n\n<p>As I mentioned - I really do not see the point in this, as the Emailadress is not used for anything. Have fun however ;)</p>\n\n<p>You can not use this with the WordPress UI - you will have to create a Plugin or something to handle this for you.</p>\n" }, { "answer_id": 215612, "author": "RichyVN", "author_id": 86810, "author_profile": "https://wordpress.stackexchange.com/users/86810", "pm_score": 0, "selected": false, "text": "<p>There is a function that lets you enter users without any email address at all! If that's what your looking for? Just put this piece of code in your functions.php</p>\n\n<pre><code> // Remove required email address in user profile\n function remove_empty_email_error( $arg ) {\n if ( !empty( $arg-&gt;errors['empty_email'] ) ) \nunset( $arg-&gt;errors['empty_email'] ); }\n add_action( 'user_profile_update_errors', 'remove_empty_email_error' );\n</code></pre>\n\n<p>This while suppress the error message in the user profile and let you enter that user witout any email address.</p>\n" }, { "answer_id": 215673, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": false, "text": "<p>Here is another approach in which we can answer the question, here is a small Plugin that adds a Submenupage for \"Users\", containing a small form where you can enter a username to create the new user with no emailadress.</p>\n\n<p>Additional Error handling allows you to see if the current user already exists, as usernames have to be unique.</p>\n\n<p>Create a <code>add-anonymous-user.php</code> file in your plugins directory, and place this code inside - activate the plugin and voila.</p>\n\n<p>Have fun!</p>\n\n<pre><code>&lt;?php\n\n /*\n Plugin Name: Add anonymous user\n Description: Add a user with no email adress\n Version: 0.0.1\n Plugin URI: http://fischi.cc\n Author: Thomas fischi! Fischer\n Author URI: https://fischi.cc\n Domain Path: /languages/\n License: GPL v2 or later\n\n */\n\n\n /* Add a Menu Page */\n add_action( 'admin_menu', 'f711_register_menu_page' );\n\n function f711_register_menu_page() {\n\n add_submenu_page( 'users.php', 'Add anonymous User', 'Anon User', 'manage_options', 'anon_user', 'f711_menu_page' );\n\n }\n\n // Function to display the input\n function f711_menu_page() {\n\n echo '&lt;div class=\"wrapper\"&gt;';\n //check if form was sent\n f711_check_for_input();\n echo '&lt;h1&gt;' . __( 'Add Anon User', 'aau' ) . '&lt;/h1&gt;';\n echo '&lt;h3&gt;' . __( 'Username', 'aau' ) . '&lt;/h3&gt;';\n // insert a small form that targets this page\n echo '&lt;form method=\"POST\" action=\"\"&gt;';\n\n echo '&lt;input type=\"text\" placeholder=\"' . __( 'Insert User Name', 'aau' ) . '\" name=\"anonname\" /&gt;';\n echo '&lt;input type=\"submit\" value=\"' . __( 'Create', 'aau' ) . '\" /&gt;';\n\n echo '&lt;/form&gt;';\n\n echo '&lt;/div&gt;';\n\n }\n\n // Function to process the input\n function f711_check_for_input() {\n\n // do nothing if Form was not sent\n if ( !isset( $_POST['anonname'] ) || $_POST['anonname'] == \"\" ) return;\n\n // sanitize the input to avoid security breaches\n $username = sanitize_text_field( $_POST['anonname'] );\n\n // define the new user\n $args = array(\n 'user_login' =&gt; $username,\n 'user_pass' =&gt; md5( rand( 1000000, 9999999 ) ), //create hash of randomized number as password\n 'role' =&gt; 'subscriber'\n );\n\n // try to insert the user\n $user_id = wp_insert_user( $args );\n\n // check if everything went coorectly\n if ( !is_wp_error( $user_id ) ) {\n //add a small notice\n echo '&lt;div class=\"updated\"&gt;&lt;p&gt;' . __( 'User created', 'aau' ) . ': ' . $username . '&lt;/p&gt;&lt;/div&gt;';\n } else {\n //show error message\n $errors = implode( ', ', $user_id-&gt;get_error_messages() );\n echo '&lt;div class=\"error\"&gt;&lt;p&gt;' . __( 'Error', 'aau' ) . ': ' . $errors . '&lt;/p&gt;&lt;/div&gt;';\n }\n\n }\n</code></pre>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87434/" ]
For starters, I'm aware of the concerns generally brought up by many when someone looks for a way to skip duplicate e-mail checks for creating new user accounts. However, In my case, I believe the reason for needing this is justified if I can explain it. I'm building an extensive vendor directory on my site using a membership plugin with public member directory (Ultimate Member). The problem is, Not all vendors are to register an account on their own. There are vendors I'd like to include in our directory purely for their public contact info for other users to search from the directory. For these vendors whom we can categorize as (unmanaged vendors), I'd like to use some catch-all e-mail such as [email protected] to register multiple accounts. These accounts will never be logged into, thus making issues with password recovery not an issue. I also cannot create a new e-mail address every single time to add each of these unmanaged vendors, nor can I just use fake e-mail addresses each time due to email bounces. Up until last week, I was using this plugin called "Multiple Accounts" to allow only a specifically designated e-mail address to be allowed multiple registration. However, I've moved my site to Multisite, and this plugin seemed to have stopped working. Upon web search, I've seen some function snippets people have suggested to bypass e-mail checks, but for reasons frowned upon by many, I cannot simply allow any and all e-mails to bypass this. I'd like to create a bypass for only 1 e-mail address (e.g. [email protected]). Would this be doable with a snippet for multisite install? By coding logic, I'm thinking along the lines of If registration email is [email protected], then allow registration without email duplicate check. All Else standard registration. I'd appreciate anyone to shed some light into this. Thanks in advance!
Here is another approach in which we can answer the question, here is a small Plugin that adds a Submenupage for "Users", containing a small form where you can enter a username to create the new user with no emailadress. Additional Error handling allows you to see if the current user already exists, as usernames have to be unique. Create a `add-anonymous-user.php` file in your plugins directory, and place this code inside - activate the plugin and voila. Have fun! ``` <?php /* Plugin Name: Add anonymous user Description: Add a user with no email adress Version: 0.0.1 Plugin URI: http://fischi.cc Author: Thomas fischi! Fischer Author URI: https://fischi.cc Domain Path: /languages/ License: GPL v2 or later */ /* Add a Menu Page */ add_action( 'admin_menu', 'f711_register_menu_page' ); function f711_register_menu_page() { add_submenu_page( 'users.php', 'Add anonymous User', 'Anon User', 'manage_options', 'anon_user', 'f711_menu_page' ); } // Function to display the input function f711_menu_page() { echo '<div class="wrapper">'; //check if form was sent f711_check_for_input(); echo '<h1>' . __( 'Add Anon User', 'aau' ) . '</h1>'; echo '<h3>' . __( 'Username', 'aau' ) . '</h3>'; // insert a small form that targets this page echo '<form method="POST" action="">'; echo '<input type="text" placeholder="' . __( 'Insert User Name', 'aau' ) . '" name="anonname" />'; echo '<input type="submit" value="' . __( 'Create', 'aau' ) . '" />'; echo '</form>'; echo '</div>'; } // Function to process the input function f711_check_for_input() { // do nothing if Form was not sent if ( !isset( $_POST['anonname'] ) || $_POST['anonname'] == "" ) return; // sanitize the input to avoid security breaches $username = sanitize_text_field( $_POST['anonname'] ); // define the new user $args = array( 'user_login' => $username, 'user_pass' => md5( rand( 1000000, 9999999 ) ), //create hash of randomized number as password 'role' => 'subscriber' ); // try to insert the user $user_id = wp_insert_user( $args ); // check if everything went coorectly if ( !is_wp_error( $user_id ) ) { //add a small notice echo '<div class="updated"><p>' . __( 'User created', 'aau' ) . ': ' . $username . '</p></div>'; } else { //show error message $errors = implode( ', ', $user_id->get_error_messages() ); echo '<div class="error"><p>' . __( 'Error', 'aau' ) . ': ' . $errors . '</p></div>'; } } ```
215,577
<p>I have a paid plugin that creates a custom type categories and posts in this categories. I want to get URLs like <em><code>site_name/category_name/post_name</code></em>. This plugin forms links like this: </p> <ul> <li>List item</li> </ul> <p>for categories - <em><code>site_name/category_name</code></em></p> <ul> <li>List item for posts - <em><code>site_name/category_name</code></em></li> </ul> <p>I have installed plugin <strong>Custom Post Type Permalinks</strong>, configured it. When I click on post link, I have a 404 page of theme (not server). But URL is right. In the post edit page the permalink is right too. Pages shows correctly.<br> I can't change any file of paid plugin or theme (it's already child theme). Can I resolve my problem with .htaccess or m.b. some another way? P.S. By the way, I've already tried to configure permalinks in Settings->Permalinks->Custom structure but result is the same.</p>
[ { "answer_id": 215578, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 0, "selected": false, "text": "<p>That is not possible in an easy way, as WordPress always checks if the Emailadress is already used.</p>\n\n<pre><code>function email_exists( $email ) {\n if ( $user = get_user_by( 'email', $email) ) {\n return $user-&gt;ID;\n }\n return false;\n}\n</code></pre>\n\n<p>This function is also not filterable, so there is no way around in this direction.</p>\n\n<p>What you could do, however, is something much easier just insert the user without an emailadress, as this is not a required field.</p>\n\n<pre><code>$userdata = array(\n 'user_login' =&gt; 'login_name' . rand( 0, 1000 ), // randomize the login to test for multiple users. This is the field where you can insert your usernames.\n 'user_pass' =&gt; NULL, // When creating an user, `user_pass` is expected.\n 'role' =&gt; 'subscriber' // do not forget to restrict capabilities for those users.\n);\n\n$user_id = wp_insert_user( $userdata );\n</code></pre>\n\n<p>If you REALLY need to have the Emailadress stored with each of those users (I do not see the point in this), you can add it manually to the database. <em>I would highly recommend not to do that.</em></p>\n\n<p>You can not know how future updates might compromise this.</p>\n\n<p>Anyway, if you like playing with fire:</p>\n\n<pre><code>global $wpdb;\n\n$query = \"UPDATE $wpdb-&gt;users SET user_email = %s WHERE ID = %d\";\n$wpdb-&gt;get_results( $wpdb-&gt;prepare( $query, '[email protected]', $user_id ) );\n</code></pre>\n\n<p>As I mentioned - I really do not see the point in this, as the Emailadress is not used for anything. Have fun however ;)</p>\n\n<p>You can not use this with the WordPress UI - you will have to create a Plugin or something to handle this for you.</p>\n" }, { "answer_id": 215612, "author": "RichyVN", "author_id": 86810, "author_profile": "https://wordpress.stackexchange.com/users/86810", "pm_score": 0, "selected": false, "text": "<p>There is a function that lets you enter users without any email address at all! If that's what your looking for? Just put this piece of code in your functions.php</p>\n\n<pre><code> // Remove required email address in user profile\n function remove_empty_email_error( $arg ) {\n if ( !empty( $arg-&gt;errors['empty_email'] ) ) \nunset( $arg-&gt;errors['empty_email'] ); }\n add_action( 'user_profile_update_errors', 'remove_empty_email_error' );\n</code></pre>\n\n<p>This while suppress the error message in the user profile and let you enter that user witout any email address.</p>\n" }, { "answer_id": 215673, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": false, "text": "<p>Here is another approach in which we can answer the question, here is a small Plugin that adds a Submenupage for \"Users\", containing a small form where you can enter a username to create the new user with no emailadress.</p>\n\n<p>Additional Error handling allows you to see if the current user already exists, as usernames have to be unique.</p>\n\n<p>Create a <code>add-anonymous-user.php</code> file in your plugins directory, and place this code inside - activate the plugin and voila.</p>\n\n<p>Have fun!</p>\n\n<pre><code>&lt;?php\n\n /*\n Plugin Name: Add anonymous user\n Description: Add a user with no email adress\n Version: 0.0.1\n Plugin URI: http://fischi.cc\n Author: Thomas fischi! Fischer\n Author URI: https://fischi.cc\n Domain Path: /languages/\n License: GPL v2 or later\n\n */\n\n\n /* Add a Menu Page */\n add_action( 'admin_menu', 'f711_register_menu_page' );\n\n function f711_register_menu_page() {\n\n add_submenu_page( 'users.php', 'Add anonymous User', 'Anon User', 'manage_options', 'anon_user', 'f711_menu_page' );\n\n }\n\n // Function to display the input\n function f711_menu_page() {\n\n echo '&lt;div class=\"wrapper\"&gt;';\n //check if form was sent\n f711_check_for_input();\n echo '&lt;h1&gt;' . __( 'Add Anon User', 'aau' ) . '&lt;/h1&gt;';\n echo '&lt;h3&gt;' . __( 'Username', 'aau' ) . '&lt;/h3&gt;';\n // insert a small form that targets this page\n echo '&lt;form method=\"POST\" action=\"\"&gt;';\n\n echo '&lt;input type=\"text\" placeholder=\"' . __( 'Insert User Name', 'aau' ) . '\" name=\"anonname\" /&gt;';\n echo '&lt;input type=\"submit\" value=\"' . __( 'Create', 'aau' ) . '\" /&gt;';\n\n echo '&lt;/form&gt;';\n\n echo '&lt;/div&gt;';\n\n }\n\n // Function to process the input\n function f711_check_for_input() {\n\n // do nothing if Form was not sent\n if ( !isset( $_POST['anonname'] ) || $_POST['anonname'] == \"\" ) return;\n\n // sanitize the input to avoid security breaches\n $username = sanitize_text_field( $_POST['anonname'] );\n\n // define the new user\n $args = array(\n 'user_login' =&gt; $username,\n 'user_pass' =&gt; md5( rand( 1000000, 9999999 ) ), //create hash of randomized number as password\n 'role' =&gt; 'subscriber'\n );\n\n // try to insert the user\n $user_id = wp_insert_user( $args );\n\n // check if everything went coorectly\n if ( !is_wp_error( $user_id ) ) {\n //add a small notice\n echo '&lt;div class=\"updated\"&gt;&lt;p&gt;' . __( 'User created', 'aau' ) . ': ' . $username . '&lt;/p&gt;&lt;/div&gt;';\n } else {\n //show error message\n $errors = implode( ', ', $user_id-&gt;get_error_messages() );\n echo '&lt;div class=\"error\"&gt;&lt;p&gt;' . __( 'Error', 'aau' ) . ': ' . $errors . '&lt;/p&gt;&lt;/div&gt;';\n }\n\n }\n</code></pre>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215577", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86327/" ]
I have a paid plugin that creates a custom type categories and posts in this categories. I want to get URLs like *`site_name/category_name/post_name`*. This plugin forms links like this: * List item for categories - *`site_name/category_name`* * List item for posts - *`site_name/category_name`* I have installed plugin **Custom Post Type Permalinks**, configured it. When I click on post link, I have a 404 page of theme (not server). But URL is right. In the post edit page the permalink is right too. Pages shows correctly. I can't change any file of paid plugin or theme (it's already child theme). Can I resolve my problem with .htaccess or m.b. some another way? P.S. By the way, I've already tried to configure permalinks in Settings->Permalinks->Custom structure but result is the same.
Here is another approach in which we can answer the question, here is a small Plugin that adds a Submenupage for "Users", containing a small form where you can enter a username to create the new user with no emailadress. Additional Error handling allows you to see if the current user already exists, as usernames have to be unique. Create a `add-anonymous-user.php` file in your plugins directory, and place this code inside - activate the plugin and voila. Have fun! ``` <?php /* Plugin Name: Add anonymous user Description: Add a user with no email adress Version: 0.0.1 Plugin URI: http://fischi.cc Author: Thomas fischi! Fischer Author URI: https://fischi.cc Domain Path: /languages/ License: GPL v2 or later */ /* Add a Menu Page */ add_action( 'admin_menu', 'f711_register_menu_page' ); function f711_register_menu_page() { add_submenu_page( 'users.php', 'Add anonymous User', 'Anon User', 'manage_options', 'anon_user', 'f711_menu_page' ); } // Function to display the input function f711_menu_page() { echo '<div class="wrapper">'; //check if form was sent f711_check_for_input(); echo '<h1>' . __( 'Add Anon User', 'aau' ) . '</h1>'; echo '<h3>' . __( 'Username', 'aau' ) . '</h3>'; // insert a small form that targets this page echo '<form method="POST" action="">'; echo '<input type="text" placeholder="' . __( 'Insert User Name', 'aau' ) . '" name="anonname" />'; echo '<input type="submit" value="' . __( 'Create', 'aau' ) . '" />'; echo '</form>'; echo '</div>'; } // Function to process the input function f711_check_for_input() { // do nothing if Form was not sent if ( !isset( $_POST['anonname'] ) || $_POST['anonname'] == "" ) return; // sanitize the input to avoid security breaches $username = sanitize_text_field( $_POST['anonname'] ); // define the new user $args = array( 'user_login' => $username, 'user_pass' => md5( rand( 1000000, 9999999 ) ), //create hash of randomized number as password 'role' => 'subscriber' ); // try to insert the user $user_id = wp_insert_user( $args ); // check if everything went coorectly if ( !is_wp_error( $user_id ) ) { //add a small notice echo '<div class="updated"><p>' . __( 'User created', 'aau' ) . ': ' . $username . '</p></div>'; } else { //show error message $errors = implode( ', ', $user_id->get_error_messages() ); echo '<div class="error"><p>' . __( 'Error', 'aau' ) . ': ' . $errors . '</p></div>'; } } ```
215,628
<p>I'm attempting to upload an audio file via AJAX form.</p> <p>Here is my HTML in the profile-edit template.</p> <pre><code>&lt;form method="post" id="my_upload_form" action="" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" id="my_file_input" accept="audio/*"&gt; &lt;input type="submit" class="btn-submit btn-sumary" value="upload audio file" name="submit" id="my_audio_submit"&gt; &lt;div id="my_error_report"&gt;&lt;/div&gt; &lt;/form&gt; </code></pre> <p>Here is my jQuery:</p> <pre><code>$('#my_upload_form').submit(function () { var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;'; var html = '&lt;strong&gt;&lt;em&gt; ' + '&lt;p style="' + css + '"&gt;' + '*'; var endHtml = '&lt;/p&gt;&lt;/em&gt;&lt;/strong&gt;'; var formData = new FormData(); var fileArray = jQuery('#my_file_input').prop('files'); if(fileArray.length &gt; 0) { var theTrack = fileArray[0]; formData.append("music", theTrack); } else { jQuery('#my_error_report').html( html + 'no track selected' + endHtml ); return false; } $.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', // async: false, data: { action : 'my_track_upload', some_data : formData }, // dataType: 'text' }).success( function( data ) { /* You win! */ alert('ajax was called success'); }).fail( function( data ) { /* You lose, show error */ alert('ajax was called failure'); }); return false; }); </code></pre> <p>Finally here is my plugin code:</p> <pre><code>add_action('wp_ajax_my_track_upload', 'my_track_upload'); function my_track_upload() { die('hello'); } </code></pre> <p>Problem (more to come): Why is the page refreshing? I return false in the jQuery 'submit' event.</p> <p>************************EDIT********************</p> <p>I changed my code to the following and it works now, though I'm not sure specifically where the problem was.</p> <p>... ... ...</p> <pre><code>var theTrack = fileArray[0]; formData.append('action', 'musistic_track_upload'); formData.append("music", theTrack); enter code here </code></pre> <p>... ... ...</p> <pre><code>$.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', data: formData, enctype: 'multipart/form-data', contentType: false, processData: false, datatype: "script", beforeSend: function() { jQuery('#my_error_report').html(''); } }).complete(function( data ) { jQuery('#my_error_report').html( html + data.responseText + endHtml ); jQuery('#my_audio_submit').val("Upload Audio File", function() { jQuery(this).prop('disabled', false); }); }); return false; </code></pre>
[ { "answer_id": 215809, "author": "Jeffrey Ponsen", "author_id": 80453, "author_profile": "https://wordpress.stackexchange.com/users/80453", "pm_score": 3, "selected": false, "text": "<p>Try using <code>preventDefault()</code>, it's a jQuery function for preventing default actions called by the browser. </p>\n\n<p>First you should call an event handler by firing up your submitter. You can do this as follow:</p>\n\n<p><code>$('#my_upload_form').submit(function (event) {</code></p>\n\n<p>After catching a submit and giving an event with it, you should prevent the default refresh of a browser:</p>\n\n<p><code>event.preventDefault();</code></p>\n\n<p>Now your code will look as follow:</p>\n\n<pre><code>$('#my_upload_form').submit(function (event) {\n\n event.preventDefault();\n\n var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';\n var html = '&lt;strong&gt;&lt;em&gt; ' + '&lt;p style=\"' + css + '\"&gt;' + '*';\n var endHtml = '&lt;/p&gt;&lt;/em&gt;&lt;/strong&gt;';\n\n var formData = new FormData();\n var fileArray = jQuery('#my_file_input').prop('files');\n\n if(fileArray.length &gt; 0) {\n var theTrack = fileArray[0];\n formData.append(\"music\", theTrack);\n } else {\n jQuery('#my_error_report').html( html + 'no track selected' + endHtml );\n return false;\n }\n\n $.ajax({\n url: '/wp-admin/admin-ajax.php',\n type: 'POST',\n // async: false,\n data: {\n action : 'my_track_upload',\n some_data : formData\n },\n // dataType: 'text'\n }).success( function( data ) {\n /* You win! */\n alert('ajax was called success');\n }).fail( function( data ) {\n /* You lose, show error */\n alert('ajax was called failure');\n });\n});\n</code></pre>\n\n<p>BTW: Always try to place <code>preventDefault()</code> on top of the function, it should prevent the default action before anything else is done.</p>\n" }, { "answer_id": 215901, "author": "Keenan Diggs", "author_id": 85662, "author_profile": "https://wordpress.stackexchange.com/users/85662", "pm_score": 2, "selected": true, "text": "<p>I was missing a crucial line in my AJAX query. Without this option, the call fails, and the pages refreshes.</p>\n\n<pre><code>processData: false,\n</code></pre>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85662/" ]
I'm attempting to upload an audio file via AJAX form. Here is my HTML in the profile-edit template. ``` <form method="post" id="my_upload_form" action="" enctype="multipart/form-data"> <input type="file" name="file" id="my_file_input" accept="audio/*"> <input type="submit" class="btn-submit btn-sumary" value="upload audio file" name="submit" id="my_audio_submit"> <div id="my_error_report"></div> </form> ``` Here is my jQuery: ``` $('#my_upload_form').submit(function () { var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;'; var html = '<strong><em> ' + '<p style="' + css + '">' + '*'; var endHtml = '</p></em></strong>'; var formData = new FormData(); var fileArray = jQuery('#my_file_input').prop('files'); if(fileArray.length > 0) { var theTrack = fileArray[0]; formData.append("music", theTrack); } else { jQuery('#my_error_report').html( html + 'no track selected' + endHtml ); return false; } $.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', // async: false, data: { action : 'my_track_upload', some_data : formData }, // dataType: 'text' }).success( function( data ) { /* You win! */ alert('ajax was called success'); }).fail( function( data ) { /* You lose, show error */ alert('ajax was called failure'); }); return false; }); ``` Finally here is my plugin code: ``` add_action('wp_ajax_my_track_upload', 'my_track_upload'); function my_track_upload() { die('hello'); } ``` Problem (more to come): Why is the page refreshing? I return false in the jQuery 'submit' event. \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*EDIT\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* I changed my code to the following and it works now, though I'm not sure specifically where the problem was. ... ... ... ``` var theTrack = fileArray[0]; formData.append('action', 'musistic_track_upload'); formData.append("music", theTrack); enter code here ``` ... ... ... ``` $.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', data: formData, enctype: 'multipart/form-data', contentType: false, processData: false, datatype: "script", beforeSend: function() { jQuery('#my_error_report').html(''); } }).complete(function( data ) { jQuery('#my_error_report').html( html + data.responseText + endHtml ); jQuery('#my_audio_submit').val("Upload Audio File", function() { jQuery(this).prop('disabled', false); }); }); return false; ```
I was missing a crucial line in my AJAX query. Without this option, the call fails, and the pages refreshes. ``` processData: false, ```
215,638
<p>My general question is: how to display product price in woocommerce of a product in a loop, not the price of the product which page it is? In other words I would like to display few related products in a grid on a single product page, but when I use this code :</p> <pre><code>&lt;?php $product = new WC_Product(get_the_ID()); echo wc_price($product-&gt;get_price_including_tax(1,$product-&gt;get_price())); ?&gt; </code></pre> <p>it displays price of a main product on the page for every single product in my grid - the price of the product which post it is, rather than the price of each product in a grid, if that makes sense... So if the price of the product on single page is Β£9.00, every product in related products grid will display with Β£9.00 too rather than it's own price...</p> <p>I am using ACF relations field to pick the products on a page.</p> <p>Here is my whole code including ACF relation field:</p> <pre><code>&lt;?php $posts = get_field('related_set_1'); if( $posts ): ?&gt; &lt;?php foreach( $posts as $p): ?&gt; &lt;li&gt; &lt;a href="&lt;?php echo get_permalink( $p-&gt;ID ); ?&gt;"&gt; &lt;?php echo get_the_post_thumbnail( $p-&gt;ID, '175x100' ) ?&gt; &lt;div style="overflow:hidden"&gt; &lt;h4&gt;&lt;?php echo $p-&gt;post_title; ?&gt;&lt;/h4&gt; &lt;p class="price"&gt; &lt;?php global $post; $product = new WC_Product($post-&gt;ID); echo wc_price($product-&gt;get_price_including_tax(1,$product-&gt;get_price())); ?&gt; &lt;/p&gt; &lt;p class="link"&gt;View now&lt;/p&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>And I use this in functions.php in filter function, if that makes any difference?</p> <pre><code>add_filter( 'woocommerce_after_single_product_summary', 'custom_related_products' ); function custom_related_products() { ?&gt; .... (the code above here) &lt;php? } </code></pre> <p>Becasue I display it on another product page I had to use </p> <pre><code>get_the_post_thumbnail( $p-&gt;ID, '175x100' ) </code></pre> <p>instead of</p> <pre><code>the_thumbnail </code></pre> <p>as otherwise I had the same issue and everything works well now, apart the price. </p> <p>Is there a way to target a price by <code>ID</code> or <code>sth</code>?</p>
[ { "answer_id": 216339, "author": "yennefer", "author_id": 87470, "author_profile": "https://wordpress.stackexchange.com/users/87470", "pm_score": 3, "selected": true, "text": "<p>I sorted this out, <code>$post</code> should be <code>$p</code> in:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>global $post;\n$product = new WC_Product( $post-&gt;ID );\n</code></pre>\n" }, { "answer_id": 301177, "author": "Ostap Brehin", "author_id": 134362, "author_profile": "https://wordpress.stackexchange.com/users/134362", "pm_score": 1, "selected": false, "text": "<p>Example</p>\n\n<pre><code>&lt;?php\nglobal $woocommerce;\n$currency = get_woocommerce_currency_symbol();\n$price = get_post_meta( get_the_ID(), '_regular_price', true);\n$sale = get_post_meta( get_the_ID(), '_sale_price', true);\n?&gt;\n\n&lt;?php if($sale) : ?&gt;\n&lt;p class=\"product-price-tickr\"&gt;&lt;del&gt;&lt;?php echo $currency; echo $price; ?&gt;&lt;/del&gt; &lt;?php echo $currency; echo $sale; ?&gt;&lt;/p&gt; \n&lt;?php elseif($price) : ?&gt;\n&lt;p class=\"product-price-tickr\"&gt;&lt;?php echo $currency; echo $price; ?&gt;&lt;/p&gt; \n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>from this\n<a href=\"https://gist.github.com/aarifhsn/d0535a720d13369010ce\" rel=\"nofollow noreferrer\">https://gist.github.com/aarifhsn/d0535a720d13369010ce</a></p>\n" }, { "answer_id": 386325, "author": "Wikus", "author_id": 84136, "author_profile": "https://wordpress.stackexchange.com/users/84136", "pm_score": 1, "selected": false, "text": "<pre><code>global $post;\n$product = new WC_Product( $post-&gt;ID );\necho $product-&gt;get_price_html();\n</code></pre>\n<p>That will return the correct price for simple and variable products and should also return the currently active prices (regular / sale).</p>\n<p>Edit: ref - <a href=\"https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_get_price_html\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_get_price_html</a></p>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215638", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87470/" ]
My general question is: how to display product price in woocommerce of a product in a loop, not the price of the product which page it is? In other words I would like to display few related products in a grid on a single product page, but when I use this code : ``` <?php $product = new WC_Product(get_the_ID()); echo wc_price($product->get_price_including_tax(1,$product->get_price())); ?> ``` it displays price of a main product on the page for every single product in my grid - the price of the product which post it is, rather than the price of each product in a grid, if that makes sense... So if the price of the product on single page is Β£9.00, every product in related products grid will display with Β£9.00 too rather than it's own price... I am using ACF relations field to pick the products on a page. Here is my whole code including ACF relation field: ``` <?php $posts = get_field('related_set_1'); if( $posts ): ?> <?php foreach( $posts as $p): ?> <li> <a href="<?php echo get_permalink( $p->ID ); ?>"> <?php echo get_the_post_thumbnail( $p->ID, '175x100' ) ?> <div style="overflow:hidden"> <h4><?php echo $p->post_title; ?></h4> <p class="price"> <?php global $post; $product = new WC_Product($post->ID); echo wc_price($product->get_price_including_tax(1,$product->get_price())); ?> </p> <p class="link">View now</p> </div> </a> </li> <?php endforeach; ?> <?php endif; ?> ``` And I use this in functions.php in filter function, if that makes any difference? ``` add_filter( 'woocommerce_after_single_product_summary', 'custom_related_products' ); function custom_related_products() { ?> .... (the code above here) <php? } ``` Becasue I display it on another product page I had to use ``` get_the_post_thumbnail( $p->ID, '175x100' ) ``` instead of ``` the_thumbnail ``` as otherwise I had the same issue and everything works well now, apart the price. Is there a way to target a price by `ID` or `sth`?
I sorted this out, `$post` should be `$p` in: ```php global $post; $product = new WC_Product( $post->ID ); ```
215,640
<p>I can't get the published post ID, i'm using a front end custom form. When the submit button is clicked site is re directed to a different page. Now, i can't get the just published post ID using:</p> <p><code>wp_insert_post($post)</code></p> <p>Because it returns the ID of redirected page instead of the published post. How can i get it? I'm running in circles here.</p>
[ { "answer_id": 215662, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p><code>wp_insert_post()</code> returns either one of three things</p>\n\n<ul>\n<li><p>the newly created post's ID</p></li>\n<li><p>a <code>WP_Error</code> object if <code>$wp_error</code> is set to true if an error occured during post insertion in which case the post is not inserted</p></li>\n<li><p><code>0</code> if <code>$wp_error</code> is set to false (<em>default</em>) if an error occured during post insertion in which case the post is not inserted</p></li>\n</ul>\n\n<p>The following should work</p>\n\n<pre><code>$args = [\n // All your post arguments\n];\n$q = wp_insert_post( $q );\nif ( 0 != $q \n &amp;&amp; !is_wp_error( $q )\n) {\n echo 'My new post ID is ' . $q;\n}\n</code></pre>\n" }, { "answer_id": 215730, "author": "Al Rosado", "author_id": 84237, "author_profile": "https://wordpress.stackexchange.com/users/84237", "pm_score": 0, "selected": false, "text": "<p>I am using a <code>custom_function()</code> to insert the post, the form redirects the user to a different page, that page has it's own ID and that's why I couldn't get this to work. </p>\n\n<p>In my case worked declaring this in my template:</p>\n\n<pre><code>if( $_POST) {\n $post_ID = custom_function();\n}\n</code></pre>\n\n<p>Then i can use <code>$post_ID</code> to get the custom data I needed from that post.</p>\n" } ]
2016/01/25
[ "https://wordpress.stackexchange.com/questions/215640", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84237/" ]
I can't get the published post ID, i'm using a front end custom form. When the submit button is clicked site is re directed to a different page. Now, i can't get the just published post ID using: `wp_insert_post($post)` Because it returns the ID of redirected page instead of the published post. How can i get it? I'm running in circles here.
`wp_insert_post()` returns either one of three things * the newly created post's ID * a `WP_Error` object if `$wp_error` is set to true if an error occured during post insertion in which case the post is not inserted * `0` if `$wp_error` is set to false (*default*) if an error occured during post insertion in which case the post is not inserted The following should work ``` $args = [ // All your post arguments ]; $q = wp_insert_post( $q ); if ( 0 != $q && !is_wp_error( $q ) ) { echo 'My new post ID is ' . $q; } ```
215,677
<p>I've been struggling with this for a few days now. What i want to do, it to limit the Postcode/zip fields to 4 numbers. So, to add a <b>maxlength</b> and a <b>type="number"</b> to those fields.</p> <p>Things i've tried so far:</p> <p>1 - (functions.php)</p> <pre><code>add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' ); function custom_override_checkout_fields( $fields ) { $fields['billing']['postcode']['maxlength'] = 4; return $fields; } </code></pre> <p>2 - (functions.php) a jQuery way</p> <pre><code>add_action("wp_footer", "cod_set_max_length"); function cod_set_max_length(){ ?&gt; &lt;script&gt; jQuery(document).ready(function($){ $("#postcode").attr('maxlength','4'); }); &lt;/script&gt; &lt;?php </code></pre>
[ { "answer_id": 216231, "author": "certainstrings", "author_id": 75979, "author_profile": "https://wordpress.stackexchange.com/users/75979", "pm_score": 2, "selected": false, "text": "<p>By the time <code>woocommerce_checkout_fields</code> filter is run, the arrays for billing and shipping have already been created. </p>\n\n<p>You can see that here: <br>\n<a href=\"https://docs.woothemes.com/wc-apidocs/source-class-WC_Checkout.html#101\" rel=\"nofollow\">https://docs.woothemes.com/wc-apidocs/source-class-WC_Checkout.html#101</a></p>\n\n<p>If you want to effect the default fields, use this hook.</p>\n\n<pre><code>function wpse215677_checkout_fields ( $fields ) {\n $fields['postcode']['maxlength'] = 4;\n return $fields;\n}\nadd_filter('woocommerce_default_address_fields', 'wpse215677_checkout_fields');\n</code></pre>\n\n<p>If you want to adjust just the default billing fields:</p>\n\n<pre><code>function wpse215677_checkout_fields ( $fields ) {\n $fields['billing_postcode']['maxlength'] = 4;\n return $fields;\n}\nadd_filter('woocommerce_billing_fields', 'wpse215677_checkout_fields');\n</code></pre>\n\n<p>Otherwise you just need to edit your array declaration:</p>\n\n<p><code>$fields['billing_postcode']['maxlength'] = 4;</code></p>\n" }, { "answer_id": 217774, "author": "Muhammad Faisal", "author_id": 88766, "author_profile": "https://wordpress.stackexchange.com/users/88766", "pm_score": 1, "selected": false, "text": "<p>You may add these functions in the functions.php of your theme:</p>\n\n<pre><code>function custom_override_checkout_fields2( $fields ) {\n$fields['shipping_postcode']['maxlength'] = 5; \nreturn $fields;\n}\nadd_filter( 'woocommerce_shipping_fields' , 'custom_override_checkout_fields2' );\n\nfunction custom_override_checkout_fields( $fields ) {\n $fields['billing_postcode']['maxlength'] = 5; \n return $fields;\n}\nadd_filter( 'woocommerce_billing_fields' , 'custom_override_checkout_fields' );\n</code></pre>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76984/" ]
I've been struggling with this for a few days now. What i want to do, it to limit the Postcode/zip fields to 4 numbers. So, to add a **maxlength** and a **type="number"** to those fields. Things i've tried so far: 1 - (functions.php) ``` add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' ); function custom_override_checkout_fields( $fields ) { $fields['billing']['postcode']['maxlength'] = 4; return $fields; } ``` 2 - (functions.php) a jQuery way ``` add_action("wp_footer", "cod_set_max_length"); function cod_set_max_length(){ ?> <script> jQuery(document).ready(function($){ $("#postcode").attr('maxlength','4'); }); </script> <?php ```
By the time `woocommerce_checkout_fields` filter is run, the arrays for billing and shipping have already been created. You can see that here: <https://docs.woothemes.com/wc-apidocs/source-class-WC_Checkout.html#101> If you want to effect the default fields, use this hook. ``` function wpse215677_checkout_fields ( $fields ) { $fields['postcode']['maxlength'] = 4; return $fields; } add_filter('woocommerce_default_address_fields', 'wpse215677_checkout_fields'); ``` If you want to adjust just the default billing fields: ``` function wpse215677_checkout_fields ( $fields ) { $fields['billing_postcode']['maxlength'] = 4; return $fields; } add_filter('woocommerce_billing_fields', 'wpse215677_checkout_fields'); ``` Otherwise you just need to edit your array declaration: `$fields['billing_postcode']['maxlength'] = 4;`
215,688
<p>I'm using the plugin <a href="https://wordpress.org/plugins/custom-css-js/" rel="noreferrer">Custom CSS JS</a> which registers it's own post type but the capability is assigned to <code>"post"</code>. </p> <p>I want to change it to <code>"manage_options"</code>.</p> <p>Is there a correct way without altering the plugin to do that? Calling a hook, a function or whatever? </p> <pre><code>public function register_post_type() { $labels = array ( 'name' =&gt; _x( 'Custom Code', 'post type general name' ), 'singular_name' =&gt; _x( 'Custom Code', 'post type singular name' ), 'menu_name' =&gt; _x( 'Custom CSS &amp; JS', 'admin menu' ), 'name_admin_bar' =&gt; _x( 'Custom Code', 'add new on admin bar' ), 'add_new' =&gt; _x( 'Add Custom Code', 'add new' ), 'add_new_item' =&gt; __( 'Add Custom Code' ), 'new_item' =&gt; __( 'New Custom Code' ), 'edit_item' =&gt; __( 'Edit Custom Code' ), 'view_item' =&gt; __( 'View Custom Code' ), 'all_items' =&gt; __( 'All Custom Code' ), 'search_items' =&gt; __( 'Search Custom Code' ), 'parent_item_colon' =&gt; __( 'Parent Custom Code:' ), 'not_found' =&gt; __( 'No Custom Code found.' ), 'not_found_in_trash' =&gt; __( 'No Custom Code found in Trash.' ), ); $args = array ( 'labels' =&gt; $labels, 'description' =&gt; __( 'Custom CSS and JS code' ), 'public' =&gt; false, 'publicly_queryable' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 100, 'menu_icon' =&gt; 'dashicons-plus-alt', 'query_var' =&gt; false, 'rewrite' =&gt; array ( 'slug' =&gt; 'custom-css-js' ), 'capability_type' =&gt; 'post', // &lt;--- I want to manipulate this 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'exclude_from_search' =&gt; true, 'menu_position' =&gt; null, 'can_export' =&gt; false, 'supports' =&gt; array ( 'title' ), ); register_post_type( 'custom-css-js', $args ); } </code></pre> <p>The above code is in <code>custom-css-js.php</code> lines <code>200-239</code>.</p>
[ { "answer_id": 215692, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>WordPress 4.4 finally saw the introduction of the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\"><code>register_post_type_args</code> filter</a> which you can use to alter the the arguments used when a <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\">custom post type (<em>or build-in type</em>) is registered</a></p>\n\n<p>I cannot code anything concrete now, but the following should get you going</p>\n\n<pre><code>add_filter( 'register_post_type_args', function ( $args, $post_type )\n{\n // Only target our specific post type\n if ( 'my_post_type' !== $post_type )\n return $args;\n\n // OK, we have our specified post type, lets alter our arguments\n ?&gt;&lt;pre&gt;&lt;?php var_dump( $args ); ?&gt;&lt;/pre&gt;&lt;?php\n\n // Change capability_type\n $args['capability_type'] = 'some_new_value';\n\n return $args;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 215697, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 3, "selected": true, "text": "<p>@PieterGoosen is cool, and still awake like me and answering like boss.</p>\n\n<p>To simplify his code and make it work to this specifically without a bunch of junk on your page:</p>\n\n<p>\n\n<pre><code>/**\n * Pieter Goosen writes awesome code\n */\nadd_filter( 'register_post_type_args', 'change_capabilities_of_the_custom_css_js_posttype' , 10, 2 );\n\nfunction change_capabilities_of_the_custom_css_js_posttype( $args, $post_type ){\n\n // Do not filter any other post type\n if ( 'custom-css-js' !== $post_type ) {\n\n // Give other post_types their original arguments\n return $args;\n\n }\n\n // Change the capability_type of the \"custom-css-js\" post_type\n $args['capability_type'] = 'manage_options';\n\n // Give the custom-css-js post type it's arguments\n return $args;\n\n}\n</code></pre>\n\n<p>The plugin you have chosen is written in a broad way. It has some insecurities.</p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64771/" ]
I'm using the plugin [Custom CSS JS](https://wordpress.org/plugins/custom-css-js/) which registers it's own post type but the capability is assigned to `"post"`. I want to change it to `"manage_options"`. Is there a correct way without altering the plugin to do that? Calling a hook, a function or whatever? ``` public function register_post_type() { $labels = array ( 'name' => _x( 'Custom Code', 'post type general name' ), 'singular_name' => _x( 'Custom Code', 'post type singular name' ), 'menu_name' => _x( 'Custom CSS & JS', 'admin menu' ), 'name_admin_bar' => _x( 'Custom Code', 'add new on admin bar' ), 'add_new' => _x( 'Add Custom Code', 'add new' ), 'add_new_item' => __( 'Add Custom Code' ), 'new_item' => __( 'New Custom Code' ), 'edit_item' => __( 'Edit Custom Code' ), 'view_item' => __( 'View Custom Code' ), 'all_items' => __( 'All Custom Code' ), 'search_items' => __( 'Search Custom Code' ), 'parent_item_colon' => __( 'Parent Custom Code:' ), 'not_found' => __( 'No Custom Code found.' ), 'not_found_in_trash' => __( 'No Custom Code found in Trash.' ), ); $args = array ( 'labels' => $labels, 'description' => __( 'Custom CSS and JS code' ), 'public' => false, 'publicly_queryable' => false, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 100, 'menu_icon' => 'dashicons-plus-alt', 'query_var' => false, 'rewrite' => array ( 'slug' => 'custom-css-js' ), 'capability_type' => 'post', // <--- I want to manipulate this 'has_archive' => true, 'hierarchical' => false, 'exclude_from_search' => true, 'menu_position' => null, 'can_export' => false, 'supports' => array ( 'title' ), ); register_post_type( 'custom-css-js', $args ); } ``` The above code is in `custom-css-js.php` lines `200-239`.
@PieterGoosen is cool, and still awake like me and answering like boss. To simplify his code and make it work to this specifically without a bunch of junk on your page: ``` /** * Pieter Goosen writes awesome code */ add_filter( 'register_post_type_args', 'change_capabilities_of_the_custom_css_js_posttype' , 10, 2 ); function change_capabilities_of_the_custom_css_js_posttype( $args, $post_type ){ // Do not filter any other post type if ( 'custom-css-js' !== $post_type ) { // Give other post_types their original arguments return $args; } // Change the capability_type of the "custom-css-js" post_type $args['capability_type'] = 'manage_options'; // Give the custom-css-js post type it's arguments return $args; } ``` The plugin you have chosen is written in a broad way. It has some insecurities.
215,707
<p>Maybe you guys know if it's possible to create an account when a new user creates a ticket. At this point there are 2 options. </p> <ol> <li>Let user create a ticket based on e-mail address</li> <li>Let user create an account first</li> </ol> <p>It would be nice if people don't need to create an account manually.<br> So if they fill in all the fields, an account will be created based on their e-mail address and receive login details for future use.</p>
[ { "answer_id": 215710, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_create_user</code> is your friend!</p>\n\n<p>It takes a username, password, and email:</p>\n\n<pre><code>wp_create_user( $username, $password, $email );\n</code></pre>\n\n<p>And here's an example:</p>\n\n<pre><code>$user_id = username_exists( $user_name );\nif ( !$user_id and email_exists($user_email) == false ) {\n $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );\n $user_id = wp_create_user( $user_name, $random_password, $user_email );\n} else {\n $random_password = __('User already exists. Password inherited.');\n}\n</code></pre>\n\n<p>Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new <code>ticket</code> is created, be it a webhook or an action depending on how <code>tickets</code> are implemented.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"nofollow\">You can find more information, including examples here</a></p>\n" }, { "answer_id": 239780, "author": "Marat Aminov", "author_id": 103122, "author_profile": "https://wordpress.stackexchange.com/users/103122", "pm_score": 0, "selected": false, "text": "<p>As I understand your case, you should try <a href=\"http://www.mycatchers.com\" rel=\"nofollow\">Catchers Helpdesk</a> plugin </p>\n\n<p>Then your customer send you a ticket, the plugin creates an user account and front end. The user will be notified by e-mail. </p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215707", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85557/" ]
Maybe you guys know if it's possible to create an account when a new user creates a ticket. At this point there are 2 options. 1. Let user create a ticket based on e-mail address 2. Let user create an account first It would be nice if people don't need to create an account manually. So if they fill in all the fields, an account will be created based on their e-mail address and receive login details for future use.
`wp_create_user` is your friend! It takes a username, password, and email: ``` wp_create_user( $username, $password, $email ); ``` And here's an example: ``` $user_id = username_exists( $user_name ); if ( !$user_id and email_exists($user_email) == false ) { $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false ); $user_id = wp_create_user( $user_name, $random_password, $user_email ); } else { $random_password = __('User already exists. Password inherited.'); } ``` Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new `ticket` is created, be it a webhook or an action depending on how `tickets` are implemented. [You can find more information, including examples here](https://codex.wordpress.org/Function_Reference/wp_create_user)
215,722
<p>My site has custom post type 'Portfolio'. If a user has at least one Portfolio, how can I disable the option to delete that user?</p> <p>I found the action/hook <code>delete_user</code>, but it doesn't seem right for this issue.</p>
[ { "answer_id": 215710, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_create_user</code> is your friend!</p>\n\n<p>It takes a username, password, and email:</p>\n\n<pre><code>wp_create_user( $username, $password, $email );\n</code></pre>\n\n<p>And here's an example:</p>\n\n<pre><code>$user_id = username_exists( $user_name );\nif ( !$user_id and email_exists($user_email) == false ) {\n $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );\n $user_id = wp_create_user( $user_name, $random_password, $user_email );\n} else {\n $random_password = __('User already exists. Password inherited.');\n}\n</code></pre>\n\n<p>Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new <code>ticket</code> is created, be it a webhook or an action depending on how <code>tickets</code> are implemented.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"nofollow\">You can find more information, including examples here</a></p>\n" }, { "answer_id": 239780, "author": "Marat Aminov", "author_id": 103122, "author_profile": "https://wordpress.stackexchange.com/users/103122", "pm_score": 0, "selected": false, "text": "<p>As I understand your case, you should try <a href=\"http://www.mycatchers.com\" rel=\"nofollow\">Catchers Helpdesk</a> plugin </p>\n\n<p>Then your customer send you a ticket, the plugin creates an user account and front end. The user will be notified by e-mail. </p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87518/" ]
My site has custom post type 'Portfolio'. If a user has at least one Portfolio, how can I disable the option to delete that user? I found the action/hook `delete_user`, but it doesn't seem right for this issue.
`wp_create_user` is your friend! It takes a username, password, and email: ``` wp_create_user( $username, $password, $email ); ``` And here's an example: ``` $user_id = username_exists( $user_name ); if ( !$user_id and email_exists($user_email) == false ) { $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false ); $user_id = wp_create_user( $user_name, $random_password, $user_email ); } else { $random_password = __('User already exists. Password inherited.'); } ``` Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new `ticket` is created, be it a webhook or an action depending on how `tickets` are implemented. [You can find more information, including examples here](https://codex.wordpress.org/Function_Reference/wp_create_user)
215,732
<p>I want to show <code>adsense ads</code> below the <strong>4th</strong> and <strong>20th</strong> paragraph of every blog post, ONLY if there is a <strong>20th</strong> paragraph.</p> <p>I managed to insert an ad below the <strong>4th</strong> ad by placing the following code in my <code>functions.php</code> file, however I don't know how to add an additional ad after the <strong>20th</strong>.</p> <pre><code>// Insert ads after second paragraph of single post content. add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { $ad_code = '&lt;div style="float:left;padding: 15px;"&gt; &lt;script type="text/javascript"&gt; google_ad_client = "ca-pub-xxxxxxxxxxxx"; google_ad_slot = "xxxxxxxxxx"; google_ad_width = 300; google_ad_height = 250; &lt;/script&gt; &lt;!-- Ad Name --&gt; &lt;script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"&gt; &lt;/script&gt; &lt;/div&gt;'; if ( is_single() &amp;&amp; ! is_admin() ) { return prefix_insert_after_paragraph( $ad_code, 3, $content ); } return $content; } // Parent Function that makes the magic happen function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '&lt;/p&gt;'; $paragraphs = explode( $closing_p, $content ); foreach ( $paragraphs as $index =&gt; $paragraph ) { if ( trim( $paragraph ) ) { $paragraphs[ $index ] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[ $index ] .= $insertion; } } return implode( '', $paragraphs ); } </code></pre>
[ { "answer_id": 215710, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_create_user</code> is your friend!</p>\n\n<p>It takes a username, password, and email:</p>\n\n<pre><code>wp_create_user( $username, $password, $email );\n</code></pre>\n\n<p>And here's an example:</p>\n\n<pre><code>$user_id = username_exists( $user_name );\nif ( !$user_id and email_exists($user_email) == false ) {\n $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );\n $user_id = wp_create_user( $user_name, $random_password, $user_email );\n} else {\n $random_password = __('User already exists. Password inherited.');\n}\n</code></pre>\n\n<p>Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new <code>ticket</code> is created, be it a webhook or an action depending on how <code>tickets</code> are implemented.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"nofollow\">You can find more information, including examples here</a></p>\n" }, { "answer_id": 239780, "author": "Marat Aminov", "author_id": 103122, "author_profile": "https://wordpress.stackexchange.com/users/103122", "pm_score": 0, "selected": false, "text": "<p>As I understand your case, you should try <a href=\"http://www.mycatchers.com\" rel=\"nofollow\">Catchers Helpdesk</a> plugin </p>\n\n<p>Then your customer send you a ticket, the plugin creates an user account and front end. The user will be notified by e-mail. </p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87528/" ]
I want to show `adsense ads` below the **4th** and **20th** paragraph of every blog post, ONLY if there is a **20th** paragraph. I managed to insert an ad below the **4th** ad by placing the following code in my `functions.php` file, however I don't know how to add an additional ad after the **20th**. ``` // Insert ads after second paragraph of single post content. add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { $ad_code = '<div style="float:left;padding: 15px;"> <script type="text/javascript"> google_ad_client = "ca-pub-xxxxxxxxxxxx"; google_ad_slot = "xxxxxxxxxx"; google_ad_width = 300; google_ad_height = 250; </script> <!-- Ad Name --> <script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div>'; if ( is_single() && ! is_admin() ) { return prefix_insert_after_paragraph( $ad_code, 3, $content ); } return $content; } // Parent Function that makes the magic happen function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '</p>'; $paragraphs = explode( $closing_p, $content ); foreach ( $paragraphs as $index => $paragraph ) { if ( trim( $paragraph ) ) { $paragraphs[ $index ] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[ $index ] .= $insertion; } } return implode( '', $paragraphs ); } ```
`wp_create_user` is your friend! It takes a username, password, and email: ``` wp_create_user( $username, $password, $email ); ``` And here's an example: ``` $user_id = username_exists( $user_name ); if ( !$user_id and email_exists($user_email) == false ) { $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false ); $user_id = wp_create_user( $user_name, $random_password, $user_email ); } else { $random_password = __('User already exists. Password inherited.'); } ``` Since your ticketing system is not a part of WordPress core, and no details are provided, you'll need to provide somewhere that will run code when a new `ticket` is created, be it a webhook or an action depending on how `tickets` are implemented. [You can find more information, including examples here](https://codex.wordpress.org/Function_Reference/wp_create_user)
215,744
<p>Is there a way to limit the dimensions of the full size uploaded image (made normally through the Media library)?</p> <p>I have clients that upload huge images files with resolutions sometimes greater than 5000 x 5000. They don't quite understand why Wordpress/websites have a hard time with these images.</p> <p>Limiting "Full" size images seems like a great solution. Is it possible via <code>functions.php</code>?</p>
[ { "answer_id": 215748, "author": "Stephen", "author_id": 85776, "author_profile": "https://wordpress.stackexchange.com/users/85776", "pm_score": 2, "selected": false, "text": "<p>So I've found this <a href=\"https://codex.wordpress.org/Class_Reference/WP_Image_Editor\" rel=\"nofollow\">WP_Image_Editor</a> in the CodeX. Basically by adding the code below it should automatically resize an image :)</p>\n\n<p>Code:</p>\n\n<pre><code>$image = wp_get_image_editor( 'cool_image.jpg' ); // Return an implementation that extends WP_Image_Editor\n\nif ( ! is_wp_error( $image ) ) {\n $image-&gt;resize( 300, 300, true );\n $image-&gt;save( 'new_image.jpg' );\n}\n</code></pre>\n\n<p>I don't know exactly if this will work but I'm sure if you look in the link I've gave you then you should be able to find it there.</p>\n\n<p>Best of luck :)</p>\n" }, { "answer_id": 408721, "author": "askuserahmed", "author_id": 221192, "author_profile": "https://wordpress.stackexchange.com/users/221192", "pm_score": 0, "selected": false, "text": "<p>I have found this in quora , if anyone has any other method to resize especially old uploaded images ,</p>\n<pre><code>add_filter('wp_generate_attachment_metadata','ad_limit_media_file_max_size'); \nfunction ad_limit_media_file_max_size($image_data) { \n if (!isset($image_data['sizes']['large'])) return $image_data; \n $upload_dir = wp_upload_dir(); \n $uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file']; \n $current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],&quot;/&quot;)); \n $large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file']; \n unlink($uploaded_image_location); \n rename($large_image_location,$uploaded_image_location); \n $image_data['width'] = $image_data['sizes']['large']['width']; \n $image_data['height'] = $image_data['sizes']['large']['height']; \n unset($image_data['sizes']['large']); \n return $image_data; \n} \n</code></pre>\n<p>Quora link:\n<a href=\"https://www.quora.com/Is-it-possible-to-create-a-child-theme-in-WordPress-that-loads-faster-than-its-parent\" rel=\"nofollow noreferrer\">https://www.quora.com/Is-it-possible-to-create-a-child-theme-in-WordPress-that-loads-faster-than-its-parent</a>\nGood luck</p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
Is there a way to limit the dimensions of the full size uploaded image (made normally through the Media library)? I have clients that upload huge images files with resolutions sometimes greater than 5000 x 5000. They don't quite understand why Wordpress/websites have a hard time with these images. Limiting "Full" size images seems like a great solution. Is it possible via `functions.php`?
So I've found this [WP\_Image\_Editor](https://codex.wordpress.org/Class_Reference/WP_Image_Editor) in the CodeX. Basically by adding the code below it should automatically resize an image :) Code: ``` $image = wp_get_image_editor( 'cool_image.jpg' ); // Return an implementation that extends WP_Image_Editor if ( ! is_wp_error( $image ) ) { $image->resize( 300, 300, true ); $image->save( 'new_image.jpg' ); } ``` I don't know exactly if this will work but I'm sure if you look in the link I've gave you then you should be able to find it there. Best of luck :)
215,745
<p>I'm building a custom theme for in-house use only. I started by putting a lot of the core functions in plugins, but then that seemed silly since they don't require any user interaction.</p> <p>Next, I put all of my classes in different php files in my theme folder and <code>include</code> them all in functions.php. </p> <p>Is there a better way to do this?</p>
[ { "answer_id": 215764, "author": "Geoff", "author_id": 26452, "author_profile": "https://wordpress.stackexchange.com/users/26452", "pm_score": 0, "selected": false, "text": "<p>I store core functions in a parent theme, then load site-specific functions to a child theme.</p>\n\n<p>Benefits:</p>\n\n<ol>\n<li>Decluttering the (child) theme with code that hardly ever changes\nper in-house preferences.</li>\n<li>Ability to push new core functionality to\nmany installations by simply updating the parent theme.</li>\n</ol>\n" }, { "answer_id": 215804, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>As @toscho mentioned in his comment, your best bet is probably an\n <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_path#Examples\" rel=\"nofollow\">autoloader</a>\n of some sort...</p>\n</blockquote>\n\n<pre><code>foreach ( glob( plugin_dir_path( __FILE__ ) . \"subfolder/*.php\" ) as $file ) {\n include_once $file;\n}\n</code></pre>\n\n<p>There are plugins that <a href=\"https://wordpress.org/plugins/wp-autoloader/\" rel=\"nofollow\">do this kind of thing</a> or possilby something like <a href=\"https://wordpress.org/plugins/code-snippets/\" rel=\"nofollow\">code snippets</a>, but I'll add some examples below...</p>\n\n<p><br></p>\n\n<h2>Example for basic functions in separate files in a plugin:</h2>\n\n<p>This example lets you easily add and remove features using theme-support. so basically in your <code>functions.php</code> you can this....</p>\n\n<pre><code>add_theme_support( feature-one );\nadd_theme_support( feature-two );\nadd_theme_support( feature-three );\n</code></pre>\n\n<p><strong><em>Create a basic plugin with the following structure:</em></strong></p>\n\n<pre><code>plugin-name/\n β”œβ”€β”€ plugin-name.php\n β”œβ”€β”€ features/feature-one.php\n β”œβ”€β”€ features/feature-two.php\n β”œβ”€β”€ features/feature-three.php\n └── features/feature-four.php\n</code></pre>\n\n<p><strong><em>Inside <code>plugin-name.php include this code:</code></em></strong></p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: My Themename Addons\nPlugin URI: https://example.com/\nDescription: Add Themename support\nVersion: 1.0.0\nAuthor: bryanwillis\nAuthor URI: https://github.com/bryanwillis/\nLicense: MIT License\nLicense URI: http://opensource.org/licenses/MIT\n*/\n\nfunction mytheme_autoload_files() {\n global $_wp_theme_features;\n foreach (glob(__DIR__ . '/theme-support/*.php') as $file) {\n $feature = 'mytheme-' . basename($file, '.php');\n if (isset($_wp_theme_features[$feature])) {\n require_once $file;\n }\n }\n}\nadd_action('after_setup_theme', 'mytheme_autoload_files', 100);\n</code></pre>\n\n<p><br></p>\n\n<hr>\n\n<h2>Second Example with functions in separate folders (like entire plugins):</h2>\n\n<p>This example doesn't have the option to remove features on the fly, but it automatically loads everything...</p>\n\n<ol>\n<li>Add a folder in your theme called <code>theme-plugins</code>.</li>\n<li>Create a file called <code>autoloader.php</code> inside theme-plugins folder with the below code and use include/require/etc. in your functions.php to include it ( you could also make this it's own plugin).</li>\n<li>Drop your plugins inside the <code>theme-plugins</code> folder to autoload them ( plugins must have the same folder name as file name.</li>\n</ol>\n\n<p><strong><em>Folder structure:</em></strong> </p>\n\n<pre><code>themename/\n └── theme-plugins/\n β”œβ”€β”€ autoloader.php\n β”œβ”€β”€ plugin-one/plugin-one.php\n β”œβ”€β”€ plugin-two/plugin-two.php\n β”œβ”€β”€ plugin-three/plugin-three.php\n └── plugin-foo/plugin-foo.php\n</code></pre>\n\n<p><strong><em>Code for <code>autoloader.php</code>:</em></strong></p>\n\n<pre><code> &lt;?php\n/**\n * Autoloader - theme-plugins/autoloader.php\n */\n function themename_plugins_autoloader() {\n $plugins_dirs = = array_filter( scandir() );\n $non_dirs = array(\n '.',\n '..',\n '.DS_Store',\n );\n for( $i = 0; $i &lt; count( $non_dirs ); $i++ ) {\n $not_dir_key = array_search( $non_dirs[ $i ], $$autoload_plugin_dirs );\n if( $not_dir_key !== false ) {\n unset( $$autoload_plugin_dirs[ $not_dir_key ] );\n }\n unset( $not_dir_key );\n }\n unset( $non_dirs );\n if( empty( $$autoload_plugin_dirs ) ) {\n return;\n }\n sort( $$autoload_plugin_dirs );\n foreach( $$autoload_plugin_dirs as $dir ) {\n $plugin_dir = plugin_dir_path( __FILE__ ) . $dir;\n $plugin_file = trailingslashit( $plugin_dir ) . $dir . '.php';\n if( is_dir( $plugin_dir ) &amp;&amp; file_exists( $plugin_file ) ) {\n require_once( $plugin_file );\n }\n unset( $plugin_file, $plugin_dir );\n }\n}\nthemename_plugins_autoloader();\n</code></pre>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215745", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87536/" ]
I'm building a custom theme for in-house use only. I started by putting a lot of the core functions in plugins, but then that seemed silly since they don't require any user interaction. Next, I put all of my classes in different php files in my theme folder and `include` them all in functions.php. Is there a better way to do this?
> > As @toscho mentioned in his comment, your best bet is probably an > [autoloader](https://codex.wordpress.org/Function_Reference/plugin_dir_path#Examples) > of some sort... > > > ``` foreach ( glob( plugin_dir_path( __FILE__ ) . "subfolder/*.php" ) as $file ) { include_once $file; } ``` There are plugins that [do this kind of thing](https://wordpress.org/plugins/wp-autoloader/) or possilby something like [code snippets](https://wordpress.org/plugins/code-snippets/), but I'll add some examples below... Example for basic functions in separate files in a plugin: ---------------------------------------------------------- This example lets you easily add and remove features using theme-support. so basically in your `functions.php` you can this.... ``` add_theme_support( feature-one ); add_theme_support( feature-two ); add_theme_support( feature-three ); ``` ***Create a basic plugin with the following structure:*** ``` plugin-name/ β”œβ”€β”€ plugin-name.php β”œβ”€β”€ features/feature-one.php β”œβ”€β”€ features/feature-two.php β”œβ”€β”€ features/feature-three.php └── features/feature-four.php ``` ***Inside `plugin-name.php include this code:`*** ``` <?php /* Plugin Name: My Themename Addons Plugin URI: https://example.com/ Description: Add Themename support Version: 1.0.0 Author: bryanwillis Author URI: https://github.com/bryanwillis/ License: MIT License License URI: http://opensource.org/licenses/MIT */ function mytheme_autoload_files() { global $_wp_theme_features; foreach (glob(__DIR__ . '/theme-support/*.php') as $file) { $feature = 'mytheme-' . basename($file, '.php'); if (isset($_wp_theme_features[$feature])) { require_once $file; } } } add_action('after_setup_theme', 'mytheme_autoload_files', 100); ``` --- Second Example with functions in separate folders (like entire plugins): ------------------------------------------------------------------------ This example doesn't have the option to remove features on the fly, but it automatically loads everything... 1. Add a folder in your theme called `theme-plugins`. 2. Create a file called `autoloader.php` inside theme-plugins folder with the below code and use include/require/etc. in your functions.php to include it ( you could also make this it's own plugin). 3. Drop your plugins inside the `theme-plugins` folder to autoload them ( plugins must have the same folder name as file name. ***Folder structure:*** ``` themename/ └── theme-plugins/ β”œβ”€β”€ autoloader.php β”œβ”€β”€ plugin-one/plugin-one.php β”œβ”€β”€ plugin-two/plugin-two.php β”œβ”€β”€ plugin-three/plugin-three.php └── plugin-foo/plugin-foo.php ``` ***Code for `autoloader.php`:*** ``` <?php /** * Autoloader - theme-plugins/autoloader.php */ function themename_plugins_autoloader() { $plugins_dirs = = array_filter( scandir() ); $non_dirs = array( '.', '..', '.DS_Store', ); for( $i = 0; $i < count( $non_dirs ); $i++ ) { $not_dir_key = array_search( $non_dirs[ $i ], $$autoload_plugin_dirs ); if( $not_dir_key !== false ) { unset( $$autoload_plugin_dirs[ $not_dir_key ] ); } unset( $not_dir_key ); } unset( $non_dirs ); if( empty( $$autoload_plugin_dirs ) ) { return; } sort( $$autoload_plugin_dirs ); foreach( $$autoload_plugin_dirs as $dir ) { $plugin_dir = plugin_dir_path( __FILE__ ) . $dir; $plugin_file = trailingslashit( $plugin_dir ) . $dir . '.php'; if( is_dir( $plugin_dir ) && file_exists( $plugin_file ) ) { require_once( $plugin_file ); } unset( $plugin_file, $plugin_dir ); } } themename_plugins_autoloader(); ```
215,766
<p>When you insert the "More" link into a post using the "Insert More Break" toolbar icon, the url that is generated is appended with "#more-". Thus when you click that link, you get the full post (via single.php), but the browser then scrolls to where the 'more' was inserted.</p> <p>Is there a filter I can use to remove the "#more-"?</p> <p>What I want is to <em>not</em> scroll to the 'more' link when the full post is displayed. Thanks.</p>
[ { "answer_id": 215768, "author": "Dejo Dekic", "author_id": 20941, "author_profile": "https://wordpress.stackexchange.com/users/20941", "pm_score": 3, "selected": true, "text": "<p>There you go this will prevent scroll (add to functions.php)</p>\n\n<pre><code>function remove_more_link_scroll( $link ) {\n$link = preg_replace( '|#more-[0-9]+|', '', $link );\nreturn $link;\n}\nadd_filter( 'the_content_more_link', 'remove_more_link_scroll' );\n</code></pre>\n\n<p>Explained in depth <a href=\"https://codex.wordpress.org/Customizing_the_Read_More#Prevent_Page_Scroll_When_Clicking_the_More_Link\" rel=\"nofollow\">Here</a>.</p>\n" }, { "answer_id": 312134, "author": "Bheemsen", "author_id": 67150, "author_profile": "https://wordpress.stackexchange.com/users/67150", "pm_score": 1, "selected": false, "text": "<p>I know a rather simple way to achieve that, with just one line of code.</p>\n\n<pre><code>the_content( '' );\n</code></pre>\n\n<p>Note that you have to use it in the templates responsible for displaying the content at appropriate places, and not in <code>functions.php</code>. I bet you won't see that #more... link again.</p>\n" } ]
2016/01/26
[ "https://wordpress.stackexchange.com/questions/215766", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76191/" ]
When you insert the "More" link into a post using the "Insert More Break" toolbar icon, the url that is generated is appended with "#more-". Thus when you click that link, you get the full post (via single.php), but the browser then scrolls to where the 'more' was inserted. Is there a filter I can use to remove the "#more-"? What I want is to *not* scroll to the 'more' link when the full post is displayed. Thanks.
There you go this will prevent scroll (add to functions.php) ``` function remove_more_link_scroll( $link ) { $link = preg_replace( '|#more-[0-9]+|', '', $link ); return $link; } add_filter( 'the_content_more_link', 'remove_more_link_scroll' ); ``` Explained in depth [Here](https://codex.wordpress.org/Customizing_the_Read_More#Prevent_Page_Scroll_When_Clicking_the_More_Link).