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
279,399
<p>I am using a WCK plugin to Wordpress. In the php code to call the image source, I used <code>wp_get_attachment_image_src()</code> but it only gets the url of the image. I want to include the alt value of it. Please help. Thanks.</p> <p>Below is my code.</p> <pre><code>&lt;div class="authortest-cont"&gt; &lt;h2&gt;&lt;span&gt;W&lt;/span&gt;hat Our &lt;small&gt;Authors Say&lt;/small&gt;&lt;/h2&gt; &lt;?php $wck_custom = get_post_meta( $post-&gt;ID, 'testimonialsbox', true); foreach($wck_custom as $wck_cstm) { $author_name = $wck_cstm['author_name']; $author_img = $wck_cstm['author_img']; $author_testimonial = $wck_cstm['author_testimonial']; if( is_numeric( $author_img ) ) { $attach_author_img = wp_get_attachment_image_src( $author_img, 'full' ); $src_author_img = $attach_author_img[0]; } else { $src_author_img = $author_img; } ?&gt; &lt;div class="col-md-6 col-sm-6"&gt; &lt;?php echo $author_testimonial; ?&gt; &lt;div class="author-det"&gt; &lt;img src="&lt;?php echo $src_author_img; ?&gt;" alt=""/&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>How <code>echo</code> alt value of that image?</p>
[ { "answer_id": 279400, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p><code>wp_get_attachment_image()</code> will generate a full image tag, including the alt attribute. If you need to put a custom class or attribute on the image (one reason you might only want the src), you can still do that with that function by using the 4th argument:</p>\n\n<pre><code>echo wp_get_attachment_image( $attachment_id, 'large', false, array( 'class' =&gt; 'my-custom-class' ) );\n</code></pre>\n\n<p>If you just want the alt text on its own, then given the ID of the attachment you can just use:</p>\n\n<pre><code>echo get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );\n</code></pre>\n" }, { "answer_id": 279401, "author": "Jeff Mattson", "author_id": 93714, "author_profile": "https://wordpress.stackexchange.com/users/93714", "pm_score": 2, "selected": false, "text": "<p>This looks like how you should use WCK:</p>\n\n<pre><code>&lt;?php\nforeach( get_cfc_meta( 'testimonialsbox' ) as $key =&gt; $value ){ ?&gt;\n &lt;?php $author_testimonial = $key['author_testimonial']; ?&gt;\n &lt;?php $photo_obj = get_cfc_field( 'testimonialsbox','photo', false, $key ); ?&gt;\n &lt;div class=\"col-md-6 col-sm-6\"&gt;\n &lt;?php echo $author_testimonial; ?&gt;\n &lt;div class=\"author-det\"&gt;\n &lt;img src=\"&lt;?php echo $photo_obj['url'] ?&gt;\" alt=\"&lt;?php echo $photo_obj['alt']; ?&gt;\"/&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125514/" ]
I am using a WCK plugin to Wordpress. In the php code to call the image source, I used `wp_get_attachment_image_src()` but it only gets the url of the image. I want to include the alt value of it. Please help. Thanks. Below is my code. ``` <div class="authortest-cont"> <h2><span>W</span>hat Our <small>Authors Say</small></h2> <?php $wck_custom = get_post_meta( $post->ID, 'testimonialsbox', true); foreach($wck_custom as $wck_cstm) { $author_name = $wck_cstm['author_name']; $author_img = $wck_cstm['author_img']; $author_testimonial = $wck_cstm['author_testimonial']; if( is_numeric( $author_img ) ) { $attach_author_img = wp_get_attachment_image_src( $author_img, 'full' ); $src_author_img = $attach_author_img[0]; } else { $src_author_img = $author_img; } ?> <div class="col-md-6 col-sm-6"> <?php echo $author_testimonial; ?> <div class="author-det"> <img src="<?php echo $src_author_img; ?>" alt=""/> </div> </div> <?php } ?> </div> ``` How `echo` alt value of that image?
`wp_get_attachment_image()` will generate a full image tag, including the alt attribute. If you need to put a custom class or attribute on the image (one reason you might only want the src), you can still do that with that function by using the 4th argument: ``` echo wp_get_attachment_image( $attachment_id, 'large', false, array( 'class' => 'my-custom-class' ) ); ``` If you just want the alt text on its own, then given the ID of the attachment you can just use: ``` echo get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); ```
279,429
<p>where the default category to is titled 'Games'.</p> <p>In the functions.php I have added this code to give each page a second category.</p> <pre><code>&lt;?php add_action('init', 'build_taxonomies', 0); function build_taxonomies() { register_taxonomy('players_team', 'player', array( 'hierarchical' =&gt; true, 'label' =&gt; 'Players Team', 'query_var' =&gt; true, 'rewrite' =&gt; true )); } </code></pre> <p>However I need a third added. I have duplicated the code above in "functions.php" however I get an error on website. TBH didn't think it would be just a simple copy &amp; paste. Im looking to add a third category called "Region".</p> <p>Any help is appreciated.</p>
[ { "answer_id": 279430, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 1, "selected": true, "text": "<p>For every taxonomy you have to choose a unique name, which is used in the database. so so your new e.g. <code>players_region</code>.</p>\n\n<pre><code>&lt;?php\nadd_action( 'init', 'build_taxonomies' );\n\nfunction build_taxonomies() {\n register_taxonomy(\n 'players_team', // Unique name.\n 'player', // Post type.\n array(\n 'hierarchical' =&gt; true,\n 'label' =&gt; 'Players Team',\n 'query_var' =&gt; true,\n 'rewrite' =&gt; true,\n )\n );\n register_taxonomy(\n 'players_region',\n 'player',\n array(\n 'hierarchical' =&gt; true,\n 'label' =&gt; 'Players Region',\n 'query_var' =&gt; true,\n 'rewrite' =&gt; true,\n )\n );\n}\n</code></pre>\n" }, { "answer_id": 279641, "author": "Level8", "author_id": 127476, "author_profile": "https://wordpress.stackexchange.com/users/127476", "pm_score": -1, "selected": false, "text": "<p>Thanks for info.</p>\n\n<p>I have found the error in the functions php, as shown above was copying to much. Causing the error.</p>\n\n<p>Thanks.</p>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127476/" ]
where the default category to is titled 'Games'. In the functions.php I have added this code to give each page a second category. ``` <?php add_action('init', 'build_taxonomies', 0); function build_taxonomies() { register_taxonomy('players_team', 'player', array( 'hierarchical' => true, 'label' => 'Players Team', 'query_var' => true, 'rewrite' => true )); } ``` However I need a third added. I have duplicated the code above in "functions.php" however I get an error on website. TBH didn't think it would be just a simple copy & paste. Im looking to add a third category called "Region". Any help is appreciated.
For every taxonomy you have to choose a unique name, which is used in the database. so so your new e.g. `players_region`. ``` <?php add_action( 'init', 'build_taxonomies' ); function build_taxonomies() { register_taxonomy( 'players_team', // Unique name. 'player', // Post type. array( 'hierarchical' => true, 'label' => 'Players Team', 'query_var' => true, 'rewrite' => true, ) ); register_taxonomy( 'players_region', 'player', array( 'hierarchical' => true, 'label' => 'Players Region', 'query_var' => true, 'rewrite' => true, ) ); } ```
279,448
<p>I am using the below contact from code in the WordPress by creating shortcode. When i submit the form it shows success message but didn't get any email in inbox or spam. Can anybody please help.</p> <pre><code>function contactform_func( $atts ) { $atts = shortcode_atts( array( 'to_email' =&gt; '', 'title' =&gt; 'Contact enquiry - '.get_bloginfo('url'), ), $atts ); $cform = "&lt;div class=\"main-form-area\" id=\"contactform_main\"&gt;"; $cerr = array(); if( isset($_POST['c_submit']) &amp;&amp; $_POST['c_submit']=='Submit' ){ $name = trim( $_POST['c_name'] ); $email = trim( $_POST['c_email'] ); $phone = trim( $_POST['c_phone'] ); $website = trim( $_POST['c_website'] ); $comments = trim( $_POST['c_comments'] ); $captcha = trim( $_POST['c_captcha'] ); $captcha_cnf = trim( $_POST['c_captcha_confirm'] ); if( !$name ) $cerr['name'] = 'Please enter your name.'; if( ! filter_var($email, FILTER_VALIDATE_EMAIL) ) $cerr['email'] = 'Please enter a valid email.'; if( !$phone ) $cerr['phone'] = 'Please enter your phone number.'; if( !$comments ) $cerr['comments'] = 'Please enter your question / comments.'; if( !$captcha || (md5($captcha) != $captcha_cnf) ) $cerr['captcha'] = 'Please enter the correct answer.'; if( count($cerr) == 0 ){ $subject = $atts['title']; $headers = "From: ".$name." &lt;" . strip_tags($email) . "&gt;\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $message = '&lt;html&gt;&lt;body&gt; &lt;table&gt; &lt;tr&gt;&lt;td&gt;Name: &lt;/td&gt;&lt;td&gt;'.$name.'&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;'.$email.'&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Phone: &lt;/td&gt;&lt;td&gt;'.$phone.'&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Website: &lt;/td&gt;&lt;td&gt;'.$website.'&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Comments: &lt;/td&gt;&lt;td&gt;'.$comments.'&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;'; mail( $atts['to_email'], $subject, $message, $headers); $cform .= '&lt;div class="success_msg"&gt;Thank you! A representative will get back to you very shortly.&lt;/div&gt;'; unset( $name, $email, $phone, $website, $comments, $captcha ); }else{ $cform .= '&lt;div class="error_msg"&gt;'; $cform .= implode('&lt;br /&gt;',$cerr); $cform .= '&lt;/div&gt;'; } } $capNum1 = rand(1,4); $capNum2 = rand(1,5); $capSum = $capNum1 + $capNum2; $sumStr = $capNum1." + ".$capNum2 ." = "; $cform .= "&lt;form name=\"contactform\" action=\"#contactform_main\" method=\"post\"&gt; &lt;p class=\"left\"&gt;&lt;input type=\"text\" name=\"c_name\" value=\"". ( ( empty($name) == false ) ? $name : "" ) ."\" placeholder=\"Name\" /&gt;&lt;/p&gt; &lt;p class=\"right\"&gt;&lt;input type=\"email\" name=\"c_email\" value=\"". ( ( empty($email) == false ) ? $email : "" ) ."\" placeholder=\"Email\" /&gt;&lt;/p&gt;&lt;div class=\"clear\"&gt;&lt;/div&gt; &lt;p class=\"left\"&gt;&lt;input type=\"tel\" name=\"c_phone\" value=\"". ( ( empty($phone) == false ) ? $phone : "" ) ."\" placeholder=\"Phone\" /&gt;&lt;/p&gt; &lt;p class=\"right\"&gt;&lt;input type=\"url\" name=\"c_website\" value=\"". ( ( empty($website) == false ) ? $website : "" ) ."\" placeholder=\"Website with prefix http://\" /&gt;&lt;/p&gt;&lt;div class=\"clear\"&gt;&lt;/div&gt; &lt;p&gt;&lt;textarea name=\"c_comments\" placeholder=\"Message\"&gt;". ( ( empty($comments) == false ) ? $comments : "" ) ."&lt;/textarea&gt;&lt;/p&gt;"; $cform .= "&lt;br /&gt;&lt;p class=\"left\"&gt;$sumStr&lt;input style=\"width:200px;\" type=\"text\" placeholder=\"Captcha\" value=\"". ( ( empty($captcha) == false ) ? $captcha : "" ) ."\" name=\"c_captcha\" /&gt;&lt;input type=\"hidden\" name=\"c_captcha_confirm\" value=\"". md5($capSum)."\"&gt;&lt;/p&gt;&lt;div class=\"clear\"&gt;&lt;/div&gt;"; $cform .= "&lt;p class=\"sub\"&gt;&lt;input type=\"submit\" name=\"c_submit\" value=\"Submit\" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;/div&gt;"; return $cform;} add_shortcode( 'contactform', 'contactform_func' ); </code></pre>
[ { "answer_id": 280923, "author": "SEO DEVS", "author_id": 111163, "author_profile": "https://wordpress.stackexchange.com/users/111163", "pm_score": 2, "selected": false, "text": "<p>The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.</p>\n" }, { "answer_id": 280933, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 1, "selected": false, "text": "<p>you can use Caption Shortcode on the image you want change caption like:</p>\n\n<pre><code>[caption]&lt;image&gt; Caption[/caption]\n</code></pre>\n\n<p>This is primarily used with individual images caption change.</p>\n\n<p>for detail information how to use caption shortcode check <a href=\"https://codex.wordpress.org/Caption_Shortcode\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>update#1 25-9-2017</p>\n\n<p>in above answer i clear that This is primarily used with individual images caption change.</p>\n\n<p>but if you want to change image caption inside gallery group ,i think you can achieve this manually by jquery (i think it's the easyist way to do it )like so:</p>\n\n<p>1-open any *.js file that already enqueued in your gallery page.\n( *.js file you can find in page source) </p>\n\n<p>2-put this little piece of code in </p>\n\n<pre><code> ( function( $ ) { \n function function_name() {\n $( '#gallery-&lt;gallery_ID&gt;-&lt;image_ID&gt;').text(\"new caption\");\n }\n\n function_name();\n } )( jQuery );\n</code></pre>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127490/" ]
I am using the below contact from code in the WordPress by creating shortcode. When i submit the form it shows success message but didn't get any email in inbox or spam. Can anybody please help. ``` function contactform_func( $atts ) { $atts = shortcode_atts( array( 'to_email' => '', 'title' => 'Contact enquiry - '.get_bloginfo('url'), ), $atts ); $cform = "<div class=\"main-form-area\" id=\"contactform_main\">"; $cerr = array(); if( isset($_POST['c_submit']) && $_POST['c_submit']=='Submit' ){ $name = trim( $_POST['c_name'] ); $email = trim( $_POST['c_email'] ); $phone = trim( $_POST['c_phone'] ); $website = trim( $_POST['c_website'] ); $comments = trim( $_POST['c_comments'] ); $captcha = trim( $_POST['c_captcha'] ); $captcha_cnf = trim( $_POST['c_captcha_confirm'] ); if( !$name ) $cerr['name'] = 'Please enter your name.'; if( ! filter_var($email, FILTER_VALIDATE_EMAIL) ) $cerr['email'] = 'Please enter a valid email.'; if( !$phone ) $cerr['phone'] = 'Please enter your phone number.'; if( !$comments ) $cerr['comments'] = 'Please enter your question / comments.'; if( !$captcha || (md5($captcha) != $captcha_cnf) ) $cerr['captcha'] = 'Please enter the correct answer.'; if( count($cerr) == 0 ){ $subject = $atts['title']; $headers = "From: ".$name." <" . strip_tags($email) . ">\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $message = '<html><body> <table> <tr><td>Name: </td><td>'.$name.'</td></tr> <tr><td>Email: </td><td>'.$email.'</td></tr> <tr><td>Phone: </td><td>'.$phone.'</td></tr> <tr><td>Website: </td><td>'.$website.'</td></tr> <tr><td>Comments: </td><td>'.$comments.'</td></tr> </table> </body> </html>'; mail( $atts['to_email'], $subject, $message, $headers); $cform .= '<div class="success_msg">Thank you! A representative will get back to you very shortly.</div>'; unset( $name, $email, $phone, $website, $comments, $captcha ); }else{ $cform .= '<div class="error_msg">'; $cform .= implode('<br />',$cerr); $cform .= '</div>'; } } $capNum1 = rand(1,4); $capNum2 = rand(1,5); $capSum = $capNum1 + $capNum2; $sumStr = $capNum1." + ".$capNum2 ." = "; $cform .= "<form name=\"contactform\" action=\"#contactform_main\" method=\"post\"> <p class=\"left\"><input type=\"text\" name=\"c_name\" value=\"". ( ( empty($name) == false ) ? $name : "" ) ."\" placeholder=\"Name\" /></p> <p class=\"right\"><input type=\"email\" name=\"c_email\" value=\"". ( ( empty($email) == false ) ? $email : "" ) ."\" placeholder=\"Email\" /></p><div class=\"clear\"></div> <p class=\"left\"><input type=\"tel\" name=\"c_phone\" value=\"". ( ( empty($phone) == false ) ? $phone : "" ) ."\" placeholder=\"Phone\" /></p> <p class=\"right\"><input type=\"url\" name=\"c_website\" value=\"". ( ( empty($website) == false ) ? $website : "" ) ."\" placeholder=\"Website with prefix http://\" /></p><div class=\"clear\"></div> <p><textarea name=\"c_comments\" placeholder=\"Message\">". ( ( empty($comments) == false ) ? $comments : "" ) ."</textarea></p>"; $cform .= "<br /><p class=\"left\">$sumStr<input style=\"width:200px;\" type=\"text\" placeholder=\"Captcha\" value=\"". ( ( empty($captcha) == false ) ? $captcha : "" ) ."\" name=\"c_captcha\" /><input type=\"hidden\" name=\"c_captcha_confirm\" value=\"". md5($capSum)."\"></p><div class=\"clear\"></div>"; $cform .= "<p class=\"sub\"><input type=\"submit\" name=\"c_submit\" value=\"Submit\" /></p> </form> </div>"; return $cform;} add_shortcode( 'contactform', 'contactform_func' ); ```
The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.
279,455
<p>There seem to be countless custom query pagination questions on here, so glad to know I'm not the only one struggling with it. Have tried following the answers in those questions but so far no luck.</p> <p>I have a custom post type, say Galleries. Each post has a title, and an Advanced Custom Field Gallery field that includes images. When on one of those posts currently it shows the linked titles for the first 12 posts to the right of the images. This means you never get to see past the 12th. I could change the 12 to -1 to show all, but list would go on for a while. </p> <p>Hoping to add pagination, so if you are on the first post, under the list on the right would said, "more" and would take you to the 13th post, and the list on the right would now show linked titles for 13 to 24. And there would be a prev button and a more button. Prev would go back to first page and show 1 12 titles, and more would take you to 25th post and show 25 to 36 and so on.</p> <p>I've tried adding pagination in various way to accomplish that but with no luck. Some questions I thought looked right but gave errors. Is pagination the right way, or should I be developing a custom if else statements or such to accomplish this?</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div id="main"&gt; &lt;div id="gallery-viewer"&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php $images = get_field('gallery_images'); if( $images ): ?&gt; &lt;ul class="thumbs"&gt; &lt;?php foreach( $images as $image ): ?&gt; &lt;li&gt; &lt;a href="&lt;?php echo $image['url']; ?&gt;"&gt; &lt;img src="&lt;?php echo $image['sizes']['gallery-landscape-thb']; ?&gt;" alt="&lt;?php echo $image['alt']; ?&gt;" /&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;div class="places"&gt; &lt;ul class="plist selected first"&gt; &lt;?php $custom_query = new WP_Query( array( 'post_type' =&gt; 'customers_gallery', 'posts_per_page' =&gt; 12, 'paged' =&gt; $paged ) ); if ( $custom_query-&gt;have_posts() ) : while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; wp_reset_query(); ?&gt; &lt;/ul&gt; // Add Pagination &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- /#main --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 280923, "author": "SEO DEVS", "author_id": 111163, "author_profile": "https://wordpress.stackexchange.com/users/111163", "pm_score": 2, "selected": false, "text": "<p>The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.</p>\n" }, { "answer_id": 280933, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 1, "selected": false, "text": "<p>you can use Caption Shortcode on the image you want change caption like:</p>\n\n<pre><code>[caption]&lt;image&gt; Caption[/caption]\n</code></pre>\n\n<p>This is primarily used with individual images caption change.</p>\n\n<p>for detail information how to use caption shortcode check <a href=\"https://codex.wordpress.org/Caption_Shortcode\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>update#1 25-9-2017</p>\n\n<p>in above answer i clear that This is primarily used with individual images caption change.</p>\n\n<p>but if you want to change image caption inside gallery group ,i think you can achieve this manually by jquery (i think it's the easyist way to do it )like so:</p>\n\n<p>1-open any *.js file that already enqueued in your gallery page.\n( *.js file you can find in page source) </p>\n\n<p>2-put this little piece of code in </p>\n\n<pre><code> ( function( $ ) { \n function function_name() {\n $( '#gallery-&lt;gallery_ID&gt;-&lt;image_ID&gt;').text(\"new caption\");\n }\n\n function_name();\n } )( jQuery );\n</code></pre>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5465/" ]
There seem to be countless custom query pagination questions on here, so glad to know I'm not the only one struggling with it. Have tried following the answers in those questions but so far no luck. I have a custom post type, say Galleries. Each post has a title, and an Advanced Custom Field Gallery field that includes images. When on one of those posts currently it shows the linked titles for the first 12 posts to the right of the images. This means you never get to see past the 12th. I could change the 12 to -1 to show all, but list would go on for a while. Hoping to add pagination, so if you are on the first post, under the list on the right would said, "more" and would take you to the 13th post, and the list on the right would now show linked titles for 13 to 24. And there would be a prev button and a more button. Prev would go back to first page and show 1 12 titles, and more would take you to 25th post and show 25 to 36 and so on. I've tried adding pagination in various way to accomplish that but with no luck. Some questions I thought looked right but gave errors. Is pagination the right way, or should I be developing a custom if else statements or such to accomplish this? ``` <?php get_header(); ?> <div id="main"> <div id="gallery-viewer"> <h3><?php the_title(); ?></h3> <?php $images = get_field('gallery_images'); if( $images ): ?> <ul class="thumbs"> <?php foreach( $images as $image ): ?> <li> <a href="<?php echo $image['url']; ?>"> <img src="<?php echo $image['sizes']['gallery-landscape-thb']; ?>" alt="<?php echo $image['alt']; ?>" /> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> <div class="places"> <ul class="plist selected first"> <?php $custom_query = new WP_Query( array( 'post_type' => 'customers_gallery', 'posts_per_page' => 12, 'paged' => $paged ) ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> <?php endif; wp_reset_query(); ?> </ul> // Add Pagination </div> </div> </div><!-- /#main --> <?php get_footer(); ?> ```
The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.
279,493
<p>So I am working on a website. I'd like it so that on the interior pages of the site, there is a different title and subtitle representing that page. Unfortunately, the theme I am working with doesn't originally have the heading in the header but in the content area. </p> <p><strong>The solution I want:</strong> I want to create a global title and subtitle within the header that changes with each page. Blog, Contact, etc.</p> <p><strong>Things I have tried:</strong></p> <ol> <li><p>Looked to see if there were any plugins. Tried GP Hooks, only seemed to work for the theme generatePress. Others didn't work the way I'd hoped.</p></li> <li><p>I tried to edit the header.php file by adding this div:</p> <p><code>&lt;div class="row"&gt;&lt;div class="heading col-md-12 col-sm-12 col-xs-12"&gt;&lt;h1&gt;&lt;?php echo $pageTitle ?&gt;&lt;/h1&gt;&lt;/div&gt;&lt;/div&gt;</code> </p></li> </ol> <p>then I went in the child theme and added this code to the functions.php file:</p> <pre><code>if (body_class === page-id-2){ $pageTitle = 'THE CROSS LIFE'; } </code></pre> <p>I know this is probably the wrong way to do this but I was trying to see if this would work for a particular page. I'm still studying coding and javascript so some much-needed help would be appreciated. Am I doing the if statement wrong? Or is there a way to do this that I'm completely ignorant about?</p> <p><strong>website</strong>: <a href="http://yourcrosslife.com/test/sample-page/" rel="nofollow noreferrer">http://yourcrosslife.com/test/sample-page/</a></p>
[ { "answer_id": 280923, "author": "SEO DEVS", "author_id": 111163, "author_profile": "https://wordpress.stackexchange.com/users/111163", "pm_score": 2, "selected": false, "text": "<p>The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.</p>\n" }, { "answer_id": 280933, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 1, "selected": false, "text": "<p>you can use Caption Shortcode on the image you want change caption like:</p>\n\n<pre><code>[caption]&lt;image&gt; Caption[/caption]\n</code></pre>\n\n<p>This is primarily used with individual images caption change.</p>\n\n<p>for detail information how to use caption shortcode check <a href=\"https://codex.wordpress.org/Caption_Shortcode\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>update#1 25-9-2017</p>\n\n<p>in above answer i clear that This is primarily used with individual images caption change.</p>\n\n<p>but if you want to change image caption inside gallery group ,i think you can achieve this manually by jquery (i think it's the easyist way to do it )like so:</p>\n\n<p>1-open any *.js file that already enqueued in your gallery page.\n( *.js file you can find in page source) </p>\n\n<p>2-put this little piece of code in </p>\n\n<pre><code> ( function( $ ) { \n function function_name() {\n $( '#gallery-&lt;gallery_ID&gt;-&lt;image_ID&gt;').text(\"new caption\");\n }\n\n function_name();\n } )( jQuery );\n</code></pre>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127514/" ]
So I am working on a website. I'd like it so that on the interior pages of the site, there is a different title and subtitle representing that page. Unfortunately, the theme I am working with doesn't originally have the heading in the header but in the content area. **The solution I want:** I want to create a global title and subtitle within the header that changes with each page. Blog, Contact, etc. **Things I have tried:** 1. Looked to see if there were any plugins. Tried GP Hooks, only seemed to work for the theme generatePress. Others didn't work the way I'd hoped. 2. I tried to edit the header.php file by adding this div: `<div class="row"><div class="heading col-md-12 col-sm-12 col-xs-12"><h1><?php echo $pageTitle ?></h1></div></div>` then I went in the child theme and added this code to the functions.php file: ``` if (body_class === page-id-2){ $pageTitle = 'THE CROSS LIFE'; } ``` I know this is probably the wrong way to do this but I was trying to see if this would work for a particular page. I'm still studying coding and javascript so some much-needed help would be appreciated. Am I doing the if statement wrong? Or is there a way to do this that I'm completely ignorant about? **website**: <http://yourcrosslife.com/test/sample-page/>
The caption is stored in the image data. The only way to achieve what you require is to use multiple copies of the image and change the image data on each image. To better understand image data go ahead and download an image to your desktop then right click it, go to properties then the details tab. this is where the image meta data is set. WordPress does has a few image meta settings but does not cover all of them. I feel its better to compress images on a pc or mac using Caesium image compressor then once compressed then change the image meta on your PC or mac. Google does not like sites to use the same image multiple times on different pages as this should be put into a sprite image. Sorry to be the barer of bad news but I hope it helps you better understand image meta.
279,498
<p>I've created a custom taxonomy (locations) which is hierarchical, and would like to: a) display an unordered list that respects the hierarchy AND b)customize the display output so that I can specify a custom url</p> <p>Here's the code I'm using, including the two different ways I'm outputting. </p> <pre><code>&lt;?php $args = array( 'taxonomy' =&gt; 'locations', 'orderby' =&gt; 'name', 'hide_empty' =&gt; 0, 'title_li' =&gt; '', 'hierarchical' =&gt; 1, 'walker' =&gt; null, ); ?&gt; // The following gives me the hierarchical display &lt;ul class="menu"&gt; &lt;?php wp_list_categories( $args ); ?&gt; &lt;/ul&gt; // And this gives me the customized links &lt;?php $categories = get_categories($args); foreach($categories as $category) { echo '&lt;li&gt;&lt;a href="http://website.com/?ls=&amp;location=' . $category-&gt;slug . '"&gt;' . $category-&gt;name.'&lt;/a&gt;&lt;/li&gt;'; } ?&gt; </code></pre> <p>The problem is making BOTH of those things happen. </p> <p>Any solutions? I'm guessing it might be a custom Walker, but I'm not savvy enough to figure that out without a little guidance!!</p>
[ { "answer_id": 279499, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>I may be mis-understanding but you don't need wp_list_categories for this. (also your coding is missing some details).</p>\n\n<p>Will this work?:</p>\n\n<pre><code>&lt;?php \n$args = array(\n'taxonomy' =&gt; 'locations',\n'orderby' =&gt; 'name',\n'hide_empty' =&gt; 0,\n);\n?&gt; \n\n// And this gives me the customized links\n\n&lt;?php \n$categories = get_categories($args);\necho '&lt;ul class=\"menu\"&gt;';\nforeach($categories as $category) { \n echo '&lt;li&gt;&lt;a href=\"http://website.com/?ls=&amp;location=' . $category-&gt;slug . '\"&gt;' . $category-&gt;name.'&lt;/a&gt;&lt;/li&gt;';\n} \necho '&lt;/ul&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 279501, "author": "jwyson", "author_id": 127524, "author_profile": "https://wordpress.stackexchange.com/users/127524", "pm_score": 1, "selected": false, "text": "<p>Solved it with the following Custom Walker:</p>\n\n<pre><code>class CustomWalker extends Walker_Category {\nfunction start_el(&amp;$output, $item, $depth=0, $args=array()) { \n$output .= \"\\n&lt;li&gt;&lt;a href=\\\"http://website.com/?ls=&amp;location=\" . $item-&gt;slug . \"\\\"&gt;\".esc_attr($item-&gt;name);\n} \n\nfunction end_el(&amp;$output, $item, $depth=0, $args=array()) { \n$output .= \"&lt;/li&gt;\\n\"; \n} \n} \n</code></pre>\n" } ]
2017/09/08
[ "https://wordpress.stackexchange.com/questions/279498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127524/" ]
I've created a custom taxonomy (locations) which is hierarchical, and would like to: a) display an unordered list that respects the hierarchy AND b)customize the display output so that I can specify a custom url Here's the code I'm using, including the two different ways I'm outputting. ``` <?php $args = array( 'taxonomy' => 'locations', 'orderby' => 'name', 'hide_empty' => 0, 'title_li' => '', 'hierarchical' => 1, 'walker' => null, ); ?> // The following gives me the hierarchical display <ul class="menu"> <?php wp_list_categories( $args ); ?> </ul> // And this gives me the customized links <?php $categories = get_categories($args); foreach($categories as $category) { echo '<li><a href="http://website.com/?ls=&location=' . $category->slug . '">' . $category->name.'</a></li>'; } ?> ``` The problem is making BOTH of those things happen. Any solutions? I'm guessing it might be a custom Walker, but I'm not savvy enough to figure that out without a little guidance!!
Solved it with the following Custom Walker: ``` class CustomWalker extends Walker_Category { function start_el(&$output, $item, $depth=0, $args=array()) { $output .= "\n<li><a href=\"http://website.com/?ls=&location=" . $item->slug . "\">".esc_attr($item->name); } function end_el(&$output, $item, $depth=0, $args=array()) { $output .= "</li>\n"; } } ```
279,533
<p>I am trying to create a simple form on one of my wordpress pages. The code used is as basic as it can be, namely the following:</p> <pre><code>&lt;form action="" method="GET"&gt; &lt;select&gt; &lt;option value="test" &gt;test&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="search"&gt; &lt;/form&gt; </code></pre> <p>the problem is, every time i click the search button, i get redirected to the homepage! Shouldn't this small little form be redirected to the page containing the form, since action is empty?</p>
[ { "answer_id": 279564, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Try</p>\n\n<pre><code>&lt;form action=\"#\" method=\"GET\"&gt;\n</code></pre>\n\n<p>(Although I prefer the POST method.)</p>\n" }, { "answer_id": 279588, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>Alright guys, believe it or not, but the underlying problem had to do with permissions on the root folder!</p>\n\n<p>the aforementioned <code>&lt;form action=\"#\" method=\"GET\"&gt;</code> didn't work either, so i digged a little deeper, and i found out certain pages couldn't be opened either.</p>\n\n<p>Why this causes every single simple form to be redirected to home is beyond me, but the solution was to change the permissions of the .htaccess file (which WAS present by the way), to 775.</p>\n\n<p>Out of caution i also changed the root folder permission to 775, and all is well now.</p>\n" } ]
2017/09/09
[ "https://wordpress.stackexchange.com/questions/279533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am trying to create a simple form on one of my wordpress pages. The code used is as basic as it can be, namely the following: ``` <form action="" method="GET"> <select> <option value="test" >test</option> </select> <input type="submit" value="search"> </form> ``` the problem is, every time i click the search button, i get redirected to the homepage! Shouldn't this small little form be redirected to the page containing the form, since action is empty?
Alright guys, believe it or not, but the underlying problem had to do with permissions on the root folder! the aforementioned `<form action="#" method="GET">` didn't work either, so i digged a little deeper, and i found out certain pages couldn't be opened either. Why this causes every single simple form to be redirected to home is beyond me, but the solution was to change the permissions of the .htaccess file (which WAS present by the way), to 775. Out of caution i also changed the root folder permission to 775, and all is well now.
279,556
<p>I installed the "JWT Authentication for WP REST API" plugin for user authentication through an Ionic app. Although authentication was successful, attempting to find a way to register users from the mobile app proved to be a particularly difficult task.</p> <p>Is there a way to register users from the API given by WordPress? Or is there some preferred way to implement this on the admin console to enable this behavior?</p> <p>I'm completely helpless here. The data is 'POST'ed through query parameters to the base url, and gives a 302 response, but when I resend the request through Fiddler it gives a 200 OK. And when I attempt to replicate the request on Postman it also gives a 200 OK.</p> <p>I considered the JSON API plugin with the JSON API USER plugin route, but these don't seem to be under active development. I've read somewhere this gets done with GET and a cookie or something?</p>
[ { "answer_id": 279558, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>The JSON API plugin is not needed, as the REST API is part of WordPress core (as of about Version 4.7, if I recall correctly).</p>\n\n<p><a href=\"https://developer.wordpress.org/rest-api/reference/users/#create-a-user\" rel=\"nofollow noreferrer\">You can indeed create a user via WordPress's REST API</a> — you pass a <code>POST</code> request to the server with the appropriate arguments. The <code>POST</code> data must include, at a minimum, the user's username, email, and password.</p>\n\n<p>Note that you'll need to be <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"nofollow noreferrer\">authenticated</a> in order to create a user. </p>\n\n<h1>References</h1>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/rest-api/reference/users/#create-a-user\" rel=\"nofollow noreferrer\">REST API » Create a User</a></li>\n<li><a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"nofollow noreferrer\">REST API » Authentication</a></li>\n</ul>\n\n<p>Caveat: I have not done this myself, but according to the documentation it should be possible.</p>\n" }, { "answer_id": 321756, "author": "Tim Hallman", "author_id": 38375, "author_profile": "https://wordpress.stackexchange.com/users/38375", "pm_score": 1, "selected": false, "text": "<p>This does not use the API, but it's a script I've used a hundred times over the years, always works. Simply drop it in the root of your install and then access the file directly. Remember to delete the file immediately afterward. I do not remember where I originally obtained this script.</p>\n\n<pre><code>&lt;?php\n// ADD NEW ADMIN USER TO WORDPRESS\n// ----------------------------------\n// Put this file in your Wordpress root directory and run it from your browser.\n// Delete it when you're done.\nrequire_once('wp-blog-header.php');\nrequire_once('wp-includes/registration.php');\n// ----------------------------------------------------\n// CONFIG VARIABLES\n// Make sure that you set these before running the file.\n$newusername = 'your_username';\n$newpassword = 'youer_password';\n$newemail = '[email protected]';\n// ----------------------------------------------------\n// This is just a security precaution, to make sure the above \"Config Variables\" \n// have been changed from their default values.\nif ( $newpassword != 'YOURPASSWORD' &amp;&amp;\n $newemail != '[email protected]' &amp;&amp;\n $newusername !='YOURUSERNAME' )\n{\n // Check that user doesn't already exist \n if ( !username_exists($newusername) &amp;&amp; !email_exists($newemail) )\n {\n // Create user and set role to administrator\n $user_id = wp_create_user( $newusername, $newpassword, $newemail);\n if ( is_int($user_id) )\n {\n $wp_user_object = new WP_User($user_id);\n $wp_user_object-&gt;set_role('administrator');\n echo 'Successfully created new admin user. Now delete this file!';\n }\n else {\n echo 'Error with wp_insert_user. No users were created.';\n }\n }\n else {\n echo 'This user or email already exists. Nothing was done.';\n }\n}\nelse {\n echo 'Whoops, looks like you did not set a password, username, or email';\n echo 'before running the script. Set these variables and try again.';\n}\n</code></pre>\n" } ]
2017/09/09
[ "https://wordpress.stackexchange.com/questions/279556", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127571/" ]
I installed the "JWT Authentication for WP REST API" plugin for user authentication through an Ionic app. Although authentication was successful, attempting to find a way to register users from the mobile app proved to be a particularly difficult task. Is there a way to register users from the API given by WordPress? Or is there some preferred way to implement this on the admin console to enable this behavior? I'm completely helpless here. The data is 'POST'ed through query parameters to the base url, and gives a 302 response, but when I resend the request through Fiddler it gives a 200 OK. And when I attempt to replicate the request on Postman it also gives a 200 OK. I considered the JSON API plugin with the JSON API USER plugin route, but these don't seem to be under active development. I've read somewhere this gets done with GET and a cookie or something?
This does not use the API, but it's a script I've used a hundred times over the years, always works. Simply drop it in the root of your install and then access the file directly. Remember to delete the file immediately afterward. I do not remember where I originally obtained this script. ``` <?php // ADD NEW ADMIN USER TO WORDPRESS // ---------------------------------- // Put this file in your Wordpress root directory and run it from your browser. // Delete it when you're done. require_once('wp-blog-header.php'); require_once('wp-includes/registration.php'); // ---------------------------------------------------- // CONFIG VARIABLES // Make sure that you set these before running the file. $newusername = 'your_username'; $newpassword = 'youer_password'; $newemail = '[email protected]'; // ---------------------------------------------------- // This is just a security precaution, to make sure the above "Config Variables" // have been changed from their default values. if ( $newpassword != 'YOURPASSWORD' && $newemail != '[email protected]' && $newusername !='YOURUSERNAME' ) { // Check that user doesn't already exist if ( !username_exists($newusername) && !email_exists($newemail) ) { // Create user and set role to administrator $user_id = wp_create_user( $newusername, $newpassword, $newemail); if ( is_int($user_id) ) { $wp_user_object = new WP_User($user_id); $wp_user_object->set_role('administrator'); echo 'Successfully created new admin user. Now delete this file!'; } else { echo 'Error with wp_insert_user. No users were created.'; } } else { echo 'This user or email already exists. Nothing was done.'; } } else { echo 'Whoops, looks like you did not set a password, username, or email'; echo 'before running the script. Set these variables and try again.'; } ```
279,627
<p>As for now, my CSS hierarchy goes like this:</p> <p>Theme > plugins (mainly page builders) > Child theme.</p> <p>How to load all plugins CSS last in hierarchy?</p>
[ { "answer_id": 279644, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>It depends on when you execute the wp_enqueue_scripts action. You need to include priority parameter and set to it some high number:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_enqueue_scripts', 10000);\nfunction my_enqueue_scripts() {\n // enqueue files //\n}\n</code></pre>\n\n<p>This means that the files enqueued with this function will be added very late, and if no other plugin/theme registers enqueue with a higher number, styles registered here will load at the end of the HEAD after all other CSS files.</p>\n" }, { "answer_id": 279678, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 2, "selected": false, "text": "<p>You have 3 options:</p>\n\n<p><strong>Option 1</strong>:<br>\nUsing dependencies, first of all get the style <code>handler</code>, if you have access to the file you can grab it from the <code>wp_enqueue_style</code> function, if not, inspect the HTML code and find the <code>id</code> the handler its the <code>id</code> without the <code>-css</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/L0Wj1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L0Wj1.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>then either if you are using <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> or <a href=\"https://developer.wordpress.org/reference/functions/wp_register_style/\" rel=\"nofollow noreferrer\">wp_register_style</a>, there is a param called <code>$deps</code> which is an array of dependencies for the CSS file, here its an example of a child theme loading the parent CSS file as a dependency, so it loads first:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( 'parent-style' ), //HERE THE HANDLE OF THE CSS FILE I WANT TO LOAD FIRST\n wp_get_theme()-&gt;get('Version')\n );\n}\n</code></pre>\n\n<p><strong>Option 2</strong>:<br>\nUsing the priority of execution in the list of attached actions to a hook, there is a <code>$priority</code> parameter in the <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action</a> function, by default the value its 10. You could either set it to 20 if you see the theme CSS its not setting it, or if you have access to the theme files set it to ssay 20 and set your plugin to 30, if not just set it to a higher number like <code>9999</code> there is no limits and no performance penalties:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style', 9999 );\n</code></pre>\n\n<p><strong>Option 3</strong>:<br>\nUsing the order of the <code>hook</code>, you can add your <code>enqueue function</code> to the <code>wp_footer</code> action, making sure the theme CSS file is loading in the <code>wp_head</code> </p>\n\n<pre><code>add_action( 'wp_footer', 'load_my_css_file' );\n</code></pre>\n\n<p>So the theme CSS file will load in the <code>&lt;head&gt;</code> and the plugin CSS file will load later in the footer.</p>\n" } ]
2017/09/11
[ "https://wordpress.stackexchange.com/questions/279627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127625/" ]
As for now, my CSS hierarchy goes like this: Theme > plugins (mainly page builders) > Child theme. How to load all plugins CSS last in hierarchy?
You have 3 options: **Option 1**: Using dependencies, first of all get the style `handler`, if you have access to the file you can grab it from the `wp_enqueue_style` function, if not, inspect the HTML code and find the `id` the handler its the `id` without the `-css` [![enter image description here](https://i.stack.imgur.com/L0Wj1.jpg)](https://i.stack.imgur.com/L0Wj1.jpg) then either if you are using [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) or [wp\_register\_style](https://developer.wordpress.org/reference/functions/wp_register_style/), there is a param called `$deps` which is an array of dependencies for the CSS file, here its an example of a child theme loading the parent CSS file as a dependency, so it loads first: ``` function my_theme_enqueue_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ), //HERE THE HANDLE OF THE CSS FILE I WANT TO LOAD FIRST wp_get_theme()->get('Version') ); } ``` **Option 2**: Using the priority of execution in the list of attached actions to a hook, there is a `$priority` parameter in the [add\_action](https://developer.wordpress.org/reference/functions/add_action/) function, by default the value its 10. You could either set it to 20 if you see the theme CSS its not setting it, or if you have access to the theme files set it to ssay 20 and set your plugin to 30, if not just set it to a higher number like `9999` there is no limits and no performance penalties: ``` add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style', 9999 ); ``` **Option 3**: Using the order of the `hook`, you can add your `enqueue function` to the `wp_footer` action, making sure the theme CSS file is loading in the `wp_head` ``` add_action( 'wp_footer', 'load_my_css_file' ); ``` So the theme CSS file will load in the `<head>` and the plugin CSS file will load later in the footer.
279,630
<p>I see that this is a big problem, not only related to the Wordpress but any other software where third-party add-ons, plugins are loosing support from original author.</p> <p>But let's focus on Wordpress... According to WordFence there is:</p> <blockquote> <p><strong>17,383 of those plugins have not been updated in the past 2 years.</strong></p> <p><strong>3,990 plugins have not been updated since 2010 which is over 7 years ago.</strong></p> </blockquote> <p>According to Isabel’s post there are several plugins that have a large install base that haven’t been updated for some time:</p> <blockquote> <p><em>“Exec-PHP plugin by Sören Weber has over 100,000 active installs despite that it has not been updated since June of 2009. Category Order by Wessley Roche has over 90,000 active installs even though it was last updated in May of 2008. Ultimate Google Analytics by Wilfred van der Deijl has over 80,000 installs even though it was last updated more than nine years ago.”</em></p> </blockquote> <p>Beside bad coding which many times lead to newly discovered vulnerabilities, and not only that, many authors are leaving their project without any support, some of them are responding, the other one are completely gone.</p> <p>There was also a problem with expired domain, here is an article: <strong><a href="https://blog.sucuri.net/2017/08/expired-domain-wordpress-plugin-redirects.html" rel="nofollow noreferrer">Expired Domain Leads to WordPress Plugin Redirects</a></strong></p> <p>So what can users do in order to prevent this problem, is there any option which will alert users if add-on is vulnerable but there is no update for it?</p>
[ { "answer_id": 279644, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>It depends on when you execute the wp_enqueue_scripts action. You need to include priority parameter and set to it some high number:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_enqueue_scripts', 10000);\nfunction my_enqueue_scripts() {\n // enqueue files //\n}\n</code></pre>\n\n<p>This means that the files enqueued with this function will be added very late, and if no other plugin/theme registers enqueue with a higher number, styles registered here will load at the end of the HEAD after all other CSS files.</p>\n" }, { "answer_id": 279678, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 2, "selected": false, "text": "<p>You have 3 options:</p>\n\n<p><strong>Option 1</strong>:<br>\nUsing dependencies, first of all get the style <code>handler</code>, if you have access to the file you can grab it from the <code>wp_enqueue_style</code> function, if not, inspect the HTML code and find the <code>id</code> the handler its the <code>id</code> without the <code>-css</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/L0Wj1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L0Wj1.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>then either if you are using <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> or <a href=\"https://developer.wordpress.org/reference/functions/wp_register_style/\" rel=\"nofollow noreferrer\">wp_register_style</a>, there is a param called <code>$deps</code> which is an array of dependencies for the CSS file, here its an example of a child theme loading the parent CSS file as a dependency, so it loads first:</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( 'parent-style' ), //HERE THE HANDLE OF THE CSS FILE I WANT TO LOAD FIRST\n wp_get_theme()-&gt;get('Version')\n );\n}\n</code></pre>\n\n<p><strong>Option 2</strong>:<br>\nUsing the priority of execution in the list of attached actions to a hook, there is a <code>$priority</code> parameter in the <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action</a> function, by default the value its 10. You could either set it to 20 if you see the theme CSS its not setting it, or if you have access to the theme files set it to ssay 20 and set your plugin to 30, if not just set it to a higher number like <code>9999</code> there is no limits and no performance penalties:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style', 9999 );\n</code></pre>\n\n<p><strong>Option 3</strong>:<br>\nUsing the order of the <code>hook</code>, you can add your <code>enqueue function</code> to the <code>wp_footer</code> action, making sure the theme CSS file is loading in the <code>wp_head</code> </p>\n\n<pre><code>add_action( 'wp_footer', 'load_my_css_file' );\n</code></pre>\n\n<p>So the theme CSS file will load in the <code>&lt;head&gt;</code> and the plugin CSS file will load later in the footer.</p>\n" } ]
2017/09/11
[ "https://wordpress.stackexchange.com/questions/279630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91550/" ]
I see that this is a big problem, not only related to the Wordpress but any other software where third-party add-ons, plugins are loosing support from original author. But let's focus on Wordpress... According to WordFence there is: > > **17,383 of those plugins have not been updated in the past 2 years.** > > > **3,990 plugins have not been updated since 2010 which is over 7 years > ago.** > > > According to Isabel’s post there are several plugins that have a large install base that haven’t been updated for some time: > > *“Exec-PHP plugin by Sören Weber has over 100,000 active installs > despite that it has not been updated since June of 2009. Category > Order by Wessley Roche has over 90,000 active installs even though it > was last updated in May of 2008. Ultimate Google Analytics by Wilfred > van der Deijl has over 80,000 installs even though it was last updated > more than nine years ago.”* > > > Beside bad coding which many times lead to newly discovered vulnerabilities, and not only that, many authors are leaving their project without any support, some of them are responding, the other one are completely gone. There was also a problem with expired domain, here is an article: **[Expired Domain Leads to WordPress Plugin Redirects](https://blog.sucuri.net/2017/08/expired-domain-wordpress-plugin-redirects.html)** So what can users do in order to prevent this problem, is there any option which will alert users if add-on is vulnerable but there is no update for it?
You have 3 options: **Option 1**: Using dependencies, first of all get the style `handler`, if you have access to the file you can grab it from the `wp_enqueue_style` function, if not, inspect the HTML code and find the `id` the handler its the `id` without the `-css` [![enter image description here](https://i.stack.imgur.com/L0Wj1.jpg)](https://i.stack.imgur.com/L0Wj1.jpg) then either if you are using [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) or [wp\_register\_style](https://developer.wordpress.org/reference/functions/wp_register_style/), there is a param called `$deps` which is an array of dependencies for the CSS file, here its an example of a child theme loading the parent CSS file as a dependency, so it loads first: ``` function my_theme_enqueue_styles() { wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ), //HERE THE HANDLE OF THE CSS FILE I WANT TO LOAD FIRST wp_get_theme()->get('Version') ); } ``` **Option 2**: Using the priority of execution in the list of attached actions to a hook, there is a `$priority` parameter in the [add\_action](https://developer.wordpress.org/reference/functions/add_action/) function, by default the value its 10. You could either set it to 20 if you see the theme CSS its not setting it, or if you have access to the theme files set it to ssay 20 and set your plugin to 30, if not just set it to a higher number like `9999` there is no limits and no performance penalties: ``` add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style', 9999 ); ``` **Option 3**: Using the order of the `hook`, you can add your `enqueue function` to the `wp_footer` action, making sure the theme CSS file is loading in the `wp_head` ``` add_action( 'wp_footer', 'load_my_css_file' ); ``` So the theme CSS file will load in the `<head>` and the plugin CSS file will load later in the footer.
279,631
<p>How to get product rating by product_id without loop?</p> <p>I have one product_id and i want get product rating, how can I do this and it is feasible? Thank</p>
[ { "answer_id": 279634, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 5, "selected": true, "text": "<p>Given a product ID you can get the average rating like this:</p>\n\n<pre><code>$product = wc_get_product( $product_id );\n$rating = $product-&gt;get_average_rating();\n</code></pre>\n\n<p>That'll return the raw number (4.00, 3.50 etc.).</p>\n\n<p>To output the rating HTML for a given product you can use this code:</p>\n\n<pre><code>$product = wc_get_product( $product_id );\n$rating = $product-&gt;get_average_rating();\n$count = $product-&gt;get_rating_count();\n\necho wc_get_rating_html( $rating, $count );\n</code></pre>\n\n<p>Or, if you're in the loop you can use this function to get the HTML for the current product:</p>\n\n<pre><code>woocommerce_template_loop_rating() \n</code></pre>\n" }, { "answer_id": 319530, "author": "Samael Pereira SImões", "author_id": 154276, "author_profile": "https://wordpress.stackexchange.com/users/154276", "pm_score": 1, "selected": false, "text": "<p>This helped me a lot, create the get_star_rating () function and return your html.</p>\n\n<p>NOTE: If it is in a loop</p>\n\n<pre><code>function get_star_rating() {\n\n global $woocommerce, $product; \n\n $average = $product-&gt;get_average_rating();\n $review_count = $product-&gt;get_review_count();\n\n return '&lt;div class=\"star-rating\"&gt;\n &lt;span style=\"width:'.( ( $average / 5 ) * 100 ) . '%\" title=\"'. \n $average.'\"&gt;\n &lt;strong itemprop=\"ratingValue\" class=\"rating\"&gt;'.$average.'&lt;/strong&gt; '.__( 'out of 5', 'woocommerce' ). \n '&lt;/span&gt; \n &lt;/div&gt;'.'\n &lt;a href=\"#reviews\" class=\"woocommerce-review-link\" rel=\"nofollow\"&gt;( ' . $review_count .' )&lt;/a&gt;';\n\n}\n</code></pre>\n" }, { "answer_id": 346886, "author": "Tarani Joshi", "author_id": 174838, "author_profile": "https://wordpress.stackexchange.com/users/174838", "pm_score": 1, "selected": false, "text": "<p>You can fetch loop top rating product </p>\n\n<pre><code>$args_top_rating1 = array(\n 'post_type' =&gt; 'product',\n 'meta_key' =&gt; '_wc_average_rating',\n 'orderby' =&gt; 'meta_value',\n 'posts_per_page' =&gt; 8,\n 'status'=&gt;'publish',\n 'catalog_visibility'=&gt;'visible',\n 'stock_status'=&gt;'instock'\n);\n\n$top_rating = new WP_Query( $args_top_rating1 );\n\n\n while ( $top_rating-&gt;have_posts() ) : $top_rating-&gt;the_post(); global $product; \n\n $urltop_rating = get_permalink($top_rating-&gt;post-&gt;ID) ;\n\n$rating_count = $product-&gt;get_rating_count();\n\n$average_rating = $product-&gt;get_average_rating();\n\necho wc_get_rating_html( $average_rating, $rating_count); \n\n\nendwhile;\n</code></pre>\n" } ]
2017/09/11
[ "https://wordpress.stackexchange.com/questions/279631", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91856/" ]
How to get product rating by product\_id without loop? I have one product\_id and i want get product rating, how can I do this and it is feasible? Thank
Given a product ID you can get the average rating like this: ``` $product = wc_get_product( $product_id ); $rating = $product->get_average_rating(); ``` That'll return the raw number (4.00, 3.50 etc.). To output the rating HTML for a given product you can use this code: ``` $product = wc_get_product( $product_id ); $rating = $product->get_average_rating(); $count = $product->get_rating_count(); echo wc_get_rating_html( $rating, $count ); ``` Or, if you're in the loop you can use this function to get the HTML for the current product: ``` woocommerce_template_loop_rating() ```
279,683
<p>I have a page that lists some custom posts and the they are not showing in the correct Alphabetical order. As a test I have also tried listing them in order of there Ids and that does not appear in the correct order either. When it's listed as Ids they appear as if they grouped into 3 groups high numbers in the 4000s, below 200 and then 3000s, it's very odd. It works fine on my local server. Also ordering works fine in the Wordpress back end. The problem appears to happened when I moved the site to a new hosting package on 1&amp;1. Has any had server specific ordering issues before?</p> <p>I've made 2 test pages that show a simple list of just titles and IDs (in the wrong order) ID order: <a href="http://www.realpatisserie.co.uk/allergen-list/allergen-list-test-id/" rel="nofollow noreferrer">http://www.realpatisserie.co.uk/allergen-list/allergen-list-test-id/</a> title order: <a href="http://www.realpatisserie.co.uk/allergen-list/allergen-list-test/" rel="nofollow noreferrer">http://www.realpatisserie.co.uk/allergen-list/allergen-list-test/</a></p> <pre><code> $args = array( 'posts_per_page' =&gt; -1, // show all items 'orderby' =&gt; 'ID', // was 'title', 'order' =&gt; 'ASC', 'post_type' =&gt; 'product_al', 'post_status' =&gt; 'publish' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); $product_title = ucfirst(get_the_title()); $product_ID = get_the_ID(); ?&gt; &lt;tr id="p_id_&lt;?= $product_ID ?&gt;'"&gt; &lt;td class="title_cell"&gt;&lt;?= $product_ID ?&gt;&lt;/td&gt; &lt;td class="title_cell"&gt;&lt;?= $product_title ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; wp_reset_postdata(); </code></pre> <p>Edit: I tried something a little different and used WP_Query and it does the same thing </p> <pre><code> $args = array( 'post_type' =&gt; 'product_al', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'ID', 'order' =&gt; 'ASC', ); $the_query = new WP_Query( $args ); while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $product_title = ucfirst(get_the_title()); $product_ID = get_the_ID(); ?&gt; &lt;tr id="p_id_&lt;?= $product_ID ?&gt;'"&gt; &lt;td class="title_cell"&gt;&lt;?= $product_ID ?&gt;&lt;/td&gt; &lt;td class="title_cell"&gt;&lt;?= $product_title ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endwhile; wp_reset_postdata(); </code></pre>
[ { "answer_id": 279686, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>It would be atypical for server configuration to have a direct impact on posts query, short of SQL explicitly misbehaving. Which would be quite an edge case.</p>\n\n<p>The much more common case would be some code attaching to query filters for its purposes and not being precise enough to target <em>just</em> the queries it needs to. Issue being specific to front end alone seems to point in this direction as well.</p>\n\n<p>In either case the troubleshooting would involve digging down to actual SQL queries being generated and executed. At some stage there would either be discrepancy between correct/wrong environment or you would be able to exclude SQL and move on to troubleshooting PHP side of it.</p>\n" }, { "answer_id": 279752, "author": "lomokev", "author_id": 7557, "author_profile": "https://wordpress.stackexchange.com/users/7557", "pm_score": 1, "selected": false, "text": "<p>Finally got to the bottom of this, My post type (<code>product_al</code>) does not support menu_order but for some reason some of the older posts had gained a values for menu_order. </p>\n\n<p>Any newly created post would have it's menu_order set to 0 that's why it all looked a little messed up.</p>\n\n<p>To Fix it I just ran this SQL in phpmyadmin to reset menu_order on my post type (<code>product_al</code>):</p>\n\n<pre><code>UPDATE wp_posts SET `menu_order` = '0' WHERE wp_posts.post_type = 'product_al' ;\n</code></pre>\n\n<p>Still don't know why I gained values on <code>menu_order</code>, I had recently moved the site but not sure how it happened. </p>\n\n<p>What I did discover which is a little odd is when using <code>WP_Query</code> even if you specify what you want your query to be ordered on it still always adds <code>ORDER BY wp_posts.menu_order</code>, if WordPress had not does this it would not of been a problem.</p>\n" } ]
2017/09/11
[ "https://wordpress.stackexchange.com/questions/279683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7557/" ]
I have a page that lists some custom posts and the they are not showing in the correct Alphabetical order. As a test I have also tried listing them in order of there Ids and that does not appear in the correct order either. When it's listed as Ids they appear as if they grouped into 3 groups high numbers in the 4000s, below 200 and then 3000s, it's very odd. It works fine on my local server. Also ordering works fine in the Wordpress back end. The problem appears to happened when I moved the site to a new hosting package on 1&1. Has any had server specific ordering issues before? I've made 2 test pages that show a simple list of just titles and IDs (in the wrong order) ID order: <http://www.realpatisserie.co.uk/allergen-list/allergen-list-test-id/> title order: <http://www.realpatisserie.co.uk/allergen-list/allergen-list-test/> ``` $args = array( 'posts_per_page' => -1, // show all items 'orderby' => 'ID', // was 'title', 'order' => 'ASC', 'post_type' => 'product_al', 'post_status' => 'publish' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); $product_title = ucfirst(get_the_title()); $product_ID = get_the_ID(); ?> <tr id="p_id_<?= $product_ID ?>'"> <td class="title_cell"><?= $product_ID ?></td> <td class="title_cell"><?= $product_title ?></td> </tr> <?php endforeach; wp_reset_postdata(); ``` Edit: I tried something a little different and used WP\_Query and it does the same thing ``` $args = array( 'post_type' => 'product_al', 'posts_per_page' => -1, 'orderby' => 'ID', 'order' => 'ASC', ); $the_query = new WP_Query( $args ); while ( $the_query->have_posts() ) : $the_query->the_post(); $product_title = ucfirst(get_the_title()); $product_ID = get_the_ID(); ?> <tr id="p_id_<?= $product_ID ?>'"> <td class="title_cell"><?= $product_ID ?></td> <td class="title_cell"><?= $product_title ?></td> </tr> <?php endwhile; wp_reset_postdata(); ```
It would be atypical for server configuration to have a direct impact on posts query, short of SQL explicitly misbehaving. Which would be quite an edge case. The much more common case would be some code attaching to query filters for its purposes and not being precise enough to target *just* the queries it needs to. Issue being specific to front end alone seems to point in this direction as well. In either case the troubleshooting would involve digging down to actual SQL queries being generated and executed. At some stage there would either be discrepancy between correct/wrong environment or you would be able to exclude SQL and move on to troubleshooting PHP side of it.
279,736
<pre><code>$output = '&lt;p class="one"&gt;&lt;small&gt;'.$newsletter_one. '&lt;/small&gt;&lt;/p&gt;' </code></pre> <p>Generally, when we write short codes we publish HTML like the above one, and instead of echo use return function.</p> <p>How should we write this one →</p> <pre><code>&lt;span class="class2" id="class3-&lt;?php echo $random;?&gt;"&gt; &lt;/span&gt; </code></pre> <p>Like this →</p> <pre><code>$output = '&lt;span class="class2" id="class3-.$random."&gt; &lt;/span&gt;' </code></pre> <p>or does this has some flaws?</p>
[ { "answer_id": 279738, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>When you want to return a data combined with a string, you can use one of the following methods:</p>\n\n<p>Either open and close the string using <code>'</code>:</p>\n\n<pre><code>return '&lt;span class=\"class2\" id=\"class3-' . $random . '\"&gt; &lt;/span&gt;';\n</code></pre>\n\n<p>Or use the double quote:</p>\n\n<pre><code>return \"&lt;span class='class2' id='class3-{$random}'&gt; &lt;/span&gt;\";\n</code></pre>\n\n<p>You can simply use <code>$random</code> without the <code>{}</code> curly brackets, but it's easier to read if you use <code>{}</code>.</p>\n\n<p>You can even use double quotes for the inner string, but you need to escape them:</p>\n\n<pre><code>return \"&lt;span class=\\\"class2\\\" id=\\\"class3-{$random}\\\"&gt; &lt;/span&gt;\";\n</code></pre>\n\n<p>As pointed out in comments by @birgire, to make it more WordPressy, we can also escape the variable:</p>\n\n<pre><code>return sprintf( '&lt;span class=\"class2\" id=\"class3-%s\"&gt;&lt;/span&gt;', esc_attr( $random ) );\n</code></pre>\n" }, { "answer_id": 279740, "author": "Richard Bos", "author_id": 127698, "author_profile": "https://wordpress.stackexchange.com/users/127698", "pm_score": 2, "selected": false, "text": "<p>In addition to Jack Johansson's answer (I'd add a comment to that but it seems I need to have been here longer to do that than to post my own answer!) I don't think you even need the internal double quotes. AFAICT (I'm a relatively recent PHP programmer), you could just write</p>\n\n<pre><code>return \"&lt;span class='class2' id='class3-{$random}'&gt; &lt;/span&gt;\";\n</code></pre>\n\n<p>and that would work just as well.</p>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` $output = '<p class="one"><small>'.$newsletter_one. '</small></p>' ``` Generally, when we write short codes we publish HTML like the above one, and instead of echo use return function. How should we write this one → ``` <span class="class2" id="class3-<?php echo $random;?>"> </span> ``` Like this → ``` $output = '<span class="class2" id="class3-.$random."> </span>' ``` or does this has some flaws?
When you want to return a data combined with a string, you can use one of the following methods: Either open and close the string using `'`: ``` return '<span class="class2" id="class3-' . $random . '"> </span>'; ``` Or use the double quote: ``` return "<span class='class2' id='class3-{$random}'> </span>"; ``` You can simply use `$random` without the `{}` curly brackets, but it's easier to read if you use `{}`. You can even use double quotes for the inner string, but you need to escape them: ``` return "<span class=\"class2\" id=\"class3-{$random}\"> </span>"; ``` As pointed out in comments by @birgire, to make it more WordPressy, we can also escape the variable: ``` return sprintf( '<span class="class2" id="class3-%s"></span>', esc_attr( $random ) ); ```
279,755
<p>I would like to display the 'file path' in the conventional position on a page on my WordPress site. Something like this:</p> <p><a href="https://i.stack.imgur.com/6aIUy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6aIUy.png" alt="example"></a></p> <p>Does anybody know if this is possible without manually typing it onto each page (not really feasible)?</p>
[ { "answer_id": 279762, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>There are a lot of plugins that offer a breadcrumb, but you can also create your own.</p>\n\n<p>To create a simple breadcrumb, you'll need 2 functions. One to create a chain of categories, and one to generate the breadcrumb itself.</p>\n\n<h2>Create a Chain of Categories</h2>\n\n<p>This function will generate a list of clickable categories, for when you are on a single post, page or category. We will use this in the breadcrumb later.</p>\n\n<pre><code>function wpse_get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array(), $iscrumb=false ) {\n $chain = '';\n $parent = get_term( $id, 'category' );\n if ( is_wp_error( $parent ) ) {\n return $parent;\n }\n if ( $nicename ) {\n $name = $parent-&gt;slug;\n } else {\n $name = $parent-&gt;name;\n }\n if ( $parent-&gt;parent &amp;&amp; ( $parent-&gt;parent != $parent-&gt;term_id ) &amp;&amp; !in_array( $parent-&gt;parent, $visited ) ) {\n $visited[] = $parent-&gt;parent;\n $chain .= wpse_get_category_parents( $parent-&gt;parent, $link, $separator, $nicename, $visited , $iscrumb);\n }\n if (is_rtl()){\n $sep_direction ='\\\\';\n } else {\n $sep_direction ='/';\n }\n if ($iscrumb){\n $chain .= '&lt;li&gt;&lt;span class=\"sep\"&gt;'.$sep_direction.'&lt;/span&gt;&lt;a href=\"' . esc_url( get_category_link( $parent-&gt;term_id ) ) . '\"&gt;&lt;span&gt;'.$name.'&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;' . $separator ;\n } elseif ( $link &amp;&amp; !$iscrumb) {\n $chain .= '&lt;a href=\"' . esc_url( get_category_link( $parent-&gt;term_id ) ) . '\"&gt;'.$name.'&lt;/a&gt;' . $separator ;\n } else {\n $chain .= $name.$separator;\n }\n return $chain;\n}\n</code></pre>\n\n<h2>Generate a Breadcrumb</h2>\n\n<p>We'll write a function and use conditionals to generate different outputs based on different locations. We will use the above function here.</p>\n\n<pre><code>function wpse_get_breadcrumbs() {\n global $wp_query;\n if (is_rtl()){\n $sep_direction ='\\\\';\n } else {\n $sep_direction ='/';\n }?&gt;\n &lt;ul&gt;&lt;?php\n // Adding the Home Page ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php echo esc_url( home_url() ); ?&gt;\"&gt;&lt;span&gt; &lt;?php bloginfo('name'); ?&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;&lt;?php\n if ( ! is_front_page() ) {\n // Check for categories, archives, search page, single posts, pages, the 404 page, and attachments\n if ( is_category() ) {\n $cat_obj = $wp_query-&gt;get_queried_object();\n $thisCat = get_category( $cat_obj-&gt;term_id );\n $parentCat = get_category( $thisCat-&gt;parent );\n if($thisCat-&gt;parent != 0) {\n $cat_parents = wpse_get_category_parents( $parentCat, true, '', false, array(), true );\n }\n if ( $thisCat-&gt;parent != 0 &amp;&amp; ! is_wp_error( $cat_parents ) ) {\n echo $cat_parents;\n }\n echo '&lt;li&gt;&lt;span class=\"sep\"&gt;'.$sep_direction.'&lt;/span&gt;&lt;a href=\"'.get_category_link($thisCat).'\"&gt;&lt;span&gt;'.single_cat_title( '', false ).'&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;';\n } elseif ( is_archive() &amp;&amp; ! is_category() ) { ?&gt;\n &lt;li&gt;&lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt; &lt;?php _e( 'Archives' ); ?&gt;&lt;/li&gt;&lt;?php\n } elseif ( is_search() ) { ?&gt;\n &lt;li&gt;&lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt; &lt;?php _e( 'Search Results' ); ?&gt;&lt;/li&gt;&lt;?php\n } elseif ( is_404() ) { ?&gt;\n &lt;li&gt;&lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt; &lt;?php _e( '404 Not Found' ); ?&gt;&lt;/li&gt;&lt;?php\n } elseif ( is_singular() ) {\n $category = get_the_category();\n $category_id = get_cat_ID( $category[0]-&gt;cat_name );\n $cat_parents = wpse_get_category_parents( $category_id, true, '',false, array(), true );\n if ( ! is_wp_error( $cat_parents ) ) {\n echo $cat_parents;\n }?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink();?&gt;\"&gt;&lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt;&lt;?php the_title();?&gt;&lt;/a&gt;\n &lt;/li&gt;&lt;?php\n } elseif ( is_singular( 'attachment' ) ) { ?&gt;\n &lt;li&gt;\n &lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt; &lt;?php the_title(); ?&gt;\n &lt;/li&gt;&lt;?php\n } elseif ( is_page() ) {\n $post = $wp_query-&gt;get_queried_object();\n if ( $post-&gt;post_parent == 0 ) { ?&gt;\n &lt;li&gt;&lt;?php _e( '&lt;span class=\"sep\"&gt;/&lt;/span&gt;' ); the_title(); ?&gt;&lt;/li&gt;&lt;?php\n } else {\n $title = the_title( '','', false );\n $ancestors = array_reverse( get_post_ancestors( $post-&gt;ID ) );\n array_push( $ancestors, $post-&gt;ID );\n foreach ( $ancestors as $ancestor ) {\n if ( $ancestor != end( $ancestors ) ) { ?&gt;\n &lt;li&gt;\n &lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt;&lt;a href=\"&lt;?php echo esc_url( get_permalink( $ancestor ) ); ?&gt;\"&gt; &lt;span&gt;&lt;?php echo strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ); ?&gt;&lt;/span&gt;&lt;/a&gt;\n &lt;/li&gt;&lt;?php\n } else { ?&gt;\n &lt;li&gt;\n &lt;span class=\"sep\"&gt;&lt;?php echo $sep_direction;?&gt;&lt;/span&gt;&lt;?php echo strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ); ?&gt;\n &lt;/li&gt;&lt;?php\n }\n }\n }\n }\n } ?&gt;\n &lt;/ul&gt;&lt;?php\n}\n</code></pre>\n\n<h2>Output the Breadcrumb</h2>\n\n<p>After including both of above functions in your theme's <code>functions.php</code> file, you should use the below code in your theme's header to output the breadcrumb:</p>\n\n<pre><code>if( ! is_home() ) {\n wpse_get_breadcrumbs();\n}\n</code></pre>\n\n<p>This will hide the breadcrumb on homepage, since it's not really required.</p>\n" }, { "answer_id": 327250, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": -1, "selected": false, "text": "<p>Breadcrumbs are an important part of almost every good website. These little navigational aids don’t just tell people where they are on your site, but they also help Google work out how your site is structured. That’s why it makes a lot of sense to add these helpful little pointers. Let’s take a look at how breadcrumbs work.</p>\n\n<p>you can Install <a href=\"https://yoast.com/\" rel=\"nofollow noreferrer\">https://yoast.com/</a> free plugin. </p>\n" }, { "answer_id": 327254, "author": "anittas joseph", "author_id": 160250, "author_profile": "https://wordpress.stackexchange.com/users/160250", "pm_score": 0, "selected": false, "text": "<p>Without using any plugin you can add custom breadcrumbs to your website. Please try the sample code for simple breadcrumb( in functions.php)</p>\n\n<pre><code>function the_breadcrumb() {\n echo '&lt;ul id=\"crumbs\"&gt;';\nif (!is_home()) {\n echo '&lt;li&gt;&lt;a href=\"';\n echo get_option('home');\n echo '\"&gt;';\n echo 'Home';\n echo \"&lt;/a&gt;&lt;/li&gt;\";\n if (is_category() || is_single()) {\n echo '&lt;li&gt;';\n the_category(' &lt;/li&gt;&lt;li&gt; ');\n if (is_single()) {\n echo \"&lt;/li&gt;&lt;li&gt;\";\n the_title();\n echo '&lt;/li&gt;';\n }\n } elseif (is_page()) {\n echo '&lt;li&gt;';\n echo the_title();\n echo '&lt;/li&gt;';\n }\n}\nelseif (is_tag()) {single_tag_title();}\nelseif (is_day()) {echo\"&lt;li&gt;Archive for \"; the_time('F jS, Y'); echo'&lt;/li&gt;';}\nelseif (is_month()) {echo\"&lt;li&gt;Archive for \"; the_time('F, Y'); echo'&lt;/li&gt;';}\nelseif (is_year()) {echo\"&lt;li&gt;Archive for \"; the_time('Y'); echo'&lt;/li&gt;';}\nelseif (is_author()) {echo\"&lt;li&gt;Author Archive\"; echo'&lt;/li&gt;';}\nelseif (isset($_GET['paged']) &amp;&amp; !empty($_GET['paged'])) {echo \"&lt;li&gt;Blog Archives\"; echo'&lt;/li&gt;';}\nelseif (is_search()) {echo\"&lt;li&gt;Search Results\"; echo'&lt;/li&gt;';}\necho '&lt;/ul&gt;';\n</code></pre>\n\n<p>}</p>\n\n<p>Add the following short code in pages you want to show the breadcrumb</p>\n\n<pre><code>&lt;?php the_breadcrumb(); ?&gt;\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127707/" ]
I would like to display the 'file path' in the conventional position on a page on my WordPress site. Something like this: [![example](https://i.stack.imgur.com/6aIUy.png)](https://i.stack.imgur.com/6aIUy.png) Does anybody know if this is possible without manually typing it onto each page (not really feasible)?
There are a lot of plugins that offer a breadcrumb, but you can also create your own. To create a simple breadcrumb, you'll need 2 functions. One to create a chain of categories, and one to generate the breadcrumb itself. Create a Chain of Categories ---------------------------- This function will generate a list of clickable categories, for when you are on a single post, page or category. We will use this in the breadcrumb later. ``` function wpse_get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array(), $iscrumb=false ) { $chain = ''; $parent = get_term( $id, 'category' ); if ( is_wp_error( $parent ) ) { return $parent; } if ( $nicename ) { $name = $parent->slug; } else { $name = $parent->name; } if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) { $visited[] = $parent->parent; $chain .= wpse_get_category_parents( $parent->parent, $link, $separator, $nicename, $visited , $iscrumb); } if (is_rtl()){ $sep_direction ='\\'; } else { $sep_direction ='/'; } if ($iscrumb){ $chain .= '<li><span class="sep">'.$sep_direction.'</span><a href="' . esc_url( get_category_link( $parent->term_id ) ) . '"><span>'.$name.'</span></a></li>' . $separator ; } elseif ( $link && !$iscrumb) { $chain .= '<a href="' . esc_url( get_category_link( $parent->term_id ) ) . '">'.$name.'</a>' . $separator ; } else { $chain .= $name.$separator; } return $chain; } ``` Generate a Breadcrumb --------------------- We'll write a function and use conditionals to generate different outputs based on different locations. We will use the above function here. ``` function wpse_get_breadcrumbs() { global $wp_query; if (is_rtl()){ $sep_direction ='\\'; } else { $sep_direction ='/'; }?> <ul><?php // Adding the Home Page ?> <li><a href="<?php echo esc_url( home_url() ); ?>"><span> <?php bloginfo('name'); ?></span></a></li><?php if ( ! is_front_page() ) { // Check for categories, archives, search page, single posts, pages, the 404 page, and attachments if ( is_category() ) { $cat_obj = $wp_query->get_queried_object(); $thisCat = get_category( $cat_obj->term_id ); $parentCat = get_category( $thisCat->parent ); if($thisCat->parent != 0) { $cat_parents = wpse_get_category_parents( $parentCat, true, '', false, array(), true ); } if ( $thisCat->parent != 0 && ! is_wp_error( $cat_parents ) ) { echo $cat_parents; } echo '<li><span class="sep">'.$sep_direction.'</span><a href="'.get_category_link($thisCat).'"><span>'.single_cat_title( '', false ).'</span></a></li>'; } elseif ( is_archive() && ! is_category() ) { ?> <li><span class="sep"><?php echo $sep_direction;?></span> <?php _e( 'Archives' ); ?></li><?php } elseif ( is_search() ) { ?> <li><span class="sep"><?php echo $sep_direction;?></span> <?php _e( 'Search Results' ); ?></li><?php } elseif ( is_404() ) { ?> <li><span class="sep"><?php echo $sep_direction;?></span> <?php _e( '404 Not Found' ); ?></li><?php } elseif ( is_singular() ) { $category = get_the_category(); $category_id = get_cat_ID( $category[0]->cat_name ); $cat_parents = wpse_get_category_parents( $category_id, true, '',false, array(), true ); if ( ! is_wp_error( $cat_parents ) ) { echo $cat_parents; }?> <li> <a href="<?php the_permalink();?>"><span class="sep"><?php echo $sep_direction;?></span><?php the_title();?></a> </li><?php } elseif ( is_singular( 'attachment' ) ) { ?> <li> <span class="sep"><?php echo $sep_direction;?></span> <?php the_title(); ?> </li><?php } elseif ( is_page() ) { $post = $wp_query->get_queried_object(); if ( $post->post_parent == 0 ) { ?> <li><?php _e( '<span class="sep">/</span>' ); the_title(); ?></li><?php } else { $title = the_title( '','', false ); $ancestors = array_reverse( get_post_ancestors( $post->ID ) ); array_push( $ancestors, $post->ID ); foreach ( $ancestors as $ancestor ) { if ( $ancestor != end( $ancestors ) ) { ?> <li> <span class="sep"><?php echo $sep_direction;?></span><a href="<?php echo esc_url( get_permalink( $ancestor ) ); ?>"> <span><?php echo strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ); ?></span></a> </li><?php } else { ?> <li> <span class="sep"><?php echo $sep_direction;?></span><?php echo strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ); ?> </li><?php } } } } } ?> </ul><?php } ``` Output the Breadcrumb --------------------- After including both of above functions in your theme's `functions.php` file, you should use the below code in your theme's header to output the breadcrumb: ``` if( ! is_home() ) { wpse_get_breadcrumbs(); } ``` This will hide the breadcrumb on homepage, since it's not really required.
279,758
<p>I create the title of the custom-post-type "produktionsauftrag" automatically. The script in my functions.php works but i cant get the postid at the end of my title. </p> <p>Filter in my functions.php file:</p> <pre><code>add_filter('wp_insert_post_data','update_pa_title',99,2); function update_pa_title($data, $postarr) { global $post; if ( !is_admin() ) return $data; if ($data['post_type'] == 'produktionsauftrag') { $data['post_title'] = 'Produktionsauftrag - ' . $post_id; return $data; } else { return $data; } } </code></pre>
[ { "answer_id": 279760, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>The filter \"wp_insert_post_data\" runs before the data is inserted into the database. When you create a new post, the ID is not set yet, it is set by the auto_increment field in the database.</p>\n\n<p>You can use a filter or action later in the process like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">save_post</a>.</p>\n" }, { "answer_id": 279775, "author": "public9nf", "author_id": 81609, "author_profile": "https://wordpress.stackexchange.com/users/81609", "pm_score": 1, "selected": true, "text": "<p>I found the solution with title_save_pre</p>\n\n<pre><code>add_filter('title_save_pre','auto_generate_post_title');\nfunction auto_generate_post_title($title) {\n global $post;\n if (isset($post-&gt;ID)) {\n if (empty($_POST['post_title']) &amp;&amp; 'produktionsauftrag' == get_post_type($post-&gt;ID)){\n // get the current post ID number\n $id = get_the_ID();\n // add ID number with order strong\n $title = 'produktionsauftrag-'.$id;} }\n return $title; \n}\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279758", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81609/" ]
I create the title of the custom-post-type "produktionsauftrag" automatically. The script in my functions.php works but i cant get the postid at the end of my title. Filter in my functions.php file: ``` add_filter('wp_insert_post_data','update_pa_title',99,2); function update_pa_title($data, $postarr) { global $post; if ( !is_admin() ) return $data; if ($data['post_type'] == 'produktionsauftrag') { $data['post_title'] = 'Produktionsauftrag - ' . $post_id; return $data; } else { return $data; } } ```
I found the solution with title\_save\_pre ``` add_filter('title_save_pre','auto_generate_post_title'); function auto_generate_post_title($title) { global $post; if (isset($post->ID)) { if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){ // get the current post ID number $id = get_the_ID(); // add ID number with order strong $title = 'produktionsauftrag-'.$id;} } return $title; } ```
279,766
<p>I am new in WordPress so I am building my first theme with theme options I am facing the problem in my theme options pages that I have made in admin. I have two different styles for my theme options in admin area when I enqueue scripts for admin the problem are as follows:</p> <ol> <li><p>When I enqueue the scripts the script loaded on all the admin pages I just want it to load it on my theme options page</p></li> <li><p>As I mentioned above that I have two different styles according to two different pages of theme options. How can I load the style accordingly?</p></li> </ol>
[ { "answer_id": 279760, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>The filter \"wp_insert_post_data\" runs before the data is inserted into the database. When you create a new post, the ID is not set yet, it is set by the auto_increment field in the database.</p>\n\n<p>You can use a filter or action later in the process like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">save_post</a>.</p>\n" }, { "answer_id": 279775, "author": "public9nf", "author_id": 81609, "author_profile": "https://wordpress.stackexchange.com/users/81609", "pm_score": 1, "selected": true, "text": "<p>I found the solution with title_save_pre</p>\n\n<pre><code>add_filter('title_save_pre','auto_generate_post_title');\nfunction auto_generate_post_title($title) {\n global $post;\n if (isset($post-&gt;ID)) {\n if (empty($_POST['post_title']) &amp;&amp; 'produktionsauftrag' == get_post_type($post-&gt;ID)){\n // get the current post ID number\n $id = get_the_ID();\n // add ID number with order strong\n $title = 'produktionsauftrag-'.$id;} }\n return $title; \n}\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279766", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123366/" ]
I am new in WordPress so I am building my first theme with theme options I am facing the problem in my theme options pages that I have made in admin. I have two different styles for my theme options in admin area when I enqueue scripts for admin the problem are as follows: 1. When I enqueue the scripts the script loaded on all the admin pages I just want it to load it on my theme options page 2. As I mentioned above that I have two different styles according to two different pages of theme options. How can I load the style accordingly?
I found the solution with title\_save\_pre ``` add_filter('title_save_pre','auto_generate_post_title'); function auto_generate_post_title($title) { global $post; if (isset($post->ID)) { if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){ // get the current post ID number $id = get_the_ID(); // add ID number with order strong $title = 'produktionsauftrag-'.$id;} } return $title; } ```
279,806
<p>I am trying to get the post id outside the loop in functions.php.but what error i am getting : <code>Notice: Trying to get property of non-object in functions.php on line 549</code></p> <pre><code>function theme_myeffecto_disable() { global $wp_query; $post_id = $wp_query-&gt;post-&gt;ID; $showreaction = get_post_meta( $post_id, 'post_reaction_show', true ); $showreaction = isset($showreaction) ? $showreaction : true; var_dump($showreaction); } add_action( 'init', 'theme_myeffecto_disable', 20 ); </code></pre> <p>and <code>$showrating</code> always comes false weather it is true or false :(</p>
[ { "answer_id": 279760, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>The filter \"wp_insert_post_data\" runs before the data is inserted into the database. When you create a new post, the ID is not set yet, it is set by the auto_increment field in the database.</p>\n\n<p>You can use a filter or action later in the process like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">save_post</a>.</p>\n" }, { "answer_id": 279775, "author": "public9nf", "author_id": 81609, "author_profile": "https://wordpress.stackexchange.com/users/81609", "pm_score": 1, "selected": true, "text": "<p>I found the solution with title_save_pre</p>\n\n<pre><code>add_filter('title_save_pre','auto_generate_post_title');\nfunction auto_generate_post_title($title) {\n global $post;\n if (isset($post-&gt;ID)) {\n if (empty($_POST['post_title']) &amp;&amp; 'produktionsauftrag' == get_post_type($post-&gt;ID)){\n // get the current post ID number\n $id = get_the_ID();\n // add ID number with order strong\n $title = 'produktionsauftrag-'.$id;} }\n return $title; \n}\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127737/" ]
I am trying to get the post id outside the loop in functions.php.but what error i am getting : `Notice: Trying to get property of non-object in functions.php on line 549` ``` function theme_myeffecto_disable() { global $wp_query; $post_id = $wp_query->post->ID; $showreaction = get_post_meta( $post_id, 'post_reaction_show', true ); $showreaction = isset($showreaction) ? $showreaction : true; var_dump($showreaction); } add_action( 'init', 'theme_myeffecto_disable', 20 ); ``` and `$showrating` always comes false weather it is true or false :(
I found the solution with title\_save\_pre ``` add_filter('title_save_pre','auto_generate_post_title'); function auto_generate_post_title($title) { global $post; if (isset($post->ID)) { if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){ // get the current post ID number $id = get_the_ID(); // add ID number with order strong $title = 'produktionsauftrag-'.$id;} } return $title; } ```
279,815
<p>Currently, we are running our WP based website at dedicated OVH web hosting with the highest performance. Due to fact that traffic at our website continuously grows, we are about to migrate to the dedicated solution and here is where my doubts come. </p> <p>While searching for WP HA tutorials I found 2 main approaches - self hosted VPS (with own instance of MySQL and Apache) or predefined hosting using images for WP like AWS or Docker. </p> <p>Which solutions will be performing better? Of course, the question is a bit generic therefore let's assume that money is not a subject so we could invest in both - high AWS plan as well as strong VPS machines. </p> <p>And second question for those who use AWS - how reliable is this solution? Do you encounter downtimes? Our monitoring shows that OVH is having issues every few days for 10-15 mins. </p>
[ { "answer_id": 279760, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>The filter \"wp_insert_post_data\" runs before the data is inserted into the database. When you create a new post, the ID is not set yet, it is set by the auto_increment field in the database.</p>\n\n<p>You can use a filter or action later in the process like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">save_post</a>.</p>\n" }, { "answer_id": 279775, "author": "public9nf", "author_id": 81609, "author_profile": "https://wordpress.stackexchange.com/users/81609", "pm_score": 1, "selected": true, "text": "<p>I found the solution with title_save_pre</p>\n\n<pre><code>add_filter('title_save_pre','auto_generate_post_title');\nfunction auto_generate_post_title($title) {\n global $post;\n if (isset($post-&gt;ID)) {\n if (empty($_POST['post_title']) &amp;&amp; 'produktionsauftrag' == get_post_type($post-&gt;ID)){\n // get the current post ID number\n $id = get_the_ID();\n // add ID number with order strong\n $title = 'produktionsauftrag-'.$id;} }\n return $title; \n}\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279815", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77480/" ]
Currently, we are running our WP based website at dedicated OVH web hosting with the highest performance. Due to fact that traffic at our website continuously grows, we are about to migrate to the dedicated solution and here is where my doubts come. While searching for WP HA tutorials I found 2 main approaches - self hosted VPS (with own instance of MySQL and Apache) or predefined hosting using images for WP like AWS or Docker. Which solutions will be performing better? Of course, the question is a bit generic therefore let's assume that money is not a subject so we could invest in both - high AWS plan as well as strong VPS machines. And second question for those who use AWS - how reliable is this solution? Do you encounter downtimes? Our monitoring shows that OVH is having issues every few days for 10-15 mins.
I found the solution with title\_save\_pre ``` add_filter('title_save_pre','auto_generate_post_title'); function auto_generate_post_title($title) { global $post; if (isset($post->ID)) { if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){ // get the current post ID number $id = get_the_ID(); // add ID number with order strong $title = 'produktionsauftrag-'.$id;} } return $title; } ```
279,821
<p>Is there any way to add a <code>crossorigin</code> attribute to a custom registered JavaScript?</p> <pre><code>wp_register_script('foo', 'http://cdn.domain.com/script.min.js', null, '1.2.3'); wp_enqueue_script( 'bar', '/path/to/bar.js', array( 'foo' ), '20170912' ); </code></pre>
[ { "answer_id": 279823, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 0, "selected": false, "text": "<p>Using wp_register_script/wp_enqueue_script functions, you can't do that. Maybe open the ticket with WordPress TRAC to be implemented in future versions.</p>\n" }, { "answer_id": 279825, "author": "Ismail", "author_id": 70833, "author_profile": "https://wordpress.stackexchange.com/users/70833", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/hooks/script_loader_tag/\" rel=\"nofollow noreferrer\"><code>script_loader_tag</code></a> or <code>script_loader_src</code> filters are there to let you tweak the HTML of the script easily so you can add custom attributes:</p>\n\n<pre><code>add_filter('script_loader_tag', function($tag, $handle){\n switch ( $handle ) {\n case 'foo':\n $tag = preg_replace(\n '/src=[\\'|\"|]/i',\n 'crossorigin $0',\n $tag\n );\n break;\n }\n\n return $tag;\n}, 10, 2);\n</code></pre>\n\n<p>To avoid conflicting with other plugins, pass unique handles to the script/style register/enqueue function, <code>foo</code> in your case:</p>\n\n<p><code>wp_register_script('foo', 'http://cdn.domain.com/script.min.js', null, '1.2.3');</code></p>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279821", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18126/" ]
Is there any way to add a `crossorigin` attribute to a custom registered JavaScript? ``` wp_register_script('foo', 'http://cdn.domain.com/script.min.js', null, '1.2.3'); wp_enqueue_script( 'bar', '/path/to/bar.js', array( 'foo' ), '20170912' ); ```
[`script_loader_tag`](https://developer.wordpress.org/reference/hooks/script_loader_tag/) or `script_loader_src` filters are there to let you tweak the HTML of the script easily so you can add custom attributes: ``` add_filter('script_loader_tag', function($tag, $handle){ switch ( $handle ) { case 'foo': $tag = preg_replace( '/src=[\'|"|]/i', 'crossorigin $0', $tag ); break; } return $tag; }, 10, 2); ``` To avoid conflicting with other plugins, pass unique handles to the script/style register/enqueue function, `foo` in your case: `wp_register_script('foo', 'http://cdn.domain.com/script.min.js', null, '1.2.3');`
279,845
<p>I run a function to rename draggable/sortable items in a list, and I'd like it if the items could have a wysiwyg editor in them. I saw that some new javascript functions were introduced with 4.8, so I tried them out. Unfortunately, I can't seem to get them to work properly with dynamic elements. Here's the function that runs in the footer:</p> <pre><code>// Check order of sortable items var checkOrder = (function checkOrder() { jQuery('.sortable-container').each(function() { jQuery(this).find('.sortable-item').each(function(i) { jQuery(this).find('label').each(function() { if (jQuery(this).attr('for')) { var oldFor = jQuery(this).attr('for'); jQuery(this).attr('for', oldFor.replace(/\d+/g, i)); } }); jQuery(this).find('input, textarea').each(function() { if (jQuery(this).attr('id')) { var oldId = jQuery(this).attr('id'); jQuery(this).attr('id', oldId.replace(/\d+/g, i)); } if (jQuery(this).attr('name')) { var oldName = jQuery(this).attr('name'); jQuery(this).attr('name', oldName.replace(/\d+/g, i)); } }); }); }); jQuery('.wp-editor').each(function() { wp.editor.initialize(this.id, { tinymce: true, quicktags: true }); }); return checkOrder; }()); </code></pre> <p>The sorting itself works; item id's and name's are changed correctly, but when I try to run wp.editor.initialize, nothing happens. If I run it again after the fact, then it creates 2 editors on top of each other, so it must be running to an extent, but not completely. I've attempted to use the javascript functions in other contexts with similar results: works sometimes or doesn't fully initialize. Any ideas what's wrong or how I can fix it?</p> <p>UPDATE:</p> <p>Ok, I think I've figured out the issue, but I'm not sure how to fix it. I don't know how to make my script dependent on wp_enqueue_editor(), specifically the script created in class-wp-editor.php. Currently it's loading after my script. As Jarocks pointed out, it's the class-wp-editor.php that defines the wp.editor.getDefaultSettings (which is where my editor.js was failing before).</p>
[ { "answer_id": 279953, "author": "Jarocks", "author_id": 127830, "author_profile": "https://wordpress.stackexchange.com/users/127830", "pm_score": 1, "selected": false, "text": "<p>I had similar issues with <code>wp.editor.initialize</code>, after a bit of troubleshooting, I found that some of the needed scripts weren't being fully loaded. </p>\n\n<p>Adding this snippet of code into my plugin fixed the issue:</p>\n\n<pre><code>if ( ! class_exists( '_WP_Editors', false ) ) {\n require( ABSPATH . WPINC . '/class-wp-editor.php' );\n}\nadd_action( 'admin_print_footer_scripts', array( '_WP_Editors', 'print_default_editor_scripts' ) );\n</code></pre>\n" }, { "answer_id": 280518, "author": "Antonio Novak", "author_id": 128215, "author_profile": "https://wordpress.stackexchange.com/users/128215", "pm_score": 2, "selected": false, "text": "<p>You can use only <code>wp_enqueue_editor();</code> instead of: </p>\n\n<pre><code>if ( ! class_exists( '_WP_Editors', false ) ) {\n require( ABSPATH . WPINC . '/class-wp-editor.php' );\n}\nadd_action( 'admin_print_footer_scripts', array( '_WP_Editors', 'print_default_editor_scripts' ) );\n</code></pre>\n" }, { "answer_id": 376771, "author": "Muhammad Junaid", "author_id": 180912, "author_profile": "https://wordpress.stackexchange.com/users/180912", "pm_score": 1, "selected": false, "text": "<p>You should try <code>wp.oldEditor.initialize()</code> instead of <code>wp.editor.initialize()</code> , Make sure to enqueue the editor first</p>\n" }, { "answer_id": 384763, "author": "Jay Maharjan", "author_id": 89462, "author_profile": "https://wordpress.stackexchange.com/users/89462", "pm_score": 1, "selected": false, "text": "<p>I have encounter the same issue after doing ajax call and found out that before initializing the editor we need to remove the editor call if we have already initialized editor in php and then only we need to initialize the editor</p>\n<pre><code>wp.editor.remove(editorID);\nwp.editor.initialize(editorID, {\n tinymce: {\n wpautop: true,\n plugins : 'charmap colorpicker hr lists paste tabfocus textcolor fullscreen wordpress wpautoresize wpeditimage wpemoji wpgallery wplink wptextpattern',\n toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,wp_more,spellchecker,fullscreen,wp_adv,listbuttons',\n toolbar2: 'styleselect,strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',\n textarea_rows : 20\n },\n quicktags: {buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'},\n mediaButtons: false,\n});\n</code></pre>\n" } ]
2017/09/12
[ "https://wordpress.stackexchange.com/questions/279845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127380/" ]
I run a function to rename draggable/sortable items in a list, and I'd like it if the items could have a wysiwyg editor in them. I saw that some new javascript functions were introduced with 4.8, so I tried them out. Unfortunately, I can't seem to get them to work properly with dynamic elements. Here's the function that runs in the footer: ``` // Check order of sortable items var checkOrder = (function checkOrder() { jQuery('.sortable-container').each(function() { jQuery(this).find('.sortable-item').each(function(i) { jQuery(this).find('label').each(function() { if (jQuery(this).attr('for')) { var oldFor = jQuery(this).attr('for'); jQuery(this).attr('for', oldFor.replace(/\d+/g, i)); } }); jQuery(this).find('input, textarea').each(function() { if (jQuery(this).attr('id')) { var oldId = jQuery(this).attr('id'); jQuery(this).attr('id', oldId.replace(/\d+/g, i)); } if (jQuery(this).attr('name')) { var oldName = jQuery(this).attr('name'); jQuery(this).attr('name', oldName.replace(/\d+/g, i)); } }); }); }); jQuery('.wp-editor').each(function() { wp.editor.initialize(this.id, { tinymce: true, quicktags: true }); }); return checkOrder; }()); ``` The sorting itself works; item id's and name's are changed correctly, but when I try to run wp.editor.initialize, nothing happens. If I run it again after the fact, then it creates 2 editors on top of each other, so it must be running to an extent, but not completely. I've attempted to use the javascript functions in other contexts with similar results: works sometimes or doesn't fully initialize. Any ideas what's wrong or how I can fix it? UPDATE: Ok, I think I've figured out the issue, but I'm not sure how to fix it. I don't know how to make my script dependent on wp\_enqueue\_editor(), specifically the script created in class-wp-editor.php. Currently it's loading after my script. As Jarocks pointed out, it's the class-wp-editor.php that defines the wp.editor.getDefaultSettings (which is where my editor.js was failing before).
You can use only `wp_enqueue_editor();` instead of: ``` if ( ! class_exists( '_WP_Editors', false ) ) { require( ABSPATH . WPINC . '/class-wp-editor.php' ); } add_action( 'admin_print_footer_scripts', array( '_WP_Editors', 'print_default_editor_scripts' ) ); ```
279,860
<p>All the resources I've read online suggest using a different CSS file (i.e. <code>editor-style.css</code>) in order to style the WYSIWYG editor to better resemble what the actual content will look like.</p> <p>For the purpose of testing I tried to just use the main <code>style.css</code> file that I've been using for the rest of the site and the styling in the WYSIWYG editor looks great and so far I haven't noticed any problems by doing this.</p> <p>Should I still create a new <code>editor-style.css</code> and use that or is it an acceptable practice to use my main <code>style.css</code>?</p> <p>For reference, this is the code I used below:</p> <pre><code>function wysiwyg_styles() { add_editor_style( 'style.css' ); } add_action( 'init', 'wysiwyg_styles' ); </code></pre>
[ { "answer_id": 279864, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>The editor doesn't use the every style used by your website's front end. So, you don't need the whole <code>style.css</code> file. But still, the file is cached by the browser, so there won't be a problem of performance, probably.</p>\n\n<p>But there might be a conflict problem if you <code>style.css</code> is fairly huge. It might override the other styles used by the admin panel. You might have noticed a few small changes in the overall look of your dashboard ( Probably, not certainly ). In this case, you can write a small stylesheet and only include styles that are used in the single posts and pages.</p>\n" }, { "answer_id": 279868, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": -1, "selected": false, "text": "<p>There's no reason you can't do that, but you need to consider a couple of things:</p>\n\n<p>Firstly, you're loading a <em>lot</em> of styles that are irrelevant to the content represented by the editor.</p>\n\n<p>And the other thing to consider is that the TinyMCE content isn't wrapped in an <code>entry</code> class or similar, so the front-end of your theme would need to use the base <code>h1</code>,<code>p</code>,<code>ul</code> styles etc. without any extra specificity or the content in the editor won't actually match the front-end. I deliberately build my themes so that the content represented by the editor uses the base styles for this very reason.</p>\n\n<p>I also use LESS when developing my themes, so I break out various parts of the CSS into separate files like <code>base.less</code>, <code>entry.less</code>, <code>widget.less</code>. Then I have two main LESS files for the front-end and editor that just import the bits they need. So <code>style.less</code> might look like:</p>\n\n<pre><code>@import (reference) 'variables';\n@import 'base/normalize';\n@import 'base/html';\n@import 'base/forms';\n@import 'base/media';\n@import 'components/grid';\n@import 'components/header'\n@import 'components/sidebar';\n@import 'components/navbar';\n@import 'components/footer';\n</code></pre>\n\n<p>While <code>editor-style.less</code> looks like:</p>\n\n<pre><code>@import (reference) 'variables';\n@import 'base/normalize';\n@import 'base/html';\n@import 'base/forms';\n@import 'base/media';\n</code></pre>\n\n<p>Then <code>style.less</code> gets compiled into <code>style.css</code> and <code>editor-style.less</code> gets compiled into <code>editor-style.css</code>.</p>\n\n<p>So I'm only writing one set of styles, but only the bits I need get put into the edtior stylesheet.</p>\n" }, { "answer_id": 279875, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>The simplest answer is: you can use whatever stylesheet you want for the editor. <code>editor-style.css</code> is just the default stylesheet loaded if none is passed to <code>add_editor_style()</code>.</p>\n\n<p>This will load the specified stylesheet:</p>\n\n<pre><code>add_editor_style( 'some-stylsheet.css' );\n</code></pre>\n\n<p>This will load editor-style.css:</p>\n\n<pre><code>add_editor_style();\n</code></pre>\n\n<p>Use whatever better fits your needs.</p>\n\n<p>By the way, it is better practice to add the editor stylesheet using <code>after_setup_theme</code> action, not <code>init</code>, as it is something specific for the theme:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'cyb_theme_setup' );\nfucntion cyb_theme_setup() {\n add_editor_style();\n}\n</code></pre>\n" } ]
2017/09/13
[ "https://wordpress.stackexchange.com/questions/279860", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123345/" ]
All the resources I've read online suggest using a different CSS file (i.e. `editor-style.css`) in order to style the WYSIWYG editor to better resemble what the actual content will look like. For the purpose of testing I tried to just use the main `style.css` file that I've been using for the rest of the site and the styling in the WYSIWYG editor looks great and so far I haven't noticed any problems by doing this. Should I still create a new `editor-style.css` and use that or is it an acceptable practice to use my main `style.css`? For reference, this is the code I used below: ``` function wysiwyg_styles() { add_editor_style( 'style.css' ); } add_action( 'init', 'wysiwyg_styles' ); ```
The simplest answer is: you can use whatever stylesheet you want for the editor. `editor-style.css` is just the default stylesheet loaded if none is passed to `add_editor_style()`. This will load the specified stylesheet: ``` add_editor_style( 'some-stylsheet.css' ); ``` This will load editor-style.css: ``` add_editor_style(); ``` Use whatever better fits your needs. By the way, it is better practice to add the editor stylesheet using `after_setup_theme` action, not `init`, as it is something specific for the theme: ``` add_action( 'after_setup_theme', 'cyb_theme_setup' ); fucntion cyb_theme_setup() { add_editor_style(); } ```
279,882
<p>I am new to WordPress development ,I am using <code>wp_insert_post()</code> to create posts from front end, This function works fine when I have already logged in but I need to implement this without any login . </p> <p>can you please guide me the exact way how this can be achieved .</p> <pre><code>$post = array( 'post_title' =&gt; "Tshirt-custom-order-".$last_inserted, 'post_content' =&gt; "oio", 'post_status' =&gt; "publish", 'post_excerpt' =&gt; "uuu", 'post_name' =&gt; "order_custom_".$last_inserted, //name/slug 'post_type' =&gt; "product", 'post_author' =&gt;6 ); //Create product/post: $new_post_id = wp_insert_post( $post, $wp_error ); //$new_post_id = wp_insert_post( $args ); </code></pre>
[ { "answer_id": 279871, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>The <code>.htaccess</code> file is mostly used to create rewrite rules and conditions, which is used by Apache and LiteSpeed web servers. NginX has its own syntax for writing and reading these settings.</p>\n\n<p>If you want to use any other permalink structure than plain, you need to have this file. Usually WordPress creates one for you, right after installation is completed.</p>\n\n<p>It is located at the root folder of your WordPress installation, however you are <em>strongly</em> discouraged to alter it if you are not familiar with how it works.</p>\n\n<p>This is the default content for a <code>.htaccess</code> file created by a fresh WordPress installation:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /your-wp-dir/\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /your-wp-dir/index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n\n<p>The <code>your-wp-dir</code> part will not exist if you install WordPress in the root folder.</p>\n" }, { "answer_id": 279889, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 4, "selected": true, "text": "<p>The <code>.htaccess</code> file is not actually required for WordPress to \"work\". However, it is required if you wish to create a more user-friendly URL structure (ie. anything other than \"plain\" permalinks, as Jack suggests).</p>\n\n<p>This is also why the default WordPress <code>.htaccess</code> file surrounds the directives in an <code>&lt;IfModule mod_rewrite.c&gt;</code> container. It \"works\" if \"mod_rewrite\" is not available on the system (you just get a less user-friendly permalink structure). mod_rewrite is Apache's URL rewriting module.</p>\n\n<p>The <code>.htaccess</code> file itself is a \"per-directory Apache configuration file\". To a <em>limited extent</em> (stress <em>limited</em>) it can be used to configure the Apache server environment. However, it is mostly used to configure/help the web application (in this case WordPress). Using <code>.htaccess</code> you can redirect/rewrite the URL, configure client-side caching, restrict access, etc. Although most of this can be configured through a more friendly WordPress plugin. <code>.htaccess</code> syntax can appear a bit cryptic and it is unforgiving if you get it wrong.</p>\n\n<p>The default WordPress <code>.htaccess</code> file implements a \"front-controller\" <em>pattern</em>. It uses mod_rewrite to route all requests (for files that don't exist, ie. <em>virtual URLs</em>) through <code>index.php</code>. This enables WordPress to then examine the requested URL, construct the page and return this to the client.</p>\n\n<p><em>Just as additional side note...</em> if you later wanted to add some redirects to this file (in the form of <code>RewriteRule</code> directives) then these must go <em>before</em> the WordPress front-controller. If you put them at the end of the file they will unlikely be processed. This is a surprisingly common source of error. If, for instance, you used cPanel to create some external redirects, then cPanel will create these at the end of the <code>.htaccess</code> file, so would require some manual editing.</p>\n\n<p>The <code>.htaccess</code> file is usually located in the root directory of the WordPress installation. However, it can be moved to parent directories (even above the document root) if you know what you are doing. <code>.htaccess</code> files are \"per-directory\". Directives in the <code>.htaccess</code> file in the root influence that directory and all subdirectories. If you had another <code>.htaccess</code> in a subdirectory then these directives override the parent <code>.htaccess</code> file. If you have access to the main server config then you don't <em>need</em> <code>.htaccess</code> at all.</p>\n" } ]
2017/09/13
[ "https://wordpress.stackexchange.com/questions/279882", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127183/" ]
I am new to WordPress development ,I am using `wp_insert_post()` to create posts from front end, This function works fine when I have already logged in but I need to implement this without any login . can you please guide me the exact way how this can be achieved . ``` $post = array( 'post_title' => "Tshirt-custom-order-".$last_inserted, 'post_content' => "oio", 'post_status' => "publish", 'post_excerpt' => "uuu", 'post_name' => "order_custom_".$last_inserted, //name/slug 'post_type' => "product", 'post_author' =>6 ); //Create product/post: $new_post_id = wp_insert_post( $post, $wp_error ); //$new_post_id = wp_insert_post( $args ); ```
The `.htaccess` file is not actually required for WordPress to "work". However, it is required if you wish to create a more user-friendly URL structure (ie. anything other than "plain" permalinks, as Jack suggests). This is also why the default WordPress `.htaccess` file surrounds the directives in an `<IfModule mod_rewrite.c>` container. It "works" if "mod\_rewrite" is not available on the system (you just get a less user-friendly permalink structure). mod\_rewrite is Apache's URL rewriting module. The `.htaccess` file itself is a "per-directory Apache configuration file". To a *limited extent* (stress *limited*) it can be used to configure the Apache server environment. However, it is mostly used to configure/help the web application (in this case WordPress). Using `.htaccess` you can redirect/rewrite the URL, configure client-side caching, restrict access, etc. Although most of this can be configured through a more friendly WordPress plugin. `.htaccess` syntax can appear a bit cryptic and it is unforgiving if you get it wrong. The default WordPress `.htaccess` file implements a "front-controller" *pattern*. It uses mod\_rewrite to route all requests (for files that don't exist, ie. *virtual URLs*) through `index.php`. This enables WordPress to then examine the requested URL, construct the page and return this to the client. *Just as additional side note...* if you later wanted to add some redirects to this file (in the form of `RewriteRule` directives) then these must go *before* the WordPress front-controller. If you put them at the end of the file they will unlikely be processed. This is a surprisingly common source of error. If, for instance, you used cPanel to create some external redirects, then cPanel will create these at the end of the `.htaccess` file, so would require some manual editing. The `.htaccess` file is usually located in the root directory of the WordPress installation. However, it can be moved to parent directories (even above the document root) if you know what you are doing. `.htaccess` files are "per-directory". Directives in the `.htaccess` file in the root influence that directory and all subdirectories. If you had another `.htaccess` in a subdirectory then these directives override the parent `.htaccess` file. If you have access to the main server config then you don't *need* `.htaccess` at all.
279,894
<p>quick newbie question but the answer is nowhere to be found!</p> <p>I am building my site from the ground up on Wordpress with Genesis and a child theme (Minimum Pro). I am interested in implementing the Bulma CSS Framework for its ease of use. I would like to do this as efficiently as possible in terms of resources. How can I proceed?</p> <ul> <li><p>Is loading <code>&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.2/css/bulma.min.css"&gt;</code> enough and optimized, or is there a way to load everything on my server if it's preferable?</p></li> <li><p>Should I "clean" unused default markups on my child themes' style.css file so it is lighter?</p></li> </ul> <p>Any clarification regarding this would be much appreciated! Nicolas</p>
[ { "answer_id": 288171, "author": "RLM", "author_id": 60779, "author_profile": "https://wordpress.stackexchange.com/users/60779", "pm_score": 2, "selected": false, "text": "<p>Here is a great <code>Wordpress/Bulma</code> boilerplate theme:</p>\n\n<p><a href=\"https://github.com/teamscops/bulmapress\" rel=\"nofollow noreferrer\">https://github.com/teamscops/bulmapress</a></p>\n\n<p>This way you won't even need a parent theme b/c you are creating a template from \"scratch\". </p>\n" }, { "answer_id": 288625, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://bulma.io/\" rel=\"noreferrer\">Bulma.io</a> is likely to conflict with any styling that comes from Genesis (or any other theme). If you understand HTML/CSS, I recommend using bulma without any other themes/frameworks to avoid conflict/bloat. If you rely on any visual page builders, I would avoid CSS frameworks like bulma and just stick with themes.</p>\n\n<p>I've done a lot of research on this and decided that existing themes were not what I wanted. The bulma framework allows me to build everything exactly as I want it. I'm currently using bulma and <a href=\"https://fontawesome.com/\" rel=\"noreferrer\">Font Awesome 5</a> (new SVG hotness) in a project and they work great once you understand the structure and modifiers.</p>\n\n<p>For my setup, I downloaded a slightly-customized version of the Bulma CSS file using this site <a href=\"https://bulma-customizer.bstash.io\" rel=\"noreferrer\">https://bulma-customizer.bstash.io</a>. I've added it to a <code>/css</code> folder inside my new theme and am enqueueing it and FA5 from my theme's <code>functions.php</code> using the following code:</p>\n\n<pre><code>// Load scripts and styles\nfunction load_styles_and_scripts() {\n\n // Base CSS file derived from bulma.io\n wp_register_style( 'base', get_template_directory_uri() . '/css/base.css' );\n wp_enqueue_style( 'base' );\n\n // Font Awesome 5\n wp_register_script( 'fontawesome', 'https://use.fontawesome.com/releases/v5.0.1/js/all.js' );\n wp_enqueue_script( 'fontawesome' );\n\n // CSS file for custom styles\n // Loaded last so I can override base styling if needed\n wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' );\n wp_enqueue_style( 'custom' );\n\n}\nadd_action( 'wp_enqueue_scripts', 'load_styles_and_scripts' );\n</code></pre>\n\n<p>Note: I'm not sure if downloading FontAwesome and serving it locally would be beneficial or not. I'm sure Google PageSpeed would prefer that, but you would miss out on future <a href=\"https://fontawesome.com/updates\" rel=\"noreferrer\">updates</a>.</p>\n" }, { "answer_id": 293343, "author": "Yasin Yaqoobi", "author_id": 136211, "author_profile": "https://wordpress.stackexchange.com/users/136211", "pm_score": 0, "selected": false, "text": "<p>Genesis framework is great for seo reasons and the built-in hooks/filters so I understand why you are using it. I incorporated bulma through multiple ways. First I used sass where a one on one match between classes was possible. i.e <code>.wrap{ @extends .container; }</code>. The other solution is to add custom classes in the html. I kept the default classes in case I decided to get rid of bulma. You can read more about it here: <a href=\"https://alexanderdejong.com/genesis/changing-adding-custom-classes-html-5/\" rel=\"nofollow noreferrer\">https://alexanderdejong.com/genesis/changing-adding-custom-classes-html-5/</a></p>\n\n<p>I also rebuilt the header, because genesis menu/header structure sucks. You can either create a new header.php <a href=\"https://github.com/teamscops/bulmapress/blob/master/header.php\" rel=\"nofollow noreferrer\">https://github.com/teamscops/bulmapress/blob/master/header.php</a> or use the built-in hooks. </p>\n\n<pre><code>remove_action( 'genesis_header', 'genesis_header_markup_open', 5 );\nremove_action( 'genesis_header', 'genesis_header_markup_close', 15 );\nremove_action( 'genesis_header', 'genesis_do_header' );\n//add in the new header markup - prefix the function name - here sm_ is used\nadd_action( 'genesis_header', 'sm_genesis_header_markup_open', 5 );\nadd_action( 'genesis_header', 'sm_genesis_header_markup_close', 15 );\nremove_action('genesis_after_header', 'genesis_do_nav');\nremove_action( 'genesis_site_title', 'genesis_seo_site_title' );\n\n\n//New Header functions\nfunction sm_genesis_header_markup_open() {\n genesis_markup( array(\n 'html5' =&gt; '&lt;header %s&gt;',\n 'context' =&gt; 'site-header',\n ) );\n // Added in content\n do_action( 'genesis_site_title' );\n echo '&lt;div class=\"navbar\"&gt;&lt;div class=\"container\"&gt;' . get_logo() . '&lt;div class=\"navbar-menu\"&gt;' .\n wp_nav_menu(array(\n 'menu_class' =&gt; 'main-menu',\n 'container_class' =&gt; 'navbar-start',\n 'echo' =&gt;false\n ))\n . '&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;';\n genesis_structural_wrap( 'header' );\n}\n\nfunction sm_genesis_header_markup_close() {\n genesis_structural_wrap( 'header', 'close' );\n genesis_markup( array(\n 'close' =&gt; '&lt;/header&gt;',\n 'context' =&gt; 'site-header',\n ) );\n}\n\nfunction get_logo() {\n return '&lt;div class=\"navbar-brand\"&gt;&lt;a class=\"navbar-item\" href=\"' . get_site_url() . '\"&gt;&lt;img class=\"logo\" src=\"' . get_stylesheet_directory_URI(). '/images/logo.png\" alt=\"logo\"&gt;&lt;/a&gt;&lt;/div&gt;';\n}\n</code></pre>\n" } ]
2017/09/13
[ "https://wordpress.stackexchange.com/questions/279894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123290/" ]
quick newbie question but the answer is nowhere to be found! I am building my site from the ground up on Wordpress with Genesis and a child theme (Minimum Pro). I am interested in implementing the Bulma CSS Framework for its ease of use. I would like to do this as efficiently as possible in terms of resources. How can I proceed? * Is loading `<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.2/css/bulma.min.css">` enough and optimized, or is there a way to load everything on my server if it's preferable? * Should I "clean" unused default markups on my child themes' style.css file so it is lighter? Any clarification regarding this would be much appreciated! Nicolas
[Bulma.io](https://bulma.io/) is likely to conflict with any styling that comes from Genesis (or any other theme). If you understand HTML/CSS, I recommend using bulma without any other themes/frameworks to avoid conflict/bloat. If you rely on any visual page builders, I would avoid CSS frameworks like bulma and just stick with themes. I've done a lot of research on this and decided that existing themes were not what I wanted. The bulma framework allows me to build everything exactly as I want it. I'm currently using bulma and [Font Awesome 5](https://fontawesome.com/) (new SVG hotness) in a project and they work great once you understand the structure and modifiers. For my setup, I downloaded a slightly-customized version of the Bulma CSS file using this site <https://bulma-customizer.bstash.io>. I've added it to a `/css` folder inside my new theme and am enqueueing it and FA5 from my theme's `functions.php` using the following code: ``` // Load scripts and styles function load_styles_and_scripts() { // Base CSS file derived from bulma.io wp_register_style( 'base', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'base' ); // Font Awesome 5 wp_register_script( 'fontawesome', 'https://use.fontawesome.com/releases/v5.0.1/js/all.js' ); wp_enqueue_script( 'fontawesome' ); // CSS file for custom styles // Loaded last so I can override base styling if needed wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' ); wp_enqueue_style( 'custom' ); } add_action( 'wp_enqueue_scripts', 'load_styles_and_scripts' ); ``` Note: I'm not sure if downloading FontAwesome and serving it locally would be beneficial or not. I'm sure Google PageSpeed would prefer that, but you would miss out on future [updates](https://fontawesome.com/updates).
279,931
<p>I apologize in advance for my lack of PHP/WP knowledge, and my wordiness in explaining what I'm looking for, but I've been trying to work out a solution for a couple of days now, and I'm just starting to wrap my head around filters and the loop. </p> <p><strong>Here's what I'd like to accomplish:</strong></p> <p>A shortcode for a plugin I'm using has an attribute tag "sched" that I would like to make essentially dynamic, changed to the current (custom)post's (custom)category slug. Here's an example of an existing shortcode that works well with the MSTW Schedules and Scoreboards plugin:</p> <pre><code>[mstw_schedule_table sched="v-football"] </code></pre> <p>My plan was to set the "sched" attribute's value to "sport" (on all posts) as a placeholder that would be replaced with the current post's "sport" custom category slug. I've set up all "sport" category slugs to correspond with the "sched" values used in the plugin, to ensure that the schedule table displayed on the current post is correct.</p> <p>Note: All of these custom posts (set up as "team") should only have one "sport" category applied to them: I have set up "sport" categories as a dropdown meta box in admin, like <a href="https://wordpress.stackexchange.com/a/28355/127459">this</a>.</p> <p>Also Note: I'd like the editable shortcode to be available within the custom post's content, so I can edit other attributes as needed for each post.</p> <p><strong>Here is what I've tried:</strong></p> <p>This is the closest I've gotten, but I know that I'm using the wrong filter, or otherwise calling the function at the wrong time. Note that I ran this code in the "single-team.php" file I created for my custom post type, before the loop. I'm aware it should probably be in functions.php or a separate plugin (please advise).</p> <p>My inspiration:<br> <a href="https://wordpress.stackexchange.com/a/257078/127459">do_shortcode_tag</a> / <a href="https://developer.wordpress.org/reference/functions/get_the_terms/#comment-2343" rel="nofollow noreferrer">get_the_terms</a></p> <pre><code> add_filter( 'do_shortcode_tag', 'wpse_106269_do_shortcode_tag', 10, 4); function wpse_106269_do_shortcode_tag( $output, $tag, $attr, $m ) { if( $tag === 'mstw_schedule_table' ) { //* Do something useful if ($attr['sched'] === 'sport-slug') { print_r($attr); // Get a list of tags and extract their names $sport = get_the_terms( get_the_ID(), 'sport' ); if ( ! empty( $sport ) &amp;&amp; ! is_wp_error( $sport ) ) { $sport_slug = wp_list_pluck( $sport, 'slug' ); $attr['sched'] = $sport_slug[0]; } echo "&lt;br&gt;"; print_r($attr); } } return $output; } </code></pre> <p>This outputs:</p> <pre><code>Array ( [sched] =&gt; sport-slug ) Array ( [sched] =&gt; v-football ) </code></pre> <p>So I know I can change the value of the shortcode's $attr, but I don't know how to replace the original shortcode with the modified one, before it's parsed by the plugin.</p> <p>I tried using <a href="https://wordpress.stackexchange.com/a/24265/127459">the_content</a>:</p> <pre><code>// Modify Content of a Post add_filter('the_content', 'se24265_my_function'); function se24265_my_function( $content ) { $write = 'hello world'; $new_content = $write . $content; $sport = get_the_terms( get_the_ID(), 'sport' ); if ( ! empty( $sport ) &amp;&amp; ! is_wp_error( $sport ) ) { $sport_slug = wp_list_pluck( $sport, 'slug' ); str_replace("sport-slug", $sport_slug[0], $new_content); } return $new_content; // outputs hello world // outputs inital shortcode without modifications } </code></pre> <p>I also thought about running the plugin's shortcode handler function (like <a href="https://wordpress.stackexchange.com/a/236430/127459">this</a>) with a modified argument, but I don't know how to access/modify that argument before it's interpreted out by the plugin.</p> <p>I've also seen <a href="https://developer.wordpress.org/reference/functions/do_shortcode/#comment-1380" rel="nofollow noreferrer">this</a> example where the shortcode is generated within the custom post template...</p> <pre><code>// Making your custom string parses shortcode $string = do_shortcode( $string ); // If your string has a custom filter, add its tag name in an applicable add_filter function add_filter( 'my_string_filter_hook_tag_name', 'do_shortcode' ); </code></pre> <p>... but I'd like to maintain the ability to edit / place the shortcode in different places within each custom post as needed, and I still don't know which filter hook to use (content_edit_pre ?) </p> <p>Any help would be appreciated. Thanks.</p>
[ { "answer_id": 288171, "author": "RLM", "author_id": 60779, "author_profile": "https://wordpress.stackexchange.com/users/60779", "pm_score": 2, "selected": false, "text": "<p>Here is a great <code>Wordpress/Bulma</code> boilerplate theme:</p>\n\n<p><a href=\"https://github.com/teamscops/bulmapress\" rel=\"nofollow noreferrer\">https://github.com/teamscops/bulmapress</a></p>\n\n<p>This way you won't even need a parent theme b/c you are creating a template from \"scratch\". </p>\n" }, { "answer_id": 288625, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://bulma.io/\" rel=\"noreferrer\">Bulma.io</a> is likely to conflict with any styling that comes from Genesis (or any other theme). If you understand HTML/CSS, I recommend using bulma without any other themes/frameworks to avoid conflict/bloat. If you rely on any visual page builders, I would avoid CSS frameworks like bulma and just stick with themes.</p>\n\n<p>I've done a lot of research on this and decided that existing themes were not what I wanted. The bulma framework allows me to build everything exactly as I want it. I'm currently using bulma and <a href=\"https://fontawesome.com/\" rel=\"noreferrer\">Font Awesome 5</a> (new SVG hotness) in a project and they work great once you understand the structure and modifiers.</p>\n\n<p>For my setup, I downloaded a slightly-customized version of the Bulma CSS file using this site <a href=\"https://bulma-customizer.bstash.io\" rel=\"noreferrer\">https://bulma-customizer.bstash.io</a>. I've added it to a <code>/css</code> folder inside my new theme and am enqueueing it and FA5 from my theme's <code>functions.php</code> using the following code:</p>\n\n<pre><code>// Load scripts and styles\nfunction load_styles_and_scripts() {\n\n // Base CSS file derived from bulma.io\n wp_register_style( 'base', get_template_directory_uri() . '/css/base.css' );\n wp_enqueue_style( 'base' );\n\n // Font Awesome 5\n wp_register_script( 'fontawesome', 'https://use.fontawesome.com/releases/v5.0.1/js/all.js' );\n wp_enqueue_script( 'fontawesome' );\n\n // CSS file for custom styles\n // Loaded last so I can override base styling if needed\n wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' );\n wp_enqueue_style( 'custom' );\n\n}\nadd_action( 'wp_enqueue_scripts', 'load_styles_and_scripts' );\n</code></pre>\n\n<p>Note: I'm not sure if downloading FontAwesome and serving it locally would be beneficial or not. I'm sure Google PageSpeed would prefer that, but you would miss out on future <a href=\"https://fontawesome.com/updates\" rel=\"noreferrer\">updates</a>.</p>\n" }, { "answer_id": 293343, "author": "Yasin Yaqoobi", "author_id": 136211, "author_profile": "https://wordpress.stackexchange.com/users/136211", "pm_score": 0, "selected": false, "text": "<p>Genesis framework is great for seo reasons and the built-in hooks/filters so I understand why you are using it. I incorporated bulma through multiple ways. First I used sass where a one on one match between classes was possible. i.e <code>.wrap{ @extends .container; }</code>. The other solution is to add custom classes in the html. I kept the default classes in case I decided to get rid of bulma. You can read more about it here: <a href=\"https://alexanderdejong.com/genesis/changing-adding-custom-classes-html-5/\" rel=\"nofollow noreferrer\">https://alexanderdejong.com/genesis/changing-adding-custom-classes-html-5/</a></p>\n\n<p>I also rebuilt the header, because genesis menu/header structure sucks. You can either create a new header.php <a href=\"https://github.com/teamscops/bulmapress/blob/master/header.php\" rel=\"nofollow noreferrer\">https://github.com/teamscops/bulmapress/blob/master/header.php</a> or use the built-in hooks. </p>\n\n<pre><code>remove_action( 'genesis_header', 'genesis_header_markup_open', 5 );\nremove_action( 'genesis_header', 'genesis_header_markup_close', 15 );\nremove_action( 'genesis_header', 'genesis_do_header' );\n//add in the new header markup - prefix the function name - here sm_ is used\nadd_action( 'genesis_header', 'sm_genesis_header_markup_open', 5 );\nadd_action( 'genesis_header', 'sm_genesis_header_markup_close', 15 );\nremove_action('genesis_after_header', 'genesis_do_nav');\nremove_action( 'genesis_site_title', 'genesis_seo_site_title' );\n\n\n//New Header functions\nfunction sm_genesis_header_markup_open() {\n genesis_markup( array(\n 'html5' =&gt; '&lt;header %s&gt;',\n 'context' =&gt; 'site-header',\n ) );\n // Added in content\n do_action( 'genesis_site_title' );\n echo '&lt;div class=\"navbar\"&gt;&lt;div class=\"container\"&gt;' . get_logo() . '&lt;div class=\"navbar-menu\"&gt;' .\n wp_nav_menu(array(\n 'menu_class' =&gt; 'main-menu',\n 'container_class' =&gt; 'navbar-start',\n 'echo' =&gt;false\n ))\n . '&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;';\n genesis_structural_wrap( 'header' );\n}\n\nfunction sm_genesis_header_markup_close() {\n genesis_structural_wrap( 'header', 'close' );\n genesis_markup( array(\n 'close' =&gt; '&lt;/header&gt;',\n 'context' =&gt; 'site-header',\n ) );\n}\n\nfunction get_logo() {\n return '&lt;div class=\"navbar-brand\"&gt;&lt;a class=\"navbar-item\" href=\"' . get_site_url() . '\"&gt;&lt;img class=\"logo\" src=\"' . get_stylesheet_directory_URI(). '/images/logo.png\" alt=\"logo\"&gt;&lt;/a&gt;&lt;/div&gt;';\n}\n</code></pre>\n" } ]
2017/09/13
[ "https://wordpress.stackexchange.com/questions/279931", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127459/" ]
I apologize in advance for my lack of PHP/WP knowledge, and my wordiness in explaining what I'm looking for, but I've been trying to work out a solution for a couple of days now, and I'm just starting to wrap my head around filters and the loop. **Here's what I'd like to accomplish:** A shortcode for a plugin I'm using has an attribute tag "sched" that I would like to make essentially dynamic, changed to the current (custom)post's (custom)category slug. Here's an example of an existing shortcode that works well with the MSTW Schedules and Scoreboards plugin: ``` [mstw_schedule_table sched="v-football"] ``` My plan was to set the "sched" attribute's value to "sport" (on all posts) as a placeholder that would be replaced with the current post's "sport" custom category slug. I've set up all "sport" category slugs to correspond with the "sched" values used in the plugin, to ensure that the schedule table displayed on the current post is correct. Note: All of these custom posts (set up as "team") should only have one "sport" category applied to them: I have set up "sport" categories as a dropdown meta box in admin, like [this](https://wordpress.stackexchange.com/a/28355/127459). Also Note: I'd like the editable shortcode to be available within the custom post's content, so I can edit other attributes as needed for each post. **Here is what I've tried:** This is the closest I've gotten, but I know that I'm using the wrong filter, or otherwise calling the function at the wrong time. Note that I ran this code in the "single-team.php" file I created for my custom post type, before the loop. I'm aware it should probably be in functions.php or a separate plugin (please advise). My inspiration: [do\_shortcode\_tag](https://wordpress.stackexchange.com/a/257078/127459) / [get\_the\_terms](https://developer.wordpress.org/reference/functions/get_the_terms/#comment-2343) ``` add_filter( 'do_shortcode_tag', 'wpse_106269_do_shortcode_tag', 10, 4); function wpse_106269_do_shortcode_tag( $output, $tag, $attr, $m ) { if( $tag === 'mstw_schedule_table' ) { //* Do something useful if ($attr['sched'] === 'sport-slug') { print_r($attr); // Get a list of tags and extract their names $sport = get_the_terms( get_the_ID(), 'sport' ); if ( ! empty( $sport ) && ! is_wp_error( $sport ) ) { $sport_slug = wp_list_pluck( $sport, 'slug' ); $attr['sched'] = $sport_slug[0]; } echo "<br>"; print_r($attr); } } return $output; } ``` This outputs: ``` Array ( [sched] => sport-slug ) Array ( [sched] => v-football ) ``` So I know I can change the value of the shortcode's $attr, but I don't know how to replace the original shortcode with the modified one, before it's parsed by the plugin. I tried using [the\_content](https://wordpress.stackexchange.com/a/24265/127459): ``` // Modify Content of a Post add_filter('the_content', 'se24265_my_function'); function se24265_my_function( $content ) { $write = 'hello world'; $new_content = $write . $content; $sport = get_the_terms( get_the_ID(), 'sport' ); if ( ! empty( $sport ) && ! is_wp_error( $sport ) ) { $sport_slug = wp_list_pluck( $sport, 'slug' ); str_replace("sport-slug", $sport_slug[0], $new_content); } return $new_content; // outputs hello world // outputs inital shortcode without modifications } ``` I also thought about running the plugin's shortcode handler function (like [this](https://wordpress.stackexchange.com/a/236430/127459)) with a modified argument, but I don't know how to access/modify that argument before it's interpreted out by the plugin. I've also seen [this](https://developer.wordpress.org/reference/functions/do_shortcode/#comment-1380) example where the shortcode is generated within the custom post template... ``` // Making your custom string parses shortcode $string = do_shortcode( $string ); // If your string has a custom filter, add its tag name in an applicable add_filter function add_filter( 'my_string_filter_hook_tag_name', 'do_shortcode' ); ``` ... but I'd like to maintain the ability to edit / place the shortcode in different places within each custom post as needed, and I still don't know which filter hook to use (content\_edit\_pre ?) Any help would be appreciated. Thanks.
[Bulma.io](https://bulma.io/) is likely to conflict with any styling that comes from Genesis (or any other theme). If you understand HTML/CSS, I recommend using bulma without any other themes/frameworks to avoid conflict/bloat. If you rely on any visual page builders, I would avoid CSS frameworks like bulma and just stick with themes. I've done a lot of research on this and decided that existing themes were not what I wanted. The bulma framework allows me to build everything exactly as I want it. I'm currently using bulma and [Font Awesome 5](https://fontawesome.com/) (new SVG hotness) in a project and they work great once you understand the structure and modifiers. For my setup, I downloaded a slightly-customized version of the Bulma CSS file using this site <https://bulma-customizer.bstash.io>. I've added it to a `/css` folder inside my new theme and am enqueueing it and FA5 from my theme's `functions.php` using the following code: ``` // Load scripts and styles function load_styles_and_scripts() { // Base CSS file derived from bulma.io wp_register_style( 'base', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'base' ); // Font Awesome 5 wp_register_script( 'fontawesome', 'https://use.fontawesome.com/releases/v5.0.1/js/all.js' ); wp_enqueue_script( 'fontawesome' ); // CSS file for custom styles // Loaded last so I can override base styling if needed wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' ); wp_enqueue_style( 'custom' ); } add_action( 'wp_enqueue_scripts', 'load_styles_and_scripts' ); ``` Note: I'm not sure if downloading FontAwesome and serving it locally would be beneficial or not. I'm sure Google PageSpeed would prefer that, but you would miss out on future [updates](https://fontawesome.com/updates).
279,947
<p>I have several wp users who do not insert a title when creating a new post (and custom type post). This means that the permalink is assigned a number as the link. Within the multisite I am developing, this will commonly stop the link from working (the page just refreshes).</p> <p>I want to show a warning message when the user fails to insert a title on the post before publishing (telling them to insert title AND edit the permalink).</p> <p>My code so far in the functions.php file:</p> <pre><code>function check_for_post_title( $post, $ID ) { $title = $post-&gt;post_title; $permalink = get_permalink( $ID ); if($title =='' || $title == null) { no_post_title_notice(); } else { some_post_title_notice(); } } add_action( 'publish_post', 'check_for_post_title', 10, 2 ); function no_post_title_notice() { ?&gt; &lt;div class="notice notice-warning is-dismissible"&gt; &lt;p&gt;&lt;?php _e( 'You have not provided a title for your post/page. This will cause the link to be broken. Please revise', 'understrap-post-title' ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } function some_post_title_notice() { ?&gt; &lt;div class="notice notice-warning is-dismissible"&gt; &lt;p&gt;&lt;?php _e( 'I dont know why this message is appearing', 'understrap-post-title' ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>Currently, it's not working and no notices are appearing at the top of the edit post screen after publishing/updating at all. Not sure why it is not firing at all (even the 'else' statement should fire something). What am I doing wrong?</p>
[ { "answer_id": 279994, "author": "Kumar", "author_id": 32466, "author_profile": "https://wordpress.stackexchange.com/users/32466", "pm_score": 3, "selected": true, "text": "<p>Your error doesn't appears on the screen because the page is reloaded after the action <code>publish_post</code>.</p>\n\n<p>I have followed a different approach altogether, I'm checking the post title at <code>wp_insert_post_data</code> if the title is empty, I mark the post_status as draft and save a simple flag in options table. The flag I've saved is used to hide the Post Published notice and display a admin notice for specifying title in order to publish the post.</p>\n\n<p>At the same moment I delete the option, so the notice is one time thing. You can modify it to a greater extent as per your requirements, but this is a basic solution and should work fine. </p>\n\n<pre><code>/**\n * Checks for empty post title, if empty sets the post status to draft\n *\n * @param $data\n * @param $postarr\n *\n * @return array\n */\nfunction wse_279994_check_post_title( $data, $postarr ) {\n if ( is_array( $data ) &amp;&amp; 'publish' == $data['post_status'] &amp;&amp; empty( $data['post_title'] ) ) {\n $data['post_status'] = 'draft';\n update_option( 'wse_279994_post_error', 'empty_title' );\n }\n\n return $data;\n}\nadd_filter( 'wp_insert_post_data', 'wse_279994_check_post_title', 10, 2 );\n\n/**\n * If the post title was empty, do not show post published message\n */\nadd_filter( 'post_updated_messages', 'wse_279994_remove_all_messages' );\n\nfunction wse_279994_remove_all_messages( $messages ) {\n if ( get_option( 'wse_279994_post_error' ) ) {\n return array();\n } else {\n return $messages;\n }\n}\n\n/**\n * Show admin notice for empty post title\n */\nadd_action( 'admin_notices', 'wse_279994_show_error' );\nfunction wse_279994_show_error() {\n $screen = get_current_screen();\n if ( $screen-&gt;id != 'post' ) {\n return;\n }\n if ( ! get_option( 'wse_279994_post_error' ) ) {\n return;\n }\n echo '&lt;div class=\"error\"&gt;&lt;p&gt;' . esc_html__( \"You need to enter a Post Title in order to publish it.\", \"wse\" ) . '&lt;/p&gt;&lt;/div&gt;';\n delete_option( 'wse_279994_post_error' );\n}\n</code></pre>\n" }, { "answer_id": 367772, "author": "Ronak J Vanpariya", "author_id": 170878, "author_profile": "https://wordpress.stackexchange.com/users/170878", "pm_score": 0, "selected": false, "text": "<p>For Custom post type Demo modified above answer</p>\n\n<pre><code>/**\n * Checks for empty post title, if empty sets the post status to draft\n *\n * @param $data\n * @param $postarr\n *\n * @return array\n */\nfunction wse_279994_check_post_title( $data, $postarr ) {\n global $post;\n if( \"demo\" == get_post_type($post) ){\n if ( is_array( $data ) &amp;&amp; 'publish' == $data['post_status'] &amp;&amp; empty( $data['post_title'] ) ) {\n $data['post_status'] = 'draft';\n update_option( 'wse_279994_post_error', 'empty_title' );\n }\n }\n\n return $data;\n}\nadd_filter( 'wp_insert_post_data', 'wse_279994_check_post_title', 10, 2 );\n</code></pre>\n" } ]
2017/09/13
[ "https://wordpress.stackexchange.com/questions/279947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105819/" ]
I have several wp users who do not insert a title when creating a new post (and custom type post). This means that the permalink is assigned a number as the link. Within the multisite I am developing, this will commonly stop the link from working (the page just refreshes). I want to show a warning message when the user fails to insert a title on the post before publishing (telling them to insert title AND edit the permalink). My code so far in the functions.php file: ``` function check_for_post_title( $post, $ID ) { $title = $post->post_title; $permalink = get_permalink( $ID ); if($title =='' || $title == null) { no_post_title_notice(); } else { some_post_title_notice(); } } add_action( 'publish_post', 'check_for_post_title', 10, 2 ); function no_post_title_notice() { ?> <div class="notice notice-warning is-dismissible"> <p><?php _e( 'You have not provided a title for your post/page. This will cause the link to be broken. Please revise', 'understrap-post-title' ); ?></p> </div> <?php } function some_post_title_notice() { ?> <div class="notice notice-warning is-dismissible"> <p><?php _e( 'I dont know why this message is appearing', 'understrap-post-title' ); ?></p> </div> <?php } ``` Currently, it's not working and no notices are appearing at the top of the edit post screen after publishing/updating at all. Not sure why it is not firing at all (even the 'else' statement should fire something). What am I doing wrong?
Your error doesn't appears on the screen because the page is reloaded after the action `publish_post`. I have followed a different approach altogether, I'm checking the post title at `wp_insert_post_data` if the title is empty, I mark the post\_status as draft and save a simple flag in options table. The flag I've saved is used to hide the Post Published notice and display a admin notice for specifying title in order to publish the post. At the same moment I delete the option, so the notice is one time thing. You can modify it to a greater extent as per your requirements, but this is a basic solution and should work fine. ``` /** * Checks for empty post title, if empty sets the post status to draft * * @param $data * @param $postarr * * @return array */ function wse_279994_check_post_title( $data, $postarr ) { if ( is_array( $data ) && 'publish' == $data['post_status'] && empty( $data['post_title'] ) ) { $data['post_status'] = 'draft'; update_option( 'wse_279994_post_error', 'empty_title' ); } return $data; } add_filter( 'wp_insert_post_data', 'wse_279994_check_post_title', 10, 2 ); /** * If the post title was empty, do not show post published message */ add_filter( 'post_updated_messages', 'wse_279994_remove_all_messages' ); function wse_279994_remove_all_messages( $messages ) { if ( get_option( 'wse_279994_post_error' ) ) { return array(); } else { return $messages; } } /** * Show admin notice for empty post title */ add_action( 'admin_notices', 'wse_279994_show_error' ); function wse_279994_show_error() { $screen = get_current_screen(); if ( $screen->id != 'post' ) { return; } if ( ! get_option( 'wse_279994_post_error' ) ) { return; } echo '<div class="error"><p>' . esc_html__( "You need to enter a Post Title in order to publish it.", "wse" ) . '</p></div>'; delete_option( 'wse_279994_post_error' ); } ```
279,999
<p>Is there a way to not show the points while you are typing the password but show the letters/numbers of the password? </p> <p>I would like to implement it in my "My account" page of woocommerce:</p> <p><a href="https://i.stack.imgur.com/qyaih.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qyaih.png" alt="enter image description here"></a> </p>
[ { "answer_id": 280002, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": -1, "selected": false, "text": "<p>override by copying <code>woocommerce/templates/myaccount/form-login.php</code>. it to <code>yourtheme/woocommerce/myaccount/form-login.php</code>.</p>\n<p>and change password field attribute <code>type=&quot;password&quot;</code> to <code>type=&quot;text&quot;</code></p>\n<p>hope it will solve your problem.</p>\n" }, { "answer_id": 280011, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>Best way to do this, without making too many changes to the code, is to use JavaScript (jQuery) that will add Hide/Show capability to the existing password field.</p>\n\n<p>Excellent free jQuery plugin for that is: <a href=\"https://github.com/cloudfour/hideShowPassword\" rel=\"nofollow noreferrer\">HideShowPassword</a>. It has many ways to customize how the password will be visible.</p>\n" }, { "answer_id": 280014, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": true, "text": "<p>I would strongly disagree to show the <strong>password as the user typing it</strong>. \nYou could instead implement a way to show the status of the field with a user action like a <strong>user click</strong> to show password or on <strong>hover</strong>.\nThe reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it</p>\n\n<p>Some examples are:\n<a href=\"https://i.stack.imgur.com/LQmAf.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LQmAf.jpg\" alt=\"enter image description here\"></a>\nCode from <strong>herdiansc</strong> </p>\n\n<pre><code>//Place this plugin snippet into another file in your applicationb\n(function ($) {\n $.toggleShowPassword = function (options) {\n var settings = $.extend({\n field: \"#password\",\n control: \"#toggle_show_password\",\n }, options);\n\n var control = $(settings.control);\n var field = $(settings.field)\n\n control.bind('click', function () {\n if (control.is(':checked')) {\n field.attr('type', 'text');\n } else {\n field.attr('type', 'password');\n }\n })\n };\n}(jQuery));\n\n//Here how to call above plugin from everywhere in your application document body\n$.toggleShowPassword({\n field: '#test1',\n control: '#test2'\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/herdiansc/dnznh/8/\" rel=\"nofollow noreferrer\">jsfiddle</a></p>\n\n<p>And \nuser <strong>Baraka Mahili</strong></p>\n\n<pre><code>$('#show_password').hover(function functionName() {\n //Change the attribute to text\n $('#password').attr('type', 'text');\n $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close');\n }, function () {\n //Change the attribute back to password\n $('#password').attr('type', 'password');\n $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open');\n }\n );\nhttps://codepen.io/GBMahili/pen/pEvVZP\n</code></pre>\n" } ]
2017/09/14
[ "https://wordpress.stackexchange.com/questions/279999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107597/" ]
Is there a way to not show the points while you are typing the password but show the letters/numbers of the password? I would like to implement it in my "My account" page of woocommerce: [![enter image description here](https://i.stack.imgur.com/qyaih.png)](https://i.stack.imgur.com/qyaih.png)
I would strongly disagree to show the **password as the user typing it**. You could instead implement a way to show the status of the field with a user action like a **user click** to show password or on **hover**. The reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it Some examples are: [![enter image description here](https://i.stack.imgur.com/LQmAf.jpg)](https://i.stack.imgur.com/LQmAf.jpg) Code from **herdiansc** ``` //Place this plugin snippet into another file in your applicationb (function ($) { $.toggleShowPassword = function (options) { var settings = $.extend({ field: "#password", control: "#toggle_show_password", }, options); var control = $(settings.control); var field = $(settings.field) control.bind('click', function () { if (control.is(':checked')) { field.attr('type', 'text'); } else { field.attr('type', 'password'); } }) }; }(jQuery)); //Here how to call above plugin from everywhere in your application document body $.toggleShowPassword({ field: '#test1', control: '#test2' }); ``` [jsfiddle](http://jsfiddle.net/herdiansc/dnznh/8/) And user **Baraka Mahili** ``` $('#show_password').hover(function functionName() { //Change the attribute to text $('#password').attr('type', 'text'); $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close'); }, function () { //Change the attribute back to password $('#password').attr('type', 'password'); $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open'); } ); https://codepen.io/GBMahili/pen/pEvVZP ```
280,022
<p>Is there a way that I can change the order of sections using custom fields?</p> <p>For example I have:</p> <pre><code>&lt;section id="1"&gt;&lt;/section&gt; &lt;section id="2"&gt;&lt;/section&gt; &lt;section id="3"&gt;&lt;/section&gt; &lt;section id="4"&gt;&lt;/section&gt; </code></pre> <p>And maybe the marketing team would like to try displaying section 4 first.</p> <p>I do use custom fields a lot to decide whether to display something...but changing the order I cannot think of a way to do it.</p> <p>Any ideas?</p>
[ { "answer_id": 280002, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": -1, "selected": false, "text": "<p>override by copying <code>woocommerce/templates/myaccount/form-login.php</code>. it to <code>yourtheme/woocommerce/myaccount/form-login.php</code>.</p>\n<p>and change password field attribute <code>type=&quot;password&quot;</code> to <code>type=&quot;text&quot;</code></p>\n<p>hope it will solve your problem.</p>\n" }, { "answer_id": 280011, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>Best way to do this, without making too many changes to the code, is to use JavaScript (jQuery) that will add Hide/Show capability to the existing password field.</p>\n\n<p>Excellent free jQuery plugin for that is: <a href=\"https://github.com/cloudfour/hideShowPassword\" rel=\"nofollow noreferrer\">HideShowPassword</a>. It has many ways to customize how the password will be visible.</p>\n" }, { "answer_id": 280014, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": true, "text": "<p>I would strongly disagree to show the <strong>password as the user typing it</strong>. \nYou could instead implement a way to show the status of the field with a user action like a <strong>user click</strong> to show password or on <strong>hover</strong>.\nThe reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it</p>\n\n<p>Some examples are:\n<a href=\"https://i.stack.imgur.com/LQmAf.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LQmAf.jpg\" alt=\"enter image description here\"></a>\nCode from <strong>herdiansc</strong> </p>\n\n<pre><code>//Place this plugin snippet into another file in your applicationb\n(function ($) {\n $.toggleShowPassword = function (options) {\n var settings = $.extend({\n field: \"#password\",\n control: \"#toggle_show_password\",\n }, options);\n\n var control = $(settings.control);\n var field = $(settings.field)\n\n control.bind('click', function () {\n if (control.is(':checked')) {\n field.attr('type', 'text');\n } else {\n field.attr('type', 'password');\n }\n })\n };\n}(jQuery));\n\n//Here how to call above plugin from everywhere in your application document body\n$.toggleShowPassword({\n field: '#test1',\n control: '#test2'\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/herdiansc/dnznh/8/\" rel=\"nofollow noreferrer\">jsfiddle</a></p>\n\n<p>And \nuser <strong>Baraka Mahili</strong></p>\n\n<pre><code>$('#show_password').hover(function functionName() {\n //Change the attribute to text\n $('#password').attr('type', 'text');\n $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close');\n }, function () {\n //Change the attribute back to password\n $('#password').attr('type', 'password');\n $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open');\n }\n );\nhttps://codepen.io/GBMahili/pen/pEvVZP\n</code></pre>\n" } ]
2017/09/14
[ "https://wordpress.stackexchange.com/questions/280022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127880/" ]
Is there a way that I can change the order of sections using custom fields? For example I have: ``` <section id="1"></section> <section id="2"></section> <section id="3"></section> <section id="4"></section> ``` And maybe the marketing team would like to try displaying section 4 first. I do use custom fields a lot to decide whether to display something...but changing the order I cannot think of a way to do it. Any ideas?
I would strongly disagree to show the **password as the user typing it**. You could instead implement a way to show the status of the field with a user action like a **user click** to show password or on **hover**. The reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it Some examples are: [![enter image description here](https://i.stack.imgur.com/LQmAf.jpg)](https://i.stack.imgur.com/LQmAf.jpg) Code from **herdiansc** ``` //Place this plugin snippet into another file in your applicationb (function ($) { $.toggleShowPassword = function (options) { var settings = $.extend({ field: "#password", control: "#toggle_show_password", }, options); var control = $(settings.control); var field = $(settings.field) control.bind('click', function () { if (control.is(':checked')) { field.attr('type', 'text'); } else { field.attr('type', 'password'); } }) }; }(jQuery)); //Here how to call above plugin from everywhere in your application document body $.toggleShowPassword({ field: '#test1', control: '#test2' }); ``` [jsfiddle](http://jsfiddle.net/herdiansc/dnznh/8/) And user **Baraka Mahili** ``` $('#show_password').hover(function functionName() { //Change the attribute to text $('#password').attr('type', 'text'); $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close'); }, function () { //Change the attribute back to password $('#password').attr('type', 'password'); $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open'); } ); https://codepen.io/GBMahili/pen/pEvVZP ```
280,023
<p>I want to rewrite custom post type slug. I used this snippet. but not working.</p> <pre><code>add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 ); function wpse247328_register_post_type_args( $args ) { if ( 'stores' === $post_type ) { $args['rewrite']['slug'] = 'location'; } return $args; } </code></pre>
[ { "answer_id": 280002, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": -1, "selected": false, "text": "<p>override by copying <code>woocommerce/templates/myaccount/form-login.php</code>. it to <code>yourtheme/woocommerce/myaccount/form-login.php</code>.</p>\n<p>and change password field attribute <code>type=&quot;password&quot;</code> to <code>type=&quot;text&quot;</code></p>\n<p>hope it will solve your problem.</p>\n" }, { "answer_id": 280011, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>Best way to do this, without making too many changes to the code, is to use JavaScript (jQuery) that will add Hide/Show capability to the existing password field.</p>\n\n<p>Excellent free jQuery plugin for that is: <a href=\"https://github.com/cloudfour/hideShowPassword\" rel=\"nofollow noreferrer\">HideShowPassword</a>. It has many ways to customize how the password will be visible.</p>\n" }, { "answer_id": 280014, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": true, "text": "<p>I would strongly disagree to show the <strong>password as the user typing it</strong>. \nYou could instead implement a way to show the status of the field with a user action like a <strong>user click</strong> to show password or on <strong>hover</strong>.\nThe reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it</p>\n\n<p>Some examples are:\n<a href=\"https://i.stack.imgur.com/LQmAf.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LQmAf.jpg\" alt=\"enter image description here\"></a>\nCode from <strong>herdiansc</strong> </p>\n\n<pre><code>//Place this plugin snippet into another file in your applicationb\n(function ($) {\n $.toggleShowPassword = function (options) {\n var settings = $.extend({\n field: \"#password\",\n control: \"#toggle_show_password\",\n }, options);\n\n var control = $(settings.control);\n var field = $(settings.field)\n\n control.bind('click', function () {\n if (control.is(':checked')) {\n field.attr('type', 'text');\n } else {\n field.attr('type', 'password');\n }\n })\n };\n}(jQuery));\n\n//Here how to call above plugin from everywhere in your application document body\n$.toggleShowPassword({\n field: '#test1',\n control: '#test2'\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/herdiansc/dnznh/8/\" rel=\"nofollow noreferrer\">jsfiddle</a></p>\n\n<p>And \nuser <strong>Baraka Mahili</strong></p>\n\n<pre><code>$('#show_password').hover(function functionName() {\n //Change the attribute to text\n $('#password').attr('type', 'text');\n $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close');\n }, function () {\n //Change the attribute back to password\n $('#password').attr('type', 'password');\n $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open');\n }\n );\nhttps://codepen.io/GBMahili/pen/pEvVZP\n</code></pre>\n" } ]
2017/09/14
[ "https://wordpress.stackexchange.com/questions/280023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116711/" ]
I want to rewrite custom post type slug. I used this snippet. but not working. ``` add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 ); function wpse247328_register_post_type_args( $args ) { if ( 'stores' === $post_type ) { $args['rewrite']['slug'] = 'location'; } return $args; } ```
I would strongly disagree to show the **password as the user typing it**. You could instead implement a way to show the status of the field with a user action like a **user click** to show password or on **hover**. The reason is that the user makes the decision to show the password. Also, improve the security as maybe the users are not alone when they typing it Some examples are: [![enter image description here](https://i.stack.imgur.com/LQmAf.jpg)](https://i.stack.imgur.com/LQmAf.jpg) Code from **herdiansc** ``` //Place this plugin snippet into another file in your applicationb (function ($) { $.toggleShowPassword = function (options) { var settings = $.extend({ field: "#password", control: "#toggle_show_password", }, options); var control = $(settings.control); var field = $(settings.field) control.bind('click', function () { if (control.is(':checked')) { field.attr('type', 'text'); } else { field.attr('type', 'password'); } }) }; }(jQuery)); //Here how to call above plugin from everywhere in your application document body $.toggleShowPassword({ field: '#test1', control: '#test2' }); ``` [jsfiddle](http://jsfiddle.net/herdiansc/dnznh/8/) And user **Baraka Mahili** ``` $('#show_password').hover(function functionName() { //Change the attribute to text $('#password').attr('type', 'text'); $('.glyphicon').removeClass('glyphicon-eye-open').addClass('glyphicon-eye-close'); }, function () { //Change the attribute back to password $('#password').attr('type', 'password'); $('.glyphicon').removeClass('glyphicon-eye-close').addClass('glyphicon-eye-open'); } ); https://codepen.io/GBMahili/pen/pEvVZP ```
280,035
<p>As you may know, when using the <code>&lt;?php</code> tag in a page, it automatically gets commented by WordPress. There are numerous famous plugins allowing to bypass this, such as "insert PHP", but they don't work on WordPress 4.8.1 (I tested a few deprecated ones).</p> <p>Does anyone know a way to use the <code>&lt;?php</code> tag correctly in WordPress 4.8.1 ?</p>
[ { "answer_id": 280037, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>Although the plugin Exce-WP <a href=\"https://wordpress.org/plugins/wp-exec-php/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-exec-php/</a> has not been updated for a while, it seems to work well with WP 4.8.1 on the several sites that I use it.</p>\n\n<p>(Expect a 'downvote' or 'hold' on this question because the moderators don't like 'opinion' questions. )</p>\n\n<p><strong>Added</strong></p>\n\n<p>Now that I think on this, there are security issues that might be involved if you let anyone include PHP code in a post or page, even with the use of shortcodes. Consider if a nefarious user added PHP code with a SQL statement to 'drop table'. Or insert malicious code on your page.</p>\n\n<p>It would be better to create a child theme and then a custom template that included your PHP code. That would be more secure.</p>\n\n<p>In my case, the site I use the PHP code plugin referenced is under my complete control; I am the only author. So in my case, the security risk is minimized, but not completely gone. </p>\n" }, { "answer_id": 280043, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": false, "text": "<p>Using the <code>&lt;?php</code> tag \"correctly\" - meaning the WordPress way - means you can't use it within post content.</p>\n\n<p>Some options you have:</p>\n\n<ol>\n<li><p>Use a shortcode instead. This will allow you to execute pre-written PHP within a post/page/CPT content editor. These allow parameters and can be pretty dynamic.</p></li>\n<li><p>Use a custom template. In a child theme, you have several ways to set a template up, and the template itself will contain the PHP you want to execute.</p>\n\n<ul>\n<li><p>You can name the file to be used automatically, such as page-slug.php - replace \"slug\" with your Page's actual slug, which is the last part of the permalink. If you have www.example.com/mypage set up as a Page, you would create a file called \"page-mypage.php\" and that would automatically apply to that page. For a Post, use \"post-mypage.php\" etc.</p></li>\n<li><p>Or, you can create a Page Template and manually select it. For example, you could create \"tpl-fancy.php\" with comments at the top of the file that name it the Fancy Page template. Then, when you create your Page, your Editor will have a dropdown menu that allows you to choose the Fancy Page template from a list. In this way, you can use the same template for multiple pages, and depending on what you want to accomplish this may be more efficient than making a separate template for each individual Page.</p></li>\n</ul></li>\n<li><p>Otherwise, you'll need to execute PHP in other parts of your template. For example if you have a widgetized sidebar, you can create a custom PHP widget and drag it into that area. If you need a custom menu, you can create that within the appropriate template file. It all depends on what particular type of PHP you want to execute.</p></li>\n</ol>\n\n<p>If you are able to update your question with more specific details about the code you want to execute, the community may have some suggestions on accomplishing that without enabling direct PHP execution within the content editor, which carries security risks.</p>\n" }, { "answer_id": 280044, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>As I mentioned in the comments, you should not and also can not use codes inside your content. Any code tags that you use will be escaped.</p>\n\n<p>Instead, define a <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"noreferrer\">shortcode</a> in your theme's <code>functions.php</code> file and use that inside your content. Let's create a simple shortcode together:</p>\n\n<pre><code>function create_shortcode( $atts ) {\n // Create a default value for the attributes\n $atts = shortcode_atts( \n array(\n 'parameter' =&gt; 'default value',\n ), \n $atts, \n 'my-shortcode' \n );\n\n // Add your functions here and return the value.\n // The value can be anything, including a full\n // HTML code or a form.\n return \"value = {$atts['paremeter']}\";\n}\nadd_shortcode( 'my-shortcode', 'create_shortcode' );\n</code></pre>\n\n<p>Now, by using <code>[my-shortcode parameter=\"sample\"]</code> in your content you can output <code>value = sample</code>. Replace the code inside the shortcode with whatever you desire, which in your case is a HTML form.</p>\n" } ]
2017/09/14
[ "https://wordpress.stackexchange.com/questions/280035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127874/" ]
As you may know, when using the `<?php` tag in a page, it automatically gets commented by WordPress. There are numerous famous plugins allowing to bypass this, such as "insert PHP", but they don't work on WordPress 4.8.1 (I tested a few deprecated ones). Does anyone know a way to use the `<?php` tag correctly in WordPress 4.8.1 ?
As I mentioned in the comments, you should not and also can not use codes inside your content. Any code tags that you use will be escaped. Instead, define a [shortcode](https://codex.wordpress.org/Function_Reference/add_shortcode) in your theme's `functions.php` file and use that inside your content. Let's create a simple shortcode together: ``` function create_shortcode( $atts ) { // Create a default value for the attributes $atts = shortcode_atts( array( 'parameter' => 'default value', ), $atts, 'my-shortcode' ); // Add your functions here and return the value. // The value can be anything, including a full // HTML code or a form. return "value = {$atts['paremeter']}"; } add_shortcode( 'my-shortcode', 'create_shortcode' ); ``` Now, by using `[my-shortcode parameter="sample"]` in your content you can output `value = sample`. Replace the code inside the shortcode with whatever you desire, which in your case is a HTML form.
280,088
<p>I want to create a splash page with a timer which disappears after 5 seconds when I open up the website before it opens up the main homepage. Any help on this will be highly appreciated. Thanks n advance</p>
[ { "answer_id": 280091, "author": "Richard Bos", "author_id": 127918, "author_profile": "https://wordpress.stackexchange.com/users/127918", "pm_score": -1, "selected": false, "text": "<p>The splash page is easy enough, that's in about half of all themes these days. To make it disappear, I would create a second page to be the real homepage and send the browser there from the splash page after five seconds.</p>\n\n<p>Ideally, I'd do that by putting a <code>header('refresh:5;url=/realhomepage/');</code> somewhere early in the splash page's code, but I haven't found that easy in WP - remember that it must be sent before you do <em>any</em> HTML output. Alternatively, you can put <code>&lt;meta http-equiv=\"refresh\" content=\"5; url=/realhomepage/\"&gt;</code> in the HTML header, which is easier but still ugly because you need to put a special case in <code>header.php</code>. In the end, I'd probably hack it by putting</p>\n\n<pre><code>sleep(5);\nwp_redirect('/realhomepage/');\nexit();\n</code></pre>\n\n<p>near the end of the splash page code.</p>\n\n<p>Also, speaking as a user rather than a programmer, I really, really wouldn't do this in the first place. Having to wait before I can use your site's functionality is a very good reason for me not to bother and to go to the competition instead.</p>\n" }, { "answer_id": 280094, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>I would propose first to make this at the front end. The reason is Google and other crawlers can read your content and don't penalize you for sneaky (the user didn't expect a redirect) redirects or slow loading times.</p>\n\n<p>What I would do:\nOn the main page :</p>\n\n<pre><code>function load_splash() {\n setTimeout(function () {\n $('#hiddendiv').hide();\n }, 5000);\n}\n</code></pre>\n\n<p>Now the load_splash can be called when the document ready</p>\n\n<pre><code>$( document ).ready(function() {\n load_splash( );\n});\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127917/" ]
I want to create a splash page with a timer which disappears after 5 seconds when I open up the website before it opens up the main homepage. Any help on this will be highly appreciated. Thanks n advance
I would propose first to make this at the front end. The reason is Google and other crawlers can read your content and don't penalize you for sneaky (the user didn't expect a redirect) redirects or slow loading times. What I would do: On the main page : ``` function load_splash() { setTimeout(function () { $('#hiddendiv').hide(); }, 5000); } ``` Now the load\_splash can be called when the document ready ``` $( document ).ready(function() { load_splash( ); }); ```
280,096
<p>Right now on my root folder, I have an "Under construction" page. So just an index.html, and a style. Then I have a test folder with Wordpress in it, so my website URL is root/test/wordpress. I want to "upload" the website to the root folder so I see the site instead of the under construction page. I have tried changing the website URL in the Wordpress dashboard but that does not work. I have also tried adding the new address in the wp-config file but that doesn't work either.</p>
[ { "answer_id": 280091, "author": "Richard Bos", "author_id": 127918, "author_profile": "https://wordpress.stackexchange.com/users/127918", "pm_score": -1, "selected": false, "text": "<p>The splash page is easy enough, that's in about half of all themes these days. To make it disappear, I would create a second page to be the real homepage and send the browser there from the splash page after five seconds.</p>\n\n<p>Ideally, I'd do that by putting a <code>header('refresh:5;url=/realhomepage/');</code> somewhere early in the splash page's code, but I haven't found that easy in WP - remember that it must be sent before you do <em>any</em> HTML output. Alternatively, you can put <code>&lt;meta http-equiv=\"refresh\" content=\"5; url=/realhomepage/\"&gt;</code> in the HTML header, which is easier but still ugly because you need to put a special case in <code>header.php</code>. In the end, I'd probably hack it by putting</p>\n\n<pre><code>sleep(5);\nwp_redirect('/realhomepage/');\nexit();\n</code></pre>\n\n<p>near the end of the splash page code.</p>\n\n<p>Also, speaking as a user rather than a programmer, I really, really wouldn't do this in the first place. Having to wait before I can use your site's functionality is a very good reason for me not to bother and to go to the competition instead.</p>\n" }, { "answer_id": 280094, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>I would propose first to make this at the front end. The reason is Google and other crawlers can read your content and don't penalize you for sneaky (the user didn't expect a redirect) redirects or slow loading times.</p>\n\n<p>What I would do:\nOn the main page :</p>\n\n<pre><code>function load_splash() {\n setTimeout(function () {\n $('#hiddendiv').hide();\n }, 5000);\n}\n</code></pre>\n\n<p>Now the load_splash can be called when the document ready</p>\n\n<pre><code>$( document ).ready(function() {\n load_splash( );\n});\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280096", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115742/" ]
Right now on my root folder, I have an "Under construction" page. So just an index.html, and a style. Then I have a test folder with Wordpress in it, so my website URL is root/test/wordpress. I want to "upload" the website to the root folder so I see the site instead of the under construction page. I have tried changing the website URL in the Wordpress dashboard but that does not work. I have also tried adding the new address in the wp-config file but that doesn't work either.
I would propose first to make this at the front end. The reason is Google and other crawlers can read your content and don't penalize you for sneaky (the user didn't expect a redirect) redirects or slow loading times. What I would do: On the main page : ``` function load_splash() { setTimeout(function () { $('#hiddendiv').hide(); }, 5000); } ``` Now the load\_splash can be called when the document ready ``` $( document ).ready(function() { load_splash( ); }); ```
280,098
<p>I need to send an email to the admin user when a post of the post type "task" is created. Any help would be really appreciated. Thanks!</p>
[ { "answer_id": 280103, "author": "Asisten", "author_id": 88402, "author_profile": "https://wordpress.stackexchange.com/users/88402", "pm_score": 1, "selected": false, "text": "<p>You can add action after wp insert post with specified post type:</p>\n\n<pre><code> function after_task_post_created( $post_id ) {\n //no action if post type not task\n if (get_post_type($post_id) != 'task')\n return;\n // If this is a revision, don't send the email.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n // if post not yet published so no action taken, i know it can be confused\n if (get_post_status( $post_id ) != 'publish' )\n return;\n\n\n // your email action\n\n $yoursubject = 'This is your email subject';\n\n $yourmessage = \"a body message here\";\n\n // Send email.\n $adminemail = get_option( 'admin_email' );\n wp_mail( $adminemail, $yoursubject, $yourmessage );\n }\n add_action( 'wp_insert_post', 'after_task_post_created');\n</code></pre>\n\n<p>reference:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_post_type/</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_option/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_option/</a></p>\n" }, { "answer_id": 280104, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>You could use this very easy action to control more than the creation of the custom post_type</p>\n\n<pre><code>add_action( 'transition_post_status', 'transition_fun', 10, 3 );\nfunction transition_fun( $new, $old, $post ) {\n if ( ( $new == 'publish' ) &amp;&amp; ( $old != 'publish' || $old != 'auto-draft' ) &amp;&amp; ( $post-&gt;post_type == 'task' ) ) {\n echo 'send mail......';\n } else {\n return;\n }\n}\n</code></pre>\n\n<p>Just insert that to your <strong>functions.php</strong> or as a <strong>plugin</strong>.</p>\n\n<p>If for example later you want to have access to the draft status you could easily do that with the 'auto-draft'</p>\n" }, { "answer_id": 280153, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": true, "text": "<p>If you want to send an email <strong>on first publish and on updates</strong>, you can avoid many extra checks by using {<code>status</code>}_{<code>post type</code>} action hook. Put the code below into the current theme's functions.php: </p>\n\n<pre><code>add_action( 'publish_task', 'wpse_admin_email', 10, 2 );\nfunction wpse_admin_email( $post_id, $post ) {\n // prepare and send email code goes here...\n}\n</code></pre>\n\n<p>If you want to send an email <strong>on first publish only</strong>, use the code below:</p>\n\n<pre><code>add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 );\nfunction wpse_admin_email_once( $new, $old, $post ) {\n if ( $post-&gt;post_type == 'task' &amp;&amp; $new == 'publish' &amp;&amp; $old == 'auto-draft' ) {\n // prepare and send email code goes here...\n }\n}\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280098", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81609/" ]
I need to send an email to the admin user when a post of the post type "task" is created. Any help would be really appreciated. Thanks!
If you want to send an email **on first publish and on updates**, you can avoid many extra checks by using {`status`}\_{`post type`} action hook. Put the code below into the current theme's functions.php: ``` add_action( 'publish_task', 'wpse_admin_email', 10, 2 ); function wpse_admin_email( $post_id, $post ) { // prepare and send email code goes here... } ``` If you want to send an email **on first publish only**, use the code below: ``` add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 ); function wpse_admin_email_once( $new, $old, $post ) { if ( $post->post_type == 'task' && $new == 'publish' && $old == 'auto-draft' ) { // prepare and send email code goes here... } } ```
280,123
<p>I'm trying to unpublish (set post_status to draft) all posts when a new one (with specific conditions that don't really matter right now) is published. </p> <p>Here's what I currently have:</p> <pre><code>function rsc_unpublish_all_ads( $post_id ) { // don't do anything if the post is not an ad $post_type = get_post_type($post_id); if ( 'rsc-ads' != $post_type ) return; // select all ads other than the current one $args = array( 'posts_per_page' =&gt; -1, 'post__not_in' =&gt; array($post_id), 'post_type' =&gt; 'rsc-ads', 'post_status' =&gt; 'publish', ); $published_ads = get_posts( $args ); if ( !empty($published_ads) ) { // set each of the published ads as draft foreach ($published_ads as $published_ad) { // check again just for the sake of it? if ( $published_ad-&gt;ID == $post_id ) return; $unpublish = array( 'ID' =&gt; $published_ad-&gt;ID, 'post_status' =&gt; 'draft' ); wp_update_post( $unpublish ); } } } add_action( 'save_post', 'rsc_unpublish_all_ads' ); </code></pre> <p>What happens is all rsc-ads posts are set to draft <strong>including</strong> the one I'm saving/updating – even though I'm checking against it twice (<code>post__not_in</code> in the <code>$args</code> AND comparing the ID in the foreach loop).</p> <p>I know <code>$post_id</code> is correct because I'm checking for post type at the beginning of my function and that works fine.</p> <p>Any ideas how to exclude the currently-being-saved post from being updated?</p>
[ { "answer_id": 280103, "author": "Asisten", "author_id": 88402, "author_profile": "https://wordpress.stackexchange.com/users/88402", "pm_score": 1, "selected": false, "text": "<p>You can add action after wp insert post with specified post type:</p>\n\n<pre><code> function after_task_post_created( $post_id ) {\n //no action if post type not task\n if (get_post_type($post_id) != 'task')\n return;\n // If this is a revision, don't send the email.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n // if post not yet published so no action taken, i know it can be confused\n if (get_post_status( $post_id ) != 'publish' )\n return;\n\n\n // your email action\n\n $yoursubject = 'This is your email subject';\n\n $yourmessage = \"a body message here\";\n\n // Send email.\n $adminemail = get_option( 'admin_email' );\n wp_mail( $adminemail, $yoursubject, $yourmessage );\n }\n add_action( 'wp_insert_post', 'after_task_post_created');\n</code></pre>\n\n<p>reference:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_post_type/</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_option/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_option/</a></p>\n" }, { "answer_id": 280104, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>You could use this very easy action to control more than the creation of the custom post_type</p>\n\n<pre><code>add_action( 'transition_post_status', 'transition_fun', 10, 3 );\nfunction transition_fun( $new, $old, $post ) {\n if ( ( $new == 'publish' ) &amp;&amp; ( $old != 'publish' || $old != 'auto-draft' ) &amp;&amp; ( $post-&gt;post_type == 'task' ) ) {\n echo 'send mail......';\n } else {\n return;\n }\n}\n</code></pre>\n\n<p>Just insert that to your <strong>functions.php</strong> or as a <strong>plugin</strong>.</p>\n\n<p>If for example later you want to have access to the draft status you could easily do that with the 'auto-draft'</p>\n" }, { "answer_id": 280153, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": true, "text": "<p>If you want to send an email <strong>on first publish and on updates</strong>, you can avoid many extra checks by using {<code>status</code>}_{<code>post type</code>} action hook. Put the code below into the current theme's functions.php: </p>\n\n<pre><code>add_action( 'publish_task', 'wpse_admin_email', 10, 2 );\nfunction wpse_admin_email( $post_id, $post ) {\n // prepare and send email code goes here...\n}\n</code></pre>\n\n<p>If you want to send an email <strong>on first publish only</strong>, use the code below:</p>\n\n<pre><code>add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 );\nfunction wpse_admin_email_once( $new, $old, $post ) {\n if ( $post-&gt;post_type == 'task' &amp;&amp; $new == 'publish' &amp;&amp; $old == 'auto-draft' ) {\n // prepare and send email code goes here...\n }\n}\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280123", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121195/" ]
I'm trying to unpublish (set post\_status to draft) all posts when a new one (with specific conditions that don't really matter right now) is published. Here's what I currently have: ``` function rsc_unpublish_all_ads( $post_id ) { // don't do anything if the post is not an ad $post_type = get_post_type($post_id); if ( 'rsc-ads' != $post_type ) return; // select all ads other than the current one $args = array( 'posts_per_page' => -1, 'post__not_in' => array($post_id), 'post_type' => 'rsc-ads', 'post_status' => 'publish', ); $published_ads = get_posts( $args ); if ( !empty($published_ads) ) { // set each of the published ads as draft foreach ($published_ads as $published_ad) { // check again just for the sake of it? if ( $published_ad->ID == $post_id ) return; $unpublish = array( 'ID' => $published_ad->ID, 'post_status' => 'draft' ); wp_update_post( $unpublish ); } } } add_action( 'save_post', 'rsc_unpublish_all_ads' ); ``` What happens is all rsc-ads posts are set to draft **including** the one I'm saving/updating – even though I'm checking against it twice (`post__not_in` in the `$args` AND comparing the ID in the foreach loop). I know `$post_id` is correct because I'm checking for post type at the beginning of my function and that works fine. Any ideas how to exclude the currently-being-saved post from being updated?
If you want to send an email **on first publish and on updates**, you can avoid many extra checks by using {`status`}\_{`post type`} action hook. Put the code below into the current theme's functions.php: ``` add_action( 'publish_task', 'wpse_admin_email', 10, 2 ); function wpse_admin_email( $post_id, $post ) { // prepare and send email code goes here... } ``` If you want to send an email **on first publish only**, use the code below: ``` add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 ); function wpse_admin_email_once( $new, $old, $post ) { if ( $post->post_type == 'task' && $new == 'publish' && $old == 'auto-draft' ) { // prepare and send email code goes here... } } ```
280,125
<p>I would like to have a separate url for each of my product variations. For that I would need to create a rewrite rule, that will work on the product URLs</p> <p>Ie, my product URL is <code>https://example.com/product/tshirt/</code> </p> <p>The product has two variations - size and color. I would like to be able to access the product on url like <code>https://example.com/product/tshirt/size-s-color-black</code></p> <p>This clearly has something to do with the <code>add_rewrite_rule</code> function. I don't know how to build the url structure to be able to access the variations part of url</p> <pre><code>function custom_rewrite_basic() { add_rewrite_rule('^product/([0-9]+)/([0-9]+)?', 'index.php?page_id=$matches[1]&amp;variations=$matches[2]', 'top'); } add_action('init', 'custom_rewrite_basic'); </code></pre> <p>Anyone?</p>
[ { "answer_id": 287827, "author": "user1049961", "author_id": 47664, "author_profile": "https://wordpress.stackexchange.com/users/47664", "pm_score": 4, "selected": true, "text": "<p>Ok, for anyone looking for this, here's a complete plugin that I came up with, that solves the issue:</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: WooCommerce Variations URL\nDescription: Adds support for variation-specific URL's for WooCommerce product variations\nAuthor: Václav Greif\nVersion: 1.0\nAuthor URI: https://wp-programator.cz\n*/\n\nnamespace WCVariationsUrl;\n\nfinal class Init\n{\n /**\n * Call this method to get singleton\n *\n * @return Init\n */\n public static function Instance()\n {\n static $inst = null;\n if ($inst === null) {\n $inst = new Init();\n }\n return $inst;\n }\n\n /**\n * Private ctor so nobody else can instance it\n *\n */\n private function __construct()\n {\n $this-&gt;add_actions();\n }\n\n /**\n * Add actions\n */\n function add_actions() {\n add_filter('woocommerce_dropdown_variation_attribute_options_args',array($this,'variation_dropdown_args'));\n add_action('init', array($this,'add_rewrite_rules'));\n add_action('wp_head', array($this,'add_js_to_head'));\n\n }\n\n function variation_dropdown_args($args) {\n // Get the WooCommerce atts\n $attributes = wc_get_attribute_taxonomies();\n $atts = [];\n foreach ($attributes as $attribute) {\n $atts[] = $attribute-&gt;attribute_name;\n }\n\n // Get the variations part of URL\n $url_string = get_query_var('variation');\n\n if ($url_string) {\n $array = [];\n preg_replace_callback(\n \"/(\\w++)(?&gt;-(\\w+-?(?(?!\" . implode(\"|\", $atts) . \")(?-1))*))/\",\n function($matches) use (&amp;$array) {\n $array[$matches[1]] = rtrim($matches[2], '-');\n },\n $url_string\n );\n\n if (!empty($array)) {\n $attribute_key = str_replace('pa_','',$args['attribute']);\n\n if (array_key_exists($attribute_key,$array)) {\n $args['selected'] = $array[$attribute_key];\n }\n }\n }\n\n return $args;\n\n }\n\n function add_rewrite_rules() {\n add_rewrite_rule('^product/([^/]*)/([^/]*)/?','index.php?product=$matches[1]&amp;variation=$matches[2]','top');\n add_rewrite_tag('%variation%', '([^&amp;]+)');\n }\n\n function add_js_to_head() {\n if (!function_exists('is_product') || !is_product())\n return;\n\n global $post;\n ?&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n var url = '&lt;?php echo get_permalink($post-&gt;ID);?&gt;';\n jQuery( document ).ready(function($) {\n setTimeout(\n function() {\n $('table.variations select').on('change',function() {\n var attributes = [];\n var allAttributesSet = true;\n $('table.variations select').each(function() {\n var value = $(this).val();\n if (value) {\n attributes.push({\n id: $(this).attr('name'),\n value: value\n });\n } else {\n allAttributesSet = false;\n }\n });\n\n if (allAttributesSet) {\n $.each(attributes,function(key, val) {\n var attributeSlug = val.id.replace('attribute_pa_','');\n url = url + attributeSlug + '-' + val.value\n if($(this)[0] !== $(attributes).last()[0]) {\n url = url + '-';\n }\n });\n window.location.replace(url);\n }\n });\n\n }, 1000\n )\n });\n &lt;/script&gt;\n &lt;?php }\n}\n\nInit::Instance();\n</code></pre>\n" }, { "answer_id": 362814, "author": "David Salcer", "author_id": 169650, "author_profile": "https://wordpress.stackexchange.com/users/169650", "pm_score": 0, "selected": false, "text": "<p>My intention: On change reload page, pass the ID as URL?attribute so i can get it on next page as GET.\nI had simmilar intention. But I wanted to pass this into the URL as an better attribute.\nThe advice here did not really suited my intention so I a bit modified it for my purpose.\nThe shop I needed this was really using intentionally and specifically only single variations, no 2-3 mixed together.</p>\n\n<pre><code>&lt;script&gt;\n jQuery(function($){\n setTimeout( function(){\n $( \".single_variation_wrap\" ).on( \"show_variation\", function ( event, variation ) {\n //alert( variation.variation_id );\n console.log( variation.variation_id );\n\n\n var url = '&lt;?php echo get_permalink($post-&gt;ID);?&gt;';\n //$('input.variation_id').change( function(){\n\n\n console.log('You just selected variation #' + variation.variation_id);\n var attributes = [];\n var allAttributesSet = true;\n $('table.variations select').each(function() {\n var value = $(this).val();\n if (value) {\n attributes.push({\n id: $(this).attr('name'),\n value: value\n });\n } else {\n allAttributesSet = false;\n }\n });\n if (allAttributesSet) {\n $.each(attributes,function(key, val) {\n var attributeSlug = val.id.replace('attribute_pa_','');\n url = url +'?variation_id='+ variation.variation_id +'&amp;'+attributeSlug+'=' + val.value;\n });\n console.log('Relocating #' + variation.variation_id);\n //window.location.replace(url);\n window.location.href = url;\n }\n\n } );\n }, 400 );\n\n });\n &lt;/script&gt;\n</code></pre>\n\n<p>Not sure if this is the best and good approach, but this is what is working for me, and it even keeps the selected values in Variation dropdown since it is only single one.</p>\n\n<p>I am calling the script above in this action:</p>\n\n<p>add_action( 'woocommerce_before_add_to_cart_quantity', 'destone_variation_modification' );</p>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280125", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47664/" ]
I would like to have a separate url for each of my product variations. For that I would need to create a rewrite rule, that will work on the product URLs Ie, my product URL is `https://example.com/product/tshirt/` The product has two variations - size and color. I would like to be able to access the product on url like `https://example.com/product/tshirt/size-s-color-black` This clearly has something to do with the `add_rewrite_rule` function. I don't know how to build the url structure to be able to access the variations part of url ``` function custom_rewrite_basic() { add_rewrite_rule('^product/([0-9]+)/([0-9]+)?', 'index.php?page_id=$matches[1]&variations=$matches[2]', 'top'); } add_action('init', 'custom_rewrite_basic'); ``` Anyone?
Ok, for anyone looking for this, here's a complete plugin that I came up with, that solves the issue: ``` <?php /* Plugin Name: WooCommerce Variations URL Description: Adds support for variation-specific URL's for WooCommerce product variations Author: Václav Greif Version: 1.0 Author URI: https://wp-programator.cz */ namespace WCVariationsUrl; final class Init { /** * Call this method to get singleton * * @return Init */ public static function Instance() { static $inst = null; if ($inst === null) { $inst = new Init(); } return $inst; } /** * Private ctor so nobody else can instance it * */ private function __construct() { $this->add_actions(); } /** * Add actions */ function add_actions() { add_filter('woocommerce_dropdown_variation_attribute_options_args',array($this,'variation_dropdown_args')); add_action('init', array($this,'add_rewrite_rules')); add_action('wp_head', array($this,'add_js_to_head')); } function variation_dropdown_args($args) { // Get the WooCommerce atts $attributes = wc_get_attribute_taxonomies(); $atts = []; foreach ($attributes as $attribute) { $atts[] = $attribute->attribute_name; } // Get the variations part of URL $url_string = get_query_var('variation'); if ($url_string) { $array = []; preg_replace_callback( "/(\w++)(?>-(\w+-?(?(?!" . implode("|", $atts) . ")(?-1))*))/", function($matches) use (&$array) { $array[$matches[1]] = rtrim($matches[2], '-'); }, $url_string ); if (!empty($array)) { $attribute_key = str_replace('pa_','',$args['attribute']); if (array_key_exists($attribute_key,$array)) { $args['selected'] = $array[$attribute_key]; } } } return $args; } function add_rewrite_rules() { add_rewrite_rule('^product/([^/]*)/([^/]*)/?','index.php?product=$matches[1]&variation=$matches[2]','top'); add_rewrite_tag('%variation%', '([^&]+)'); } function add_js_to_head() { if (!function_exists('is_product') || !is_product()) return; global $post; ?> <script type="text/javascript"> var url = '<?php echo get_permalink($post->ID);?>'; jQuery( document ).ready(function($) { setTimeout( function() { $('table.variations select').on('change',function() { var attributes = []; var allAttributesSet = true; $('table.variations select').each(function() { var value = $(this).val(); if (value) { attributes.push({ id: $(this).attr('name'), value: value }); } else { allAttributesSet = false; } }); if (allAttributesSet) { $.each(attributes,function(key, val) { var attributeSlug = val.id.replace('attribute_pa_',''); url = url + attributeSlug + '-' + val.value if($(this)[0] !== $(attributes).last()[0]) { url = url + '-'; } }); window.location.replace(url); } }); }, 1000 ) }); </script> <?php } } Init::Instance(); ```
280,146
<p>I want to remove automatically the <em>Home</em> menu item, <strong>but only once</strong>, more precisely <strong>at the first run of Wordpress or at the first child theme activation/loading</strong>. Now I have a function in the functions.php of my child theme that checks if the <em>Home</em> menu item exists and delete it from the menu. Of course, this function runs every time when Wordpress loads. <strong>How to make it to run only once?</strong> I tried the <code>add_filter_once()</code> function, but I got only a <code>PHP Fatal error: Call to undefined function add_filter_once()</code>.</p> <pre><code>function filter_wp_nav_menu_objects( $sorted_menu_items, $args ) { foreach( $sorted_menu_items as $data ) { if ( in_array( &quot;menu-item-home&quot;, $data-&gt;classes ) ) { wp_delete_post( $data-&gt;ID ); } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'filter_wp_nav_menu_objects', 10, 2 ); </code></pre>
[ { "answer_id": 379826, "author": "Tariq Ahmed", "author_id": 119429, "author_profile": "https://wordpress.stackexchange.com/users/119429", "pm_score": 4, "selected": true, "text": "<p>There is no native WordPress hook called <code>add_filter_once()</code>. This is an custom solution which will help you to run your hook only once.</p>\n<p>For example if inside a loop or whatever situation you are facing. However,\nThe basic idea is to check when you need to stop using your hook and simply <strong>remove_hook</strong> from WordPress and once all done, you need to registere it again.</p>\n<p>example code:</p>\n<pre><code>function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) {\n $singular = function () use ( $hook, $callback, $priority, $args, &amp;$singular ) {\n call_user_func_array( $callback, func_get_args() );\n remove_filter( $hook, $singular, $priority );\n };\n\n return add_filter( $hook, $singular, $priority, $args );\n}\n</code></pre>\n<p>The best way to understand what I try to explain to visit this <a href=\"https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb\" rel=\"nofollow noreferrer\">link</a></p>\n" }, { "answer_id": 403037, "author": "David Wolf", "author_id": 218274, "author_profile": "https://wordpress.stackexchange.com/users/218274", "pm_score": 1, "selected": false, "text": "<p>An ugly but working way to accomplish this would be to have an <code>global</code> array, and inside your filter callback, you would check if the array already contains the hook name of the filter, you only want to apply once. If it turns out, that the value is already set, the callback will immediately return the input.</p>\n<p>Technically, your filter will run every time, but the logic won't be applied each time, since it will skip for the 2nd execution and up.</p>\n<p>This technique also works for class based filters, which somehow are not treated equally by WordPress, for example removing a class based filter is some sort of mess.</p>\n<pre class=\"lang-php prettyprint-override\"><code> // … inside a class\n\n public function addMyFilter()\n {\n add_filter('some_filter', [$this, 'someMethod']);\n }\n\n public function someMethod($val)\n {\n global $myFiltersThatWhereExecAlready;\n\n if (empty($myFiltersThatWhereExecAlready)) {\n $myFiltersThatWhereExecAlready = [];\n }\n\n if (in_array(__METHOD__, $myFiltersThatWhereExecAlready)) {\n return $val;\n }\n\n $myFiltersThatWhereExecAlready[] = __METHOD__;\n\n // … doing your filtering\n }\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280146", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I want to remove automatically the *Home* menu item, **but only once**, more precisely **at the first run of Wordpress or at the first child theme activation/loading**. Now I have a function in the functions.php of my child theme that checks if the *Home* menu item exists and delete it from the menu. Of course, this function runs every time when Wordpress loads. **How to make it to run only once?** I tried the `add_filter_once()` function, but I got only a `PHP Fatal error: Call to undefined function add_filter_once()`. ``` function filter_wp_nav_menu_objects( $sorted_menu_items, $args ) { foreach( $sorted_menu_items as $data ) { if ( in_array( "menu-item-home", $data->classes ) ) { wp_delete_post( $data->ID ); } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'filter_wp_nav_menu_objects', 10, 2 ); ```
There is no native WordPress hook called `add_filter_once()`. This is an custom solution which will help you to run your hook only once. For example if inside a loop or whatever situation you are facing. However, The basic idea is to check when you need to stop using your hook and simply **remove\_hook** from WordPress and once all done, you need to registere it again. example code: ``` function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) { $singular = function () use ( $hook, $callback, $priority, $args, &$singular ) { call_user_func_array( $callback, func_get_args() ); remove_filter( $hook, $singular, $priority ); }; return add_filter( $hook, $singular, $priority, $args ); } ``` The best way to understand what I try to explain to visit this [link](https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb)
280,151
<p>I am saving a post id in a variable with the_id() function. And then i need to fetch the data of same post id from database . As post id is working fine but i am getting error while executing get result . below is the code . Can anyone please help ?</p> <pre><code> $a = the_ID();; global $wpdb; $data = $wpdb-&gt;get_results("SELECT `id`,`guid` FROM `wp_posts` WHERE `post_type` = 'local-offer' group by `post_author`"); $result = $wpdb-&gt;get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$a." "); </code></pre>
[ { "answer_id": 379826, "author": "Tariq Ahmed", "author_id": 119429, "author_profile": "https://wordpress.stackexchange.com/users/119429", "pm_score": 4, "selected": true, "text": "<p>There is no native WordPress hook called <code>add_filter_once()</code>. This is an custom solution which will help you to run your hook only once.</p>\n<p>For example if inside a loop or whatever situation you are facing. However,\nThe basic idea is to check when you need to stop using your hook and simply <strong>remove_hook</strong> from WordPress and once all done, you need to registere it again.</p>\n<p>example code:</p>\n<pre><code>function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) {\n $singular = function () use ( $hook, $callback, $priority, $args, &amp;$singular ) {\n call_user_func_array( $callback, func_get_args() );\n remove_filter( $hook, $singular, $priority );\n };\n\n return add_filter( $hook, $singular, $priority, $args );\n}\n</code></pre>\n<p>The best way to understand what I try to explain to visit this <a href=\"https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb\" rel=\"nofollow noreferrer\">link</a></p>\n" }, { "answer_id": 403037, "author": "David Wolf", "author_id": 218274, "author_profile": "https://wordpress.stackexchange.com/users/218274", "pm_score": 1, "selected": false, "text": "<p>An ugly but working way to accomplish this would be to have an <code>global</code> array, and inside your filter callback, you would check if the array already contains the hook name of the filter, you only want to apply once. If it turns out, that the value is already set, the callback will immediately return the input.</p>\n<p>Technically, your filter will run every time, but the logic won't be applied each time, since it will skip for the 2nd execution and up.</p>\n<p>This technique also works for class based filters, which somehow are not treated equally by WordPress, for example removing a class based filter is some sort of mess.</p>\n<pre class=\"lang-php prettyprint-override\"><code> // … inside a class\n\n public function addMyFilter()\n {\n add_filter('some_filter', [$this, 'someMethod']);\n }\n\n public function someMethod($val)\n {\n global $myFiltersThatWhereExecAlready;\n\n if (empty($myFiltersThatWhereExecAlready)) {\n $myFiltersThatWhereExecAlready = [];\n }\n\n if (in_array(__METHOD__, $myFiltersThatWhereExecAlready)) {\n return $val;\n }\n\n $myFiltersThatWhereExecAlready[] = __METHOD__;\n\n // … doing your filtering\n }\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127961/" ]
I am saving a post id in a variable with the\_id() function. And then i need to fetch the data of same post id from database . As post id is working fine but i am getting error while executing get result . below is the code . Can anyone please help ? ``` $a = the_ID();; global $wpdb; $data = $wpdb->get_results("SELECT `id`,`guid` FROM `wp_posts` WHERE `post_type` = 'local-offer' group by `post_author`"); $result = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$a." "); ```
There is no native WordPress hook called `add_filter_once()`. This is an custom solution which will help you to run your hook only once. For example if inside a loop or whatever situation you are facing. However, The basic idea is to check when you need to stop using your hook and simply **remove\_hook** from WordPress and once all done, you need to registere it again. example code: ``` function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) { $singular = function () use ( $hook, $callback, $priority, $args, &$singular ) { call_user_func_array( $callback, func_get_args() ); remove_filter( $hook, $singular, $priority ); }; return add_filter( $hook, $singular, $priority, $args ); } ``` The best way to understand what I try to explain to visit this [link](https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb)
280,156
<p>We are trying to get our set up an SMTP function but keep hitting errors with the test email. We even tried both WP-Mail-SMTP and Easy WP SMTP. After talking with our host at WPEngine we couldn't find any issue on their end since they do use OpenSSL and told us to use port 2525 since we are using Outlook. Our IT department also said that port should work just fine and isn't blocked by Outlook. I even used another SMTP hostname of premierdisability-com.mail.protection.outlook.com. However, that one gave the same error but said connection Timed Out instead of Network is unreachable. </p> <p>The only option I can think of is editing/swapping the class-phpmailer.php and class-smtp.php files with an older version. But Easy WP SMTP says it should be compatible with our setup of WP (WP v4.8, PHP v5.6). Do you think that would be a good option to try or know of anything else to try?</p> <pre><code> object(PHPMailer)#1882 (76) { ["Version"]=&gt; string(6) "5.2.22" ["Priority"]=&gt; NULL ["CharSet"]=&gt; string(5) "UTF-8" ["ContentType"]=&gt; string(10) "text/plain" ["Encoding"]=&gt; string(4) "7bit" ["ErrorInfo"]=&gt; string(82) "SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting" ["From"]=&gt; string(34) "[email protected]" ["FromName"]=&gt; string(27) "Premier Disability Services" ["Sender"]=&gt; string(34) "[email protected]" ["ReturnPath"]=&gt; string(0) "" ["Subject"]=&gt; string(56) "WP Mail SMTP: Test mail to [email protected]" ["Body"]=&gt; string(68) "This is a test email generated by the WP Mail SMTP WordPress plugin." ["AltBody"]=&gt; string(0) "" ["Ical"]=&gt; string(0) "" ["MIMEBody":protected]=&gt; string(69) "This is a test email generated by the WP Mail SMTP WordPress plugin. " ["MIMEHeader":protected]=&gt; string(405) "Date: Fri, 15 Sep 2017 18:16:49 +0000 To: [email protected] From: Premier Disability Services Subject: WP Mail SMTP: Test mail to [email protected] Message-ID: &lt;[email protected]&gt; X-Mailer: PHPMailer 5.2.22 (https://github.com/PHPMailer/PHPMailer) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 " ["mailHeader":protected]=&gt; string(0) "" ["WordWrap"]=&gt; int(0) ["Mailer"]=&gt; string(4) "smtp" ["Sendmail"]=&gt; string(18) "/usr/sbin/sendmail" ["UseSendmailOptions"]=&gt; bool(true) ["PluginDir"]=&gt; string(0) "" ["ConfirmReadingTo"]=&gt; string(0) "" ["Hostname"]=&gt; string(0) "" ["MessageID"]=&gt; string(0) "" ["MessageDate"]=&gt; string(31) "Fri, 15 Sep 2017 18:16:49 +0000" ["Host"]=&gt; string(18) "smtp.office365.com" ["Port"]=&gt; string(4) "2525" ["Helo"]=&gt; string(0) "" ["SMTPSecure"]=&gt; string(3) "tls" ["SMTPAutoTLS"]=&gt; bool(false) ["SMTPAuth"]=&gt; bool(true) ["SMTPOptions"]=&gt; array(0) { } ["Username"]=&gt; string(34) "[email protected]" ["Password"]=&gt; string(8) "*******" ["AuthType"]=&gt; string(0) "" ["Realm"]=&gt; string(0) "" ["Workstation"]=&gt; string(0) "" ["Timeout"]=&gt; int(300) ["SMTPDebug"]=&gt; bool(true) ["Debugoutput"]=&gt; string(4) "echo" ["SMTPKeepAlive"]=&gt; bool(false) ["SingleTo"]=&gt; bool(false) ["SingleToArray"]=&gt; array(0) { } ["do_verp"]=&gt; bool(false) ["AllowEmpty"]=&gt; bool(false) ["LE"]=&gt; string(1) " " ["DKIM_selector"]=&gt; string(0) "" ["DKIM_identity"]=&gt; string(0) "" ["DKIM_passphrase"]=&gt; string(0) "" ["DKIM_domain"]=&gt; string(0) "" ["DKIM_private"]=&gt; string(0) "" ["DKIM_private_string"]=&gt; string(0) "" ["action_function"]=&gt; string(0) "" ["XMailer"]=&gt; string(0) "" ["smtp":protected]=&gt; object(SMTP)#1886 (14) { ["Version"]=&gt; string(6) "5.2.22" ["SMTP_PORT"]=&gt; int(25) ["CRLF"]=&gt; string(2) " " ["do_debug"]=&gt; bool(true) ["Debugoutput"]=&gt; string(4) "echo" ["do_verp"]=&gt; bool(false) ["Timeout"]=&gt; int(300) ["Timelimit"]=&gt; int(300) ["smtp_transaction_id_patterns":protected]=&gt; array(3) { ["exim"]=&gt; string(21) "/[0-9]{3} OK id=(.*)/" ["sendmail"]=&gt; string(29) "/[0-9]{3} 2.0.0 (.*) Message/" ["postfix"]=&gt; string(35) "/[0-9]{3} 2.0.0 Ok: queued as (.*)/" } ["smtp_conn":protected]=&gt; bool(false) ["error":protected]=&gt; array(4) { ["error"]=&gt; string(0) "" ["detail"]=&gt; string(0) "" ["smtp_code"]=&gt; string(0) "" ["smtp_code_ex"]=&gt; string(0) "" } ["helo_rply":protected]=&gt; NULL ["server_caps":protected]=&gt; NULL ["last_reply":protected]=&gt; string(0) "" } ["to":protected]=&gt; array(1) { [0]=&gt; array(2) { [0]=&gt; string(29) "[email protected]" [1]=&gt; string(0) "" } } ["cc":protected]=&gt; array(0) { } ["bcc":protected]=&gt; array(0) { } ["ReplyTo":protected]=&gt; array(0) { } ["all_recipients":protected]=&gt; array(1) { ["[email protected]"]=&gt; bool(true) } ["RecipientsQueue":protected]=&gt; array(0) { } ["ReplyToQueue":protected]=&gt; array(0) { } ["attachment":protected]=&gt; array(0) { } ["CustomHeader":protected]=&gt; array(0) { } ["lastMessageID":protected]=&gt; string(56) "&lt;[email protected]&gt;" ["message_type":protected]=&gt; string(5) "plain" ["boundary":protected]=&gt; array(3) { [1]=&gt; string(35) "b1_2b81fcc2a1a7b45ecfed265c6f74ed17" [2]=&gt; string(35) "b2_2b81fcc2a1a7b45ecfed265c6f74ed17" [3]=&gt; string(35) "b3_2b81fcc2a1a7b45ecfed265c6f74ed17" } ["language":protected]=&gt; array(19) { ["authenticate"]=&gt; string(35) "SMTP Error: Could not authenticate." ["connect_host"]=&gt; string(43) "SMTP Error: Could not connect to SMTP host." ["data_not_accepted"]=&gt; string(30) "SMTP Error: data not accepted." ["empty_message"]=&gt; string(18) "Message body empty" ["encoding"]=&gt; string(18) "Unknown encoding: " ["execute"]=&gt; string(19) "Could not execute: " ["file_access"]=&gt; string(23) "Could not access file: " ["file_open"]=&gt; string(33) "File Error: Could not open file: " ["from_failed"]=&gt; string(35) "The following From address failed: " ["instantiate"]=&gt; string(36) "Could not instantiate mail function." ["invalid_address"]=&gt; string(17) "Invalid address: " ["mailer_not_supported"]=&gt; string(25) " mailer is not supported." ["provide_address"]=&gt; string(54) "You must provide at least one recipient email address." ["recipients_failed"]=&gt; string(45) "SMTP Error: The following recipients failed: " ["signing"]=&gt; string(15) "Signing Error: " ["smtp_connect_failed"]=&gt; string(22) "SMTP connect() failed." ["smtp_error"]=&gt; string(19) "SMTP server error: " ["variable_set"]=&gt; string(30) "Cannot set or reset variable: " ["extension_missing"]=&gt; string(19) "Extension missing: " } ["error_count":protected]=&gt; int(2) ["sign_cert_file":protected]=&gt; string(0) "" ["sign_key_file":protected]=&gt; string(0) "" ["sign_extracerts_file":protected]=&gt; string(0) "" ["sign_key_pass":protected]=&gt; string(0) "" ["exceptions":protected]=&gt; bool(true) ["uniqueid":protected]=&gt; string(32) "2b81fcc2a1a7b45ecfed265c6f74ed17" } The SMTP debugging output is shown below: 2017-09-15 18:16:49 Connection: opening to smtp.office365.com:2525, timeout=300, options=array ( ) 2017-09-15 18:17:59 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to smtp.office365.com:2525 (Network is unreachable) 2017-09-15 18:17:59 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2017-09-15 18:17:59 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting </code></pre>
[ { "answer_id": 379826, "author": "Tariq Ahmed", "author_id": 119429, "author_profile": "https://wordpress.stackexchange.com/users/119429", "pm_score": 4, "selected": true, "text": "<p>There is no native WordPress hook called <code>add_filter_once()</code>. This is an custom solution which will help you to run your hook only once.</p>\n<p>For example if inside a loop or whatever situation you are facing. However,\nThe basic idea is to check when you need to stop using your hook and simply <strong>remove_hook</strong> from WordPress and once all done, you need to registere it again.</p>\n<p>example code:</p>\n<pre><code>function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) {\n $singular = function () use ( $hook, $callback, $priority, $args, &amp;$singular ) {\n call_user_func_array( $callback, func_get_args() );\n remove_filter( $hook, $singular, $priority );\n };\n\n return add_filter( $hook, $singular, $priority, $args );\n}\n</code></pre>\n<p>The best way to understand what I try to explain to visit this <a href=\"https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb\" rel=\"nofollow noreferrer\">link</a></p>\n" }, { "answer_id": 403037, "author": "David Wolf", "author_id": 218274, "author_profile": "https://wordpress.stackexchange.com/users/218274", "pm_score": 1, "selected": false, "text": "<p>An ugly but working way to accomplish this would be to have an <code>global</code> array, and inside your filter callback, you would check if the array already contains the hook name of the filter, you only want to apply once. If it turns out, that the value is already set, the callback will immediately return the input.</p>\n<p>Technically, your filter will run every time, but the logic won't be applied each time, since it will skip for the 2nd execution and up.</p>\n<p>This technique also works for class based filters, which somehow are not treated equally by WordPress, for example removing a class based filter is some sort of mess.</p>\n<pre class=\"lang-php prettyprint-override\"><code> // … inside a class\n\n public function addMyFilter()\n {\n add_filter('some_filter', [$this, 'someMethod']);\n }\n\n public function someMethod($val)\n {\n global $myFiltersThatWhereExecAlready;\n\n if (empty($myFiltersThatWhereExecAlready)) {\n $myFiltersThatWhereExecAlready = [];\n }\n\n if (in_array(__METHOD__, $myFiltersThatWhereExecAlready)) {\n return $val;\n }\n\n $myFiltersThatWhereExecAlready[] = __METHOD__;\n\n // … doing your filtering\n }\n</code></pre>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118885/" ]
We are trying to get our set up an SMTP function but keep hitting errors with the test email. We even tried both WP-Mail-SMTP and Easy WP SMTP. After talking with our host at WPEngine we couldn't find any issue on their end since they do use OpenSSL and told us to use port 2525 since we are using Outlook. Our IT department also said that port should work just fine and isn't blocked by Outlook. I even used another SMTP hostname of premierdisability-com.mail.protection.outlook.com. However, that one gave the same error but said connection Timed Out instead of Network is unreachable. The only option I can think of is editing/swapping the class-phpmailer.php and class-smtp.php files with an older version. But Easy WP SMTP says it should be compatible with our setup of WP (WP v4.8, PHP v5.6). Do you think that would be a good option to try or know of anything else to try? ``` object(PHPMailer)#1882 (76) { ["Version"]=> string(6) "5.2.22" ["Priority"]=> NULL ["CharSet"]=> string(5) "UTF-8" ["ContentType"]=> string(10) "text/plain" ["Encoding"]=> string(4) "7bit" ["ErrorInfo"]=> string(82) "SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting" ["From"]=> string(34) "[email protected]" ["FromName"]=> string(27) "Premier Disability Services" ["Sender"]=> string(34) "[email protected]" ["ReturnPath"]=> string(0) "" ["Subject"]=> string(56) "WP Mail SMTP: Test mail to [email protected]" ["Body"]=> string(68) "This is a test email generated by the WP Mail SMTP WordPress plugin." ["AltBody"]=> string(0) "" ["Ical"]=> string(0) "" ["MIMEBody":protected]=> string(69) "This is a test email generated by the WP Mail SMTP WordPress plugin. " ["MIMEHeader":protected]=> string(405) "Date: Fri, 15 Sep 2017 18:16:49 +0000 To: [email protected] From: Premier Disability Services Subject: WP Mail SMTP: Test mail to [email protected] Message-ID: <[email protected]> X-Mailer: PHPMailer 5.2.22 (https://github.com/PHPMailer/PHPMailer) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 " ["mailHeader":protected]=> string(0) "" ["WordWrap"]=> int(0) ["Mailer"]=> string(4) "smtp" ["Sendmail"]=> string(18) "/usr/sbin/sendmail" ["UseSendmailOptions"]=> bool(true) ["PluginDir"]=> string(0) "" ["ConfirmReadingTo"]=> string(0) "" ["Hostname"]=> string(0) "" ["MessageID"]=> string(0) "" ["MessageDate"]=> string(31) "Fri, 15 Sep 2017 18:16:49 +0000" ["Host"]=> string(18) "smtp.office365.com" ["Port"]=> string(4) "2525" ["Helo"]=> string(0) "" ["SMTPSecure"]=> string(3) "tls" ["SMTPAutoTLS"]=> bool(false) ["SMTPAuth"]=> bool(true) ["SMTPOptions"]=> array(0) { } ["Username"]=> string(34) "[email protected]" ["Password"]=> string(8) "*******" ["AuthType"]=> string(0) "" ["Realm"]=> string(0) "" ["Workstation"]=> string(0) "" ["Timeout"]=> int(300) ["SMTPDebug"]=> bool(true) ["Debugoutput"]=> string(4) "echo" ["SMTPKeepAlive"]=> bool(false) ["SingleTo"]=> bool(false) ["SingleToArray"]=> array(0) { } ["do_verp"]=> bool(false) ["AllowEmpty"]=> bool(false) ["LE"]=> string(1) " " ["DKIM_selector"]=> string(0) "" ["DKIM_identity"]=> string(0) "" ["DKIM_passphrase"]=> string(0) "" ["DKIM_domain"]=> string(0) "" ["DKIM_private"]=> string(0) "" ["DKIM_private_string"]=> string(0) "" ["action_function"]=> string(0) "" ["XMailer"]=> string(0) "" ["smtp":protected]=> object(SMTP)#1886 (14) { ["Version"]=> string(6) "5.2.22" ["SMTP_PORT"]=> int(25) ["CRLF"]=> string(2) " " ["do_debug"]=> bool(true) ["Debugoutput"]=> string(4) "echo" ["do_verp"]=> bool(false) ["Timeout"]=> int(300) ["Timelimit"]=> int(300) ["smtp_transaction_id_patterns":protected]=> array(3) { ["exim"]=> string(21) "/[0-9]{3} OK id=(.*)/" ["sendmail"]=> string(29) "/[0-9]{3} 2.0.0 (.*) Message/" ["postfix"]=> string(35) "/[0-9]{3} 2.0.0 Ok: queued as (.*)/" } ["smtp_conn":protected]=> bool(false) ["error":protected]=> array(4) { ["error"]=> string(0) "" ["detail"]=> string(0) "" ["smtp_code"]=> string(0) "" ["smtp_code_ex"]=> string(0) "" } ["helo_rply":protected]=> NULL ["server_caps":protected]=> NULL ["last_reply":protected]=> string(0) "" } ["to":protected]=> array(1) { [0]=> array(2) { [0]=> string(29) "[email protected]" [1]=> string(0) "" } } ["cc":protected]=> array(0) { } ["bcc":protected]=> array(0) { } ["ReplyTo":protected]=> array(0) { } ["all_recipients":protected]=> array(1) { ["[email protected]"]=> bool(true) } ["RecipientsQueue":protected]=> array(0) { } ["ReplyToQueue":protected]=> array(0) { } ["attachment":protected]=> array(0) { } ["CustomHeader":protected]=> array(0) { } ["lastMessageID":protected]=> string(56) "<[email protected]>" ["message_type":protected]=> string(5) "plain" ["boundary":protected]=> array(3) { [1]=> string(35) "b1_2b81fcc2a1a7b45ecfed265c6f74ed17" [2]=> string(35) "b2_2b81fcc2a1a7b45ecfed265c6f74ed17" [3]=> string(35) "b3_2b81fcc2a1a7b45ecfed265c6f74ed17" } ["language":protected]=> array(19) { ["authenticate"]=> string(35) "SMTP Error: Could not authenticate." ["connect_host"]=> string(43) "SMTP Error: Could not connect to SMTP host." ["data_not_accepted"]=> string(30) "SMTP Error: data not accepted." ["empty_message"]=> string(18) "Message body empty" ["encoding"]=> string(18) "Unknown encoding: " ["execute"]=> string(19) "Could not execute: " ["file_access"]=> string(23) "Could not access file: " ["file_open"]=> string(33) "File Error: Could not open file: " ["from_failed"]=> string(35) "The following From address failed: " ["instantiate"]=> string(36) "Could not instantiate mail function." ["invalid_address"]=> string(17) "Invalid address: " ["mailer_not_supported"]=> string(25) " mailer is not supported." ["provide_address"]=> string(54) "You must provide at least one recipient email address." ["recipients_failed"]=> string(45) "SMTP Error: The following recipients failed: " ["signing"]=> string(15) "Signing Error: " ["smtp_connect_failed"]=> string(22) "SMTP connect() failed." ["smtp_error"]=> string(19) "SMTP server error: " ["variable_set"]=> string(30) "Cannot set or reset variable: " ["extension_missing"]=> string(19) "Extension missing: " } ["error_count":protected]=> int(2) ["sign_cert_file":protected]=> string(0) "" ["sign_key_file":protected]=> string(0) "" ["sign_extracerts_file":protected]=> string(0) "" ["sign_key_pass":protected]=> string(0) "" ["exceptions":protected]=> bool(true) ["uniqueid":protected]=> string(32) "2b81fcc2a1a7b45ecfed265c6f74ed17" } The SMTP debugging output is shown below: 2017-09-15 18:16:49 Connection: opening to smtp.office365.com:2525, timeout=300, options=array ( ) 2017-09-15 18:17:59 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to smtp.office365.com:2525 (Network is unreachable) 2017-09-15 18:17:59 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2017-09-15 18:17:59 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting ```
There is no native WordPress hook called `add_filter_once()`. This is an custom solution which will help you to run your hook only once. For example if inside a loop or whatever situation you are facing. However, The basic idea is to check when you need to stop using your hook and simply **remove\_hook** from WordPress and once all done, you need to registere it again. example code: ``` function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) { $singular = function () use ( $hook, $callback, $priority, $args, &$singular ) { call_user_func_array( $callback, func_get_args() ); remove_filter( $hook, $singular, $priority ); }; return add_filter( $hook, $singular, $priority, $args ); } ``` The best way to understand what I try to explain to visit this [link](https://gist.github.com/stevegrunwell/c8307af5b88310ac1c49f6fa91f62bcb)
280,161
<p>I'm trying to overwrite following code in the child theme. I want to load file <code>/inc/soundtheme-admin.php</code> from child folder. I copied same code snippet in <code>child-theme/functions.php</code> and also copied the <code>inc/soundtheme-admin.php</code>. I also replaced the <code>get_template_directory()</code> to <code>get_stylesheet_directory()</code> but its still loading parent file.</p> <p>Please correct me where I'm making a mistake. Thanks in advance.</p> <pre><code>// Code snippet from parent-theme/functions.php if( function_exists('acf_add_options_page') ) { require get_template_directory() . '/inc/soundtheme-admin.php'; $paper_themes = acf_add_options_page(array( 'page_title' =&gt; '', 'menu_title' =&gt; 'Sound Theme', 'menu_slug' =&gt; 'theme-general-settings', 'capability' =&gt; 'edit_posts', 'redirect' =&gt; false, 'autoload' =&gt; false, 'icon_url' =&gt; 'dashicons-carrot' )); acf_add_options_sub_page(array( 'page_title' =&gt; '', 'menu_title' =&gt; 'Sound Options', 'parent_slug' =&gt; 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' =&gt; '', 'menu_title' =&gt; 'Sound Layouts', 'parent_slug' =&gt; 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' =&gt; '', 'menu_title' =&gt; 'Sound Code', 'parent_slug' =&gt; 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' =&gt; '', 'menu_title' =&gt; 'Sound Supports', 'parent_slug' =&gt; 'theme-general-settings', )); } </code></pre>
[ { "answer_id": 280164, "author": "dwcouch", "author_id": 33411, "author_profile": "https://wordpress.stackexchange.com/users/33411", "pm_score": 2, "selected": true, "text": "<p><strong>The functions in your child theme will be loaded before the functions in the parent theme</strong>. This means that if your parent and child themes both have functions called my_function() which do a similar job, the one in the parent theme will load last, meaning it will override the one in the child theme.</p>\n\n<p>~<a href=\"https://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623\" rel=\"nofollow noreferrer\">Guide to Functions and Child themes</a></p>\n\n<p>Further:</p>\n\n<p><strong>Function Priority</strong></p>\n\n<p>If you're not using your own parent theme, or you're using a third party one without pluggable functions, you'll need another method.</p>\n\n<p>When you write functions you can assign them a priority, which tells WordPress when to run them. You do this when adding your function to an action or filter hook. WordPress will then run the functions attached to a given hook in ascending order of priority, so those with higher numbers will run last.</p>\n\n<p>Let's imagine the function in the parent theme isn't pluggable, and looks like this:</p>\n\n<pre><code>&lt;?php\n function parent_function() {\n // Contents for your function here.\n }\n add_action( 'init', 'parent_function' );\n?&gt;\n</code></pre>\n\n<p>This means the function in your child theme would look like this:</p>\n\n<pre><code> &lt;?php\n function child_function() {\n // Contents for your function here.\n }\n add_action( 'init', 'child_function', 15 );\n ?&gt;\n</code></pre>\n\n<p>That should get you started...</p>\n" }, { "answer_id": 280168, "author": "MKS", "author_id": 127970, "author_profile": "https://wordpress.stackexchange.com/users/127970", "pm_score": 0, "selected": false, "text": "<p>Above comment definitely helped. The declaration was in the different file for acf_add_options_page function and you need to include that file child-functions.php file too.</p>\n\n<p>I just copied the code inside if block from parent-functions.php file and paste it in child-functions.php file including required files. That worked for me.</p>\n\n<p>Hope it will help you too.</p>\n\n<p>Thanks.</p>\n" } ]
2017/09/15
[ "https://wordpress.stackexchange.com/questions/280161", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127970/" ]
I'm trying to overwrite following code in the child theme. I want to load file `/inc/soundtheme-admin.php` from child folder. I copied same code snippet in `child-theme/functions.php` and also copied the `inc/soundtheme-admin.php`. I also replaced the `get_template_directory()` to `get_stylesheet_directory()` but its still loading parent file. Please correct me where I'm making a mistake. Thanks in advance. ``` // Code snippet from parent-theme/functions.php if( function_exists('acf_add_options_page') ) { require get_template_directory() . '/inc/soundtheme-admin.php'; $paper_themes = acf_add_options_page(array( 'page_title' => '', 'menu_title' => 'Sound Theme', 'menu_slug' => 'theme-general-settings', 'capability' => 'edit_posts', 'redirect' => false, 'autoload' => false, 'icon_url' => 'dashicons-carrot' )); acf_add_options_sub_page(array( 'page_title' => '', 'menu_title' => 'Sound Options', 'parent_slug' => 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' => '', 'menu_title' => 'Sound Layouts', 'parent_slug' => 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' => '', 'menu_title' => 'Sound Code', 'parent_slug' => 'theme-general-settings', )); acf_add_options_sub_page(array( 'page_title' => '', 'menu_title' => 'Sound Supports', 'parent_slug' => 'theme-general-settings', )); } ```
**The functions in your child theme will be loaded before the functions in the parent theme**. This means that if your parent and child themes both have functions called my\_function() which do a similar job, the one in the parent theme will load last, meaning it will override the one in the child theme. ~[Guide to Functions and Child themes](https://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623) Further: **Function Priority** If you're not using your own parent theme, or you're using a third party one without pluggable functions, you'll need another method. When you write functions you can assign them a priority, which tells WordPress when to run them. You do this when adding your function to an action or filter hook. WordPress will then run the functions attached to a given hook in ascending order of priority, so those with higher numbers will run last. Let's imagine the function in the parent theme isn't pluggable, and looks like this: ``` <?php function parent_function() { // Contents for your function here. } add_action( 'init', 'parent_function' ); ?> ``` This means the function in your child theme would look like this: ``` <?php function child_function() { // Contents for your function here. } add_action( 'init', 'child_function', 15 ); ?> ``` That should get you started...
280,176
<p>I have been using quark a lot which is a starter theme.</p> <p>I have been using a child theme with quark for a few reasons:</p> <ul> <li>Clear separation of code </li> <li>Ability to easily update quark on theme updates</li> </ul> <p>As I have become more in tune with the theme and wordpress, I am trying to reduce the load and resources to ensure speed and efficiency.</p> <p>I am now debating the use of a child theme - Mainly because I know a child theme already adds additional resources </p> <p>e.g. it requires 2 x style.css (parent and child) and sometimes, overwriting styles is cumbersome and creates extra code which wouldn't be required by using starter theme in standalone - I could just delete the code.</p> <p>The same goes for functions.php - quark loads 2 x google fonts - if i dont use them and load my own google fonts, i end up loading resources that are superfluous.</p> <p>BUT, using a starter theme disables the ability to easily update to the latest theme when a new version is released...</p> <p>So... I guess I want to know if I am correct - is this just the "rub of the green" and effectively I have to sum up whether I want to deal with a few extra resources versus the inability to auto-update my theme?</p> <p>Or am I missing some unique concept to each method?</p>
[ { "answer_id": 280164, "author": "dwcouch", "author_id": 33411, "author_profile": "https://wordpress.stackexchange.com/users/33411", "pm_score": 2, "selected": true, "text": "<p><strong>The functions in your child theme will be loaded before the functions in the parent theme</strong>. This means that if your parent and child themes both have functions called my_function() which do a similar job, the one in the parent theme will load last, meaning it will override the one in the child theme.</p>\n\n<p>~<a href=\"https://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623\" rel=\"nofollow noreferrer\">Guide to Functions and Child themes</a></p>\n\n<p>Further:</p>\n\n<p><strong>Function Priority</strong></p>\n\n<p>If you're not using your own parent theme, or you're using a third party one without pluggable functions, you'll need another method.</p>\n\n<p>When you write functions you can assign them a priority, which tells WordPress when to run them. You do this when adding your function to an action or filter hook. WordPress will then run the functions attached to a given hook in ascending order of priority, so those with higher numbers will run last.</p>\n\n<p>Let's imagine the function in the parent theme isn't pluggable, and looks like this:</p>\n\n<pre><code>&lt;?php\n function parent_function() {\n // Contents for your function here.\n }\n add_action( 'init', 'parent_function' );\n?&gt;\n</code></pre>\n\n<p>This means the function in your child theme would look like this:</p>\n\n<pre><code> &lt;?php\n function child_function() {\n // Contents for your function here.\n }\n add_action( 'init', 'child_function', 15 );\n ?&gt;\n</code></pre>\n\n<p>That should get you started...</p>\n" }, { "answer_id": 280168, "author": "MKS", "author_id": 127970, "author_profile": "https://wordpress.stackexchange.com/users/127970", "pm_score": 0, "selected": false, "text": "<p>Above comment definitely helped. The declaration was in the different file for acf_add_options_page function and you need to include that file child-functions.php file too.</p>\n\n<p>I just copied the code inside if block from parent-functions.php file and paste it in child-functions.php file including required files. That worked for me.</p>\n\n<p>Hope it will help you too.</p>\n\n<p>Thanks.</p>\n" } ]
2017/09/16
[ "https://wordpress.stackexchange.com/questions/280176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10368/" ]
I have been using quark a lot which is a starter theme. I have been using a child theme with quark for a few reasons: * Clear separation of code * Ability to easily update quark on theme updates As I have become more in tune with the theme and wordpress, I am trying to reduce the load and resources to ensure speed and efficiency. I am now debating the use of a child theme - Mainly because I know a child theme already adds additional resources e.g. it requires 2 x style.css (parent and child) and sometimes, overwriting styles is cumbersome and creates extra code which wouldn't be required by using starter theme in standalone - I could just delete the code. The same goes for functions.php - quark loads 2 x google fonts - if i dont use them and load my own google fonts, i end up loading resources that are superfluous. BUT, using a starter theme disables the ability to easily update to the latest theme when a new version is released... So... I guess I want to know if I am correct - is this just the "rub of the green" and effectively I have to sum up whether I want to deal with a few extra resources versus the inability to auto-update my theme? Or am I missing some unique concept to each method?
**The functions in your child theme will be loaded before the functions in the parent theme**. This means that if your parent and child themes both have functions called my\_function() which do a similar job, the one in the parent theme will load last, meaning it will override the one in the child theme. ~[Guide to Functions and Child themes](https://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623) Further: **Function Priority** If you're not using your own parent theme, or you're using a third party one without pluggable functions, you'll need another method. When you write functions you can assign them a priority, which tells WordPress when to run them. You do this when adding your function to an action or filter hook. WordPress will then run the functions attached to a given hook in ascending order of priority, so those with higher numbers will run last. Let's imagine the function in the parent theme isn't pluggable, and looks like this: ``` <?php function parent_function() { // Contents for your function here. } add_action( 'init', 'parent_function' ); ?> ``` This means the function in your child theme would look like this: ``` <?php function child_function() { // Contents for your function here. } add_action( 'init', 'child_function', 15 ); ?> ``` That should get you started...
280,198
<p>I am a beginner with WordPress. Studying hook, add_action() and add_filer() and see in the documentation that</p> <pre><code>add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 ) </code></pre> <p>But I dont know how to get $tag and where to get it to fill into add_action() or add_filter() function? Thank you.</p>
[ { "answer_id": 280204, "author": "Trac Nguyen", "author_id": 128003, "author_profile": "https://wordpress.stackexchange.com/users/128003", "pm_score": 1, "selected": false, "text": "<p>These 2 function <code>add_action()</code> and <code>add_filter()</code> are magics of WP and do not directly affect your code. In WordPress, they use <code>hooks</code> for mocking into existing functions, methods without changing it's code. </p>\n\n<p>The <code>$tag</code> you are referring is the <strong>name of the hook</strong> that you want to use. List of core hooks can be found here <a href=\"https://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Hooks</a>. However you can easily create for own hooks. E.g.:</p>\n\n<ul>\n<li>When you create a theme, and you want to allow others to add some additional HTML after your header, you may create this snippet:</li>\n</ul>\n\n<p>in functions.php (or in you lib)</p>\n\n<pre><code>function get_custom_header($tag){\n get_header($tag);\n do_action('after_template_header', $tag); // Add $tag as param, this $tag is not\n}\n</code></pre>\n\n<p>in index.php (in theme) or in any theme file</p>\n\n<pre><code>&lt;?php get_custom_header(); // instead of get_header(); ?&gt;\n</code></pre>\n\n<p>For hooking, others need to add this: (<code>$tag</code> you are asking is 'after_template_header' for this case)</p>\n\n<pre><code>add_action('after_template_header', 'hook_to_header', 10, 1); // 4th param tell WP to use 1 arguments, if you put it 0, you will not need to pass $tag to function\nfunction hook_to_header($tag) {\n echo \"After header with tag '$tag' text here\";\n}\n</code></pre>\n\n<p>Hope this can help you learning WP well my fellow. Good understand on hooks will help you to do advanced development on WP.</p>\n" }, { "answer_id": 357251, "author": "Mohammad Anwer Moin", "author_id": 181685, "author_profile": "https://wordpress.stackexchange.com/users/181685", "pm_score": 0, "selected": false, "text": "<p>You are asking how to replace your <code>$tag</code> in \n<code>add_action</code> function.</p>\n\n<p>Actually the <code>$tag</code> can replace with <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">Hooks</a> ( terminology used by WordPress )\nand in function <code>add_action()</code> they write general syntax and use tag instead of Hook. These hooks have Names which are String type and can be replaced according to your need.</p>\n\n<p>Here is a Hook <a href=\"https://developer.wordpress.org/reference/hooks/after_setup_theme/\" rel=\"nofollow noreferrer\">after_header_theme</a> which can be used as a tag in <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action()</a>\nas</p>\n\n<pre><code>add_action('after_setup_theme','title_helper');\n</code></pre>\n\n<ul>\n<li><code>after_setup_theme</code> is a Hook provided by WordPress ( <code>$tag</code> according to function syntax )</li>\n<li><code>title_helper</code> is custom function </li>\n</ul>\n\n<p>Means upon setting up the theme <code>title_helper</code> function will call and you can fill <code>title_helper</code> function according to your need.</p>\n" } ]
2017/09/16
[ "https://wordpress.stackexchange.com/questions/280198", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127997/" ]
I am a beginner with WordPress. Studying hook, add\_action() and add\_filer() and see in the documentation that ``` add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 ) ``` But I dont know how to get $tag and where to get it to fill into add\_action() or add\_filter() function? Thank you.
These 2 function `add_action()` and `add_filter()` are magics of WP and do not directly affect your code. In WordPress, they use `hooks` for mocking into existing functions, methods without changing it's code. The `$tag` you are referring is the **name of the hook** that you want to use. List of core hooks can be found here <https://codex.wordpress.org/Plugin_API/Hooks>. However you can easily create for own hooks. E.g.: * When you create a theme, and you want to allow others to add some additional HTML after your header, you may create this snippet: in functions.php (or in you lib) ``` function get_custom_header($tag){ get_header($tag); do_action('after_template_header', $tag); // Add $tag as param, this $tag is not } ``` in index.php (in theme) or in any theme file ``` <?php get_custom_header(); // instead of get_header(); ?> ``` For hooking, others need to add this: (`$tag` you are asking is 'after\_template\_header' for this case) ``` add_action('after_template_header', 'hook_to_header', 10, 1); // 4th param tell WP to use 1 arguments, if you put it 0, you will not need to pass $tag to function function hook_to_header($tag) { echo "After header with tag '$tag' text here"; } ``` Hope this can help you learning WP well my fellow. Good understand on hooks will help you to do advanced development on WP.
280,200
<p>I deleted everything in my directory to "start over" When I install wordpress it says : Your PHP installation appears to be missing the MySQL extension which is required by WordPress. I tried changing the php version but it makes no difference. here is a scrnsht of my home dir : <a href="https://i.stack.imgur.com/LDYXu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LDYXu.png" alt="picture of dir"></a> is there somthing I'm missing. Also I had downloaded a full site backup b4 I deleted here's a scrsht of what the folders are :</p> <p><a href="https://i.stack.imgur.com/ptlzf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ptlzf.jpg" alt="backup dir"></a> </p> <p>what backup files should I use and how can I revert the website back to normal. thanks a lot</p>
[ { "answer_id": 280204, "author": "Trac Nguyen", "author_id": 128003, "author_profile": "https://wordpress.stackexchange.com/users/128003", "pm_score": 1, "selected": false, "text": "<p>These 2 function <code>add_action()</code> and <code>add_filter()</code> are magics of WP and do not directly affect your code. In WordPress, they use <code>hooks</code> for mocking into existing functions, methods without changing it's code. </p>\n\n<p>The <code>$tag</code> you are referring is the <strong>name of the hook</strong> that you want to use. List of core hooks can be found here <a href=\"https://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Hooks</a>. However you can easily create for own hooks. E.g.:</p>\n\n<ul>\n<li>When you create a theme, and you want to allow others to add some additional HTML after your header, you may create this snippet:</li>\n</ul>\n\n<p>in functions.php (or in you lib)</p>\n\n<pre><code>function get_custom_header($tag){\n get_header($tag);\n do_action('after_template_header', $tag); // Add $tag as param, this $tag is not\n}\n</code></pre>\n\n<p>in index.php (in theme) or in any theme file</p>\n\n<pre><code>&lt;?php get_custom_header(); // instead of get_header(); ?&gt;\n</code></pre>\n\n<p>For hooking, others need to add this: (<code>$tag</code> you are asking is 'after_template_header' for this case)</p>\n\n<pre><code>add_action('after_template_header', 'hook_to_header', 10, 1); // 4th param tell WP to use 1 arguments, if you put it 0, you will not need to pass $tag to function\nfunction hook_to_header($tag) {\n echo \"After header with tag '$tag' text here\";\n}\n</code></pre>\n\n<p>Hope this can help you learning WP well my fellow. Good understand on hooks will help you to do advanced development on WP.</p>\n" }, { "answer_id": 357251, "author": "Mohammad Anwer Moin", "author_id": 181685, "author_profile": "https://wordpress.stackexchange.com/users/181685", "pm_score": 0, "selected": false, "text": "<p>You are asking how to replace your <code>$tag</code> in \n<code>add_action</code> function.</p>\n\n<p>Actually the <code>$tag</code> can replace with <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"nofollow noreferrer\">Hooks</a> ( terminology used by WordPress )\nand in function <code>add_action()</code> they write general syntax and use tag instead of Hook. These hooks have Names which are String type and can be replaced according to your need.</p>\n\n<p>Here is a Hook <a href=\"https://developer.wordpress.org/reference/hooks/after_setup_theme/\" rel=\"nofollow noreferrer\">after_header_theme</a> which can be used as a tag in <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action()</a>\nas</p>\n\n<pre><code>add_action('after_setup_theme','title_helper');\n</code></pre>\n\n<ul>\n<li><code>after_setup_theme</code> is a Hook provided by WordPress ( <code>$tag</code> according to function syntax )</li>\n<li><code>title_helper</code> is custom function </li>\n</ul>\n\n<p>Means upon setting up the theme <code>title_helper</code> function will call and you can fill <code>title_helper</code> function according to your need.</p>\n" } ]
2017/09/16
[ "https://wordpress.stackexchange.com/questions/280200", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128000/" ]
I deleted everything in my directory to "start over" When I install wordpress it says : Your PHP installation appears to be missing the MySQL extension which is required by WordPress. I tried changing the php version but it makes no difference. here is a scrnsht of my home dir : [![picture of dir](https://i.stack.imgur.com/LDYXu.png)](https://i.stack.imgur.com/LDYXu.png) is there somthing I'm missing. Also I had downloaded a full site backup b4 I deleted here's a scrsht of what the folders are : [![backup dir](https://i.stack.imgur.com/ptlzf.jpg)](https://i.stack.imgur.com/ptlzf.jpg) what backup files should I use and how can I revert the website back to normal. thanks a lot
These 2 function `add_action()` and `add_filter()` are magics of WP and do not directly affect your code. In WordPress, they use `hooks` for mocking into existing functions, methods without changing it's code. The `$tag` you are referring is the **name of the hook** that you want to use. List of core hooks can be found here <https://codex.wordpress.org/Plugin_API/Hooks>. However you can easily create for own hooks. E.g.: * When you create a theme, and you want to allow others to add some additional HTML after your header, you may create this snippet: in functions.php (or in you lib) ``` function get_custom_header($tag){ get_header($tag); do_action('after_template_header', $tag); // Add $tag as param, this $tag is not } ``` in index.php (in theme) or in any theme file ``` <?php get_custom_header(); // instead of get_header(); ?> ``` For hooking, others need to add this: (`$tag` you are asking is 'after\_template\_header' for this case) ``` add_action('after_template_header', 'hook_to_header', 10, 1); // 4th param tell WP to use 1 arguments, if you put it 0, you will not need to pass $tag to function function hook_to_header($tag) { echo "After header with tag '$tag' text here"; } ``` Hope this can help you learning WP well my fellow. Good understand on hooks will help you to do advanced development on WP.
280,241
<p>I uploaded an html 403 and 404 page to my WordPress theme directory and if I hit a random mistake after .com such as .com/yyyy then it loads the 404 page for example - so all is good...</p> <p>However...I would like the 403.php to be shown when someone outside my permitted IP string attempts to access my log in page.</p> <p>This .htaccess rule works great BUT it create a never-ending loop as WordPress tries to find the 403.php page..</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine on RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$ RewriteCond %{REMOTE_ADDR} !^111\.111\.22\.33$ RewriteRule ^(.*)$ - [R=403,L] &lt;/IfModule&gt; </code></pre> <p>So you can see on the last line that there is R=403 which is trying to find the 403 page, but it can't find it...</p> <p>I therefore added the following lines (trying one at a time) but they didnt work:</p> <pre><code>ErrorDocument 403 /403.php ErrorDocument 404 /404.php </code></pre> <p>and then I tried</p> <pre><code>ErrorDocument 403 /index.php?error=403 ErrorDocument 404 /index.php?error=404 </code></pre> <p>And no joy...</p> <p>Should the 403 and 404 template have WordPress specific php at the top of the template?</p> <p>Or - how can i correctly call the 403.php when the user WITHOUT the correct IP address tries to access the log in page?</p> <p>Thanks!</p>
[ { "answer_id": 280243, "author": "Asisten", "author_id": 88402, "author_profile": "https://wordpress.stackexchange.com/users/88402", "pm_score": -1, "selected": false, "text": "<ol>\n<li><p>Wordpress has built in 404 and 403 template, it called in 404.php and 403.php in your template.</p></li>\n<li><p>OR, You can also defined which page / action will load when specified error code sent by detected http response code, put this on your functions.php file:</p></li>\n</ol>\n\n<p><code>function detect_response_header(){\n if (http_response_code() == 403) {\n // do some action here, include template file, redirect to outside wordpress environment (file that not WordPress not involved in your site) or whatever\n }\n }\n add_action('template_redirect','detect_response_header');\n</code></p>\n\n<p>ref:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/init</a></p>\n" }, { "answer_id": 280251, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>it create a never-ending loop as WordPress tries to find the 403.php page</p>\n</blockquote>\n\n<p>Not WordPress, but Apache. WordPress never even sees the request.</p>\n\n<p>You need to make an exception for your custom 403 error document, otherwise, the directives you have posted would issue another 403 for the error document itself... an endless loop.</p>\n\n<p>If your <code>ErrorDocument</code> is defined like so:</p>\n\n<pre><code>ErrorDocument 403 /403.php\n</code></pre>\n\n<p>Then you can either create an exception <em>before</em> your existing rules like this:</p>\n\n<pre><code>RewriteRule ^403\\.php$ - [L]\n</code></pre>\n\n<p>Which effectively instructs mod_rewrite/Apache to do nothing when the <code>/403.php</code> document is requested.</p>\n\n<p>Or, incorporate this into your existing rule block. For example:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} ^(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^(.*)?wp-admin$\nRewriteCond %{REMOTE_ADDR} !^111\\.111\\.22\\.33$\nRewriteRule !^403\\.php$ - [R=403,L]\n</code></pre>\n\n<p>The <code>!</code> prefix on the <code>RewriteRule</code> <em>pattern</em> negates the regex. So, this rule block will only be processed if the <code>/403.php</code> document is <em>not</em> requested. Note that <code>[R=403,L]</code> is the same as <code>[F]</code>.</p>\n\n<p>Or, you can simply disable your custom error document instead and use Apache's default error response:</p>\n\n<pre><code>ErrorDocument 403 default\n</code></pre>\n" } ]
2017/09/17
[ "https://wordpress.stackexchange.com/questions/280241", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I uploaded an html 403 and 404 page to my WordPress theme directory and if I hit a random mistake after .com such as .com/yyyy then it loads the 404 page for example - so all is good... However...I would like the 403.php to be shown when someone outside my permitted IP string attempts to access my log in page. This .htaccess rule works great BUT it create a never-ending loop as WordPress tries to find the 403.php page.. ``` <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$ RewriteCond %{REMOTE_ADDR} !^111\.111\.22\.33$ RewriteRule ^(.*)$ - [R=403,L] </IfModule> ``` So you can see on the last line that there is R=403 which is trying to find the 403 page, but it can't find it... I therefore added the following lines (trying one at a time) but they didnt work: ``` ErrorDocument 403 /403.php ErrorDocument 404 /404.php ``` and then I tried ``` ErrorDocument 403 /index.php?error=403 ErrorDocument 404 /index.php?error=404 ``` And no joy... Should the 403 and 404 template have WordPress specific php at the top of the template? Or - how can i correctly call the 403.php when the user WITHOUT the correct IP address tries to access the log in page? Thanks!
> > it create a never-ending loop as WordPress tries to find the 403.php page > > > Not WordPress, but Apache. WordPress never even sees the request. You need to make an exception for your custom 403 error document, otherwise, the directives you have posted would issue another 403 for the error document itself... an endless loop. If your `ErrorDocument` is defined like so: ``` ErrorDocument 403 /403.php ``` Then you can either create an exception *before* your existing rules like this: ``` RewriteRule ^403\.php$ - [L] ``` Which effectively instructs mod\_rewrite/Apache to do nothing when the `/403.php` document is requested. Or, incorporate this into your existing rule block. For example: ``` RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$ RewriteCond %{REMOTE_ADDR} !^111\.111\.22\.33$ RewriteRule !^403\.php$ - [R=403,L] ``` The `!` prefix on the `RewriteRule` *pattern* negates the regex. So, this rule block will only be processed if the `/403.php` document is *not* requested. Note that `[R=403,L]` is the same as `[F]`. Or, you can simply disable your custom error document instead and use Apache's default error response: ``` ErrorDocument 403 default ```
280,256
<p>I am trying to use <code>wp_remote_post()</code> like this:</p> <pre><code>wp_remote_post( $url, array( 'blocking' =&gt; false, 'timeout' =&gt; 0.1 ) ); </code></pre> <p>The problem is that it seems to always force the timeout to 1s.<br> I don't even want to wait for 1s, I just want the remote post to start and immediately go back to my the calling function. ( I have also tried setting <code>timeout =&gt; 0</code> but it always takes 1s to return.)</p> <p>How can I skip this minimum of 1s?</p>
[ { "answer_id": 280259, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 0, "selected": false, "text": "<p>The timeout is the <strong>maximal</strong> not minimal time the functions waits for an answer. So, if the answers comes before the timeout, the function returns the value.</p>\n\n<blockquote>\n <p>The argument 'timeout' allows for setting the time in seconds, before the connection is dropped and an error is returned.</p>\n</blockquote>\n\n<p>source: <a href=\"https://codex.wordpress.org/HTTP_API#Other_Arguments\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/HTTP_API#Other_Arguments</a></p>\n\n<p>Also: The timeout has to be an integer, not a float. </p>\n" }, { "answer_id": 356316, "author": "Tiny Hust", "author_id": 102988, "author_profile": "https://wordpress.stackexchange.com/users/102988", "pm_score": 1, "selected": false, "text": "<p>For cURL, a minimum of 1 second applies, as DNS resolution operates at second-resolution only.\nSee more in wp-includes/class-request.php function request()</p>\n" } ]
2017/09/17
[ "https://wordpress.stackexchange.com/questions/280256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124462/" ]
I am trying to use `wp_remote_post()` like this: ``` wp_remote_post( $url, array( 'blocking' => false, 'timeout' => 0.1 ) ); ``` The problem is that it seems to always force the timeout to 1s. I don't even want to wait for 1s, I just want the remote post to start and immediately go back to my the calling function. ( I have also tried setting `timeout => 0` but it always takes 1s to return.) How can I skip this minimum of 1s?
For cURL, a minimum of 1 second applies, as DNS resolution operates at second-resolution only. See more in wp-includes/class-request.php function request()
280,257
<p>Problem Description:</p> <p>the code below is from a single-featured-article.php file . Copying this custom template for a custom post type 'featured-article' from my plug-in to the active theme folder . The template is rendering fine . Even the query showing data in the array .</p> <p>see: result of print_r($featured_articles) is in the second part</p> <p>But 'the_post()' not showing any post. What's wrong with code ?</p> <pre><code>&lt;?php $featured_articles = new WP_Query(array('post_type' =&gt; 'featured-article')); echo '&lt;pre&gt;'; print_r($featured_articles); echo '&lt;/pre&gt;'; if ($featured_articles-&gt;have_posts()): while ($featured_articles-&gt;have_posts()) : $featured_articles-&gt;the_post(); // Include the single post content template. get_template_part('template-parts/post/content', get_post_format()); // If comments are open or we have at least one comment, load up the comment template. if (comments_open() || get_comments_number()) { comments_template(); } if (is_singular('attachment')) { // Parent post navigation. the_post_navigation(array( 'prev_text' =&gt; _x('&lt;span class="meta-nav"&gt;Published in&lt;/span&gt;&lt;span class="post-title"&gt;%title&lt;/span&gt;', 'Parent post link', 'twentysixteen'), )); } elseif (is_singular('featured-article')) { // Previous/next post navigation. the_post_navigation(array( 'next_text' =&gt; '&lt;span class="meta-nav" aria-hidden="true"&gt;' . __('Next', 'twentysixteen') . '&lt;/span&gt; ' . '&lt;span class="screen-reader-text"&gt;' . __('Next post:', 'twentysixteen') . '&lt;/span&gt; ' . '&lt;span class="post-title"&gt;%title&lt;/span&gt;', 'prev_text' =&gt; '&lt;span class="meta-nav" aria-hidden="true"&gt;' . __('Previous', 'twentysixteen') . '&lt;/span&gt; ' . '&lt;span class="screen-reader-text"&gt;' . __('Previous post:', 'twentysixteen') . '&lt;/span&gt; ' . '&lt;span class="post-title"&gt;%title&lt;/span&gt;', )); } // End of the loop. endwhile; endif; ?&gt; </code></pre> <p>result of print_r($featured_articles) : </p> <pre><code>WP_Query Object ( [query] =&gt; Array ( [post_type] =&gt; featured-article ) [query_vars] =&gt; Array ( [post_type] =&gt; featured-article [error] =&gt; [m] =&gt; [p] =&gt; 0 [post_parent] =&gt; [subpost] =&gt; [subpost_id] =&gt; [attachment] =&gt; [attachment_id] =&gt; 0 [name] =&gt; [static] =&gt; [pagename] =&gt; [page_id] =&gt; 0 [second] =&gt; [minute] =&gt; [hour] =&gt; [day] =&gt; 0 [monthnum] =&gt; 0 [year] =&gt; 0 [w] =&gt; 0 [category_name] =&gt; [tag] =&gt; [cat] =&gt; [tag_id] =&gt; [author] =&gt; [author_name] =&gt; [feed] =&gt; [tb] =&gt; [paged] =&gt; 0 [meta_key] =&gt; [meta_value] =&gt; [preview] =&gt; [s] =&gt; [sentence] =&gt; [title] =&gt; [fields] =&gt; [menu_order] =&gt; [embed] =&gt; [category__in] =&gt; Array ( ) [category__not_in] =&gt; Array ( ) [category__and] =&gt; Array ( ) [post__in] =&gt; Array ( ) [post__not_in] =&gt; Array ( ) [post_name__in] =&gt; Array ( ) [tag__in] =&gt; Array ( ) [tag__not_in] =&gt; Array ( ) [tag__and] =&gt; Array ( ) [tag_slug__in] =&gt; Array ( ) [tag_slug__and] =&gt; Array ( ) [post_parent__in] =&gt; Array ( ) [post_parent__not_in] =&gt; Array ( ) [author__in] =&gt; Array ( ) [author__not_in] =&gt; Array ( ) [ignore_sticky_posts] =&gt; [suppress_filters] =&gt; [cache_results] =&gt; 1 [update_post_term_cache] =&gt; 1 [lazy_load_term_meta] =&gt; 1 [update_post_meta_cache] =&gt; 1 [posts_per_page] =&gt; 2 [nopaging] =&gt; [comments_per_page] =&gt; 50 [no_found_rows] =&gt; [order] =&gt; DESC ) [tax_query] =&gt; WP_Tax_Query Object ( [queries] =&gt; Array ( ) [relation] =&gt; AND [table_aliases:protected] =&gt; Array ( ) [queried_terms] =&gt; Array ( ) [primary_table] =&gt; wp_posts [primary_id_column] =&gt; ID ) [meta_query] =&gt; WP_Meta_Query Object ( [queries] =&gt; Array ( ) [relation] =&gt; [meta_table] =&gt; [meta_id_column] =&gt; [primary_table] =&gt; [primary_id_column] =&gt; [table_aliases:protected] =&gt; Array ( ) [clauses:protected] =&gt; Array ( ) [has_or_relation:protected] =&gt; ) [date_query] =&gt; [request] =&gt; SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'featured-article' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 2 [posts] =&gt; Array ( [0] =&gt; WP_Post Object ( [ID] =&gt; 433 [post_author] =&gt; 1 [post_date] =&gt; 2017-09-16 19:13:24 [post_date_gmt] =&gt; 2017-09-16 13:13:24 [post_content] =&gt; dsfsf fsf werfwe frewgtv r j tut ttyuytu u tyu [post_title] =&gt; DCV featured article [post_excerpt] =&gt; [post_status] =&gt; publish [comment_status] =&gt; closed [ping_status] =&gt; closed [post_password] =&gt; [post_name] =&gt; dcv-featured-article [to_ping] =&gt; [pinged] =&gt; [post_modified] =&gt; 2017-09-16 19:13:24 [post_modified_gmt] =&gt; 2017-09-16 13:13:24 [post_content_filtered] =&gt; [post_parent] =&gt; 0 [guid] =&gt; http://rs-wordpress.com/?post_type=featured-article&amp;p=433 [menu_order] =&gt; 0 [post_type] =&gt; featured-article [post_mime_type] =&gt; [comment_count] =&gt; 0 [filter] =&gt; raw ) [1] =&gt; WP_Post Object ( [ID] =&gt; 432 [post_author] =&gt; 1 [post_date] =&gt; 2017-09-16 18:49:05 [post_date_gmt] =&gt; 2017-09-16 12:49:05 [post_content] =&gt; chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon [post_title] =&gt; cfc feature article [post_excerpt] =&gt; [post_status] =&gt; publish [comment_status] =&gt; closed [ping_status] =&gt; closed [post_password] =&gt; [post_name] =&gt; cfc-feature-article [to_ping] =&gt; [pinged] =&gt; [post_modified] =&gt; 2017-09-16 18:49:05 [post_modified_gmt] =&gt; 2017-09-16 12:49:05 [post_content_filtered] =&gt; [post_parent] =&gt; 0 [guid] =&gt; http://rs-wordpress.com/?post_type=featured-article&amp;p=432 [menu_order] =&gt; 0 [post_type] =&gt; featured-article [post_mime_type] =&gt; [comment_count] =&gt; 0 [filter] =&gt; raw ) ) [post_count] =&gt; 2 [current_post] =&gt; -1 [in_the_loop] =&gt; [post] =&gt; WP_Post Object ( [ID] =&gt; 433 [post_author] =&gt; 1 [post_date] =&gt; 2017-09-16 19:13:24 [post_date_gmt] =&gt; 2017-09-16 13:13:24 [post_content] =&gt; dsfsf fsf werfwe frewgtv r j tut ttyuytu u tyu [post_title] =&gt; DCV featured article [post_excerpt] =&gt; [post_status] =&gt; publish [comment_status] =&gt; closed [ping_status] =&gt; closed [post_password] =&gt; [post_name] =&gt; dcv-featured-article [to_ping] =&gt; [pinged] =&gt; [post_modified] =&gt; 2017-09-16 19:13:24 [post_modified_gmt] =&gt; 2017-09-16 13:13:24 [post_content_filtered] =&gt; [post_parent] =&gt; 0 [guid] =&gt; http://rs-wordpress.com/?post_type=featured-article&amp;p=433 [menu_order] =&gt; 0 [post_type] =&gt; featured-article [post_mime_type] =&gt; [comment_count] =&gt; 0 [filter] =&gt; raw ) [comment_count] =&gt; 0 [current_comment] =&gt; -1 [found_posts] =&gt; 3 [max_num_pages] =&gt; 2 [max_num_comment_pages] =&gt; 0 [is_single] =&gt; [is_preview] =&gt; [is_page] =&gt; [is_archive] =&gt; 1 [is_date] =&gt; [is_year] =&gt; [is_month] =&gt; [is_day] =&gt; [is_time] =&gt; [is_author] =&gt; [is_category] =&gt; [is_tag] =&gt; [is_tax] =&gt; [is_search] =&gt; [is_feed] =&gt; [is_comment_feed] =&gt; [is_trackback] =&gt; [is_home] =&gt; [is_404] =&gt; [is_embed] =&gt; [is_paged] =&gt; [is_admin] =&gt; [is_attachment] =&gt; [is_singular] =&gt; [is_robots] =&gt; [is_posts_page] =&gt; [is_post_type_archive] =&gt; 1 [query_vars_hash:WP_Query:private] =&gt; 8c6cb592fd6eb096f5db534a95e5b42c [query_vars_changed:WP_Query:private] =&gt; [thumbnails_cached] =&gt; [stopwords:WP_Query:private] =&gt; [compat_fields:WP_Query:private] =&gt; Array ( [0] =&gt; query_vars_hash [1] =&gt; query_vars_changed ) [compat_methods:WP_Query:private] =&gt; Array ( [0] =&gt; init_query_flags [1] =&gt; parse_tax_query ) ) </code></pre>
[ { "answer_id": 280258, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p><code>the_post()</code> doesn't render anything. Read <a href=\"https://developer.wordpress.org/reference/classes/wp_query/the_post/\" rel=\"nofollow noreferrer\">the documentation</a>:</p>\n\n<blockquote>\n <p>Retrieves the next post, sets up the post, sets the ‘in the loop’\n property to true.</p>\n</blockquote>\n\n<p>So all it does is set it so that functions like <code>the_title()</code> or <code>the_content()</code> use the title and content from the current post in the query as you loop through it.</p>\n\n<p>If a post isn't rendering it would be because <code>get_template_part('template-parts/post/content', get_post_format());</code> is referring to a template doesn't exist. You need to make sure that template exists and uses the right functions, like <code>the_title()</code>, to output content. <code>the_post()</code> doesn't output anything.</p>\n\n<p>EDIT: Or, more likely, it's this:</p>\n\n<pre><code>$featured_articles &gt; have_posts()\n</code></pre>\n\n<p>That's not the correct syntax. <code>have_posts()</code> is a method on <code>$featured_articles</code> so it needs to be written like this:</p>\n\n<pre><code>$featured_articles-&gt;have_posts()\n</code></pre>\n" }, { "answer_id": 280268, "author": "keramzyt", "author_id": 81741, "author_profile": "https://wordpress.stackexchange.com/users/81741", "pm_score": 1, "selected": true, "text": "<p>You made a mistake in the syntax:</p>\n\n<p><code>if ($featured_articles &gt; have_posts()):\n while ($featured_articles &gt; have_posts()) : $featured_articles-&gt;the_post();</code></p>\n\n<p>in the <code>if</code> and <code>while</code> conditions should be <code>-&gt;</code> instead <code>&gt;</code>.</p>\n" } ]
2017/09/17
[ "https://wordpress.stackexchange.com/questions/280257", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127638/" ]
Problem Description: the code below is from a single-featured-article.php file . Copying this custom template for a custom post type 'featured-article' from my plug-in to the active theme folder . The template is rendering fine . Even the query showing data in the array . see: result of print\_r($featured\_articles) is in the second part But 'the\_post()' not showing any post. What's wrong with code ? ``` <?php $featured_articles = new WP_Query(array('post_type' => 'featured-article')); echo '<pre>'; print_r($featured_articles); echo '</pre>'; if ($featured_articles->have_posts()): while ($featured_articles->have_posts()) : $featured_articles->the_post(); // Include the single post content template. get_template_part('template-parts/post/content', get_post_format()); // If comments are open or we have at least one comment, load up the comment template. if (comments_open() || get_comments_number()) { comments_template(); } if (is_singular('attachment')) { // Parent post navigation. the_post_navigation(array( 'prev_text' => _x('<span class="meta-nav">Published in</span><span class="post-title">%title</span>', 'Parent post link', 'twentysixteen'), )); } elseif (is_singular('featured-article')) { // Previous/next post navigation. the_post_navigation(array( 'next_text' => '<span class="meta-nav" aria-hidden="true">' . __('Next', 'twentysixteen') . '</span> ' . '<span class="screen-reader-text">' . __('Next post:', 'twentysixteen') . '</span> ' . '<span class="post-title">%title</span>', 'prev_text' => '<span class="meta-nav" aria-hidden="true">' . __('Previous', 'twentysixteen') . '</span> ' . '<span class="screen-reader-text">' . __('Previous post:', 'twentysixteen') . '</span> ' . '<span class="post-title">%title</span>', )); } // End of the loop. endwhile; endif; ?> ``` result of print\_r($featured\_articles) : ``` WP_Query Object ( [query] => Array ( [post_type] => featured-article ) [query_vars] => Array ( [post_type] => featured-article [error] => [m] => [p] => 0 [post_parent] => [subpost] => [subpost_id] => [attachment] => [attachment_id] => 0 [name] => [static] => [pagename] => [page_id] => 0 [second] => [minute] => [hour] => [day] => 0 [monthnum] => 0 [year] => 0 [w] => 0 [category_name] => [tag] => [cat] => [tag_id] => [author] => [author_name] => [feed] => [tb] => [paged] => 0 [meta_key] => [meta_value] => [preview] => [s] => [sentence] => [title] => [fields] => [menu_order] => [embed] => [category__in] => Array ( ) [category__not_in] => Array ( ) [category__and] => Array ( ) [post__in] => Array ( ) [post__not_in] => Array ( ) [post_name__in] => Array ( ) [tag__in] => Array ( ) [tag__not_in] => Array ( ) [tag__and] => Array ( ) [tag_slug__in] => Array ( ) [tag_slug__and] => Array ( ) [post_parent__in] => Array ( ) [post_parent__not_in] => Array ( ) [author__in] => Array ( ) [author__not_in] => Array ( ) [ignore_sticky_posts] => [suppress_filters] => [cache_results] => 1 [update_post_term_cache] => 1 [lazy_load_term_meta] => 1 [update_post_meta_cache] => 1 [posts_per_page] => 2 [nopaging] => [comments_per_page] => 50 [no_found_rows] => [order] => DESC ) [tax_query] => WP_Tax_Query Object ( [queries] => Array ( ) [relation] => AND [table_aliases:protected] => Array ( ) [queried_terms] => Array ( ) [primary_table] => wp_posts [primary_id_column] => ID ) [meta_query] => WP_Meta_Query Object ( [queries] => Array ( ) [relation] => [meta_table] => [meta_id_column] => [primary_table] => [primary_id_column] => [table_aliases:protected] => Array ( ) [clauses:protected] => Array ( ) [has_or_relation:protected] => ) [date_query] => [request] => SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'featured-article' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 2 [posts] => Array ( [0] => WP_Post Object ( [ID] => 433 [post_author] => 1 [post_date] => 2017-09-16 19:13:24 [post_date_gmt] => 2017-09-16 13:13:24 [post_content] => dsfsf fsf werfwe frewgtv r j tut ttyuytu u tyu [post_title] => DCV featured article [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => dcv-featured-article [to_ping] => [pinged] => [post_modified] => 2017-09-16 19:13:24 [post_modified_gmt] => 2017-09-16 13:13:24 [post_content_filtered] => [post_parent] => 0 [guid] => http://rs-wordpress.com/?post_type=featured-article&p=433 [menu_order] => 0 [post_type] => featured-article [post_mime_type] => [comment_count] => 0 [filter] => raw ) [1] => WP_Post Object ( [ID] => 432 [post_author] => 1 [post_date] => 2017-09-16 18:49:05 [post_date_gmt] => 2017-09-16 12:49:05 [post_content] => chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon chloro-fluro carbon [post_title] => cfc feature article [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => cfc-feature-article [to_ping] => [pinged] => [post_modified] => 2017-09-16 18:49:05 [post_modified_gmt] => 2017-09-16 12:49:05 [post_content_filtered] => [post_parent] => 0 [guid] => http://rs-wordpress.com/?post_type=featured-article&p=432 [menu_order] => 0 [post_type] => featured-article [post_mime_type] => [comment_count] => 0 [filter] => raw ) ) [post_count] => 2 [current_post] => -1 [in_the_loop] => [post] => WP_Post Object ( [ID] => 433 [post_author] => 1 [post_date] => 2017-09-16 19:13:24 [post_date_gmt] => 2017-09-16 13:13:24 [post_content] => dsfsf fsf werfwe frewgtv r j tut ttyuytu u tyu [post_title] => DCV featured article [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => dcv-featured-article [to_ping] => [pinged] => [post_modified] => 2017-09-16 19:13:24 [post_modified_gmt] => 2017-09-16 13:13:24 [post_content_filtered] => [post_parent] => 0 [guid] => http://rs-wordpress.com/?post_type=featured-article&p=433 [menu_order] => 0 [post_type] => featured-article [post_mime_type] => [comment_count] => 0 [filter] => raw ) [comment_count] => 0 [current_comment] => -1 [found_posts] => 3 [max_num_pages] => 2 [max_num_comment_pages] => 0 [is_single] => [is_preview] => [is_page] => [is_archive] => 1 [is_date] => [is_year] => [is_month] => [is_day] => [is_time] => [is_author] => [is_category] => [is_tag] => [is_tax] => [is_search] => [is_feed] => [is_comment_feed] => [is_trackback] => [is_home] => [is_404] => [is_embed] => [is_paged] => [is_admin] => [is_attachment] => [is_singular] => [is_robots] => [is_posts_page] => [is_post_type_archive] => 1 [query_vars_hash:WP_Query:private] => 8c6cb592fd6eb096f5db534a95e5b42c [query_vars_changed:WP_Query:private] => [thumbnails_cached] => [stopwords:WP_Query:private] => [compat_fields:WP_Query:private] => Array ( [0] => query_vars_hash [1] => query_vars_changed ) [compat_methods:WP_Query:private] => Array ( [0] => init_query_flags [1] => parse_tax_query ) ) ```
You made a mistake in the syntax: `if ($featured_articles > have_posts()): while ($featured_articles > have_posts()) : $featured_articles->the_post();` in the `if` and `while` conditions should be `->` instead `>`.
280,271
<p>I use <em>Tinymce Advanced</em> plugin. I would like to remove p tag by adding this code <code>remove_filter( 'the_content', 'wpautop' );</code> to my <code>functions.php</code>. However, it does't work. When I press ENTER, it still inserts double line, not single line. The <code>p</code> character still displays at the bottom left of the <code>textarea</code>.</p>
[ { "answer_id": 280330, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Your code seems pretty correnct. Please check whether your code actually removes <code>wpautop</code> function or not with this below line of code-</p>\n\n<pre><code>var_dump( $wp_filter['the_content'] );\n</code></pre>\n\n<p>Add it at the end of your <code>functions.php</code> and analyze the output. If the <code>wpautop</code> is still there then either it is getting added after your code is been executed or your code is not been executing at all.</p>\n\n<p>If all the above is good but the code still doesn't work then I can suggest you this below forced removal of those <code>p</code> tag with below code-</p>\n\n<pre><code>add_action( 'admin_print_footer_scripts', 'the_dramatist_remove_wpautop', 100 );\nfunction the_dramatist_remove_wpautop() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n (function($) {\n if ( typeof wp === 'object' &amp;&amp; typeof wp.editor === 'object') {\n wp.editor.autop = function (text) { return text; };\n wp.editor.removep = function (text) { return text; };\n }\n })( jQuery);\n &lt;/script&gt; \n &lt;?php\n}\n</code></pre>\n\n<blockquote>\n <p>This later block of code isn't tested. Please test it before going live.</p>\n</blockquote>\n\n<p>Hope the above answer helps.</p>\n" }, { "answer_id": 301071, "author": "ekerner", "author_id": 141957, "author_profile": "https://wordpress.stackexchange.com/users/141957", "pm_score": 1, "selected": false, "text": "<p>You can achieve this much easier with css (escpecially for wp-ers who dont have access to edit plugins):</p>\n\n<pre><code>&lt;style&gt;\np:empty{\n height: 0;\n margin: 0;\n padding: 0;\n}\n&lt;/style&gt;\n</code></pre>\n" } ]
2017/09/17
[ "https://wordpress.stackexchange.com/questions/280271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125408/" ]
I use *Tinymce Advanced* plugin. I would like to remove p tag by adding this code `remove_filter( 'the_content', 'wpautop' );` to my `functions.php`. However, it does't work. When I press ENTER, it still inserts double line, not single line. The `p` character still displays at the bottom left of the `textarea`.
You can achieve this much easier with css (escpecially for wp-ers who dont have access to edit plugins): ``` <style> p:empty{ height: 0; margin: 0; padding: 0; } </style> ```
280,278
<p>In the customizer, the site identity section is missing a logo upload field. Adding such field is not a big deal: A field can be added, but I don't know the section name that is created in the core of the WordPress. Can someone help me in that?</p> <p>The field can be created like this:</p> <pre><code> $fields[] = array( 'type' =&gt; 'color', 'setting' =&gt; 'links_color', 'label' =&gt; __( 'Links Color', 'twentytwelve' ), 'section' =&gt; 'header', 'default' =&gt; '#00A2E8', 'priority' =&gt; 10, 'output' =&gt; array( 'element' =&gt; 'body #page a, body #page a:link, body #page a:visited, body #page a:hover', 'property' =&gt; 'color', ) ); </code></pre> <p>The below is a section for the header:</p> <pre><code>'section' =&gt; 'header', </code></pre> <p>I want to know the section name of the site identity so that the logo option can be added there.<a href="https://i.stack.imgur.com/5eFGI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5eFGI.png" alt="enter image description here"></a></p>
[ { "answer_id": 280294, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 3, "selected": true, "text": "<p>The “Site Identity” section has the ID of <code>title_tagline</code> for historical reasons.</p>\n\n<p>If you want to see the IDs for the core sections, all you have to do is look at the source for <a href=\"https://github.com/WordPress/wordpress-develop/blob/2ff66f7c50cf375289cf5f2e47d140250c94e59e/src/wp-includes/class-wp-customize-manager.php#L3724-L4261\" rel=\"nofollow noreferrer\"><code>WP_Customize_Manager::register_controls()</code></a>. Alternatively, you can get a list of all the sections registered, whether by core or by plugins, by opening your console and entering: <code>_.keys( wp.customize.settings.sections )</code>.</p>\n" }, { "answer_id": 365097, "author": "Suraj Khanal", "author_id": 151972, "author_profile": "https://wordpress.stackexchange.com/users/151972", "pm_score": 0, "selected": false, "text": "<p>For anyone in the future searching for the already defined section name, have a look at this <a href=\"https://developer.wordpress.org/themes/customize-api/customizer-objects/#sections\" rel=\"nofollow noreferrer\">official link</a> from wordpress documentation. </p>\n" } ]
2017/09/17
[ "https://wordpress.stackexchange.com/questions/280278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
In the customizer, the site identity section is missing a logo upload field. Adding such field is not a big deal: A field can be added, but I don't know the section name that is created in the core of the WordPress. Can someone help me in that? The field can be created like this: ``` $fields[] = array( 'type' => 'color', 'setting' => 'links_color', 'label' => __( 'Links Color', 'twentytwelve' ), 'section' => 'header', 'default' => '#00A2E8', 'priority' => 10, 'output' => array( 'element' => 'body #page a, body #page a:link, body #page a:visited, body #page a:hover', 'property' => 'color', ) ); ``` The below is a section for the header: ``` 'section' => 'header', ``` I want to know the section name of the site identity so that the logo option can be added there.[![enter image description here](https://i.stack.imgur.com/5eFGI.png)](https://i.stack.imgur.com/5eFGI.png)
The “Site Identity” section has the ID of `title_tagline` for historical reasons. If you want to see the IDs for the core sections, all you have to do is look at the source for [`WP_Customize_Manager::register_controls()`](https://github.com/WordPress/wordpress-develop/blob/2ff66f7c50cf375289cf5f2e47d140250c94e59e/src/wp-includes/class-wp-customize-manager.php#L3724-L4261). Alternatively, you can get a list of all the sections registered, whether by core or by plugins, by opening your console and entering: `_.keys( wp.customize.settings.sections )`.
280,311
<p>I'm seeking to echo the domain name (url) without the 'http://' (or 'https://').</p> <p>I've created the following: </p> <p><code>&lt;?php $surl = bloginfo('url'); $findh = array( 'http://' ); $replace = ''; $outputh = str_replace( $findh, $replace, $surl ); echo $outputh; ?&gt;</code></p> <p>also another one (of many) I tried:</p> <pre><code>&lt;?php $surl = bloginfo('url'); echo str_replace('http://', '', $surl); ?&gt; </code></pre> <p>Seems like a simple task, but output still includes the 'http://' when the domain is echo'd. Reviewed other posts here and other sites to no avail. Perhaps something within Wordpress base files is interfering, not sure on this one.</p> <p>Thanks in advance for any feedback!</p>
[ { "answer_id": 280313, "author": "UltimateDevil", "author_id": 128073, "author_profile": "https://wordpress.stackexchange.com/users/128073", "pm_score": 0, "selected": false, "text": "<p>try this may help you,</p>\n\n<pre><code>$link = get_permalink();\n $remove_http = '#^http(s)?://#';\n $remove_www = '/^www\\./';\n $replace = '';\n $new_link = preg_replace( $remove_http, $replace, $permalink );\n $new_link = preg_replace( $remove_www, $replace, $new_link );\n echo '&lt;p&gt;' . $new_link . '&lt;/p&gt;';\n</code></pre>\n" }, { "answer_id": 280347, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 2, "selected": false, "text": "<p>You could use core PHP function <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\"><code>parse_url();</code></a> for this.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>$url = 'https://www.google.com/';\n$url_data = parse_url( $url );\n$url_data['host'] = explode( '.', $url_data['host'] );\nunset( $url_data['host'][0] );\n\necho join( '.', $url_data['host'] ); // outputs: google.com\n</code></pre>\n" }, { "answer_id": 280349, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/bloginfo/\" rel=\"nofollow noreferrer\">bloginfo</a> echos its result, this is why your attempt to \"get the value\" and manipulate it results in nothing, as no value is actually being returned. If you want to get the relevant value you should use <code>get_bloginfo</code> instead </p>\n" }, { "answer_id": 340799, "author": "Gopala krishnan", "author_id": 168404, "author_profile": "https://wordpress.stackexchange.com/users/168404", "pm_score": 2, "selected": false, "text": "<p>Use this code to remove <code>http://</code> and <code>https://</code></p>\n<pre><code>$str = 'http://www.google.com';\n$str = preg_replace('#^https?://#i', '', $str);\necho $str;\n</code></pre>\n" } ]
2017/09/18
[ "https://wordpress.stackexchange.com/questions/280311", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128074/" ]
I'm seeking to echo the domain name (url) without the 'http://' (or 'https://'). I've created the following: `<?php $surl = bloginfo('url'); $findh = array( 'http://' ); $replace = ''; $outputh = str_replace( $findh, $replace, $surl ); echo $outputh; ?>` also another one (of many) I tried: ``` <?php $surl = bloginfo('url'); echo str_replace('http://', '', $surl); ?> ``` Seems like a simple task, but output still includes the 'http://' when the domain is echo'd. Reviewed other posts here and other sites to no avail. Perhaps something within Wordpress base files is interfering, not sure on this one. Thanks in advance for any feedback!
You could use core PHP function [`parse_url();`](http://php.net/manual/en/function.parse-url.php) for this. **Example:** ``` $url = 'https://www.google.com/'; $url_data = parse_url( $url ); $url_data['host'] = explode( '.', $url_data['host'] ); unset( $url_data['host'][0] ); echo join( '.', $url_data['host'] ); // outputs: google.com ```
280,338
<p>In my plugin (my first one), I inserted 2 posts with a custom post_type ('foo' for this example). This kind of post is exactly like a page but which is unedited (so hidden in the admin. interface). I would like to display this post on the front-end as a page (so with the template: page.php) when the user click on the button with the url : - mysiteurl.com?post_type=foo&amp;p=140 where 140 is the post ID.</p> <p>I get this error </p> <blockquote> <p>Trying to get property of non-object in ...\wordpress\wp-includes\canonical.php on line 120</p> </blockquote> <pre><code>&lt;?php namespace MyNameSpace\FrontEnd; class FrontEnd { public function __construct(){ // Include dependencies $this-&gt;include_dependencies(); // Initialize the components $this-&gt;init(); } private function include_dependencies(){ ... } private function init(){ add_filter( 'template_include', array( $this, 'foo_subs_form_page_template'), 99 ); ... } public function foo_subs_form_page_template( $template ) { if ( is_page( 'foo' ) ) { $new_template = locate_template( array( 'page.php' ) ); if ( '' != $new_template ) { return $new_template; } } return $template; } } </code></pre> <p>What do I need for that ?</p>
[ { "answer_id": 280313, "author": "UltimateDevil", "author_id": 128073, "author_profile": "https://wordpress.stackexchange.com/users/128073", "pm_score": 0, "selected": false, "text": "<p>try this may help you,</p>\n\n<pre><code>$link = get_permalink();\n $remove_http = '#^http(s)?://#';\n $remove_www = '/^www\\./';\n $replace = '';\n $new_link = preg_replace( $remove_http, $replace, $permalink );\n $new_link = preg_replace( $remove_www, $replace, $new_link );\n echo '&lt;p&gt;' . $new_link . '&lt;/p&gt;';\n</code></pre>\n" }, { "answer_id": 280347, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 2, "selected": false, "text": "<p>You could use core PHP function <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\"><code>parse_url();</code></a> for this.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>$url = 'https://www.google.com/';\n$url_data = parse_url( $url );\n$url_data['host'] = explode( '.', $url_data['host'] );\nunset( $url_data['host'][0] );\n\necho join( '.', $url_data['host'] ); // outputs: google.com\n</code></pre>\n" }, { "answer_id": 280349, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/bloginfo/\" rel=\"nofollow noreferrer\">bloginfo</a> echos its result, this is why your attempt to \"get the value\" and manipulate it results in nothing, as no value is actually being returned. If you want to get the relevant value you should use <code>get_bloginfo</code> instead </p>\n" }, { "answer_id": 340799, "author": "Gopala krishnan", "author_id": 168404, "author_profile": "https://wordpress.stackexchange.com/users/168404", "pm_score": 2, "selected": false, "text": "<p>Use this code to remove <code>http://</code> and <code>https://</code></p>\n<pre><code>$str = 'http://www.google.com';\n$str = preg_replace('#^https?://#i', '', $str);\necho $str;\n</code></pre>\n" } ]
2017/09/18
[ "https://wordpress.stackexchange.com/questions/280338", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
In my plugin (my first one), I inserted 2 posts with a custom post\_type ('foo' for this example). This kind of post is exactly like a page but which is unedited (so hidden in the admin. interface). I would like to display this post on the front-end as a page (so with the template: page.php) when the user click on the button with the url : - mysiteurl.com?post\_type=foo&p=140 where 140 is the post ID. I get this error > > Trying to get property of non-object in ...\wordpress\wp-includes\canonical.php on line 120 > > > ``` <?php namespace MyNameSpace\FrontEnd; class FrontEnd { public function __construct(){ // Include dependencies $this->include_dependencies(); // Initialize the components $this->init(); } private function include_dependencies(){ ... } private function init(){ add_filter( 'template_include', array( $this, 'foo_subs_form_page_template'), 99 ); ... } public function foo_subs_form_page_template( $template ) { if ( is_page( 'foo' ) ) { $new_template = locate_template( array( 'page.php' ) ); if ( '' != $new_template ) { return $new_template; } } return $template; } } ``` What do I need for that ?
You could use core PHP function [`parse_url();`](http://php.net/manual/en/function.parse-url.php) for this. **Example:** ``` $url = 'https://www.google.com/'; $url_data = parse_url( $url ); $url_data['host'] = explode( '.', $url_data['host'] ); unset( $url_data['host'][0] ); echo join( '.', $url_data['host'] ); // outputs: google.com ```
280,364
<p>We bought a SLL certificate recently to change our website to work with https protocol. After this change, we realized that the tag:</p> <pre><code>&lt;meta property="og:image" content="https://[ ... url ...].jpg" /&gt; </code></pre> <p>is working when you load the website and open its source code. The thing is: Facebook sharing debug tool doesn't find this tag anymore. When I click on the link that shows me what is Facebook seeing (HTML), this tag is written like this:</p> <pre><code>&lt;metaproperty content="https://[ ... url ...].jpg"&gt; </code></pre> <p>I already updated the Yoast SEO plugin to the newest version, but didn't solve the problem.</p> <p>Anyone has any clue?</p>
[ { "answer_id": 280374, "author": "Jan Boddez", "author_id": 128111, "author_profile": "https://wordpress.stackexchange.com/users/128111", "pm_score": 1, "selected": false, "text": "<p>I don't think the tag is wrongly formatted <em>because</em> of the SSL certificate.</p>\n\n<p>Sometimes, it takes quite a while (several hours?) for Facebook to update its cache. It's confused me before, too.</p>\n\n<p>As a matter of fact, the tag in the source <em>is</em> what Facebook uses to generate its preview. So if that's correct, you should eventually be okay.</p>\n\n<p>Think the Facebook developer pages should let you clear the cache for your page manually, too.</p>\n" }, { "answer_id": 280375, "author": "Von", "author_id": 124661, "author_profile": "https://wordpress.stackexchange.com/users/124661", "pm_score": 1, "selected": false, "text": "<p>Use the facebook debug tool. You can use the \"scrape again\" button to make sure the featured image gets pulled back in.</p>\n\n<p><a href=\"https://developers.facebook.com/tools/debug/\" rel=\"nofollow noreferrer\">https://developers.facebook.com/tools/debug/</a></p>\n" }, { "answer_id": 280452, "author": "Adriano Castro", "author_id": 77513, "author_profile": "https://wordpress.stackexchange.com/users/77513", "pm_score": 3, "selected": true, "text": "<p>The https change was not the cause. Actually - coincidentally - the W3 Total Cache was updated on the same day, and the <strong>Minify</strong> setting was breaking lines between <strong>meta</strong> and <strong>property</strong> words on the HTML, which were causing the error on Facebook debug tool.</p>\n" } ]
2017/09/18
[ "https://wordpress.stackexchange.com/questions/280364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77513/" ]
We bought a SLL certificate recently to change our website to work with https protocol. After this change, we realized that the tag: ``` <meta property="og:image" content="https://[ ... url ...].jpg" /> ``` is working when you load the website and open its source code. The thing is: Facebook sharing debug tool doesn't find this tag anymore. When I click on the link that shows me what is Facebook seeing (HTML), this tag is written like this: ``` <metaproperty content="https://[ ... url ...].jpg"> ``` I already updated the Yoast SEO plugin to the newest version, but didn't solve the problem. Anyone has any clue?
The https change was not the cause. Actually - coincidentally - the W3 Total Cache was updated on the same day, and the **Minify** setting was breaking lines between **meta** and **property** words on the HTML, which were causing the error on Facebook debug tool.
280,429
<p>I'm developing a WordPress theme and I would like to add a feature like that of page origin page builder.</p> <p>I would have just used their plugin but I don't really like the way it's setup. My main question is a guideline on how to make a page builder to have a button with an ability to insert widgets into areas.</p> <p>I've searched and searched but I've not found any post related to inserting widgets on pages.</p> <p>I'm not that good with JavaScript but I also have a little knowledge on PHP.</p> <p>Any answer will be appreciated.</p>
[ { "answer_id": 280462, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Building a page builder would be a much more complex undertaking than some other options. I would suggest creating a child theme from your current one, then creating a custom template (i.e. \"tpl-custom-sidebar.php\") that has a widgetized sidebar. Then, you would manage the widgets for that template in Appearance > Widgets or the Customizer.</p>\n\n<p>You could create as many or as few of these custom templates as you want, then just select the appropriate template from the dropdown menu in the editor screen.</p>\n\n<p>Another option, depending on what you're trying to accomplish, may be to convert your widgets into shortcodes. By doing this you can paste your shortcodes directly into the editor of the particular post(s) you want to affect. This might be a little easier to keep track of because you can see right in the post content what shortcodes are in use.</p>\n" }, { "answer_id": 280474, "author": "Eh Jewel", "author_id": 75264, "author_profile": "https://wordpress.stackexchange.com/users/75264", "pm_score": 1, "selected": false, "text": "<p>You can insert widgets into a post by Shortcode. Just make a shortcode with <code>dynamic_sidebar()</code> function to insert your specified sidebar widgets.</p>\n\n<pre><code>&lt;?php\nadd_shortcode('sidebar_widgets', function($atts, $content) {\nob_start();\n$atts = shortcode_atts(array(\n 'sidebar_id' =&gt; '',\n),$atts);\n?&gt;\n &lt;div&gt;\n &lt;?php dynamic_sidebar($atts['sidebar_id']); ?&gt;\n &lt;/div&gt;\n &lt;?php\n$html = ob_get_clean();\nreturn $html;\n});\n</code></pre>\n\n<p>You can implement this shortcode with any page builder plugin. </p>\n" } ]
2017/09/19
[ "https://wordpress.stackexchange.com/questions/280429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127929/" ]
I'm developing a WordPress theme and I would like to add a feature like that of page origin page builder. I would have just used their plugin but I don't really like the way it's setup. My main question is a guideline on how to make a page builder to have a button with an ability to insert widgets into areas. I've searched and searched but I've not found any post related to inserting widgets on pages. I'm not that good with JavaScript but I also have a little knowledge on PHP. Any answer will be appreciated.
You can insert widgets into a post by Shortcode. Just make a shortcode with `dynamic_sidebar()` function to insert your specified sidebar widgets. ``` <?php add_shortcode('sidebar_widgets', function($atts, $content) { ob_start(); $atts = shortcode_atts(array( 'sidebar_id' => '', ),$atts); ?> <div> <?php dynamic_sidebar($atts['sidebar_id']); ?> </div> <?php $html = ob_get_clean(); return $html; }); ``` You can implement this shortcode with any page builder plugin.
280,430
<p>Can I do this for posts?</p> <p>I have the most recents posts I am fetching and I am showing the thumbnail (the featured image) of these posts IF they exist.</p> <p><strong>What I want to do now, is to show category images IF the featured image does not exist.</strong></p> <p>Can someone help me with this?</p> <p>I have this, at the moment:</p> <pre><code> &lt;?php $args = array( 'numberposts' =&gt; '5' ); $recent_posts = wp_get_recent_posts($args); $category = get_the_category(); foreach( $recent_posts as $recent ){ if($recent['post_status']=="publish"){ if ( has_post_thumbnail($recent["ID"])) { echo '&lt;a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" &gt;' . get_the_post_thumbnail($recent["ID"], 'thumbnail').'&lt;div class="browse_category_name"&gt; ' . $recent["post_title"]. '&lt;div&gt; ' . get_the_author_meta('display_name', $recent["post_author"]). '&lt;/div&gt;&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; '; } else{ echo '&lt;a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" &gt;' . get_categories_with_images($post-&gt;ID,' ,') . $recent["post_title"].'&lt;/a&gt;&lt;/li&gt; '; } } } ?&gt; </code></pre> <p>And this is my <strong>functions.php:</strong></p> <pre><code>function get_categories_with_images($post_id,$separator ){ //first get all categories of that post $post_categories = wp_get_post_categories( $post_id ); $cats = array(); foreach($post_categories as $c){ $cat = get_category( $c ); $cat_data = get_option("category_$c"); //and then i just display my category image if it exists $cat_image = ''; if (isset($cat_data['img'])){ $cat_image = '&lt;img src="'.$cat_data['img'].'"&gt;'; } $cats[] = $cat_image . '&lt;a href="'.get_category_link( $c ) . '"&gt;' .$cat-&gt;name .'&lt;/a&gt;'; } return implode($separator , $cats); } </code></pre> <p>Problem: category image is not shown, even though thumbnail / featured image is not set.</p>
[ { "answer_id": 280462, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Building a page builder would be a much more complex undertaking than some other options. I would suggest creating a child theme from your current one, then creating a custom template (i.e. \"tpl-custom-sidebar.php\") that has a widgetized sidebar. Then, you would manage the widgets for that template in Appearance > Widgets or the Customizer.</p>\n\n<p>You could create as many or as few of these custom templates as you want, then just select the appropriate template from the dropdown menu in the editor screen.</p>\n\n<p>Another option, depending on what you're trying to accomplish, may be to convert your widgets into shortcodes. By doing this you can paste your shortcodes directly into the editor of the particular post(s) you want to affect. This might be a little easier to keep track of because you can see right in the post content what shortcodes are in use.</p>\n" }, { "answer_id": 280474, "author": "Eh Jewel", "author_id": 75264, "author_profile": "https://wordpress.stackexchange.com/users/75264", "pm_score": 1, "selected": false, "text": "<p>You can insert widgets into a post by Shortcode. Just make a shortcode with <code>dynamic_sidebar()</code> function to insert your specified sidebar widgets.</p>\n\n<pre><code>&lt;?php\nadd_shortcode('sidebar_widgets', function($atts, $content) {\nob_start();\n$atts = shortcode_atts(array(\n 'sidebar_id' =&gt; '',\n),$atts);\n?&gt;\n &lt;div&gt;\n &lt;?php dynamic_sidebar($atts['sidebar_id']); ?&gt;\n &lt;/div&gt;\n &lt;?php\n$html = ob_get_clean();\nreturn $html;\n});\n</code></pre>\n\n<p>You can implement this shortcode with any page builder plugin. </p>\n" } ]
2017/09/19
[ "https://wordpress.stackexchange.com/questions/280430", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62192/" ]
Can I do this for posts? I have the most recents posts I am fetching and I am showing the thumbnail (the featured image) of these posts IF they exist. **What I want to do now, is to show category images IF the featured image does not exist.** Can someone help me with this? I have this, at the moment: ``` <?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts($args); $category = get_the_category(); foreach( $recent_posts as $recent ){ if($recent['post_status']=="publish"){ if ( has_post_thumbnail($recent["ID"])) { echo '<a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], 'thumbnail').'<div class="browse_category_name"> ' . $recent["post_title"]. '<div> ' . get_the_author_meta('display_name', $recent["post_author"]). '</div></div></a></li> '; } else{ echo '<a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_categories_with_images($post->ID,' ,') . $recent["post_title"].'</a></li> '; } } } ?> ``` And this is my **functions.php:** ``` function get_categories_with_images($post_id,$separator ){ //first get all categories of that post $post_categories = wp_get_post_categories( $post_id ); $cats = array(); foreach($post_categories as $c){ $cat = get_category( $c ); $cat_data = get_option("category_$c"); //and then i just display my category image if it exists $cat_image = ''; if (isset($cat_data['img'])){ $cat_image = '<img src="'.$cat_data['img'].'">'; } $cats[] = $cat_image . '<a href="'.get_category_link( $c ) . '">' .$cat->name .'</a>'; } return implode($separator , $cats); } ``` Problem: category image is not shown, even though thumbnail / featured image is not set.
You can insert widgets into a post by Shortcode. Just make a shortcode with `dynamic_sidebar()` function to insert your specified sidebar widgets. ``` <?php add_shortcode('sidebar_widgets', function($atts, $content) { ob_start(); $atts = shortcode_atts(array( 'sidebar_id' => '', ),$atts); ?> <div> <?php dynamic_sidebar($atts['sidebar_id']); ?> </div> <?php $html = ob_get_clean(); return $html; }); ``` You can implement this shortcode with any page builder plugin.
280,457
<p>I've created a page with list of custom terms: <a href="https://i.stack.imgur.com/JZIhy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JZIhy.png" alt="enter image description here"></a></p> <p>Under each Term, i need to show every posts with post_type = 'courses'e taxnonomy = 'courses_category'</p> <p>What will be the query to display those records?</p> <p>Thanks</p>
[ { "answer_id": 280462, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Building a page builder would be a much more complex undertaking than some other options. I would suggest creating a child theme from your current one, then creating a custom template (i.e. \"tpl-custom-sidebar.php\") that has a widgetized sidebar. Then, you would manage the widgets for that template in Appearance > Widgets or the Customizer.</p>\n\n<p>You could create as many or as few of these custom templates as you want, then just select the appropriate template from the dropdown menu in the editor screen.</p>\n\n<p>Another option, depending on what you're trying to accomplish, may be to convert your widgets into shortcodes. By doing this you can paste your shortcodes directly into the editor of the particular post(s) you want to affect. This might be a little easier to keep track of because you can see right in the post content what shortcodes are in use.</p>\n" }, { "answer_id": 280474, "author": "Eh Jewel", "author_id": 75264, "author_profile": "https://wordpress.stackexchange.com/users/75264", "pm_score": 1, "selected": false, "text": "<p>You can insert widgets into a post by Shortcode. Just make a shortcode with <code>dynamic_sidebar()</code> function to insert your specified sidebar widgets.</p>\n\n<pre><code>&lt;?php\nadd_shortcode('sidebar_widgets', function($atts, $content) {\nob_start();\n$atts = shortcode_atts(array(\n 'sidebar_id' =&gt; '',\n),$atts);\n?&gt;\n &lt;div&gt;\n &lt;?php dynamic_sidebar($atts['sidebar_id']); ?&gt;\n &lt;/div&gt;\n &lt;?php\n$html = ob_get_clean();\nreturn $html;\n});\n</code></pre>\n\n<p>You can implement this shortcode with any page builder plugin. </p>\n" } ]
2017/09/19
[ "https://wordpress.stackexchange.com/questions/280457", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128160/" ]
I've created a page with list of custom terms: [![enter image description here](https://i.stack.imgur.com/JZIhy.png)](https://i.stack.imgur.com/JZIhy.png) Under each Term, i need to show every posts with post\_type = 'courses'e taxnonomy = 'courses\_category' What will be the query to display those records? Thanks
You can insert widgets into a post by Shortcode. Just make a shortcode with `dynamic_sidebar()` function to insert your specified sidebar widgets. ``` <?php add_shortcode('sidebar_widgets', function($atts, $content) { ob_start(); $atts = shortcode_atts(array( 'sidebar_id' => '', ),$atts); ?> <div> <?php dynamic_sidebar($atts['sidebar_id']); ?> </div> <?php $html = ob_get_clean(); return $html; }); ``` You can implement this shortcode with any page builder plugin.
280,459
<p>I am trying to create custom slider so trying to print all ul in same li . but problem is that I am getting data in different different ul. Here is query.</p> <pre><code> &lt;?php $args = array( 'post_type' =&gt; 'slider', 'posts_per_page' =&gt; 5 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); echo '&lt;ul&gt;';?&gt; &lt;li data-transition="fade" data-slotamount="6"&gt; &lt;?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt; &lt;p&gt;&lt;a href="#."&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt; &lt;/li&gt; &lt;?php echo '&lt;/ul&gt;'; endwhile; wp_reset_postdata();?&gt; </code></pre> <p>Here Is output</p> <pre><code> &lt;ul&gt; &lt;li data-transition="fade" data-slotamount="6"&gt; &lt;img width="1364" height="612" src="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5.jpg" class="thumbnail zoom" alt="" srcset="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5.jpg 1364w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-300x135.jpg 300w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-768x345.jpg 768w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-1024x459.jpg 1024w" sizes="(max-width: 1364px) 100vw, 1364px" /&gt; &lt;p&gt;&lt;a href="#."&gt;slider2&lt;/a&gt;&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt;&lt;ul&gt; &lt;li data-transition="fade" data-slotamount="6"&gt; &lt;img width="1364" height="612" src="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4.jpg" class="thumbnail zoom" alt="" srcset="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4.jpg 1364w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-300x135.jpg 300w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-768x345.jpg 768w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-1024x459.jpg 1024w" sizes="(max-width: 1364px) 100vw, 1364px" /&gt; &lt;p&gt;&lt;a href="#."&gt;slider1&lt;/a&gt;&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 280460, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Move the <code>&lt;ul&gt;</code> out of the <code>while</code> loop:</p>\n\n<pre><code>$loop = new WP_Query( $args );\necho '&lt;ul&gt;';\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php\nendwhile; wp_reset_postdata();\necho '&lt;/ul&gt;';\n</code></pre>\n" }, { "answer_id": 280461, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": 2, "selected": false, "text": "<p>Preblem is because inside loop you have UL </p>\n\n<pre><code>echo '&lt;ul&gt;';\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php \n endwhile;echo '&lt;/ul&gt;';\n</code></pre>\n\n<p>Just make one IF statment before echo-ing UL tag </p>\n\n<pre><code> $loop = new WP_Query( $args );\n if($loop-have_posts()):\n echo '&lt;ul&gt;';\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php\n endwhile; echo '&lt;/ul&gt;';endif; wp_reset_postdata();?&gt; \n</code></pre>\n" } ]
2017/09/19
[ "https://wordpress.stackexchange.com/questions/280459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120176/" ]
I am trying to create custom slider so trying to print all ul in same li . but problem is that I am getting data in different different ul. Here is query. ``` <?php $args = array( 'post_type' => 'slider', 'posts_per_page' => 5 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<ul>';?> <li data-transition="fade" data-slotamount="6"> <?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'thumbnail zoom' ) );?> <p><a href="#."><?php the_title();?></a></p> </li> <?php echo '</ul>'; endwhile; wp_reset_postdata();?> ``` Here Is output ``` <ul> <li data-transition="fade" data-slotamount="6"> <img width="1364" height="612" src="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5.jpg" class="thumbnail zoom" alt="" srcset="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5.jpg 1364w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-300x135.jpg 300w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-768x345.jpg 768w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner5-1024x459.jpg 1024w" sizes="(max-width: 1364px) 100vw, 1364px" /> <p><a href="#.">slider2</a></p> </li> </ul><ul> <li data-transition="fade" data-slotamount="6"> <img width="1364" height="612" src="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4.jpg" class="thumbnail zoom" alt="" srcset="http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4.jpg 1364w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-300x135.jpg 300w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-768x345.jpg 768w, http://localhost/wordpress/wp-content/uploads/2017/09/main-banner4-1024x459.jpg 1024w" sizes="(max-width: 1364px) 100vw, 1364px" /> <p><a href="#.">slider1</a></p> </li> </ul> ```
Preblem is because inside loop you have UL ``` echo '<ul>'; while ( $loop->have_posts() ) : $loop->the_post(); ?> <li data-transition="fade" data-slotamount="6"> <?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'thumbnail zoom' ) );?> <p><a href="#."><?php the_title();?></a></p> </li> <?php endwhile;echo '</ul>'; ``` Just make one IF statment before echo-ing UL tag ``` $loop = new WP_Query( $args ); if($loop-have_posts()): echo '<ul>'; while ( $loop->have_posts() ) : $loop->the_post(); ?> <li data-transition="fade" data-slotamount="6"> <?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'thumbnail zoom' ) );?> <p><a href="#."><?php the_title();?></a></p> </li> <?php endwhile; echo '</ul>';endif; wp_reset_postdata();?> ```
280,532
<p>I'm making a plugin which generate a form in a custom post. For security, I would like to avise the administrator with a notice if this specific post does not work with HTTPS/SSL yet.</p> <p>I know the function <strong>is_ssl()</strong> but it is to check the current page, not a specific post by the ID.</p> <p>Someone has got an idea ?</p>
[ { "answer_id": 280460, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Move the <code>&lt;ul&gt;</code> out of the <code>while</code> loop:</p>\n\n<pre><code>$loop = new WP_Query( $args );\necho '&lt;ul&gt;';\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php\nendwhile; wp_reset_postdata();\necho '&lt;/ul&gt;';\n</code></pre>\n" }, { "answer_id": 280461, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": 2, "selected": false, "text": "<p>Preblem is because inside loop you have UL </p>\n\n<pre><code>echo '&lt;ul&gt;';\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php \n endwhile;echo '&lt;/ul&gt;';\n</code></pre>\n\n<p>Just make one IF statment before echo-ing UL tag </p>\n\n<pre><code> $loop = new WP_Query( $args );\n if($loop-have_posts()):\n echo '&lt;ul&gt;';\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;li data-transition=\"fade\" data-slotamount=\"6\"&gt;\n &lt;?php\n echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' =&gt; 'thumbnail zoom' ) );?&gt;\n &lt;p&gt;&lt;a href=\"#.\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php\n endwhile; echo '&lt;/ul&gt;';endif; wp_reset_postdata();?&gt; \n</code></pre>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280532", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I'm making a plugin which generate a form in a custom post. For security, I would like to avise the administrator with a notice if this specific post does not work with HTTPS/SSL yet. I know the function **is\_ssl()** but it is to check the current page, not a specific post by the ID. Someone has got an idea ?
Preblem is because inside loop you have UL ``` echo '<ul>'; while ( $loop->have_posts() ) : $loop->the_post(); ?> <li data-transition="fade" data-slotamount="6"> <?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'thumbnail zoom' ) );?> <p><a href="#."><?php the_title();?></a></p> </li> <?php endwhile;echo '</ul>'; ``` Just make one IF statment before echo-ing UL tag ``` $loop = new WP_Query( $args ); if($loop-have_posts()): echo '<ul>'; while ( $loop->have_posts() ) : $loop->the_post(); ?> <li data-transition="fade" data-slotamount="6"> <?php echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'thumbnail zoom' ) );?> <p><a href="#."><?php the_title();?></a></p> </li> <?php endwhile; echo '</ul>';endif; wp_reset_postdata();?> ```
280,540
<p>I have two areas where I fetch the most recent entries. In the first area, I want to get the first 10 posts. In the second area, I want to fetch the posts starting at post number 11....</p> <p>I have this:</p> <pre><code>&lt;?php $args = array( 'numberposts' =&gt; '10' ); $recent_posts = wp_get_recent_posts($args); $featured_posts = themename_get_featured_posts(); if(!empty($featured_posts) &amp;&amp; is_array($featured_posts)) { $query_arr = array( 'post__not_in' =&gt; $featured_posts, $recent_posts, 'paged' =&gt; $paged, 'suppress_filters' =&gt; false, ); query_posts($query_arr); } $key = 11; if (have_posts()) : while (have_posts()) : the_post(); $image_thumb = ''; $key++; $image_id = get_post_thumbnail_id(get_the_ID()); ?&gt; </code></pre> <p>But whatever I do (even if I'd remove the first if statement) I keep seeing the same posts in every area...</p> <p>How can I get this to work?</p>
[ { "answer_id": 280542, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>Looking at the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters\" rel=\"nofollow noreferrer\">pagination parameters</a> I see two possibilities: Either use <code>offset</code> or <code>paged</code>.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'offset' =&gt; 10,\n);\n</code></pre>\n\n<p>should work just as well as</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; 2,\n);\n</code></pre>\n" }, { "answer_id": 280557, "author": "Siyah", "author_id": 62192, "author_profile": "https://wordpress.stackexchange.com/users/62192", "pm_score": 2, "selected": false, "text": "<p>I solved it myself. What I did, is adding this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$loop = new WP_Query(array(\n 'offset' =&gt; 20, \n));\n</code></pre>\n<p>And then changing:</p>\n<pre><code>if (have_posts()) : while (have_posts()) : the_post();\n</code></pre>\n<p>into:</p>\n<pre><code>if ($loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n</code></pre>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62192/" ]
I have two areas where I fetch the most recent entries. In the first area, I want to get the first 10 posts. In the second area, I want to fetch the posts starting at post number 11.... I have this: ``` <?php $args = array( 'numberposts' => '10' ); $recent_posts = wp_get_recent_posts($args); $featured_posts = themename_get_featured_posts(); if(!empty($featured_posts) && is_array($featured_posts)) { $query_arr = array( 'post__not_in' => $featured_posts, $recent_posts, 'paged' => $paged, 'suppress_filters' => false, ); query_posts($query_arr); } $key = 11; if (have_posts()) : while (have_posts()) : the_post(); $image_thumb = ''; $key++; $image_id = get_post_thumbnail_id(get_the_ID()); ?> ``` But whatever I do (even if I'd remove the first if statement) I keep seeing the same posts in every area... How can I get this to work?
I solved it myself. What I did, is adding this: ```php $loop = new WP_Query(array( 'offset' => 20, )); ``` And then changing: ``` if (have_posts()) : while (have_posts()) : the_post(); ``` into: ``` if ($loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ```
280,546
<p>Here is my website <a href="http://www.taramesh.ae/" rel="nofollow noreferrer">http://www.taramesh.ae/</a> I'm trying to perform SEO on it and for this I need to set alt attribute for each image. Even I have given it in media but instead, it is not showing when I look it in inspect element or view source. I have found an article related to this <a href="https://wordpress.stackexchange.com/questions/253743/alt-title-tags-not-showing">alt, title tags not showing</a> but it did not help me as its answer was specific to the theme. I'm using Food &amp; Cook theme for my website <a href="http://dahz.daffyhazan.com/food-cook/" rel="nofollow noreferrer">http://dahz.daffyhazan.com/food-cook/</a>. Can anyone help me please.</p>
[ { "answer_id": 280542, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>Looking at the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters\" rel=\"nofollow noreferrer\">pagination parameters</a> I see two possibilities: Either use <code>offset</code> or <code>paged</code>.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'offset' =&gt; 10,\n);\n</code></pre>\n\n<p>should work just as well as</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; 2,\n);\n</code></pre>\n" }, { "answer_id": 280557, "author": "Siyah", "author_id": 62192, "author_profile": "https://wordpress.stackexchange.com/users/62192", "pm_score": 2, "selected": false, "text": "<p>I solved it myself. What I did, is adding this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$loop = new WP_Query(array(\n 'offset' =&gt; 20, \n));\n</code></pre>\n<p>And then changing:</p>\n<pre><code>if (have_posts()) : while (have_posts()) : the_post();\n</code></pre>\n<p>into:</p>\n<pre><code>if ($loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n</code></pre>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280546", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128233/" ]
Here is my website <http://www.taramesh.ae/> I'm trying to perform SEO on it and for this I need to set alt attribute for each image. Even I have given it in media but instead, it is not showing when I look it in inspect element or view source. I have found an article related to this [alt, title tags not showing](https://wordpress.stackexchange.com/questions/253743/alt-title-tags-not-showing) but it did not help me as its answer was specific to the theme. I'm using Food & Cook theme for my website <http://dahz.daffyhazan.com/food-cook/>. Can anyone help me please.
I solved it myself. What I did, is adding this: ```php $loop = new WP_Query(array( 'offset' => 20, )); ``` And then changing: ``` if (have_posts()) : while (have_posts()) : the_post(); ``` into: ``` if ($loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ```
280,554
<p>I want to import existing users with their passwords from an old WordPress site to a new one. The new WordPress installation has also existing users. Therefore I couldn't simply export/import the database tables from the old site.</p> <p>Is there any other way to import the old users with passwords to the new site?</p>
[ { "answer_id": 280542, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>Looking at the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters\" rel=\"nofollow noreferrer\">pagination parameters</a> I see two possibilities: Either use <code>offset</code> or <code>paged</code>.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'offset' =&gt; 10,\n);\n</code></pre>\n\n<p>should work just as well as</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; 2,\n);\n</code></pre>\n" }, { "answer_id": 280557, "author": "Siyah", "author_id": 62192, "author_profile": "https://wordpress.stackexchange.com/users/62192", "pm_score": 2, "selected": false, "text": "<p>I solved it myself. What I did, is adding this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$loop = new WP_Query(array(\n 'offset' =&gt; 20, \n));\n</code></pre>\n<p>And then changing:</p>\n<pre><code>if (have_posts()) : while (have_posts()) : the_post();\n</code></pre>\n<p>into:</p>\n<pre><code>if ($loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n</code></pre>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96806/" ]
I want to import existing users with their passwords from an old WordPress site to a new one. The new WordPress installation has also existing users. Therefore I couldn't simply export/import the database tables from the old site. Is there any other way to import the old users with passwords to the new site?
I solved it myself. What I did, is adding this: ```php $loop = new WP_Query(array( 'offset' => 20, )); ``` And then changing: ``` if (have_posts()) : while (have_posts()) : the_post(); ``` into: ``` if ($loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ```
280,566
<p>If you want to escape string values in an SQL query, you can use WordPress's <a href="https://developer.wordpress.org/reference/functions/esc_sql/" rel="nofollow noreferrer"><code>esc_sql</code></a> function:</p> <pre><code>&lt;?php $wpdb-&gt;get_var( "SELECT * FROM something WHERE foo = '" . esc_sql( $foo ) . "'" ); </code></pre> <p>You can also use the much more convenient <a href="https://developer.wordpress.org/reference/classes/wpdb/prepare/" rel="nofollow noreferrer"><code>prepare</code></a> function like this:</p> <pre><code>&lt;?php $wpdb&gt;-get_var( $wpdb-&gt;prepare( "SELECT * FROM something WHERE foo = %s", $foo ) ); </code></pre> <p>However, <code>esc_sql</code> is not suitable for escaping table names or column names, (only string values). And there is no way to use <code>prepare</code> for escaping table names or column names.</p> <p>How can I escape <code>$foo</code> and <code>$bar</code> properly in this example SQL query?</p> <pre><code>SELECT * FROM $foo WHERE $bar = "example"; </code></pre>
[ { "answer_id": 280583, "author": "Flimm", "author_id": 122391, "author_profile": "https://wordpress.stackexchange.com/users/122391", "pm_score": 3, "selected": true, "text": "<p>I can't find a function shipped with WordPress that does this, so I created my own:</p>\n\n<pre><code> function esc_sql_name( $name ) {\n return str_replace( \"`\", \"``\", $name );\n }\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code> $escaped_name = esc_sql_name( $column_name );\n\n $sql = $wpdb-&gt;prepare(\n \"SELECT * FROM example WHERE `$escaped_name` = %s\",\n $foobar\n );\n</code></pre>\n\n<h2>Reference:</h2>\n\n<ul>\n<li><a href=\"https://dev.mysql.com/doc/refman/5.7/en/identifiers.html\" rel=\"nofollow noreferrer\">MySQL documentation on identifiers</a></li>\n</ul>\n" }, { "answer_id": 377605, "author": "JonShipman", "author_id": 121885, "author_profile": "https://wordpress.stackexchange.com/users/121885", "pm_score": 1, "selected": false, "text": "<p>Use the function <code>sanitize_key</code></p>\n<p>See the developer docs here: <a href=\"https://developer.wordpress.org/reference/functions/sanitize_key/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/sanitize_key/</a></p>\n<p>Note: it does perform a strtolower as WordPress Core Standards do require lowercase column names.</p>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280566", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122391/" ]
If you want to escape string values in an SQL query, you can use WordPress's [`esc_sql`](https://developer.wordpress.org/reference/functions/esc_sql/) function: ``` <?php $wpdb->get_var( "SELECT * FROM something WHERE foo = '" . esc_sql( $foo ) . "'" ); ``` You can also use the much more convenient [`prepare`](https://developer.wordpress.org/reference/classes/wpdb/prepare/) function like this: ``` <?php $wpdb>-get_var( $wpdb->prepare( "SELECT * FROM something WHERE foo = %s", $foo ) ); ``` However, `esc_sql` is not suitable for escaping table names or column names, (only string values). And there is no way to use `prepare` for escaping table names or column names. How can I escape `$foo` and `$bar` properly in this example SQL query? ``` SELECT * FROM $foo WHERE $bar = "example"; ```
I can't find a function shipped with WordPress that does this, so I created my own: ``` function esc_sql_name( $name ) { return str_replace( "`", "``", $name ); } ``` You can use it like this: ``` $escaped_name = esc_sql_name( $column_name ); $sql = $wpdb->prepare( "SELECT * FROM example WHERE `$escaped_name` = %s", $foobar ); ``` Reference: ---------- * [MySQL documentation on identifiers](https://dev.mysql.com/doc/refman/5.7/en/identifiers.html)
280,604
<p>My site was first built with html/css in 2000, and when I rebuilt it with WordPress in 2012, I kept the .html extension in the interest of keeping the same URLs. I'd like to get rid of it now and redirect the old html pages to the new extension-less pages.</p> <p>My current permalink structure is: /%category%/%postname%.html</p> <p>I'd like it to be: /%category%/%postname%</p> <p>To do that, I tried deleting ".html' from the end of the permalink structure, then saving permalinks. Then, I put this in my .htaccess:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html </code></pre> <p>But it doesn't work -- pages just give me 404 errors that way. </p> <p>I took a look at the Yoast permalink redirection tool, but that only redirects to /%postname% -- I'm not sure if it's possible to modify the outputted rule to add the category before the postname. </p>
[ { "answer_id": 280583, "author": "Flimm", "author_id": 122391, "author_profile": "https://wordpress.stackexchange.com/users/122391", "pm_score": 3, "selected": true, "text": "<p>I can't find a function shipped with WordPress that does this, so I created my own:</p>\n\n<pre><code> function esc_sql_name( $name ) {\n return str_replace( \"`\", \"``\", $name );\n }\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code> $escaped_name = esc_sql_name( $column_name );\n\n $sql = $wpdb-&gt;prepare(\n \"SELECT * FROM example WHERE `$escaped_name` = %s\",\n $foobar\n );\n</code></pre>\n\n<h2>Reference:</h2>\n\n<ul>\n<li><a href=\"https://dev.mysql.com/doc/refman/5.7/en/identifiers.html\" rel=\"nofollow noreferrer\">MySQL documentation on identifiers</a></li>\n</ul>\n" }, { "answer_id": 377605, "author": "JonShipman", "author_id": 121885, "author_profile": "https://wordpress.stackexchange.com/users/121885", "pm_score": 1, "selected": false, "text": "<p>Use the function <code>sanitize_key</code></p>\n<p>See the developer docs here: <a href=\"https://developer.wordpress.org/reference/functions/sanitize_key/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/sanitize_key/</a></p>\n<p>Note: it does perform a strtolower as WordPress Core Standards do require lowercase column names.</p>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280604", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128267/" ]
My site was first built with html/css in 2000, and when I rebuilt it with WordPress in 2012, I kept the .html extension in the interest of keeping the same URLs. I'd like to get rid of it now and redirect the old html pages to the new extension-less pages. My current permalink structure is: /%category%/%postname%.html I'd like it to be: /%category%/%postname% To do that, I tried deleting ".html' from the end of the permalink structure, then saving permalinks. Then, I put this in my .htaccess: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html ``` But it doesn't work -- pages just give me 404 errors that way. I took a look at the Yoast permalink redirection tool, but that only redirects to /%postname% -- I'm not sure if it's possible to modify the outputted rule to add the category before the postname.
I can't find a function shipped with WordPress that does this, so I created my own: ``` function esc_sql_name( $name ) { return str_replace( "`", "``", $name ); } ``` You can use it like this: ``` $escaped_name = esc_sql_name( $column_name ); $sql = $wpdb->prepare( "SELECT * FROM example WHERE `$escaped_name` = %s", $foobar ); ``` Reference: ---------- * [MySQL documentation on identifiers](https://dev.mysql.com/doc/refman/5.7/en/identifiers.html)
280,615
<p>I saw this question on another post but was unable to add an answer because my reputation is too low. So I thought I would create a new thread. </p> <ul> <li>So I migrated a website from a draft server to a live server. <ul> <li>I copied the website folder from the draft server and pasted into the live server.</li> <li>I copied the website database, created a new database in mysql in the live server, and pasted the copied database in the new database folder in phpmyadmin</li> <li>I updated the website address from the draft url to the live url in the wp_options folder in phpmyadmin.</li> <li>I updated the two siteurls in the config.php file in cpanel file manager</li> </ul></li> </ul> <p>After all this was done I found that only the website homepage was working and none of the links were working. So I went to wp-admin > Settings > Permalinks and selected save changes. And.. The problem was still happening (only homepage working). Answer is in the answer section.</p>
[ { "answer_id": 280616, "author": "Justin Young", "author_id": 114859, "author_profile": "https://wordpress.stackexchange.com/users/114859", "pm_score": -1, "selected": false, "text": "<p>This was the solution</p>\n\n<ul>\n<li>Go ftp or file manager\n\n<ul>\n<li>find the .htaccess file</li>\n</ul></li>\n</ul>\n\n<p><strong>Next: Change the code inside file (Look for RewriteBase line)</strong></p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase / (\"this line should be only a slash after RewriteBase - remove anything else\")\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>This should solve the problem.\n- Justin</p>\n" }, { "answer_id": 280624, "author": "LEXmono", "author_id": 128060, "author_profile": "https://wordpress.stackexchange.com/users/128060", "pm_score": 0, "selected": false, "text": "<p>For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. </p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2017/09/20
[ "https://wordpress.stackexchange.com/questions/280615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114859/" ]
I saw this question on another post but was unable to add an answer because my reputation is too low. So I thought I would create a new thread. * So I migrated a website from a draft server to a live server. + I copied the website folder from the draft server and pasted into the live server. + I copied the website database, created a new database in mysql in the live server, and pasted the copied database in the new database folder in phpmyadmin + I updated the website address from the draft url to the live url in the wp\_options folder in phpmyadmin. + I updated the two siteurls in the config.php file in cpanel file manager After all this was done I found that only the website homepage was working and none of the links were working. So I went to wp-admin > Settings > Permalinks and selected save changes. And.. The problem was still happening (only homepage working). Answer is in the answer section.
For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
280,633
<p>I want my posts to be limited to number characters. I want this to happen on the page that shows all my posts. I am using this snippet. The read more link also appears when you are viewing the single post. I only want this to happen on the multi post view</p> <p><a href="https://i.stack.imgur.com/vcIun.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vcIun.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/j2KzH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j2KzH.png" alt="enter image description here"></a></p> <pre><code>//for index.php that calls content add_filter("the_content", "break_text"); function break_text($text){ $length = 500; if(strlen($text)&lt;$length+10) return $text;//don't cut if too short $break_pos = strpos($text, ' ', $length);//find next space after desired length $visible = substr($text, 0, $break_pos); return balanceTags($visible) . "&lt;a href='".get_permalink()."'&gt;read more&lt;/a&gt; "; } </code></pre>
[ { "answer_id": 280616, "author": "Justin Young", "author_id": 114859, "author_profile": "https://wordpress.stackexchange.com/users/114859", "pm_score": -1, "selected": false, "text": "<p>This was the solution</p>\n\n<ul>\n<li>Go ftp or file manager\n\n<ul>\n<li>find the .htaccess file</li>\n</ul></li>\n</ul>\n\n<p><strong>Next: Change the code inside file (Look for RewriteBase line)</strong></p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase / (\"this line should be only a slash after RewriteBase - remove anything else\")\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>This should solve the problem.\n- Justin</p>\n" }, { "answer_id": 280624, "author": "LEXmono", "author_id": 128060, "author_profile": "https://wordpress.stackexchange.com/users/128060", "pm_score": 0, "selected": false, "text": "<p>For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. </p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2017/09/21
[ "https://wordpress.stackexchange.com/questions/280633", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128284/" ]
I want my posts to be limited to number characters. I want this to happen on the page that shows all my posts. I am using this snippet. The read more link also appears when you are viewing the single post. I only want this to happen on the multi post view [![enter image description here](https://i.stack.imgur.com/vcIun.png)](https://i.stack.imgur.com/vcIun.png) [![enter image description here](https://i.stack.imgur.com/j2KzH.png)](https://i.stack.imgur.com/j2KzH.png) ``` //for index.php that calls content add_filter("the_content", "break_text"); function break_text($text){ $length = 500; if(strlen($text)<$length+10) return $text;//don't cut if too short $break_pos = strpos($text, ' ', $length);//find next space after desired length $visible = substr($text, 0, $break_pos); return balanceTags($visible) . "<a href='".get_permalink()."'>read more</a> "; } ```
For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
280,649
<p>I have 2 WordPress shortcodes I am working on:</p> <ol> <li>A Chapter. [chapter name="the begining"]...content...[/chapter]</li> <li>A table of contents [toc][/toc]. The toc needs to display a simple list of the chapters.</li> </ol> <p>Specification:</p> <ul> <li>There can be many chapters in a post. </li> <li>There can be one, two or no toc shortcode in a post. </li> <li>The toc can be either before or after the chapters or both before and after. It is up to the post writer so I don't know in advance. </li> <li>I cannot use nested shortcodes as those are difficult for writers to work with.</li> </ul> <p>I thought of using a static toc array to add chapters at each chapter tag and then output it in the toc shortcode. Alas, the toc shortcode can appear BEFORE the chapters and then the array will be empty.</p> <p>The following post html will not show the toc:</p> <pre><code>[toc][/toc] Here is some content [chapter name="hello"]xxx[/chapter] In between content may come here [chapter name="world"]yyy[/chapter] Some more stuff </code></pre> <p>This is my starting code (embeded in a class):</p> <pre><code>public static function register_chapter_shortcode($atts, $content=null){ $atts = shortcode_atts ( array ( 'name' =&gt; '', ), $atts ); $name = $atts["name"]; if (self::$toc == null){ self::$toc = array ($name); } else { array_push(self::$toc, $name); } return ' &lt;h2&gt;'.$atts["name"].'&lt;/h2&gt; &lt;div&gt;'.do_shortcode($content).'&lt;/div&gt;' ; } public static function register_toc_shortcode($atts, $content=null){ $items = ""; foreach (self::$toc as $item){ $items = $items. '&lt;li&gt;&lt;a href="#"&gt;'.$item.'&lt;/a&gt;&lt;/li&gt;'; } return ' &lt;ul&gt;'.$items.'&lt;/ul&gt; '; } </code></pre>
[ { "answer_id": 280616, "author": "Justin Young", "author_id": 114859, "author_profile": "https://wordpress.stackexchange.com/users/114859", "pm_score": -1, "selected": false, "text": "<p>This was the solution</p>\n\n<ul>\n<li>Go ftp or file manager\n\n<ul>\n<li>find the .htaccess file</li>\n</ul></li>\n</ul>\n\n<p><strong>Next: Change the code inside file (Look for RewriteBase line)</strong></p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase / (\"this line should be only a slash after RewriteBase - remove anything else\")\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>This should solve the problem.\n- Justin</p>\n" }, { "answer_id": 280624, "author": "LEXmono", "author_id": 128060, "author_profile": "https://wordpress.stackexchange.com/users/128060", "pm_score": 0, "selected": false, "text": "<p>For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. </p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2017/09/21
[ "https://wordpress.stackexchange.com/questions/280649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123681/" ]
I have 2 WordPress shortcodes I am working on: 1. A Chapter. [chapter name="the begining"]...content...[/chapter] 2. A table of contents [toc][/toc]. The toc needs to display a simple list of the chapters. Specification: * There can be many chapters in a post. * There can be one, two or no toc shortcode in a post. * The toc can be either before or after the chapters or both before and after. It is up to the post writer so I don't know in advance. * I cannot use nested shortcodes as those are difficult for writers to work with. I thought of using a static toc array to add chapters at each chapter tag and then output it in the toc shortcode. Alas, the toc shortcode can appear BEFORE the chapters and then the array will be empty. The following post html will not show the toc: ``` [toc][/toc] Here is some content [chapter name="hello"]xxx[/chapter] In between content may come here [chapter name="world"]yyy[/chapter] Some more stuff ``` This is my starting code (embeded in a class): ``` public static function register_chapter_shortcode($atts, $content=null){ $atts = shortcode_atts ( array ( 'name' => '', ), $atts ); $name = $atts["name"]; if (self::$toc == null){ self::$toc = array ($name); } else { array_push(self::$toc, $name); } return ' <h2>'.$atts["name"].'</h2> <div>'.do_shortcode($content).'</div>' ; } public static function register_toc_shortcode($atts, $content=null){ $items = ""; foreach (self::$toc as $item){ $items = $items. '<li><a href="#">'.$item.'</a></li>'; } return ' <ul>'.$items.'</ul> '; } ```
For those who may come along: In addition to your proposed answer, you can use the .htaccess file in your web root directory. These often get missed as they are hidden files on linux systems. You can check and make sure that was copied over, or make a new file and paste the rewrite rules into that. Here is an example of mine. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
280,660
<pre><code>&lt;?php /** * Template Name: Custom Page Template */ get_header(); if(is_user_logged_in()){ // content for login user } else { // https://developer.wordpress.org/reference/functions/wp_redirect/ // wp_redirect() does not validate that the $location is a reference to the current host // That means this function is vulnerable to open redirects if you pass it a $location supplied by the user. // So use it only when navigating to another website wp_safe_redirect('/wp-login.php'); exit; } ?&gt; </code></pre>
[ { "answer_id": 280665, "author": "Wh0CaREs", "author_id": 123614, "author_profile": "https://wordpress.stackexchange.com/users/123614", "pm_score": 0, "selected": false, "text": "<p>As I know you can use wp_redirect before content is sent to the browser. You should use hooks for that.</p>\n\n<p>But you can use PHP header function</p>\n\n<pre><code>if ( TRUE ) {\nheader( \"Location: \" . home_url() );\ndie();\n}\n</code></pre>\n\n<p>But I am not 100% sure is this header(Location) gonna make you problem with \"headers already sent\"</p>\n" }, { "answer_id": 280667, "author": "Dev02ali", "author_id": 109633, "author_profile": "https://wordpress.stackexchange.com/users/109633", "pm_score": 0, "selected": false, "text": "<p>try this code,</p>\n\n<pre><code>get_header();\nglobal $current_user;\nget_currentuserinfo();\n\nif(is_user_logged_in()){\n // content for login user\n} \nelse {\n$url = 'http://example.com';\nwp_redirect($url);\n exit();\n} \n</code></pre>\n" }, { "answer_id": 280680, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 4, "selected": true, "text": "<p>Redirects are performed by outputting HTTP headers, <code>wp_redirect()</code> just adds some bits on top of it for flexibility.</p>\n\n<p>Headers are only ever meant to be used <em>before any and all output</em> to a page, since that is how HTTP response is structured.</p>\n\n<p>Hypothetically it could work in template <em>if</em> you make sure it fires before any output. Practically it is a normal practice to deal with redirects on an appropriate hook, before any template/output is ever reached. The common hook to use is <code>template_redirect</code>.</p>\n" } ]
2017/09/21
[ "https://wordpress.stackexchange.com/questions/280660", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128293/" ]
``` <?php /** * Template Name: Custom Page Template */ get_header(); if(is_user_logged_in()){ // content for login user } else { // https://developer.wordpress.org/reference/functions/wp_redirect/ // wp_redirect() does not validate that the $location is a reference to the current host // That means this function is vulnerable to open redirects if you pass it a $location supplied by the user. // So use it only when navigating to another website wp_safe_redirect('/wp-login.php'); exit; } ?> ```
Redirects are performed by outputting HTTP headers, `wp_redirect()` just adds some bits on top of it for flexibility. Headers are only ever meant to be used *before any and all output* to a page, since that is how HTTP response is structured. Hypothetically it could work in template *if* you make sure it fires before any output. Practically it is a normal practice to deal with redirects on an appropriate hook, before any template/output is ever reached. The common hook to use is `template_redirect`.
280,693
<p>I have tried a lot but didn't got a proper result. Someone please check my code, where I am doing mistake.</p> <p>I want to show other posts with same categories but not the post shows on single page also previous and next post of the current post. Is there any other way to show?</p> <pre><code>$thisid = get_the_ID(); $prevpost = get_previous_post(); $previd = $prevpost-&gt;ID; $nextpost = get_next_post(); $nextid = $nextpost-&gt;ID; $excludearray = array($previd, $thisid, $nextid); $args = "posts_per_page=4&amp;exclude=$thisid,$previd,$nextid&amp;cat="; $categories = get_the_category(); $i = 1; foreach ($categories as $category) { if ($i == 1) { $args .= $category-&gt;term_id; } else { $args .= "," . $category-&gt;term_id; } $i++; } $query = new WP_Query($args); if ($query-&gt;have_posts()): while ($query-&gt;have_posts()): $query-&gt;the_post(); endwhile; endif; </code></pre> <p>Thanks.</p>
[ { "answer_id": 280695, "author": "Jan Boddez", "author_id": 128111, "author_profile": "https://wordpress.stackexchange.com/users/128111", "pm_score": 2, "selected": false, "text": "<p>Have a look at <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a>, and maybe try passing your args in an array.\nAbove page lists this exact example, which should work:</p>\n\n<pre>// This WILL work\n$exclude_ids = array( 1, 2, 3 );\n$query = new WP_Query( array( 'post__not_in' => $exclude_ids ) );</pre>\n" }, { "answer_id": 280696, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": -1, "selected": false, "text": "<p>You are <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> arguments in <code>WP_Query</code>. Just use <code>get_posts()</code> instead. </p>\n" }, { "answer_id": 280770, "author": "Satrughna Sethy", "author_id": 128317, "author_profile": "https://wordpress.stackexchange.com/users/128317", "pm_score": 0, "selected": false, "text": "<p>Thanks all for guiding me, I just changed the code. Below I am writing my ans.</p>\n\n<pre><code>$thisid = get_the_ID();\n$prevpost = get_previous_post();\n$previd = $prevpost-&gt;ID;\n$nextpost = get_next_post();\n$nextid = $nextpost-&gt;ID;\n$excludearray = array($previd, $thisid, $nextid);\n\n$exclude_ids = array($previd, $thisid, $nextid);\n$args = array(\n \"posts_per_page\" =&gt; 4,\n \"post__not_in\" =&gt; $exclude_ids\n);\n$categories = get_the_category();\n$i = 0;\n$cat = array();\nforeach ($categories as $category) {\n $cat[$i] = $category-&gt;term_id;\n $i++;\n}\n$cats = array(\n \"category\" =&gt; $cat\n);\n$args = array_merge($args, $cats);\n$query = new WP_Query($args);\n\nif ($query-&gt;have_posts()):\n while ($query-&gt;have_posts()):\n $query-&gt;the_post();\n //Some design stuff.\n endwhile;\nendif;\nwp_reset_query();\n</code></pre>\n" } ]
2017/09/21
[ "https://wordpress.stackexchange.com/questions/280693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128317/" ]
I have tried a lot but didn't got a proper result. Someone please check my code, where I am doing mistake. I want to show other posts with same categories but not the post shows on single page also previous and next post of the current post. Is there any other way to show? ``` $thisid = get_the_ID(); $prevpost = get_previous_post(); $previd = $prevpost->ID; $nextpost = get_next_post(); $nextid = $nextpost->ID; $excludearray = array($previd, $thisid, $nextid); $args = "posts_per_page=4&exclude=$thisid,$previd,$nextid&cat="; $categories = get_the_category(); $i = 1; foreach ($categories as $category) { if ($i == 1) { $args .= $category->term_id; } else { $args .= "," . $category->term_id; } $i++; } $query = new WP_Query($args); if ($query->have_posts()): while ($query->have_posts()): $query->the_post(); endwhile; endif; ``` Thanks.
Have a look at <https://codex.wordpress.org/Class_Reference/WP_Query>, and maybe try passing your args in an array. Above page lists this exact example, which should work: ``` // This WILL work $exclude_ids = array( 1, 2, 3 ); $query = new WP_Query( array( 'post__not_in' => $exclude_ids ) ); ```
280,694
<p>I am a newbie with WordPress and I have a little question. I met an issue this morning ("wpdb class was not found") with WordPress and while debugging I find that my wpbg.php file was empty !</p> <p>Here comes my question:</p> <p><strong>Is it possible that WordPress erase the content of a file because the server has no more memory or I need to search somewhere else to understand where the issue came from ?</strong></p> <p>The server hosting the website has no more memory (I am gonna buy more memory) even if to add a little change to the .css ^^</p> <p>Thank you for your interest.</p>
[ { "answer_id": 280695, "author": "Jan Boddez", "author_id": 128111, "author_profile": "https://wordpress.stackexchange.com/users/128111", "pm_score": 2, "selected": false, "text": "<p>Have a look at <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a>, and maybe try passing your args in an array.\nAbove page lists this exact example, which should work:</p>\n\n<pre>// This WILL work\n$exclude_ids = array( 1, 2, 3 );\n$query = new WP_Query( array( 'post__not_in' => $exclude_ids ) );</pre>\n" }, { "answer_id": 280696, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": -1, "selected": false, "text": "<p>You are <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> arguments in <code>WP_Query</code>. Just use <code>get_posts()</code> instead. </p>\n" }, { "answer_id": 280770, "author": "Satrughna Sethy", "author_id": 128317, "author_profile": "https://wordpress.stackexchange.com/users/128317", "pm_score": 0, "selected": false, "text": "<p>Thanks all for guiding me, I just changed the code. Below I am writing my ans.</p>\n\n<pre><code>$thisid = get_the_ID();\n$prevpost = get_previous_post();\n$previd = $prevpost-&gt;ID;\n$nextpost = get_next_post();\n$nextid = $nextpost-&gt;ID;\n$excludearray = array($previd, $thisid, $nextid);\n\n$exclude_ids = array($previd, $thisid, $nextid);\n$args = array(\n \"posts_per_page\" =&gt; 4,\n \"post__not_in\" =&gt; $exclude_ids\n);\n$categories = get_the_category();\n$i = 0;\n$cat = array();\nforeach ($categories as $category) {\n $cat[$i] = $category-&gt;term_id;\n $i++;\n}\n$cats = array(\n \"category\" =&gt; $cat\n);\n$args = array_merge($args, $cats);\n$query = new WP_Query($args);\n\nif ($query-&gt;have_posts()):\n while ($query-&gt;have_posts()):\n $query-&gt;the_post();\n //Some design stuff.\n endwhile;\nendif;\nwp_reset_query();\n</code></pre>\n" } ]
2017/09/21
[ "https://wordpress.stackexchange.com/questions/280694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128314/" ]
I am a newbie with WordPress and I have a little question. I met an issue this morning ("wpdb class was not found") with WordPress and while debugging I find that my wpbg.php file was empty ! Here comes my question: **Is it possible that WordPress erase the content of a file because the server has no more memory or I need to search somewhere else to understand where the issue came from ?** The server hosting the website has no more memory (I am gonna buy more memory) even if to add a little change to the .css ^^ Thank you for your interest.
Have a look at <https://codex.wordpress.org/Class_Reference/WP_Query>, and maybe try passing your args in an array. Above page lists this exact example, which should work: ``` // This WILL work $exclude_ids = array( 1, 2, 3 ); $query = new WP_Query( array( 'post__not_in' => $exclude_ids ) ); ```
280,747
<p>I'm really new to php and I'm trying to get an image set using advanced custom fields on my front end. I've looked at the docs and forums but I can't get the url. All the code works but for the image. I expect the url value to show up but instead I get a blank value. I know I need to get the taxonomy ID, I must be missing something.</p> <p>Here is an image of my ACF settings: <a href="https://puu.sh/xFI3Y/23bea86ecf.png" rel="nofollow noreferrer">https://puu.sh/xFI3Y/23bea86ecf.png</a></p> <p>And it's rules: <a href="https://puu.sh/xFI5N/2865cecc5a.png" rel="nofollow noreferrer">https://puu.sh/xFI5N/2865cecc5a.png</a></p> <pre><code>&lt;?php // get all the categories from the database $cats = get_categories(); // loop through the categories foreach ($cats as $cat) { // setup the category ID $cat_id= $cat-&gt;term_id; ?&gt; &lt;div style="background: url( &lt;?php the_field('category-image', 'term_'. $cat_id); ?&gt; );"&gt;&lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>Thanks for any advice in advance.</p>
[ { "answer_id": 280751, "author": "roychri", "author_id": 128349, "author_profile": "https://wordpress.stackexchange.com/users/128349", "pm_score": 2, "selected": true, "text": "<p>Make sure you are using version 5.5.0 or newer since only that version support the format</p>\n\n<pre><code>'term_' . $id\n</code></pre>\n\n<p>Try passing <code>$cat</code> as the second parameter to <code>the_field()</code>.</p>\n" }, { "answer_id": 280754, "author": "Draxy", "author_id": 128346, "author_profile": "https://wordpress.stackexchange.com/users/128346", "pm_score": 0, "selected": false, "text": "<p>Fixed with this code:</p>\n\n<pre><code>$cat_image = get_field('category_image', $cat);\necho \"&lt;div class='catalog-category'&gt;\n&lt;h2 class='category-title'&gt;\".$cat-&gt;name.\"&lt;/h2&gt;\";?&gt; \n&lt;div class=\"category-image\" style=\"background: url( &lt;?= $cat_image ?&gt; );&lt;/div&gt;\n</code></pre>\n\n<p>Thanks for the help! Sorry for the noob question.</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128346/" ]
I'm really new to php and I'm trying to get an image set using advanced custom fields on my front end. I've looked at the docs and forums but I can't get the url. All the code works but for the image. I expect the url value to show up but instead I get a blank value. I know I need to get the taxonomy ID, I must be missing something. Here is an image of my ACF settings: <https://puu.sh/xFI3Y/23bea86ecf.png> And it's rules: <https://puu.sh/xFI5N/2865cecc5a.png> ``` <?php // get all the categories from the database $cats = get_categories(); // loop through the categories foreach ($cats as $cat) { // setup the category ID $cat_id= $cat->term_id; ?> <div style="background: url( <?php the_field('category-image', 'term_'. $cat_id); ?> );"></div> <?php } ?> ``` Thanks for any advice in advance.
Make sure you are using version 5.5.0 or newer since only that version support the format ``` 'term_' . $id ``` Try passing `$cat` as the second parameter to `the_field()`.
280,782
<p>I have a registration form where i am trying to register new members. I am trying to pass both the formdata for image upload and ajax action in wordpress. Currently i am trying to print the values in console. But the ajax function is not at all called as action is not working. How can i do that. Please help me.</p> <p><strong>HTML</strong></p> <pre><code>&lt;form id="landlordregform" method="post" action="" enctype="multipart/form-data" novalidate="novalidate"&gt; &lt;div class="registrationformbox landloardregformbox"&gt; &lt;div id="custommsg"&gt;&lt;/div&gt; &lt;table width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="username" placeholder="USERNAME*" id="username" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="password" name="password" placeholder="PASSWORD*" id="password" class="valid validate-equalTo-blur" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="password" name="confirmpassword" placeholder="CONFIRM PASSWORD*" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="name" placeholder="NAME*" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="email" placeholder="EMAIL*" id="email" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="telephone" placeholder="TELEPHONE*" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="town_city" placeholder="TOWN/CITY*" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="postcode" placeholder="POST CODE*" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="file" name="profilepic" class="valid" aria-invalid="false"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;textarea name="address" placeholder="ADDRESS*" class="valid" aria-invalid="false"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="submitubttonbox"&gt;&lt;button type="button" name="landlordregisterbutton" id="landlordregisterbutton" class="qbutton white big_large"&gt;Register&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>jQuery("#landlordregisterbutton").click(function(){ if(jQuery("#landlordregform").valid()){ var formData=new FormData(document.getElementById('landlordregform')); //formData.append( 'file', input.files[0] ); jQuery.ajax({ url: jQuery("#cusajaxurl").val(), type: 'POST', data: formData + '&amp;action=custom_landlord_registration_process', cache: false, processData: false, contentType: false, success: function(data) { console.log(data); } }); } }); </code></pre> <p><strong>Functions</strong></p> <pre><code>add_action('wp_ajax_nopriv_custom_landlord_registration_process','custom_landlord_registration_process'); add_action('wp_ajax_custom_landlord_registration_process','custom_landlord_registration_process'); function custom_landlord_registration_process(){ //$formdata=array(); //parse_str($_POST['formdata'],$formdata); print_r($_POST); die(); } </code></pre>
[ { "answer_id": 280784, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>try to add the action in the formdata : </p>\n\n<pre><code> var formData=new FormData(document.getElementById('landlordregform')); \n\n formData.append(\"action\", \"custom_landlord_registration_process\"); \n\n jQuery.ajax({\n url: jQuery(\"#cusajaxurl\").val(),\n type: 'POST',\n data: formData, \n cache: false,\n processData: false, \n contentType: false, \n success: function(data) {\n console.log(data);\n }\n });\n</code></pre>\n" }, { "answer_id": 280785, "author": "Annapurna", "author_id": 98322, "author_profile": "https://wordpress.stackexchange.com/users/98322", "pm_score": 1, "selected": false, "text": "<p>you can send any number of data in data in array this way : </p>\n\n<pre><code>jQuery.ajax({\n url: jQuery(\"#cusajaxurl\").val(),\n type: 'POST',\n data: {\n 'action' : 'custom_landlord_registration_process',\n 'form_data' : formData,\n },\n cache: false,\n processData: false, \n contentType: false, \n success: function(data) {\n console.log(data);\n }\n });\n</code></pre>\n\n<p>and then access formData in php file as $_POST['form_data'].</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280782", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128368/" ]
I have a registration form where i am trying to register new members. I am trying to pass both the formdata for image upload and ajax action in wordpress. Currently i am trying to print the values in console. But the ajax function is not at all called as action is not working. How can i do that. Please help me. **HTML** ``` <form id="landlordregform" method="post" action="" enctype="multipart/form-data" novalidate="novalidate"> <div class="registrationformbox landloardregformbox"> <div id="custommsg"></div> <table width="100%"> <tbody> <tr> <td><input type="text" name="username" placeholder="USERNAME*" id="username" class="valid" aria-invalid="false"></td> <td><input type="password" name="password" placeholder="PASSWORD*" id="password" class="valid validate-equalTo-blur" aria-invalid="false"></td> <td><input type="password" name="confirmpassword" placeholder="CONFIRM PASSWORD*" class="valid" aria-invalid="false"></td> </tr> <tr> <td><input type="text" name="name" placeholder="NAME*" class="valid" aria-invalid="false"></td> <td><input type="text" name="email" placeholder="EMAIL*" id="email" class="valid" aria-invalid="false"></td> <td><input type="text" name="telephone" placeholder="TELEPHONE*" class="valid" aria-invalid="false"></td> </tr> <tr> <td><input type="text" name="town_city" placeholder="TOWN/CITY*" class="valid" aria-invalid="false"></td> <td><input type="text" name="postcode" placeholder="POST CODE*" class="valid" aria-invalid="false"></td> <td><input type="file" name="profilepic" class="valid" aria-invalid="false"></td> </tr> </tbody> </table> <table width="100%"> <tbody> <tr> <td><textarea name="address" placeholder="ADDRESS*" class="valid" aria-invalid="false"></textarea></td> </tr> </tbody> </table> <div class="submitubttonbox"><button type="button" name="landlordregisterbutton" id="landlordregisterbutton" class="qbutton white big_large">Register</button></div> </div> </form> ``` **jQuery** ``` jQuery("#landlordregisterbutton").click(function(){ if(jQuery("#landlordregform").valid()){ var formData=new FormData(document.getElementById('landlordregform')); //formData.append( 'file', input.files[0] ); jQuery.ajax({ url: jQuery("#cusajaxurl").val(), type: 'POST', data: formData + '&action=custom_landlord_registration_process', cache: false, processData: false, contentType: false, success: function(data) { console.log(data); } }); } }); ``` **Functions** ``` add_action('wp_ajax_nopriv_custom_landlord_registration_process','custom_landlord_registration_process'); add_action('wp_ajax_custom_landlord_registration_process','custom_landlord_registration_process'); function custom_landlord_registration_process(){ //$formdata=array(); //parse_str($_POST['formdata'],$formdata); print_r($_POST); die(); } ```
try to add the action in the formdata : ``` var formData=new FormData(document.getElementById('landlordregform')); formData.append("action", "custom_landlord_registration_process"); jQuery.ajax({ url: jQuery("#cusajaxurl").val(), type: 'POST', data: formData, cache: false, processData: false, contentType: false, success: function(data) { console.log(data); } }); ```
280,792
<p>I'm trying to search only by a custom post type in Wordpress. </p> <p>In my search form I have:</p> <pre><code>&lt;input type="hidden" name="post_type" value="customposttype" /&gt; </code></pre> <p>In my functions file I have:</p> <pre><code> function template_chooser($template) { global $wp_query; $post_type = get_query_var('post_type'); if( $wp_query-&gt;is_search &amp;&amp; $post_type == 'customposttype' ) { return locate_template('customposttype-search.php'); } return $template; } add_filter('template_include', 'template_chooser'); </code></pre> <p>This gets me to the right search template. However, I'm still getting ALL WordPress results in the actual search results. Do I need to modify:</p> <pre><code>&lt;?php if( have_posts()){ ?&gt; &lt;?php while( have_posts() ) : the_post(); ?&gt; ... </code></pre> <p>somehow too in my "customposttype-search.php"?</p>
[ { "answer_id": 280784, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>try to add the action in the formdata : </p>\n\n<pre><code> var formData=new FormData(document.getElementById('landlordregform')); \n\n formData.append(\"action\", \"custom_landlord_registration_process\"); \n\n jQuery.ajax({\n url: jQuery(\"#cusajaxurl\").val(),\n type: 'POST',\n data: formData, \n cache: false,\n processData: false, \n contentType: false, \n success: function(data) {\n console.log(data);\n }\n });\n</code></pre>\n" }, { "answer_id": 280785, "author": "Annapurna", "author_id": 98322, "author_profile": "https://wordpress.stackexchange.com/users/98322", "pm_score": 1, "selected": false, "text": "<p>you can send any number of data in data in array this way : </p>\n\n<pre><code>jQuery.ajax({\n url: jQuery(\"#cusajaxurl\").val(),\n type: 'POST',\n data: {\n 'action' : 'custom_landlord_registration_process',\n 'form_data' : formData,\n },\n cache: false,\n processData: false, \n contentType: false, \n success: function(data) {\n console.log(data);\n }\n });\n</code></pre>\n\n<p>and then access formData in php file as $_POST['form_data'].</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121694/" ]
I'm trying to search only by a custom post type in Wordpress. In my search form I have: ``` <input type="hidden" name="post_type" value="customposttype" /> ``` In my functions file I have: ``` function template_chooser($template) { global $wp_query; $post_type = get_query_var('post_type'); if( $wp_query->is_search && $post_type == 'customposttype' ) { return locate_template('customposttype-search.php'); } return $template; } add_filter('template_include', 'template_chooser'); ``` This gets me to the right search template. However, I'm still getting ALL WordPress results in the actual search results. Do I need to modify: ``` <?php if( have_posts()){ ?> <?php while( have_posts() ) : the_post(); ?> ... ``` somehow too in my "customposttype-search.php"?
try to add the action in the formdata : ``` var formData=new FormData(document.getElementById('landlordregform')); formData.append("action", "custom_landlord_registration_process"); jQuery.ajax({ url: jQuery("#cusajaxurl").val(), type: 'POST', data: formData, cache: false, processData: false, contentType: false, success: function(data) { console.log(data); } }); ```
280,796
<p>I would like to apply special styling to the menu items of pages that are children of child pages. Is there a way to do this?</p>
[ { "answer_id": 280798, "author": "Elmar Anthony Furtado Tavares", "author_id": 128314, "author_profile": "https://wordpress.stackexchange.com/users/128314", "pm_score": 1, "selected": false, "text": "<p>You can target your elements with jQuery using these methods:</p>\n\n<p><strong>children()</strong>:<a href=\"https://api.jquery.com/children/\" rel=\"nofollow noreferrer\">https://api.jquery.com/children/</a></p>\n\n<p><em>or</em></p>\n\n<p><strong>find()</strong>: <a href=\"https://api.jquery.com/find/\" rel=\"nofollow noreferrer\">https://api.jquery.com/find/</a></p>\n\n<p>You may have some class you could target like .dropdown-menu or something else.</p>\n" }, { "answer_id": 280801, "author": "Юксел Османов", "author_id": 128373, "author_profile": "https://wordpress.stackexchange.com/users/128373", "pm_score": 2, "selected": false, "text": "<p>If you are looking only for styling you can go something like this:</p>\n\n<pre><code>ul ( main-items ) &gt; ul ( secondary menu ) &gt; ul ( third level menu ).\n</code></pre>\n\n<p>You can provide more information about what exactly you need to style and the context.</p>\n" }, { "answer_id": 280805, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>Add this <code>CSS</code> rule to your stylesheet:</p>\n\n<pre><code>ul.menu ul.sub-menu ul.sub-menu li{\n //special styling here\n}\n</code></pre>\n\n<p>its the default <code>CSS</code> classnaming <code>WordPress</code> use for the menus, you can see how i add it here.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vfxiK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vfxiK.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118284/" ]
I would like to apply special styling to the menu items of pages that are children of child pages. Is there a way to do this?
Add this `CSS` rule to your stylesheet: ``` ul.menu ul.sub-menu ul.sub-menu li{ //special styling here } ``` its the default `CSS` classnaming `WordPress` use for the menus, you can see how i add it here. [![enter image description here](https://i.stack.imgur.com/vfxiK.png)](https://i.stack.imgur.com/vfxiK.png)
280,797
<p>Lets say i need to add custom radio fields ( company or person ) at the top of the form to the billing for. And if the visitor checks person they should pay 21% Tax and they select company that is localated in NL they also should pay 21% tax. Any other case they should be free of tax? Any ideas ?</p> <p>This is what i've tried :</p> <pre><code>add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields'); </code></pre> <p>function custom_woocommerce_billing_fields($fields){</p> <pre><code>$fields['customer_type'] = array( 'label' =&gt; __('Bedrijf', 'woocommerce'), 'placeholder' =&gt; _x('Bedrijf', 'placeholder', 'woocommerce'), 'required' =&gt; false, 'clear' =&gt; false, 'type' =&gt; 'checkbox', 'class' =&gt; array('my-css'), ); $fields['customer_type_personal'] = array( 'label' =&gt; __('Persoonlijke', 'woocommerce'), 'placeholder' =&gt; _x('Persoonlijke', 'placeholder', 'woocommerce'), 'required' =&gt; false, 'clear' =&gt; false, 'type' =&gt; 'checkbox', 'class' =&gt; array('my-css-2'), ); return $fields; </code></pre> <p>}</p>
[ { "answer_id": 280798, "author": "Elmar Anthony Furtado Tavares", "author_id": 128314, "author_profile": "https://wordpress.stackexchange.com/users/128314", "pm_score": 1, "selected": false, "text": "<p>You can target your elements with jQuery using these methods:</p>\n\n<p><strong>children()</strong>:<a href=\"https://api.jquery.com/children/\" rel=\"nofollow noreferrer\">https://api.jquery.com/children/</a></p>\n\n<p><em>or</em></p>\n\n<p><strong>find()</strong>: <a href=\"https://api.jquery.com/find/\" rel=\"nofollow noreferrer\">https://api.jquery.com/find/</a></p>\n\n<p>You may have some class you could target like .dropdown-menu or something else.</p>\n" }, { "answer_id": 280801, "author": "Юксел Османов", "author_id": 128373, "author_profile": "https://wordpress.stackexchange.com/users/128373", "pm_score": 2, "selected": false, "text": "<p>If you are looking only for styling you can go something like this:</p>\n\n<pre><code>ul ( main-items ) &gt; ul ( secondary menu ) &gt; ul ( third level menu ).\n</code></pre>\n\n<p>You can provide more information about what exactly you need to style and the context.</p>\n" }, { "answer_id": 280805, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>Add this <code>CSS</code> rule to your stylesheet:</p>\n\n<pre><code>ul.menu ul.sub-menu ul.sub-menu li{\n //special styling here\n}\n</code></pre>\n\n<p>its the default <code>CSS</code> classnaming <code>WordPress</code> use for the menus, you can see how i add it here.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vfxiK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vfxiK.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280797", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128373/" ]
Lets say i need to add custom radio fields ( company or person ) at the top of the form to the billing for. And if the visitor checks person they should pay 21% Tax and they select company that is localated in NL they also should pay 21% tax. Any other case they should be free of tax? Any ideas ? This is what i've tried : ``` add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields'); ``` function custom\_woocommerce\_billing\_fields($fields){ ``` $fields['customer_type'] = array( 'label' => __('Bedrijf', 'woocommerce'), 'placeholder' => _x('Bedrijf', 'placeholder', 'woocommerce'), 'required' => false, 'clear' => false, 'type' => 'checkbox', 'class' => array('my-css'), ); $fields['customer_type_personal'] = array( 'label' => __('Persoonlijke', 'woocommerce'), 'placeholder' => _x('Persoonlijke', 'placeholder', 'woocommerce'), 'required' => false, 'clear' => false, 'type' => 'checkbox', 'class' => array('my-css-2'), ); return $fields; ``` }
Add this `CSS` rule to your stylesheet: ``` ul.menu ul.sub-menu ul.sub-menu li{ //special styling here } ``` its the default `CSS` classnaming `WordPress` use for the menus, you can see how i add it here. [![enter image description here](https://i.stack.imgur.com/vfxiK.png)](https://i.stack.imgur.com/vfxiK.png)
280,807
<p>I'm trying to add a child theme on a website, I created the folder called mythemename-child, I created the style.css file with this information inside: </p> <pre><code>/* Theme Name: Mizrahi-child Theme URI: http://www.templatemonster.com/wordpress-themes Description: Your theme description. Author: Matteo Schiatti Author URI: http://www.templatemonster.com/ Template: mizrahi Version: 1.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: mizrahi Tags: one-column, two-columns, three-columns, left-sidebar, right-sidebar, custom-background, custom-colors, custom-menu, featured-images, post-formats, sticky-post, theme-options, threaded-comments, translation-ready */ </code></pre> <p>After I created the function.php file with this content:</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } </code></pre> <p>I can see the child theme in the back office but when I activate it the site lose all the css. </p> <p>I can't understand why, I tried also with the @import method on the style.css file but nothing: </p> <p>@import url("../twentyfifteen/style.css");</p> <p>I added this code on my function.php: </p> <pre><code> &lt;?php function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/font-awesome.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/magnific-popup.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/magnific-popup.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/material-icons.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/material-icons.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/slider-pro.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/slider-pro.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/style.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/swiper.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/swiper.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/booked.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/builder.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/restaurant-menu.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/buttons.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/elements.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/footer.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/forms.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/header.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/menus.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/misc.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/navigation.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/post.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/social.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/about.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/custom-post.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/instagram.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/subscribe.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/widget-default.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/rtl.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); </code></pre>
[ { "answer_id": 280798, "author": "Elmar Anthony Furtado Tavares", "author_id": 128314, "author_profile": "https://wordpress.stackexchange.com/users/128314", "pm_score": 1, "selected": false, "text": "<p>You can target your elements with jQuery using these methods:</p>\n\n<p><strong>children()</strong>:<a href=\"https://api.jquery.com/children/\" rel=\"nofollow noreferrer\">https://api.jquery.com/children/</a></p>\n\n<p><em>or</em></p>\n\n<p><strong>find()</strong>: <a href=\"https://api.jquery.com/find/\" rel=\"nofollow noreferrer\">https://api.jquery.com/find/</a></p>\n\n<p>You may have some class you could target like .dropdown-menu or something else.</p>\n" }, { "answer_id": 280801, "author": "Юксел Османов", "author_id": 128373, "author_profile": "https://wordpress.stackexchange.com/users/128373", "pm_score": 2, "selected": false, "text": "<p>If you are looking only for styling you can go something like this:</p>\n\n<pre><code>ul ( main-items ) &gt; ul ( secondary menu ) &gt; ul ( third level menu ).\n</code></pre>\n\n<p>You can provide more information about what exactly you need to style and the context.</p>\n" }, { "answer_id": 280805, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>Add this <code>CSS</code> rule to your stylesheet:</p>\n\n<pre><code>ul.menu ul.sub-menu ul.sub-menu li{\n //special styling here\n}\n</code></pre>\n\n<p>its the default <code>CSS</code> classnaming <code>WordPress</code> use for the menus, you can see how i add it here.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vfxiK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vfxiK.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280807", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107597/" ]
I'm trying to add a child theme on a website, I created the folder called mythemename-child, I created the style.css file with this information inside: ``` /* Theme Name: Mizrahi-child Theme URI: http://www.templatemonster.com/wordpress-themes Description: Your theme description. Author: Matteo Schiatti Author URI: http://www.templatemonster.com/ Template: mizrahi Version: 1.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: mizrahi Tags: one-column, two-columns, three-columns, left-sidebar, right-sidebar, custom-background, custom-colors, custom-menu, featured-images, post-formats, sticky-post, theme-options, threaded-comments, translation-ready */ ``` After I created the function.php file with this content: ``` <?php add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } ``` I can see the child theme in the back office but when I activate it the site lose all the css. I can't understand why, I tried also with the @import method on the style.css file but nothing: @import url("../twentyfifteen/style.css"); I added this code on my function.php: ``` <?php function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/font-awesome.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/magnific-popup.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/magnific-popup.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/material-icons.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/material-icons.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/slider-pro.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/slider-pro.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/style.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/swiper.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/swiper.min.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/booked.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/builder.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/plugins/restaurant-menu.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/buttons.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/elements.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/footer.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/forms.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/header.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/menus.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/misc.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/navigation.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/post.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/site/social.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/about.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/custom-post.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/instagram.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/subscribe.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/assets/css/dynamic/widgets/widget-default.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/rtl.css' ); wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); ```
Add this `CSS` rule to your stylesheet: ``` ul.menu ul.sub-menu ul.sub-menu li{ //special styling here } ``` its the default `CSS` classnaming `WordPress` use for the menus, you can see how i add it here. [![enter image description here](https://i.stack.imgur.com/vfxiK.png)](https://i.stack.imgur.com/vfxiK.png)
280,811
<p>I want to get next and previous posts based on a particular category slugs. For example, some posts might have the "sports" category while another has the "tech" category.</p> <p>I was hoping to plug in a category slug into <code>get_adjacent_post</code> but it doesn't appear that it's working. It looks like it just wants use the slug "category" or maybe custom taxonomies rather than slugs within the "category" taxonomy.</p> <p>Here's an example of what I was trying to do:</p> <pre><code>$adj = get_adjacent_post(true, '', true, 'sports'); </code></pre>
[ { "answer_id": 280812, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>What you call \"slugs\" here is more appropriately called <em>terms</em>. It is a little confusing with native taxonomies because it turns into tautology: individual categories are <em>terms</em> of the category <em>taxonomy</em>.</p>\n\n<p>So <code>sports</code> and <code>tech</code> are terms of native <code>category</code> taxonomy.</p>\n\n<p>The function arguments operate on <em>taxonomy</em> level, not <em>term</em> level. That is you need to provide a taxonomy slug, such as <code>category</code>, and <em>all</em> of the terms in that taxonomy will be considered for a match.</p>\n\n<p>From arguments point of view one of the options here is to use <code>$excluded_terms</code> argument to exclude everything but the one term you want.</p>\n\n<p>Other than that it's pretty low level function, which directly generates a lot of custom SQL. There are abundant filters for manipulating that part of the process, like <code>get_{$adjacent}_post_join</code> and <code>get_{$adjacent}_post_where</code>, but it's not something I would call <em>easily</em> adjustable.</p>\n" }, { "answer_id": 280813, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>According to <a href=\"https://developer.wordpress.org/reference/functions/get_adjacent_post/\" rel=\"nofollow noreferrer\">the documentation for <code>get_adjacent_post()</code></a>, the parameters are:</p>\n\n<blockquote>\n <p><code>$in_same_term</code> (bool) (Optional) Whether post should be in a same\n taxonomy term.<br>\n Default value: <code>false</code></p>\n \n <p><code>$excluded_terms</code> (array|string) (Optional) Array or comma-separated\n list of excluded term IDs.<br>\n Default value: <code>''</code> </p>\n \n <p><code>$previous</code> (bool) (Optional) Whether to retrieve previous post.<br>\n Default value: <code>true</code> </p>\n \n <p><code>$taxonomy</code> (string) (Optional) Taxonomy, if <code>$in_same_term</code>\n is <code>true</code>.<br>\n Default value: <code>'category'</code></p>\n</blockquote>\n\n<p>The <code>$taxonomy</code> parameter is so you can specify which taxonomy (category, tag, or custom taxonomy) you'd like use to select the adjacent post.</p>\n\n<p>So no, it appears you can't specify the taxonomy term (eg, <code>sports</code> or <code>tech</code> in your question).</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57849/" ]
I want to get next and previous posts based on a particular category slugs. For example, some posts might have the "sports" category while another has the "tech" category. I was hoping to plug in a category slug into `get_adjacent_post` but it doesn't appear that it's working. It looks like it just wants use the slug "category" or maybe custom taxonomies rather than slugs within the "category" taxonomy. Here's an example of what I was trying to do: ``` $adj = get_adjacent_post(true, '', true, 'sports'); ```
What you call "slugs" here is more appropriately called *terms*. It is a little confusing with native taxonomies because it turns into tautology: individual categories are *terms* of the category *taxonomy*. So `sports` and `tech` are terms of native `category` taxonomy. The function arguments operate on *taxonomy* level, not *term* level. That is you need to provide a taxonomy slug, such as `category`, and *all* of the terms in that taxonomy will be considered for a match. From arguments point of view one of the options here is to use `$excluded_terms` argument to exclude everything but the one term you want. Other than that it's pretty low level function, which directly generates a lot of custom SQL. There are abundant filters for manipulating that part of the process, like `get_{$adjacent}_post_join` and `get_{$adjacent}_post_where`, but it's not something I would call *easily* adjustable.
280,825
<pre><code>/home/&lt;website&gt;/public_html/wp-content/themes/basic/functions.php </code></pre> <p>At the very end of the file, I have included these 8 lines:</p> <pre><code>// Add Shortcode function custom_shortcode() { return "Hello world."; } add_shortcode( 'test', 'custom_shortcode' ); </code></pre> <p>Doesn't work and I can't figure out why.</p> <p>I am self-hosted running the free Basic theme. I have the following plugins:</p> <ul> <li>Cache Enabler,</li> <li>Disable Emojis,</li> <li>Remove Google Fonts References,</li> <li>UpdraftPlus - Backup/Restore,</li> <li>WP Fastest Cache,</li> <li>WP Statistics.</li> </ul> <p>I've tried various different ways of doing this and have looked up several guides. They all say to do exactly what I'm doing and that it will work, but when I do it it does not work.</p>
[ { "answer_id": 280812, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>What you call \"slugs\" here is more appropriately called <em>terms</em>. It is a little confusing with native taxonomies because it turns into tautology: individual categories are <em>terms</em> of the category <em>taxonomy</em>.</p>\n\n<p>So <code>sports</code> and <code>tech</code> are terms of native <code>category</code> taxonomy.</p>\n\n<p>The function arguments operate on <em>taxonomy</em> level, not <em>term</em> level. That is you need to provide a taxonomy slug, such as <code>category</code>, and <em>all</em> of the terms in that taxonomy will be considered for a match.</p>\n\n<p>From arguments point of view one of the options here is to use <code>$excluded_terms</code> argument to exclude everything but the one term you want.</p>\n\n<p>Other than that it's pretty low level function, which directly generates a lot of custom SQL. There are abundant filters for manipulating that part of the process, like <code>get_{$adjacent}_post_join</code> and <code>get_{$adjacent}_post_where</code>, but it's not something I would call <em>easily</em> adjustable.</p>\n" }, { "answer_id": 280813, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>According to <a href=\"https://developer.wordpress.org/reference/functions/get_adjacent_post/\" rel=\"nofollow noreferrer\">the documentation for <code>get_adjacent_post()</code></a>, the parameters are:</p>\n\n<blockquote>\n <p><code>$in_same_term</code> (bool) (Optional) Whether post should be in a same\n taxonomy term.<br>\n Default value: <code>false</code></p>\n \n <p><code>$excluded_terms</code> (array|string) (Optional) Array or comma-separated\n list of excluded term IDs.<br>\n Default value: <code>''</code> </p>\n \n <p><code>$previous</code> (bool) (Optional) Whether to retrieve previous post.<br>\n Default value: <code>true</code> </p>\n \n <p><code>$taxonomy</code> (string) (Optional) Taxonomy, if <code>$in_same_term</code>\n is <code>true</code>.<br>\n Default value: <code>'category'</code></p>\n</blockquote>\n\n<p>The <code>$taxonomy</code> parameter is so you can specify which taxonomy (category, tag, or custom taxonomy) you'd like use to select the adjacent post.</p>\n\n<p>So no, it appears you can't specify the taxonomy term (eg, <code>sports</code> or <code>tech</code> in your question).</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128333/" ]
``` /home/<website>/public_html/wp-content/themes/basic/functions.php ``` At the very end of the file, I have included these 8 lines: ``` // Add Shortcode function custom_shortcode() { return "Hello world."; } add_shortcode( 'test', 'custom_shortcode' ); ``` Doesn't work and I can't figure out why. I am self-hosted running the free Basic theme. I have the following plugins: * Cache Enabler, * Disable Emojis, * Remove Google Fonts References, * UpdraftPlus - Backup/Restore, * WP Fastest Cache, * WP Statistics. I've tried various different ways of doing this and have looked up several guides. They all say to do exactly what I'm doing and that it will work, but when I do it it does not work.
What you call "slugs" here is more appropriately called *terms*. It is a little confusing with native taxonomies because it turns into tautology: individual categories are *terms* of the category *taxonomy*. So `sports` and `tech` are terms of native `category` taxonomy. The function arguments operate on *taxonomy* level, not *term* level. That is you need to provide a taxonomy slug, such as `category`, and *all* of the terms in that taxonomy will be considered for a match. From arguments point of view one of the options here is to use `$excluded_terms` argument to exclude everything but the one term you want. Other than that it's pretty low level function, which directly generates a lot of custom SQL. There are abundant filters for manipulating that part of the process, like `get_{$adjacent}_post_join` and `get_{$adjacent}_post_where`, but it's not something I would call *easily* adjustable.
280,836
<p>I have many hundreds of post which start with 'Post' and then a hyphen - </p> <p>Some of these post have some other unimportant text before it, usually post summaries. What comes after the hyphen is the body of the post that I want to retain.</p> <p>My objective is to have a solution that (ideally) automatically finds 'Post' at the beginning of the posts and then deletes all the text/everything that comes before it, including the word Post WITH the hyphen. So what remains will be the main post.</p> <p>I have no idea how to approach this (very new to WP development).</p>
[ { "answer_id": 280855, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 1, "selected": false, "text": "<p>Note that this filter function, added to the theme functions.php file, will apply to all output that uses \"the_content\" everywhere (all posts essentially) - so exercise or consider narrowing the scope.</p>\n\n<p>For instance, you might want to limit it to the first 100 characters, or to posts before a certain date, or within a certain category before a certain date, etc., otherwise someday someone may happen to use the same sequence of characters and be shocked to find that everything up to them has apparently been deleted.</p>\n\n<pre><code>/**\n * Filter all posts to remove 'Post - ' \n * and all characters preceding it \n * from all posts\n**/\nadd_filter( 'the_content', 'get_rid_of_text_to_post_dash' );\n\nfunction get_rid_of_text_to_post_dash( $content ) { \n\n $key_string = 'Post - ';\n $new_content = ( strpos( $content, $key_string ) ) ? \n substr( $content, strpos( $content, $key_string) + 7 ) : \n $content;\n\n return $new_content;\n\n}\n</code></pre>\n" }, { "answer_id": 280903, "author": "SEO DEVS", "author_id": 111163, "author_profile": "https://wordpress.stackexchange.com/users/111163", "pm_score": 0, "selected": false, "text": "<p>To save using extra filters it is best to completely remove the text. To do this open the websites database in phpmyadmin select all and download. once on a local machine open in notepad and do ctrl + h this allows you to find and replace just use this to remove all the unwanted text. once complete save it then go back to phpmyadmin to import the edited .sql database file. You will need to delete the tables in your database before you can import so make sure to download another copy of your database as a backup.</p>\n\n<p>Hope this helps</p>\n" } ]
2017/09/22
[ "https://wordpress.stackexchange.com/questions/280836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121633/" ]
I have many hundreds of post which start with 'Post' and then a hyphen - Some of these post have some other unimportant text before it, usually post summaries. What comes after the hyphen is the body of the post that I want to retain. My objective is to have a solution that (ideally) automatically finds 'Post' at the beginning of the posts and then deletes all the text/everything that comes before it, including the word Post WITH the hyphen. So what remains will be the main post. I have no idea how to approach this (very new to WP development).
Note that this filter function, added to the theme functions.php file, will apply to all output that uses "the\_content" everywhere (all posts essentially) - so exercise or consider narrowing the scope. For instance, you might want to limit it to the first 100 characters, or to posts before a certain date, or within a certain category before a certain date, etc., otherwise someday someone may happen to use the same sequence of characters and be shocked to find that everything up to them has apparently been deleted. ``` /** * Filter all posts to remove 'Post - ' * and all characters preceding it * from all posts **/ add_filter( 'the_content', 'get_rid_of_text_to_post_dash' ); function get_rid_of_text_to_post_dash( $content ) { $key_string = 'Post - '; $new_content = ( strpos( $content, $key_string ) ) ? substr( $content, strpos( $content, $key_string) + 7 ) : $content; return $new_content; } ```
280,845
<p>Can we count the WordPress loop and store it in a variable?</p> <pre><code>&lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;?php $post_id = get_the_ID(); ?&gt; &lt;?php get_template_part('content','home'); ?&gt; some code to be executed &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>what I want is that for every 5 posts fetched ceratin code should be executed(example newsletter) → That means within the loop for every 5h, 10th, 15th, ____________ infinite posts(5n, n>=1) the code should be executed.</p>
[ { "answer_id": 280847, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 3, "selected": true, "text": "<p><code>$wp_query-&gt;current_post</code> is the build-in loop counter, starting with 0 zero for the first post in the loop.</p>\n\n<p>so the line <code>some code to be executed</code> could translate to:</p>\n\n<p><code>&lt;?php if( $wp_query-&gt;current_post &gt; 0 &amp;&amp; $wp_query-&gt;current_post % 5 == 0 ) { ?&gt;\n some code to be executed\n&lt;?php } ?&gt;</code></p>\n" }, { "answer_id": 280849, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>PLease check this code snippet</p>\n\n<pre><code> &lt;?php $i=0; \nif ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php $post_id = get_the_ID(); ?&gt;\n if($i%5 == 0)\n {\\\\code to be executed}\n &lt;?php get_template_part('content','home'); ?&gt;\n some code to be executed\n&lt;?php $i++;endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/09/23
[ "https://wordpress.stackexchange.com/questions/280845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
Can we count the WordPress loop and store it in a variable? ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $post_id = get_the_ID(); ?> <?php get_template_part('content','home'); ?> some code to be executed <?php endwhile; ?> <?php endif; ?> ``` what I want is that for every 5 posts fetched ceratin code should be executed(example newsletter) → That means within the loop for every 5h, 10th, 15th, \_\_\_\_\_\_\_\_\_\_\_\_ infinite posts(5n, n>=1) the code should be executed.
`$wp_query->current_post` is the build-in loop counter, starting with 0 zero for the first post in the loop. so the line `some code to be executed` could translate to: `<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>`
280,857
<p>I am trying to follow <a href="https://adactio.com/journal/8504" rel="nofollow noreferrer">this tutorial</a> that says i can make a server to send a file like style.css if the requested file is style.15458888.css with a rewrite rule to be put inside the htaccess file. </p> <p>This Rule</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L] </code></pre> <p>So i followed with this in the <code>head</code> tag:</p> <pre><code>&lt;?php $time = filemtime(get_template_directory() .'/assets/css/main.css');?&gt; &lt;link href="&lt;?php echo get_template_directory_uri().'/assets/css/main.'.$time.'.css'?&gt;" rel="stylesheet" type="text/css"&gt; </code></pre> <p>and this inside the <code>Htaccess</code>:</p> <pre><code> # BEGIN WordPress &lt;IfModule mod_expires.c&gt; ExpiresActive On ExpiresByType image/jpg "access plus 6 hours" ExpiresByType image/jpeg "access plus 6 hours" ExpiresByType image/gif "access plus 6 hours" ExpiresByType image/png "access plus 6 hours" ExpiresByType text/css "access plus 6 hours" ExpiresByType application/pdf "access plus 1 week" ExpiresByType text/javascript "access plus 6 hours" ExpiresByType text/html "access plus 10 minutes" ExpiresByType image/x-icon "access plus 1 year" ExpiresDefault "access plus 3 hours" &lt;/IfModule&gt; Header set X-Endurance-Cache-Level "2" &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] RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>As you can see the <code>RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L]</code> has been added before the <code>&lt;/IfModule&gt;</code></p> <p>And the file name changed correctly having this:</p> <pre><code>&lt;link href="http://ask.prosentra.com/wp-content/themes/tutorialblog/assets/css/main.1504604028.css" rel="stylesheet" type="text/css"&gt; </code></pre> <p>But still the server doesn't implement the rule i mentioned. What is wrong?</p>
[ { "answer_id": 280847, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 3, "selected": true, "text": "<p><code>$wp_query-&gt;current_post</code> is the build-in loop counter, starting with 0 zero for the first post in the loop.</p>\n\n<p>so the line <code>some code to be executed</code> could translate to:</p>\n\n<p><code>&lt;?php if( $wp_query-&gt;current_post &gt; 0 &amp;&amp; $wp_query-&gt;current_post % 5 == 0 ) { ?&gt;\n some code to be executed\n&lt;?php } ?&gt;</code></p>\n" }, { "answer_id": 280849, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>PLease check this code snippet</p>\n\n<pre><code> &lt;?php $i=0; \nif ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php $post_id = get_the_ID(); ?&gt;\n if($i%5 == 0)\n {\\\\code to be executed}\n &lt;?php get_template_part('content','home'); ?&gt;\n some code to be executed\n&lt;?php $i++;endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/09/23
[ "https://wordpress.stackexchange.com/questions/280857", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102224/" ]
I am trying to follow [this tutorial](https://adactio.com/journal/8504) that says i can make a server to send a file like style.css if the requested file is style.15458888.css with a rewrite rule to be put inside the htaccess file. This Rule ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L] ``` So i followed with this in the `head` tag: ``` <?php $time = filemtime(get_template_directory() .'/assets/css/main.css');?> <link href="<?php echo get_template_directory_uri().'/assets/css/main.'.$time.'.css'?>" rel="stylesheet" type="text/css"> ``` and this inside the `Htaccess`: ``` # BEGIN WordPress <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 6 hours" ExpiresByType image/jpeg "access plus 6 hours" ExpiresByType image/gif "access plus 6 hours" ExpiresByType image/png "access plus 6 hours" ExpiresByType text/css "access plus 6 hours" ExpiresByType application/pdf "access plus 1 week" ExpiresByType text/javascript "access plus 6 hours" ExpiresByType text/html "access plus 10 minutes" ExpiresByType image/x-icon "access plus 1 year" ExpiresDefault "access plus 3 hours" </IfModule> Header set X-Endurance-Cache-Level "2" <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L] </IfModule> # END WordPress ``` As you can see the `RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L]` has been added before the `</IfModule>` And the file name changed correctly having this: ``` <link href="http://ask.prosentra.com/wp-content/themes/tutorialblog/assets/css/main.1504604028.css" rel="stylesheet" type="text/css"> ``` But still the server doesn't implement the rule i mentioned. What is wrong?
`$wp_query->current_post` is the build-in loop counter, starting with 0 zero for the first post in the loop. so the line `some code to be executed` could translate to: `<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>`
280,868
<p>I am willing to migrate a new website to the customer server to replace its old one. The old customer website used to be a single website (no network). I want to replace it with a network so as to be able to have one site in French, and another in English.</p> <p>I would like it to use subfolders. So that :</p> <blockquote> <p>idakt.com --> contains French version of the site,</p> <p>idakt.com/en --> contains English version of the site.</p> </blockquote> <p>I have followed the steps described <a href="https://www.elegantthemes.com/blog/resources/the-complete-guide-to-creating-a-wordpress-multisite-installation" rel="nofollow noreferrer">here</a> up to the update of the wp-config.php file with the following code :</p> <pre><code>define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'mydomain.com'); define('PATH_CURRENT_SITE', '/wordpress/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); </code></pre> <p>Then I have put the following code in .htaccess file (according to the same guidelines)</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I managed to create a new site <code>idakt.com/en</code> in my network, but it does not appear in the drop down menu of my dashboard, see screenshot. Therefore I am afraid something is wrong and I go ahead many problems in my next steps to update the 2 sites in my network...</p> <p>NB: I do not care if all the links are broken with the set-up of the network.</p> <p>I thank you very much in advance for your help! <a href="https://i.stack.imgur.com/d91j3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d91j3.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 280847, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 3, "selected": true, "text": "<p><code>$wp_query-&gt;current_post</code> is the build-in loop counter, starting with 0 zero for the first post in the loop.</p>\n\n<p>so the line <code>some code to be executed</code> could translate to:</p>\n\n<p><code>&lt;?php if( $wp_query-&gt;current_post &gt; 0 &amp;&amp; $wp_query-&gt;current_post % 5 == 0 ) { ?&gt;\n some code to be executed\n&lt;?php } ?&gt;</code></p>\n" }, { "answer_id": 280849, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>PLease check this code snippet</p>\n\n<pre><code> &lt;?php $i=0; \nif ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php $post_id = get_the_ID(); ?&gt;\n if($i%5 == 0)\n {\\\\code to be executed}\n &lt;?php get_template_part('content','home'); ?&gt;\n some code to be executed\n&lt;?php $i++;endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/09/23
[ "https://wordpress.stackexchange.com/questions/280868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128403/" ]
I am willing to migrate a new website to the customer server to replace its old one. The old customer website used to be a single website (no network). I want to replace it with a network so as to be able to have one site in French, and another in English. I would like it to use subfolders. So that : > > idakt.com --> contains French version of the site, > > > idakt.com/en --> contains English version of the site. > > > I have followed the steps described [here](https://www.elegantthemes.com/blog/resources/the-complete-guide-to-creating-a-wordpress-multisite-installation) up to the update of the wp-config.php file with the following code : ``` define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'mydomain.com'); define('PATH_CURRENT_SITE', '/wordpress/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); ``` Then I have put the following code in .htaccess file (according to the same guidelines) ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </IfModule> # END WordPress ``` I managed to create a new site `idakt.com/en` in my network, but it does not appear in the drop down menu of my dashboard, see screenshot. Therefore I am afraid something is wrong and I go ahead many problems in my next steps to update the 2 sites in my network... NB: I do not care if all the links are broken with the set-up of the network. I thank you very much in advance for your help! [![enter image description here](https://i.stack.imgur.com/d91j3.jpg)](https://i.stack.imgur.com/d91j3.jpg)
`$wp_query->current_post` is the build-in loop counter, starting with 0 zero for the first post in the loop. so the line `some code to be executed` could translate to: `<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>`
280,871
<p>I'm running a WP multisite using subdomains. I would like to force SSL protocol for all requests and am running into an issue for non-SSL requests on my child sites. I'm using the <a href="https://wordpress.org/plugins/wp-force-ssl/" rel="nofollow noreferrer">WP Force SSL</a> plugin. I've done a bit of digging around and tried the following .htaccess directive, but it doesn't work (nor do anything):</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre> <p>For example:</p> <ul> <li><a href="http://derpsite.tld" rel="nofollow noreferrer">http://derpsite.tld</a> = redirects to SSL Protocol</li> <li><a href="https://derpsite.tld" rel="nofollow noreferrer">https://derpsite.tld</a> = works</li> <li><a href="http://child1.derpsite.tld" rel="nofollow noreferrer">http://child1.derpsite.tld</a> = breaks. Specifically, I get a <code>http://child1.derpsite.tld/cgi-sys/defaultwebpage.cgi</code> cPanel error page</li> <li><a href="https://child1.derpsite.tld" rel="nofollow noreferrer">https://child1.derpsite.tld</a> = works</li> </ul> <p><strong>EDIT 1</strong></p> <p>I've reached out to both my host (dedicated server that has cPanel installed) and cPanel (the latter with whom I still have an open ticket). cPanel has mentioned:</p> <blockquote> <p>Apache on cPanel is configured a bit different than other servers you may be used to. By default, Apache will accept any domain name being requested because it's set up as a wildcard. On cPanel servers, the virtualhosts are configured specifically for the domains you create. For example, when you created the cPanel account for defectslawyer.com, it set up a configuration that is specific to defectslawyer.com. Let's say I point the DNS for my domain thisisarealdomain.com to your server. When I make the request for thisisarealdomain.com, Apache checks it's configuration for that domain, doesn't find it, then returns the cPanel default page.</p> <p>It sounds like you have DNS configured correctly, I'm assuming a wildcard subdomain record pointing to your server, but Apache doesn't know what to do with what's being requested. At least on the non-SSL side of things. What should solve the problem is to add a wildcard subdomain in cPanel [ <a href="https://documentation.cpanel.net/display/ALD/Subdomains" rel="nofollow noreferrer">https://documentation.cpanel.net/display/ALD/Subdomains</a> ] so that the Apache vhost for *.derpsite.tld is added. Then, when <em>anything</em>.derpsite.tld is requested, Apache will be able to find that vhost and know what to load.</p> <p>The reason SSL version may be working is you likely installed the SSL as *.derpsite.tld which creates that SSL vhost. </p> </blockquote> <p>Based on this input I have:</p> <ul> <li>Added a wildcard subdomain within cPanel (and have the subdomain document root point to the main site root)...which now kicks out a <code>500 internal server error</code> for both <code>http://child1.derpsite.tld</code> and <code>https://child1.derpsite.tld</code>)</li> <li>I'm currently reviewing how I have my SSL set up</li> </ul> <p><strong>EDIT 2</strong></p> <p>The <code>500 internal server error</code> above seems to have been the result of installing my SSL on a wildcard domain; please see my '<a href="https://wordpress.stackexchange.com/a/281376/47880">answer</a>' below</p>
[ { "answer_id": 280896, "author": "SEO DEVS", "author_id": 111163, "author_profile": "https://wordpress.stackexchange.com/users/111163", "pm_score": 0, "selected": false, "text": "<p>Because this is classed as 2 different domains, it will need to be done in 2 parts. Try this:</p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{HTTP_HOST} ^derpsite\\.tld [NC]\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://derpsite.tld/$1 [R,L]\n\nRewriteCond %{HTTP_HOST} ^child1\\.derpsite\\.tld [NC]\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://child1.derpsite.tld/$1 [R,L]\n</code></pre>\n" }, { "answer_id": 281080, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>From the description of the error you get, it seems like you do not get at all to your account related software when trying to access the child on http. This sounds like a web server configuration error, so in your case you need to make sure that in your cpanel you enabled subdomains for http and not only https</p>\n" }, { "answer_id": 281325, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 0, "selected": false, "text": "<p>You typically do not need to run plugins to force the SSL if you configured websever well. </p>\n\n<p>You just need <code>Settings -&gt; General</code> and change both URLs to have <code>https://</code> rather than <code>http://</code>. Also purge the caching plugins is always the good idea. As I see the SSL certificates are in place and are working for you based on what you said.</p>\n\n<p>The core of this plugin you mentioned is this:</p>\n\n<pre><code>// \"The Core\"\ndefine('FORCE_SSL' , true);\n\nif (defined('FORCE_SSL'))\n add_action('template_redirect', 'force_ssl');\n\nfunction force_ssl(){\n\nif ( FORCE_SSL &amp;&amp; !is_ssl () )\n {\n wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );\n exit();\n }\n}\n</code></pre>\n\n<p>As you can see PHP or WordPress has been used to force the redirection. Instead these re-directions are better and smarter on webserver level. No PHP need to be used.</p>\n" }, { "answer_id": 281376, "author": "Ryan Dorn", "author_id": 47880, "author_profile": "https://wordpress.stackexchange.com/users/47880", "pm_score": 1, "selected": false, "text": "<p>Thanks to everyone who commented on this, it definitely helped steer me towards the right direction and, finally, I believe that I know what happened, which was a combination of several factors. I realize that this may not be <em>'strictly</em> WP related', but for those using <strong>cPanel</strong>, the following should be of some assistance. I’ve compiled a few 'rule of thumb' items that, when all in place together, seem to have resolved the issue of forcing SSL protocols:</p>\n\n<ul>\n<li><code>siteurl</code> and <code>home</code> fields in the options database table for each site (or in wp-admin ... <code>~/wp-admin/network/sites.php &gt; Edit Site &gt; Site Address (URL)</code> for each site) need to use <code>https://</code> in the URL</li>\n<li>If using a wildcard SSL <em>(which I imagine will be the case for most wanting to use SSL on a subdomain-driven multisite)</em> is <a href=\"https://documentation.cpanel.net/display/ALD/Install+an+SSL+Certificate+on+a+Domain\" rel=\"nofollow noreferrer\">installed</a> for the <strong>root domain, not a wildcard domain</strong>. I had my SSL installed on *<code>derpsite.tld</code> and removed/reinstalled it for <code>derpsite.tld</code></li>\n<li>In DNS an ‘A’ wildcard record needs to point to the server IP, i.e. <code>*.derpsite.tld -&gt; YOURSERVERIP</code></li>\n<li>In cPanel, a <a href=\"https://www.siteground.com/kb/how_to_enable_wildcard_subdomains/\" rel=\"nofollow noreferrer\">wildcard subdomain</a> (<code>*.derpsite.tld</code>) needs to be created and the subdomain directory should be the root directory (in most <strong>cPanel</strong> cases, this will be <code>/public_html</code> ...because, if running a multisite, you don’t actually want real directories to be created for 'child site' subdomains)</li>\n<li>Additional note: if you are doing domain mapping, you will likely have to '<a href=\"https://documentation.cpanel.net/display/ALD/Park+a+Domain\" rel=\"nofollow noreferrer\">park</a>' your external domain via WHM or cPanel to get it to run forced through SSL. Also, as of <a href=\"https://codex.wordpress.org/WordPress_Multisite_Domain_Mapping\" rel=\"nofollow noreferrer\">4.5+ domain mapping is native</a>). <em>Please note: at the time of writing I am using WP v.4.8.2 and cPanel v.66.0.23 ...sites running a WP version prior to 4.5 may require a different configuration</em></li>\n<li>I'm not entirely sure if this is necessary, but I have the following directives in my root <code>.htacess</code> file:</li>\n</ul>\n\n<p><code>\n RewriteEngine On\n RewriteCond %{HTTPS} !=on\n RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]<br>\n RewriteCond %{HTTP_HOST} ^my\\-mapped\\-external\\-domain\\.tld[NC]\n RewriteCond %{SERVER_PORT} 80 \n RewriteRule ^(.*)$ https://my-mapped-external-domain.tld/$1 [R,L]\n</code></p>\n\n<p>Hope this helps someone!</p>\n" } ]
2017/09/23
[ "https://wordpress.stackexchange.com/questions/280871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47880/" ]
I'm running a WP multisite using subdomains. I would like to force SSL protocol for all requests and am running into an issue for non-SSL requests on my child sites. I'm using the [WP Force SSL](https://wordpress.org/plugins/wp-force-ssl/) plugin. I've done a bit of digging around and tried the following .htaccess directive, but it doesn't work (nor do anything): ``` RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` For example: * <http://derpsite.tld> = redirects to SSL Protocol * <https://derpsite.tld> = works * <http://child1.derpsite.tld> = breaks. Specifically, I get a `http://child1.derpsite.tld/cgi-sys/defaultwebpage.cgi` cPanel error page * <https://child1.derpsite.tld> = works **EDIT 1** I've reached out to both my host (dedicated server that has cPanel installed) and cPanel (the latter with whom I still have an open ticket). cPanel has mentioned: > > Apache on cPanel is configured a bit different than other servers you may be used to. By default, Apache will accept any domain name being requested because it's set up as a wildcard. On cPanel servers, the virtualhosts are configured specifically for the domains you create. For example, when you created the cPanel account for defectslawyer.com, it set up a configuration that is specific to defectslawyer.com. Let's say I point the DNS for my domain thisisarealdomain.com to your server. When I make the request for thisisarealdomain.com, Apache checks it's configuration for that domain, doesn't find it, then returns the cPanel default page. > > > It sounds like you have DNS configured correctly, I'm assuming a wildcard subdomain record pointing to your server, but Apache doesn't know what to do with what's being requested. At least on the non-SSL side of things. What should solve the problem is to add a wildcard subdomain in cPanel [ <https://documentation.cpanel.net/display/ALD/Subdomains> ] so that the Apache vhost for \*.derpsite.tld is added. Then, when *anything*.derpsite.tld is requested, Apache will be able to find that vhost and know what to load. > > > The reason SSL version may be working is you likely installed the SSL as \*.derpsite.tld which creates that SSL vhost. > > > Based on this input I have: * Added a wildcard subdomain within cPanel (and have the subdomain document root point to the main site root)...which now kicks out a `500 internal server error` for both `http://child1.derpsite.tld` and `https://child1.derpsite.tld`) * I'm currently reviewing how I have my SSL set up **EDIT 2** The `500 internal server error` above seems to have been the result of installing my SSL on a wildcard domain; please see my '[answer](https://wordpress.stackexchange.com/a/281376/47880)' below
From the description of the error you get, it seems like you do not get at all to your account related software when trying to access the child on http. This sounds like a web server configuration error, so in your case you need to make sure that in your cpanel you enabled subdomains for http and not only https
280,897
<p>This is my first experience with WordPress multisite and i followed all instructions from codex to make my website a multisite.<br> But my sub domains are not working and chrome is displaying this message for my sub domains.<br> DNS address could not be found.<br> Do i have to create sub domain all the time in my cpanel before creating new website (sub domain) in WordPress? I already have few sub domains which are working perfectly but these all are separate websites. Now i make my main domain a multisite but all sub domains are not working on this. Here is my htaccess code which is provided my WordPress </p> <pre><code>RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^wp-admin$ wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ $1 [L] RewriteRule . index.php [L] </code></pre> <p>I also add code in my wp-config file provided by WordPress and able to login into network panel and to create sub domains but when i try to visit any of the sub domain it displays DNS error. I will really appreciate it if someone will guide me about this. Thank you!</p>
[ { "answer_id": 280898, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Do I have to create sub domain all the time in my cpanel before creating new website (sub domain) in WordPress?</p>\n</blockquote>\n\n<p>You need to make sure that the subdomains are created <em>somewhere</em>. WordPress doesn't have the capability to create DNS entries for you.</p>\n\n<p>If you've got WordPress set up on <code>example.com</code> and you want to create <code>site1.example.com</code>, <code>site2.example.com</code>, etc., you need to ensure that the DNS entries for <code>site1.example.com</code>, <code>site2.example.com</code>, etc., are active.</p>\n\n<p>Depending on your hosting situation, you might be able to create <strong>wildcard</strong> subdomains, meaning that you can add <code>*.example.com</code> to your DNS entries, which would allow you to point anything ending in <code>.example.com</code> to your Multisite installation. <strong>This is something you'll need to research with your hosting company</strong>, though, and not something we can guide you through here.</p>\n\n<p><a href=\"https://codex.wordpress.org/Before_You_Create_A_Network#Domain-based\" rel=\"nofollow noreferrer\">Codex: Before You Create a Network » Domain-based</a></p>\n" }, { "answer_id": 384311, "author": "Mike Hall", "author_id": 202716, "author_profile": "https://wordpress.stackexchange.com/users/202716", "pm_score": 0, "selected": false, "text": "<p>Thanks for your answer wplearner and Pat J - this helped me solve my problem.\nI was finding that after converting to a multi site worpress install using subdomains my main site worked mainsite.com but training.example.com did not. I just got a Internal Server Error page.</p>\n<p>Solution:</p>\n<ol>\n<li>I logged into CPanel &gt; Subdomains</li>\n<li>Added the subdomain training.example.com and had it just direct to the document root /public-html/</li>\n<li>In the &quot;manage subdomains&quot; section I clicked the &quot;Manage redirection&quot; settings and I set it to redirect to <a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a> (I use SSL on my site so i guess if you don't use SSL just send it to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> ) and saved</li>\n<li>Go back to your wordpress admin section, click into My Sites and go to the second site and it worked!\nTHANK YOU SO MUCH!</li>\n</ol>\n" } ]
2017/09/23
[ "https://wordpress.stackexchange.com/questions/280897", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120693/" ]
This is my first experience with WordPress multisite and i followed all instructions from codex to make my website a multisite. But my sub domains are not working and chrome is displaying this message for my sub domains. DNS address could not be found. Do i have to create sub domain all the time in my cpanel before creating new website (sub domain) in WordPress? I already have few sub domains which are working perfectly but these all are separate websites. Now i make my main domain a multisite but all sub domains are not working on this. Here is my htaccess code which is provided my WordPress ``` RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^wp-admin$ wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ $1 [L] RewriteRule . index.php [L] ``` I also add code in my wp-config file provided by WordPress and able to login into network panel and to create sub domains but when i try to visit any of the sub domain it displays DNS error. I will really appreciate it if someone will guide me about this. Thank you!
> > Do I have to create sub domain all the time in my cpanel before creating new website (sub domain) in WordPress? > > > You need to make sure that the subdomains are created *somewhere*. WordPress doesn't have the capability to create DNS entries for you. If you've got WordPress set up on `example.com` and you want to create `site1.example.com`, `site2.example.com`, etc., you need to ensure that the DNS entries for `site1.example.com`, `site2.example.com`, etc., are active. Depending on your hosting situation, you might be able to create **wildcard** subdomains, meaning that you can add `*.example.com` to your DNS entries, which would allow you to point anything ending in `.example.com` to your Multisite installation. **This is something you'll need to research with your hosting company**, though, and not something we can guide you through here. [Codex: Before You Create a Network » Domain-based](https://codex.wordpress.org/Before_You_Create_A_Network#Domain-based)
280,912
<p>I found many requests made from Russia targeting the file admin-ajax.php, my server is not working right now.</p> <p>I am sure that this traffic doesn't come from normal users but a robot.</p> <p>How to avoid processing these queries to save resources ?</p> <pre><code>5.188.203.23 - - [24/Sep/2017:02:18:36 +0200] "POST /wp-admin/admin-ajax.php HTTP/1.1" 200 1 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36" </code></pre>
[ { "answer_id": 280919, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Right now (version 4.8) there is no simple way to do it without crippling the admin.</p>\n\n<p>OTOH, processing an ajax request that basically does nothing has very little cost in CPU cycles (lighter than an uncached front page) and you can probably just ignore it. If your site goes down because of it you have some very bad code going on.</p>\n" }, { "answer_id": 280922, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use <strong>.htaccess</strong> to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution.</p>\n\n<p>Simples way to ban IP in <strong>.htaccess</strong> is (replace 123.123.123.123 with IP you want to ban):</p>\n\n<pre><code>Deny from 123.123.123.123\n</code></pre>\n\n<p>You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different.</p>\n\n<p>But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.</p>\n" } ]
2017/09/24
[ "https://wordpress.stackexchange.com/questions/280912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121382/" ]
I found many requests made from Russia targeting the file admin-ajax.php, my server is not working right now. I am sure that this traffic doesn't come from normal users but a robot. How to avoid processing these queries to save resources ? ``` 5.188.203.23 - - [24/Sep/2017:02:18:36 +0200] "POST /wp-admin/admin-ajax.php HTTP/1.1" 200 1 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36" ```
You can use **.htaccess** to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution. Simples way to ban IP in **.htaccess** is (replace 123.123.123.123 with IP you want to ban): ``` Deny from 123.123.123.123 ``` You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different. But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.
280,931
<p>I have a really weird issue. I use the Facebook Open Graph, Google+ and Twitter Card Tags plugin to create open graph tags for my wordpress pages. Normally this works smoothly. It takes the first image of a page and uses it as the <code>og:image</code> tag.</p> <p>Example page: <a href="https://ungehorsam.org/programm/geschichten" rel="nofollow noreferrer">https://ungehorsam.org/programm/geschichten</a></p> <p>The created tag (see HTML code of page linked above) looks like this:</p> <pre><code>&lt;meta property="og:image" content="https://ungehorsam.org/wp-content/uploads/mlk_web.jpg"/&gt; </code></pre> <p>However, I have one weird problematic page. The page does not load: <a href="https://ungehorsam.org/programm/empty-cages" rel="nofollow noreferrer">https://ungehorsam.org/programm/empty-cages</a></p> <p>I inspected the HTML code and it seems that it stops right where the facebook open graph tags should appear. It turns out, that if I remove the image from the post, the page loads normally. Also: If I use a different picture than <a href="https://ungehorsam.org/wp-content/uploads/cage.jpg" rel="nofollow noreferrer">this one</a>, the page renders as expected. It seems that only when I use <a href="https://ungehorsam.org/wp-content/uploads/cage.jpg" rel="nofollow noreferrer">this specific picture</a>, the open graph tags cannot be generated by the plugin.</p> <p>So I tried:</p> <ul> <li>use a different picture than this one => page loaded</li> <li>delete and reupload the problematic picture => page still does not load</li> <li>delete, save the picture with slightly different quality, and reupload it => page still does not load</li> </ul> <p>I ran out of ideas on how to tackle this now. What is the problem with this picture? Why can't the plugin create the open graph tags if this picture is included in the post?</p>
[ { "answer_id": 280919, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Right now (version 4.8) there is no simple way to do it without crippling the admin.</p>\n\n<p>OTOH, processing an ajax request that basically does nothing has very little cost in CPU cycles (lighter than an uncached front page) and you can probably just ignore it. If your site goes down because of it you have some very bad code going on.</p>\n" }, { "answer_id": 280922, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use <strong>.htaccess</strong> to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution.</p>\n\n<p>Simples way to ban IP in <strong>.htaccess</strong> is (replace 123.123.123.123 with IP you want to ban):</p>\n\n<pre><code>Deny from 123.123.123.123\n</code></pre>\n\n<p>You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different.</p>\n\n<p>But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.</p>\n" } ]
2017/09/24
[ "https://wordpress.stackexchange.com/questions/280931", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26545/" ]
I have a really weird issue. I use the Facebook Open Graph, Google+ and Twitter Card Tags plugin to create open graph tags for my wordpress pages. Normally this works smoothly. It takes the first image of a page and uses it as the `og:image` tag. Example page: <https://ungehorsam.org/programm/geschichten> The created tag (see HTML code of page linked above) looks like this: ``` <meta property="og:image" content="https://ungehorsam.org/wp-content/uploads/mlk_web.jpg"/> ``` However, I have one weird problematic page. The page does not load: <https://ungehorsam.org/programm/empty-cages> I inspected the HTML code and it seems that it stops right where the facebook open graph tags should appear. It turns out, that if I remove the image from the post, the page loads normally. Also: If I use a different picture than [this one](https://ungehorsam.org/wp-content/uploads/cage.jpg), the page renders as expected. It seems that only when I use [this specific picture](https://ungehorsam.org/wp-content/uploads/cage.jpg), the open graph tags cannot be generated by the plugin. So I tried: * use a different picture than this one => page loaded * delete and reupload the problematic picture => page still does not load * delete, save the picture with slightly different quality, and reupload it => page still does not load I ran out of ideas on how to tackle this now. What is the problem with this picture? Why can't the plugin create the open graph tags if this picture is included in the post?
You can use **.htaccess** to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution. Simples way to ban IP in **.htaccess** is (replace 123.123.123.123 with IP you want to ban): ``` Deny from 123.123.123.123 ``` You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different. But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.
280,938
<p>I want to add few settings fields dynamically on settings page depending on user action. I am planning to register these new fields dynamically once user asks for it and show the corresponding HTML using jQuery. Is it possible to register settings once you are already on settings page? Also, is there a better way to do this?</p>
[ { "answer_id": 280919, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Right now (version 4.8) there is no simple way to do it without crippling the admin.</p>\n\n<p>OTOH, processing an ajax request that basically does nothing has very little cost in CPU cycles (lighter than an uncached front page) and you can probably just ignore it. If your site goes down because of it you have some very bad code going on.</p>\n" }, { "answer_id": 280922, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use <strong>.htaccess</strong> to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution.</p>\n\n<p>Simples way to ban IP in <strong>.htaccess</strong> is (replace 123.123.123.123 with IP you want to ban):</p>\n\n<pre><code>Deny from 123.123.123.123\n</code></pre>\n\n<p>You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different.</p>\n\n<p>But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.</p>\n" } ]
2017/09/24
[ "https://wordpress.stackexchange.com/questions/280938", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116770/" ]
I want to add few settings fields dynamically on settings page depending on user action. I am planning to register these new fields dynamically once user asks for it and show the corresponding HTML using jQuery. Is it possible to register settings once you are already on settings page? Also, is there a better way to do this?
You can use **.htaccess** to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution. Simples way to ban IP in **.htaccess** is (replace 123.123.123.123 with IP you want to ban): ``` Deny from 123.123.123.123 ``` You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different. But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.
280,947
<p>I'm trying to use the REST API v2 to populate a modal window when clicking on a project custom post type item.</p> <p>Projects have a custom taxonomy, Skills. I'm using ?_embed on the JSON URL and it is returning the custom taxonomy items, but it's being limited to 10 terms for each returned Project item. I can't seem to do anything to get ALL of the tagged Skills to return for a given Project item.</p> <p>I updated the general pagination settings in the WordPress settings to be 20, thinking that would adjust the number of associated taxonomy terms returned: no change.</p> <p>I added the following method to make the taxonomy accessible via REST:</p> <pre><code>add_action( 'init', 'my_custom_taxonomy_rest_support', 25 ); function my_custom_taxonomy_rest_support() { global $wp_taxonomies; $taxonomy_name = 'skill'; if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) { $wp_taxonomies[ $taxonomy_name ]-&gt;show_in_rest = true; $wp_taxonomies[ $taxonomy_name ]-&gt;posts_per_page = -1; } } </code></pre> <p>And I've tried all variations of per_page, posts_per_page and using -1, 0, 99 to no avail. I can't seem to find anything about this being an issue for anyone else so I'm at a bit of a loss of what to do here. If a project is tagged with 14 skills, the most I can ever get back from the REST API is 10 Skill taxonomy terms for each Project. </p> <p>Anyone know how to change the limit to be unlimited?</p>
[ { "answer_id": 280919, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Right now (version 4.8) there is no simple way to do it without crippling the admin.</p>\n\n<p>OTOH, processing an ajax request that basically does nothing has very little cost in CPU cycles (lighter than an uncached front page) and you can probably just ignore it. If your site goes down because of it you have some very bad code going on.</p>\n" }, { "answer_id": 280922, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can use <strong>.htaccess</strong> to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution.</p>\n\n<p>Simples way to ban IP in <strong>.htaccess</strong> is (replace 123.123.123.123 with IP you want to ban):</p>\n\n<pre><code>Deny from 123.123.123.123\n</code></pre>\n\n<p>You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different.</p>\n\n<p>But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.</p>\n" } ]
2017/09/24
[ "https://wordpress.stackexchange.com/questions/280947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99012/" ]
I'm trying to use the REST API v2 to populate a modal window when clicking on a project custom post type item. Projects have a custom taxonomy, Skills. I'm using ?\_embed on the JSON URL and it is returning the custom taxonomy items, but it's being limited to 10 terms for each returned Project item. I can't seem to do anything to get ALL of the tagged Skills to return for a given Project item. I updated the general pagination settings in the WordPress settings to be 20, thinking that would adjust the number of associated taxonomy terms returned: no change. I added the following method to make the taxonomy accessible via REST: ``` add_action( 'init', 'my_custom_taxonomy_rest_support', 25 ); function my_custom_taxonomy_rest_support() { global $wp_taxonomies; $taxonomy_name = 'skill'; if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) { $wp_taxonomies[ $taxonomy_name ]->show_in_rest = true; $wp_taxonomies[ $taxonomy_name ]->posts_per_page = -1; } } ``` And I've tried all variations of per\_page, posts\_per\_page and using -1, 0, 99 to no avail. I can't seem to find anything about this being an issue for anyone else so I'm at a bit of a loss of what to do here. If a project is tagged with 14 skills, the most I can ever get back from the REST API is 10 Skill taxonomy terms for each Project. Anyone know how to change the limit to be unlimited?
You can use **.htaccess** to ban IP's that you don't want to access your website. If you are attacked from the same IP over the prolonged period of time, and with great frequency, banning the IP is the best solution. Simples way to ban IP in **.htaccess** is (replace 123.123.123.123 with IP you want to ban): ``` Deny from 123.123.123.123 ``` You can add multiple lines like this for multiple IP's. This works for Apache servers if you use some other server type, the method to ban IP's will be different. But, before you do this, make sure you are really banning the malicious user that tries to do something bad. A better solution is to use some security plugin that can identify malicious or spam sources and ban them for you.
280,966
<p>I'm using the Twenty Seventeen theme and my goal is to move the main menu (top nav) from its position under the header image to the very top of the page directly over the header image (transparent background), but there seems to be a lot of javascript in addition to css involved in positioning the menu and making it sticky when scrolling. </p> <p>Can someone point me in the direction of the specific js files/functions that control and calculate the menu position on the homepage and secondary pages? It would also be useful to know the css lines that control this to check I have them all. Every time I think I've got the js and css covered the result is still buggy so I'm obviously missing something. Thanks.</p>
[ { "answer_id": 282593, "author": "Brian", "author_id": 129437, "author_profile": "https://wordpress.stackexchange.com/users/129437", "pm_score": 0, "selected": false, "text": "<p>Try adding the following</p>\n\n<pre><code>.navigation-top {\n top: 14px;\n}\n</code></pre>\n\n<p>Should move the menu to the top of the screen although this will affect all pages.</p>\n" }, { "answer_id": 300284, "author": "Uladzislau Sauka", "author_id": 141448, "author_profile": "https://wordpress.stackexchange.com/users/141448", "pm_score": -1, "selected": false, "text": "<pre><code>@media screen and (min-width: 48em){\n .home .navigation-top {\n top: 0;\n bottom:auto;\n }\n}\n</code></pre>\n" }, { "answer_id": 405576, "author": "Phil", "author_id": 222038, "author_profile": "https://wordpress.stackexchange.com/users/222038", "pm_score": 1, "selected": false, "text": "<p>This is a two step solution:</p>\n<ol>\n<li>Install plugin &quot;Options for Twenty Seventeen&quot; (<a href=\"https://wordpress.org/plugins/options-for-twenty-seventeen/\" rel=\"nofollow noreferrer\">Link</a>)</li>\n<li>Add the following CSS to &quot;Design&quot; &gt; &quot;Customizer&quot; &gt; &quot;Additional CSS&quot;</li>\n</ol>\n<hr />\n<pre><code>.navigation-top {\n position: fixed;\n bottom: auto;\n left: 0;\n right: 0;\n top: 0;\n width: 100%;\n}\n\n.custom-header {\n padding-top: 50px;\n}\n</code></pre>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/280966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67759/" ]
I'm using the Twenty Seventeen theme and my goal is to move the main menu (top nav) from its position under the header image to the very top of the page directly over the header image (transparent background), but there seems to be a lot of javascript in addition to css involved in positioning the menu and making it sticky when scrolling. Can someone point me in the direction of the specific js files/functions that control and calculate the menu position on the homepage and secondary pages? It would also be useful to know the css lines that control this to check I have them all. Every time I think I've got the js and css covered the result is still buggy so I'm obviously missing something. Thanks.
This is a two step solution: 1. Install plugin "Options for Twenty Seventeen" ([Link](https://wordpress.org/plugins/options-for-twenty-seventeen/)) 2. Add the following CSS to "Design" > "Customizer" > "Additional CSS" --- ``` .navigation-top { position: fixed; bottom: auto; left: 0; right: 0; top: 0; width: 100%; } .custom-header { padding-top: 50px; } ```
280,981
<p>I'm having quite a few problems with my WP settings. The main issue is that I need to have WP installed at //domain1.xxx/ and viewed at //domain2.xxx. It's not enough to change wp_home and wp_site_url to achieve this. Since I want to remove all trace of domain1 when viewing the site at domain2 I use relative paths (courtesy of a plugin called "Remove HTTP"). The problem that remains is that some plugins still use absolute paths. One of them is Contact Form 7 which use the WP REST API. My question is: Can I redefine the REST variables so that I remove domain1 and replace it with preferable "/" or if that fails use domain2.</p>
[ { "answer_id": 282593, "author": "Brian", "author_id": 129437, "author_profile": "https://wordpress.stackexchange.com/users/129437", "pm_score": 0, "selected": false, "text": "<p>Try adding the following</p>\n\n<pre><code>.navigation-top {\n top: 14px;\n}\n</code></pre>\n\n<p>Should move the menu to the top of the screen although this will affect all pages.</p>\n" }, { "answer_id": 300284, "author": "Uladzislau Sauka", "author_id": 141448, "author_profile": "https://wordpress.stackexchange.com/users/141448", "pm_score": -1, "selected": false, "text": "<pre><code>@media screen and (min-width: 48em){\n .home .navigation-top {\n top: 0;\n bottom:auto;\n }\n}\n</code></pre>\n" }, { "answer_id": 405576, "author": "Phil", "author_id": 222038, "author_profile": "https://wordpress.stackexchange.com/users/222038", "pm_score": 1, "selected": false, "text": "<p>This is a two step solution:</p>\n<ol>\n<li>Install plugin &quot;Options for Twenty Seventeen&quot; (<a href=\"https://wordpress.org/plugins/options-for-twenty-seventeen/\" rel=\"nofollow noreferrer\">Link</a>)</li>\n<li>Add the following CSS to &quot;Design&quot; &gt; &quot;Customizer&quot; &gt; &quot;Additional CSS&quot;</li>\n</ol>\n<hr />\n<pre><code>.navigation-top {\n position: fixed;\n bottom: auto;\n left: 0;\n right: 0;\n top: 0;\n width: 100%;\n}\n\n.custom-header {\n padding-top: 50px;\n}\n</code></pre>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/280981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128466/" ]
I'm having quite a few problems with my WP settings. The main issue is that I need to have WP installed at //domain1.xxx/ and viewed at //domain2.xxx. It's not enough to change wp\_home and wp\_site\_url to achieve this. Since I want to remove all trace of domain1 when viewing the site at domain2 I use relative paths (courtesy of a plugin called "Remove HTTP"). The problem that remains is that some plugins still use absolute paths. One of them is Contact Form 7 which use the WP REST API. My question is: Can I redefine the REST variables so that I remove domain1 and replace it with preferable "/" or if that fails use domain2.
This is a two step solution: 1. Install plugin "Options for Twenty Seventeen" ([Link](https://wordpress.org/plugins/options-for-twenty-seventeen/)) 2. Add the following CSS to "Design" > "Customizer" > "Additional CSS" --- ``` .navigation-top { position: fixed; bottom: auto; left: 0; right: 0; top: 0; width: 100%; } .custom-header { padding-top: 50px; } ```
280,994
<p>I'm trying to sort by custom meta data for posts. The custom meta is forum_order. The posts currently only display when the value is either minus or above 0. I would like the default to be 0 so unless the user sets it it will be displayed alphabetical. </p> <pre><code>$forum_category_query = new WP_Query( array( 'post_type' =&gt; 'forums', 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'forum_order', 'order' =&gt; 'ASC', 'meta_query' =&gt; array( array( 'key' =&gt; 'forum_type', 'value' =&gt; 'category' ) ) ) ); while ( $forum_category_query-&gt;have_posts() ) : $forum_category_query-&gt;the_post(); </code></pre> <p>I have spent hours searching on Google and on here but I'm so confused! </p>
[ { "answer_id": 280997, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>try this to do a double sort.<br>\non <code>forum_order</code> first and by <code>title</code> if <code>forum_order</code> values are the same</p>\n\n<pre><code>$forum_category_query = new WP_Query( \n array( \n 'post_type' =&gt; 'forums',\n 'meta_key' =&gt; 'forum_order', \n \"orderby\" =&gt; [\n \"meta_value_num\" =&gt; \"ASC\",\n \"title\" =&gt; \"ASC\",\n ],\n 'meta_query' =&gt; array( \n array( \n 'key' =&gt; 'forum_type', \n 'value' =&gt; 'category'\n ) \n ) \n ) \n);\n</code></pre>\n" }, { "answer_id": 281006, "author": "lukgoh", "author_id": 128475, "author_profile": "https://wordpress.stackexchange.com/users/128475", "pm_score": 1, "selected": false, "text": "<p>SOLVED:</p>\n\n<p>I had this in the function to save the meta data (like an idiot!!)</p>\n\n<pre><code>if ( !$value ) delete_post_meta( $post-&gt;ID, $key ); // Delete if blank\n</code></pre>\n\n<p>So it wasn't saving the meta value if set to 0.</p>\n\n<p>I changed it to:</p>\n\n<pre><code>if ( !$value ) add_post_meta( $post-&gt;ID, $key, '0' ); // add 0 if blank\n</code></pre>\n\n<p>Simple to solve... after hours of agony. </p>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/280994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128475/" ]
I'm trying to sort by custom meta data for posts. The custom meta is forum\_order. The posts currently only display when the value is either minus or above 0. I would like the default to be 0 so unless the user sets it it will be displayed alphabetical. ``` $forum_category_query = new WP_Query( array( 'post_type' => 'forums', 'orderby' => 'meta_value_num', 'meta_key' => 'forum_order', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'forum_type', 'value' => 'category' ) ) ) ); while ( $forum_category_query->have_posts() ) : $forum_category_query->the_post(); ``` I have spent hours searching on Google and on here but I'm so confused!
SOLVED: I had this in the function to save the meta data (like an idiot!!) ``` if ( !$value ) delete_post_meta( $post->ID, $key ); // Delete if blank ``` So it wasn't saving the meta value if set to 0. I changed it to: ``` if ( !$value ) add_post_meta( $post->ID, $key, '0' ); // add 0 if blank ``` Simple to solve... after hours of agony.
280,995
<p>In my Plugin, I have an object 'Settings' (to display stuff in Wordpress settings).</p> <p><strong>Settings.php</strong></p> <pre><code>&lt;?php namespace FooNamespace\Admin\Settings; class Settings { public $menu_slug; public function __construct(){ $this-&gt;menu_slug = 'settings-'.PLUGIN_DOMAIN ; // Initialize the component $this-&gt;init(); } protected function init(){ // output method add_action( '_output_content_submenu_page_' . $this-&gt;menu_slug, array( $this, 'html_page_template' ) ); } public function html_page_template(){ include_once 'views/view-settings.php'; } } </code></pre> <p>In 'view-settings.php', I can normally use all basic wordpress functions.</p> <p><strong>view-settings.php</strong></p> <pre><code>&lt;div class="wrap"&gt; &lt;h1 class="wp-heading-inline"&gt; &lt;?php _e('Settings for '.PLUGIN_TITLE, PLUGIN_DOMAIN); ?&gt; &lt;/h1&gt; &lt;hr wp-header-end /&gt; &lt;h2 class="nav-tab-wrapper"&gt; ... &lt;/h2&gt; &lt;?php foreach ($tabs as $tab ){ ?&gt; &lt;?php include_once $tab["path"]; ?&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>But in my included file ( <code>include_once $tab["path"];</code> ), I cannot use the wordpress function like <code>__()</code> or <code>_e()</code>.</p> <p><strong>Included file</strong></p> <pre><code>&lt;form id="form-settings-recaptach" method="post"&gt; &lt;table class="widefat fixed"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;label class="label"&gt;&lt;?php _e( "Foo", PLUGIN_DOMAIN ); ?&gt;&lt;/label&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>So I get this error :</p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function _e()</p> </blockquote> <p><em><strong>Notice</strong> : if I include the child php file directly inside Settings.php, the functions are called. So It's a real problem of include inside an iclude and levels for Wordpress</em></p> <p>Why ? How can I debug this ?</p>
[ { "answer_id": 281003, "author": "Akash K.", "author_id": 124921, "author_profile": "https://wordpress.stackexchange.com/users/124921", "pm_score": 0, "selected": false, "text": "<p>I've had this problem in past</p>\n\n<p>try using <code>include</code> with <code>locate_template</code>:\nI don't exactly remember the reason but this code still works:</p>\n\n<p>Example:\n<code>include(locate_template(YOUR_TEMPLATE_PATH));</code></p>\n\n<p><a href=\"http://jeroensormani.com/how-to-add-template-files-in-your-plugin/\" rel=\"nofollow noreferrer\">Here's</a> a complete demonstration too, using the same idea, if you need more help.</p>\n\n<p><strong>For Admin Panel</strong></p>\n\n<p><code>include</code> simply works in admin panel.</p>\n\n<p>You might want to modify your code like:</p>\n\n<pre><code>public function init(){\n add_menu_page( 'Your Plugin Name' , 'Your Plugin Settings' , 'manage_options' , 'your_plugin_settings' , array( $this, 'settings_page' ) );\n}\npublic function html_page_template(){\n ob_start();\n include('views/view-settings.php');\n $html = ob_get_clean();\n echo $html;\n}\n</code></pre>\n\n<p>If the <code>init</code> function is calling your custom hook, then please don't modify it and make sure that code is working properly. Your <code>html_page_template</code> function should now output the form.</p>\n" }, { "answer_id": 281028, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": -1, "selected": true, "text": "<p>I found the problem and I have the solution :\nTo include the child file, as I'm working on localhost I changed the path :</p>\n\n<p><strong>My error :</strong></p>\n\n<pre><code> plugin_dir_path( __FILE__ ).'my-child-template.php' //&lt;-- \\path\\to\\file/my-child-template.php\n\n //Changed by\n plugin_dir_url( __FILE__ ).'my-child-template.php' //&lt;-- http://localhost/wordpress/wp-content/plugins/my-plugin/path/to/file/my-child-template.php\n</code></pre>\n\n<p>With the second path, it worked on localhost, it managed to include the template but impossible to call worpdress functions.</p>\n\n<p>So, I had to find a solution to include the path file instead of the url but with a localhost compatibility.</p>\n\n<p><strong>The solution is :</strong></p>\n\n<pre><code>public function html_page_template(){\n ob_start();\n $ipAddress = gethostbyname($_SERVER['SERVER_NAME']);\n if( $ipAddress === \"127.0.0.1\"){\n $base_path = dirname( __FILE__ ).\"\\\\templates\\\\\";\n }else{\n $base_path = plugin_dir_path( __FILE__ ).\"templates/\";\n }\n $a_settings_tab = array( \n 0 =&gt; array(\n \"key\" =&gt; \"foo\",\n \"path\" =&gt; $base_path .\"foo.php\"\n ), \n 1 =&gt; array(\n \"key\" =&gt; \"bar\",\n \"path\" =&gt; $base_path .\"bar.php\"\n )\n );\n\n include_once 'views/view-settings.php';\n $html = ob_get_clean();\n echo $html;\n}\n</code></pre>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/280995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
In my Plugin, I have an object 'Settings' (to display stuff in Wordpress settings). **Settings.php** ``` <?php namespace FooNamespace\Admin\Settings; class Settings { public $menu_slug; public function __construct(){ $this->menu_slug = 'settings-'.PLUGIN_DOMAIN ; // Initialize the component $this->init(); } protected function init(){ // output method add_action( '_output_content_submenu_page_' . $this->menu_slug, array( $this, 'html_page_template' ) ); } public function html_page_template(){ include_once 'views/view-settings.php'; } } ``` In 'view-settings.php', I can normally use all basic wordpress functions. **view-settings.php** ``` <div class="wrap"> <h1 class="wp-heading-inline"> <?php _e('Settings for '.PLUGIN_TITLE, PLUGIN_DOMAIN); ?> </h1> <hr wp-header-end /> <h2 class="nav-tab-wrapper"> ... </h2> <?php foreach ($tabs as $tab ){ ?> <?php include_once $tab["path"]; ?> <?php } ?> </div> ``` But in my included file ( `include_once $tab["path"];` ), I cannot use the wordpress function like `__()` or `_e()`. **Included file** ``` <form id="form-settings-recaptach" method="post"> <table class="widefat fixed"> <tbody> <tr> <td> <label class="label"><?php _e( "Foo", PLUGIN_DOMAIN ); ?></label> </td> </tr> </tbody> </table> </form> ``` So I get this error : > > Fatal error: Uncaught Error: Call to undefined function \_e() > > > ***Notice** : if I include the child php file directly inside Settings.php, the functions are called. So It's a real problem of include inside an iclude and levels for Wordpress* Why ? How can I debug this ?
I found the problem and I have the solution : To include the child file, as I'm working on localhost I changed the path : **My error :** ``` plugin_dir_path( __FILE__ ).'my-child-template.php' //<-- \path\to\file/my-child-template.php //Changed by plugin_dir_url( __FILE__ ).'my-child-template.php' //<-- http://localhost/wordpress/wp-content/plugins/my-plugin/path/to/file/my-child-template.php ``` With the second path, it worked on localhost, it managed to include the template but impossible to call worpdress functions. So, I had to find a solution to include the path file instead of the url but with a localhost compatibility. **The solution is :** ``` public function html_page_template(){ ob_start(); $ipAddress = gethostbyname($_SERVER['SERVER_NAME']); if( $ipAddress === "127.0.0.1"){ $base_path = dirname( __FILE__ )."\\templates\\"; }else{ $base_path = plugin_dir_path( __FILE__ )."templates/"; } $a_settings_tab = array( 0 => array( "key" => "foo", "path" => $base_path ."foo.php" ), 1 => array( "key" => "bar", "path" => $base_path ."bar.php" ) ); include_once 'views/view-settings.php'; $html = ob_get_clean(); echo $html; } ```
281,013
<p>I have an issue that I can find how to setup vertical scroll-bars but not horizontal scrollbars.</p> <p>A couple of demos are at:</p> <p><a href="https://www.w3schools.com/TagS/tag_textarea.asp" rel="nofollow noreferrer">https://www.w3schools.com/TagS/tag_textarea.asp</a> <a href="https://stackoverflow.com/questions/19292559/how-to-scroll-text-area-horizontally">https://stackoverflow.com/questions/19292559/how-to-scroll-text-area-horizontally</a></p> <p>I ran out of references. I am looking to have the box formatted within a table to handle 100% width of the table and the available height.</p>
[ { "answer_id": 281003, "author": "Akash K.", "author_id": 124921, "author_profile": "https://wordpress.stackexchange.com/users/124921", "pm_score": 0, "selected": false, "text": "<p>I've had this problem in past</p>\n\n<p>try using <code>include</code> with <code>locate_template</code>:\nI don't exactly remember the reason but this code still works:</p>\n\n<p>Example:\n<code>include(locate_template(YOUR_TEMPLATE_PATH));</code></p>\n\n<p><a href=\"http://jeroensormani.com/how-to-add-template-files-in-your-plugin/\" rel=\"nofollow noreferrer\">Here's</a> a complete demonstration too, using the same idea, if you need more help.</p>\n\n<p><strong>For Admin Panel</strong></p>\n\n<p><code>include</code> simply works in admin panel.</p>\n\n<p>You might want to modify your code like:</p>\n\n<pre><code>public function init(){\n add_menu_page( 'Your Plugin Name' , 'Your Plugin Settings' , 'manage_options' , 'your_plugin_settings' , array( $this, 'settings_page' ) );\n}\npublic function html_page_template(){\n ob_start();\n include('views/view-settings.php');\n $html = ob_get_clean();\n echo $html;\n}\n</code></pre>\n\n<p>If the <code>init</code> function is calling your custom hook, then please don't modify it and make sure that code is working properly. Your <code>html_page_template</code> function should now output the form.</p>\n" }, { "answer_id": 281028, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": -1, "selected": true, "text": "<p>I found the problem and I have the solution :\nTo include the child file, as I'm working on localhost I changed the path :</p>\n\n<p><strong>My error :</strong></p>\n\n<pre><code> plugin_dir_path( __FILE__ ).'my-child-template.php' //&lt;-- \\path\\to\\file/my-child-template.php\n\n //Changed by\n plugin_dir_url( __FILE__ ).'my-child-template.php' //&lt;-- http://localhost/wordpress/wp-content/plugins/my-plugin/path/to/file/my-child-template.php\n</code></pre>\n\n<p>With the second path, it worked on localhost, it managed to include the template but impossible to call worpdress functions.</p>\n\n<p>So, I had to find a solution to include the path file instead of the url but with a localhost compatibility.</p>\n\n<p><strong>The solution is :</strong></p>\n\n<pre><code>public function html_page_template(){\n ob_start();\n $ipAddress = gethostbyname($_SERVER['SERVER_NAME']);\n if( $ipAddress === \"127.0.0.1\"){\n $base_path = dirname( __FILE__ ).\"\\\\templates\\\\\";\n }else{\n $base_path = plugin_dir_path( __FILE__ ).\"templates/\";\n }\n $a_settings_tab = array( \n 0 =&gt; array(\n \"key\" =&gt; \"foo\",\n \"path\" =&gt; $base_path .\"foo.php\"\n ), \n 1 =&gt; array(\n \"key\" =&gt; \"bar\",\n \"path\" =&gt; $base_path .\"bar.php\"\n )\n );\n\n include_once 'views/view-settings.php';\n $html = ob_get_clean();\n echo $html;\n}\n</code></pre>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/281013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126081/" ]
I have an issue that I can find how to setup vertical scroll-bars but not horizontal scrollbars. A couple of demos are at: <https://www.w3schools.com/TagS/tag_textarea.asp> <https://stackoverflow.com/questions/19292559/how-to-scroll-text-area-horizontally> I ran out of references. I am looking to have the box formatted within a table to handle 100% width of the table and the available height.
I found the problem and I have the solution : To include the child file, as I'm working on localhost I changed the path : **My error :** ``` plugin_dir_path( __FILE__ ).'my-child-template.php' //<-- \path\to\file/my-child-template.php //Changed by plugin_dir_url( __FILE__ ).'my-child-template.php' //<-- http://localhost/wordpress/wp-content/plugins/my-plugin/path/to/file/my-child-template.php ``` With the second path, it worked on localhost, it managed to include the template but impossible to call worpdress functions. So, I had to find a solution to include the path file instead of the url but with a localhost compatibility. **The solution is :** ``` public function html_page_template(){ ob_start(); $ipAddress = gethostbyname($_SERVER['SERVER_NAME']); if( $ipAddress === "127.0.0.1"){ $base_path = dirname( __FILE__ )."\\templates\\"; }else{ $base_path = plugin_dir_path( __FILE__ )."templates/"; } $a_settings_tab = array( 0 => array( "key" => "foo", "path" => $base_path ."foo.php" ), 1 => array( "key" => "bar", "path" => $base_path ."bar.php" ) ); include_once 'views/view-settings.php'; $html = ob_get_clean(); echo $html; } ```
281,031
<p>I want to add a dynamic page for every page that has URL subpage of "/team".</p> <p>How would I configure "add_rewrite_rule" regex expression to allow me that?</p> <p>Example:</p> <pre><code>path: http://page.com/business/team rewrite: http://page.com/index.php?department-team=business path: http://page.com/hr/team rewrite: http://page.com/index.php?department-team=hr </code></pre> <p>Code I'm working with:</p> <pre><code>add_action('query_vars', 'department_team_add_query_vars'); add_action('init', 'department_team_add_rewrite_rules'); add_filter('template_include', 'department_team_template_include'); function department_team_add_query_vars($vars) { $vars[] = 'department-team'; return $vars; } function department_team_add_rewrite_rules() { // do I need this? //add_rewrite_tag('%department-team%', '([^&amp;]+)'); // rewrite url to add_rewrite_rule( '/([^/]*)/team', 'index.php?department-team=$matches[1]', 'top' ); } function department_team_template_include($template) { global $wp_query; $new_template = ''; var_dump(array_key_exists('department-team', $wp_query-&gt;query_vars)); var_dump($wp_query-&gt;query_vars); if (array_key_exists('department-team', $wp_query-&gt;query_vars)) { switch ($wp_query-&gt;query_vars['department-team']) { case 'team': $new_template = locate_template(['department_team.php']); break; } if ($new_template != '') { var_dump('aaa'); die(); return $new_template; } else { $wp_query-&gt;set_404(); status_header(404); return get_404_template(); } } return $template; } </code></pre>
[ { "answer_id": 281032, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p>Use <code>add_rewrite_endpoint</code> instead, it generates the rules for you.</p>\n\n<pre><code>add_rewrite_endpoint( 'team', EP_PAGES );\n</code></pre>\n" }, { "answer_id": 281049, "author": "scytale", "author_id": 128374, "author_profile": "https://wordpress.stackexchange.com/users/128374", "pm_score": 1, "selected": false, "text": "<p>I do something similar. I have a page (country_tc) that uses a custom page template that either dynamically generates info for requested country, or a series of sub-pages for the country e.g.</p>\n\n<p><code>/country/Egypt</code> (<em>index.php?pagename=country&amp;countrytc=egypt</em>)</p>\n\n<p><code>/country/egypt/safety</code> (<em>index.php?pagename=country&amp;countrytc=egypt/safety</em>)</p>\n\n<p>I use <strong>page_rewrite_rules</strong> for the re-write. I've not had time to vet your code, so this is how I'd do it: </p>\n\n<p>In a site functions <strong>plugin</strong>:</p>\n\n<pre><code>// allow WP to store querystring attribs for use in our pages\nfunction tc_query_vars_filter($vars) {\n $vars[] = 'department-team';\n $vars[] .= 'another-var';\n return $vars;\n}\nadd_filter( 'query_vars', 'tc_query_vars_filter' );\n\nfunction tc_rewrite_rules($rules) {\n global $wp_rewrite;\n $tc_rule = array(\n // working example from my site\n 'country/(.+)/?' =&gt; 'index.php?pagename=' . 'country' . '&amp;countrytc=$matches[1]',\n // YOUR rule (not tested)\n '/([^/]*)/team', 'index.php?pagename=YOURPAGENAME&amp;department-team=$matches[1]'\n );\n return array_merge($tc_rule, $rules);\n}\nadd_filter('page_rewrite_rules', 'tc_rewrite_rules');\n</code></pre>\n\n<p><strong>AFTER ACTIVATING PLUGIN YOU NEED TO RE-SAVE PERMALINKS ON DASHBOARD - THIS WILL FLUSH/UPDATE YOUR REWRITE RULES</strong></p>\n\n<p>Do the rest of your code <strong>in your custom page</strong> using:</p>\n\n<p><code>get_query_var('department-team')</code> - sanitize, validate do your includes as required.</p>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/281031", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80191/" ]
I want to add a dynamic page for every page that has URL subpage of "/team". How would I configure "add\_rewrite\_rule" regex expression to allow me that? Example: ``` path: http://page.com/business/team rewrite: http://page.com/index.php?department-team=business path: http://page.com/hr/team rewrite: http://page.com/index.php?department-team=hr ``` Code I'm working with: ``` add_action('query_vars', 'department_team_add_query_vars'); add_action('init', 'department_team_add_rewrite_rules'); add_filter('template_include', 'department_team_template_include'); function department_team_add_query_vars($vars) { $vars[] = 'department-team'; return $vars; } function department_team_add_rewrite_rules() { // do I need this? //add_rewrite_tag('%department-team%', '([^&]+)'); // rewrite url to add_rewrite_rule( '/([^/]*)/team', 'index.php?department-team=$matches[1]', 'top' ); } function department_team_template_include($template) { global $wp_query; $new_template = ''; var_dump(array_key_exists('department-team', $wp_query->query_vars)); var_dump($wp_query->query_vars); if (array_key_exists('department-team', $wp_query->query_vars)) { switch ($wp_query->query_vars['department-team']) { case 'team': $new_template = locate_template(['department_team.php']); break; } if ($new_template != '') { var_dump('aaa'); die(); return $new_template; } else { $wp_query->set_404(); status_header(404); return get_404_template(); } } return $template; } ```
I do something similar. I have a page (country\_tc) that uses a custom page template that either dynamically generates info for requested country, or a series of sub-pages for the country e.g. `/country/Egypt` (*index.php?pagename=country&countrytc=egypt*) `/country/egypt/safety` (*index.php?pagename=country&countrytc=egypt/safety*) I use **page\_rewrite\_rules** for the re-write. I've not had time to vet your code, so this is how I'd do it: In a site functions **plugin**: ``` // allow WP to store querystring attribs for use in our pages function tc_query_vars_filter($vars) { $vars[] = 'department-team'; $vars[] .= 'another-var'; return $vars; } add_filter( 'query_vars', 'tc_query_vars_filter' ); function tc_rewrite_rules($rules) { global $wp_rewrite; $tc_rule = array( // working example from my site 'country/(.+)/?' => 'index.php?pagename=' . 'country' . '&countrytc=$matches[1]', // YOUR rule (not tested) '/([^/]*)/team', 'index.php?pagename=YOURPAGENAME&department-team=$matches[1]' ); return array_merge($tc_rule, $rules); } add_filter('page_rewrite_rules', 'tc_rewrite_rules'); ``` **AFTER ACTIVATING PLUGIN YOU NEED TO RE-SAVE PERMALINKS ON DASHBOARD - THIS WILL FLUSH/UPDATE YOUR REWRITE RULES** Do the rest of your code **in your custom page** using: `get_query_var('department-team')` - sanitize, validate do your includes as required.
281,058
<p>in my web I have a button (.x-btn.widgetbar) that displays a section of widgets in the upper right as in this <a href="http://demo.theme.co/integrity-1/" rel="nofollow noreferrer">example</a>.</p> <p>I have modified the icon to change based on whether the user is registered or not, I would like that when the user is not logged in redirect to a login page instead of displaying the widgetbar.</p> <p>I'm new to this and I do not know where to start, I've consulted in several forums and I think I could find the code but I do not know what file to edit, I've been trying for weeks but I can not apologize in advance for the query.</p> <p>I try this function in functions.php but doesnt works..</p> <pre><code>function wp_redirect_NotLogin () { if( isset($_POST['x-btn-widgetbar']) &amp;&amp; ! is_user_logged_in() ) { wp_redirect( home_url( '/register/' ) ); exit(); } } </code></pre>
[ { "answer_id": 281063, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 2, "selected": true, "text": "<p>when you want interaction between client side and server side you should use ajax .</p>\n\n<p>i think this <a href=\"https://wordpress.stackexchange.com/questions/69814/check-if-user-is-logged-in-using-jquery\">Link</a> will be very helpful to you :)\nPut this in your javascript</p>\n\n<pre><code>var data = {\n action: 'is_user_logged_in'\n};\njquery.('.x-btn-widgetbar').on('click',function(){\n jQuery.post(ajaxurl, data, function(response) {\n if(response == 'yes') {\n // user is logged in, do your stuff here\n } else {\n // user is not logged in, show login form here\n window.location = &lt;login url here &gt;;\n\n }\n });\n});\n</code></pre>\n\n<p>put this in your functions.php</p>\n\n<pre><code>function ajax_check_user_logged_in() {\n echo is_user_logged_in()?'yes':'no';\n die();\n}\nadd_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');\nadd_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');\n</code></pre>\n\n<p>Update #1 26-9-2017</p>\n\n<p>and if you want widgetbar to hide you can use this jquery :</p>\n\n<pre><code>jquery('.x-widgetbar').hide();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>jquery('.x-widgetbar').css({display:'none'});\n</code></pre>\n\n<p>or simplay put this in *.css file:</p>\n\n<pre><code>.x-widgetbar{display:'none'}\n</code></pre>\n\n<p>update#2 26-9-2017</p>\n\n<p>if want only hide the widgetbar without hiding the x button it self you can replace .x-widgetbar by .x-widgetbar-inner</p>\n" }, { "answer_id": 281094, "author": "Parthavi Patel", "author_id": 110795, "author_profile": "https://wordpress.stackexchange.com/users/110795", "pm_score": 1, "selected": false, "text": "<p><strong>just checking the body for logged-in class</strong></p>\n\n<pre><code>if( jQuery('body').hasClass('logged-in') ) {\n// do something\n} \n</code></pre>\n" }, { "answer_id": 281145, "author": "wpecko", "author_id": 128506, "author_profile": "https://wordpress.stackexchange.com/users/128506", "pm_score": 0, "selected": false, "text": "<p>Thanks all for your help, Ibrahim youre great!!</p>\n\n<p>Finally I got it to work as I wanted, so I close the post and leave what has worked for me if someone can at some point take advantage of it.</p>\n\n<p>I try with the code that you provide me in Javascript:</p>\n\n<pre><code>var data = {\n action: 'is_user_logged_in'\n};\n\njQuery('.x-btn-widgetbar').on('click', function() { \n\n jQuery.post(ajaxurl, data, function(response) {\n if(response == 'yes') {\n // user is logged in, do your stuff here\n\n } else {\n // user is not logged in, show login form here\n jQuery('.x-widgetbar').hide();\n window.location.href='https://website.com/login';\n }\n });\n\n});\n</code></pre>\n\n<p>And this in functions.php:</p>\n\n<pre><code>function ajax_check_user_logged_in() {\n echo is_user_logged_in()?'yes':'no';\n die();\n}\nadd_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');\nadd_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');\n</code></pre>\n\n<p>This code does exactly what I wanted but I had a slight delay in responding by taking a few seconds to redirect and sending an alert that I did not add in the code.</p>\n\n<p>I've tried what Samuel and Parthavi (thanks a lot!) wrote and put this code in Javascript:</p>\n\n<pre><code>jQuery('.x-btn-widgetbar').on('click', function() {\n\n if(jQuery('body').hasClass('logged-in') ) {\n\n } else {\n jQuery('.x-widgetbar').hide();\n window.location.href='https://website.com/login';\n }\n\n});\n</code></pre>\n\n<p>With this code the behavior is the same and works well, but the response is faster and prevents small delays.</p>\n\n<p>If you see some way to debug the code or see something that would help me avoid problems I would appreciate it since I am not an expert in javascript.</p>\n\n<p>Thanks in advance for all your help, I hope everything goes well for you.</p>\n" } ]
2017/09/25
[ "https://wordpress.stackexchange.com/questions/281058", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128506/" ]
in my web I have a button (.x-btn.widgetbar) that displays a section of widgets in the upper right as in this [example](http://demo.theme.co/integrity-1/). I have modified the icon to change based on whether the user is registered or not, I would like that when the user is not logged in redirect to a login page instead of displaying the widgetbar. I'm new to this and I do not know where to start, I've consulted in several forums and I think I could find the code but I do not know what file to edit, I've been trying for weeks but I can not apologize in advance for the query. I try this function in functions.php but doesnt works.. ``` function wp_redirect_NotLogin () { if( isset($_POST['x-btn-widgetbar']) && ! is_user_logged_in() ) { wp_redirect( home_url( '/register/' ) ); exit(); } } ```
when you want interaction between client side and server side you should use ajax . i think this [Link](https://wordpress.stackexchange.com/questions/69814/check-if-user-is-logged-in-using-jquery) will be very helpful to you :) Put this in your javascript ``` var data = { action: 'is_user_logged_in' }; jquery.('.x-btn-widgetbar').on('click',function(){ jQuery.post(ajaxurl, data, function(response) { if(response == 'yes') { // user is logged in, do your stuff here } else { // user is not logged in, show login form here window.location = <login url here >; } }); }); ``` put this in your functions.php ``` function ajax_check_user_logged_in() { echo is_user_logged_in()?'yes':'no'; die(); } add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in'); add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in'); ``` Update #1 26-9-2017 and if you want widgetbar to hide you can use this jquery : ``` jquery('.x-widgetbar').hide(); ``` or ``` jquery('.x-widgetbar').css({display:'none'}); ``` or simplay put this in \*.css file: ``` .x-widgetbar{display:'none'} ``` update#2 26-9-2017 if want only hide the widgetbar without hiding the x button it self you can replace .x-widgetbar by .x-widgetbar-inner
281,068
<pre><code>wp_register_script( $handle, $src, $deps, $ver, $in_footer ); </code></pre> <p>If <code>$ver</code> is not required then should we leave that space blank? or completely remove the commas?</p> <p>Example →</p> <pre><code>wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', array( 'jquery' ), '1.1', true ); </code></pre> <p>There is no dependency on JQuery. this needs to be removed entirely:</p> <pre><code>, array( 'jquery' ), </code></pre> <p>or leave it blank like this →</p> <pre><code> wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', , '1.1', true ); </code></pre>
[ { "answer_id": 281069, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 0, "selected": false, "text": "<p>you cant leave it empty, at least you have to put an empty string <code>''</code>, it will default the dependency to <code>array()</code> and the version to <code>false</code>:</p>\n\n<pre><code>wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', '','' , true );\n</code></pre>\n\n<p>for readability you can, and its used widely:</p>\n\n<pre><code>wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', array(), null , true );\n</code></pre>\n\n<p>with would be just the same.</p>\n" }, { "answer_id": 281070, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Simply pass in <code>null</code> or the empty equivalent.</p>\n\n<p>For example, if you don't depend on anything, say so. It's expecting an array of the dependencies, so pass an empty array <code>array()</code></p>\n\n<p>Or pass in <code>null</code></p>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281068", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ``` If `$ver` is not required then should we leave that space blank? or completely remove the commas? Example → ``` wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', array( 'jquery' ), '1.1', true ); ``` There is no dependency on JQuery. this needs to be removed entirely: ``` , array( 'jquery' ), ``` or leave it blank like this → ``` wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', , '1.1', true ); ```
Simply pass in `null` or the empty equivalent. For example, if you don't depend on anything, say so. It's expecting an array of the dependencies, so pass an empty array `array()` Or pass in `null`
281,081
<p>Contributors loses the ability to edit their posts after one admin approves their post. </p> <p>I'd like to know how can I add the capability of them to edit their posts, even after admin approval or admin edit. I don't want to use any plugin for that..</p> <p><a href="https://i.stack.imgur.com/vlq7L.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vlq7L.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 281082, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>Author role provides this functionality by default.\nElse you can use any user role editor plugin to customize capabilities</p>\n" }, { "answer_id": 295531, "author": "Kedves Hunor", "author_id": 137773, "author_profile": "https://wordpress.stackexchange.com/users/137773", "pm_score": 2, "selected": false, "text": "<p>You need to add a the <code>edit_published_posts</code> capability for the <code>contributor</code> role in the <code>functions.php</code></p>\n\n<pre><code>add_filter('init', function () {\n $role = get_role('contributor');\n $role-&gt;add_cap('edit_published_posts');\n});\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102182/" ]
Contributors loses the ability to edit their posts after one admin approves their post. I'd like to know how can I add the capability of them to edit their posts, even after admin approval or admin edit. I don't want to use any plugin for that.. [![enter image description here](https://i.stack.imgur.com/vlq7L.jpg)](https://i.stack.imgur.com/vlq7L.jpg)
You need to add a the `edit_published_posts` capability for the `contributor` role in the `functions.php` ``` add_filter('init', function () { $role = get_role('contributor'); $role->add_cap('edit_published_posts'); }); ```
281,088
<p>I have been trying but its not working.</p> <p>but if i try </p> <pre><code>&lt;?php echo do_shortcode("[mimo]"); ?&gt; &lt;?php echo do_shortcode("[mibaby]"); ?&gt; </code></pre> <p>it will work fine.</p> <p>But to apply it in post content using <code>[mimo] [mibaby]</code></p> <p>it won't work.</p> <p>Here is the Functions i am using...</p> <pre><code>function wpb_custom_new_menuw() { remove_filter( 'the_content', 'wpautop' ); } add_shortcode('mibaby', 'wpb_custom_new_menuw'); function wpb_custom_new_menu() { remove_filter( 'the_excerpt', 'wpautop' ); } add_shortcode('mimo', 'wpb_custom_new_menu'); </code></pre>
[ { "answer_id": 281082, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>Author role provides this functionality by default.\nElse you can use any user role editor plugin to customize capabilities</p>\n" }, { "answer_id": 295531, "author": "Kedves Hunor", "author_id": 137773, "author_profile": "https://wordpress.stackexchange.com/users/137773", "pm_score": 2, "selected": false, "text": "<p>You need to add a the <code>edit_published_posts</code> capability for the <code>contributor</code> role in the <code>functions.php</code></p>\n\n<pre><code>add_filter('init', function () {\n $role = get_role('contributor');\n $role-&gt;add_cap('edit_published_posts');\n});\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128516/" ]
I have been trying but its not working. but if i try ``` <?php echo do_shortcode("[mimo]"); ?> <?php echo do_shortcode("[mibaby]"); ?> ``` it will work fine. But to apply it in post content using `[mimo] [mibaby]` it won't work. Here is the Functions i am using... ``` function wpb_custom_new_menuw() { remove_filter( 'the_content', 'wpautop' ); } add_shortcode('mibaby', 'wpb_custom_new_menuw'); function wpb_custom_new_menu() { remove_filter( 'the_excerpt', 'wpautop' ); } add_shortcode('mimo', 'wpb_custom_new_menu'); ```
You need to add a the `edit_published_posts` capability for the `contributor` role in the `functions.php` ``` add_filter('init', function () { $role = get_role('contributor'); $role->add_cap('edit_published_posts'); }); ```
281,093
<p>I would like to have my index or <a href="https://publiqly.com/blog/" rel="nofollow noreferrer">posts overview page</a> load each post teaser starting at char 206 of each post's body content. This as all posts start with a general introduction in the post body content that is the same. To load that on the index.php teaser is useless information. </p> <p>With <code>get_the_post</code> I managed to load content but the <code>substr</code> does not work as it should. It filter the content for the page. Not for the content of each page (body text).</p> <p>Here is the code:</p> <pre><code>&lt;?php /* Template name: Blog Page */ get_header(); the_post(); ?&gt; &lt;div class="grid-container blog" id="main-container"&gt; &lt;div class="grid-100 mobile-grid-100 nopadding" id="normal-content-wrap"&gt; &lt;h1&gt;&lt;?php the_title();?&gt;&lt;/h1&gt; &lt;?php $content = apply_filters( 'the_content', get_the_content() ); //$content = strip_tags($content); echo substr($content, 200, 20); echo $content; //the_content();?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>As you can see I commented out the <code>strip_tags</code> as I realized the formatting is fine. I do not want to loose the formatting. I just want each individual post to show a piece of that post starting at char x. How can this be done?</p>
[ { "answer_id": 281082, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>Author role provides this functionality by default.\nElse you can use any user role editor plugin to customize capabilities</p>\n" }, { "answer_id": 295531, "author": "Kedves Hunor", "author_id": 137773, "author_profile": "https://wordpress.stackexchange.com/users/137773", "pm_score": 2, "selected": false, "text": "<p>You need to add a the <code>edit_published_posts</code> capability for the <code>contributor</code> role in the <code>functions.php</code></p>\n\n<pre><code>add_filter('init', function () {\n $role = get_role('contributor');\n $role-&gt;add_cap('edit_published_posts');\n});\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12260/" ]
I would like to have my index or [posts overview page](https://publiqly.com/blog/) load each post teaser starting at char 206 of each post's body content. This as all posts start with a general introduction in the post body content that is the same. To load that on the index.php teaser is useless information. With `get_the_post` I managed to load content but the `substr` does not work as it should. It filter the content for the page. Not for the content of each page (body text). Here is the code: ``` <?php /* Template name: Blog Page */ get_header(); the_post(); ?> <div class="grid-container blog" id="main-container"> <div class="grid-100 mobile-grid-100 nopadding" id="normal-content-wrap"> <h1><?php the_title();?></h1> <?php $content = apply_filters( 'the_content', get_the_content() ); //$content = strip_tags($content); echo substr($content, 200, 20); echo $content; //the_content();?> </div> </div> <?php get_footer(); ?> ``` As you can see I commented out the `strip_tags` as I realized the formatting is fine. I do not want to loose the formatting. I just want each individual post to show a piece of that post starting at char x. How can this be done?
You need to add a the `edit_published_posts` capability for the `contributor` role in the `functions.php` ``` add_filter('init', function () { $role = get_role('contributor'); $role->add_cap('edit_published_posts'); }); ```
281,102
<p>I am using the default WordPress embed to embed a couple of videos in the content. </p> <p>I want to extract the video link from <code>[embed]https://www.youtube.com/watch?v=Z9QbYZh1YXY[/embed]</code>, can anyone help with the regex?</p>
[ { "answer_id": 281082, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>Author role provides this functionality by default.\nElse you can use any user role editor plugin to customize capabilities</p>\n" }, { "answer_id": 295531, "author": "Kedves Hunor", "author_id": 137773, "author_profile": "https://wordpress.stackexchange.com/users/137773", "pm_score": 2, "selected": false, "text": "<p>You need to add a the <code>edit_published_posts</code> capability for the <code>contributor</code> role in the <code>functions.php</code></p>\n\n<pre><code>add_filter('init', function () {\n $role = get_role('contributor');\n $role-&gt;add_cap('edit_published_posts');\n});\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281102", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am using the default WordPress embed to embed a couple of videos in the content. I want to extract the video link from `[embed]https://www.youtube.com/watch?v=Z9QbYZh1YXY[/embed]`, can anyone help with the regex?
You need to add a the `edit_published_posts` capability for the `contributor` role in the `functions.php` ``` add_filter('init', function () { $role = get_role('contributor'); $role->add_cap('edit_published_posts'); }); ```
281,127
<p>Here I created a custom profile page based on the current logged user to check only his own data inserted in a custom database.</p> <p>You can see that in every row, I added a button "Delete" missing the appropriate code.</p> <p>Everything is working well except that part where I want to add a function to Delete the record. Maybe $wpdb->delete() solves my problem.</p> <p>This is my code:</p> <pre><code>if ( is_user_logged_in() ) { global $wpdb; $current_user = wp_get_current_user(); $username = $current_user-&gt;user_login; $reservations = $wpdb-&gt;get_results($wpdb-&gt;prepare("SELECT * FROM SaveContactForm7_1 WHERE user = %s", $username)); echo "&lt;div align='center'&gt;"; echo "&lt;table class='responsive-table'&gt;"; echo "&lt;caption&gt;Liste des r&amp;eacute;servations&lt;/caption&gt;"; echo "&lt;thead&gt;"; echo "&lt;tr&gt;"; echo "&lt;th scope='col'&gt;Nom&lt;/th&gt;"; echo "&lt;th scope='col'&gt;ID&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Qualit&amp;eacute;&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Arriv&amp;eacute;e&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Num Vol&lt;/th&gt;"; echo "&lt;th scope='col'&gt;H. Att&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Prov&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Depart&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Num Vol&lt;/th&gt;"; echo "&lt;th scope='col'&gt;H. Decl&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Dest&lt;/th&gt;"; echo "&lt;th scope='col'&gt;H&amp;ocirc;tel&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Chambre&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Total&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Modifier&lt;/th&gt;"; echo "&lt;th scope='col'&gt;Effacer&lt;/th&gt;"; echo "&lt;/tr&gt;"; echo "&lt;/thead&gt;"; foreach($reservations as $reservation){ echo "&lt;tbody&gt;"; echo "&lt;tr&gt;"; echo "&lt;th scope='row'&gt;".$reservation-&gt;nom."&lt;/th&gt;"; echo "&lt;td data-title='ID'&gt;".$reservation-&gt;user."&lt;/td&gt;"; echo "&lt;td data-title='Qualit&amp;eacute;'&gt;".$reservation-&gt;qualite."&lt;/td&gt;"; echo "&lt;td data-title='Arriv&amp;eacute;e'&gt;".$reservation-&gt;datearrivee."&lt;/td&gt;"; echo "&lt;td data-title='N&amp;#176; Vol'&gt;".$reservation-&gt;num_vol_arrivee."&lt;/td&gt;"; echo "&lt;td data-title='Atterrissage'&gt;".$reservation-&gt;heure_atterrissage." &lt;/td&gt;"; echo "&lt;td data-title='Provenance'&gt;".$reservation-&gt;provenance."&lt;/td&gt;"; echo "&lt;td data-title='D&amp;eacute;part'&gt;".$reservation-&gt;datedepart."&lt;/td&gt;"; echo "&lt;td data-title='N&amp;#176; VOL'&gt;".$reservation-&gt;num_vol_depart."&lt;/td&gt;"; echo "&lt;td data-title='D&amp;eacute;collage'&gt;".$reservation-&gt;heure_decollage." &lt;/td&gt;"; echo "&lt;td data-title='D&amp;eacute;stination'&gt;".$reservation-&gt;destination." &lt;/td&gt;"; echo "&lt;td data-title='Choix'&gt;".$reservation-&gt;choix."&lt;/td&gt;"; echo "&lt;td data-title='Chambre'&gt;".$reservation-&gt;typech."&lt;/td&gt;"; echo "&lt;td data-title='Prix Total' data-type='currency'&gt;".$reservation- &gt;calculated_choix."&lt;/td&gt;"; </code></pre> <p>And here the "Delete" part:</p> <pre><code>echo "&lt;td align='center'&gt; &lt;***I need the code here "input" or "a href" ***&gt;&lt;img class='icon' width='16' height='16' src='../remove-icon.png' alt='Delete' title='Delete'&gt;&lt;/a&gt; &lt;/td&gt;"; echo "&lt;/tr&gt;"; echo "&lt;/tbody&gt;"; } echo "&lt;/table&gt;"; echo "&lt;/div&gt;"; } </code></pre>
[ { "answer_id": 281150, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>client side -> user click delete button/link</p></li>\n<li><p>AJAX ->send this action from client side to server side to run php function delete corresponding raw from database .</p></li>\n<li><p>server side->function to delete raw from database <code>$wpdb-&gt;delete()</code></p></li>\n<li><p>AJAX success ->hide this raw from client page and update this only part of page</p></li>\n</ul>\n\n<p>check that <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">link</a> </p>\n" }, { "answer_id": 281153, "author": "Prince J", "author_id": 105584, "author_profile": "https://wordpress.stackexchange.com/users/105584", "pm_score": 2, "selected": true, "text": "<p>Yes, you can use wpdb to delete the record in the custom table. Something like this in the wordpress function.</p>\n\n<pre><code>require_once ('../../../../wp-load.php');\n\nif (!empty($_POST['id'])) {\n\n global $wpdb;\n\n $table='table_name';\n $id = $_POST['id'];\n $wpdb-&gt;delete( $table, array( 'id' =&gt; $id ) );\n\n}\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126576/" ]
Here I created a custom profile page based on the current logged user to check only his own data inserted in a custom database. You can see that in every row, I added a button "Delete" missing the appropriate code. Everything is working well except that part where I want to add a function to Delete the record. Maybe $wpdb->delete() solves my problem. This is my code: ``` if ( is_user_logged_in() ) { global $wpdb; $current_user = wp_get_current_user(); $username = $current_user->user_login; $reservations = $wpdb->get_results($wpdb->prepare("SELECT * FROM SaveContactForm7_1 WHERE user = %s", $username)); echo "<div align='center'>"; echo "<table class='responsive-table'>"; echo "<caption>Liste des r&eacute;servations</caption>"; echo "<thead>"; echo "<tr>"; echo "<th scope='col'>Nom</th>"; echo "<th scope='col'>ID</th>"; echo "<th scope='col'>Qualit&eacute;</th>"; echo "<th scope='col'>Arriv&eacute;e</th>"; echo "<th scope='col'>Num Vol</th>"; echo "<th scope='col'>H. Att</th>"; echo "<th scope='col'>Prov</th>"; echo "<th scope='col'>Depart</th>"; echo "<th scope='col'>Num Vol</th>"; echo "<th scope='col'>H. Decl</th>"; echo "<th scope='col'>Dest</th>"; echo "<th scope='col'>H&ocirc;tel</th>"; echo "<th scope='col'>Chambre</th>"; echo "<th scope='col'>Total</th>"; echo "<th scope='col'>Modifier</th>"; echo "<th scope='col'>Effacer</th>"; echo "</tr>"; echo "</thead>"; foreach($reservations as $reservation){ echo "<tbody>"; echo "<tr>"; echo "<th scope='row'>".$reservation->nom."</th>"; echo "<td data-title='ID'>".$reservation->user."</td>"; echo "<td data-title='Qualit&eacute;'>".$reservation->qualite."</td>"; echo "<td data-title='Arriv&eacute;e'>".$reservation->datearrivee."</td>"; echo "<td data-title='N&#176; Vol'>".$reservation->num_vol_arrivee."</td>"; echo "<td data-title='Atterrissage'>".$reservation->heure_atterrissage." </td>"; echo "<td data-title='Provenance'>".$reservation->provenance."</td>"; echo "<td data-title='D&eacute;part'>".$reservation->datedepart."</td>"; echo "<td data-title='N&#176; VOL'>".$reservation->num_vol_depart."</td>"; echo "<td data-title='D&eacute;collage'>".$reservation->heure_decollage." </td>"; echo "<td data-title='D&eacute;stination'>".$reservation->destination." </td>"; echo "<td data-title='Choix'>".$reservation->choix."</td>"; echo "<td data-title='Chambre'>".$reservation->typech."</td>"; echo "<td data-title='Prix Total' data-type='currency'>".$reservation- >calculated_choix."</td>"; ``` And here the "Delete" part: ``` echo "<td align='center'> <***I need the code here "input" or "a href" ***><img class='icon' width='16' height='16' src='../remove-icon.png' alt='Delete' title='Delete'></a> </td>"; echo "</tr>"; echo "</tbody>"; } echo "</table>"; echo "</div>"; } ```
Yes, you can use wpdb to delete the record in the custom table. Something like this in the wordpress function. ``` require_once ('../../../../wp-load.php'); if (!empty($_POST['id'])) { global $wpdb; $table='table_name'; $id = $_POST['id']; $wpdb->delete( $table, array( 'id' => $id ) ); } ```
281,134
<p>I am using a customised archive template for a custom post type.</p> <p>At the top of the page, I'd like to show a specific post, found using a new <code>wp_query()</code> call.</p> <pre><code>$args = [ 'posts_per_page' =&gt; 1, 'post_type' =&gt; 'document', 'order' =&gt; 'DESC', 'orderby' =&gt; 'date', ]; $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); the_title(); the_date( 'F Y' ); } wp_reset_postdata(); } </code></pre> <p>Custom search form</p> <pre><code>&lt;form id="document-filter" method="post"&gt; &lt;select name="order_by"&gt; &lt;option value="date"&gt;Date&lt;/option&gt; &lt;option value="title"&gt;Name&lt;/option&gt; &lt;/select&gt; &lt;select name="order"&gt; &lt;option value="desc"&gt;DESC&lt;/option&gt; &lt;option value="asc"&gt;ASC&lt;/option&gt; &lt;/select&gt; &lt;input name="s" type="text" placeholder="Filter by keyword" value=""/&gt; &lt;input name="post_type" type="hidden" value="document"/&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>Initially, it works. However, if I then use the custom search form to either sort the archive list (date/name, asc/desc), the custom <code>wp_query()</code> is affected, and the <code>query_vars</code> array is overriding my supplied arguments.</p> <p>Example</p> <p>Posts, in date order, descending:</p> <ol> <li>Post C</li> <li>Post B</li> <li>Post A</li> </ol> <p>Initially, my custom query at the top of the page will output <code>Post C</code>, which is correct.</p> <p>If I use the search/filter form to change the order of the posts to:</p> <ol> <li>Post A</li> <li>Post B</li> <li>Post C</li> </ol> <p>The singular queried post will now be <code>Post A</code>, which is incorrect. My custom query args have not changed, but are being overridden by the search form somehow.</p>
[ { "answer_id": 281150, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>client side -> user click delete button/link</p></li>\n<li><p>AJAX ->send this action from client side to server side to run php function delete corresponding raw from database .</p></li>\n<li><p>server side->function to delete raw from database <code>$wpdb-&gt;delete()</code></p></li>\n<li><p>AJAX success ->hide this raw from client page and update this only part of page</p></li>\n</ul>\n\n<p>check that <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">link</a> </p>\n" }, { "answer_id": 281153, "author": "Prince J", "author_id": 105584, "author_profile": "https://wordpress.stackexchange.com/users/105584", "pm_score": 2, "selected": true, "text": "<p>Yes, you can use wpdb to delete the record in the custom table. Something like this in the wordpress function.</p>\n\n<pre><code>require_once ('../../../../wp-load.php');\n\nif (!empty($_POST['id'])) {\n\n global $wpdb;\n\n $table='table_name';\n $id = $_POST['id'];\n $wpdb-&gt;delete( $table, array( 'id' =&gt; $id ) );\n\n}\n</code></pre>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127925/" ]
I am using a customised archive template for a custom post type. At the top of the page, I'd like to show a specific post, found using a new `wp_query()` call. ``` $args = [ 'posts_per_page' => 1, 'post_type' => 'document', 'order' => 'DESC', 'orderby' => 'date', ]; $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); the_title(); the_date( 'F Y' ); } wp_reset_postdata(); } ``` Custom search form ``` <form id="document-filter" method="post"> <select name="order_by"> <option value="date">Date</option> <option value="title">Name</option> </select> <select name="order"> <option value="desc">DESC</option> <option value="asc">ASC</option> </select> <input name="s" type="text" placeholder="Filter by keyword" value=""/> <input name="post_type" type="hidden" value="document"/> <input type="submit" /> </form> ``` Initially, it works. However, if I then use the custom search form to either sort the archive list (date/name, asc/desc), the custom `wp_query()` is affected, and the `query_vars` array is overriding my supplied arguments. Example Posts, in date order, descending: 1. Post C 2. Post B 3. Post A Initially, my custom query at the top of the page will output `Post C`, which is correct. If I use the search/filter form to change the order of the posts to: 1. Post A 2. Post B 3. Post C The singular queried post will now be `Post A`, which is incorrect. My custom query args have not changed, but are being overridden by the search form somehow.
Yes, you can use wpdb to delete the record in the custom table. Something like this in the wordpress function. ``` require_once ('../../../../wp-load.php'); if (!empty($_POST['id'])) { global $wpdb; $table='table_name'; $id = $_POST['id']; $wpdb->delete( $table, array( 'id' => $id ) ); } ```
281,140
<p>I already tried in several ways to remove the last slash of the url that I created with <code>add_rewrite_rule</code>.</p> <p>below is the implementation of my code</p> <pre><code>function master_load_ads_txt_template_include($template) { $is_load_ads_txt = (bool)get_query_var('ads-txt'); if( $is_load_ads_txt ) { $template = get_template_part("template-parts/ads-txt"); } return $template; } add_action( 'template_include', 'master_load_ads_txt_template_include' ); function master_load_ads_txt_rewrite() { add_rewrite_rule('ads.txt', 'index.php?ads-txt=true', 'top'); add_rewrite_rule('^ads.txt/', 'ads.txt', 'top'); } add_action('init', 'master_load_ads_txt_rewrite'); function master_load_ads_txt_query_vars( $query_vars ) { $query_vars[] = 'ads-txt'; return $query_vars; } add_filter( 'query_vars', 'master_load_ads_txt_query_vars'); </code></pre> <p>the code is working but does not remove the slash at the end of the url</p> <p><a href="https://i.stack.imgur.com/aQZr7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQZr7.png" alt="enter image description here"></a></p>
[ { "answer_id": 281815, "author": "Elton Peetz", "author_id": 128979, "author_profile": "https://wordpress.stackexchange.com/users/128979", "pm_score": 0, "selected": false, "text": "<pre><code>/* ORIGINAL CODE */\nfunction master_load_ads_txt_template_include($template) {\n $is_load_ads_txt = (bool)get_query_var('ads-txt');\n if( $is_load_ads_txt ) {\n $template = get_template_part(\"template-parts/ads-txt\");\n }\n return $template;\n}\nadd_action( 'template_include', 'master_load_ads_txt_template_include' );\n\nfunction master_load_ads_txt_rewrite() {\n /* UPDATE RULE */\n add_rewrite_rule('^ads.txt$', 'index.php?ads-txt=true', 'top');\n}\nadd_action('init', 'master_load_ads_txt_rewrite');\n\nfunction master_load_ads_txt_query_vars( $query_vars ) {\n $query_vars[] = 'ads-txt';\n return $query_vars;\n}\nadd_filter( 'query_vars', 'master_load_ads_txt_query_vars');\n\n/* ACTION TO ALLOW URL WITHOUT LAST TRAILING SLASH */\nfunction disable_canonical_redirects_for_ads_txt( $redirect_url, $requested_url ) {\n if ( preg_match( '|ads\\.txt|', $requested_url ) ) {\n return $requested_url;\n }\n return $redirect_url;\n}\nadd_action( 'redirect_canonical', 'disable_canonical_redirects_for_ads_txt', 10, 2 );\n</code></pre>\n" }, { "answer_id": 338821, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": false, "text": "<p>Replace all your above code with the one below:</p>\n\n<pre><code>&lt;?php\n\nfunction master_load_ads_txt_template_include( $template ) {\n $is_load_ads_txt = (bool) get_query_var( 'ads-txt' );\n\n if ( $is_load_ads_txt ) {\n $template = locate_template( 'template-parts/ads-txt.php' );\n }\n\n return $template;\n}\n\nadd_filter( 'template_include', 'master_load_ads_txt_template_include' );\n\nfunction master_load_ads_txt_rewrite() {\n add_rewrite_rule( 'ads.txt', 'index.php?ads-txt=true', 'top' );\n\n // The line below doesn't work and it's useless.\n // add_rewrite_rule( '^ads.txt/', 'ads.txt', 'top' );\n}\n\nadd_action( 'init', 'master_load_ads_txt_rewrite' );\n\nfunction master_load_ads_txt_query_vars( $query_vars ) {\n $query_vars[] = 'ads-txt';\n\n return $query_vars;\n}\n\nadd_filter( 'query_vars', 'master_load_ads_txt_query_vars' );\n\nfunction redirect_canonical_callback( $redirect_url, $requested_url ) {\n $is_load_ads_txt = (bool) get_query_var( 'ads-txt' );\n\n if ( $is_load_ads_txt ) {\n return $requested_url;\n }\n\n return $redirect_url;\n}\n\nadd_filter( 'redirect_canonical', 'redirect_canonical_callback', 100, 2 );\n\n</code></pre>\n\n<p><strong>A few notes:</strong></p>\n\n<ol>\n<li><code>template_include</code> is a filter hook, not an action hook. It's fixed.</li>\n<li>As pointed in the comments your rule <code>add_rewrite_rule('^ads.txt/', 'ads.txt', 'top');</code> is useless. It's fixed.</li>\n<li>In this case, <code>redirect_canonical</code> should be used within a filter hook, not an action.</li>\n<li>After putting the code above in your <strong>functions.php</strong> file don't forget to flush your permalinks by visiting <strong>Settings</strong> > <strong>Permalinks</strong>.</li>\n</ol>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128543/" ]
I already tried in several ways to remove the last slash of the url that I created with `add_rewrite_rule`. below is the implementation of my code ``` function master_load_ads_txt_template_include($template) { $is_load_ads_txt = (bool)get_query_var('ads-txt'); if( $is_load_ads_txt ) { $template = get_template_part("template-parts/ads-txt"); } return $template; } add_action( 'template_include', 'master_load_ads_txt_template_include' ); function master_load_ads_txt_rewrite() { add_rewrite_rule('ads.txt', 'index.php?ads-txt=true', 'top'); add_rewrite_rule('^ads.txt/', 'ads.txt', 'top'); } add_action('init', 'master_load_ads_txt_rewrite'); function master_load_ads_txt_query_vars( $query_vars ) { $query_vars[] = 'ads-txt'; return $query_vars; } add_filter( 'query_vars', 'master_load_ads_txt_query_vars'); ``` the code is working but does not remove the slash at the end of the url [![enter image description here](https://i.stack.imgur.com/aQZr7.png)](https://i.stack.imgur.com/aQZr7.png)
Replace all your above code with the one below: ``` <?php function master_load_ads_txt_template_include( $template ) { $is_load_ads_txt = (bool) get_query_var( 'ads-txt' ); if ( $is_load_ads_txt ) { $template = locate_template( 'template-parts/ads-txt.php' ); } return $template; } add_filter( 'template_include', 'master_load_ads_txt_template_include' ); function master_load_ads_txt_rewrite() { add_rewrite_rule( 'ads.txt', 'index.php?ads-txt=true', 'top' ); // The line below doesn't work and it's useless. // add_rewrite_rule( '^ads.txt/', 'ads.txt', 'top' ); } add_action( 'init', 'master_load_ads_txt_rewrite' ); function master_load_ads_txt_query_vars( $query_vars ) { $query_vars[] = 'ads-txt'; return $query_vars; } add_filter( 'query_vars', 'master_load_ads_txt_query_vars' ); function redirect_canonical_callback( $redirect_url, $requested_url ) { $is_load_ads_txt = (bool) get_query_var( 'ads-txt' ); if ( $is_load_ads_txt ) { return $requested_url; } return $redirect_url; } add_filter( 'redirect_canonical', 'redirect_canonical_callback', 100, 2 ); ``` **A few notes:** 1. `template_include` is a filter hook, not an action hook. It's fixed. 2. As pointed in the comments your rule `add_rewrite_rule('^ads.txt/', 'ads.txt', 'top');` is useless. It's fixed. 3. In this case, `redirect_canonical` should be used within a filter hook, not an action. 4. After putting the code above in your **functions.php** file don't forget to flush your permalinks by visiting **Settings** > **Permalinks**.
281,157
<p>I'm not entirely sure where I can even ask this question as it pertains to both HTML and WP.</p> <p>Anyways, our old intranet solution basically held a bunch of .htm documents that we made in Word and then turned into .htm.</p> <p>We have switched to a WP solution and have begun uploading these .htm docs as media as it is the easiest solution for the 1700 docs we have. The issue is, these .htm docs contain hyperlinks inside of them that link to other .htm docs on our old website. This means that once we decommission our old server, all of those hyperlinks will be dead. I'm talking about thousands of useless links inside of the .htm docs.</p> <p>How can I solve this problem? Ideally, we don't want to individually edit each .htm doc and change the links inside of them. We have also tried the html to post converter plugin but it makes the formatting all wonky. We don't want to, but should we just keep the old server as a file server of sorts so the links still work?</p> <p><strong>URL structure</strong></p> <p>OLD: <a href="http://websrv04/DIL%20Manuals/Employee%20Manual/Drayden%20Core%20Values.htm" rel="nofollow noreferrer">http://websrv04/DIL%20Manuals/Employee%20Manual/Drayden%20Core%20Values.htm</a> NEW: droogle.dil/wp-content/uploads/2017/08/Core-Values.htm </p> <p><strong>href example from an old .htm doc</strong></p> <p><strong><em>Code</em></strong></p> <pre><code>&lt;/span&gt;&lt;/span&gt;&lt;span lang=EN-CA style='font-family: "Arial","sans-serif";color:green;mso-ansi-language:EN-CA'&gt;Refer to &lt;/span&gt;&lt;a href="http://websrv04/DIL%20Manuals/Policy%20Works%20Accessing%20Policy%20Works.htm"&gt;&lt;span lang=EN-CA style='font-family:"Arial","sans-serif";mso-ansi-language:EN-CA'&gt;Policy Works Accessing Policy Works&lt;/span&gt;&lt;/a&gt;&lt;span lang=EN-CA style='font-family: "Arial","sans-serif";color:green;mso-ansi-language:EN-CA'&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/p&gt; </code></pre> <p><strong><em>Final product</em></strong></p> <p>Refer to <a href="http://websrv04/DIL%20Manuals/Policy%20Works%20Accessing%20Policy%20Works.htm" rel="nofollow noreferrer">Policy Works Accessing Policy Works</a></p></p>
[ { "answer_id": 281815, "author": "Elton Peetz", "author_id": 128979, "author_profile": "https://wordpress.stackexchange.com/users/128979", "pm_score": 0, "selected": false, "text": "<pre><code>/* ORIGINAL CODE */\nfunction master_load_ads_txt_template_include($template) {\n $is_load_ads_txt = (bool)get_query_var('ads-txt');\n if( $is_load_ads_txt ) {\n $template = get_template_part(\"template-parts/ads-txt\");\n }\n return $template;\n}\nadd_action( 'template_include', 'master_load_ads_txt_template_include' );\n\nfunction master_load_ads_txt_rewrite() {\n /* UPDATE RULE */\n add_rewrite_rule('^ads.txt$', 'index.php?ads-txt=true', 'top');\n}\nadd_action('init', 'master_load_ads_txt_rewrite');\n\nfunction master_load_ads_txt_query_vars( $query_vars ) {\n $query_vars[] = 'ads-txt';\n return $query_vars;\n}\nadd_filter( 'query_vars', 'master_load_ads_txt_query_vars');\n\n/* ACTION TO ALLOW URL WITHOUT LAST TRAILING SLASH */\nfunction disable_canonical_redirects_for_ads_txt( $redirect_url, $requested_url ) {\n if ( preg_match( '|ads\\.txt|', $requested_url ) ) {\n return $requested_url;\n }\n return $redirect_url;\n}\nadd_action( 'redirect_canonical', 'disable_canonical_redirects_for_ads_txt', 10, 2 );\n</code></pre>\n" }, { "answer_id": 338821, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": false, "text": "<p>Replace all your above code with the one below:</p>\n\n<pre><code>&lt;?php\n\nfunction master_load_ads_txt_template_include( $template ) {\n $is_load_ads_txt = (bool) get_query_var( 'ads-txt' );\n\n if ( $is_load_ads_txt ) {\n $template = locate_template( 'template-parts/ads-txt.php' );\n }\n\n return $template;\n}\n\nadd_filter( 'template_include', 'master_load_ads_txt_template_include' );\n\nfunction master_load_ads_txt_rewrite() {\n add_rewrite_rule( 'ads.txt', 'index.php?ads-txt=true', 'top' );\n\n // The line below doesn't work and it's useless.\n // add_rewrite_rule( '^ads.txt/', 'ads.txt', 'top' );\n}\n\nadd_action( 'init', 'master_load_ads_txt_rewrite' );\n\nfunction master_load_ads_txt_query_vars( $query_vars ) {\n $query_vars[] = 'ads-txt';\n\n return $query_vars;\n}\n\nadd_filter( 'query_vars', 'master_load_ads_txt_query_vars' );\n\nfunction redirect_canonical_callback( $redirect_url, $requested_url ) {\n $is_load_ads_txt = (bool) get_query_var( 'ads-txt' );\n\n if ( $is_load_ads_txt ) {\n return $requested_url;\n }\n\n return $redirect_url;\n}\n\nadd_filter( 'redirect_canonical', 'redirect_canonical_callback', 100, 2 );\n\n</code></pre>\n\n<p><strong>A few notes:</strong></p>\n\n<ol>\n<li><code>template_include</code> is a filter hook, not an action hook. It's fixed.</li>\n<li>As pointed in the comments your rule <code>add_rewrite_rule('^ads.txt/', 'ads.txt', 'top');</code> is useless. It's fixed.</li>\n<li>In this case, <code>redirect_canonical</code> should be used within a filter hook, not an action.</li>\n<li>After putting the code above in your <strong>functions.php</strong> file don't forget to flush your permalinks by visiting <strong>Settings</strong> > <strong>Permalinks</strong>.</li>\n</ol>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128554/" ]
I'm not entirely sure where I can even ask this question as it pertains to both HTML and WP. Anyways, our old intranet solution basically held a bunch of .htm documents that we made in Word and then turned into .htm. We have switched to a WP solution and have begun uploading these .htm docs as media as it is the easiest solution for the 1700 docs we have. The issue is, these .htm docs contain hyperlinks inside of them that link to other .htm docs on our old website. This means that once we decommission our old server, all of those hyperlinks will be dead. I'm talking about thousands of useless links inside of the .htm docs. How can I solve this problem? Ideally, we don't want to individually edit each .htm doc and change the links inside of them. We have also tried the html to post converter plugin but it makes the formatting all wonky. We don't want to, but should we just keep the old server as a file server of sorts so the links still work? **URL structure** OLD: <http://websrv04/DIL%20Manuals/Employee%20Manual/Drayden%20Core%20Values.htm> NEW: droogle.dil/wp-content/uploads/2017/08/Core-Values.htm **href example from an old .htm doc** ***Code*** ``` </span></span><span lang=EN-CA style='font-family: "Arial","sans-serif";color:green;mso-ansi-language:EN-CA'>Refer to </span><a href="http://websrv04/DIL%20Manuals/Policy%20Works%20Accessing%20Policy%20Works.htm"><span lang=EN-CA style='font-family:"Arial","sans-serif";mso-ansi-language:EN-CA'>Policy Works Accessing Policy Works</span></a><span lang=EN-CA style='font-family: "Arial","sans-serif";color:green;mso-ansi-language:EN-CA'><o:p></o:p></span></p> ``` ***Final product*** Refer to [Policy Works Accessing Policy Works](http://websrv04/DIL%20Manuals/Policy%20Works%20Accessing%20Policy%20Works.htm)
Replace all your above code with the one below: ``` <?php function master_load_ads_txt_template_include( $template ) { $is_load_ads_txt = (bool) get_query_var( 'ads-txt' ); if ( $is_load_ads_txt ) { $template = locate_template( 'template-parts/ads-txt.php' ); } return $template; } add_filter( 'template_include', 'master_load_ads_txt_template_include' ); function master_load_ads_txt_rewrite() { add_rewrite_rule( 'ads.txt', 'index.php?ads-txt=true', 'top' ); // The line below doesn't work and it's useless. // add_rewrite_rule( '^ads.txt/', 'ads.txt', 'top' ); } add_action( 'init', 'master_load_ads_txt_rewrite' ); function master_load_ads_txt_query_vars( $query_vars ) { $query_vars[] = 'ads-txt'; return $query_vars; } add_filter( 'query_vars', 'master_load_ads_txt_query_vars' ); function redirect_canonical_callback( $redirect_url, $requested_url ) { $is_load_ads_txt = (bool) get_query_var( 'ads-txt' ); if ( $is_load_ads_txt ) { return $requested_url; } return $redirect_url; } add_filter( 'redirect_canonical', 'redirect_canonical_callback', 100, 2 ); ``` **A few notes:** 1. `template_include` is a filter hook, not an action hook. It's fixed. 2. As pointed in the comments your rule `add_rewrite_rule('^ads.txt/', 'ads.txt', 'top');` is useless. It's fixed. 3. In this case, `redirect_canonical` should be used within a filter hook, not an action. 4. After putting the code above in your **functions.php** file don't forget to flush your permalinks by visiting **Settings** > **Permalinks**.
281,182
<p>Inside my loop, I'm trying to have a link show and it won't I'm not sure why</p> <p>Here is the code:</p> <pre><code>&lt;?php the_title('&lt;h2 class="wow"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"', '&lt;/a&gt;&lt;/h2&gt;'); ?&gt; </code></pre> <p>I understand this is maybe because of the <code>''</code> quotations instead of <code>""</code>, but how would I achieve this general thing with just PHP and not by wrapping <code>the_title();</code> in an a tag.</p>
[ { "answer_id": 281186, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You can't nest these functions. Change your code to</p>\n\n<pre><code>&lt;h2 class=\"wow\"&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n</code></pre>\n" }, { "answer_id": 281187, "author": "Patrice Poliquin", "author_id": 32365, "author_profile": "https://wordpress.stackexchange.com/users/32365", "pm_score": 1, "selected": false, "text": "<p>23 seconds too late.</p>\n\n<p>I think the issue is that you have a double open/close statement.</p>\n\n<p>Without seeing your code, I would suggest you to edit your line of code as </p>\n\n<pre><code>&lt;h2 class=\"wow\"&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n</code></pre>\n" }, { "answer_id": 281197, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 3, "selected": true, "text": "<p>because <code>the_title()</code> expects a string for the <code>$before</code> and <code>$after</code> args, you need to use the string version of the permalink, in a string concatenation;</p>\n\n<p><code>&lt;?php the_title('&lt;h2 class=\"wow\"&gt;&lt;a href=\"'.get_permalink().'\"&gt;', '&lt;/a&gt;&lt;/h2&gt;'); ?&gt;</code></p>\n\n<p>you also had a missing <code>&gt;</code>.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_permalink/</a></p>\n" } ]
2017/09/26
[ "https://wordpress.stackexchange.com/questions/281182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83544/" ]
Inside my loop, I'm trying to have a link show and it won't I'm not sure why Here is the code: ``` <?php the_title('<h2 class="wow"><a href="<?php the_permalink(); ?>"', '</a></h2>'); ?> ``` I understand this is maybe because of the `''` quotations instead of `""`, but how would I achieve this general thing with just PHP and not by wrapping `the_title();` in an a tag.
because `the_title()` expects a string for the `$before` and `$after` args, you need to use the string version of the permalink, in a string concatenation; `<?php the_title('<h2 class="wow"><a href="'.get_permalink().'">', '</a></h2>'); ?>` you also had a missing `>`. <https://developer.wordpress.org/reference/functions/get_permalink/>