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
217,340
<p>So within my Customizer I have a section that controls this Slider on the Homepage - the thing the client might not want to use all the Slider Images but all the Sliders still show anyway and the ones without an Image just show the alt tag.</p> <p>Is there a way to basically check if there is a image and if not don't display that Slide?</p> <p><strong>EDIT</strong>: I'm trying to achieve something similar to <code>post_thumbnail</code> as in if there is an image then displays it but if there isn't one then don't display it at all.</p> <p>So this is how I get the Slider mage:</p> <pre><code>&lt;div class="item active"&gt; &lt;img class="img-responsive" src="&lt;?php echo esc_url( get_theme_mod( 'slider_one' ) ); ?&gt;" alt="Slider 1"&gt; &lt;/div&gt; </code></pre> <p>Then I register this in my <strong>Customizer.php</strong>:</p> <pre><code>/** * Adding the Section for Slider */ $wp_customize-&gt;add_section('slideshow', array( 'title' =&gt; __('Slider Images', 'patti-theme'), 'priority' =&gt; 60, )); /** * Adding the Settings for Slider */ $wp_customize-&gt;add_setting('slider_one', array( 'transport' =&gt; 'refresh', 'height' =&gt; 525, )); /** * Adding the Controls for Slider */ $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'slider_one_control', array( 'label' =&gt; __('Slider Image #1', 'patti-theme'), 'section' =&gt; 'slideshow', 'settings' =&gt; 'slider_one', ))); </code></pre> <p>So is there a way to check if <code>slider_one</code> has a Image inserted and if not don't display it.</p> <p>What is shown if there is no <strong>Image</strong> inserted:</p> <p><a href="https://i.stack.imgur.com/9eOny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9eOny.png" alt="enter image description here"></a></p> <p>They then click Select Image and shows the Media Library where they can pick and Image or even Upload a new Image</p> <p>How the <strong>Slider</strong> outputs the Image if there is no Image:</p> <p><a href="https://i.stack.imgur.com/NFxKu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NFxKu.png" alt="enter image description here"></a></p> <p>I don't want this Slider to display at all if the <code>src</code> element inside the <code>img</code> tag is empty.</p> <p>The Slider outputs the Image with this line of code:</p> <pre><code>&lt;img class="img-responsive" src="&lt;?php echo esc_url( get_theme_mod( 'slider_one' ) ); ?&gt;" alt="Slider 1"&gt; </code></pre>
[ { "answer_id": 217350, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": false, "text": "<p>Just do a conditional check slightly earlier to wrap the div?</p>\n\n<pre><code>&lt;?php if ( get_theme_mod( 'slider_one', '') != '') : ?&gt;\n&lt;div class=\"item active\"&gt;\n &lt;img class=\"img-responsive\" src=\"&lt;?php echo esc_url( get_theme_mod( 'slider_one', '' ) ); ?&gt;\" alt=\"Slider 1\"&gt;\n&lt;/div&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 217359, "author": "Kaspar Lee", "author_id": 84836, "author_profile": "https://wordpress.stackexchange.com/users/84836", "pm_score": 3, "selected": true, "text": "<p>Try the following code:</p>\n\n<pre><code>&lt;div class=\"item active &lt;?php\n // If image URL is empty, echo \"hidden\"\n echo (get_theme_mod('slider_one', '') == '' ? 'hidden' : '');\n?&gt;\"&gt;\n &lt;img class=\"img-responsive\" src=\"&lt;?php echo esc_url( get_theme_mod( 'slider_one', '' ) ); ?&gt;\" alt=\"Slider 1\"&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then use the following CSS:</p>\n\n<pre><code>.hidden { display: none }\n</code></pre>\n\n<hr>\n\n<p>What this will do is:</p>\n\n<ul>\n<li>If no image is selected (i.e. <code>get_theme_mod(...) == ''</code>)</li>\n<li>Echo class <code>hidden</code></li>\n<li>The CSS will hide all elements with <code>.hidden</code></li>\n</ul>\n" } ]
2016/02/11
[ "https://wordpress.stackexchange.com/questions/217340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85776/" ]
So within my Customizer I have a section that controls this Slider on the Homepage - the thing the client might not want to use all the Slider Images but all the Sliders still show anyway and the ones without an Image just show the alt tag. Is there a way to basically check if there is a image and if not don't display that Slide? **EDIT**: I'm trying to achieve something similar to `post_thumbnail` as in if there is an image then displays it but if there isn't one then don't display it at all. So this is how I get the Slider mage: ``` <div class="item active"> <img class="img-responsive" src="<?php echo esc_url( get_theme_mod( 'slider_one' ) ); ?>" alt="Slider 1"> </div> ``` Then I register this in my **Customizer.php**: ``` /** * Adding the Section for Slider */ $wp_customize->add_section('slideshow', array( 'title' => __('Slider Images', 'patti-theme'), 'priority' => 60, )); /** * Adding the Settings for Slider */ $wp_customize->add_setting('slider_one', array( 'transport' => 'refresh', 'height' => 525, )); /** * Adding the Controls for Slider */ $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'slider_one_control', array( 'label' => __('Slider Image #1', 'patti-theme'), 'section' => 'slideshow', 'settings' => 'slider_one', ))); ``` So is there a way to check if `slider_one` has a Image inserted and if not don't display it. What is shown if there is no **Image** inserted: [![enter image description here](https://i.stack.imgur.com/9eOny.png)](https://i.stack.imgur.com/9eOny.png) They then click Select Image and shows the Media Library where they can pick and Image or even Upload a new Image How the **Slider** outputs the Image if there is no Image: [![enter image description here](https://i.stack.imgur.com/NFxKu.png)](https://i.stack.imgur.com/NFxKu.png) I don't want this Slider to display at all if the `src` element inside the `img` tag is empty. The Slider outputs the Image with this line of code: ``` <img class="img-responsive" src="<?php echo esc_url( get_theme_mod( 'slider_one' ) ); ?>" alt="Slider 1"> ```
Try the following code: ``` <div class="item active <?php // If image URL is empty, echo "hidden" echo (get_theme_mod('slider_one', '') == '' ? 'hidden' : ''); ?>"> <img class="img-responsive" src="<?php echo esc_url( get_theme_mod( 'slider_one', '' ) ); ?>" alt="Slider 1"> </div> ``` Then use the following CSS: ``` .hidden { display: none } ``` --- What this will do is: * If no image is selected (i.e. `get_theme_mod(...) == ''`) * Echo class `hidden` * The CSS will hide all elements with `.hidden`
217,364
<p>I have two sites which I've copied a plugin from the first site and then altered the plugin and changed the name of plugins directoy and class name.</p> <p>Like from:</p> <pre><code>old_xplugin </code></pre> <p>In the root of this plugin I have file called <code>old_xplugin.php</code> and class name equiavivalent: <code>class old_xplugin</code></p> <p>TO</p> <p><code>new_xplugin</code> (now with modifications of the old xplugin) In the root of this plugin I now a have file called <code>new_xplugin.php</code> and class name equiavivalent: <code>class new_xplugin</code></p> <p>Everything works until I change the name of the folder. (I can change name of the plugin, and the class name without problem).</p> <p>But when I change the name of the folder I get jQuery reference eror: not defined. <strong>Why isn't jQuery loaded when change of the plugins folder?</strong></p> <p>This is the structure of the plugin file(s):</p> <p><strong>main plugin file</strong> (new_xplugin.php). These things are not changed after copying the plugin.</p> <pre><code>public function __construct() { //Iniate jquery and css add_action( 'wp_enqueue_scripts', array($this, 'js_css' ) ); } public function js_css() { wp_enqueue_script( 'wtfjs', plugins_url( '/js/wtf.js' , __FILE__) ); } </code></pre> <p><strong>wtf.js</strong></p> <pre><code>jQuery(function ($) { //Wordpress says: jQuery reference error: undefined. //code }); </code></pre>
[ { "answer_id": 217365, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>No idea why the change of folder name makes a difference, but you should add jquery as dependency in your enqueue</p>\n\n<pre><code>wp_enqueue_script(\n 'wtfjs',\n plugins_url( '/js/wtf.js' , __FILE__),\n array('jquery')\n ); \n</code></pre>\n" }, { "answer_id": 217370, "author": "bestprogrammerintheworld", "author_id": 38848, "author_profile": "https://wordpress.stackexchange.com/users/38848", "pm_score": 0, "selected": false, "text": "<p>Thanks to @Mark Kaplun that spotted the actual issue. jQuery did not load before wp_enque_script was executed. So I hooked the function <code>js_css()</code> into init like this:</p>\n\n<pre><code>add_action( 'init', array( $this, 'js_css' ) );\n</code></pre>\n\n<p>and that solved the problem! :-)</p>\n\n<p>(Very strange that this even worked on site1 though)</p>\n" } ]
2016/02/11
[ "https://wordpress.stackexchange.com/questions/217364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38848/" ]
I have two sites which I've copied a plugin from the first site and then altered the plugin and changed the name of plugins directoy and class name. Like from: ``` old_xplugin ``` In the root of this plugin I have file called `old_xplugin.php` and class name equiavivalent: `class old_xplugin` TO `new_xplugin` (now with modifications of the old xplugin) In the root of this plugin I now a have file called `new_xplugin.php` and class name equiavivalent: `class new_xplugin` Everything works until I change the name of the folder. (I can change name of the plugin, and the class name without problem). But when I change the name of the folder I get jQuery reference eror: not defined. **Why isn't jQuery loaded when change of the plugins folder?** This is the structure of the plugin file(s): **main plugin file** (new\_xplugin.php). These things are not changed after copying the plugin. ``` public function __construct() { //Iniate jquery and css add_action( 'wp_enqueue_scripts', array($this, 'js_css' ) ); } public function js_css() { wp_enqueue_script( 'wtfjs', plugins_url( '/js/wtf.js' , __FILE__) ); } ``` **wtf.js** ``` jQuery(function ($) { //Wordpress says: jQuery reference error: undefined. //code }); ```
No idea why the change of folder name makes a difference, but you should add jquery as dependency in your enqueue ``` wp_enqueue_script( 'wtfjs', plugins_url( '/js/wtf.js' , __FILE__), array('jquery') ); ```
217,390
<p>I am trying to enqueue multiple Google fonts with multiple weights (400,600,700, etc,) and styles (normal, italic) and can't figure out why it is not working. </p> <p>This is the code that I am using in the functions.php:</p> <pre><code>function load_fonts() { wp_register_style('googleFonts', 'http://fonts.googleapis.com/css?family=Dosis:400,600,700|Roboto:400,400italic,700,700italic'); wp_enqueue_style( 'googleFonts'); } add_action('wp_print_styles', 'load_fonts'); </code></pre> <p>This is the link that is being output in the source: </p> <pre><code>&lt;link rel='stylesheet' id='googleFonts-css' href='http://fonts.googleapis.com/css?family=+Dosis%3A400%2C600%2C700%7CRoboto%3A400%2C400italic%2C700%2C700italic&amp;#038;ver=4.4.2' type='text/css' media='all' /&gt; </code></pre> <p>I tested IOS devices at BrowsserStack and using the WhatFont browser extension and the WhatFont extension for Safari on an iPhone (worked well). It showed it using the fallback font-family Arial. I realized that this has something to do with the server (cheap shared hosted plan -- ugh!). What I am not quite sure, but I appreciate everyone's input</p> <p>Any idea's?</p>
[ { "answer_id": 217395, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The default themes, TwentyXXXX, do it somewhat like this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse217390_enqueue_google_fonts' );\nfunction wpse217390_enqueue_google_fonts() {\n\n $query_args = array(\n 'family' =&gt; 'Dosis:400,600,700|Roboto:400,400italic,700,700italic'\n );\n\n wp_register_style( \n 'google-fonts', \n add_query_arg( $query_args, '//fonts.googleapis.com/css' ), \n array(), \n null \n );\n wp_enqueue_style( 'google-fonts' );\n\n}\n</code></pre>\n" }, { "answer_id": 257043, "author": "Rubel Hossain", "author_id": 64150, "author_profile": "https://wordpress.stackexchange.com/users/64150", "pm_score": 2, "selected": false, "text": "<h1>Adding Multiple Google fonts in Wordpress Standard Way</h1>\n<pre><code> function adding_theme_css_js(){\n\n wp_enqueue_style(&quot;adding-google-fonts&quot;, all_google_fonts());\n\n }\n\n add_action(&quot;wp_enqueue_scripts&quot;,&quot;adding_theme_css_js&quot;);\n\n\n\n function all_google_fonts() {\n\n $fonts = array(\n\n &quot;Open+Sans:400,300&quot;,\n &quot;Raleway:400,600&quot;\n\n );\n\n $fonts_collection = add_query_arg(array(\n\n &quot;family&quot;=&gt;urlencode(implode(&quot;|&quot;,$fonts)),\n\n &quot;subset&quot;=&gt;&quot;latin&quot;\n\n ),'https://fonts.googleapis.com/css');\n\n return $fonts_collection;\n }\n</code></pre>\n" }, { "answer_id": 268336, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>A more efficient way to do this would be to use the <a href=\"http://google-webfonts-helper.herokuapp.com/fonts\" rel=\"nofollow noreferrer\">Google Webfonts Helper</a> app. You select the typeface you want and then the weights/styles. It will then generate CSS and a .zip file for you to download and make these local fonts that you can then serve up yourself. This way you are not dependent on Google's servers or dealing with quirky URLs.</p>\n\n<p>It is especially important if you plan to submit a theme to WordPress for hosting in their theme repository as your theme will be rejected if it is dependent on assets being loaded via CDN/etc. only without any local fallback anyways.</p>\n" }, { "answer_id": 291768, "author": "thetwopct", "author_id": 135299, "author_profile": "https://wordpress.stackexchange.com/users/135299", "pm_score": 2, "selected": false, "text": "<p>A tidied/working answer based on Rubel Hossains answer above.... Add this to functions.php and update with the font names and weights you want. </p>\n\n<pre><code> // Enqueue the fonts\n function add_fonts_to_theme(){\n wp_enqueue_style(\"adding-google-fonts\", all_google_fonts());\n }\n add_action(\"wp_enqueue_scripts\",\"add_fonts_to_theme\");\n\n // Choose the fonts \n function all_google_fonts() {\n $fonts = array(\n \"Open+Sans:400,700\",\n \"Caveat:400,700\",\n \"Quicksand:400,700\"\n );\n $fonts_collection = add_query_arg(array(\n \"family\"=&gt;urlencode(implode(\"|\",$fonts)),\n \"subset\"=&gt;\"latin\"\n ),'https://fonts.googleapis.com/css');\n return $fonts_collection;\n }\n</code></pre>\n" }, { "answer_id": 373540, "author": "Patryk", "author_id": 114486, "author_profile": "https://wordpress.stackexchange.com/users/114486", "pm_score": 0, "selected": false, "text": "<p>Simple add to the end <code>, array(), null</code> like that:</p>\n<pre><code>function load_fonts() {\nwp_register_style(\n 'googleFonts', \n 'http://fonts.googleapis.com/css?family=Dosis:400,600,700|Roboto:400,400italic,700,700italic', \n array(), \n null\n);\nwp_enqueue_style( 'googleFonts');\n}\nadd_action('wp_print_styles', 'load_fonts');\n</code></pre>\n<p>This solution ommit adding version to the end.</p>\n" } ]
2016/02/11
[ "https://wordpress.stackexchange.com/questions/217390", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87090/" ]
I am trying to enqueue multiple Google fonts with multiple weights (400,600,700, etc,) and styles (normal, italic) and can't figure out why it is not working. This is the code that I am using in the functions.php: ``` function load_fonts() { wp_register_style('googleFonts', 'http://fonts.googleapis.com/css?family=Dosis:400,600,700|Roboto:400,400italic,700,700italic'); wp_enqueue_style( 'googleFonts'); } add_action('wp_print_styles', 'load_fonts'); ``` This is the link that is being output in the source: ``` <link rel='stylesheet' id='googleFonts-css' href='http://fonts.googleapis.com/css?family=+Dosis%3A400%2C600%2C700%7CRoboto%3A400%2C400italic%2C700%2C700italic&#038;ver=4.4.2' type='text/css' media='all' /> ``` I tested IOS devices at BrowsserStack and using the WhatFont browser extension and the WhatFont extension for Safari on an iPhone (worked well). It showed it using the fallback font-family Arial. I realized that this has something to do with the server (cheap shared hosted plan -- ugh!). What I am not quite sure, but I appreciate everyone's input Any idea's?
The default themes, TwentyXXXX, do it somewhat like this: ``` add_action( 'wp_enqueue_scripts', 'wpse217390_enqueue_google_fonts' ); function wpse217390_enqueue_google_fonts() { $query_args = array( 'family' => 'Dosis:400,600,700|Roboto:400,400italic,700,700italic' ); wp_register_style( 'google-fonts', add_query_arg( $query_args, '//fonts.googleapis.com/css' ), array(), null ); wp_enqueue_style( 'google-fonts' ); } ```
217,413
<p>It's showing <code>widgets.php</code>:</p> <p><a href="https://i.stack.imgur.com/pSn9D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pSn9D.png" alt="enter image description here"></a></p> <p>Not showing customizer:</p> <p><a href="https://i.stack.imgur.com/VUrfE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VUrfE.png" alt="not show customizer"></a></p> <p><strong>sidebar.php</strong></p> <pre><code>function footer_sidebar() { register_sidebar( array( 'name' =&gt; __( 'Footer Sidebar 1', 'footer1' ), 'id' =&gt; 'footer1', 'description' =&gt; __( 'Footer Sidebar 1', 'footer1' ), 'before_widget' =&gt; '&lt;div id="footer1" class="col-md-4" style="margin-bottom:10px;margin-top:-25px;"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); register_sidebar( array( 'name' =&gt; __( 'Footer Sidebar 2', 'footer2' ), 'id' =&gt; 'footer2', 'description' =&gt; __( 'Footer Sidebar 2', 'footer2' ), 'before_widget' =&gt; '&lt;div id="footer2" class="col-md-4" style="margin-bottom:10px;margin-top:-25px;"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); } add_action( 'widgets_init', 'footer_sidebar' ); </code></pre> <p><strong>footer.php</strong></p> <pre><code>&lt;div class="row"&gt; &lt;?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer1') ) : ?&gt;&lt;?php endif; ?&gt; &lt;?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer2') ) : ?&gt;&lt;?php endif; ?&gt; &lt;?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer3') ) : ?&gt;&lt;?php endif; ?&gt; &lt;?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer4') ) : ?&gt;&lt;?php endif; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 217414, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 2, "selected": false, "text": "<p>You have to put the function <code>footer_sidebar()</code> in the file functions.php not sidebar.php</p>\n\n<p>Is the footer.php included on site you opened the customizer?</p>\n" }, { "answer_id": 228944, "author": "rakifsul", "author_id": 96331, "author_profile": "https://wordpress.stackexchange.com/users/96331", "pm_score": 0, "selected": false, "text": "<p>You might be forgotten to add wp_footer(); function before the closing body tag in your footer.php. That causes the javascript cannot finish its instruction in the customizer.</p>\n" } ]
2016/02/11
[ "https://wordpress.stackexchange.com/questions/217413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88537/" ]
It's showing `widgets.php`: [![enter image description here](https://i.stack.imgur.com/pSn9D.png)](https://i.stack.imgur.com/pSn9D.png) Not showing customizer: [![not show customizer](https://i.stack.imgur.com/VUrfE.png)](https://i.stack.imgur.com/VUrfE.png) **sidebar.php** ``` function footer_sidebar() { register_sidebar( array( 'name' => __( 'Footer Sidebar 1', 'footer1' ), 'id' => 'footer1', 'description' => __( 'Footer Sidebar 1', 'footer1' ), 'before_widget' => '<div id="footer1" class="col-md-4" style="margin-bottom:10px;margin-top:-25px;">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'Footer Sidebar 2', 'footer2' ), 'id' => 'footer2', 'description' => __( 'Footer Sidebar 2', 'footer2' ), 'before_widget' => '<div id="footer2" class="col-md-4" style="margin-bottom:10px;margin-top:-25px;">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'footer_sidebar' ); ``` **footer.php** ``` <div class="row"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer1') ) : ?><?php endif; ?> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer2') ) : ?><?php endif; ?> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer3') ) : ?><?php endif; ?> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer4') ) : ?><?php endif; ?> </div> ```
You have to put the function `footer_sidebar()` in the file functions.php not sidebar.php Is the footer.php included on site you opened the customizer?
217,420
<p>I have a Wordpress based site with an additional custom PHP application with files in it's own folders - "staff", "volunteers" etc. We have mod-rewrite in .htaccess file so we can use permalinks</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; </code></pre> <p>I have a specific page in the "staff" folder, "form.php" that is giving me trouble - specifically, after Apache/PHP upgrade apostrophes in the POST variables seems to cause an issue - BUT instead of a PHP or SQL error I get Wordpress 404 page. How do I change that so I can start troubleshooting? I can not disable permalinks, the site is live. </p> <p><code>RewriteEngine Off</code> in .htaccess in "staff" folder does not do anything. </p> <p><a href="https://i.stack.imgur.com/KYsL5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KYsL5.jpg" alt="I am attaching two screenshots to show that the file indeed exists."></a> The first image shows what happens if the form textarea variable had an apostrophe plus space, the second shows that an apostrophe by itself does not cause a problem. </p> <p>Thank you! </p> <p>UPDATE: I got it down to a specific combination of letters, spaces and apostrophe</p> <p><code>always rembember to 'select'</code> - gives a consistent 404 error <code>always remember to 'salut'</code> - does not</p> <p>so I think it's reserved query words(?) in combination with apostrophe that is causing the issue and if I manage to keep Wordpress out of this folder, we would not be having any issues! </p> <p>UPDATE 2: the issue turned out to be a general Apache error - issues with mod-sec. However, instead of generating 403 forbidden that would be easier to troubleshoot, 404 page complicated the troubleshooting process. </p>
[ { "answer_id": 217421, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 0, "selected": false, "text": "<p>WordPress has several methods for seeing PHP Errors, Warnings, and Notices. Specifically, you can set WP_DEBUG to true and enable WP_DEBUG_LOG and WP_DEBUG_DISPLAY, as per <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\">these instructions.</a></p>\n\n<p>However, I am not sure that will fix your issue, as the 404 error likely indicates that your file does not exist, which may not generate any PHP errors. Are you sure that you are entering the exact url, on the correct server, etc?</p>\n" }, { "answer_id": 217496, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 3, "selected": true, "text": "<p>You can add a <a href=\"http://httpd.apache.org/docs/current/mod/mod_rewrite.html\" rel=\"nofollow\"><code>RewriteRule</code></a> to your <code>.htaccess</code> to instruct <code>mod_rewrite</code> to stop processing any URI that begins with <code>Staff/</code> or resolves to <code>Staff</code>:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteRule ^/?Staff(/|$) - [END,NC]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>In effect, this should be the same as a <code>RewriteEngine Off</code> directive in a <code>.htaccess</code> file in <code>/Staff</code>.</p>\n\n<p>Breaking down the new rule:\n<code>RewriteRule ^/?Staff(/|$) - [END,NC]</code></p>\n\n<ul>\n<li><code>^/?Staff(/|$)</code>: The first argument of a <code>RewriteRule</code> is a REGEX pattern to check against the path portion of requested URIs, in this case <code>Staff/Schedule/Schedu-Mod_Results_test.php</code>\n\n<ul>\n<li><code>^</code> matches the very beginning of the URI path</li>\n<li><code>/?</code> matches whether or not a leading forward-slash is present (this is only necessary to compensate for old Apache servers - it isn't needed in Apache 2+</li>\n<li><code>Staff</code> matches the literal string <code>Staff</code></li>\n<li><code>(/|$)</code> matches either a forward-slash, or the very end of the URI path</li>\n</ul></li>\n<li><code>-</code>: If the pattern is found in the URI path, the second argument specifies what to replace the entire URI path with. In this case <code>-</code> indicates that the URI should not be modified.</li>\n<li><code>[END,NC]</code>: the third argument consists of boolean flags that further modify the rule.\n\n<ul>\n<li><code>END</code> is similar to L (last), however indicates that this should be the <strong>very last</strong> rule processed within the context of the directory: if the pattern matches the URI, don't process any subsequent rewrite rules OR rounds (thus eliminating any possibility of handing the request to WordPress)</li>\n<li><code>NC</code> (<strong>N</strong>o<strong>C</strong>ase) makes pattern matching case-insensative.</li>\n</ul></li>\n</ul>\n" } ]
2016/02/12
[ "https://wordpress.stackexchange.com/questions/217420", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44405/" ]
I have a Wordpress based site with an additional custom PHP application with files in it's own folders - "staff", "volunteers" etc. We have mod-rewrite in .htaccess file so we can use permalinks ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` I have a specific page in the "staff" folder, "form.php" that is giving me trouble - specifically, after Apache/PHP upgrade apostrophes in the POST variables seems to cause an issue - BUT instead of a PHP or SQL error I get Wordpress 404 page. How do I change that so I can start troubleshooting? I can not disable permalinks, the site is live. `RewriteEngine Off` in .htaccess in "staff" folder does not do anything. [![I am attaching two screenshots to show that the file indeed exists.](https://i.stack.imgur.com/KYsL5.jpg)](https://i.stack.imgur.com/KYsL5.jpg) The first image shows what happens if the form textarea variable had an apostrophe plus space, the second shows that an apostrophe by itself does not cause a problem. Thank you! UPDATE: I got it down to a specific combination of letters, spaces and apostrophe `always rembember to 'select'` - gives a consistent 404 error `always remember to 'salut'` - does not so I think it's reserved query words(?) in combination with apostrophe that is causing the issue and if I manage to keep Wordpress out of this folder, we would not be having any issues! UPDATE 2: the issue turned out to be a general Apache error - issues with mod-sec. However, instead of generating 403 forbidden that would be easier to troubleshoot, 404 page complicated the troubleshooting process.
You can add a [`RewriteRule`](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) to your `.htaccess` to instruct `mod_rewrite` to stop processing any URI that begins with `Staff/` or resolves to `Staff`: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^/?Staff(/|$) - [END,NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` In effect, this should be the same as a `RewriteEngine Off` directive in a `.htaccess` file in `/Staff`. Breaking down the new rule: `RewriteRule ^/?Staff(/|$) - [END,NC]` * `^/?Staff(/|$)`: The first argument of a `RewriteRule` is a REGEX pattern to check against the path portion of requested URIs, in this case `Staff/Schedule/Schedu-Mod_Results_test.php` + `^` matches the very beginning of the URI path + `/?` matches whether or not a leading forward-slash is present (this is only necessary to compensate for old Apache servers - it isn't needed in Apache 2+ + `Staff` matches the literal string `Staff` + `(/|$)` matches either a forward-slash, or the very end of the URI path * `-`: If the pattern is found in the URI path, the second argument specifies what to replace the entire URI path with. In this case `-` indicates that the URI should not be modified. * `[END,NC]`: the third argument consists of boolean flags that further modify the rule. + `END` is similar to L (last), however indicates that this should be the **very last** rule processed within the context of the directory: if the pattern matches the URI, don't process any subsequent rewrite rules OR rounds (thus eliminating any possibility of handing the request to WordPress) + `NC` (**N**o**C**ase) makes pattern matching case-insensative.
217,441
<p>My plugin uses the following code to reference a file, but I've read <code>WP_PLUGIN_DIR</code> won't work if a user renames the default plugin folder. I would also like to replace <code>/location-specific-menu-items/</code>with a reference to the current plugin folder. </p> <pre><code>$gi = geoip_open(WP_PLUGIN_DIR ."/location-specific-menu-items/GeoIP.dat", GEOIP_STANDARD); </code></pre> <p>How could I rewrite this to make it work regardless of the names of the WP plugin directory and the specific plugin folder?</p> <p>EDIT:</p> <p>Here is my final working solution following everyone's input. Many thanks!</p> <pre><code>$GeoIPv4_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv4.dat'; $GeoIPv6_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv6.dat'; if (!filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE) { if ( is_readable ( $GeoIPv4_file ) ) { $gi = geoip_open( $GeoIPv4_file, GEOIP_STANDARD ); $user_country = geoip_country_code_by_addr($gi, $ip_address); geoip_close($gi); } } elseif (!filter_var($ip_address, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) === FALSE) { if ( is_readable ( $GeoIPv6_file ) ) { $gi = geoip_open( $GeoIPv6_file, GEOIP_STANDARD ); $user_country = geoip_country_code_by_addr($gi, $ip_address); geoip_close($gi); } } else { $user_country = "Can't locate IP: " . $ip_address; } </code></pre>
[ { "answer_id": 217451, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>If the plugin structure is:</p>\n\n<pre><code>plugins/\n some-plugin/\n some-plugin.php\n data/\n GeoIP.dat\n</code></pre>\n\n<p>then for PHP 5.3.0+, you could try the magic constant <a href=\"http://php.net/manual/en/language.constants.predefined.php\"><code>__DIR__</code></a> </p>\n\n<blockquote>\n <p><code>__DIR__</code> The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to\n <code>dirname(__FILE__)</code>. This directory name does not have a trailing slash\n unless it is the root directory.</p>\n</blockquote>\n\n<p>within the <code>some-plugin.php</code> file:</p>\n\n<pre><code>// Full path of the GeoIP.dat file\n$file = __DIR__ . '/data/GeoIP.dat';\n\n// Open datafile\nif( is_readable ( $file ) ) \n $gi = geoip_open( $file, GEOIP_STANDARD );\n</code></pre>\n\n<p>For wider PHP support you could use <a href=\"http://php.net/manual/en/function.dirname.php\"><code>dirname( __FILE__ )</code></a>, where <code>__FILE__</code> was added in PHP 4.0.2.</p>\n" }, { "answer_id": 217452, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 2, "selected": false, "text": "<p>You could also have a look at the functions WordPress has on board for this: e.g. <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_path/\" rel=\"nofollow\"><code>plugin_dir_path()</code></a>, <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"nofollow\"><code>plugins_url()</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\"><code>plugin_dir_url()</code></a></p>\n\n<p>They will help you with determining where your plugin is placed on the server. Those functions are also recommended by the Codex in <a href=\"https://codex.wordpress.org/Writing_a_Plugin#Names.2C_Files.2C_and_Locations\" rel=\"nofollow\">Writing a Plugin: Names, Files, and Locations.</a></p>\n\n<p>Besides that you can obviously use magic constants from PHP and filtering their output to determine where your files are.</p>\n" }, { "answer_id": 217454, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>plugin_dir_path(__FILE__);\n</code></pre>\n\n<p>Which as is just a wrapper function anyway for:</p>\n\n<pre><code>trailingslashit(dirname(__FILE__)); \n</code></pre>\n" } ]
2016/02/12
[ "https://wordpress.stackexchange.com/questions/217441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81557/" ]
My plugin uses the following code to reference a file, but I've read `WP_PLUGIN_DIR` won't work if a user renames the default plugin folder. I would also like to replace `/location-specific-menu-items/`with a reference to the current plugin folder. ``` $gi = geoip_open(WP_PLUGIN_DIR ."/location-specific-menu-items/GeoIP.dat", GEOIP_STANDARD); ``` How could I rewrite this to make it work regardless of the names of the WP plugin directory and the specific plugin folder? EDIT: Here is my final working solution following everyone's input. Many thanks! ``` $GeoIPv4_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv4.dat'; $GeoIPv6_file = plugin_dir_path( __FILE__ ) . 'data/GeoIPv6.dat'; if (!filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE) { if ( is_readable ( $GeoIPv4_file ) ) { $gi = geoip_open( $GeoIPv4_file, GEOIP_STANDARD ); $user_country = geoip_country_code_by_addr($gi, $ip_address); geoip_close($gi); } } elseif (!filter_var($ip_address, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) === FALSE) { if ( is_readable ( $GeoIPv6_file ) ) { $gi = geoip_open( $GeoIPv6_file, GEOIP_STANDARD ); $user_country = geoip_country_code_by_addr($gi, $ip_address); geoip_close($gi); } } else { $user_country = "Can't locate IP: " . $ip_address; } ```
If the plugin structure is: ``` plugins/ some-plugin/ some-plugin.php data/ GeoIP.dat ``` then for PHP 5.3.0+, you could try the magic constant [`__DIR__`](http://php.net/manual/en/language.constants.predefined.php) > > `__DIR__` The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to > `dirname(__FILE__)`. This directory name does not have a trailing slash > unless it is the root directory. > > > within the `some-plugin.php` file: ``` // Full path of the GeoIP.dat file $file = __DIR__ . '/data/GeoIP.dat'; // Open datafile if( is_readable ( $file ) ) $gi = geoip_open( $file, GEOIP_STANDARD ); ``` For wider PHP support you could use [`dirname( __FILE__ )`](http://php.net/manual/en/function.dirname.php), where `__FILE__` was added in PHP 4.0.2.
217,490
<p>I want to get the count of my posts. I think use </p> <p>wp-json/wp/v2/categories?page=1 >> count it's a good way to go. But using above solution is not a cup of tea in term of speed and i don't know how to get all the categories by one call.(if u know it would be so helpful if u share it). is there any way/tutorial/... enable me to add the post count in a main call? like this route: wp-json/wp/v2/posts....</p>
[ { "answer_id": 236880, "author": "Sdghasemi", "author_id": 101489, "author_profile": "https://wordpress.stackexchange.com/users/101489", "pm_score": 0, "selected": false, "text": "<p>I've spent hours on searching on getting number of posts with WP REST API even v2 through Google and WordPress or the library official docs but unfortunately came up with nothing.</p>\n\n<p>So I tried getting posts with increasing page number until the returned <strong>JSON array length</strong> becomes <strong>0</strong> which means there's <strong>no more page with posts</strong> on the category, and stopped increasing the page number.</p>\n\n<p>But if you want to get an arbitrary number of <strong>posts per page</strong> with WP REST API you can easily use <code>filter[posts_per_page]={$numberOfPosts}</code> parameter while sending the request.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 237643, "author": "DARK_DIESEL", "author_id": 101932, "author_profile": "https://wordpress.stackexchange.com/users/101932", "pm_score": 1, "selected": false, "text": "<p>Try to answer to part of your question. Count of post wp rest api v2 returned in headers. You can get value something like this:</p>\n\n<pre><code>headers('X-WP-Total')\n</code></pre>\n\n<p>Count posts per page:</p>\n\n<pre><code>wp-json/wp/v2/categories?page=1&amp;per_page=5\n</code></pre>\n" }, { "answer_id": 250589, "author": "Tunji", "author_id": 54764, "author_profile": "https://wordpress.stackexchange.com/users/54764", "pm_score": 5, "selected": false, "text": "<p>The WP Rest API sends the total count(<strong>found_posts</strong>) property from WP_Query. in a header called <strong><code>X-WP-Total</code></strong>.</p>\n\n<p><strong>FOR POSTS:</strong> you can make a call to posts endpoint of the REST API </p>\n\n<pre><code>http://demo.wp-api.org/wp-json/wp/v2/posts\n</code></pre>\n\n<p>The value for posts count is returned in the header as <strong><code>X-WP-Total</code></strong>. Below is a sample response from the hosted demo</p>\n\n<pre><code>Access-Control-Allow-Headers:Authorization, Content-Type\nAccess-Control-Expose-Headers:X-WP-Total, X-WP-TotalPages\nAllow:GET\nCache-Control:max-age=300, must-revalidate\nConnection:keep-alive\nContent-Encoding:gzip\nContent-Type:application/json; charset=UTF-8\nDate:Wed, 28 Dec 2016 12:48:50 GMT\nLast-Modified:Wed, 28 Dec 2016 12:48:50 GMT\nLink:&lt;https://demo.wp-api.org/wp-json/wp/v2/posts?page=2&gt;; rel=\"next\"\nServer:nginx/1.4.6 (Ubuntu)\nTransfer-Encoding:chunked\nVary:Cookie\nVia:1.1 dfa2cbb51ec90b28f03125592b887c7d.cloudfront.net (CloudFront)\nX-Amz-Cf-Id:ri4C3e-AdixwqGv_wYNdGRq9ChsIroy1Waxe2GqkiTqbk4CpiSIQfw==\nX-Batcache:MISS\nX-Cache:Miss from cloudfront\nX-Content-Type-Options:nosniff\nX-EC2-Instance-Id:i-198c7e94\nX-Powered-By:PHP/7.0.11-1+deb.sury.org~trusty+1\nX-Robots-Tag:noindex\nX-WP-Total:71\nX-WP-TotalPages:8\n</code></pre>\n\n<p><strong>NOTE:</strong></p>\n\n<p>You can also limit the <strong>posts per page</strong> you're fetching to 1 so you're not getting all your wordpress posts just to get the posts count</p>\n\n<pre><code>http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=1\n</code></pre>\n\n<h2>To Get All Categories</h2>\n\n<p>All you have to do is make a GET request to the categories endpoint at:</p>\n\n<pre><code>http://demo.wp-api.org/wp-json/wp/v2/categories\n</code></pre>\n\n<p>This would return all the categories and also the total count of categories can be found in the <strong><code>X-WP-Total</code></strong> header.</p>\n" }, { "answer_id": 274198, "author": "mgtech", "author_id": 124357, "author_profile": "https://wordpress.stackexchange.com/users/124357", "pm_score": 3, "selected": false, "text": "<p>In case it's not clear how to actually access the header (with the post count) from the Ajax request, following is how to do it with jQuery .get. The key is that the callback function has an optional parameter containing the request, which includes the headers.</p>\n\n<pre><code>$.get( 'http://demo.wp-api.org/wp-json/wp/v2/posts', function( data, status, request ) {\nnumPosts = request.getResponseHeader('x-wp-total');\nconsole.log( numPosts ); //outputs number of posts to console\n});\n</code></pre>\n" } ]
2016/02/12
[ "https://wordpress.stackexchange.com/questions/217490", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84324/" ]
I want to get the count of my posts. I think use wp-json/wp/v2/categories?page=1 >> count it's a good way to go. But using above solution is not a cup of tea in term of speed and i don't know how to get all the categories by one call.(if u know it would be so helpful if u share it). is there any way/tutorial/... enable me to add the post count in a main call? like this route: wp-json/wp/v2/posts....
The WP Rest API sends the total count(**found\_posts**) property from WP\_Query. in a header called **`X-WP-Total`**. **FOR POSTS:** you can make a call to posts endpoint of the REST API ``` http://demo.wp-api.org/wp-json/wp/v2/posts ``` The value for posts count is returned in the header as **`X-WP-Total`**. Below is a sample response from the hosted demo ``` Access-Control-Allow-Headers:Authorization, Content-Type Access-Control-Expose-Headers:X-WP-Total, X-WP-TotalPages Allow:GET Cache-Control:max-age=300, must-revalidate Connection:keep-alive Content-Encoding:gzip Content-Type:application/json; charset=UTF-8 Date:Wed, 28 Dec 2016 12:48:50 GMT Last-Modified:Wed, 28 Dec 2016 12:48:50 GMT Link:<https://demo.wp-api.org/wp-json/wp/v2/posts?page=2>; rel="next" Server:nginx/1.4.6 (Ubuntu) Transfer-Encoding:chunked Vary:Cookie Via:1.1 dfa2cbb51ec90b28f03125592b887c7d.cloudfront.net (CloudFront) X-Amz-Cf-Id:ri4C3e-AdixwqGv_wYNdGRq9ChsIroy1Waxe2GqkiTqbk4CpiSIQfw== X-Batcache:MISS X-Cache:Miss from cloudfront X-Content-Type-Options:nosniff X-EC2-Instance-Id:i-198c7e94 X-Powered-By:PHP/7.0.11-1+deb.sury.org~trusty+1 X-Robots-Tag:noindex X-WP-Total:71 X-WP-TotalPages:8 ``` **NOTE:** You can also limit the **posts per page** you're fetching to 1 so you're not getting all your wordpress posts just to get the posts count ``` http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=1 ``` To Get All Categories --------------------- All you have to do is make a GET request to the categories endpoint at: ``` http://demo.wp-api.org/wp-json/wp/v2/categories ``` This would return all the categories and also the total count of categories can be found in the **`X-WP-Total`** header.
217,503
<p>When I log in to my WordPress blog, there's a checkbox that says <em>Remember me</em>. But whether or not I check this, if I come back in a day or two I have to log in again, so it doesn't appear that this checkbox does anything. (My Google account, by contrast, hasn't ever once asked me to re-login on this computer, for more than a year now.) </p> <p>How do I make WP <em>actually remember me?</em></p>
[ { "answer_id": 217504, "author": "Mechow", "author_id": 87922, "author_profile": "https://wordpress.stackexchange.com/users/87922", "pm_score": -1, "selected": false, "text": "<p>Does it require you to type your user name when you come back in a few days? If you have to type that, then yes - something is wrong with your cookies perhaps. </p>\n\n<p>If it fills in your user name only, its working as intended. Remember me shouldn't maintain the logged in session indefinitely, only remember the user's name last used. Password will still be required. </p>\n" }, { "answer_id": 217517, "author": "BillK", "author_id": 87352, "author_profile": "https://wordpress.stackexchange.com/users/87352", "pm_score": 0, "selected": false, "text": "<p>The cookies are set to expire two weeks from the time they are created. From the <a href=\"https://codex.wordpress.org/WordPress_Cookies\" rel=\"nofollow\">codex</a> </p>\n\n<p>The expiration period is set in <code>wp-includes/pluggable.php</code> as shown below:</p>\n\n<pre><code>$expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );\n</code></pre>\n\n<p>You can use the <code>auth_cookie_expiration</code> filter to change this value.</p>\n" } ]
2016/02/12
[ "https://wordpress.stackexchange.com/questions/217503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88604/" ]
When I log in to my WordPress blog, there's a checkbox that says *Remember me*. But whether or not I check this, if I come back in a day or two I have to log in again, so it doesn't appear that this checkbox does anything. (My Google account, by contrast, hasn't ever once asked me to re-login on this computer, for more than a year now.) How do I make WP *actually remember me?*
The cookies are set to expire two weeks from the time they are created. From the [codex](https://codex.wordpress.org/WordPress_Cookies) The expiration period is set in `wp-includes/pluggable.php` as shown below: ``` $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember ); ``` You can use the `auth_cookie_expiration` filter to change this value.
217,512
<p>When I console.log(wp) the object only includes: -wp.emoji -wp.heartbeat -wp.svgPainter</p> <p>Script is loaded in the footer and last in the DOM. What am I missing?</p>
[ { "answer_id": 217514, "author": "Justin W Hall", "author_id": 11857, "author_profile": "https://wordpress.stackexchange.com/users/11857", "pm_score": 4, "selected": true, "text": "<p>Ah, I get it. When you enqueue your admin script, add 'wp-util' as a dependancy. </p>\n\n<pre><code> wp_enqueue_script( 'script_handle', plugin_dir_url( __FILE__ ) . 'script.js', array( 'jquery', 'wp-util' ), '1.0', true );\n</code></pre>\n" }, { "answer_id": 384050, "author": "Tahi Reu", "author_id": 148666, "author_profile": "https://wordpress.stackexchange.com/users/148666", "pm_score": 0, "selected": false, "text": "<p>In my case I had W3 Total Cache installed, and Minify option was set to Manual.</p>\n<p>After I removed wp-underscore script from manual minify list, issue with the <code>wp.template() Not a function</code> was gone.</p>\n" } ]
2016/02/13
[ "https://wordpress.stackexchange.com/questions/217512", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11857/" ]
When I console.log(wp) the object only includes: -wp.emoji -wp.heartbeat -wp.svgPainter Script is loaded in the footer and last in the DOM. What am I missing?
Ah, I get it. When you enqueue your admin script, add 'wp-util' as a dependancy. ``` wp_enqueue_script( 'script_handle', plugin_dir_url( __FILE__ ) . 'script.js', array( 'jquery', 'wp-util' ), '1.0', true ); ```
217,556
<p>I have a plugin that is creating a few pages and I want to use the custom templates I made for those specific pages. The pages a creating fine and even one of the templates is working but the other isnt. I will mark it but here is the code: </p> <pre><code>function ch_register_pages() { $ch_register_page_title = 'CH'; $ch_register_page_check = get_page_by_title($ch_register_page_title); $ch_register_page = array( 'post_type' =&gt; 'page', 'post_title' =&gt; $ch_register_page_title, 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_slug' =&gt; 'CH' ); wp_insert_post($ch_register_page); $ch_parent = get_page_by_path('CH'); $ch_parent_id = $ch_parent-&gt;ID; $ch_register_page_thankyou_title = 'CH Thank-You'; $ch_register_page_thankyou_check = get_page_by_title($ch_register_page_thankyou_title); $ch_register_page_thankyou = array( 'post_type' =&gt; 'page', 'post_title' =&gt; $ch_register_page_thankyou_title, 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_slug' =&gt; 'CH-Thank-you', 'post_parent' =&gt; $ch_parent_id ); wp_insert_post($ch_register_page_thankyou); } register_activation_hook( __FILE__, 'ch_register_pages' ); /* * Add page templates to pages * */ function ch_register_page_thanks_template() { ////////////////&lt;-------------Doesnt work if ( is_page( 'CH-Thank-you' ) ) {//change this to match slug $page_thankyou_template = dirname( __FILE__ ) . '/inc/page-ch-thank-you.php'; } return $page_thankyou_template; } add_filter( 'page_template', 'ch_register_page_thanks_template' ); function ch_register_page_template() {////////////////&lt;-------------Works if ( is_page( 'CH' ) ) { //change this to match slug $page_template = dirname( __FILE__ ) . '/inc/page-ch.php'; } return $page_template; } add_filter( 'page_template', 'ch_register_page_template' ); </code></pre>
[ { "answer_id": 217557, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p>Both of your filters return nothing if the conditional doesn't match, so if the first one matches, it's broken by the one that runs after it.</p>\n\n<p>Remember that filters are dealing with some sort of value that is passed through them. Your filters should pass back the unaltered template that was passed to them as function argument if the conditional doesn't match.</p>\n\n<pre><code>function ch_register_page_template( $page_template ) {\n\n if ( is_page( 'CH' ) ) { //change this to match slug\n $page_template = dirname( __FILE__ ) . '/inc/page-ch.php';\n }\n\n return $page_template;\n\n}\nadd_filter( 'page_template', 'ch_register_page_template' );\n</code></pre>\n" }, { "answer_id": 217558, "author": "Packy", "author_id": 35153, "author_profile": "https://wordpress.stackexchange.com/users/35153", "pm_score": 1, "selected": false, "text": "<p>I got it. It kind of makes sense but doesnt really. The one template wasnt working becuase I was looking for just the slug. Since its a child of the other page I needed to add it in the <code>is_page</code> statement. This worked (I also just did it all in one function):</p>\n\n<pre><code>function ch_register_page_template($page_template;) {////////////////&lt;-------------Works\n\n if ( is_page( 'CH' ) ) { //change this to match slug\n $page_template = dirname( __FILE__ ) . '/inc/page-ch.php';\n return $page_template;\n }\n\n if ( is_page( 'CH/CH-Thank-you' ) ) {//change this to match slug\n $page_template = dirname( __FILE__ ) . '/inc/page-ch-thank-you.php';\n return $page_template;\n\n }\n\n return $page_template;\n\n}\n\nadd_filter( 'page_template', 'ch_register_page_template' );\n</code></pre>\n" } ]
2016/02/13
[ "https://wordpress.stackexchange.com/questions/217556", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35153/" ]
I have a plugin that is creating a few pages and I want to use the custom templates I made for those specific pages. The pages a creating fine and even one of the templates is working but the other isnt. I will mark it but here is the code: ``` function ch_register_pages() { $ch_register_page_title = 'CH'; $ch_register_page_check = get_page_by_title($ch_register_page_title); $ch_register_page = array( 'post_type' => 'page', 'post_title' => $ch_register_page_title, 'post_status' => 'publish', 'post_author' => 1, 'post_slug' => 'CH' ); wp_insert_post($ch_register_page); $ch_parent = get_page_by_path('CH'); $ch_parent_id = $ch_parent->ID; $ch_register_page_thankyou_title = 'CH Thank-You'; $ch_register_page_thankyou_check = get_page_by_title($ch_register_page_thankyou_title); $ch_register_page_thankyou = array( 'post_type' => 'page', 'post_title' => $ch_register_page_thankyou_title, 'post_status' => 'publish', 'post_author' => 1, 'post_slug' => 'CH-Thank-you', 'post_parent' => $ch_parent_id ); wp_insert_post($ch_register_page_thankyou); } register_activation_hook( __FILE__, 'ch_register_pages' ); /* * Add page templates to pages * */ function ch_register_page_thanks_template() { ////////////////<-------------Doesnt work if ( is_page( 'CH-Thank-you' ) ) {//change this to match slug $page_thankyou_template = dirname( __FILE__ ) . '/inc/page-ch-thank-you.php'; } return $page_thankyou_template; } add_filter( 'page_template', 'ch_register_page_thanks_template' ); function ch_register_page_template() {////////////////<-------------Works if ( is_page( 'CH' ) ) { //change this to match slug $page_template = dirname( __FILE__ ) . '/inc/page-ch.php'; } return $page_template; } add_filter( 'page_template', 'ch_register_page_template' ); ```
I got it. It kind of makes sense but doesnt really. The one template wasnt working becuase I was looking for just the slug. Since its a child of the other page I needed to add it in the `is_page` statement. This worked (I also just did it all in one function): ``` function ch_register_page_template($page_template;) {////////////////<-------------Works if ( is_page( 'CH' ) ) { //change this to match slug $page_template = dirname( __FILE__ ) . '/inc/page-ch.php'; return $page_template; } if ( is_page( 'CH/CH-Thank-you' ) ) {//change this to match slug $page_template = dirname( __FILE__ ) . '/inc/page-ch-thank-you.php'; return $page_template; } return $page_template; } add_filter( 'page_template', 'ch_register_page_template' ); ```
217,607
<p>Is there any more elegant way to automatically add the parent categories through PHP (not JavaScript) upon registering categories for a post from some custom page?</p> <p>I Add the categories checked with the following code:</p> <pre><code>wp_set_post_terms($post_id, $catarray, 'category'); </code></pre> <p>And then to automatically add the parent categories I have written this whole switch case that I often need to manually update... =S Is there any more elegant way than the way here down below?</p> <pre><code>foreach ($catarray as $cat) { switch ($cat) { case "228": // アクセサリー case "226": // バッグ case "224": // 衣服 case "231": // 帽子・スカーフ case "229": // ジュエリー case "262": // 雨具 case "227": // 靴 case "230": // 生地 case "232": // 腕時計 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '225')"); // Apparel &amp; Accessories(アパレル&アクセサリー) break; case "252": // カー部品 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '251')"); // カー用品 break; case "284": // 携帯電話・アクセサリー case "266": // 家電 case "222": // オーディオ・映像装置 case "221": // その他のデジタル製品 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '17')"); // デジタル製品&家電 break; case "204": // 乾燥食品 case "197": // 飲料品 case "203": // 青果品 case "206": // 肉類 case "199": // 面類・米&小麦 case "202": // ソース類 case "201": // スパイス・調味料類 case "200": // お菓子・スナック類 case "205": // 野菜類 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '198')"); // 飲食料品 break; case "218": // 浴槽製品 case "220": // 家具 case "216": // キッチン用具・食器 case "219": // 伝統工芸品 case "272": // 雑貨 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '217')"); // 家具・キッチン用具・食器 break; case "254": // すべての農作製品 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '253')"); // 農作製品 break; case "236": // アニメ製品 case "237": // ギフト製品 case "234": // 玩具 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '235')"); // ギフト・玩具・アニメ製品 break; case "214": // 美容器具・製品 case "208": // 化粧品 case "211": // 香水 case "212": // スキンケア製品 case "213": // 石鹸・洗髪料 case "210": // サプリメント・ビタミン $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '209')"); // 健康・美容製品 break; case "250": // 工業製品 case "248": // 建設資材 case "247": // 床材 case "264": // 水周り製品 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '249')"); // 工業・建設資材&製品 break; case "269": // エネルギー・ソーラー case "245": // 照明 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '244')"); // 照明・エネルギー break; case "242": // 芸術品 case "243": // 高級ステレオ $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '241')"); // 高級製品 break; case "261": // 医療品・医薬品 case "267": // 化学製品 case "268": // 研究器具 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '260')"); // 医療品・化学製品・研究器具 break; case "240": // オフィス用品 case "263": // スクラッチカード case "169": // 文房具 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '238')"); // オフィス什器・文房具 break; case "259": // スポーツ器具 case "256": // スポーツウェア case "258": // 運動補助器具 $wpdb-&gt;query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '257')"); // スポーツ関連 break; default: break; } } </code></pre>
[ { "answer_id": 217612, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 2, "selected": false, "text": "<pre><code>function wpse_set_parent_terms($post_id, $post){\n\n $post_type = 'post'; //set the post type you wish to operate on\n $taxonomy = 'category'; //set the taxonomy you wish to operate on\n\n if(get_post_type() !== $post_type) {\n return $post_id;\n }\n\n foreach(wp_get_post_terms($post_id, $taxonomy) as $term){\n\n while($term-&gt;parent !== 0 &amp;&amp; !has_term($term-&gt;parent, $taxonomy, $post)) {\n\n wp_set_post_terms($post_id, array($term-&gt;parent), $taxonomy, true);\n\n $term = get_term($term-&gt;parent, $taxonomy);\n\n }\n\n }\n}\n\nadd_action('save_post', 'wpse_set_parent_terms', 10, 2);\n</code></pre>\n\n<p>This should be pretty... ↓</p>\n\n<p><a href=\"https://i.stack.imgur.com/NZVWV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NZVWV.png\" alt=\"enter image description here\"></a></p>\n\n<p>Hope that helps...</p>\n" }, { "answer_id": 217613, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_post_terms/\" rel=\"nofollow\"><code>wp_set_post_terms()</code></a> uses <a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow\"><code>wp_set_object_terms()</code></a>. There is an action hook called <a href=\"https://developer.wordpress.org/reference/hooks/set_object_terms/\" rel=\"nofollow\"><code>set_object_terms</code></a> which fires on successful setting of an object's terms. The action hook looks like this</p>\n\n<pre><code>do_action ( 'set_object_terms', int $object_id, array $terms, array $tt_ids, string $taxonomy, bool $append, array $old_tt_ids )\n</code></pre>\n\n<p>What we can do here is, inside our action callback function, we can check whether the terms that we inserted is top level, and if not, we can get the parent ID's from the term objects and then add the parent terms to the post object</p>\n\n<p>You can try the following:</p>\n\n<pre><code>add_action( 'set_object_terms', function ( $object_id, $terms, $tt_ids, $taxonomy )\n{\n // Lets make sure we run this only once\n remove_action( current_action(), __FUNCTION__ );\n\n // Lets only target the category taxonomy, if not, lets bail\n if ( 'category' !== $taxonomy ) \n return;\n\n // Make sure we have terms to avoid bugs\n if ( !$tt_ids )\n return;\n\n // Get all the terms already assinged to the post-\n $post_terms = get_the_terms( $object_id, $taxonomy );\n\n if ( $post_terms ) {\n $post_term_ids = wp_list_pluck( $post_terms, 'term_id' );\n\n // Bail if $post_term_ids === $tt_ids\n if ( $post_term_ids === $tt_ids )\n return;\n }\n\n // We are busy with the category taxonomy, continue to execute\n $parent_ids = [];\n\n // Lets loop through the terms and get their parents\n foreach ( $tt_ids as $term ) {\n // Get the term object\n $term_object = get_term_by( 'id', $term, $taxonomy );\n // If top level term, just continue to the next one\n if ( 0 === $term_object-&gt;parent )\n continue;\n\n // Our term is not top level, save the parent term in an array\n $parent_ids[] = $term_object-&gt;parent;\n }\n\n // Make sure we have parent terms, if not, bail\n if ( !$parent_ids )\n return;\n\n // Make sure we do not have duplicate parent term ID's, if so, remove duplicates\n $parent_ids = array_unique( $parent_ids );\n\n // Make sure that our parent id's not in the $terms array, if so, remove them\n $parent_ids = array_diff( $parent_ids, $tt_ids );\n\n // Make sure we still have parent ID's left\n if ( !$parent_ids )\n return;\n\n // Lets add our parent terms to the object's other terms\n wp_set_object_terms( $object_id, $parent_ids, $taxonomy, true );\n\n}, 10, 4 );\n</code></pre>\n\n<h2>EDIT - Use-case</h2>\n\n<p>The above code goes into your <code>functions.php</code> and will automatically add the parent terms to the post if we pass any child terms to <code>wp_set_object_terms()</code>.</p>\n\n<p>Now, in your template, you can do the following</p>\n\n<pre><code>$child_cat_ids = [120]; // Array of child categories\nwp_set_object_terms( \n 147, // Post ID\n $child_cat_ids, // Array of child category ID's\n 'category', // Taxonomy the terms belongs to\n true // Only append terms to existing ones\n);\n</code></pre>\n\n<p>Note that you only need to worry about the child category you want to add to the post. As I said, the action above will take care to add the correct parent term to the post</p>\n" } ]
2016/02/14
[ "https://wordpress.stackexchange.com/questions/217607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87968/" ]
Is there any more elegant way to automatically add the parent categories through PHP (not JavaScript) upon registering categories for a post from some custom page? I Add the categories checked with the following code: ``` wp_set_post_terms($post_id, $catarray, 'category'); ``` And then to automatically add the parent categories I have written this whole switch case that I often need to manually update... =S Is there any more elegant way than the way here down below? ``` foreach ($catarray as $cat) { switch ($cat) { case "228": // アクセサリー case "226": // バッグ case "224": // 衣服 case "231": // 帽子・スカーフ case "229": // ジュエリー case "262": // 雨具 case "227": // 靴 case "230": // 生地 case "232": // 腕時計 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '225')"); // Apparel & Accessories(アパレル&アクセサリー) break; case "252": // カー部品 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '251')"); // カー用品 break; case "284": // 携帯電話・アクセサリー case "266": // 家電 case "222": // オーディオ・映像装置 case "221": // その他のデジタル製品 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '17')"); // デジタル製品&家電 break; case "204": // 乾燥食品 case "197": // 飲料品 case "203": // 青果品 case "206": // 肉類 case "199": // 面類・米&小麦 case "202": // ソース類 case "201": // スパイス・調味料類 case "200": // お菓子・スナック類 case "205": // 野菜類 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '198')"); // 飲食料品 break; case "218": // 浴槽製品 case "220": // 家具 case "216": // キッチン用具・食器 case "219": // 伝統工芸品 case "272": // 雑貨 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '217')"); // 家具・キッチン用具・食器 break; case "254": // すべての農作製品 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '253')"); // 農作製品 break; case "236": // アニメ製品 case "237": // ギフト製品 case "234": // 玩具 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '235')"); // ギフト・玩具・アニメ製品 break; case "214": // 美容器具・製品 case "208": // 化粧品 case "211": // 香水 case "212": // スキンケア製品 case "213": // 石鹸・洗髪料 case "210": // サプリメント・ビタミン $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '209')"); // 健康・美容製品 break; case "250": // 工業製品 case "248": // 建設資材 case "247": // 床材 case "264": // 水周り製品 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '249')"); // 工業・建設資材&製品 break; case "269": // エネルギー・ソーラー case "245": // 照明 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '244')"); // 照明・エネルギー break; case "242": // 芸術品 case "243": // 高級ステレオ $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '241')"); // 高級製品 break; case "261": // 医療品・医薬品 case "267": // 化学製品 case "268": // 研究器具 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '260')"); // 医療品・化学製品・研究器具 break; case "240": // オフィス用品 case "263": // スクラッチカード case "169": // 文房具 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '238')"); // オフィス什器・文房具 break; case "259": // スポーツ器具 case "256": // スポーツウェア case "258": // 運動補助器具 $wpdb->query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('".$post_id."', '257')"); // スポーツ関連 break; default: break; } } ```
[`wp_set_post_terms()`](https://developer.wordpress.org/reference/functions/wp_set_post_terms/) uses [`wp_set_object_terms()`](https://developer.wordpress.org/reference/functions/wp_set_object_terms/). There is an action hook called [`set_object_terms`](https://developer.wordpress.org/reference/hooks/set_object_terms/) which fires on successful setting of an object's terms. The action hook looks like this ``` do_action ( 'set_object_terms', int $object_id, array $terms, array $tt_ids, string $taxonomy, bool $append, array $old_tt_ids ) ``` What we can do here is, inside our action callback function, we can check whether the terms that we inserted is top level, and if not, we can get the parent ID's from the term objects and then add the parent terms to the post object You can try the following: ``` add_action( 'set_object_terms', function ( $object_id, $terms, $tt_ids, $taxonomy ) { // Lets make sure we run this only once remove_action( current_action(), __FUNCTION__ ); // Lets only target the category taxonomy, if not, lets bail if ( 'category' !== $taxonomy ) return; // Make sure we have terms to avoid bugs if ( !$tt_ids ) return; // Get all the terms already assinged to the post- $post_terms = get_the_terms( $object_id, $taxonomy ); if ( $post_terms ) { $post_term_ids = wp_list_pluck( $post_terms, 'term_id' ); // Bail if $post_term_ids === $tt_ids if ( $post_term_ids === $tt_ids ) return; } // We are busy with the category taxonomy, continue to execute $parent_ids = []; // Lets loop through the terms and get their parents foreach ( $tt_ids as $term ) { // Get the term object $term_object = get_term_by( 'id', $term, $taxonomy ); // If top level term, just continue to the next one if ( 0 === $term_object->parent ) continue; // Our term is not top level, save the parent term in an array $parent_ids[] = $term_object->parent; } // Make sure we have parent terms, if not, bail if ( !$parent_ids ) return; // Make sure we do not have duplicate parent term ID's, if so, remove duplicates $parent_ids = array_unique( $parent_ids ); // Make sure that our parent id's not in the $terms array, if so, remove them $parent_ids = array_diff( $parent_ids, $tt_ids ); // Make sure we still have parent ID's left if ( !$parent_ids ) return; // Lets add our parent terms to the object's other terms wp_set_object_terms( $object_id, $parent_ids, $taxonomy, true ); }, 10, 4 ); ``` EDIT - Use-case --------------- The above code goes into your `functions.php` and will automatically add the parent terms to the post if we pass any child terms to `wp_set_object_terms()`. Now, in your template, you can do the following ``` $child_cat_ids = [120]; // Array of child categories wp_set_object_terms( 147, // Post ID $child_cat_ids, // Array of child category ID's 'category', // Taxonomy the terms belongs to true // Only append terms to existing ones ); ``` Note that you only need to worry about the child category you want to add to the post. As I said, the action above will take care to add the correct parent term to the post
217,608
<p>How could I include the following script and stylesheet in a wordpress plugin if they only need to load in the admin panel?</p> <pre><code>&lt;script type="text/javascript" src="/wp-includes/js/jquery/jquery.js?ver=1.11.3"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="assets/chosen.min.css"&gt; &lt;script type="text/javascript" src="assets/chosen.jquery.min.js"&gt;&lt;/script&gt; </code></pre>
[ { "answer_id": 217609, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 1, "selected": false, "text": "<p>There are probably various ways to do this – personally I use the following for loading some small scripts only on the \"new\" and \"edit\" pages (datepicker etc.):</p>\n\n<pre><code>function load_my_admin_scripts( $hook ) {\n\n if (( $hook == 'post.php' || $hook == 'post-new.php' )) {\n\n wp_enqueue_script(\n 'my-datepicker', // name / handle of the script\n SCRIPTS . 'script.js', // path to the script\n array( 'jquery', 'jquery-ui-datepicker' ), // array of registered handles this script depends on\n '1.0', // script version number (optional)\n true // enqueue the script before &lt;/head&gt;\n );\n\n }\n\n}\n\nadd_action( 'admin_enqueue_scripts', 'load_my_admin_scripts' );\n</code></pre>\n" }, { "answer_id": 217611, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": false, "text": "<pre><code>function load_admin_script_wpse_217608() {\n $assets_path = plugins_url('assets/', __FILE__);\n\n wp_enqueue_style('chosen-style', $assets_path . 'chosen.min.css');\n wp_enqueue_script('jquery');\n wp_enqueue_script('chosen-script', $assets_path . 'chosen.jquery.min.js', array(), '1.0.0', true);\n}\n\nadd_action( 'admin_enqueue_scripts', 'load_admin_script_wpse_217608' );\n</code></pre>\n\n<p>Where <code>$assets_path</code> is the path to your assets folder. </p>\n\n<p><strong>Edit</strong>: Props to @cale_b for using <code>plugins_url()</code> to avoid confusion and hard coded strings.</p>\n" }, { "answer_id": 217707, "author": "j8d", "author_id": 81557, "author_profile": "https://wordpress.stackexchange.com/users/81557", "pm_score": 0, "selected": false, "text": "<p>I first added</p>\n\n<pre><code>function __construct() {\n if( is_admin() ) {\n add_action( 'admin_enqueue_scripts', array( &amp;$this, 'xsmi_load_admin_script' ) );\n...\n</code></pre>\n\n<p>since it's in a class.</p>\n\n<p>And the function...</p>\n\n<pre><code>function xsmi_load_admin_script() {\nwp_register_style( 'chosencss', plugins_url( 'assets/chosen.css', __FILE__ ), true, '', 'all' );\nwp_register_script( 'chosenjs', plugins_url( 'assets/chosen.jquery.js', __FILE__ ), array( 'jquery' ), '', true );\nwp_enqueue_style( 'chosencss' );\nwp_enqueue_script( 'chosenjs' );\n}\n</code></pre>\n\n<p>The <code>true</code> at the end of <code>wp_register_script</code> loads it in the footer. This is the only way I could get it to work. That for the help!</p>\n" } ]
2016/02/14
[ "https://wordpress.stackexchange.com/questions/217608", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81557/" ]
How could I include the following script and stylesheet in a wordpress plugin if they only need to load in the admin panel? ``` <script type="text/javascript" src="/wp-includes/js/jquery/jquery.js?ver=1.11.3"></script> <link rel="stylesheet" type="text/css" href="assets/chosen.min.css"> <script type="text/javascript" src="assets/chosen.jquery.min.js"></script> ```
There are probably various ways to do this – personally I use the following for loading some small scripts only on the "new" and "edit" pages (datepicker etc.): ``` function load_my_admin_scripts( $hook ) { if (( $hook == 'post.php' || $hook == 'post-new.php' )) { wp_enqueue_script( 'my-datepicker', // name / handle of the script SCRIPTS . 'script.js', // path to the script array( 'jquery', 'jquery-ui-datepicker' ), // array of registered handles this script depends on '1.0', // script version number (optional) true // enqueue the script before </head> ); } } add_action( 'admin_enqueue_scripts', 'load_my_admin_scripts' ); ```
217,646
<p>I want to have different sized previews for different kinds of work I've done. Say 100x100px for regular stuff, but 200x200px for a bigger project.</p> <p>I figure I can use category to sort, and I know how to call that separately, but I don't want to list all the 'premium' stuff first and then the rest later. I want all works to appear (roughly) in the correct order, but with some projects at a larger scale. This would still call more attention to them, but a bit more playfully than clumping them all together.</p> <p><a href="https://i.stack.imgur.com/mFFkk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mFFkk.png" alt="enter image description here"></a></p> <p>Is there some way to add a CSS class to certain excerpts halfway through the loop? Maybe it's possible to filter by combining a CSS classes of the excerpt and the category? Can I do something with tags? Perhaps another solution I'm missing?</p>
[ { "answer_id": 217609, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 1, "selected": false, "text": "<p>There are probably various ways to do this – personally I use the following for loading some small scripts only on the \"new\" and \"edit\" pages (datepicker etc.):</p>\n\n<pre><code>function load_my_admin_scripts( $hook ) {\n\n if (( $hook == 'post.php' || $hook == 'post-new.php' )) {\n\n wp_enqueue_script(\n 'my-datepicker', // name / handle of the script\n SCRIPTS . 'script.js', // path to the script\n array( 'jquery', 'jquery-ui-datepicker' ), // array of registered handles this script depends on\n '1.0', // script version number (optional)\n true // enqueue the script before &lt;/head&gt;\n );\n\n }\n\n}\n\nadd_action( 'admin_enqueue_scripts', 'load_my_admin_scripts' );\n</code></pre>\n" }, { "answer_id": 217611, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": false, "text": "<pre><code>function load_admin_script_wpse_217608() {\n $assets_path = plugins_url('assets/', __FILE__);\n\n wp_enqueue_style('chosen-style', $assets_path . 'chosen.min.css');\n wp_enqueue_script('jquery');\n wp_enqueue_script('chosen-script', $assets_path . 'chosen.jquery.min.js', array(), '1.0.0', true);\n}\n\nadd_action( 'admin_enqueue_scripts', 'load_admin_script_wpse_217608' );\n</code></pre>\n\n<p>Where <code>$assets_path</code> is the path to your assets folder. </p>\n\n<p><strong>Edit</strong>: Props to @cale_b for using <code>plugins_url()</code> to avoid confusion and hard coded strings.</p>\n" }, { "answer_id": 217707, "author": "j8d", "author_id": 81557, "author_profile": "https://wordpress.stackexchange.com/users/81557", "pm_score": 0, "selected": false, "text": "<p>I first added</p>\n\n<pre><code>function __construct() {\n if( is_admin() ) {\n add_action( 'admin_enqueue_scripts', array( &amp;$this, 'xsmi_load_admin_script' ) );\n...\n</code></pre>\n\n<p>since it's in a class.</p>\n\n<p>And the function...</p>\n\n<pre><code>function xsmi_load_admin_script() {\nwp_register_style( 'chosencss', plugins_url( 'assets/chosen.css', __FILE__ ), true, '', 'all' );\nwp_register_script( 'chosenjs', plugins_url( 'assets/chosen.jquery.js', __FILE__ ), array( 'jquery' ), '', true );\nwp_enqueue_style( 'chosencss' );\nwp_enqueue_script( 'chosenjs' );\n}\n</code></pre>\n\n<p>The <code>true</code> at the end of <code>wp_register_script</code> loads it in the footer. This is the only way I could get it to work. That for the help!</p>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88691/" ]
I want to have different sized previews for different kinds of work I've done. Say 100x100px for regular stuff, but 200x200px for a bigger project. I figure I can use category to sort, and I know how to call that separately, but I don't want to list all the 'premium' stuff first and then the rest later. I want all works to appear (roughly) in the correct order, but with some projects at a larger scale. This would still call more attention to them, but a bit more playfully than clumping them all together. [![enter image description here](https://i.stack.imgur.com/mFFkk.png)](https://i.stack.imgur.com/mFFkk.png) Is there some way to add a CSS class to certain excerpts halfway through the loop? Maybe it's possible to filter by combining a CSS classes of the excerpt and the category? Can I do something with tags? Perhaps another solution I'm missing?
There are probably various ways to do this – personally I use the following for loading some small scripts only on the "new" and "edit" pages (datepicker etc.): ``` function load_my_admin_scripts( $hook ) { if (( $hook == 'post.php' || $hook == 'post-new.php' )) { wp_enqueue_script( 'my-datepicker', // name / handle of the script SCRIPTS . 'script.js', // path to the script array( 'jquery', 'jquery-ui-datepicker' ), // array of registered handles this script depends on '1.0', // script version number (optional) true // enqueue the script before </head> ); } } add_action( 'admin_enqueue_scripts', 'load_my_admin_scripts' ); ```
217,674
<p>I don't know what I'm doing wrong... I'm using the starter timber theme... I'm trying unslider to work with my theme... indicated here is somehow a proof I did right in putting scripts from the function.php... </p> <pre><code>&lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/jquery.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/resources/bootstrap/js/bootstrap.min.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/bootstrap-wp.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/skip-link-focus-fix.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/unislider/js/unslider-min.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/stickyFooter.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/script.js?ver=1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/luxjeweler/wp-includes/js/wp-embed.min.js?ver=4.4.2'&gt;&lt;/script&gt; </code></pre> <p>but somehow jquery is not working... tried using the jquery enqueue default provided by wordpress and a custom enqueue but with no success... I tried testing by using this simple code:</p> <pre><code>$(document).ready(function(){ alert("test"); }); </code></pre> <p>no response when I refresh the page... </p> <h3>Edit (15-02-16):</h3> <p>This is my enqueue function:</p> <pre><code>function luxjewels_scripts() { // Import the necessary TK Bootstrap WP CSS additions wp_enqueue_style( 'luxjewels-bootstrap-wp', get_template_directory_uri() . '/includes/css/bootstrap-wp.css', false, '1'); // load bootstrap css wp_enqueue_style( 'luxjewels-bootstrap', get_template_directory_uri() . '/includes/resources/bootstrap/css/bootstrap.css', false, '1' ); // load Font Awesome css wp_enqueue_style( 'luxjewels-font-awesome', get_template_directory_uri() . '/includes/css/font-awesome.min.css', false, '1' ); // load styles wp_enqueue_style( 'luxjewels-style', get_stylesheet_uri() ); wp_enqueue_style( 'luxjewels-unslider', get_template_directory_uri() . '/includes/unslider/css/unslider.css', true, '1'); wp_enqueue_script( 'luxjewels-jquery', get_template_directory_uri() . '/includes/js/jquery.js', array(), '1', true ); // load bootstrap js wp_enqueue_script('luxjewels-bootstrapjs', get_template_directory_uri().'/includes/resources/bootstrap/js/bootstrap.min.js', array(), '1', true); // load bootstrap wp js wp_enqueue_script( 'luxjewels-bootstrapwp', get_template_directory_uri() . '/includes/js/bootstrap-wp.js', array(), '1', true); wp_enqueue_script( 'luxjewels-skip-link-focus-fix', get_template_directory_uri() . '/includes/js/skip-link-focus-fix.js', array(), '1', true ); // load Unslider js and css wp_enqueue_style( 'luxjewels-unslider-dots', get_template_directory_uri() . '/includes/unslider/css/unslider-dots.css', false, '1', true); wp_enqueue_script('luxjewels-unslider-min', get_template_directory_uri().'/includes/unslider/js/unslider-min.js', array(), '1', true); // load stickyfooter js wp_enqueue_script( 'luxjewels-stickyfooter', get_template_directory_uri() . '/includes/js/stickyFooter.js', array(), '1', true ); // load custom js wp_enqueue_script( 'luxjewels-custom-script', get_template_directory_uri() . '/script.js', array(), '1', true ); } add_action( 'wp_enqueue_scripts', 'luxjewels_scripts' ); </code></pre>
[ { "answer_id": 217677, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": false, "text": "<p>Remove this line:</p>\n\n<pre><code>wp_enqueue_script( 'luxjewels-jquery', get_template_directory_uri() . '/includes/js/jquery.js', array(), '1', true );\n</code></pre>\n\n<p>And replace the following line:</p>\n\n<pre><code>wp_enqueue_script( 'luxjewels-custom-script', get_template_directory_uri() . '/script.js', array(), '1', true );\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>wp_enqueue_script( 'luxjewels-custom-script', get_template_directory_uri() . '/script.js', array('jquery'), '1', true );\n</code></pre>\n\n<h3>Explanation:</h3>\n\n<p>The instead of loading our custom jQuery library, we can simply load jQuery from the core. And declaring dependency, we're doing this simply by modifying our second line of code.</p>\n" }, { "answer_id": 217684, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": true, "text": "<pre><code>$(document).ready(function(){\n alert(\"test\");\n}); \n</code></pre>\n\n<p>It could be that your jQuery is working in compatibility mode. Try replacing <code>$</code> with jQuery:</p>\n\n<pre><code>jQuery(document).ready(function(){\n alert(\"test\");\n}); \n</code></pre>\n\n<p>Edit: As per the author edit on the post:</p>\n\n<pre><code>jQuery(document).ready(function(){\n jQuery('.automatic-slider').unslider({\n autoplay: true\n });\n}); \n</code></pre>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217674", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86161/" ]
I don't know what I'm doing wrong... I'm using the starter timber theme... I'm trying unslider to work with my theme... indicated here is somehow a proof I did right in putting scripts from the function.php... ``` <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/jquery.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/resources/bootstrap/js/bootstrap.min.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/bootstrap-wp.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/skip-link-focus-fix.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/unislider/js/unslider-min.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/includes/js/stickyFooter.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-content/themes/timber-starter-theme-master/script.js?ver=1'></script> <script type='text/javascript' src='http://localhost/luxjeweler/wp-includes/js/wp-embed.min.js?ver=4.4.2'></script> ``` but somehow jquery is not working... tried using the jquery enqueue default provided by wordpress and a custom enqueue but with no success... I tried testing by using this simple code: ``` $(document).ready(function(){ alert("test"); }); ``` no response when I refresh the page... ### Edit (15-02-16): This is my enqueue function: ``` function luxjewels_scripts() { // Import the necessary TK Bootstrap WP CSS additions wp_enqueue_style( 'luxjewels-bootstrap-wp', get_template_directory_uri() . '/includes/css/bootstrap-wp.css', false, '1'); // load bootstrap css wp_enqueue_style( 'luxjewels-bootstrap', get_template_directory_uri() . '/includes/resources/bootstrap/css/bootstrap.css', false, '1' ); // load Font Awesome css wp_enqueue_style( 'luxjewels-font-awesome', get_template_directory_uri() . '/includes/css/font-awesome.min.css', false, '1' ); // load styles wp_enqueue_style( 'luxjewels-style', get_stylesheet_uri() ); wp_enqueue_style( 'luxjewels-unslider', get_template_directory_uri() . '/includes/unslider/css/unslider.css', true, '1'); wp_enqueue_script( 'luxjewels-jquery', get_template_directory_uri() . '/includes/js/jquery.js', array(), '1', true ); // load bootstrap js wp_enqueue_script('luxjewels-bootstrapjs', get_template_directory_uri().'/includes/resources/bootstrap/js/bootstrap.min.js', array(), '1', true); // load bootstrap wp js wp_enqueue_script( 'luxjewels-bootstrapwp', get_template_directory_uri() . '/includes/js/bootstrap-wp.js', array(), '1', true); wp_enqueue_script( 'luxjewels-skip-link-focus-fix', get_template_directory_uri() . '/includes/js/skip-link-focus-fix.js', array(), '1', true ); // load Unslider js and css wp_enqueue_style( 'luxjewels-unslider-dots', get_template_directory_uri() . '/includes/unslider/css/unslider-dots.css', false, '1', true); wp_enqueue_script('luxjewels-unslider-min', get_template_directory_uri().'/includes/unslider/js/unslider-min.js', array(), '1', true); // load stickyfooter js wp_enqueue_script( 'luxjewels-stickyfooter', get_template_directory_uri() . '/includes/js/stickyFooter.js', array(), '1', true ); // load custom js wp_enqueue_script( 'luxjewels-custom-script', get_template_directory_uri() . '/script.js', array(), '1', true ); } add_action( 'wp_enqueue_scripts', 'luxjewels_scripts' ); ```
``` $(document).ready(function(){ alert("test"); }); ``` It could be that your jQuery is working in compatibility mode. Try replacing `$` with jQuery: ``` jQuery(document).ready(function(){ alert("test"); }); ``` Edit: As per the author edit on the post: ``` jQuery(document).ready(function(){ jQuery('.automatic-slider').unslider({ autoplay: true }); }); ```
217,675
<p>This shouldn't be so hard! But I cannot find the answer to this question on Google..</p> <p>How can I link from an attachment template to the full post please?</p> <p>Bonus question!</p> <p>How can I grab the custom field data from the post that the attachment belong to on the attachment template?</p> <p>I use this to grab the data on other template files:</p> <pre><code>&lt;?php echo get_post_meta($post-&gt;ID, 'custom-field', true); ?&gt; </code></pre>
[ { "answer_id": 217680, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><em>Q: How can I link from an attachment template to the full post please?</em></p>\n</blockquote>\n\n<p>I think you are referring to something like <a href=\"https://github.com/nanodesigns/nano-progga/blob/master/image.php#L18-L30\" rel=\"nofollow\">this</a>:</p>\n\n<pre><code>&lt;a class=\"back-to-article\" href=\"&lt;?php echo get_permalink($post-&gt;post_parent); ?&gt;\"&gt;\n &lt;?php _e('Get to Main Article', 'textdomain'); ?&gt;\n&lt;a/&gt;\n</code></pre>\n\n<blockquote>\n <p><em>Q: How can I grab the custom field data from the post that the attachment belong to on the attachment template?</em></p>\n</blockquote>\n\n<p>Answering because it's your first question. From the next time, one question per se, please.</p>\n\n<p>Your code was correct. You can use the code within a loop like:</p>\n\n<pre><code>echo get_post_meta(get_the_ID(), 'custom-field', true);\n</code></pre>\n\n<p>or you can use with global:</p>\n\n<pre><code>global $post;\necho get_post_meta($post-&gt;ID, 'custom-field', true);\n</code></pre>\n\n<p>Please check the whole code on the github repo for more idea.</p>\n" }, { "answer_id": 217681, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>If the attachment is attached to a post, the post is determined as \"post_parent\".</p>\n\n<p>So, if you are in the attachement template (attachment.php, image.php, etc):</p>\n\n<pre><code>while ( have_posts() ) {\n the_post();\n // Get parent id of current post (get_the_ID() gets id of current post,\n // whicdh is the attachement, as we are in the attachment template)\n $parent_id = wp_get_post_parent_id( get_the_ID() );\n\n}\n</code></pre>\n\n<p>You can get the parent id also with this method, but I just prefer the other:</p>\n\n<pre><code>while ( have_posts() ) {\n the_post();\n global $post;\n $parent_id = $post-&gt;post_parent;\n}\n</code></pre>\n\n<p>Once you have the parent post ID, you can get the link, custom fields or whatever you want of the parent post:</p>\n\n<pre><code> if( $parent_id ) {\n // parent post has been found, get its permalink\n $parent_url = get_permalink( $parent_id );\n\n ?&gt;\n &lt;a href=\"&lt;?php echo $parent_url; ?&gt;\"&gt;\n &lt;?php _e('Go to parent post', 'textdomain'); ?&gt;\n &lt;a/&gt;\n &lt;?php\n echo get_post_meta( $parent_id, 'custom-field', true );\n }\n</code></pre>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10425/" ]
This shouldn't be so hard! But I cannot find the answer to this question on Google.. How can I link from an attachment template to the full post please? Bonus question! How can I grab the custom field data from the post that the attachment belong to on the attachment template? I use this to grab the data on other template files: ``` <?php echo get_post_meta($post->ID, 'custom-field', true); ?> ```
If the attachment is attached to a post, the post is determined as "post\_parent". So, if you are in the attachement template (attachment.php, image.php, etc): ``` while ( have_posts() ) { the_post(); // Get parent id of current post (get_the_ID() gets id of current post, // whicdh is the attachement, as we are in the attachment template) $parent_id = wp_get_post_parent_id( get_the_ID() ); } ``` You can get the parent id also with this method, but I just prefer the other: ``` while ( have_posts() ) { the_post(); global $post; $parent_id = $post->post_parent; } ``` Once you have the parent post ID, you can get the link, custom fields or whatever you want of the parent post: ``` if( $parent_id ) { // parent post has been found, get its permalink $parent_url = get_permalink( $parent_id ); ?> <a href="<?php echo $parent_url; ?>"> <?php _e('Go to parent post', 'textdomain'); ?> <a/> <?php echo get_post_meta( $parent_id, 'custom-field', true ); } ```
217,685
<p>On <a href="http://test.doig.com.au/meyer/" rel="nofollow">this site</a>, I have the following form which allows a visitor to select from a choice of mortgage calculators to use:</p> <pre><code>&lt;select id="dynamic_select" name="cars"&gt; &lt;option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA"&gt;Borrowing Power Calculator&lt;/option&gt; ... &lt;/select&gt;&lt;input id="Submitgo" type="submit" style="float:right; clear:both;"/&gt;&lt;/p&gt; &lt;br class="cleanBreak" /&gt; &lt;script&gt;// &lt;![CDATA[ $('#Submitgo').on('click', function() { var url = $('#dynamic_select').val(); window.location = url; }); // ]]&gt;&lt;/script&gt; </code></pre> <p>When the form selection is chosen, and the submit button is clicked, the user is taken to an external page where the calculator is displayed.</p> <p>I would like the form to display within a new Wordpress page. </p> <p>Unfortunately I am designer, not a developer, so I do not know where to start.</p> <p>I gather perhaps I can change <code>window.location = url</code> to equate to a Wordpress URL?</p> <p>Perhaps I need to embed the url within an iframe? However, I don't know how to get the window.location to forward to a Wordpress page with an iframe containing the calculator URL.</p> <p>Thanks.</p>
[ { "answer_id": 217688, "author": "kinjal jethva", "author_id": 88703, "author_profile": "https://wordpress.stackexchange.com/users/88703", "pm_score": 0, "selected": false, "text": "<p>You should get results using below code:</p>\n\n<pre><code>$( \"#dynamic_select\" ).change( function() {\n var changingUrl = $( this ).val();\n window.location = changingUrl;\n} );\n</code></pre>\n\n<p>Here you will get a selected option URL by selecting an option from the select box as:</p>\n\n<pre><code>var changingUrl = $( this ).val();\n</code></pre>\n\n<p>Then redirect the page as you want using:</p>\n\n<pre><code>window.location = changingUrl;\n</code></pre>\n" }, { "answer_id": 218216, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": false, "text": "<p>Since you don't have access to this website and form your best bet will be to use an <code>&lt;iframe&gt;</code>. Paste this in some page:</p>\n\n<pre><code>&lt;iframe src=\"http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA\" style=\"height: 100%; width: 700px;\"&gt;\n &lt;p&gt;\n &lt;a href=\"http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA\"&gt;\n Fallback link for browsers that, unlikely, don't support frames\n &lt;/a&gt;\n &lt;/p&gt;\n&lt;/iframe&gt;\n</code></pre>\n\n<p>Although keep in mind that some browsers won't show the form as well as if you use it on a page with <code>HTTPS</code> the form won't be show and you will get <code>Mixed Content</code> errors.</p>\n" }, { "answer_id": 218330, "author": "nonsensecreativity", "author_id": 10997, "author_profile": "https://wordpress.stackexchange.com/users/10997", "pm_score": 2, "selected": false, "text": "<p>It's better to use Iframe in this case. Here is how I will do it. Do you really need the submit button? in this case I do it without submit button, you can change it to your needs. This example codes can be added to your WordPress page through <strong>Text</strong> Tab on editor</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n .hideframe {\n visibility:collapse;\n display:hidden;\n height:0px;\n }\n&lt;/style&gt;\n\n&lt;select id=\"car\" name=\"car\"&gt;\n &lt;option value=\"none\"&gt;None&lt;/option&gt;\n &lt;option value=\"calc\"&gt;Borrowing Power Calculator&lt;/option&gt; \n&lt;/select&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n window.onload = function() {\n document.getElementById( 'car' ).onchange = function() {\n var calc = document.getElementById( 'calc' );\n if( this.value === 'calc' ) {\n calc.classList.remove( 'hideframe' );\n } else {\n calc.classList.add( 'hideframe' );\n }\n };\n }\n&lt;/script&gt;\n\n&lt;!-- iframe start --&gt;\n\n&lt;div id=\"calc\" class=\"hideframe\"&gt;\n &lt;iframe src=\"http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA\" /&gt;\n&lt;/div&gt;\n&lt;!-- iframe end --&gt;\n</code></pre>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
On [this site](http://test.doig.com.au/meyer/), I have the following form which allows a visitor to select from a choice of mortgage calculators to use: ``` <select id="dynamic_select" name="cars"> <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA">Borrowing Power Calculator</option> ... </select><input id="Submitgo" type="submit" style="float:right; clear:both;"/></p> <br class="cleanBreak" /> <script>// <![CDATA[ $('#Submitgo').on('click', function() { var url = $('#dynamic_select').val(); window.location = url; }); // ]]></script> ``` When the form selection is chosen, and the submit button is clicked, the user is taken to an external page where the calculator is displayed. I would like the form to display within a new Wordpress page. Unfortunately I am designer, not a developer, so I do not know where to start. I gather perhaps I can change `window.location = url` to equate to a Wordpress URL? Perhaps I need to embed the url within an iframe? However, I don't know how to get the window.location to forward to a Wordpress page with an iframe containing the calculator URL. Thanks.
It's better to use Iframe in this case. Here is how I will do it. Do you really need the submit button? in this case I do it without submit button, you can change it to your needs. This example codes can be added to your WordPress page through **Text** Tab on editor ``` <style type="text/css"> .hideframe { visibility:collapse; display:hidden; height:0px; } </style> <select id="car" name="car"> <option value="none">None</option> <option value="calc">Borrowing Power Calculator</option> </select> <script type="text/javascript"> window.onload = function() { document.getElementById( 'car' ).onchange = function() { var calc = document.getElementById( 'calc' ); if( this.value === 'calc' ) { calc.classList.remove( 'hideframe' ); } else { calc.classList.add( 'hideframe' ); } }; } </script> <!-- iframe start --> <div id="calc" class="hideframe"> <iframe src="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA" /> </div> <!-- iframe end --> ```
217,737
<p>I'm running a WordPress 4.4.2. I have one site that's working fine. When I went to set up another site, I got the following error upon trying to save the "general" settings page:</p> <pre><code>Catchable fatal error: Object of class WP_Error could not be converted to string in /{site-url}/wp-includes/formatting.php on line 1025' </code></pre> <p>Before saving the settings, I deleted the existing sample page and sample post and created a new page. Didn't touch anything else.</p> <p>After researching the problem, I have done all of the following:</p> <ul> <li>Deactivated all plugins (error persists)</li> <li>Changed to default WordPress theme (error persists)</li> <li>Reinstalled current WordPress version (error persists)</li> <li>Upgraded the network (error persists)</li> <li>Checked Options tables in phpMyAdmin, no fishy strings exist</li> <li>Compared Options table between the site with and without the error, they seem identical</li> <li>Run the WP-Optimize plugin</li> </ul> <p>I notice that I can only save values to the Options table from phpMyAdmin. When I try via the browser (ex. <code>wp-admin/network/site-settings.php?id=#</code>), the options don't save.</p> <p>When I set an additional site to test, I don't have this problem. Obviously, I can just delete the site and start over, but a) the problem exists also on my default multisite, and b) I'd like to understand what's causing it.</p> <p>Is this a bug? Am I missing something obvious?</p>
[ { "answer_id": 217728, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>With this sort of question, the simplest thing to do is to <a href=\"https://codex.wordpress.org/Function_Reference/the_author_meta\" rel=\"nofollow\">look it up in Codex</a> then follow the link to see <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/author-template.php#L113\" rel=\"nofollow\">the function in source</a>.</p>\n\n<p>There we can see that <code>the_author_meta</code> just calls <code>get_the_author_meta</code> and passes the result through a filter.</p>\n\n<pre><code>function the_author_meta( $field = '', $user_id = false ) {\n $author_meta = get_the_author_meta( $field, $user_id );\n\n echo apply_filters( 'the_author_' . $field, $author_meta, $user_id );\n}\n</code></pre>\n\n<p>Another important thing to note is that, like post metadata, when you request a single meta item, all of it is loaded and cached, so it doesn't really matter if you fetch one meta field or 50, it's just a single trip to the database to fetch it all in both cases.</p>\n" }, { "answer_id": 217729, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>If you look at the source code for <a href=\"https://developer.wordpress.org/reference/functions/the_author_meta/\" rel=\"noreferrer\"><code>the_author_meta()</code></a>, it simply, in essence, just echo's the result from <a href=\"https://developer.wordpress.org/reference/functions/get_the_author_meta/\" rel=\"noreferrer\"><code>get_the_author_meta()</code></a>.</p>\n\n<p>WordPress has quite a lot of functions where functions with a <code>the_*</code> prefix simply echos the results from its <code>get_*</code> counter parts. The <code>get_*</code> prefix is almost always used for functions which return its results. </p>\n\n<p>There is really no performance differences between the two functions here, and you can use anyone to your liking, although each actually has each own specific use. Use <code>the_author_meta()</code> if you need to display the data, it looks a bit nutty to use <code>echo get_the_author_meta()</code>. Use <code>get_the_author_meta()</code> if you need to store the data for later use, or in shortcodes which require returned content </p>\n\n<h2>EDIT</h2>\n\n<p>You can always look up the source code on <a href=\"https://developer.wordpress.org\" rel=\"noreferrer\">https://developer.wordpress.org</a>, something you should always do. Never ever take something for granted. Just an example of the above, <code>get_the_content()</code> return unfiltered, raw post content, <code>the_content</code> returns the filtered content from the <code>get_the_content()</code>, so they are vastly apart in what they do</p>\n\n<h2>EDIT 2</h2>\n\n<blockquote>\n <p>....is there a third better alternative</p>\n</blockquote>\n\n<p>If you look at the source code from <code>get_the_author_meta()</code>, it uses <a href=\"https://developer.wordpress.org/reference/functions/get_userdata/\" rel=\"noreferrer\"><code>get_userdata()</code></a> which returns all the fields you might be interested in</p>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217737", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43669/" ]
I'm running a WordPress 4.4.2. I have one site that's working fine. When I went to set up another site, I got the following error upon trying to save the "general" settings page: ``` Catchable fatal error: Object of class WP_Error could not be converted to string in /{site-url}/wp-includes/formatting.php on line 1025' ``` Before saving the settings, I deleted the existing sample page and sample post and created a new page. Didn't touch anything else. After researching the problem, I have done all of the following: * Deactivated all plugins (error persists) * Changed to default WordPress theme (error persists) * Reinstalled current WordPress version (error persists) * Upgraded the network (error persists) * Checked Options tables in phpMyAdmin, no fishy strings exist * Compared Options table between the site with and without the error, they seem identical * Run the WP-Optimize plugin I notice that I can only save values to the Options table from phpMyAdmin. When I try via the browser (ex. `wp-admin/network/site-settings.php?id=#`), the options don't save. When I set an additional site to test, I don't have this problem. Obviously, I can just delete the site and start over, but a) the problem exists also on my default multisite, and b) I'd like to understand what's causing it. Is this a bug? Am I missing something obvious?
If you look at the source code for [`the_author_meta()`](https://developer.wordpress.org/reference/functions/the_author_meta/), it simply, in essence, just echo's the result from [`get_the_author_meta()`](https://developer.wordpress.org/reference/functions/get_the_author_meta/). WordPress has quite a lot of functions where functions with a `the_*` prefix simply echos the results from its `get_*` counter parts. The `get_*` prefix is almost always used for functions which return its results. There is really no performance differences between the two functions here, and you can use anyone to your liking, although each actually has each own specific use. Use `the_author_meta()` if you need to display the data, it looks a bit nutty to use `echo get_the_author_meta()`. Use `get_the_author_meta()` if you need to store the data for later use, or in shortcodes which require returned content EDIT ---- You can always look up the source code on <https://developer.wordpress.org>, something you should always do. Never ever take something for granted. Just an example of the above, `get_the_content()` return unfiltered, raw post content, `the_content` returns the filtered content from the `get_the_content()`, so they are vastly apart in what they do EDIT 2 ------ > > ....is there a third better alternative > > > If you look at the source code from `get_the_author_meta()`, it uses [`get_userdata()`](https://developer.wordpress.org/reference/functions/get_userdata/) which returns all the fields you might be interested in
217,738
<p>I have a code which calculates estimated reading time of a blog post <em>(feel free to use it as you wish)</em>:</p> <pre><code>function estimated_reading_time( $post ) { $words = str_word_count( strip_tags( $post-&gt;post_content ) ); //Average reading speed of an adult is 200-250 words per minute $minutes = floor( $words / 200 ); $seconds = floor( $words % 200 / ( 200 / 60 ) ); //At least a minute if ( $minutes &gt;= 1 ) { $estimated_time = $minutes . ' minute' . ( $minutes == 1 ? '' : 's' ) . ', ' . $seconds . ' second' . ( $seconds == 1 ? '' : 's' ); } //Less than a minute else { $estimated_time = $seconds . ' second' . ($seconds == 1 ? '' : 's'); } return $estimated_time; } </code></pre> <p><strong>Problem:</strong> This function is suitable for the page generating loop however it is unnessesary to run this function for every blog post in every page load in a blog. It would be smarter to save it as post meta.</p> <hr> <p><strong>Question:</strong> How to save <code>$estimated_time</code> as post meta to WordPress default blog post?</p> <p>Are there any actions, hooks or callbacks that I could use in <code>functions.php</code> or in a plugin?</p> <p>PS! It should save the value when post is created and also when it's edited later on.. </p>
[ { "answer_id": 217739, "author": "BillK", "author_id": 87352, "author_profile": "https://wordpress.stackexchange.com/users/87352", "pm_score": 0, "selected": false, "text": "<p>Hook your function to <code>save_post</code>. Use <code>add_post_meta</code> to add the field for a new post or update if this is an edit. See the <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">Codex</a> for adding vs. updating custom fields.</p>\n" }, { "answer_id": 217740, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 3, "selected": true, "text": "<p>You can use the action hook <code>save_post_{post_type}</code>, so for the post type 'post' (blog posts) it is: <code>save_post_post</code>. For more info see the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">codex</a>.</p>\n\n<pre><code>add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3);\n\nfunction sw150216_save_reading_time( $post_id, $post, $update ) {\n $reading_time = estimated_reading_time( $post );\n if ( $update ) {\n update_post_meta ( $post_id, 'reading_time', $reading_time );\n } else {\n add_post_meta( $post_id, 'reading_time', $reading_time, true );\n }\n}\n</code></pre>\n" } ]
2016/02/15
[ "https://wordpress.stackexchange.com/questions/217738", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
I have a code which calculates estimated reading time of a blog post *(feel free to use it as you wish)*: ``` function estimated_reading_time( $post ) { $words = str_word_count( strip_tags( $post->post_content ) ); //Average reading speed of an adult is 200-250 words per minute $minutes = floor( $words / 200 ); $seconds = floor( $words % 200 / ( 200 / 60 ) ); //At least a minute if ( $minutes >= 1 ) { $estimated_time = $minutes . ' minute' . ( $minutes == 1 ? '' : 's' ) . ', ' . $seconds . ' second' . ( $seconds == 1 ? '' : 's' ); } //Less than a minute else { $estimated_time = $seconds . ' second' . ($seconds == 1 ? '' : 's'); } return $estimated_time; } ``` **Problem:** This function is suitable for the page generating loop however it is unnessesary to run this function for every blog post in every page load in a blog. It would be smarter to save it as post meta. --- **Question:** How to save `$estimated_time` as post meta to WordPress default blog post? Are there any actions, hooks or callbacks that I could use in `functions.php` or in a plugin? PS! It should save the value when post is created and also when it's edited later on..
You can use the action hook `save_post_{post_type}`, so for the post type 'post' (blog posts) it is: `save_post_post`. For more info see the [codex](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). ``` add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3); function sw150216_save_reading_time( $post_id, $post, $update ) { $reading_time = estimated_reading_time( $post ); if ( $update ) { update_post_meta ( $post_id, 'reading_time', $reading_time ); } else { add_post_meta( $post_id, 'reading_time', $reading_time, true ); } } ```
217,750
<p>Goodevening,</p> <p>i create a CPT (newsletter) and i want to hide from specific pages. I try to do that with many ways, but the newsletter not hide.</p> <p>Edit: I want to hide in page subscribe {slug} and 6677 {id}</p> <p>1) JQuery</p> <pre><code> jQuery(document).ready(function($) { if (window.location.pathname == "localhost/mysite/subscribe/") { $('.subscribe').hide(); } }); </code></pre> <p>2) Conditional tags</p> <pre><code>&lt;?php if(is_page(6677) ) { ?&gt; &lt;style&gt; .subscribe-content{ display: none!important; } &lt;/style&gt; &lt;?php } ?&gt; </code></pre> <p>3) parameters in CPT array</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'subscribe', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'post__not_in' =&gt; array(6677,613), 'caller_get_posts'=&gt; 1 ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;?php the_content();?&gt; &lt;?php endwhile; else : ?&gt; &lt;center&gt;&lt;h2&gt; Do nothing&lt;/h2&gt;&lt;/center&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre> <p>Thanks in advanced. </p>
[ { "answer_id": 217739, "author": "BillK", "author_id": 87352, "author_profile": "https://wordpress.stackexchange.com/users/87352", "pm_score": 0, "selected": false, "text": "<p>Hook your function to <code>save_post</code>. Use <code>add_post_meta</code> to add the field for a new post or update if this is an edit. See the <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">Codex</a> for adding vs. updating custom fields.</p>\n" }, { "answer_id": 217740, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 3, "selected": true, "text": "<p>You can use the action hook <code>save_post_{post_type}</code>, so for the post type 'post' (blog posts) it is: <code>save_post_post</code>. For more info see the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">codex</a>.</p>\n\n<pre><code>add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3);\n\nfunction sw150216_save_reading_time( $post_id, $post, $update ) {\n $reading_time = estimated_reading_time( $post );\n if ( $update ) {\n update_post_meta ( $post_id, 'reading_time', $reading_time );\n } else {\n add_post_meta( $post_id, 'reading_time', $reading_time, true );\n }\n}\n</code></pre>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Goodevening, i create a CPT (newsletter) and i want to hide from specific pages. I try to do that with many ways, but the newsletter not hide. Edit: I want to hide in page subscribe {slug} and 6677 {id} 1) JQuery ``` jQuery(document).ready(function($) { if (window.location.pathname == "localhost/mysite/subscribe/") { $('.subscribe').hide(); } }); ``` 2) Conditional tags ``` <?php if(is_page(6677) ) { ?> <style> .subscribe-content{ display: none!important; } </style> <?php } ?> ``` 3) parameters in CPT array ``` <?php $args = array( 'post_type' => 'subscribe', 'post_status' => 'publish', 'posts_per_page' => -1, 'post__not_in' => array(6677,613), 'caller_get_posts'=> 1 ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php the_content();?> <?php endwhile; else : ?> <center><h2> Do nothing</h2></center> <?php endif; ?> <?php wp_reset_postdata(); ?> ``` Thanks in advanced.
You can use the action hook `save_post_{post_type}`, so for the post type 'post' (blog posts) it is: `save_post_post`. For more info see the [codex](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). ``` add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3); function sw150216_save_reading_time( $post_id, $post, $update ) { $reading_time = estimated_reading_time( $post ); if ( $update ) { update_post_meta ( $post_id, 'reading_time', $reading_time ); } else { add_post_meta( $post_id, 'reading_time', $reading_time, true ); } } ```
217,755
<p>I am trying to build a custom theme for my wordpress site, I am putting it together from a bootstrap theme I found. This is my first foray into developing with php, and I've just finished learning to list posts. Since I have two posts, I haven't bothered to figure out how to break the loop into multiple pages (ie. show 10 posts per page and navigation at the bottom).</p> <p>What I am trying to learn is how to make the permalinks work in the theme I am building. I get that wordpress works by making queries and displaying those queries. I don't understand how to obtain arguments for the query, or if that is how I get the permalinks and pages to work.</p> <p>I haven't figured out the right google search parameters to resolve my confusion. So what should I be researching, or perhaps a tutorial?</p> <p>ps. sorry if I get the tags wrong, or if this isn't stackexchangey enough, I know it wouldn't be for the original.</p> <p>edit:</p> <p>You see I don't know how to fill in the else for my <code>wp-content/themes/name/index.php</code> file. This is the structure I have setup thus far.</p> <pre><code>&lt;?php $last_date = ''; if( is_home() ) : while( have_posts() ) : the_post(); ?&gt; &lt;?php $the_date = the_date( 'Y', '', '', false ); if ( false ) : //$the_date != $last_date ) : ?&gt; &lt;!-- Year HTML --&gt; &lt;?php endif; $last_date = $the_date; ?&gt; &lt;!-- Blog Entries (titles, author, tags, date, excerpt --&gt; &lt;?php endwhile; else : ?&gt; &lt;!-- No Frigging Clue! --&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 217739, "author": "BillK", "author_id": 87352, "author_profile": "https://wordpress.stackexchange.com/users/87352", "pm_score": 0, "selected": false, "text": "<p>Hook your function to <code>save_post</code>. Use <code>add_post_meta</code> to add the field for a new post or update if this is an edit. See the <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">Codex</a> for adding vs. updating custom fields.</p>\n" }, { "answer_id": 217740, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 3, "selected": true, "text": "<p>You can use the action hook <code>save_post_{post_type}</code>, so for the post type 'post' (blog posts) it is: <code>save_post_post</code>. For more info see the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">codex</a>.</p>\n\n<pre><code>add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3);\n\nfunction sw150216_save_reading_time( $post_id, $post, $update ) {\n $reading_time = estimated_reading_time( $post );\n if ( $update ) {\n update_post_meta ( $post_id, 'reading_time', $reading_time );\n } else {\n add_post_meta( $post_id, 'reading_time', $reading_time, true );\n }\n}\n</code></pre>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88686/" ]
I am trying to build a custom theme for my wordpress site, I am putting it together from a bootstrap theme I found. This is my first foray into developing with php, and I've just finished learning to list posts. Since I have two posts, I haven't bothered to figure out how to break the loop into multiple pages (ie. show 10 posts per page and navigation at the bottom). What I am trying to learn is how to make the permalinks work in the theme I am building. I get that wordpress works by making queries and displaying those queries. I don't understand how to obtain arguments for the query, or if that is how I get the permalinks and pages to work. I haven't figured out the right google search parameters to resolve my confusion. So what should I be researching, or perhaps a tutorial? ps. sorry if I get the tags wrong, or if this isn't stackexchangey enough, I know it wouldn't be for the original. edit: You see I don't know how to fill in the else for my `wp-content/themes/name/index.php` file. This is the structure I have setup thus far. ``` <?php $last_date = ''; if( is_home() ) : while( have_posts() ) : the_post(); ?> <?php $the_date = the_date( 'Y', '', '', false ); if ( false ) : //$the_date != $last_date ) : ?> <!-- Year HTML --> <?php endif; $last_date = $the_date; ?> <!-- Blog Entries (titles, author, tags, date, excerpt --> <?php endwhile; else : ?> <!-- No Frigging Clue! --> <?php endif; ?> ```
You can use the action hook `save_post_{post_type}`, so for the post type 'post' (blog posts) it is: `save_post_post`. For more info see the [codex](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). ``` add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3); function sw150216_save_reading_time( $post_id, $post, $update ) { $reading_time = estimated_reading_time( $post ); if ( $update ) { update_post_meta ( $post_id, 'reading_time', $reading_time ); } else { add_post_meta( $post_id, 'reading_time', $reading_time, true ); } } ```
217,778
<p>I am writing a plugin (<a href="https://github.com/uncovery/unc_gallery" rel="nofollow noreferrer">Github Link</a>) and have trouble setting up the titles of the admin menu.</p> <p>I defined a top header menu with add_menu_page (<a href="https://github.com/uncovery/unc_gallery/blob/master/unc_backend.inc.php#L17" rel="nofollow noreferrer">link to code, same as below</a>) and 2 children with add_submenu_page, but I get 4 lines in the Admin menu, the main one, then that one again (with the same link target) in small and then the 2 children.</p> <pre><code>add_action('admin_menu', 'unc_gallery_admin_menu'); function unc_gallery_admin_menu() { // the main page where we manage the options add_menu_page( 'Uncovery Gallery Options', // $page_title, 'Uncovery Gallery', // $menu_title, 'manage_options', // $capability, 'unc_gallery_admin_menu', // $menu_slug, 'unc_gallery_options' // $function, $icon_url, $position ); // where we upload images $upload_page_hook_suffix = add_submenu_page( 'unc_gallery_admin_menu', // $parent_slug 'Upload Images', // $page_title 'Upload Images', // $menu_title 'manage_options', // capability, manage_options is the default 'unc_gallery_admin_upload', // menu_slug 'unc_uploads_form' // function ); add_action('admin_print_scripts-' . $upload_page_hook_suffix, 'unc_gallery_admin_add_css_and_js'); // where we list up all the images $view_page_hook_suffix = add_submenu_page( 'unc_gallery_admin_menu', // $parent_slug 'View Images', // $page_title 'View Images', // $menu_title 'manage_options', // capability, manage_options is the default 'unc_gallery_admin_view', // menu_slug 'unc_gallery_admin_display_images' // function ); add_action('admin_print_scripts-' . $view_page_hook_suffix, 'unc_gallery_admin_add_css_and_js'); } </code></pre> <p><a href="https://i.stack.imgur.com/Lhn3i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lhn3i.png" alt="enter image description here" /></a></p> <p>How can I either change the title of the 2nd &quot;Uncovery Gallery&quot; or preferably remove it?</p> <p>thanks!</p>
[ { "answer_id": 217739, "author": "BillK", "author_id": 87352, "author_profile": "https://wordpress.stackexchange.com/users/87352", "pm_score": 0, "selected": false, "text": "<p>Hook your function to <code>save_post</code>. Use <code>add_post_meta</code> to add the field for a new post or update if this is an edit. See the <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">Codex</a> for adding vs. updating custom fields.</p>\n" }, { "answer_id": 217740, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 3, "selected": true, "text": "<p>You can use the action hook <code>save_post_{post_type}</code>, so for the post type 'post' (blog posts) it is: <code>save_post_post</code>. For more info see the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">codex</a>.</p>\n\n<pre><code>add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3);\n\nfunction sw150216_save_reading_time( $post_id, $post, $update ) {\n $reading_time = estimated_reading_time( $post );\n if ( $update ) {\n update_post_meta ( $post_id, 'reading_time', $reading_time );\n } else {\n add_post_meta( $post_id, 'reading_time', $reading_time, true );\n }\n}\n</code></pre>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217778", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32482/" ]
I am writing a plugin ([Github Link](https://github.com/uncovery/unc_gallery)) and have trouble setting up the titles of the admin menu. I defined a top header menu with add\_menu\_page ([link to code, same as below](https://github.com/uncovery/unc_gallery/blob/master/unc_backend.inc.php#L17)) and 2 children with add\_submenu\_page, but I get 4 lines in the Admin menu, the main one, then that one again (with the same link target) in small and then the 2 children. ``` add_action('admin_menu', 'unc_gallery_admin_menu'); function unc_gallery_admin_menu() { // the main page where we manage the options add_menu_page( 'Uncovery Gallery Options', // $page_title, 'Uncovery Gallery', // $menu_title, 'manage_options', // $capability, 'unc_gallery_admin_menu', // $menu_slug, 'unc_gallery_options' // $function, $icon_url, $position ); // where we upload images $upload_page_hook_suffix = add_submenu_page( 'unc_gallery_admin_menu', // $parent_slug 'Upload Images', // $page_title 'Upload Images', // $menu_title 'manage_options', // capability, manage_options is the default 'unc_gallery_admin_upload', // menu_slug 'unc_uploads_form' // function ); add_action('admin_print_scripts-' . $upload_page_hook_suffix, 'unc_gallery_admin_add_css_and_js'); // where we list up all the images $view_page_hook_suffix = add_submenu_page( 'unc_gallery_admin_menu', // $parent_slug 'View Images', // $page_title 'View Images', // $menu_title 'manage_options', // capability, manage_options is the default 'unc_gallery_admin_view', // menu_slug 'unc_gallery_admin_display_images' // function ); add_action('admin_print_scripts-' . $view_page_hook_suffix, 'unc_gallery_admin_add_css_and_js'); } ``` [![enter image description here](https://i.stack.imgur.com/Lhn3i.png)](https://i.stack.imgur.com/Lhn3i.png) How can I either change the title of the 2nd "Uncovery Gallery" or preferably remove it? thanks!
You can use the action hook `save_post_{post_type}`, so for the post type 'post' (blog posts) it is: `save_post_post`. For more info see the [codex](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post). ``` add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3); function sw150216_save_reading_time( $post_id, $post, $update ) { $reading_time = estimated_reading_time( $post ); if ( $update ) { update_post_meta ( $post_id, 'reading_time', $reading_time ); } else { add_post_meta( $post_id, 'reading_time', $reading_time, true ); } } ```
217,792
<p>In wordpress we use _e when we have to print things. Example - </p> <pre><code>&lt;div class="col-md-12 col-sm-12 col-xs-12 tuts"&gt; &lt;p&gt;&lt;?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way.', 'tuts'); ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>where tuts is a text domain. The above setting is trying to print something on WordPress 404 page. But what if I wish to insert a link that can navigate to the Homepage.</p> <p>I think this will work - ">Home</p> <p>I tried it like this - </p> <pre><code>&lt;?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to &lt;a href="&lt;?php bloginfo('url');?&gt;"&gt;Home Page&lt;/a&gt;.', 'tuts'); ?&gt; </code></pre>
[ { "answer_id": 217793, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": -1, "selected": false, "text": "<p>There are my code.you can use.</p>\n\n<pre><code>&lt;?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to &lt;a href=\"'.get_bloginfo('url').'\"&gt;Home Page&lt;/a&gt;.', 'tuts'); ?&gt;\n</code></pre>\n" }, { "answer_id": 217796, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": true, "text": "<p>You can write like below:</p>\n\n<pre><code>&lt;?php /* translators: %s: home page URL */\nprintf( __( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to &lt;a href=\"%s\"&gt;Home Page&lt;/a&gt;.', 'tuts'), get_bloginfo('url') ); ?&gt;\n</code></pre>\n\n<p>Note as we're using <code>printf()</code>, that's why we're not using <a href=\"https://codex.wordpress.org/Function_Reference/_e\" rel=\"nofollow\"><code>_e()</code></a>, but we're using <a href=\"http://codex.wordpress.org/Function_Reference/_2\" rel=\"nofollow\"><code>__()</code></a>.</p>\n\n<p><strong>Reference:</strong> <a href=\"http://php.net/manual/en/function.printf.php\" rel=\"nofollow\"><code>printf()</code></a> - PHP</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
In wordpress we use \_e when we have to print things. Example - ``` <div class="col-md-12 col-sm-12 col-xs-12 tuts"> <p><?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way.', 'tuts'); ?></p> </div> ``` where tuts is a text domain. The above setting is trying to print something on WordPress 404 page. But what if I wish to insert a link that can navigate to the Homepage. I think this will work - ">Home I tried it like this - ``` <?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to <a href="<?php bloginfo('url');?>">Home Page</a>.', 'tuts'); ?> ```
You can write like below: ``` <?php /* translators: %s: home page URL */ printf( __( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to <a href="%s">Home Page</a>.', 'tuts'), get_bloginfo('url') ); ?> ``` Note as we're using `printf()`, that's why we're not using [`_e()`](https://codex.wordpress.org/Function_Reference/_e), but we're using [`__()`](http://codex.wordpress.org/Function_Reference/_2). **Reference:** [`printf()`](http://php.net/manual/en/function.printf.php) - PHP
217,795
<p>I'm working on a checklist within wordpress – I have a huge list of posts and I want to tag them with checks that have been done for the post.</p> <p>However, I want to display all the tags not applied on this post.</p> <p>For example:</p> <hr> <p><strong>Sarah's Document</strong></p> <p>Processes not checked yet: <code>ISU-123</code>, <code>ISU-124</code>, <code>ISU-125</code></p> <hr> <p><strong>Andrew's Document</strong></p> <p>Processes not checked yet: <code>ISU-125</code></p> <hr> <p>I want to apply a reverse tagging method almost – I tag posts that have the processes applied to them and show a visual for process not yet tagged on each post.</p> <p>Is there a way of using <code>get_the_tags</code> for showing tags not applied? Or perhaps doing a query for all tags and excluding an array?</p>
[ { "answer_id": 217793, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": -1, "selected": false, "text": "<p>There are my code.you can use.</p>\n\n<pre><code>&lt;?php _e( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to &lt;a href=\"'.get_bloginfo('url').'\"&gt;Home Page&lt;/a&gt;.', 'tuts'); ?&gt;\n</code></pre>\n" }, { "answer_id": 217796, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": true, "text": "<p>You can write like below:</p>\n\n<pre><code>&lt;?php /* translators: %s: home page URL */\nprintf( __( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to &lt;a href=\"%s\"&gt;Home Page&lt;/a&gt;.', 'tuts'), get_bloginfo('url') ); ?&gt;\n</code></pre>\n\n<p>Note as we're using <code>printf()</code>, that's why we're not using <a href=\"https://codex.wordpress.org/Function_Reference/_e\" rel=\"nofollow\"><code>_e()</code></a>, but we're using <a href=\"http://codex.wordpress.org/Function_Reference/_2\" rel=\"nofollow\"><code>__()</code></a>.</p>\n\n<p><strong>Reference:</strong> <a href=\"http://php.net/manual/en/function.printf.php\" rel=\"nofollow\"><code>printf()</code></a> - PHP</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27504/" ]
I'm working on a checklist within wordpress – I have a huge list of posts and I want to tag them with checks that have been done for the post. However, I want to display all the tags not applied on this post. For example: --- **Sarah's Document** Processes not checked yet: `ISU-123`, `ISU-124`, `ISU-125` --- **Andrew's Document** Processes not checked yet: `ISU-125` --- I want to apply a reverse tagging method almost – I tag posts that have the processes applied to them and show a visual for process not yet tagged on each post. Is there a way of using `get_the_tags` for showing tags not applied? Or perhaps doing a query for all tags and excluding an array?
You can write like below: ``` <?php /* translators: %s: home page URL */ printf( __( 'We are sorry, but there is nothing here! You might even call this a 404 Page Not Found error message, which is exactly what it is. The page you are looking for either does not exist, or the URL you followed or typed to get to it is incorrect in some way. Go back to <a href="%s">Home Page</a>.', 'tuts'), get_bloginfo('url') ); ?> ``` Note as we're using `printf()`, that's why we're not using [`_e()`](https://codex.wordpress.org/Function_Reference/_e), but we're using [`__()`](http://codex.wordpress.org/Function_Reference/_2). **Reference:** [`printf()`](http://php.net/manual/en/function.printf.php) - PHP
217,809
<p>I cannot for the life of me find the code for this particular item:</p> <p><a href="https://i.stack.imgur.com/jQagI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jQagI.png" alt="enter image description here"></a></p> <p>Usually in other themes there's the link "Edit" on the front page and post page to directly go to edit the post in admin panel. However, in this theme it is missing and I'm looking to add it.</p> <p>But I'm completely lost here. The theme I'm using is <a href="https://wordpress.org/themes/geiseric/" rel="nofollow noreferrer">https://wordpress.org/themes/geiseric/</a> but it inherits a lot of stuff from <a href="https://wordpress.org/themes/kuorinka/" rel="nofollow noreferrer">https://wordpress.org/themes/kuorinka/</a> .</p> <p>Could somebody please help me?</p> <p>Late edit: So, I figured out by adding echo "test.test.test" in at various places in index.php and single.php. In index.php and single.php it's this part that I need to change it's somewhere inside there</p> <p><code>get_template_part( 'content', ( post_type_supports( get_post_type(), 'post-formats' ) ? get_post_format() : get_post_type() ) );</code></p> <p>I have no idea how to go from there. I don't get the Theme code structure at all.. </p>
[ { "answer_id": 217810, "author": "Tribalpixel", "author_id": 11987, "author_profile": "https://wordpress.stackexchange.com/users/11987", "pm_score": 2, "selected": false, "text": "<p>I dont know thoses theme, but in wordpress normaly you use: </p>\n\n<pre><code>edit_post_link()\nedit_comment_link()\nedit_tag_link()\nedit_bookmark_link()\n</code></pre>\n\n<p>in your templates, inside your loops</p>\n\n<p>maybe some themes use custom functions for that, if so you normaly will find them in functions.php of the theme</p>\n\n<p>check the codex:\n<a href=\"https://codex.wordpress.org/Function_Reference/edit_post_link\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/edit_post_link</a></p>\n" }, { "answer_id": 217823, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 3, "selected": true, "text": "<p>This should be located in the <code>entry-meta.php</code> file of the parent theme (kuorinka). Here is the code:</p>\n\n<pre><code>&lt;?php if ( 'post' == get_post_type() ) : ?&gt;\n &lt;div class=\"entry-meta\"&gt;\n &lt;!-- Date &amp; Author name--&gt;\n &lt;?php kuorinka_posted_on(); ?&gt;\n &lt;!-- Comments count --&gt;\n &lt;?php if ( ! post_password_required() &amp;&amp; ( comments_open() || '0' != get_comments_number() ) ) : ?&gt;\n &lt;span class=\"comments-link\"&gt;&lt;?php comments_popup_link( false, false, false, 'comments-link', false ); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;&lt;!-- .entry-meta --&gt;\n&lt;?php endif;\n</code></pre>\n\n<p>The function <code>kuorinka_posted_on()</code> is defined again in the parent theme in <code>kuorinka\\inc\\template-tags.php</code> on lines 36-58. </p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/288/" ]
I cannot for the life of me find the code for this particular item: [![enter image description here](https://i.stack.imgur.com/jQagI.png)](https://i.stack.imgur.com/jQagI.png) Usually in other themes there's the link "Edit" on the front page and post page to directly go to edit the post in admin panel. However, in this theme it is missing and I'm looking to add it. But I'm completely lost here. The theme I'm using is <https://wordpress.org/themes/geiseric/> but it inherits a lot of stuff from <https://wordpress.org/themes/kuorinka/> . Could somebody please help me? Late edit: So, I figured out by adding echo "test.test.test" in at various places in index.php and single.php. In index.php and single.php it's this part that I need to change it's somewhere inside there `get_template_part( 'content', ( post_type_supports( get_post_type(), 'post-formats' ) ? get_post_format() : get_post_type() ) );` I have no idea how to go from there. I don't get the Theme code structure at all..
This should be located in the `entry-meta.php` file of the parent theme (kuorinka). Here is the code: ``` <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <!-- Date & Author name--> <?php kuorinka_posted_on(); ?> <!-- Comments count --> <?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php comments_popup_link( false, false, false, 'comments-link', false ); ?></span> <?php endif; ?> </div><!-- .entry-meta --> <?php endif; ``` The function `kuorinka_posted_on()` is defined again in the parent theme in `kuorinka\inc\template-tags.php` on lines 36-58.
217,812
<p>I have my calendar events, I want to sort them by creation date with the query, but here's the issue:</p> <p>I have a meta key which has child values: First one is <code>$data = get_post_meta(get_the_ID(),'_event_data',true);</code> and then I get <code>$date = $data['begin'];</code></p> <p>I need to make the query sort based on the <code>$date = $data['begin']</code> but how do I do it before the loop? I can't change the code, how am I able to get it? Everything and anyhow how I try to fix it, it orders the events by the automatically given id.</p>
[ { "answer_id": 217810, "author": "Tribalpixel", "author_id": 11987, "author_profile": "https://wordpress.stackexchange.com/users/11987", "pm_score": 2, "selected": false, "text": "<p>I dont know thoses theme, but in wordpress normaly you use: </p>\n\n<pre><code>edit_post_link()\nedit_comment_link()\nedit_tag_link()\nedit_bookmark_link()\n</code></pre>\n\n<p>in your templates, inside your loops</p>\n\n<p>maybe some themes use custom functions for that, if so you normaly will find them in functions.php of the theme</p>\n\n<p>check the codex:\n<a href=\"https://codex.wordpress.org/Function_Reference/edit_post_link\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/edit_post_link</a></p>\n" }, { "answer_id": 217823, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 3, "selected": true, "text": "<p>This should be located in the <code>entry-meta.php</code> file of the parent theme (kuorinka). Here is the code:</p>\n\n<pre><code>&lt;?php if ( 'post' == get_post_type() ) : ?&gt;\n &lt;div class=\"entry-meta\"&gt;\n &lt;!-- Date &amp; Author name--&gt;\n &lt;?php kuorinka_posted_on(); ?&gt;\n &lt;!-- Comments count --&gt;\n &lt;?php if ( ! post_password_required() &amp;&amp; ( comments_open() || '0' != get_comments_number() ) ) : ?&gt;\n &lt;span class=\"comments-link\"&gt;&lt;?php comments_popup_link( false, false, false, 'comments-link', false ); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;&lt;!-- .entry-meta --&gt;\n&lt;?php endif;\n</code></pre>\n\n<p>The function <code>kuorinka_posted_on()</code> is defined again in the parent theme in <code>kuorinka\\inc\\template-tags.php</code> on lines 36-58. </p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88796/" ]
I have my calendar events, I want to sort them by creation date with the query, but here's the issue: I have a meta key which has child values: First one is `$data = get_post_meta(get_the_ID(),'_event_data',true);` and then I get `$date = $data['begin'];` I need to make the query sort based on the `$date = $data['begin']` but how do I do it before the loop? I can't change the code, how am I able to get it? Everything and anyhow how I try to fix it, it orders the events by the automatically given id.
This should be located in the `entry-meta.php` file of the parent theme (kuorinka). Here is the code: ``` <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <!-- Date & Author name--> <?php kuorinka_posted_on(); ?> <!-- Comments count --> <?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php comments_popup_link( false, false, false, 'comments-link', false ); ?></span> <?php endif; ?> </div><!-- .entry-meta --> <?php endif; ``` The function `kuorinka_posted_on()` is defined again in the parent theme in `kuorinka\inc\template-tags.php` on lines 36-58.
217,820
<p>After a lengthy break from WP i'm getting my hands dirty with quite a complex plugin which is coming along nicely, but right now i am at the point of needing some advice on quite a complex issue:</p> <p><strong>Project Outline</strong> Plugin is multi-functional with the core element being that it is a members based system focused on online rpg gaming, member signs up (members country is set on registration from a select option dropdown field), creates his/her profile <strong>and sets timezone</strong> within their profile, once profile is completed then the member has the option to join an existing group based on Country, Gaming Platform etc, or they can go ahead and create their own group and become group manager.</p> <p>Being part of a group a member can then post a "mission, quest" etc, upon posting all group members are emailed with the details and a link to the post where they can join if interested.</p> <p><strong>The problem</strong> This is where i need some advice, the time of the "mission/quest" needs to be relevant to the group that its posted from, but timezones being timezones are not exactly country specific (ie one country can have many timezones), an example being the US both the user post and the email would need to show the time as in the coming example as 3.00pm EST or 3.00pm PST so that interested parties have a clear and concise information to the time the "mission/quest" commences.</p> <p><strong>The Question</strong> Is it possible to hook into the Wordpress timezones function (the one you see on wp install) or would you suggest going the laborious route and building my own?, if the WP option is recommended then where can i find info (im thinking codex but im finding nothing in there regarding the WP function) to put me on the right track, timezones are not my strong point and i've known from the outset that this part of the plugin would be my stumbling block, however its of the highest importance that it is integrated so that it is easier on the enduser and removes confusion.</p>
[ { "answer_id": 217810, "author": "Tribalpixel", "author_id": 11987, "author_profile": "https://wordpress.stackexchange.com/users/11987", "pm_score": 2, "selected": false, "text": "<p>I dont know thoses theme, but in wordpress normaly you use: </p>\n\n<pre><code>edit_post_link()\nedit_comment_link()\nedit_tag_link()\nedit_bookmark_link()\n</code></pre>\n\n<p>in your templates, inside your loops</p>\n\n<p>maybe some themes use custom functions for that, if so you normaly will find them in functions.php of the theme</p>\n\n<p>check the codex:\n<a href=\"https://codex.wordpress.org/Function_Reference/edit_post_link\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/edit_post_link</a></p>\n" }, { "answer_id": 217823, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 3, "selected": true, "text": "<p>This should be located in the <code>entry-meta.php</code> file of the parent theme (kuorinka). Here is the code:</p>\n\n<pre><code>&lt;?php if ( 'post' == get_post_type() ) : ?&gt;\n &lt;div class=\"entry-meta\"&gt;\n &lt;!-- Date &amp; Author name--&gt;\n &lt;?php kuorinka_posted_on(); ?&gt;\n &lt;!-- Comments count --&gt;\n &lt;?php if ( ! post_password_required() &amp;&amp; ( comments_open() || '0' != get_comments_number() ) ) : ?&gt;\n &lt;span class=\"comments-link\"&gt;&lt;?php comments_popup_link( false, false, false, 'comments-link', false ); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;&lt;!-- .entry-meta --&gt;\n&lt;?php endif;\n</code></pre>\n\n<p>The function <code>kuorinka_posted_on()</code> is defined again in the parent theme in <code>kuorinka\\inc\\template-tags.php</code> on lines 36-58. </p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3710/" ]
After a lengthy break from WP i'm getting my hands dirty with quite a complex plugin which is coming along nicely, but right now i am at the point of needing some advice on quite a complex issue: **Project Outline** Plugin is multi-functional with the core element being that it is a members based system focused on online rpg gaming, member signs up (members country is set on registration from a select option dropdown field), creates his/her profile **and sets timezone** within their profile, once profile is completed then the member has the option to join an existing group based on Country, Gaming Platform etc, or they can go ahead and create their own group and become group manager. Being part of a group a member can then post a "mission, quest" etc, upon posting all group members are emailed with the details and a link to the post where they can join if interested. **The problem** This is where i need some advice, the time of the "mission/quest" needs to be relevant to the group that its posted from, but timezones being timezones are not exactly country specific (ie one country can have many timezones), an example being the US both the user post and the email would need to show the time as in the coming example as 3.00pm EST or 3.00pm PST so that interested parties have a clear and concise information to the time the "mission/quest" commences. **The Question** Is it possible to hook into the Wordpress timezones function (the one you see on wp install) or would you suggest going the laborious route and building my own?, if the WP option is recommended then where can i find info (im thinking codex but im finding nothing in there regarding the WP function) to put me on the right track, timezones are not my strong point and i've known from the outset that this part of the plugin would be my stumbling block, however its of the highest importance that it is integrated so that it is easier on the enduser and removes confusion.
This should be located in the `entry-meta.php` file of the parent theme (kuorinka). Here is the code: ``` <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <!-- Date & Author name--> <?php kuorinka_posted_on(); ?> <!-- Comments count --> <?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php comments_popup_link( false, false, false, 'comments-link', false ); ?></span> <?php endif; ?> </div><!-- .entry-meta --> <?php endif; ``` The function `kuorinka_posted_on()` is defined again in the parent theme in `kuorinka\inc\template-tags.php` on lines 36-58.
217,828
<p>Which is the best approach to hide WordPress, preferably everything from folders and files, to admin login ? I'm pretty new to that stuff, so I'll prefer a plugin ratter a custom code, unless it's easy enough to set-it up. </p>
[ { "answer_id": 217833, "author": "rob_st", "author_id": 29055, "author_profile": "https://wordpress.stackexchange.com/users/29055", "pm_score": 1, "selected": false, "text": "<p>Well, it depends what you mean by \"hide\" and what you're going to approach.</p>\n\n<p>Hiding folders and files doesn't really make sense when you want to have your site acessible through the web.</p>\n\n<p>You could <em>rename</em> your wp-login-URL, as <a href=\"https://wordpress.stackexchange.com/questions/6402/is-there-any-way-to-rename-or-hide-wp-login-php\">described in this answer</a>, which basically contains al otta reading stuff.</p>\n\n<p>To prevent acessing your wp-admin folder, you could tweak your <code>.htacces</code>-file in the wordpress root folder.</p>\n\n<pre><code>## Disallow admin pages from external IPs\nRewriteCond %{REQUEST_URI} ^(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^(.*)?wp-admin$\nRewriteCond %{REMOTE_ADDR} !^(xxx\\.xxx\\.xxx\\.xxx)$\nRewriteRule ^(.*)$ - [F]\n</code></pre>\n\n<p>Where xxx is your <strong>static</strong> IP-adress. But that won't make much sense if your ISP only gives your a dynamic IP.</p>\n" }, { "answer_id": 219258, "author": "WP-Silver", "author_id": 5344, "author_profile": "https://wordpress.stackexchange.com/users/5344", "pm_score": 3, "selected": true, "text": "<p>If you are new to php and mod_rewrite i suggest so you check with the section of my response. Or if you keen to try it yourself, you can use something like this to hide the wp-content/plugins path structure:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteRule ^modules/(.*) /wp-content/plugins/$1 [L,QSA]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>This will change the path to /modules . Apply something similar to other structure, you may need some advanced rewrites, see <a href=\"http://httpd.apache.org/docs/current/mod/mod_rewrite.html\" rel=\"nofollow\">http://httpd.apache.org/docs/current/mod/mod_rewrite.html</a> </p>\n\n<p>If prefer something out of the box, there re few interesting plugins, some commercial, also free at WordPress repository, i suggest to try <a href=\"https://wordpress.org/plugins/wp-hide-security-enhancer/\" rel=\"nofollow\">WP Hide &amp; Security Enhancer</a>. This include lot's of things and help to change pretty much everything to make your WordPress unrecognizable. Here are some features of the code:</p>\n\n<ul>\n<li>Custom admin Url</li>\n<li>Block default admin Url</li>\n<li>Block any direct folder access to completely hide the structure</li>\n<li>Custom wp-login.php filename</li>\n<li>Block default wp-login.php</li>\n<li>Block default wp-signup.php</li>\n<li>Adjustable theme url</li>\n<li>New child theme url</li>\n<li>Change theme style file name</li>\n<li>Custom wp-include</li>\n<li>Block default wp-include paths</li>\n<li>Block defalt wp-content</li>\n<li>Custom plugins urls</li>\n<li>Block default plugins paths</li>\n<li>New upload url</li>\n<li>Block default upload urls</li>\n<li>Remove wordpress version</li>\n<li>Meta Generator block</li>\n<li>Disble the emoji and required javascript code</li>\n<li>Remove wlwmanifest Meta</li>\n<li>Remove rsd_link Meta</li>\n<li>Remove wpemoji</li>\n</ul>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217828", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88807/" ]
Which is the best approach to hide WordPress, preferably everything from folders and files, to admin login ? I'm pretty new to that stuff, so I'll prefer a plugin ratter a custom code, unless it's easy enough to set-it up.
If you are new to php and mod\_rewrite i suggest so you check with the section of my response. Or if you keen to try it yourself, you can use something like this to hide the wp-content/plugins path structure: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^modules/(.*) /wp-content/plugins/$1 [L,QSA] </IfModule> ``` This will change the path to /modules . Apply something similar to other structure, you may need some advanced rewrites, see <http://httpd.apache.org/docs/current/mod/mod_rewrite.html> If prefer something out of the box, there re few interesting plugins, some commercial, also free at WordPress repository, i suggest to try [WP Hide & Security Enhancer](https://wordpress.org/plugins/wp-hide-security-enhancer/). This include lot's of things and help to change pretty much everything to make your WordPress unrecognizable. Here are some features of the code: * Custom admin Url * Block default admin Url * Block any direct folder access to completely hide the structure * Custom wp-login.php filename * Block default wp-login.php * Block default wp-signup.php * Adjustable theme url * New child theme url * Change theme style file name * Custom wp-include * Block default wp-include paths * Block defalt wp-content * Custom plugins urls * Block default plugins paths * New upload url * Block default upload urls * Remove wordpress version * Meta Generator block * Disble the emoji and required javascript code * Remove wlwmanifest Meta * Remove rsd\_link Meta * Remove wpemoji
217,847
<p>I'd like to exclude categories from <a href="https://codex.wordpress.org/Template_Tags/wp_list_categories" rel="nofollow"><code>wp_list_categories()</code></a> but I want to use the category slug because I do development on a local install where the category ID will be different in production. I got this to work with the following code:</p> <pre><code>$exclcat = array( 'fp-feature', 'fp-aside-feature' ); $output_categories = array(); $categories = get_categories( $args ); foreach( $categories as $category ) { if( in_array( $category-&gt;slug, $exclcat ) ) { $output_categories[ $category-&gt;cat_ID ] = $category-&gt;cat_ID; } } $args = array( 'orderby' =&gt; 'ID', 'show_count' =&gt; 0, //Use 1 to show the count 'taxonomy' =&gt; 'category', 'use_desc_for_title' =&gt; 1, 'echo' =&gt; 1, //Use 0 to not output results 'title_li' =&gt; '', //creates an &lt;li&gt; entry with text entered here - can be blank 'exclude' =&gt; $output_categories, ); wp_list_categories( $args ); </code></pre> <p>Is this the proper way to do it or is there a more efficient way?</p>
[ { "answer_id": 217853, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>Instead of getting <em>all</em> categories you could just loop through your excluded slug array and use <a href=\"https://developer.wordpress.org/reference/functions/get_term_by/\" rel=\"nofollow\"><code>get_term_by()</code></a>:</p>\n\n<pre><code>$exclude_slugs = array( 'fp-feature', 'fp-aside-feature' ); \n$exclude_ids = array();\n\nforeach( $exclude_slugs as $slug ) { \n $tmp_term = get_term_by( 'slug', $slug, 'category' );\n\n if( is_object( $tmp_term ) ) {\n $exclude_ids[] = $tmp_term-&gt;term_id;\n }\n}\n\n$args = array(\n 'orderby' =&gt; 'ID',\n 'show_count' =&gt; 0, //Use 1 to show the count\n 'taxonomy' =&gt; 'category',\n 'use_desc_for_title' =&gt; 1,\n 'echo' =&gt; 1, //Use 0 to not output results\n 'title_li' =&gt; '', //creates an &lt;li&gt; entry with text entered here - can be blank\n 'exclude' =&gt; $exclude_ids,\n);\n\nwp_list_categories( $args );\n</code></pre>\n\n<p>This will make sure we only get terms that we want to exclude.</p>\n" }, { "answer_id": 217858, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>I would suggest a cleaner approach would be to implement an <code>exclude_slugs</code> argument for the function, then you can just use the following in your template code:</p>\n\n<pre><code>wp_list_categories([\n 'exclude_slugs' =&gt; [ 'fp-feature', 'fp-aside-feature' ],\n\n // Other arguments\n]);\n</code></pre>\n\n<p>Here's the filter, pop it in your <code>functions.php</code>:</p>\n\n<pre><code>function wpse_217847_list_terms_exclusions( $query, $args ) {\n if ( ! empty( $args['exclude_slugs'] ) ) {\n if ( ! is_array( $slugs = $args['exclude_slugs'] ) )\n $slugs = array_map( 'trim', explode( ',', $slugs ) );\n\n $slugs = array_map( 'esc_sql', $slugs );\n $slugs = implode( '\",\"', $slugs );\n $query .= sprintf( ' AND t.slug NOT IN (\"%s\")', $slugs );\n }\n\n return $query;\n}\n\nadd_filter( 'list_terms_exclusions', 'wpse_217847_list_terms_exclusions', 10, 2 );\n</code></pre>\n\n<p>Bonus points: no additional db queries needed to first get the slug => ID translations. </p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217847", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86078/" ]
I'd like to exclude categories from [`wp_list_categories()`](https://codex.wordpress.org/Template_Tags/wp_list_categories) but I want to use the category slug because I do development on a local install where the category ID will be different in production. I got this to work with the following code: ``` $exclcat = array( 'fp-feature', 'fp-aside-feature' ); $output_categories = array(); $categories = get_categories( $args ); foreach( $categories as $category ) { if( in_array( $category->slug, $exclcat ) ) { $output_categories[ $category->cat_ID ] = $category->cat_ID; } } $args = array( 'orderby' => 'ID', 'show_count' => 0, //Use 1 to show the count 'taxonomy' => 'category', 'use_desc_for_title' => 1, 'echo' => 1, //Use 0 to not output results 'title_li' => '', //creates an <li> entry with text entered here - can be blank 'exclude' => $output_categories, ); wp_list_categories( $args ); ``` Is this the proper way to do it or is there a more efficient way?
I would suggest a cleaner approach would be to implement an `exclude_slugs` argument for the function, then you can just use the following in your template code: ``` wp_list_categories([ 'exclude_slugs' => [ 'fp-feature', 'fp-aside-feature' ], // Other arguments ]); ``` Here's the filter, pop it in your `functions.php`: ``` function wpse_217847_list_terms_exclusions( $query, $args ) { if ( ! empty( $args['exclude_slugs'] ) ) { if ( ! is_array( $slugs = $args['exclude_slugs'] ) ) $slugs = array_map( 'trim', explode( ',', $slugs ) ); $slugs = array_map( 'esc_sql', $slugs ); $slugs = implode( '","', $slugs ); $query .= sprintf( ' AND t.slug NOT IN ("%s")', $slugs ); } return $query; } add_filter( 'list_terms_exclusions', 'wpse_217847_list_terms_exclusions', 10, 2 ); ``` Bonus points: no additional db queries needed to first get the slug => ID translations.
217,875
<p>When I try to use the Flexslider with 'built-in' jquery, the Flexslider won't work. When I use my own <strong>myjquery</strong> file, It works as if nothing ever.<br> Do I always have to use my own jquery file even wordpress has its own?</p> <ul> <li>Wordpress' (built in) jQuery vserion: 1.11.3 </li> <li>Flexbox required jQuery version: 1.7+ </li> <li><strong>myjquery</strong> = jquery version: 1.12.0</li> </ul> <p>Summary: flexbox should work with jQuery of WordPress.</p> <hr> <h3>More Details</h3> <p>Flexslider doesn't work when I use Wordpress' jQuery. It works when I add my own <strong>myjquery.js</strong> which is jquery 1.12.0 and when I dequeue original jquery <code>wp_dequeue_script('jquery');</code>.<br> It looks like WordPress' jQuery is not visible for my Flexslider and custom.js file.</p> <p>Errors:<br> When I run the site with WordPress with its own jQuery there is one error:<br> <code>$ is not a function</code> file: 'custom.js:2:1' what means that jquery is not found but it's included in header (I've checked). My conclusion is the dependency <code>array('jquery')</code> doesn't work. I've tried to use <code>wp_register_script('flexbox', ...)</code> with different function (even without dependencies and false, false or true, true, etc..) </p> <p><em>When I use 'myjquery' there is no errors and plugin works correctly.</em></p> <p>The content of 'custom.js': <code> $(window).load(function() { $('.flexslider').flexslider({ animation: "slide" }); }); </code></p> <hr> <p>Register and include styles &amp; scripts (part of the <strong>functions.php</strong> file):</p> <pre><code>wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.js' ); wp_register_script( 'myjquery', get_template_directory_uri() . '/js/jquery.js' ); wp_register_script( 'flexslider', get_template_directory_uri() . '/js/flexslider.js', array('jquery'), false, true ); wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array('flexslider'), false, true ); // Enqueue :: styles &amp; scripts function mytheme_enqueue_items() { wp_enqueue_style( 'my-main-css' ); wp_enqueue_style( 'bootstrap-css' ); wp_enqueue_style( 'bootstrap-responsive' ); wp_enqueue_style( 'flexslider-css' ); // wp_enqueue_script( '**myjquery**' ); // **flexslider works correctly when uncommented** wp_enqueue_script( 'bootstrap-js' ); wp_enqueue_script( 'flexslider' ); wp_enqueue_script( 'custom-js' ); } add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_items' ); </code></pre>
[ { "answer_id": 217901, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 0, "selected": false, "text": "<p>First off, you should be registering your scripts in the same function that you enqueue them with. </p>\n\n<p>Your comment <code>flexslider works correctly when uncommented</code> suggests that you might just be missing this:</p>\n\n<p><code>wp_enqueue_script( 'jquery' );</code></p>\n\n<p>Though jQuery is \"built-in,\" you still need to enqueue the script with the handle. Basically, WordPress includes the files and does the <code>wp_register_script</code> part, but you still need to enqueue it, which tells WordPress you want to load it.</p>\n\n<p><strong>Edit:</strong> </p>\n\n<p>Sorry, I just noticed that you have jQuery as a dependency in your <code>wp_register_script</code>. So you shouldn't need to enqueue it like I suggested above.</p>\n" }, { "answer_id": 217942, "author": "rflw", "author_id": 70809, "author_profile": "https://wordpress.stackexchange.com/users/70809", "pm_score": 2, "selected": true, "text": "<p>The problem was jquery conflict (error <code>$ is not a function</code>).<br>\nAll custom scripts should be running in no-conflict mode.<br>\nI've used <code>jQuery(...)</code> instead of <code>$()</code>.</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217875", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70809/" ]
When I try to use the Flexslider with 'built-in' jquery, the Flexslider won't work. When I use my own **myjquery** file, It works as if nothing ever. Do I always have to use my own jquery file even wordpress has its own? * Wordpress' (built in) jQuery vserion: 1.11.3 * Flexbox required jQuery version: 1.7+ * **myjquery** = jquery version: 1.12.0 Summary: flexbox should work with jQuery of WordPress. --- ### More Details Flexslider doesn't work when I use Wordpress' jQuery. It works when I add my own **myjquery.js** which is jquery 1.12.0 and when I dequeue original jquery `wp_dequeue_script('jquery');`. It looks like WordPress' jQuery is not visible for my Flexslider and custom.js file. Errors: When I run the site with WordPress with its own jQuery there is one error: `$ is not a function` file: 'custom.js:2:1' what means that jquery is not found but it's included in header (I've checked). My conclusion is the dependency `array('jquery')` doesn't work. I've tried to use `wp_register_script('flexbox', ...)` with different function (even without dependencies and false, false or true, true, etc..) *When I use 'myjquery' there is no errors and plugin works correctly.* The content of 'custom.js': `$(window).load(function() { $('.flexslider').flexslider({ animation: "slide" }); });` --- Register and include styles & scripts (part of the **functions.php** file): ``` wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.js' ); wp_register_script( 'myjquery', get_template_directory_uri() . '/js/jquery.js' ); wp_register_script( 'flexslider', get_template_directory_uri() . '/js/flexslider.js', array('jquery'), false, true ); wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array('flexslider'), false, true ); // Enqueue :: styles & scripts function mytheme_enqueue_items() { wp_enqueue_style( 'my-main-css' ); wp_enqueue_style( 'bootstrap-css' ); wp_enqueue_style( 'bootstrap-responsive' ); wp_enqueue_style( 'flexslider-css' ); // wp_enqueue_script( '**myjquery**' ); // **flexslider works correctly when uncommented** wp_enqueue_script( 'bootstrap-js' ); wp_enqueue_script( 'flexslider' ); wp_enqueue_script( 'custom-js' ); } add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_items' ); ```
The problem was jquery conflict (error `$ is not a function`). All custom scripts should be running in no-conflict mode. I've used `jQuery(...)` instead of `$()`.
217,880
<p>Wordpress should always allow me to change the language, anytime. However, sometimes I get stuck in these kind of situations, where I only get to choose "English (United States)".</p> <p><em>(Settings > General Settings > Site Language)</em></p> <h2>What I expect:</h2> <p><img src="https://i.imgur.com/lJolMVV.png" alt="a"></p> <h2>What I get:</h2> <p><img src="https://i.imgur.com/J8KDDjT.png" alt="a"></p> <p>Why is that? How can I fix this?</p>
[ { "answer_id": 230379, "author": "Roberto Cinetto", "author_id": 59622, "author_profile": "https://wordpress.stackexchange.com/users/59622", "pm_score": 0, "selected": false, "text": "<p>I've solved this issue defining the right way wordpress search for the <code>wp-content</code> folder. </p>\n\n<p>In <code>wp-config.php</code> you can specify the position of the <code>wp-content</code> folder. Based on the system you are working on, try to set the following code:</p>\n\n<pre><code>define('WP_CONTENT_DIR', realpath(dirname(__FILE__) . '/wp-content'));\n</code></pre>\n\n<p>or this one: </p>\n\n<pre><code>define('WP_CONTENT_DIR', realpath($_SERVER['DOCUMENT_ROOT'] . '/wp-content'));\n</code></pre>\n" }, { "answer_id": 254877, "author": "NicolasZ", "author_id": 112340, "author_profile": "https://wordpress.stackexchange.com/users/112340", "pm_score": 1, "selected": false, "text": "<p>I had the exact same problem. \nIn case you have a multi-language plugin installed, you have to deactivate it(or delete it) and then you will be able to change the language to whatever you need. I had this problem specifically with Multisite Language Switcher.</p>\n\n<p>PS. i checked before and i had the language files in my wordpress installation.</p>\n" }, { "answer_id": 268715, "author": "Alexey Muravyov", "author_id": 120846, "author_profile": "https://wordpress.stackexchange.com/users/120846", "pm_score": 4, "selected": false, "text": "<p>I have no experience with WP before. I tried to install WP 4.7 and have same problem. Only English was in dropdown list.\nI thought WP downloads all translate files automaticall but unfortunately it didn't.</p>\n\n<p>To get languages in dropdown list (Settings > General Settings > Site Language)\nyou need install translate files to <code>wp-content/languages</code> directory.</p>\n\n<p>To download language file select version of WP here\n<a href=\"https://translate.wordpress.org/projects/wp\" rel=\"noreferrer\">https://translate.wordpress.org/projects/wp</a>\nthan select language.\nYou will get a page where you can download language file.</p>\n\n<p>For example for wp4.7 Ukraine I have got this page</p>\n\n<pre><code>translate.wordpress.org/projects/wp/4.7.x/uk/default\n</code></pre>\n\n<p>At the end of the page find <code>Export</code> link.\nSelect <strong>'all current</strong>' as '<strong>Machine Object Messages Catalog (.mo)</strong>'\nand click <code>export</code></p>\n\n<p>Then put downloaded file in <strong>wp-content/languages</strong> directory.\nOpen or refresh Settings > General Settings page.\nYou should see new language in dropdown list.</p>\n\n<p>It is <strong>important to download .mo file</strong> exactly. I spent a lot of time trying to install .po file.\nAlso if you linux user and have only .po file you can convert it by command</p>\n\n<pre><code>msgfmt -o uk_UA.mo uk_UA.po\n</code></pre>\n\n<p>To install translate files for plugins and themes you should to do same things with some difference.</p>\n\n<p>More details you can find here\n<a href=\"https://codex.wordpress.org/Installing_WordPress_in_Your_Language\" rel=\"noreferrer\">https://codex.wordpress.org/Installing_WordPress_in_Your_Language</a></p>\n" }, { "answer_id": 270819, "author": "Hans Westman", "author_id": 45196, "author_profile": "https://wordpress.stackexchange.com/users/45196", "pm_score": 5, "selected": false, "text": "<p>Maybe WordPress doesn't have permissions to save the new language files. I had the same problem, and I solved it by adding the following to <code>wp-config.php</code></p>\n\n<pre><code>define('FS_METHOD', 'direct');\n</code></pre>\n\n<p>You might also want to check that your <code>wp-content/</code>-directory is writable for the web server user.</p>\n" }, { "answer_id": 274639, "author": "Ivan Shatsky", "author_id": 124579, "author_profile": "https://wordpress.stackexchange.com/users/124579", "pm_score": 3, "selected": false, "text": "<p>Just ran into the same issue. In my case, the reason was simple. When you install an English-only version of WordPress, there is no <code>languages</code> subdirectory under the <code>wp-content</code> directory. Create it manually, and you will receive all available language list at your WP dashboard.</p>\n<h2>1. Create the target directory</h2>\n<p>By default, the &quot;content&quot; directory is <code>&lt;wordpress folder&gt;/wp-content</code>. However depending on your installation it might not be that one.</p>\n<p>To check, run <code>wp eval &quot;echo WP_CONTENT_DIR;&quot;</code></p>\n<p>Once you have identified that directory, create a <code>languages</code> directory in it.</p>\n<h2>2. Install languages</h2>\n<p>If Wordpress doesn't have permissions to install languages for you into that folder, you can do it yourself by placing the <code>.po</code> and <code>.mo</code> files in it. Restart Wordpress and it will pick them up.</p>\n<h2>3. Install languages for plugins and themes</h2>\n<h3>3.1 First option: Let Wordpress download them</h3>\n<p>At this point, you got WP core translation files, but not the plugins or themes ones. To get all other translation files, go to <strong>Updates</strong> section under <strong>Dashboard</strong>, and click <strong>Check again</strong> button. At the bottom of the page you'll see a message <em>New translations available</em>. Click on the <strong>Update translations</strong> button, and WP will download all available translations for your plugins and themes.</p>\n<h3>3.2 Second option: place them yourself manually</h3>\n<p>As mentioned above, Wordpress must have write permissions on <code>languages</code> directory, in other case you'll have to download all translation files manually. Place <code>.po</code> and <code>.mo</code> translation files for installed themes in <code>languages/themes</code> subdirectory, and translation files for installed plugins in <code>languages/plugins</code> subdirectory.</p>\n" }, { "answer_id": 278704, "author": "Cristiano", "author_id": 126944, "author_profile": "https://wordpress.stackexchange.com/users/126944", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and I spent hours to read different complicated solutions.</p>\n\n<p><strong>Just 3 very basic steps.</strong></p>\n\n<p><strong>1</strong> Create a new folder in your ‘/wp-content’ directory called ‘/languages’<br/>\n<strong>2</strong> Copy in this folder the language pack of the language you want to install<br/>\n (download it from <a href=\"https://make.wordpress.org/polyglots/teams/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/polyglots/teams/</a>)<br/>\n<strong>3</strong> Choose the new language through the interface<br/></p>\n\n<p>Details here: <a href=\"https://www.linuwi.com/tutorials/how-to-change-wordpress-language/\" rel=\"nofollow noreferrer\">https://www.linuwi.com/tutorials/how-to-change-wordpress-language/</a></p>\n" }, { "answer_id": 283176, "author": "Mike", "author_id": 51562, "author_profile": "https://wordpress.stackexchange.com/users/51562", "pm_score": 1, "selected": false, "text": "<p>Like Ivan described above, make sure PHP has the right file permissions so it can create a /languages subdirectory under the /wp-content directory. If it has, it will create the directory automatically and let you select a language unter Settings > General Settings > Site Language.</p>\n" }, { "answer_id": 292958, "author": "eVagabond", "author_id": 126739, "author_profile": "https://wordpress.stackexchange.com/users/126739", "pm_score": 1, "selected": false, "text": "<p>In my case since I was using <strong>WPML</strong> for translation, I had to go to the WPML Setup Page, to change my default language.</p>\n\n<p><a href=\"https://i.stack.imgur.com/O0Nvb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O0Nvb.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 306090, "author": "Archana Sharma", "author_id": 143984, "author_profile": "https://wordpress.stackexchange.com/users/143984", "pm_score": 2, "selected": false, "text": "<p>This problem is occurred in WordPress 4.0 and above versions also , because of permissions. Because of this WordPress cannot download the language packs. To add other languages in admin panel general settings , add this code inside <strong>wp-config.php</strong> just below the <strong>define('WP_DEBUG', true);</strong></p>\n\n<pre><code>define('FS_METHOD', 'direct');\n</code></pre>\n\n<p>After saving changes check on admin panel general settings , now you will find number of languages. And if in case you will not find your language inside a list , try to add a language packs using plugin or add through code. You can follow official documentation for this.</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88841/" ]
Wordpress should always allow me to change the language, anytime. However, sometimes I get stuck in these kind of situations, where I only get to choose "English (United States)". *(Settings > General Settings > Site Language)* What I expect: -------------- ![a](https://i.imgur.com/lJolMVV.png) What I get: ----------- ![a](https://i.imgur.com/J8KDDjT.png) Why is that? How can I fix this?
Maybe WordPress doesn't have permissions to save the new language files. I had the same problem, and I solved it by adding the following to `wp-config.php` ``` define('FS_METHOD', 'direct'); ``` You might also want to check that your `wp-content/`-directory is writable for the web server user.
217,881
<p>I need to remove all theme <em>(both child and parent)</em> css styles from a singular page using functions.php in a child theme. Here's what I'm currently adding to the child's functions.php</p> <pre><code>// import parent and child theme css function theme_enqueue_styles() { wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'); wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array($parent_style));} // remove the parent &amp; style css function PREFIX_remove_scripts() { wp_dequeue_style( 'parent-style' ); wp_dequeue_style( 'child-style' ); wp_dequeue_style( 'parent-style-css' ); wp_deregister_style( 'parent-style' ); wp_deregister_style( 'child-style' ); wp_deregister_style( 'parent-style-css' ); </code></pre> <p>I want to apply this <strong>PREFIX_remove_scripts</strong> function to only one page on the site. How can I best accomplish this? Or is there another suitable way? Many thanks in advance!</p>
[ { "answer_id": 217892, "author": "Cai", "author_id": 81652, "author_profile": "https://wordpress.stackexchange.com/users/81652", "pm_score": 4, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">conditional tags</a> to target the specific page you need to remove the styles on. You can use <code>is_page()</code> to target a <em>page</em> page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target <em>any</em> page.</p>\n\n<pre><code>function wpse_217881_remove_scripts() {\n\n // Check for the page you want to target\n if ( is_page( 'About Me And Joe' ) ) {\n\n // Remove Styles\n wp_dequeue_style( 'parent-style' );\n wp_dequeue_style( 'child-style' );\n wp_dequeue_style( 'parent-style-css' );\n wp_deregister_style( 'parent-style' );\n wp_deregister_style( 'child-style' );\n wp_deregister_style( 'parent-style-css' );\n }\n}\n</code></pre>\n\n<p>I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance <code>wp_enqueue_scripts</code>.</p>\n\n<p><em>From the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code> docs</a>:</em></p>\n\n<blockquote>\n <p>Despite the name, it is used for enqueuing both scripts and styles</p>\n</blockquote>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' );\n\n// Optionaly add a priority if needed i.e:\n// add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 );\n</code></pre>\n" }, { "answer_id": 406864, "author": "nab", "author_id": 198153, "author_profile": "https://wordpress.stackexchange.com/users/198153", "pm_score": 0, "selected": false, "text": "<p>The best solutiuon for me was to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">template</a> with different or no head.</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78266/" ]
I need to remove all theme *(both child and parent)* css styles from a singular page using functions.php in a child theme. Here's what I'm currently adding to the child's functions.php ``` // import parent and child theme css function theme_enqueue_styles() { wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'); wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array($parent_style));} // remove the parent & style css function PREFIX_remove_scripts() { wp_dequeue_style( 'parent-style' ); wp_dequeue_style( 'child-style' ); wp_dequeue_style( 'parent-style-css' ); wp_deregister_style( 'parent-style' ); wp_deregister_style( 'child-style' ); wp_deregister_style( 'parent-style-css' ); ``` I want to apply this **PREFIX\_remove\_scripts** function to only one page on the site. How can I best accomplish this? Or is there another suitable way? Many thanks in advance!
You can use [conditional tags](https://codex.wordpress.org/Conditional_Tags) to target the specific page you need to remove the styles on. You can use `is_page()` to target a *page* page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target *any* page. ``` function wpse_217881_remove_scripts() { // Check for the page you want to target if ( is_page( 'About Me And Joe' ) ) { // Remove Styles wp_dequeue_style( 'parent-style' ); wp_dequeue_style( 'child-style' ); wp_dequeue_style( 'parent-style-css' ); wp_deregister_style( 'parent-style' ); wp_deregister_style( 'child-style' ); wp_deregister_style( 'parent-style-css' ); } } ``` I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance `wp_enqueue_scripts`. *From the [`wp_enqueue_scripts` docs](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts):* > > Despite the name, it is used for enqueuing both scripts and styles > > > ``` add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' ); // Optionaly add a priority if needed i.e: // add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 ); ```
217,882
<p>I'm trying to stylise my navigation menu regarding selected page.</p> <p>I made a page for news, but when I click on the following pages (page 2 for example), the navigation menu loses its class. I want it retains its <code>current-item-menu</code> class on this case.</p> <p>How can I do this ?</p> <p>Thanks for your help !</p>
[ { "answer_id": 217892, "author": "Cai", "author_id": 81652, "author_profile": "https://wordpress.stackexchange.com/users/81652", "pm_score": 4, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">conditional tags</a> to target the specific page you need to remove the styles on. You can use <code>is_page()</code> to target a <em>page</em> page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target <em>any</em> page.</p>\n\n<pre><code>function wpse_217881_remove_scripts() {\n\n // Check for the page you want to target\n if ( is_page( 'About Me And Joe' ) ) {\n\n // Remove Styles\n wp_dequeue_style( 'parent-style' );\n wp_dequeue_style( 'child-style' );\n wp_dequeue_style( 'parent-style-css' );\n wp_deregister_style( 'parent-style' );\n wp_deregister_style( 'child-style' );\n wp_deregister_style( 'parent-style-css' );\n }\n}\n</code></pre>\n\n<p>I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance <code>wp_enqueue_scripts</code>.</p>\n\n<p><em>From the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code> docs</a>:</em></p>\n\n<blockquote>\n <p>Despite the name, it is used for enqueuing both scripts and styles</p>\n</blockquote>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' );\n\n// Optionaly add a priority if needed i.e:\n// add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 );\n</code></pre>\n" }, { "answer_id": 406864, "author": "nab", "author_id": 198153, "author_profile": "https://wordpress.stackexchange.com/users/198153", "pm_score": 0, "selected": false, "text": "<p>The best solutiuon for me was to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">template</a> with different or no head.</p>\n" } ]
2016/02/16
[ "https://wordpress.stackexchange.com/questions/217882", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88843/" ]
I'm trying to stylise my navigation menu regarding selected page. I made a page for news, but when I click on the following pages (page 2 for example), the navigation menu loses its class. I want it retains its `current-item-menu` class on this case. How can I do this ? Thanks for your help !
You can use [conditional tags](https://codex.wordpress.org/Conditional_Tags) to target the specific page you need to remove the styles on. You can use `is_page()` to target a *page* page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target *any* page. ``` function wpse_217881_remove_scripts() { // Check for the page you want to target if ( is_page( 'About Me And Joe' ) ) { // Remove Styles wp_dequeue_style( 'parent-style' ); wp_dequeue_style( 'child-style' ); wp_dequeue_style( 'parent-style-css' ); wp_deregister_style( 'parent-style' ); wp_deregister_style( 'child-style' ); wp_deregister_style( 'parent-style-css' ); } } ``` I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance `wp_enqueue_scripts`. *From the [`wp_enqueue_scripts` docs](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts):* > > Despite the name, it is used for enqueuing both scripts and styles > > > ``` add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' ); // Optionaly add a priority if needed i.e: // add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 ); ```
217,897
<p>I've been adding all the <em>"recommended"</em> <strong>schema.org</strong> markup to my sites for awhile now. Most of the schema markup <a href="https://developers.google.com/structured-data/" rel="nofollow">adds value to google searches</a>. </p> <p>There's other markup though that I've been using and I'm not really sure who actually uses it (search engines, other sites, etc).</p> <p><strong>Specifically, for this question, I'm wondering about the wordpress related schema.org markup:</strong></p> <p><strong>Header:</strong> <code>&lt;header itemscope itemtype="https://schema.org/WPHeader"&gt;</code></p> <p><strong>Sidebar:</strong> <code>&lt;aside itemscope itemtype="https://schema.org/WPSideBar"&gt;</code></p> <p><strong>Footer:</strong> <code>&lt;footer itemscope itemtype="https://schema.org/WPFooter"&gt;</code></p> <p>Does anyone know what the purpose of this markup is? Does it add SEO value? If so how and where? Thanks!</p>
[ { "answer_id": 217892, "author": "Cai", "author_id": 81652, "author_profile": "https://wordpress.stackexchange.com/users/81652", "pm_score": 4, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">conditional tags</a> to target the specific page you need to remove the styles on. You can use <code>is_page()</code> to target a <em>page</em> page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target <em>any</em> page.</p>\n\n<pre><code>function wpse_217881_remove_scripts() {\n\n // Check for the page you want to target\n if ( is_page( 'About Me And Joe' ) ) {\n\n // Remove Styles\n wp_dequeue_style( 'parent-style' );\n wp_dequeue_style( 'child-style' );\n wp_dequeue_style( 'parent-style-css' );\n wp_deregister_style( 'parent-style' );\n wp_deregister_style( 'child-style' );\n wp_deregister_style( 'parent-style-css' );\n }\n}\n</code></pre>\n\n<p>I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance <code>wp_enqueue_scripts</code>.</p>\n\n<p><em>From the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code> docs</a>:</em></p>\n\n<blockquote>\n <p>Despite the name, it is used for enqueuing both scripts and styles</p>\n</blockquote>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' );\n\n// Optionaly add a priority if needed i.e:\n// add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 );\n</code></pre>\n" }, { "answer_id": 406864, "author": "nab", "author_id": 198153, "author_profile": "https://wordpress.stackexchange.com/users/198153", "pm_score": 0, "selected": false, "text": "<p>The best solutiuon for me was to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">template</a> with different or no head.</p>\n" } ]
2016/02/17
[ "https://wordpress.stackexchange.com/questions/217897", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38123/" ]
I've been adding all the *"recommended"* **schema.org** markup to my sites for awhile now. Most of the schema markup [adds value to google searches](https://developers.google.com/structured-data/). There's other markup though that I've been using and I'm not really sure who actually uses it (search engines, other sites, etc). **Specifically, for this question, I'm wondering about the wordpress related schema.org markup:** **Header:** `<header itemscope itemtype="https://schema.org/WPHeader">` **Sidebar:** `<aside itemscope itemtype="https://schema.org/WPSideBar">` **Footer:** `<footer itemscope itemtype="https://schema.org/WPFooter">` Does anyone know what the purpose of this markup is? Does it add SEO value? If so how and where? Thanks!
You can use [conditional tags](https://codex.wordpress.org/Conditional_Tags) to target the specific page you need to remove the styles on. You can use `is_page()` to target a *page* page (as opposed to another post type) and pass a page ID, slug, title, or no argument to target *any* page. ``` function wpse_217881_remove_scripts() { // Check for the page you want to target if ( is_page( 'About Me And Joe' ) ) { // Remove Styles wp_dequeue_style( 'parent-style' ); wp_dequeue_style( 'child-style' ); wp_dequeue_style( 'parent-style-css' ); wp_deregister_style( 'parent-style' ); wp_deregister_style( 'child-style' ); wp_deregister_style( 'parent-style-css' ); } } ``` I'm assuming you already are, but to be explicit, you should be calling the function that dequeue/deregisters the styles from an action hook - in this instance `wp_enqueue_scripts`. *From the [`wp_enqueue_scripts` docs](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts):* > > Despite the name, it is used for enqueuing both scripts and styles > > > ``` add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts' ); // Optionaly add a priority if needed i.e: // add_action( 'wp_enqueue_scripts', 'wpse_217881_remove_scripts', 20 ); ```
217,932
<p>I have written some long descriptions for a custom category taxonomy. I don't want to remove them, I just want to hide it from the management page:</p> <pre><code>/wp-admin/term.php?taxonomy=custom_category </code></pre> <p>I could use CSS to hide the class "column-description", but I don't know how to only apply it to this taxonomy. </p>
[ { "answer_id": 217934, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>You could target the edit form for the <em>post_tag</em> taxonomy, through the <code>post_tag_edit_form</code> hook:</p>\n\n<pre><code>/**\n * Hide the term description in the post_tag edit form\n */\nadd_action( \"post_tag_edit_form\", function( $tag, $taxonomy )\n{ \n ?&gt;&lt;style&gt;.term-description-wrap{display:none;}&lt;/style&gt;&lt;?php\n}, 10, 2 );\n</code></pre>\n\n<p>Here you can also target an individual tag.</p>\n\n<p>If you need something similar for other taxonomies, you can use the <code>{taxonomy_slug}_edit_form</code> hook.</p>\n\n<h2>Update</h2>\n\n<p>It looks like the question was about the list tables, not the edit form.</p>\n\n<p>I dug into the list tables in WorPress and found a way to remove the description column from the term table in <code>edit-tags.php</code></p>\n\n<pre><code>/**\n * Remove the 'description' column from the table in 'edit-tags.php'\n * but only for the 'post_tag' taxonomy\n */\nadd_filter('manage_edit-post_tag_columns', function ( $columns ) \n{\n if( isset( $columns['description'] ) )\n unset( $columns['description'] ); \n\n return $columns;\n} );\n</code></pre>\n\n<p>If you want to do the same for other taxonomies, use the <code>manage_edit-{taxonomy_slug}_columns</code> filter.</p>\n" }, { "answer_id": 269272, "author": "iwanuschka", "author_id": 121207, "author_profile": "https://wordpress.stackexchange.com/users/121207", "pm_score": 2, "selected": false, "text": "<p>If you also need to hide the description field in the add form use this code</p>\n\n<pre><code>/**\n * Hide the term description in the edit form\n */\nadd_action( '{taxonomy_slug}_add_form', function( $taxonomy )\n{\n ?&gt;&lt;style&gt;.term-description-wrap{display:none;}&lt;/style&gt;&lt;?php\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 308418, "author": "Michel Moraes", "author_id": 109142, "author_profile": "https://wordpress.stackexchange.com/users/109142", "pm_score": 3, "selected": false, "text": "<p>The cleanest way to do that, removing the description field from the edit screen also in the add screen:</p>\n\n<pre><code>function hide_description_row() {\n echo \"&lt;style&gt; .term-description-wrap { display:none; } &lt;/style&gt;\";\n}\n\nadd_action( \"{taxonomy_slug}_edit_form\", 'hide_description_row');\nadd_action( \"{taxonomy_slug}_add_form\", 'hide_description_row');\n</code></pre>\n\n<p>Of course you need to replace {taxonomy_slug} with your taxonomy slug.</p>\n" } ]
2016/02/17
[ "https://wordpress.stackexchange.com/questions/217932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have written some long descriptions for a custom category taxonomy. I don't want to remove them, I just want to hide it from the management page: ``` /wp-admin/term.php?taxonomy=custom_category ``` I could use CSS to hide the class "column-description", but I don't know how to only apply it to this taxonomy.
You could target the edit form for the *post\_tag* taxonomy, through the `post_tag_edit_form` hook: ``` /** * Hide the term description in the post_tag edit form */ add_action( "post_tag_edit_form", function( $tag, $taxonomy ) { ?><style>.term-description-wrap{display:none;}</style><?php }, 10, 2 ); ``` Here you can also target an individual tag. If you need something similar for other taxonomies, you can use the `{taxonomy_slug}_edit_form` hook. Update ------ It looks like the question was about the list tables, not the edit form. I dug into the list tables in WorPress and found a way to remove the description column from the term table in `edit-tags.php` ``` /** * Remove the 'description' column from the table in 'edit-tags.php' * but only for the 'post_tag' taxonomy */ add_filter('manage_edit-post_tag_columns', function ( $columns ) { if( isset( $columns['description'] ) ) unset( $columns['description'] ); return $columns; } ); ``` If you want to do the same for other taxonomies, use the `manage_edit-{taxonomy_slug}_columns` filter.
217,954
<p>I'm in the process of creating my first theme, and I'm using Quark as a starter theme.</p> <p>I would like the theme to have various options, one being header selection. (let's say 5 different headers - when selected, the header will show site wide.)</p> <p>I also would like to implement various headers whose code are available on codepen, but what I'm struggling with is giving users the ability to select their header of choice.</p> <p>Let' say I want to implement this menu first : <a href="http://codepen.io/WhiteWolfWizard/pen/CJLeu" rel="nofollow">http://codepen.io/WhiteWolfWizard/pen/CJLeu</a>.</p> <p>I've read the Codex for get header function, and I also saw this :</p> <pre><code>&lt;?php if ( is_home() ) : get_header( 'home' ); elseif ( is_404() ) : get_header( '404' ); else : get_header(); endif; ?&gt; </code></pre> <p>It's not suitable to what I'm trying to do, since it shows a header on a per-page basis.</p> <p>So I was wondering : where the code for the different headers should be, and how can I give the users the ability to select the headers ? (either with option tree, Customizer API, or a better solution if you have any)</p> <p>Thanks</p> <p>PS : I'm a beginner at this.</p>
[ { "answer_id": 217968, "author": "тнє Sufi", "author_id": 28744, "author_profile": "https://wordpress.stackexchange.com/users/28744", "pm_score": 0, "selected": false, "text": "<p>With Option Tree, you can use it like this way:</p>\n\n<p>Lets say you will provide 5 different header designs. Create 5 header files:</p>\n\n<ol>\n<li>header.php </li>\n<li>header-two.php </li>\n<li>header-three.php </li>\n<li>header-four.php </li>\n<li>header-five.php</li>\n</ol>\n\n<p>Now you can check it like:</p>\n\n<pre><code>if (ot_get_option('your_header_selection_key') == 'one'){\n get_header();\n} elseif (ot_get_option('your_header_selection_key') == 'two'){\n get_header('two');\n} elseif (ot_get_option('your_header_selection_key') == 'three'){\n get_header('three');\n} elseif (ot_get_option('your_header_selection_key') == 'four'){\n get_header('four');\n} elseif (ot_get_option('your_header_selection_key') == 'five'){\n get_header('five');\n}\n</code></pre>\n\n<p>You can wrap these code in a function inside <code>functions.php</code> and call from page templates, instead writing them on every template file.</p>\n\n<p>This is just an idea. You can use <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/\" rel=\"nofollow\">Customizer API</a> with this same idea, if you do not use Option Tree.</p>\n" }, { "answer_id": 218002, "author": "dingo_d", "author_id": 58895, "author_profile": "https://wordpress.stackexchange.com/users/58895", "pm_score": 2, "selected": true, "text": "<p>So first you need customizer options. You can put this in <code>customizer.php</code> and include that file in your <code>functions.php</code> or you can just put it in <code>functions.php</code> directly.</p>\n\n<pre><code>add_action('customize_register', 'mytheme_customize_register');\n\nfunction mytheme_customize_register( $wp_customize ) {\n\n /**\n ------------------------------------------------------------\n SECTION: Header\n ------------------------------------------------------------\n **/\n $wp_customize-&gt;add_section('section_header', array(\n 'title' =&gt; esc_html__('Header', 'mytheme'),\n 'description' =&gt; esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ),\n 'priority' =&gt; 1,\n ));\n\n /**\n Header Styles\n **/\n $wp_customize-&gt;add_setting( 'header_styles', array(\n 'default' =&gt; '',\n ));\n $wp_customize-&gt;add_control( 'header_styles', array(\n 'label' =&gt; esc_html__( 'Header Styles', 'mytheme' ),\n 'section' =&gt; 'section_header',\n 'type' =&gt; 'select',\n 'choices' =&gt; array(\n 'style_1' =&gt; esc_html__('Header 1', 'mytheme'),\n 'style_2' =&gt; esc_html__('Header 2', 'mytheme'),\n 'style_3' =&gt; esc_html__('Header 3', 'mytheme'),\n ),\n ));\n\n}\n</code></pre>\n\n<p>This will give you a dropdown settings in your customizer.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Z2uMP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2uMP.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>With that you can, wherever your header element tag <code>&lt;header&gt;</code> is located, add any styling or even include separate file if you want.</p>\n\n<p>Say that your header is in a file called <code>header_style_1.php</code> located in a <code>partials</code> folder, and it's included in the <code>header.php</code> file as</p>\n\n<pre><code>get_template_part('partials/header_style_1);\n</code></pre>\n\n<p>You can add files <code>header_style_2.php</code> and <code>header_style_3.php</code> and in your <code>header.php</code> just add:</p>\n\n<pre><code>$header_style = get_theme_mod('header_styles', 'style_1');\n\nget_template_part('partials/header_'.$header_layout);\n</code></pre>\n\n<p>This will fetch any of that templates you created for your header. </p>\n\n<p>Hope this helps.</p>\n" } ]
2016/02/17
[ "https://wordpress.stackexchange.com/questions/217954", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37147/" ]
I'm in the process of creating my first theme, and I'm using Quark as a starter theme. I would like the theme to have various options, one being header selection. (let's say 5 different headers - when selected, the header will show site wide.) I also would like to implement various headers whose code are available on codepen, but what I'm struggling with is giving users the ability to select their header of choice. Let' say I want to implement this menu first : <http://codepen.io/WhiteWolfWizard/pen/CJLeu>. I've read the Codex for get header function, and I also saw this : ``` <?php if ( is_home() ) : get_header( 'home' ); elseif ( is_404() ) : get_header( '404' ); else : get_header(); endif; ?> ``` It's not suitable to what I'm trying to do, since it shows a header on a per-page basis. So I was wondering : where the code for the different headers should be, and how can I give the users the ability to select the headers ? (either with option tree, Customizer API, or a better solution if you have any) Thanks PS : I'm a beginner at this.
So first you need customizer options. You can put this in `customizer.php` and include that file in your `functions.php` or you can just put it in `functions.php` directly. ``` add_action('customize_register', 'mytheme_customize_register'); function mytheme_customize_register( $wp_customize ) { /** ------------------------------------------------------------ SECTION: Header ------------------------------------------------------------ **/ $wp_customize->add_section('section_header', array( 'title' => esc_html__('Header', 'mytheme'), 'description' => esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ), 'priority' => 1, )); /** Header Styles **/ $wp_customize->add_setting( 'header_styles', array( 'default' => '', )); $wp_customize->add_control( 'header_styles', array( 'label' => esc_html__( 'Header Styles', 'mytheme' ), 'section' => 'section_header', 'type' => 'select', 'choices' => array( 'style_1' => esc_html__('Header 1', 'mytheme'), 'style_2' => esc_html__('Header 2', 'mytheme'), 'style_3' => esc_html__('Header 3', 'mytheme'), ), )); } ``` This will give you a dropdown settings in your customizer. [![enter image description here](https://i.stack.imgur.com/Z2uMP.jpg)](https://i.stack.imgur.com/Z2uMP.jpg) With that you can, wherever your header element tag `<header>` is located, add any styling or even include separate file if you want. Say that your header is in a file called `header_style_1.php` located in a `partials` folder, and it's included in the `header.php` file as ``` get_template_part('partials/header_style_1); ``` You can add files `header_style_2.php` and `header_style_3.php` and in your `header.php` just add: ``` $header_style = get_theme_mod('header_styles', 'style_1'); get_template_part('partials/header_'.$header_layout); ``` This will fetch any of that templates you created for your header. Hope this helps.
217,960
<p>I installed wp 4.2.2 on xampp localhost - multisite, following this article <a href="https://premium.wpmudev.org/blog/setting-up-xampp/" rel="nofollow">https://premium.wpmudev.org/blog/setting-up-xampp/</a></p> <p>xampp is surely ok, because it works a year without a problem.</p> <p>The new installation is wordpress only.</p> <p>Installation seems ok, but starting dashboard - Appearance - Themes I can see just current theme (Twenty Sixteen), without any button to load additional themes.</p> <p>I checked wp-content folder - there are three default themes there.</p> <p>Any help?</p>
[ { "answer_id": 217968, "author": "тнє Sufi", "author_id": 28744, "author_profile": "https://wordpress.stackexchange.com/users/28744", "pm_score": 0, "selected": false, "text": "<p>With Option Tree, you can use it like this way:</p>\n\n<p>Lets say you will provide 5 different header designs. Create 5 header files:</p>\n\n<ol>\n<li>header.php </li>\n<li>header-two.php </li>\n<li>header-three.php </li>\n<li>header-four.php </li>\n<li>header-five.php</li>\n</ol>\n\n<p>Now you can check it like:</p>\n\n<pre><code>if (ot_get_option('your_header_selection_key') == 'one'){\n get_header();\n} elseif (ot_get_option('your_header_selection_key') == 'two'){\n get_header('two');\n} elseif (ot_get_option('your_header_selection_key') == 'three'){\n get_header('three');\n} elseif (ot_get_option('your_header_selection_key') == 'four'){\n get_header('four');\n} elseif (ot_get_option('your_header_selection_key') == 'five'){\n get_header('five');\n}\n</code></pre>\n\n<p>You can wrap these code in a function inside <code>functions.php</code> and call from page templates, instead writing them on every template file.</p>\n\n<p>This is just an idea. You can use <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/\" rel=\"nofollow\">Customizer API</a> with this same idea, if you do not use Option Tree.</p>\n" }, { "answer_id": 218002, "author": "dingo_d", "author_id": 58895, "author_profile": "https://wordpress.stackexchange.com/users/58895", "pm_score": 2, "selected": true, "text": "<p>So first you need customizer options. You can put this in <code>customizer.php</code> and include that file in your <code>functions.php</code> or you can just put it in <code>functions.php</code> directly.</p>\n\n<pre><code>add_action('customize_register', 'mytheme_customize_register');\n\nfunction mytheme_customize_register( $wp_customize ) {\n\n /**\n ------------------------------------------------------------\n SECTION: Header\n ------------------------------------------------------------\n **/\n $wp_customize-&gt;add_section('section_header', array(\n 'title' =&gt; esc_html__('Header', 'mytheme'),\n 'description' =&gt; esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ),\n 'priority' =&gt; 1,\n ));\n\n /**\n Header Styles\n **/\n $wp_customize-&gt;add_setting( 'header_styles', array(\n 'default' =&gt; '',\n ));\n $wp_customize-&gt;add_control( 'header_styles', array(\n 'label' =&gt; esc_html__( 'Header Styles', 'mytheme' ),\n 'section' =&gt; 'section_header',\n 'type' =&gt; 'select',\n 'choices' =&gt; array(\n 'style_1' =&gt; esc_html__('Header 1', 'mytheme'),\n 'style_2' =&gt; esc_html__('Header 2', 'mytheme'),\n 'style_3' =&gt; esc_html__('Header 3', 'mytheme'),\n ),\n ));\n\n}\n</code></pre>\n\n<p>This will give you a dropdown settings in your customizer.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Z2uMP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2uMP.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>With that you can, wherever your header element tag <code>&lt;header&gt;</code> is located, add any styling or even include separate file if you want.</p>\n\n<p>Say that your header is in a file called <code>header_style_1.php</code> located in a <code>partials</code> folder, and it's included in the <code>header.php</code> file as</p>\n\n<pre><code>get_template_part('partials/header_style_1);\n</code></pre>\n\n<p>You can add files <code>header_style_2.php</code> and <code>header_style_3.php</code> and in your <code>header.php</code> just add:</p>\n\n<pre><code>$header_style = get_theme_mod('header_styles', 'style_1');\n\nget_template_part('partials/header_'.$header_layout);\n</code></pre>\n\n<p>This will fetch any of that templates you created for your header. </p>\n\n<p>Hope this helps.</p>\n" } ]
2016/02/17
[ "https://wordpress.stackexchange.com/questions/217960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25574/" ]
I installed wp 4.2.2 on xampp localhost - multisite, following this article <https://premium.wpmudev.org/blog/setting-up-xampp/> xampp is surely ok, because it works a year without a problem. The new installation is wordpress only. Installation seems ok, but starting dashboard - Appearance - Themes I can see just current theme (Twenty Sixteen), without any button to load additional themes. I checked wp-content folder - there are three default themes there. Any help?
So first you need customizer options. You can put this in `customizer.php` and include that file in your `functions.php` or you can just put it in `functions.php` directly. ``` add_action('customize_register', 'mytheme_customize_register'); function mytheme_customize_register( $wp_customize ) { /** ------------------------------------------------------------ SECTION: Header ------------------------------------------------------------ **/ $wp_customize->add_section('section_header', array( 'title' => esc_html__('Header', 'mytheme'), 'description' => esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ), 'priority' => 1, )); /** Header Styles **/ $wp_customize->add_setting( 'header_styles', array( 'default' => '', )); $wp_customize->add_control( 'header_styles', array( 'label' => esc_html__( 'Header Styles', 'mytheme' ), 'section' => 'section_header', 'type' => 'select', 'choices' => array( 'style_1' => esc_html__('Header 1', 'mytheme'), 'style_2' => esc_html__('Header 2', 'mytheme'), 'style_3' => esc_html__('Header 3', 'mytheme'), ), )); } ``` This will give you a dropdown settings in your customizer. [![enter image description here](https://i.stack.imgur.com/Z2uMP.jpg)](https://i.stack.imgur.com/Z2uMP.jpg) With that you can, wherever your header element tag `<header>` is located, add any styling or even include separate file if you want. Say that your header is in a file called `header_style_1.php` located in a `partials` folder, and it's included in the `header.php` file as ``` get_template_part('partials/header_style_1); ``` You can add files `header_style_2.php` and `header_style_3.php` and in your `header.php` just add: ``` $header_style = get_theme_mod('header_styles', 'style_1'); get_template_part('partials/header_'.$header_layout); ``` This will fetch any of that templates you created for your header. Hope this helps.
218,005
<p>I'm sure this must be super simple, but Google isn't helping me!</p> <p>I am using an up-to-date WordPress and I have a two-column layout on my blog section (content left, Twitter feed right) that I am very happy with. This was created using just the <code>Appearance &gt; Widgets</code> page. </p> <p>Now I want to use the exact same layout for all my pages, which are currently single column. </p> <p>How do I do this? Do I need to use PHP?</p> <p>If I open the editor for a page and choose "Blog" as my template, then the whole page is replaced with my blog. </p>
[ { "answer_id": 217968, "author": "тнє Sufi", "author_id": 28744, "author_profile": "https://wordpress.stackexchange.com/users/28744", "pm_score": 0, "selected": false, "text": "<p>With Option Tree, you can use it like this way:</p>\n\n<p>Lets say you will provide 5 different header designs. Create 5 header files:</p>\n\n<ol>\n<li>header.php </li>\n<li>header-two.php </li>\n<li>header-three.php </li>\n<li>header-four.php </li>\n<li>header-five.php</li>\n</ol>\n\n<p>Now you can check it like:</p>\n\n<pre><code>if (ot_get_option('your_header_selection_key') == 'one'){\n get_header();\n} elseif (ot_get_option('your_header_selection_key') == 'two'){\n get_header('two');\n} elseif (ot_get_option('your_header_selection_key') == 'three'){\n get_header('three');\n} elseif (ot_get_option('your_header_selection_key') == 'four'){\n get_header('four');\n} elseif (ot_get_option('your_header_selection_key') == 'five'){\n get_header('five');\n}\n</code></pre>\n\n<p>You can wrap these code in a function inside <code>functions.php</code> and call from page templates, instead writing them on every template file.</p>\n\n<p>This is just an idea. You can use <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/\" rel=\"nofollow\">Customizer API</a> with this same idea, if you do not use Option Tree.</p>\n" }, { "answer_id": 218002, "author": "dingo_d", "author_id": 58895, "author_profile": "https://wordpress.stackexchange.com/users/58895", "pm_score": 2, "selected": true, "text": "<p>So first you need customizer options. You can put this in <code>customizer.php</code> and include that file in your <code>functions.php</code> or you can just put it in <code>functions.php</code> directly.</p>\n\n<pre><code>add_action('customize_register', 'mytheme_customize_register');\n\nfunction mytheme_customize_register( $wp_customize ) {\n\n /**\n ------------------------------------------------------------\n SECTION: Header\n ------------------------------------------------------------\n **/\n $wp_customize-&gt;add_section('section_header', array(\n 'title' =&gt; esc_html__('Header', 'mytheme'),\n 'description' =&gt; esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ),\n 'priority' =&gt; 1,\n ));\n\n /**\n Header Styles\n **/\n $wp_customize-&gt;add_setting( 'header_styles', array(\n 'default' =&gt; '',\n ));\n $wp_customize-&gt;add_control( 'header_styles', array(\n 'label' =&gt; esc_html__( 'Header Styles', 'mytheme' ),\n 'section' =&gt; 'section_header',\n 'type' =&gt; 'select',\n 'choices' =&gt; array(\n 'style_1' =&gt; esc_html__('Header 1', 'mytheme'),\n 'style_2' =&gt; esc_html__('Header 2', 'mytheme'),\n 'style_3' =&gt; esc_html__('Header 3', 'mytheme'),\n ),\n ));\n\n}\n</code></pre>\n\n<p>This will give you a dropdown settings in your customizer.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Z2uMP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2uMP.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>With that you can, wherever your header element tag <code>&lt;header&gt;</code> is located, add any styling or even include separate file if you want.</p>\n\n<p>Say that your header is in a file called <code>header_style_1.php</code> located in a <code>partials</code> folder, and it's included in the <code>header.php</code> file as</p>\n\n<pre><code>get_template_part('partials/header_style_1);\n</code></pre>\n\n<p>You can add files <code>header_style_2.php</code> and <code>header_style_3.php</code> and in your <code>header.php</code> just add:</p>\n\n<pre><code>$header_style = get_theme_mod('header_styles', 'style_1');\n\nget_template_part('partials/header_'.$header_layout);\n</code></pre>\n\n<p>This will fetch any of that templates you created for your header. </p>\n\n<p>Hope this helps.</p>\n" } ]
2016/02/17
[ "https://wordpress.stackexchange.com/questions/218005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86612/" ]
I'm sure this must be super simple, but Google isn't helping me! I am using an up-to-date WordPress and I have a two-column layout on my blog section (content left, Twitter feed right) that I am very happy with. This was created using just the `Appearance > Widgets` page. Now I want to use the exact same layout for all my pages, which are currently single column. How do I do this? Do I need to use PHP? If I open the editor for a page and choose "Blog" as my template, then the whole page is replaced with my blog.
So first you need customizer options. You can put this in `customizer.php` and include that file in your `functions.php` or you can just put it in `functions.php` directly. ``` add_action('customize_register', 'mytheme_customize_register'); function mytheme_customize_register( $wp_customize ) { /** ------------------------------------------------------------ SECTION: Header ------------------------------------------------------------ **/ $wp_customize->add_section('section_header', array( 'title' => esc_html__('Header', 'mytheme'), 'description' => esc_attr__( 'Choose one of three different Header Styles', 'mytheme' ), 'priority' => 1, )); /** Header Styles **/ $wp_customize->add_setting( 'header_styles', array( 'default' => '', )); $wp_customize->add_control( 'header_styles', array( 'label' => esc_html__( 'Header Styles', 'mytheme' ), 'section' => 'section_header', 'type' => 'select', 'choices' => array( 'style_1' => esc_html__('Header 1', 'mytheme'), 'style_2' => esc_html__('Header 2', 'mytheme'), 'style_3' => esc_html__('Header 3', 'mytheme'), ), )); } ``` This will give you a dropdown settings in your customizer. [![enter image description here](https://i.stack.imgur.com/Z2uMP.jpg)](https://i.stack.imgur.com/Z2uMP.jpg) With that you can, wherever your header element tag `<header>` is located, add any styling or even include separate file if you want. Say that your header is in a file called `header_style_1.php` located in a `partials` folder, and it's included in the `header.php` file as ``` get_template_part('partials/header_style_1); ``` You can add files `header_style_2.php` and `header_style_3.php` and in your `header.php` just add: ``` $header_style = get_theme_mod('header_styles', 'style_1'); get_template_part('partials/header_'.$header_layout); ``` This will fetch any of that templates you created for your header. Hope this helps.
218,025
<p>I wish to remove the author's links to their original website, from my page</p> <p>I know this is in either the functions.php or comments.php files.</p> <p>I'm not sure exactly of how to edit these php files, </p> <p>I've come across some code online that basically states that I must insert the following. But I am not sure where exactly to insert the curly brackets or normal brackets etc, so that the lines of code are implemented, and which brackets to use in this case.</p> <p>Help please. I am new to Wordpress like less than 1 week old. So editing .php files is a bit daunting- but I am looking to learn how to do it successfully.</p> <p>The website is www.nouvida.com--- I want the comment author's links not to be connected to the Original Theme's homepage..</p> <pre><code>add_filter( 'get_comment_author_link', 'remove_html_link_tag_from_comment_author_link' ); function remove_html_link_tag_from_comment_author_link ( $link ) { if( !in_the_loop() ) { $link = preg_replace('/&lt;a href=[\",\'](.*?)[\",\']&gt;(.*?)&lt;\/a&gt;/', "\\2", $link); } return $link; } </code></pre>
[ { "answer_id": 218028, "author": "jepser", "author_id": 6519, "author_profile": "https://wordpress.stackexchange.com/users/6519", "pm_score": -1, "selected": false, "text": "<p>If I understand what do you want to make, paste this in your functions.php</p>\n\n<pre><code>function alter_comment_form_fields($fields){\n $fields['url'] = ''; //removes website field\n\n return $fields;\n}\n\nadd_filter('comment_form_default_fields','alter_comment_form_fields');\n</code></pre>\n\n<p>This will remove the website field from the comments form.</p>\n\n<p>If you don't want to display the link on authors comment, try to modify comments.php if it's present in your theme.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 218029, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 1, "selected": false, "text": "<p>Add following code snippet in <code>functions.php</code>. (<em>in your <code>theme</code>folder</em>)</p>\n\n<p><strong>Edit new code:</strong><br />\n- <em>This should do the trick, sorry for the delay.</em></p>\n\n<pre><code>/**\n * Remove post author link on comments\n * \n * @return string $author\n */\nfunction wpse218025_remove_comment_author_link( $return, $author, $comment_ID ) {\n return $author;\n}\nadd_filter( 'get_comment_author_link', 'wpse218025_remove_comment_author_link', 10, 3 );\n</code></pre>\n\n<blockquote>\n <p>Note: you can add <code>functions</code> almost always to your <code>functions.php</code> in your <code>theme</code> folder. Ofcourse is it also possible to make a plugin but that needs a little more coding.<br />\n Please take a look <a href=\"https://codex.wordpress.org/Plugin_Resources\" rel=\"nofollow\">here</a> for making your own plugin.</p>\n</blockquote>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88910/" ]
I wish to remove the author's links to their original website, from my page I know this is in either the functions.php or comments.php files. I'm not sure exactly of how to edit these php files, I've come across some code online that basically states that I must insert the following. But I am not sure where exactly to insert the curly brackets or normal brackets etc, so that the lines of code are implemented, and which brackets to use in this case. Help please. I am new to Wordpress like less than 1 week old. So editing .php files is a bit daunting- but I am looking to learn how to do it successfully. The website is www.nouvida.com--- I want the comment author's links not to be connected to the Original Theme's homepage.. ``` add_filter( 'get_comment_author_link', 'remove_html_link_tag_from_comment_author_link' ); function remove_html_link_tag_from_comment_author_link ( $link ) { if( !in_the_loop() ) { $link = preg_replace('/<a href=[\",\'](.*?)[\",\']>(.*?)<\/a>/', "\\2", $link); } return $link; } ```
Add following code snippet in `functions.php`. (*in your `theme`folder*) **Edit new code:** - *This should do the trick, sorry for the delay.* ``` /** * Remove post author link on comments * * @return string $author */ function wpse218025_remove_comment_author_link( $return, $author, $comment_ID ) { return $author; } add_filter( 'get_comment_author_link', 'wpse218025_remove_comment_author_link', 10, 3 ); ``` > > Note: you can add `functions` almost always to your `functions.php` in your `theme` folder. Ofcourse is it also possible to make a plugin but that needs a little more coding. > > Please take a look [here](https://codex.wordpress.org/Plugin_Resources) for making your own plugin. > > >
218,036
<p>how can i display in my theme all woocommerce category title are custom filed value. </p> <p>example html like bellow </p> <pre><code>&lt;li&gt;&lt;a href="#"&gt; &lt;div&gt; &lt;h2&gt;category title&lt;/h5&gt; &lt;h3&gt;custom field one value&lt;/h6&gt; &lt;/div&gt; &lt;div class="imgpos"&gt;custom field two value&lt;/div&gt; &lt;/a&gt;&lt;/li&gt; </code></pre> <p>i tried many way but still not success </p> <pre><code>&lt;?php $post_type = 'product'; // Get all the taxonomies for this post type $taxonomies = get_object_taxonomies( (object) array( 'post_type' =&gt; $post_type ) ); foreach( $taxonomies as $taxonomy ) : // Gets every "category" (term) in this taxonomy to get the respective posts $terms = get_terms( $taxonomy ); foreach( $terms as $term ) : $posts = new WP_Query( "taxonomy=$taxonomy&amp;term=$term-&gt;slug&amp;posts_per_page=2" ); if( $posts-&gt;have_posts() ): while( $posts-&gt;have_posts() ) : $posts-&gt;the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;span&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;?php endwhile; endif; endforeach; endforeach; ?&gt; </code></pre> <p><strong>UPDATE 1</strong> bellow code only give me category title and link but can not figure out how to get costume filed value also </p> <pre><code>&lt;?php $args = array( 'number' =&gt; $number, 'orderby' =&gt; 'title', 'order' =&gt; 'ASC', 'hide_empty' =&gt; $hide_empty, 'include' =&gt; $ids ); $product_categories = get_terms( 'product_cat', $args ); $count = count($product_categories); if ( $count &gt; 0 ){ foreach ( $product_categories as $product_category ) { echo '&lt;h4&gt;&lt;a href="' . get_term_link( $product_category ) . '"&gt;' . $product_category-&gt;name . '&lt;/a&gt;&lt;/h4&gt;'; $args = array( 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'slug', // 'terms' =&gt; 'white-wines' 'terms' =&gt; $product_category-&gt;slug ) ), ); } } ?&gt; </code></pre> <p>example for get custom value code will be bellow. i want fit that inside div</p> <pre><code> &lt;?php if( get_field('hexagon_thumbnail') ): ?&gt; &lt;img src="&lt;?php the_field('hexagon_thumbnail'); ?&gt;" /&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 218043, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;?php\n\n$post_type = 'product';\n\n$taxonomies = get_object_taxonomies((object) array( 'post_type' =&gt; $post_type ));\n\nforeach ($taxonomies as $taxonomy) : \n\n $terms = get_terms($taxonomy);\n\n foreach ($terms as $term) : \n\n $term_link = get_term_link($term-&gt;term_id);\n\n $posts = new WP_Query( \"taxonomy=$taxonomy&amp;term=$term-&gt;slug&amp;posts_per_page=2\" ); ?&gt;\n\n &lt;li&gt;\n\n &lt;h2&gt;\n &lt;a href=\"&lt;?php echo $term_link; ?&gt;\"&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/a&gt;\n &lt;/h2&gt;\n\n &lt;?php \n\n if( $posts-&gt;have_posts() ): while( $posts-&gt;have_posts() ) : $posts-&gt;the_post(); ?&gt;\n\n &lt;div&gt;\n\n &lt;?php if( get_field('hexagon_thumbnail') ): ?&gt;\n\n &lt;img src=\"&lt;?php the_field('hexagon_thumbnail'); ?&gt;\" /&gt;\n\n &lt;?php endif; ?&gt;\n\n &lt;/div&gt;\n\n &lt;?php endwhile; endif; ?&gt;\n\n &lt;/li&gt; &lt;!-- end list item --&gt;\n\n&lt;?php endforeach; endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 237082, "author": "user101626", "author_id": 101626, "author_profile": "https://wordpress.stackexchange.com/users/101626", "pm_score": 0, "selected": false, "text": "<p>To fetch the value of ACF in the product loop you need to pass the id of the product, if the acf in product, or if the ACF in product category the id will be term id followed by product_cat_{term_id} as the second parameter of the the_field or get field function. </p>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87838/" ]
how can i display in my theme all woocommerce category title are custom filed value. example html like bellow ``` <li><a href="#"> <div> <h2>category title</h5> <h3>custom field one value</h6> </div> <div class="imgpos">custom field two value</div> </a></li> ``` i tried many way but still not success ``` <?php $post_type = 'product'; // Get all the taxonomies for this post type $taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) ); foreach( $taxonomies as $taxonomy ) : // Gets every "category" (term) in this taxonomy to get the respective posts $terms = get_terms( $taxonomy ); foreach( $terms as $term ) : $posts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=2" ); if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?> <a href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span></a><br><br> <?php endwhile; endif; endforeach; endforeach; ?> ``` **UPDATE 1** bellow code only give me category title and link but can not figure out how to get costume filed value also ``` <?php $args = array( 'number' => $number, 'orderby' => 'title', 'order' => 'ASC', 'hide_empty' => $hide_empty, 'include' => $ids ); $product_categories = get_terms( 'product_cat', $args ); $count = count($product_categories); if ( $count > 0 ){ foreach ( $product_categories as $product_category ) { echo '<h4><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</a></h4>'; $args = array( 'posts_per_page' => -1, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'product_cat', 'field' => 'slug', // 'terms' => 'white-wines' 'terms' => $product_category->slug ) ), ); } } ?> ``` example for get custom value code will be bellow. i want fit that inside div ``` <?php if( get_field('hexagon_thumbnail') ): ?> <img src="<?php the_field('hexagon_thumbnail'); ?>" /> <?php endif; ?> ```
``` <?php $post_type = 'product'; $taxonomies = get_object_taxonomies((object) array( 'post_type' => $post_type )); foreach ($taxonomies as $taxonomy) : $terms = get_terms($taxonomy); foreach ($terms as $term) : $term_link = get_term_link($term->term_id); $posts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=2" ); ?> <li> <h2> <a href="<?php echo $term_link; ?>"><?php echo $term->name; ?></a> </h2> <?php if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?> <div> <?php if( get_field('hexagon_thumbnail') ): ?> <img src="<?php the_field('hexagon_thumbnail'); ?>" /> <?php endif; ?> </div> <?php endwhile; endif; ?> </li> <!-- end list item --> <?php endforeach; endforeach; ?> ```
218,049
<p>I'm building my own website within WordPress from scratch. It's not really a new theme, just everything from the beginning, starting with an index file, header, footer, single, comments, functions etc. Utilizing WordPress' features where ever I need them.</p> <p>I've always been doing good at that, except from when I discovered the Nested comment feature and wanted to tap into that.</p> <p>But.</p> <p>I can't get the freaking <strong>comment-reply.js</strong> to load. Doesn't matter whether I run it in functions or in the header. Even if I just use the raw</p> <pre><code>wp_enqueue_script( 'comment-reply' ) </code></pre> <p>that should load on each page.</p> <p>It completely ignores it. If I call the .js file directly by naming the hardcoded url it loads, but this is not the way it's supposed to be coded. It's just a bad work-around.</p> <pre><code>&lt;?php if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option('thread_comments') ) { ?&gt; &lt;script src="&lt;?php bloginfo( 'url' ); ?&gt;/wp-includes/js/comment-reply.js"&gt;&lt;/script&gt; &lt;?php } ?&gt; </code></pre> <p>I've even tried to empty all code out so that the ONLY thing the website does is to load the script but without results. And yes nested comments are activated in settings. I've also tried reinstalling on different domains in case the WP code got screwed.</p> <p>Any suggestions?</p>
[ { "answer_id": 218087, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 4, "selected": true, "text": "<p>Maybe this helps you out?<br />\nPlease make a backup from <code>functions.php</code> and add following <code>function</code>.</p>\n\n<pre><code>/**\n * Add .js script if \"Enable threaded comments\" is activated in Admin\n * Codex: {@link https://developer.wordpress.org/reference/functions/wp_enqueue_script/}\n */\nfunction wpse218049_enqueue_comments_reply() {\n\n if( is_singular() &amp;&amp; comments_open() &amp;&amp; ( get_option( 'thread_comments' ) == 1) ) {\n // Load comment-reply.js (into footer)\n wp_enqueue_script( 'comment-reply', '/wp-includes/js/comment-reply.min.js', array(), false, true );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse218049_enqueue_comments_reply' );\n</code></pre>\n\n<blockquote>\n <p>Note: see codex on how to <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">enqueue</a></p>\n</blockquote>\n" }, { "answer_id": 231865, "author": "Nu Kieu", "author_id": 98083, "author_profile": "https://wordpress.stackexchange.com/users/98083", "pm_score": 1, "selected": false, "text": "<p>I had this problem too. I found out that the <code>comment-reply.js</code> is loaded at the bottom of the page, so you won't find it in your header. Make sure you have <code>wp_footer()</code> inside your <code>footer.php</code>.</p>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88957/" ]
I'm building my own website within WordPress from scratch. It's not really a new theme, just everything from the beginning, starting with an index file, header, footer, single, comments, functions etc. Utilizing WordPress' features where ever I need them. I've always been doing good at that, except from when I discovered the Nested comment feature and wanted to tap into that. But. I can't get the freaking **comment-reply.js** to load. Doesn't matter whether I run it in functions or in the header. Even if I just use the raw ``` wp_enqueue_script( 'comment-reply' ) ``` that should load on each page. It completely ignores it. If I call the .js file directly by naming the hardcoded url it loads, but this is not the way it's supposed to be coded. It's just a bad work-around. ``` <?php if ( is_singular() && comments_open() && get_option('thread_comments') ) { ?> <script src="<?php bloginfo( 'url' ); ?>/wp-includes/js/comment-reply.js"></script> <?php } ?> ``` I've even tried to empty all code out so that the ONLY thing the website does is to load the script but without results. And yes nested comments are activated in settings. I've also tried reinstalling on different domains in case the WP code got screwed. Any suggestions?
Maybe this helps you out? Please make a backup from `functions.php` and add following `function`. ``` /** * Add .js script if "Enable threaded comments" is activated in Admin * Codex: {@link https://developer.wordpress.org/reference/functions/wp_enqueue_script/} */ function wpse218049_enqueue_comments_reply() { if( is_singular() && comments_open() && ( get_option( 'thread_comments' ) == 1) ) { // Load comment-reply.js (into footer) wp_enqueue_script( 'comment-reply', '/wp-includes/js/comment-reply.min.js', array(), false, true ); } } add_action( 'wp_enqueue_scripts', 'wpse218049_enqueue_comments_reply' ); ``` > > Note: see codex on how to [enqueue](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) > > >
218,057
<p>I've written a custom theme. It's pretty complex so I won't post a huge code block here for everyone's sanity.</p> <p>In my <code>functions.php</code> file I have the following hook being called:</p> <pre><code>function DA_script_enqueue() { if( is_404() ){ //load scripts with wp_enqueue_script() } if( is_search() ){ //load scripts with wp_enqueue_script() } } add_action( 'wp_enqueue_scripts', 'DA_script_enqueue'); </code></pre> <p>What happens on my wordpress website when my theme is activated is that no scripts get added to the <code>search.php</code> page but they <strong>do</strong> get added to the <code>404.php</code> page which is very odd! In fact, not even killing the page works with <code>die();</code></p> <pre><code>if( is_search() ){ die('it works'); } </code></pre> <p>This leads me to think that the condition is never being met within the hook override for <code>wp_enqueue_scripts</code>. I'm not sure if this is a bug, or if my logic is just incorrect and I'm calling the wrong functions. What else can I try to make my logic work?</p> <p>Thanks </p> <p><strong>Edit:</strong> Okay an update: I just tried the above code in another theme and it <strong>DOES</strong> do what it's supposed to! I guess the question I should now be asking is what can I do to ensure <code>is_search()</code> returns <code>true</code>? So far I've disabled <strong>all</strong> plugins and removed a <code>query_posts()</code> call from index.php, but still facing issues :( </p> <p><strong>Edit #2:</strong> After 9 hours of debugging this (<em>sigh</em>) I've finally found what's causing the problem (but no solution to it - yet!)</p> <p>I created a test wordpress site and copied over my custom theme files. I deleted them one by one until I had the bare minimum files needed for a theme and that's when I found out what was causing the problem. It seems having a <code>header.php</code> file makes <code>is_search()</code> return <code>false</code>. Very strange!</p> <p><a href="https://i.stack.imgur.com/mDisN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mDisN.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/QCHIs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QCHIs.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/JGOTd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JGOTd.png" alt="enter image description here"></a></p> <p>As you can see from the screenshots above, as soon as I delete the header.php file everything is fine as <code>is_search()</code> returns true.</p> <p>What on earth could be causing this very strange issue? I have other themes with a header.php file in them and they work fine...</p> <p>I'm going to continue to play around with this but here are my source files just in case:</p> <p><code>search.php</code>:</p> <pre><code>&lt;?php get_header(); ?&gt; search page &lt;?php get_footer(); ?&gt; </code></pre> <p><code>functions.php</code>:</p> <pre><code>&lt;?php // This function will load certain scripts on certain pages - saving on bandwidth and server resourses. function init_scripts() { if ( is_search() ) { die('Yes this is the search page loading from the init_scripts function'); } } add_action( 'wp_enqueue_scripts', 'init_scripts' ); ?&gt; </code></pre> <p><code>header.php</code>:</p> <pre><code>header </code></pre> <p><strong>Edit #3:</strong> Here is the output of <code>$wp_query</code> also <a href="http://pastebin.com/Z0DwDd20" rel="nofollow noreferrer">http://pastebin.com/Z0DwDd20</a></p> <p><strong>Edit #4:</strong> Time for bed now so I guess I'll have another shot at this tomorrow. Here's the theme files just in case anyone is interested: <a href="https://drive.google.com/folderview?id=0B1zYR-LjR-j9NFV2ZXg3V0NJblk&amp;usp=sharing" rel="nofollow noreferrer">https://drive.google.com/folderview?id=0B1zYR-LjR-j9NFV2ZXg3V0NJblk&amp;usp=sharing</a></p>
[ { "answer_id": 218147, "author": "Stephen", "author_id": 85039, "author_profile": "https://wordpress.stackexchange.com/users/85039", "pm_score": 1, "selected": false, "text": "<p>As a partial answer to your question, I can explain your confusion over deleting the header file. The <code>wp_enqueue_scripts</code> hook is fired in the <code>wp_head()</code>, which must be in your <code>header.php</code> file. Your dummy header file doesn't include this, so the entire <code>DA_script_enqueue</code> function isn't running at all. When you delete the header.php file, WordPress uses a default instead, which does include <code>wp_head</code>.</p>\n\n<p>For your original problem you'll need to go back to square one and debug things a bit at a time, but without losing the <code>wp_head()</code> function.</p>\n" }, { "answer_id": 218148, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>The <code>var_dump</code> from the main query is fine, <code>is_search()</code> returns true as it should. Also, the SQL query look fine for a search page.</p>\n\n<p>This further deepens my suspicion that something is altering the main query right after it is successfully executed, and this happens most probably before <code>wp_enqueue_scripts</code>.</p>\n\n<p>The most probable culprit here is <code>query_posts</code>. I can remember a while ago that someone had such an issue which turned out to be YOAST plugin (<em>IIRC</em>) which used <code>query_posts</code> or some bad filter or something, and the issue was solved by deactivating the plugin.</p>\n\n<p>Your best place to start here would be to search your theme for <code>query_posts</code> and sort that out if there is any instances of <code>query_posts</code>. If it is not in a theme, you'll need to look into your plugins. Deactivate your plugins one by one and test after each one has being deactivated. You should be able to find the culprit with this method</p>\n\n<h2>EDIT</h2>\n\n<p>Try resetting the main query on <code>wp_enqueue_scripts</code> and then check if your styles and scripts are enqueued from your action. If so, that means that <code>is_search()</code> returns true, which 99.9% confirms the use of <code>query_posts</code> somewhere in your theme or plugin. </p>\n\n<p><strong><em>NOTE:</strong> This is just a test and <strong>not</strong> a solution.</em></p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function ()\n{\n wp_reset_query();\n}, 9 );\n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>I just realised that you have already deactivated all plugins. As you have stated, when you delete <code>header.php</code>, your results is ok. </p>\n\n<p><strong>Debugging</strong></p>\n\n<p>Unfortunately, the files you linked to does not help as it is basicly just all the themes in you themes folder, but here is some basic debug info</p>\n\n<ul>\n<li><p>Code editors has quite good search functions which you can use to search for spefific strings inside all files within your theme. I would start by searching for all instances of <code>query_posts</code>, specially inside your functions files as it seems like the issue is caused by something hooked to an action hook which resides in the header or is actually hooked to <code>wp_head</code></p></li>\n<li><p><code>header.php</code> houses the <code>wp_head()</code> function which is just a wrapper for the <code>wp_head</code> action. There are many action hooks (<em>like <code>wp_enqueue_scripts</code></em>) hooked to <code>wp_head</code>. Check <a href=\"https://wordpress.stackexchange.com/q/17394/31545\">this post</a> in order to get a list of everything hooked to <code>wp_head</code>. As a quick debugging check to check if the issue is caused by anything hooked to <code>wp_head</code> before going on a wild goose chase, simply delete <code>wp_head()</code> and check the <code>is_search()</code> condition. Obviously, if <code>is_search()</code> return true then, something hooked to <code>wp_head</code> is causing the issue. </p></li>\n<li><p><code>header.php</code> also houses functions like navigations menus, and most of these functions are filterable to filters. It might be that there is a bad filter that is used by one of these functions. If the above two bullet points where fruitless, delete these functions one by one to determine the bad apple. nce you have the bad apple, it is as easy as looking at the source code to determine which filters it uses and then looking for these custom filters in your theme's function files</p></li>\n</ul>\n" }, { "answer_id": 320647, "author": "bedman", "author_id": 155015, "author_profile": "https://wordpress.stackexchange.com/users/155015", "pm_score": 2, "selected": false, "text": "<p>When using <code>wp_enqueue_script</code>, you probably passing <code>true</code> for <code>in_footer</code> parameter. If so, then check that your <code>search.php</code> is calling <code>get_footer()</code> function at the bottom. </p>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218057", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36192/" ]
I've written a custom theme. It's pretty complex so I won't post a huge code block here for everyone's sanity. In my `functions.php` file I have the following hook being called: ``` function DA_script_enqueue() { if( is_404() ){ //load scripts with wp_enqueue_script() } if( is_search() ){ //load scripts with wp_enqueue_script() } } add_action( 'wp_enqueue_scripts', 'DA_script_enqueue'); ``` What happens on my wordpress website when my theme is activated is that no scripts get added to the `search.php` page but they **do** get added to the `404.php` page which is very odd! In fact, not even killing the page works with `die();` ``` if( is_search() ){ die('it works'); } ``` This leads me to think that the condition is never being met within the hook override for `wp_enqueue_scripts`. I'm not sure if this is a bug, or if my logic is just incorrect and I'm calling the wrong functions. What else can I try to make my logic work? Thanks **Edit:** Okay an update: I just tried the above code in another theme and it **DOES** do what it's supposed to! I guess the question I should now be asking is what can I do to ensure `is_search()` returns `true`? So far I've disabled **all** plugins and removed a `query_posts()` call from index.php, but still facing issues :( **Edit #2:** After 9 hours of debugging this (*sigh*) I've finally found what's causing the problem (but no solution to it - yet!) I created a test wordpress site and copied over my custom theme files. I deleted them one by one until I had the bare minimum files needed for a theme and that's when I found out what was causing the problem. It seems having a `header.php` file makes `is_search()` return `false`. Very strange! [![enter image description here](https://i.stack.imgur.com/mDisN.png)](https://i.stack.imgur.com/mDisN.png) [![enter image description here](https://i.stack.imgur.com/QCHIs.png)](https://i.stack.imgur.com/QCHIs.png) [![enter image description here](https://i.stack.imgur.com/JGOTd.png)](https://i.stack.imgur.com/JGOTd.png) As you can see from the screenshots above, as soon as I delete the header.php file everything is fine as `is_search()` returns true. What on earth could be causing this very strange issue? I have other themes with a header.php file in them and they work fine... I'm going to continue to play around with this but here are my source files just in case: `search.php`: ``` <?php get_header(); ?> search page <?php get_footer(); ?> ``` `functions.php`: ``` <?php // This function will load certain scripts on certain pages - saving on bandwidth and server resourses. function init_scripts() { if ( is_search() ) { die('Yes this is the search page loading from the init_scripts function'); } } add_action( 'wp_enqueue_scripts', 'init_scripts' ); ?> ``` `header.php`: ``` header ``` **Edit #3:** Here is the output of `$wp_query` also <http://pastebin.com/Z0DwDd20> **Edit #4:** Time for bed now so I guess I'll have another shot at this tomorrow. Here's the theme files just in case anyone is interested: <https://drive.google.com/folderview?id=0B1zYR-LjR-j9NFV2ZXg3V0NJblk&usp=sharing>
When using `wp_enqueue_script`, you probably passing `true` for `in_footer` parameter. If so, then check that your `search.php` is calling `get_footer()` function at the bottom.
218,064
<p>I'm trying to retrieve the posts of specific taxonomy categories. I have two taxonomy categories.</p> <ol> <li>Category One</li> <li>Category Two</li> </ol> <p>In these two have some different and same posts. So when i retrieve the data through <code>terms id</code> then query return some post two times, because these posts are link from above two categories. </p> <pre><code>$ourwork_cat_ids = array(3,4);// Category Term ID $args_OW = array(); foreach($ourwork_cat_ids as $wIds){ $args_OW[] = array( 'post_type' =&gt; 'portfolio', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'portfolio_category', 'field' =&gt; 'id', 'terms' =&gt; $wIds ) ) ); }//end foreach foreach($args_OW as $OW){ $portfolioQuery = new WP_Query($OW); if( $portfolioQuery-&gt;have_posts() ){ while( $portfolioQuery-&gt;have_posts() ){ $portfolioQuery-&gt;the_post(); echo the_title().'&lt;br /&gt;'; } } }// end foreach Out Put post one post two post two post three </code></pre> <p>So is there possible that i can skip double post ? I will appreciate if someone guide me for that. Thanks.</p>
[ { "answer_id": 218069, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 3, "selected": true, "text": "<p>You should never use <code>WP_Query</code> inside that kind of loop <em>(there might be few exceptions but not in your case)</em> because you can do most things with one query. This <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">codex link</a> has everything related to <code>WP_Query</code> with explanations and very simple examples.</p>\n\n<p>If taxonomies were a list of groceries and a trip to shop would be a query I doubt you would go to shop for each item separately. No, you will go once and buy them all.</p>\n\n<hr>\n\n<p>Take a look at these examples and let me know if you're having any problems.</p>\n\n<pre><code>//If you're using actual categories\n$args = array(\n 'post_type' =&gt; 'portfolio',\n 'cat' =&gt; '2, 4, 5, 77, 1031' // Category IDs\n);\n\n//If you're using single custom taxonomy\n$args = array(\n 'post_type' =&gt; 'portfolio',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'portfolio_tax',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array( 2, 4, 5, 77, 1031 ) // Term IDs\n )\n )\n);\n\n//If you're using multiple custom taxonomies\n$args = array(\n 'post_type' =&gt; 'portfolio',\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND', // Relation can be 'AND' or 'OR'\n array(\n 'taxonomy' =&gt; 'portfolio_tax',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array( 2, 4, 5, 77, 1031 ) // Term IDs\n ),\n array(\n 'taxonomy' =&gt; 'second_tax',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array( 1, 3, 6, 81, 1251 ) // Term IDs\n )\n )\n);\n\n\n//Query itself with output\n$query_results = new WP_Query( $args );\n\nwhile( $query_results-&gt;have_posts() ) { \n\n $query_results-&gt;the_post(); \n echo the_title() . '&lt;br /&gt;';\n}\n</code></pre>\n" }, { "answer_id": 218070, "author": "тнє Sufi", "author_id": 28744, "author_profile": "https://wordpress.stackexchange.com/users/28744", "pm_score": 0, "selected": false, "text": "<p>You are doing it wrong. You don't need to use a <code>foreach</code> loop here. <code>tax_query</code> parameter <code>terms</code> can be <code>int</code> or <code>string</code> or <code>array</code>.</p>\n\n<p>You can make your code more simple like this:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'portfolio',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'portfolio_category',\n 'field' =&gt; 'id',\n 'terms' =&gt; array(3,4);// Category Term ID\n )\n )\n );\n</code></pre>\n\n<p>To skip double post, we can use <code>posts_distinct</code> filter. We need to put it before our <code>WP_Query</code>.</p>\n\n<pre><code>function search_distinct() {\n return \"DISTINCT\";\n}\nadd_filter('posts_distinct', 'search_distinct');\n</code></pre>\n\n<p>Now, here is our <code>WP_Query</code>:</p>\n\n<pre><code>$portfolioQuery = new WP_Query($args);\nif( $portfolioQuery-&gt;have_posts() ){ \n while( $portfolioQuery-&gt;have_posts() ){ $portfolioQuery-&gt;the_post(); \n echo the_title().'&lt;br /&gt;';\n }\n}\nwp_reset_postdata();\n</code></pre>\n\n<p>We will need to remove the filter.</p>\n\n<pre><code>remove_filter('posts_distinct', 'search_distinct');\n</code></pre>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218064", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88873/" ]
I'm trying to retrieve the posts of specific taxonomy categories. I have two taxonomy categories. 1. Category One 2. Category Two In these two have some different and same posts. So when i retrieve the data through `terms id` then query return some post two times, because these posts are link from above two categories. ``` $ourwork_cat_ids = array(3,4);// Category Term ID $args_OW = array(); foreach($ourwork_cat_ids as $wIds){ $args_OW[] = array( 'post_type' => 'portfolio', 'tax_query' => array( array( 'taxonomy' => 'portfolio_category', 'field' => 'id', 'terms' => $wIds ) ) ); }//end foreach foreach($args_OW as $OW){ $portfolioQuery = new WP_Query($OW); if( $portfolioQuery->have_posts() ){ while( $portfolioQuery->have_posts() ){ $portfolioQuery->the_post(); echo the_title().'<br />'; } } }// end foreach Out Put post one post two post two post three ``` So is there possible that i can skip double post ? I will appreciate if someone guide me for that. Thanks.
You should never use `WP_Query` inside that kind of loop *(there might be few exceptions but not in your case)* because you can do most things with one query. This [codex link](https://codex.wordpress.org/Class_Reference/WP_Query) has everything related to `WP_Query` with explanations and very simple examples. If taxonomies were a list of groceries and a trip to shop would be a query I doubt you would go to shop for each item separately. No, you will go once and buy them all. --- Take a look at these examples and let me know if you're having any problems. ``` //If you're using actual categories $args = array( 'post_type' => 'portfolio', 'cat' => '2, 4, 5, 77, 1031' // Category IDs ); //If you're using single custom taxonomy $args = array( 'post_type' => 'portfolio', 'tax_query' => array( array( 'taxonomy' => 'portfolio_tax', 'field' => 'term_id', 'terms' => array( 2, 4, 5, 77, 1031 ) // Term IDs ) ) ); //If you're using multiple custom taxonomies $args = array( 'post_type' => 'portfolio', 'tax_query' => array( 'relation' => 'AND', // Relation can be 'AND' or 'OR' array( 'taxonomy' => 'portfolio_tax', 'field' => 'term_id', 'terms' => array( 2, 4, 5, 77, 1031 ) // Term IDs ), array( 'taxonomy' => 'second_tax', 'field' => 'term_id', 'terms' => array( 1, 3, 6, 81, 1251 ) // Term IDs ) ) ); //Query itself with output $query_results = new WP_Query( $args ); while( $query_results->have_posts() ) { $query_results->the_post(); echo the_title() . '<br />'; } ```
218,081
<p>I have the following code used to create a Custom Post Type. All works the save function is being triggered, and it seems to be saving. But I cannot get the saved data to output in the text field on Page Edit. I've stared at this and played around with it for days now. Looked at every tutorial online. I can't figure out what I am missing here. Any help would be great appreciated.</p> <p>I tried changing the <code>10,2</code> but doesn't help. I tried writing new code in the save function that you can see is commented out and this doesn't work either.</p> <pre><code>// Registers the new post type and taxonomy function course_listing_posttype() { register_post_type( 'courses', array( 'labels' =&gt; array( 'name' =&gt; __( 'Course Listings' ), 'singular_name' =&gt; __( 'Course Listing' ), 'add_new' =&gt; __( 'Add New Course' ), 'add_new_item' =&gt; __( 'Add New Course Listing' ), 'edit_item' =&gt; __( 'Edit Course Listing' ), 'new_item' =&gt; __( 'Add New Course Listing' ), 'view_item' =&gt; __( 'View Course Listing' ), 'search_items' =&gt; __( 'Search Course Listing' ), 'not_found' =&gt; __( 'No Course Listings found' ), 'not_found_in_trash' =&gt; __( 'No Course Listings found in trash' ) ), 'public' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'thumbnail' ), 'capability_type' =&gt; 'post', 'rewrite' =&gt; array("slug" =&gt; "courses"), // Permalinks format 'menu_position' =&gt; 5, 'taxonomies' =&gt; array( 'regional', 'national', 'global'), //figure out how to show this 'register_meta_box_cb' =&gt; 'add_course_listing' ) ); } add_action( 'init', 'course_listing_posttype' ); // Add Meta Boxes function add_course_listing() { //meta for application deadline add_meta_box('course_listing_meta', 'Course Listing Details', 'course_listing_meta', 'courses', 'normal', 'default'); } add_action("add_meta_boxes", "add_course_listing"); //application deadline meta function course_listing_meta($object) { global $post; wp_nonce_field(basename(__FILE__), "meta-box-nonce"); ?&gt; &lt;label for="application_deadline"&gt;&lt;strong&gt;Application Deadline:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Select the deadline for the course application&lt;/i&gt;&lt;br&gt; &lt;input type="text" id="application_deadline" name="application_deadline" value="&lt;?php echo get_post_meta($object-&gt;ID, 'application_deadline', true); ?&gt;" size="120"&gt; &lt;br&gt;&lt;br&gt; &lt;label for="workshop_date"&gt;&lt;strong&gt;On-Site Workshop Dates:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;input type="text" id="workshop_date" name="workshop_date" value="&lt;?php echo get_post_meta($object-&gt;ID, 'workshop_date', true); ?&gt;" size="120"&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;Contact Information:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;textarea type="text" id="contact_information" name="contact_information" value="&lt;?php echo get_post_meta($object-&gt;ID, 'contact_information', true); ?&gt;" rows="10" cols="120"&gt;&lt;/textarea&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;Directions:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;textarea type="text" id="directions" name="directions" value="&lt;?php echo get_post_meta($object-&gt;ID, 'directions', true); ?&gt;" rows="10" cols="120"&gt;&lt;/textarea&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;Hotels and Lodging:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;textarea type="text" id="lodging" name="lodging" value="&lt;?php echo get_post_meta($object-&gt;ID, 'lodging', true); ?&gt;" rows="10" cols="120"&gt;&lt;/textarea&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;Veterinarians Nearby:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;textarea type="text" id="veterinarians" name="veterinarians" value="&lt;?php echo get_post_meta($object-&gt;ID, 'veterinarians', true); ?&gt;" rows="10" cols="120"&gt;&lt;/textarea&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;State:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;input type="text" id="state" name="state" value="&lt;?php echo get_post_meta($object-&gt;ID, 'state', true); ?&gt;" size="120"&gt; &lt;br&gt;&lt;br&gt; &lt;label&gt;&lt;strong&gt;Zip Code:&lt;/strong&gt;&lt;/label&gt;&lt;br&gt; &lt;i&gt;Lorem ipsum dorem doleorum fibrouich forloer kolem lorey&lt;/i&gt;&lt;br&gt; &lt;input type="text" id="zip" name="zip" value="&lt;?php echo get_post_meta($object-&gt;ID, 'zip', true); ?&gt;" size="120"&gt; &lt;br&gt;&lt;br&gt; &lt;?php } // Save the Metabox Data function wpt_save_events_meta($post_id, $post) { /* if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))) return $post_id; if(!current_user_can("edit_post", $post_id)) return $post_id; */ //global $post; if(defined("DOING_AUTOSAVE") &amp;&amp; DOING_AUTOSAVE) return $post_id; /* $slug = "post"; if($slug != $post-&gt;post_type) return $post_id; */ $meta_box_text_value = ""; $meta_box_dropdown_value = ""; $meta_box_checkbox_value = ""; if ( isset( $_POST['contact_information'] ) &amp;&amp; $_POST['contact_information'] != '' ) { update_post_meta( $meta_box_text_value, 'courses', $_POST['contact_information'] ); } /* //save workshop date if(isset($_POST["contact_information"])) { $meta_box_text_value = $_POST["contact_information"]; } update_post_meta($post_id, "contact_information", $meta_box_text_value); */ } add_action('save_post', 'wpt_save_events_meta', 10, 2); // save the custom fields </code></pre>
[ { "answer_id": 218089, "author": "Tom Kentell", "author_id": 88813, "author_profile": "https://wordpress.stackexchange.com/users/88813", "pm_score": -1, "selected": true, "text": "<p>Based on the amount of times you missed the c from the word project... my first recommendation would be to check for typos in your code/file names :)</p>\n\n<p>Try updating permalinks in here: /wp-admin/options-permalink.php. Just hit update, and see if that solves the problem.</p>\n\n<p>Also, see if any errors are getting reported, open up wp-config and change <code>define('WP_DEBUG', false);</code> to <code>true</code>. Then try your single page again and see if any errors come back.</p>\n\n<p>You could also check your PHP error logs for any signs.</p>\n" }, { "answer_id": 218090, "author": "setterGetter", "author_id": 8756, "author_profile": "https://wordpress.stackexchange.com/users/8756", "pm_score": 0, "selected": false, "text": "<p>I can reiterate what Tom J Nowell said.... also install the WP <a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow noreferrer\">Debug Bar</a> plugin, specifically the WP_Query tab in this instance, which is super helpful at determining what template WordPress is using to render the current page:</p>\n\n<p>i.e. <a href=\"https://i.stack.imgur.com/VeOYQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VeOYQ.png\" alt=\"WP_Query tab of Debug Bar\"></a></p>\n" } ]
2016/02/18
[ "https://wordpress.stackexchange.com/questions/218081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
I have the following code used to create a Custom Post Type. All works the save function is being triggered, and it seems to be saving. But I cannot get the saved data to output in the text field on Page Edit. I've stared at this and played around with it for days now. Looked at every tutorial online. I can't figure out what I am missing here. Any help would be great appreciated. I tried changing the `10,2` but doesn't help. I tried writing new code in the save function that you can see is commented out and this doesn't work either. ``` // Registers the new post type and taxonomy function course_listing_posttype() { register_post_type( 'courses', array( 'labels' => array( 'name' => __( 'Course Listings' ), 'singular_name' => __( 'Course Listing' ), 'add_new' => __( 'Add New Course' ), 'add_new_item' => __( 'Add New Course Listing' ), 'edit_item' => __( 'Edit Course Listing' ), 'new_item' => __( 'Add New Course Listing' ), 'view_item' => __( 'View Course Listing' ), 'search_items' => __( 'Search Course Listing' ), 'not_found' => __( 'No Course Listings found' ), 'not_found_in_trash' => __( 'No Course Listings found in trash' ) ), 'public' => true, 'supports' => array( 'title', 'editor', 'thumbnail' ), 'capability_type' => 'post', 'rewrite' => array("slug" => "courses"), // Permalinks format 'menu_position' => 5, 'taxonomies' => array( 'regional', 'national', 'global'), //figure out how to show this 'register_meta_box_cb' => 'add_course_listing' ) ); } add_action( 'init', 'course_listing_posttype' ); // Add Meta Boxes function add_course_listing() { //meta for application deadline add_meta_box('course_listing_meta', 'Course Listing Details', 'course_listing_meta', 'courses', 'normal', 'default'); } add_action("add_meta_boxes", "add_course_listing"); //application deadline meta function course_listing_meta($object) { global $post; wp_nonce_field(basename(__FILE__), "meta-box-nonce"); ?> <label for="application_deadline"><strong>Application Deadline:</strong></label><br> <i>Select the deadline for the course application</i><br> <input type="text" id="application_deadline" name="application_deadline" value="<?php echo get_post_meta($object->ID, 'application_deadline', true); ?>" size="120"> <br><br> <label for="workshop_date"><strong>On-Site Workshop Dates:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <input type="text" id="workshop_date" name="workshop_date" value="<?php echo get_post_meta($object->ID, 'workshop_date', true); ?>" size="120"> <br><br> <label><strong>Contact Information:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <textarea type="text" id="contact_information" name="contact_information" value="<?php echo get_post_meta($object->ID, 'contact_information', true); ?>" rows="10" cols="120"></textarea> <br><br> <label><strong>Directions:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <textarea type="text" id="directions" name="directions" value="<?php echo get_post_meta($object->ID, 'directions', true); ?>" rows="10" cols="120"></textarea> <br><br> <label><strong>Hotels and Lodging:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <textarea type="text" id="lodging" name="lodging" value="<?php echo get_post_meta($object->ID, 'lodging', true); ?>" rows="10" cols="120"></textarea> <br><br> <label><strong>Veterinarians Nearby:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <textarea type="text" id="veterinarians" name="veterinarians" value="<?php echo get_post_meta($object->ID, 'veterinarians', true); ?>" rows="10" cols="120"></textarea> <br><br> <label><strong>State:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <input type="text" id="state" name="state" value="<?php echo get_post_meta($object->ID, 'state', true); ?>" size="120"> <br><br> <label><strong>Zip Code:</strong></label><br> <i>Lorem ipsum dorem doleorum fibrouich forloer kolem lorey</i><br> <input type="text" id="zip" name="zip" value="<?php echo get_post_meta($object->ID, 'zip', true); ?>" size="120"> <br><br> <?php } // Save the Metabox Data function wpt_save_events_meta($post_id, $post) { /* if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))) return $post_id; if(!current_user_can("edit_post", $post_id)) return $post_id; */ //global $post; if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) return $post_id; /* $slug = "post"; if($slug != $post->post_type) return $post_id; */ $meta_box_text_value = ""; $meta_box_dropdown_value = ""; $meta_box_checkbox_value = ""; if ( isset( $_POST['contact_information'] ) && $_POST['contact_information'] != '' ) { update_post_meta( $meta_box_text_value, 'courses', $_POST['contact_information'] ); } /* //save workshop date if(isset($_POST["contact_information"])) { $meta_box_text_value = $_POST["contact_information"]; } update_post_meta($post_id, "contact_information", $meta_box_text_value); */ } add_action('save_post', 'wpt_save_events_meta', 10, 2); // save the custom fields ```
Based on the amount of times you missed the c from the word project... my first recommendation would be to check for typos in your code/file names :) Try updating permalinks in here: /wp-admin/options-permalink.php. Just hit update, and see if that solves the problem. Also, see if any errors are getting reported, open up wp-config and change `define('WP_DEBUG', false);` to `true`. Then try your single page again and see if any errors come back. You could also check your PHP error logs for any signs.
218,137
<p>I am retrieving taxonomy terms. The code is working.<br> Foreach creates three options for the select tag. There are three terms. But, when I wanted to echo "selected" for each options, after selecting one. it returns odd result. What is the problem? Here is the code. </p> <pre><code>$terms = get_terms( 'department' ); if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){ echo '&lt;select class="widefat" name="departments"&gt;'; foreach ( $terms as $term ) { echo '&lt;option value="'. $term-&gt;name .'"'.($_POST['departments'] == $term-&gt;name) ? ' selected="selected" ' : ''.'&gt;'. $term-&gt;name . '&lt;/option&gt;'; } echo '&lt;/select&gt;'; } </code></pre> <p>Returns this: </p> <pre><code>&lt;select class="widefat" name="departments"&gt; selected="selected" selected="selected" selected="selected" &lt;/select&gt; </code></pre> <p>Custom post name: employee Taxonomy name: department There are three terms available: Web Designer, Web Developer, Graphics Designer</p> <p>I am getting the taxonomy terms if I use this code.</p> <pre><code>$terms = get_terms( 'department' ); if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){ echo '&lt;select class="widefat" name="departments"&gt;'; foreach ( $terms as $term ) { $value = $term-&gt;name; for ($i=0; $i &lt; count($term); $i++) { echo '&lt;option value="' . $value .'"'.'&gt;' . $value . '&lt;/option&gt;'; } } echo '&lt;/select&gt;'; </code></pre> <p>Returns: </p> <pre><code>&lt;select class="widefat" name="departments"&gt; &lt;option value="Graphic Designer"&gt;Graphic Designer&lt;/option&gt; &lt;option value="Web Designer"&gt;Web Designer&lt;/option&gt; &lt;option value="Web Devloper"&gt;Web Devloper&lt;/option&gt; &lt;/select&gt; </code></pre> <p>But if I want to implement selected into the selected option then it is collapsing. </p> <p>I want to add if you chose Graphic Designer then the option would look like </p> <pre><code>&lt;option value="Graphic Designer" selected="selected"&gt;Graphic Designer&lt;/option&gt; </code></pre> <p>But this is not happening. </p>
[ { "answer_id": 218140, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 4, "selected": true, "text": "<p>WordPress doesn't track if a user is online. It can only know if the current is online, which is always yes ( else there would be no request ). If you want to know if a different user that isn't the current user is online, that information doesn't exist, and you'll need to implement it yourself.</p>\n\n<p><code>is_user_logged_in</code> checks if the current user is authenticated aka logged in, it's not a test if a user is online</p>\n\n<p>In order to do this you're also going to have to make compromises, and realtime online or not status tracking is not something you can do solely within WordPress.</p>\n\n<p>Your options include:</p>\n\n<ul>\n<li>Updating a timestamp every time you access a page in user meta, then using that timestamp as a test ( aka if a users timestamp is within the last 5 minutes consider them online ), have an AJAX call ping your site to refresh the timer. Note that if the user closes their browser just after loading a page, they'll still show online for 5 minutes, and there's a performance cost to doing this, it will not scale with traffic</li>\n<li>Having a flag that indicates a user is online, and setting it to true when a user hits any page. Have a cron job that sets all flags to false at regular intervals. This will be cheaper to query on, but it's more expensive to run. You can make it less expensive by increasing the time delay of cron jobs, thus reducing accuracy. This still makes logged in users more expensive as every page load includes a database write. It will not scale with traffic.</li>\n<li>Use an external service and set up a Heroku/Simperium/Node server that's independent of WordPress and tracks online state. How you would do this is beyond the scope of this site as you're moving into other areas of expertise outside of WordPress. This is the most complex and expensive option, but it does mean your WordPress install is not adversely impacted. It does mean that the online presence data is unavailable in WordPress itself, you will not be able to query unless you build mechanisms to do so which will be expensive. The code that makes the icon green will need to be in javascript on the browser. The worst case scenario here however is that your presence logic fails as your external server buckles under load, but your WordPress site no longer has DB writes on every page load, and your site scales better with traffic than the other options</li>\n</ul>\n\n<p>Overall, what you're asking for is non-trivial, and while sounding simple, will either be very performance heavy, inaccurate, or require an additional server and development time. There is a trade off.</p>\n\n<p>Also, any solution you devise that runs in PHP will necessarily mean that you can no longer do full page caches unless the online offline functionality is powered by javascript. Otherwise, if you show someone as online and your pages are cached for 24 hours, they'll still be online for the following 24 hours. If you use either of the first 2 options I presented, you'll also be unable to use caching for logged in users, and tools such as batcache or Varnish will break your system if applied to those users unless an uncached AJAX based system is used to indicate that someone is online</p>\n\n<p>Will this change in the future? No, WordPress doesn't handle this kind of functionality or store this kind of data. WordPress does track sessions in user meta, but this is not the kind of data you are looking for. This may indicate how many devices a user has logged in on, but it's by no means reliable, and it can't be used to give an online or offline indicator</p>\n" }, { "answer_id": 353100, "author": "Samuel E. Cerezo", "author_id": 97635, "author_profile": "https://wordpress.stackexchange.com/users/97635", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question, but here is what I've developed using WordPress token sessions.</p>\n\n<p>First of all, I've developed a function that update timestamp of current session. If I access to a web page where I'm connected, login timestamp and expiration timestamp are updated (login to current timestamp)</p>\n\n<pre><code>add_action('init', function() {\n\n $sessions = get_user_meta(get_current_user_id(), 'session_tokens', true);\n\n $session = $sessions[hash('sha256', wp_get_session_token())];\n\n $duration = $session['expiration'] - $session['login'];\n\n $sessions[hash('sha256', wp_get_session_token())]['login'] = current_time('U');\n\n $sessions[hash('sha256', wp_get_session_token())]['expiration'] = current_time('U') + $duration;\n\n update_user_meta(get_current_user_id(), 'session_tokens', $sessions);\n\n});\n</code></pre>\n\n<p>After this, I calculate time passed after user login in actives sessions.</p>\n\n<p>If this time between current and login is less than 5 minutes, I think user is \"online\". If this time is between 5 and 20 minutes, I think user is \"away\".</p>\n\n<pre><code>function is_user_online($user = null) {\n\n if (is_null($user)) {\n $user = get_current_user_id();\n }\n\n $session_time = false;\n\n $sessions = get_user_meta($user, 'session_tokens', true);\n\n foreach ($sessions as $session) {\n\n $time = current_time('U') - $session['login'];\n\n if ($time == false || $time &lt; $session_time) {\n $session_time = $time;\n }\n\n }\n\n if (is_numeric($session_time) &amp;&amp; $session_time &lt;= 1200 &amp;&amp; $session_time &gt; 300) {\n $session_time = 'away';\n } else if (is_numeric($session_time) &amp;&amp; $session_time &lt;= 300) {\n $session_time = 'online';\n } else {\n $session_time = false;\n }\n\n return $session_time;\n\n}\n</code></pre>\n\n<p>I've also modified session life. 1 hour for normal and 7 days for \"remember me\".</p>\n\n<pre><code>add_filter('auth_cookie_expiration', function($seconds, $user_id, $remember){\n\n if ($remember) {\n $expiration = 7*24*60*60;\n } else {\n $expiration = 60*60;\n }\n\n if (PHP_INT_MAX - time() &lt; $expiration) {\n $expiration = PHP_INT_MAX - time() - 5;\n }\n\n return $expiration;\n\n}, 99, 3);\n</code></pre>\n\n<p>With this solution you can't know if user is online at real time but I think is a great solution :)</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218137", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88854/" ]
I am retrieving taxonomy terms. The code is working. Foreach creates three options for the select tag. There are three terms. But, when I wanted to echo "selected" for each options, after selecting one. it returns odd result. What is the problem? Here is the code. ``` $terms = get_terms( 'department' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<select class="widefat" name="departments">'; foreach ( $terms as $term ) { echo '<option value="'. $term->name .'"'.($_POST['departments'] == $term->name) ? ' selected="selected" ' : ''.'>'. $term->name . '</option>'; } echo '</select>'; } ``` Returns this: ``` <select class="widefat" name="departments"> selected="selected" selected="selected" selected="selected" </select> ``` Custom post name: employee Taxonomy name: department There are three terms available: Web Designer, Web Developer, Graphics Designer I am getting the taxonomy terms if I use this code. ``` $terms = get_terms( 'department' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<select class="widefat" name="departments">'; foreach ( $terms as $term ) { $value = $term->name; for ($i=0; $i < count($term); $i++) { echo '<option value="' . $value .'"'.'>' . $value . '</option>'; } } echo '</select>'; ``` Returns: ``` <select class="widefat" name="departments"> <option value="Graphic Designer">Graphic Designer</option> <option value="Web Designer">Web Designer</option> <option value="Web Devloper">Web Devloper</option> </select> ``` But if I want to implement selected into the selected option then it is collapsing. I want to add if you chose Graphic Designer then the option would look like ``` <option value="Graphic Designer" selected="selected">Graphic Designer</option> ``` But this is not happening.
WordPress doesn't track if a user is online. It can only know if the current is online, which is always yes ( else there would be no request ). If you want to know if a different user that isn't the current user is online, that information doesn't exist, and you'll need to implement it yourself. `is_user_logged_in` checks if the current user is authenticated aka logged in, it's not a test if a user is online In order to do this you're also going to have to make compromises, and realtime online or not status tracking is not something you can do solely within WordPress. Your options include: * Updating a timestamp every time you access a page in user meta, then using that timestamp as a test ( aka if a users timestamp is within the last 5 minutes consider them online ), have an AJAX call ping your site to refresh the timer. Note that if the user closes their browser just after loading a page, they'll still show online for 5 minutes, and there's a performance cost to doing this, it will not scale with traffic * Having a flag that indicates a user is online, and setting it to true when a user hits any page. Have a cron job that sets all flags to false at regular intervals. This will be cheaper to query on, but it's more expensive to run. You can make it less expensive by increasing the time delay of cron jobs, thus reducing accuracy. This still makes logged in users more expensive as every page load includes a database write. It will not scale with traffic. * Use an external service and set up a Heroku/Simperium/Node server that's independent of WordPress and tracks online state. How you would do this is beyond the scope of this site as you're moving into other areas of expertise outside of WordPress. This is the most complex and expensive option, but it does mean your WordPress install is not adversely impacted. It does mean that the online presence data is unavailable in WordPress itself, you will not be able to query unless you build mechanisms to do so which will be expensive. The code that makes the icon green will need to be in javascript on the browser. The worst case scenario here however is that your presence logic fails as your external server buckles under load, but your WordPress site no longer has DB writes on every page load, and your site scales better with traffic than the other options Overall, what you're asking for is non-trivial, and while sounding simple, will either be very performance heavy, inaccurate, or require an additional server and development time. There is a trade off. Also, any solution you devise that runs in PHP will necessarily mean that you can no longer do full page caches unless the online offline functionality is powered by javascript. Otherwise, if you show someone as online and your pages are cached for 24 hours, they'll still be online for the following 24 hours. If you use either of the first 2 options I presented, you'll also be unable to use caching for logged in users, and tools such as batcache or Varnish will break your system if applied to those users unless an uncached AJAX based system is used to indicate that someone is online Will this change in the future? No, WordPress doesn't handle this kind of functionality or store this kind of data. WordPress does track sessions in user meta, but this is not the kind of data you are looking for. This may indicate how many devices a user has logged in on, but it's by no means reliable, and it can't be used to give an online or offline indicator
218,149
<p>I have a self-hosted WordPress blog, and for weeks someone has been trying log in as admin. I'm looking for a way to stop it. Since I started blocking the originating IP address, the attempts started coming from many IPs but in batches of three or four tries at 10 minute intervals - so it's obviously one person and I guess they're using a botnet.</p> <p>I use several security steps and keep all plugins up to date. Wordpress is itself automatically kept up to date nowadays, of course. </p> <p>These are not all my security actions, but I have ... - "Limit Login Attempts" plugin, but the switching around of the IP address by the hacker meant that this didn't have much effect. </p> <ul> <li><p>I password-protect the wp-admin directory with htaccess and htpasswd. Since this had been in place for a long time, I just changed that directory access user name and password, but that made no difference, he still gets to the login dialog.</p></li> <li><p>Of course, my WP admin account is not called 'admin' and I deleted the original admin a/c. </p></li> <li><p>For a while, I even tried renaming wp-login.php, and moved wp-admin out of the blog's directory. It's quick and easy for me to reverse this when I want to blog or make changes. But Limit Login Attempts still reported attempts - 21 since I renamed/moved these. How is that possible? I've now returned these to the normal place.</p></li> <li><p>I added this to .htaccess in the blog's main directory (where nnn etc is my fixed IP and example.com substitutes for the real domain):</p> <pre><code>RewriteCond %{REMOTE_ADDR} !^nnn\.nnn\.nnn\.nnn$ RewriteRule ^wp-(login|register)\.php http://www.example.com/blog/ [R,L] </code></pre></li> <li><p>and I added a variation of that to .htaccess in the blog's wp-admin directory:</p> <pre><code>RewriteCond %{REMOTE_ADDR} !^nnn\.nnn\.nnn\.nnn$ RewriteRule ^wp-admin.*?$ http://www.example.com/blog/ [R,L] </code></pre></li> </ul> <p>When I try to log in from a different IP address via wp-login.php, the first htaccess correctly shunts me straight to the blog's front page. Equally, when I try to access wp-admin from that different IP address, the second htaccess takes me straight to the blog's front page as it should. Only when I try to log in from my fixed IP do I see the request for the directory access passwd, and then the WP login page. </p> <p>And yet the hacker is able to reach the login dialog. He's not managed to actually log in yet, I run WordPress File Monitor and see no unexpected file changes, and he hasn't discovered the real admin username - but I can't be complacent.</p> <p>So, can anyone help me understand :</p> <ol> <li><p>How is it that the hacker can still reach the login page? Even when wp-login.php and wp-admin were temporarily renamed / moved? I cleared the cache and turned supercache off days ago (and renamed wp-super-cache) in case pages in cache were allowing them to reach it.</p></li> <li><p>What can I do to stop this? I have full access to the parent site (shared hosting) and MySQL database.</p></li> </ol>
[ { "answer_id": 218152, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p><a href=\"https://m.youtube.com/watch?v=YRzg8XrvT3g\" rel=\"nofollow\">You can run, but you can't hide - Taylor Wagner</a></p>\n</blockquote>\n\n<p>You cannot stop anyone from trying to hack your site. Hackers use many software/bots/techniques in order to find your site, and to hack it (<em>exactly how this works is frankly way above me</em>), and you cannot \"hide\" from this. These software/bots \"guesses\" URL's on your site, so it is not that they know where your login page is right-of-the-back. It is basically a guessing a game which continues till the guess is correct. </p>\n\n<p>Whether you like it not, knowingly or unknowingly, you are bombarded by many hacking attempts per day, and you cannot stop it. You can only hope that your current measures (<em>like using good security plugins, strong passwords, keeping PHP and WordPress up-to-date, writing \"safe\" code and never trusting any type of user inputs, you yourself include</em>) are good enough against the attack. You'll need to remember, no code on no platform or language is ever safe against hacking, every piece of code can be hacked, you can only make it as hard as possible for hackers to gain access to your site through your code or login pages. </p>\n\n<p>Stop worrying about trying to hide from hackers, what you have done so far is about as much as you can do to prevent from being \"found\". Rather spend your time in making it as hard as you can for someone or something to actually gain access to your site. </p>\n" }, { "answer_id": 218158, "author": "Neeraj Kumar Jha", "author_id": 85373, "author_profile": "https://wordpress.stackexchange.com/users/85373", "pm_score": 3, "selected": true, "text": "<p>One thing you can do is if you don't have membership website then make it such that wp-admin/wp-login can be open through your IP address and block all other IP address. But make sure that you don't have membership website (No other subscribers/publishers that can login. Only you are the person to log in.)</p>\n\n<p>The other thing you can do is use \"CDN\" like cloudflare which will filter the IPs before reaching to your server. This make your site fast as well.</p>\n\n<p>Hope this helps.</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89014/" ]
I have a self-hosted WordPress blog, and for weeks someone has been trying log in as admin. I'm looking for a way to stop it. Since I started blocking the originating IP address, the attempts started coming from many IPs but in batches of three or four tries at 10 minute intervals - so it's obviously one person and I guess they're using a botnet. I use several security steps and keep all plugins up to date. Wordpress is itself automatically kept up to date nowadays, of course. These are not all my security actions, but I have ... - "Limit Login Attempts" plugin, but the switching around of the IP address by the hacker meant that this didn't have much effect. * I password-protect the wp-admin directory with htaccess and htpasswd. Since this had been in place for a long time, I just changed that directory access user name and password, but that made no difference, he still gets to the login dialog. * Of course, my WP admin account is not called 'admin' and I deleted the original admin a/c. * For a while, I even tried renaming wp-login.php, and moved wp-admin out of the blog's directory. It's quick and easy for me to reverse this when I want to blog or make changes. But Limit Login Attempts still reported attempts - 21 since I renamed/moved these. How is that possible? I've now returned these to the normal place. * I added this to .htaccess in the blog's main directory (where nnn etc is my fixed IP and example.com substitutes for the real domain): ``` RewriteCond %{REMOTE_ADDR} !^nnn\.nnn\.nnn\.nnn$ RewriteRule ^wp-(login|register)\.php http://www.example.com/blog/ [R,L] ``` * and I added a variation of that to .htaccess in the blog's wp-admin directory: ``` RewriteCond %{REMOTE_ADDR} !^nnn\.nnn\.nnn\.nnn$ RewriteRule ^wp-admin.*?$ http://www.example.com/blog/ [R,L] ``` When I try to log in from a different IP address via wp-login.php, the first htaccess correctly shunts me straight to the blog's front page. Equally, when I try to access wp-admin from that different IP address, the second htaccess takes me straight to the blog's front page as it should. Only when I try to log in from my fixed IP do I see the request for the directory access passwd, and then the WP login page. And yet the hacker is able to reach the login dialog. He's not managed to actually log in yet, I run WordPress File Monitor and see no unexpected file changes, and he hasn't discovered the real admin username - but I can't be complacent. So, can anyone help me understand : 1. How is it that the hacker can still reach the login page? Even when wp-login.php and wp-admin were temporarily renamed / moved? I cleared the cache and turned supercache off days ago (and renamed wp-super-cache) in case pages in cache were allowing them to reach it. 2. What can I do to stop this? I have full access to the parent site (shared hosting) and MySQL database.
One thing you can do is if you don't have membership website then make it such that wp-admin/wp-login can be open through your IP address and block all other IP address. But make sure that you don't have membership website (No other subscribers/publishers that can login. Only you are the person to log in.) The other thing you can do is use "CDN" like cloudflare which will filter the IPs before reaching to your server. This make your site fast as well. Hope this helps.
218,169
<p>I've been trying to change my <code>WP_Query</code> to <code>get_posts</code> methods. But I am not really sure how to check if <code>get_posts</code> is null or have a value.</p> <p>How can i transform this <code>WP_Query</code> checker to appropriate <code>get_posts</code> checker?</p> <p>This is my <code>WP_Query</code> checker:</p> <pre><code>$custom_query = new WP_Query($args); if ( $custom_query-&gt;have_posts() ) { ... } </code></pre>
[ { "answer_id": 218170, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>Using a simple <code>empty</code> function.</p>\n\n<pre><code>$wpse_posts = get_posts( $args );\n\nif ( ! empty( $wpse_posts ) ) {\n //Do the loop\n\n} else {\n //No post found\n}\n</code></pre>\n" }, { "answer_id": 218172, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>From previous questions, I know you would want optimize your queries. There is no need to change <code>WP_Query</code> into <code>get_posts</code> for perfomance. As I stated in a another post, yes, <code>get_posts()</code> is faster than <code>WP_Query</code> because <code>get_posts()</code> legally breaks pagination, but what <code>get_posts()</code> do can be done with <code>WP_Query</code>.</p>\n\n<p>To really understand what <code>get_posts()</code> does, lets look at the <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow\">source code</a>. In essence, <code>get_posts()</code> does the following: (<em>lets forget about the useless parameters in <code>get_posts()</code></em>)</p>\n\n<pre><code>$args = [\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; 1\n // Any other user passed arguments\n];\n$r = new WP_Query( $args );\nreturn $r-&gt;posts;\n</code></pre>\n\n<h2>WHAT DOES IT ALL MEAN</h2>\n\n<ul>\n<li><p><code>get_posts()</code> just returns the <code>$posts</code> property from the query object. <code>$posts</code> holds an array of posts</p></li>\n<li><p><code>'no_found_rows' =&gt; true</code> is what legally breaks pagination, and is one of the reasons why you should not use <code>get_posts</code> for paginated queries. This is also why <code>get_posts()</code> is faster than a normal <code>WP_Query</code> as by default <code>no_found_rows</code> is set to false.</p></li>\n</ul>\n\n<p>Because <code>get_posts()</code> only returns an array of posts, and not the query object, you must use a normal <code>foreach</code> loop to loop through the posts. Another thing to note, because the query object is not returned, the template tags like <code>the_content()</code> is not available because the <code>$post</code> global is not set to the current post. In a normal loop, <code>the_post()</code> sets up postdata which makes template tags available. For <code>get_posts()</code>, we need to do this manually by using <code>setup_postdata( $post )</code> in our foreach loop</p>\n\n<p>To properly loop through <code>get_posts()</code>, we need to do something like this</p>\n\n<pre><code>$posts_array = get_posts( $args );\nif ( $posts_array ) { // Make sure we have posts before we attempt to loop through them\n foreach ( $posts_array as $post ) {\n setup_postdata( $post );\n\n // Now we can use template tags\n the_title();\n the_content();\n }\n wp_reset_postdata(); // VERY VERY IMPORTANT\n}\n</code></pre>\n\n<p>I would not go through all of this to change existing <code>WP_Query</code> instances in order to optimize them. Simply add <code>'no_found_rows' =&gt; true</code> to your <code>WP_Query</code> arguments, and viola, you are doing exatly what <code>get_posts()</code> is doing</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88947/" ]
I've been trying to change my `WP_Query` to `get_posts` methods. But I am not really sure how to check if `get_posts` is null or have a value. How can i transform this `WP_Query` checker to appropriate `get_posts` checker? This is my `WP_Query` checker: ``` $custom_query = new WP_Query($args); if ( $custom_query->have_posts() ) { ... } ```
From previous questions, I know you would want optimize your queries. There is no need to change `WP_Query` into `get_posts` for perfomance. As I stated in a another post, yes, `get_posts()` is faster than `WP_Query` because `get_posts()` legally breaks pagination, but what `get_posts()` do can be done with `WP_Query`. To really understand what `get_posts()` does, lets look at the [source code](https://developer.wordpress.org/reference/functions/get_posts/). In essence, `get_posts()` does the following: (*lets forget about the useless parameters in `get_posts()`*) ``` $args = [ 'no_found_rows' => true, 'ignore_sticky_posts' => 1 // Any other user passed arguments ]; $r = new WP_Query( $args ); return $r->posts; ``` WHAT DOES IT ALL MEAN --------------------- * `get_posts()` just returns the `$posts` property from the query object. `$posts` holds an array of posts * `'no_found_rows' => true` is what legally breaks pagination, and is one of the reasons why you should not use `get_posts` for paginated queries. This is also why `get_posts()` is faster than a normal `WP_Query` as by default `no_found_rows` is set to false. Because `get_posts()` only returns an array of posts, and not the query object, you must use a normal `foreach` loop to loop through the posts. Another thing to note, because the query object is not returned, the template tags like `the_content()` is not available because the `$post` global is not set to the current post. In a normal loop, `the_post()` sets up postdata which makes template tags available. For `get_posts()`, we need to do this manually by using `setup_postdata( $post )` in our foreach loop To properly loop through `get_posts()`, we need to do something like this ``` $posts_array = get_posts( $args ); if ( $posts_array ) { // Make sure we have posts before we attempt to loop through them foreach ( $posts_array as $post ) { setup_postdata( $post ); // Now we can use template tags the_title(); the_content(); } wp_reset_postdata(); // VERY VERY IMPORTANT } ``` I would not go through all of this to change existing `WP_Query` instances in order to optimize them. Simply add `'no_found_rows' => true` to your `WP_Query` arguments, and viola, you are doing exatly what `get_posts()` is doing
218,174
<p>I have create a form and i want to store the form data in <code>wp_options</code> table so for that i have created this query</p> <pre><code>$insertquery = $wpdb-&gt;query("INSERT INTO `wp_options`(`option_name`,`option_value`) VALUES ('smsfactory123','asdasdf')"); </code></pre> <p>Now when i am importing the static data then it doesn't create any problem when i pass the variable which is containing array it shows me error.</p> <pre><code>$apidetail = array( 'userid' =&gt; $uid, 'userpassword' =&gt; $upwd, 'senderid' =&gt; $sid, 'ono' =&gt; $ono, 'message' =&gt; $message, ); </code></pre> <p>This is how i am getting value of array in variable</p>
[ { "answer_id": 218176, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": 1, "selected": false, "text": "<p>You can save array with update_option function like below code.</p>\n\n<pre><code>update_option('option_name', $arr_store_me); \n</code></pre>\n" }, { "answer_id": 218180, "author": "Maximus Light", "author_id": 89031, "author_profile": "https://wordpress.stackexchange.com/users/89031", "pm_score": -1, "selected": true, "text": "<p>You could also use <code>json_encode()</code> function instead of <code>serialize</code>.</p>\n\n<pre><code>$var = json_encode($array);\nupdate_option('option_name', $var); \n</code></pre>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218174", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88914/" ]
I have create a form and i want to store the form data in `wp_options` table so for that i have created this query ``` $insertquery = $wpdb->query("INSERT INTO `wp_options`(`option_name`,`option_value`) VALUES ('smsfactory123','asdasdf')"); ``` Now when i am importing the static data then it doesn't create any problem when i pass the variable which is containing array it shows me error. ``` $apidetail = array( 'userid' => $uid, 'userpassword' => $upwd, 'senderid' => $sid, 'ono' => $ono, 'message' => $message, ); ``` This is how i am getting value of array in variable
You could also use `json_encode()` function instead of `serialize`. ``` $var = json_encode($array); update_option('option_name', $var); ```
218,178
<p>I've been thinking of using <code>WP_Query</code>'s pagination to make a custom lazy loading. is there a way to utilize the <code>WP_Query</code>'s pagination for a lazy load?</p> <p>Say for example, I have to load 24 posts in the first load, and when the scroll reach bottom it will lazy load the next 24 post.</p> <p>Is this possible?</p>
[ { "answer_id": 218209, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 3, "selected": true, "text": "<p>Take a look at this rough example. This requires a little bit of adaptation but as a whole, it does what you want - it loads X amount of next posts if user clicks a button which should be below already loaded posts.</p>\n\n<p>If you want to automatically load more posts if user scrolls down, just replace click event with some other code that keeps an eye on scrolling. There's plenty of examples online.</p>\n\n<ul>\n<li>Keep an eye on <code>jQuery('some-html-element')-s</code>, make sure to rename these element names or change your own <code>HTML</code> to make them fit</li>\n<li>Total posts count: you can make it visible if you want users to see total posts count or use <code>CSS</code> <code>opacity</code> to hide it. It still needs to be somewhere in order to have a place to store the value</li>\n</ul>\n\n<hr>\n\n<p><strong>This goes to your main .js:</strong> </p>\n\n<p>This function handles all the DOM manipulation and ajax. It can be called however you wish.</p>\n\n<pre><code>//ajaxLock is just a flag to prevent double clicks and spamming\nvar ajaxLock = false;\n\nif( ! ajaxLock ) {\n\n function ajax_next_posts() {\n\n ajaxLock = true;\n\n //How many posts there's total\n var totalPosts = parseInt( jQuery( '#total-posts-count' ).text() );\n //How many have been loaded\n var postOffset = jQuery( '.single-post' ).length;\n //How many do you want to load in single patch\n var postsPerPage = 24;\n\n //Hide button if all posts are loaded\n if( totalPosts &lt; postOffset + ( 1 * postsPerPage ) ) {\n\n jQuery( '#more-posts-button' ).fadeOut();\n }\n\n //Change that to your right site url unless you've already set global ajaxURL\n var ajaxURL = 'http://www.my-site.com/wp-admin/admin-ajax.php';\n\n //Parameters you want to pass to query\n var ajaxData = '&amp;post_offset=' + postOffset + '&amp;action=ajax_next_posts';\n\n //Ajax call itself\n jQuery.ajax({\n\n type: 'get',\n url: ajaxURL,\n data: ajaxData,\n dataType: 'json',\n\n //Ajax call is successful\n success: function ( response ) {\n\n //Add new posts\n jQuery( '#posts-container' ).append( response[0] );\n //Update the count of total posts\n jQuery( '#total-posts-count' ).text( response[1] );\n\n ajaxLock = false;\n },\n\n //Ajax call is not successful, still remove lock in order to try again\n error: function () {\n\n ajaxLock = false;\n }\n });\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>This goes to your main .js:</strong> </p>\n\n<p>This is an example how to call function above with button, this is better in my opinion, user can choose if he/she wants to see more..</p>\n\n<pre><code>//Load more posts button\njQuery( '#more-posts-button' ).click( function( e ) {\n\n e.preventDefault(); \n\n ajax_next_posts(); \n\n});\n</code></pre>\n\n<hr>\n\n<p><strong>This goes to functions.php or create a mu-plugin:</strong> </p>\n\n<p>This is the function that \"runs\" in your server, ajax calls this, it does it's thing and sends results back.</p>\n\n<pre><code>//More posts - first for logged in users, other for not logged in\nadd_action('wp_ajax_ajax_next_posts', 'ajax_next_posts');\nadd_action('wp_ajax_nopriv_ajax_next_posts', 'ajax_next_posts');\n\nfunction ajax_next_posts() {\n\n //Build query\n $args = array(\n //All your query arguments\n );\n\n //Get offset\n if( ! empty( $_GET['post_offset'] ) ) {\n\n $offset = $_GET['post_offset'];\n $args['offset'] = $offset;\n\n //Also have to set posts_per_page, otherwise offset is ignored\n $args['posts_per_page'] = 24;\n }\n\n $count_results = '0';\n\n $query_results = new WP_Query( $args );\n\n //Results found\n if ( $query_results-&gt;have_posts() ) {\n\n $count_results = $query_results-&gt;found_posts;\n\n //Start \"saving\" results' HTML\n $results_html = '';\n ob_start();\n\n while ( $query_results-&gt;have_posts() ) { \n\n $query_results-&gt;the_post();\n\n //Your single post HTML here\n } \n\n //\"Save\" results' HTML as variable\n $results_html = ob_get_clean(); \n }\n\n //Build ajax response\n $response = array();\n\n //1. value is HTML of new posts and 2. is total count of posts\n array_push ( $response, $results_html, $count_results );\n echo json_encode( $response );\n\n //Always use die() in the end of ajax functions\n die(); \n}\n</code></pre>\n" }, { "answer_id": 218214, "author": "MrFox", "author_id": 69240, "author_profile": "https://wordpress.stackexchange.com/users/69240", "pm_score": 0, "selected": false, "text": "<p>I've been using infinite scroll for this.</p>\n\n<p>Here is what I have used in script.js</p>\n\n<pre><code>$(function(){\n var $container = $('#ms-container');\n $container.imagesLoaded(function(){\n $container.masonry({\n itemSelector : '.ms-item',\n\n\n });\n });\n//var templateUrl = object_name.templateUrl;\n//var src = \"'\"+templateUrl+\"/images/loader.gif' \";\n\n$container.infinitescroll({\n navSelector : '#navigation', // selector for the paged navigation \n nextSelector : '#navigation a', // selector for the NEXT link (to page 2)\n itemSelector : '.ms-item', \n\n\n loading: {\n finishedMsg: $('&lt;div class=\"finmsg\"&gt;No More Posts.&lt;/div&gt;'),\n msgText: '',\n img: '',\n speed: 0\n }\n },\n // trigger Masonry as a callback\n function( newElements ) {\n // hide new items while they are loading\n var $newElems = $( newElements ).css({ opacity: 0 });\n // ensure that images load before adding to masonry layout\n $newElems.imagesLoaded(function(){\n // show elems now they're ready\n $newElems.animate({ opacity: 1 });\n $container.masonry( 'appended', $newElems, true ); \n });\n }\n );\n});\n</code></pre>\n\n<p>I am using masonry, so you might need to tweak this. \nThe overall container on the archive page is </p>\n\n<pre><code>&lt;div id=\"ms-container\"&gt;\n</code></pre>\n\n<p>Hence:</p>\n\n<pre><code>var $container = $('#ms-container');\n</code></pre>\n\n<p>My container for each individual post displayed on my archive page is:</p>\n\n<pre><code>&lt;div class=\"ms-item col-sm-4\"&gt;\n</code></pre>\n\n<p>Hence:</p>\n\n<pre><code>itemSelector : '.ms-item',\n</code></pre>\n\n<p>This is what I am using as the pagination at the bottom of the archive page:</p>\n\n<pre><code> &lt;div id =\"navigation\" class=\"pagination pull-left prevnext\"&gt;\n &lt;ul class=\"list-inline clearfix\"&gt;\n &lt;li class=\"text-left pull-left\"&gt;&lt;?php previous_posts_link( '&lt;span class=\"glyphicon glyphicon-menu-left\" aria-hidden=\"true\"&gt;&lt;/span&gt; Previous' );?&gt;&lt;/li&gt;\n &lt;li class=\"text-right pull-right\"&gt;&lt;?php next_posts_link( 'Next &lt;span class=\"glyphicon glyphicon-menu-right\" aria-hidden=\"true\"&gt;&lt;/span&gt;'); ?&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>If I remember correctly this is where I got the info on how to do it:\n<a href=\"https://stackoverflow.com/questions/9766515/imagesloaded-method-not-working-with-jquery-masonry-and-infinite-scroll\">https://stackoverflow.com/questions/9766515/imagesloaded-method-not-working-with-jquery-masonry-and-infinite-scroll</a></p>\n" }, { "answer_id": 408542, "author": "Amoeba", "author_id": 214231, "author_profile": "https://wordpress.stackexchange.com/users/214231", "pm_score": 0, "selected": false, "text": "<p>Thanks for your answer N00b. It worked really well. I tweaked it a little bit because the lock didn't work and I wanted to pull posts per page from the WordPress options page. I also reduced HTML markup by using the <a href=\"https://api.jquery.com/data/\" rel=\"nofollow noreferrer\">jQuery .data() function</a>.</p>\n<p><strong>Main JS</strong></p>\n<pre><code>(function($) {\n //Load more posts button\n $( '#more-posts-button' ).click( function( e ) {\n\n e.preventDefault(); \n \n if( ! $(&quot;#more-posts-button&quot;).data(&quot;lock&quot;) ) {\n ajax_next_posts(); \n }\n\n });\n\n function ajax_next_posts() {\n\n $(&quot;#more-posts-button&quot;).data(&quot;lock&quot;,true);\n \n //How many have been loaded\n var postOffset = $( '.single-post' ).length;\n\n\n //Change that to your right site url unless you've already set global ajaxURL\n var ajaxURL = '//' + window.location.hostname + '/wp-admin/admin-ajax.php';\n\n //Parameters you want to pass to query\n var ajaxData = '&amp;post_offset=' + postOffset + '&amp;action=ajax_next_posts';\n\n //Ajax call itself\n $.ajax({\n\n type: 'get',\n url: ajaxURL,\n data: ajaxData,\n dataType: 'json',\n\n //Ajax call is successful\n success: function ( response ) {\n\n //Add new posts\n $( '.posts-container' ).append( response[0] );\n \n //Update the count of total posts\n $(&quot;#more-posts-button&quot;).data(&quot;count&quot;, response[1] );\n\n //How many posts there's total\n var totalPosts = $(&quot;#more-posts-button&quot;).data(&quot;count&quot;); \n\n //How many have been loaded\n var postOffset = $( '.single-post' ).length;\n\n //How many do you want to load in single patch\n var postsPerPage = response[2];\n\n //Hide button if all posts are loaded\n if( totalPosts &lt; postOffset + ( 1 * postsPerPage ) ) {\n\n $( '#more-posts-button' ).fadeOut();\n }\n\n $(&quot;#more-posts-button&quot;).data(&quot;lock&quot;,false);\n },\n\n //Ajax call is not successful, still remove lock in order to try again\n error: function () {\n\n $(&quot;#more-posts-button&quot;).data(&quot;lock&quot;,false);\n }\n });\n }\n \n})( jQuery );\n</code></pre>\n<p><strong>Main HTML</strong></p>\n<pre><code>&lt;div class=&quot;lazy-pagination&quot;&gt;&lt;a class=&quot;button&quot; id=&quot;more-posts-button&quot; href=&quot;#&quot;&gt;Show more posts&lt;/a&gt;&lt;/div&gt;\n</code></pre>\n<p><strong>functions.php</strong></p>\n<pre><code>//lazy load pagination\n//More posts - first for logged in users, other for not logged in\nadd_action('wp_ajax_ajax_next_posts', 'ajax_next_posts');\nadd_action('wp_ajax_nopriv_ajax_next_posts', 'ajax_next_posts');\n\nfunction ajax_next_posts() {\n\n //Build query\n $args = array(\n //All your query arguments\n );\n\n //Get offset\n if( ! empty( $_GET['post_offset'] ) ) {\n\n $offset = $_GET['post_offset'];\n $args['offset'] = $offset;\n\n //Also have to set posts_per_page, otherwise offset is ignored\n $args['posts_per_page'] = get_option( 'posts_per_page' );\n }\n\n $count_results = '0';\n\n $query_results = new WP_Query( $args );\n\n //Results found\n if ( $query_results-&gt;have_posts() ) {\n\n $count_results = $query_results-&gt;found_posts;\n\n //Start &quot;saving&quot; results' HTML\n $results_html = '';\n ob_start();\n\n while ( $query_results-&gt;have_posts() ) { \n\n $query_results-&gt;the_post();\n\n //Your single post HTML here\n get_template_part( 'template-parts/content-blog', get_post_type() );\n } \n\n //&quot;Save&quot; results' HTML as variable\n $results_html = ob_get_clean(); \n }\n\n //Build ajax response\n $response = array();\n\n //1. value is HTML of new posts and 2. is total count of posts\n array_push ( $response, $results_html, $count_results, $args['posts_per_page'] );\n echo json_encode( $response );\n\n //Always use die() in the end of ajax functions\n die(); \n}\n</code></pre>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218178", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88947/" ]
I've been thinking of using `WP_Query`'s pagination to make a custom lazy loading. is there a way to utilize the `WP_Query`'s pagination for a lazy load? Say for example, I have to load 24 posts in the first load, and when the scroll reach bottom it will lazy load the next 24 post. Is this possible?
Take a look at this rough example. This requires a little bit of adaptation but as a whole, it does what you want - it loads X amount of next posts if user clicks a button which should be below already loaded posts. If you want to automatically load more posts if user scrolls down, just replace click event with some other code that keeps an eye on scrolling. There's plenty of examples online. * Keep an eye on `jQuery('some-html-element')-s`, make sure to rename these element names or change your own `HTML` to make them fit * Total posts count: you can make it visible if you want users to see total posts count or use `CSS` `opacity` to hide it. It still needs to be somewhere in order to have a place to store the value --- **This goes to your main .js:** This function handles all the DOM manipulation and ajax. It can be called however you wish. ``` //ajaxLock is just a flag to prevent double clicks and spamming var ajaxLock = false; if( ! ajaxLock ) { function ajax_next_posts() { ajaxLock = true; //How many posts there's total var totalPosts = parseInt( jQuery( '#total-posts-count' ).text() ); //How many have been loaded var postOffset = jQuery( '.single-post' ).length; //How many do you want to load in single patch var postsPerPage = 24; //Hide button if all posts are loaded if( totalPosts < postOffset + ( 1 * postsPerPage ) ) { jQuery( '#more-posts-button' ).fadeOut(); } //Change that to your right site url unless you've already set global ajaxURL var ajaxURL = 'http://www.my-site.com/wp-admin/admin-ajax.php'; //Parameters you want to pass to query var ajaxData = '&post_offset=' + postOffset + '&action=ajax_next_posts'; //Ajax call itself jQuery.ajax({ type: 'get', url: ajaxURL, data: ajaxData, dataType: 'json', //Ajax call is successful success: function ( response ) { //Add new posts jQuery( '#posts-container' ).append( response[0] ); //Update the count of total posts jQuery( '#total-posts-count' ).text( response[1] ); ajaxLock = false; }, //Ajax call is not successful, still remove lock in order to try again error: function () { ajaxLock = false; } }); } } ``` --- **This goes to your main .js:** This is an example how to call function above with button, this is better in my opinion, user can choose if he/she wants to see more.. ``` //Load more posts button jQuery( '#more-posts-button' ).click( function( e ) { e.preventDefault(); ajax_next_posts(); }); ``` --- **This goes to functions.php or create a mu-plugin:** This is the function that "runs" in your server, ajax calls this, it does it's thing and sends results back. ``` //More posts - first for logged in users, other for not logged in add_action('wp_ajax_ajax_next_posts', 'ajax_next_posts'); add_action('wp_ajax_nopriv_ajax_next_posts', 'ajax_next_posts'); function ajax_next_posts() { //Build query $args = array( //All your query arguments ); //Get offset if( ! empty( $_GET['post_offset'] ) ) { $offset = $_GET['post_offset']; $args['offset'] = $offset; //Also have to set posts_per_page, otherwise offset is ignored $args['posts_per_page'] = 24; } $count_results = '0'; $query_results = new WP_Query( $args ); //Results found if ( $query_results->have_posts() ) { $count_results = $query_results->found_posts; //Start "saving" results' HTML $results_html = ''; ob_start(); while ( $query_results->have_posts() ) { $query_results->the_post(); //Your single post HTML here } //"Save" results' HTML as variable $results_html = ob_get_clean(); } //Build ajax response $response = array(); //1. value is HTML of new posts and 2. is total count of posts array_push ( $response, $results_html, $count_results ); echo json_encode( $response ); //Always use die() in the end of ajax functions die(); } ```
218,186
<p>I want to use some of the Wordpress API built in functions such as wp_remote_request(). I have tried using this in a php file in my root Wordpress installation but I am just getting an error: </p> <blockquote> <p>Fatal error: Call to undefined function wp_remote_request() in /home/pacekuwa/public_html/gf.php on line 23</p> </blockquote> <p>I have a feeling I am not putting my code in the right place or need to include one or more Wordpress files...</p> <p>Could anyone tell me where I should be putting my code? </p> <p>EDIT:</p> <p>I am trying to create a page that makes a remote API call to my Gravity Forms plugin to retrieve submitted form entries using the Gravity Forms Web API. I was trying to follow their <a href="https://www.gravityhelp.com/documentation/article/web-api/#get-entries" rel="nofollow">example</a>, but don't know where the code they give should go within my installation to get it to work. </p>
[ { "answer_id": 218245, "author": "Ramūnas Pabrėža", "author_id": 84687, "author_profile": "https://wordpress.stackexchange.com/users/84687", "pm_score": 1, "selected": false, "text": "<p>Wordpress functions are used in theme or plugin files. If you want to use wordpress functions in custom php file you have to include wp-load.php file. <code>require_once(\"../../../../wp-load.php\");</code> . Number of dots depends where is your custom file.</p>\n" }, { "answer_id": 218247, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": true, "text": "<p>You can <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">create a plugin</a> to contain your code. The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action)\" rel=\"nofollow\"><code>admin_post_</code> action</a> can be used to trigger a request handler. WordPress core will be loaded, and the API will work.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Ben's GF Plugin\n*/\n\n// for logged-in users\nadd_action( 'admin_post_ben_gf', 'ben_gf_handle_request' );\n// for non logged-in users\nadd_action( 'admin_post_nopriv_ben_gf', 'ben_gf_handle_request' );\n\nfunction ben_gf_handle_request() {\n\n // Your processing code.\n // WordPress functions will work here.\n echo 'Your home url: ' . home_url();\n\n // die() at the end to terminate execution\n die();\n}\n</code></pre>\n\n<p>This will map your request handler to the URL:</p>\n\n<pre><code>http://www.example.com/wp-admin/admin-post.php?action=ben_gf\n</code></pre>\n\n<p>Use caution if you are allowing non-logged in users to access this URL, you don't want to publicly expose sensitive data.</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17930/" ]
I want to use some of the Wordpress API built in functions such as wp\_remote\_request(). I have tried using this in a php file in my root Wordpress installation but I am just getting an error: > > Fatal error: Call to undefined function wp\_remote\_request() in > /home/pacekuwa/public\_html/gf.php on line 23 > > > I have a feeling I am not putting my code in the right place or need to include one or more Wordpress files... Could anyone tell me where I should be putting my code? EDIT: I am trying to create a page that makes a remote API call to my Gravity Forms plugin to retrieve submitted form entries using the Gravity Forms Web API. I was trying to follow their [example](https://www.gravityhelp.com/documentation/article/web-api/#get-entries), but don't know where the code they give should go within my installation to get it to work.
You can [create a plugin](https://codex.wordpress.org/Writing_a_Plugin) to contain your code. The [`admin_post_` action](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action)) can be used to trigger a request handler. WordPress core will be loaded, and the API will work. ``` <?php /* Plugin Name: Ben's GF Plugin */ // for logged-in users add_action( 'admin_post_ben_gf', 'ben_gf_handle_request' ); // for non logged-in users add_action( 'admin_post_nopriv_ben_gf', 'ben_gf_handle_request' ); function ben_gf_handle_request() { // Your processing code. // WordPress functions will work here. echo 'Your home url: ' . home_url(); // die() at the end to terminate execution die(); } ``` This will map your request handler to the URL: ``` http://www.example.com/wp-admin/admin-post.php?action=ben_gf ``` Use caution if you are allowing non-logged in users to access this URL, you don't want to publicly expose sensitive data.
218,194
<p>Hi i want to know can i create two <code>tables</code> while installing my custom plugin. This is the way i am creating the <code>tables</code> in database</p> <pre><code> function wnm_install(){ global $wpdb; global $wnm_db_version; $sms_table = $wpdb-&gt;prefix . "smsfactory"; if($wpdb-&gt;get_var("show tables like '". $sms_table . "'") != $sms_table){ $sql_sms_table = "CREATE TABLE ". $sms_table . " ( SfID int(11) NOT NULL AUTO_INCREMENT, sf_name varchar(128) NOT NULL, start_duration date NOT NULL, end_duration date NOT NULL, activity varchar(500) NOT NULL, survey_settings varchar(50) NOT NULL, `limit` varchar(50) NOT NULL, goal varchar(100) DEFAULT NULL, PRIMARY KEY (SfID) ) "; } $sms_message_table = $wpdb-&gt;prefix . "smsfactorymessagetemplate"; if($wpdb-&gt;get_var("show tables like '". $sms_message_table . "'") != $sms_message_table){ $sql = "CREATE TABLE ". $sms_message_table . " ( sfID int(11) NOT NULL AUTO_INCREMENT, sftemplate_name varchar(256) NOT NULL, sftemplate_type varchar(128) NOT NULL, PRIMARY KEY (sfID) ) "; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); add_option("wnm_db_version", $wnm_db_version); } </code></pre> <p>Now problem with this code is it creates the second table and skip the first one so please tell me any solution for this </p>
[ { "answer_id": 218198, "author": "Steven", "author_id": 1447, "author_profile": "https://wordpress.stackexchange.com/users/1447", "pm_score": 3, "selected": true, "text": "<p>Seems to me you are just executing one query: <code>dbDelta($sql);</code>.</p>\n\n<p>Have you tried adding <code>dbDelta($sql_sms_table);</code>?</p>\n" }, { "answer_id": 218199, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": false, "text": "<p>In your original code, you were only calling <code>dbDelta($sql)</code> and not <code>dbDelta($sql_sms_table)</code> also.</p>\n<h3>A better way...</h3>\n<p><code>dbDelta()</code> can take an array of queries, so we need to set an empty array on the <code>$sql</code> variable to store the queries if their conditions evaluate <code>true</code>.</p>\n<pre><code>function wnm_install() {\n\n global $wpdb, $wnm_db_version;\n\n $sql = array();\n\n //sms table\n $sms_table = $wpdb-&gt;prefix . &quot;smsfactory&quot;;\n\n if( $wpdb-&gt;get_var(&quot;show tables like '&quot;. $sms_table . &quot;'&quot;) !== $sms_table ) { \n\n $sql[] = &quot;CREATE TABLE &quot;. $sms_table . &quot; (\n SfID int(11) NOT NULL AUTO_INCREMENT,\n sf_name varchar(128) NOT NULL,\n start_duration date NOT NULL,\n end_duration date NOT NULL,\n activity varchar(500) NOT NULL,\n survey_settings varchar(50) NOT NULL,\n `limit` varchar(50) NOT NULL,\n goal varchar(100) DEFAULT NULL,\n PRIMARY KEY (SfID)\n ) &quot;;\n\n }\n\n //sms messages table\n $sms_message_table = $wpdb-&gt;prefix . &quot;smsfactorymessagetemplate&quot;;\n \n if( $wpdb-&gt;get_var(&quot;show tables like '&quot;. $sms_message_table . &quot;'&quot;) !== $sms_message_table ) { \n\n $sql[] = &quot;CREATE TABLE &quot;. $sms_message_table . &quot; (\n sfID int(11) NOT NULL AUTO_INCREMENT,\n sftemplate_name varchar(256) NOT NULL,\n sftemplate_type varchar(128) NOT NULL,\n PRIMARY KEY (sfID)\n ) &quot;;\n\n }\n\n\n if ( !empty($sql) ) {\n\n require_once(ABSPATH . 'wp-admin/includes/upgrade.php');\n\n dbDelta($sql);\n add_option(&quot;wnm_db_version&quot;, $wnm_db_version);\n \n }\n\n}\n</code></pre>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218194", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88914/" ]
Hi i want to know can i create two `tables` while installing my custom plugin. This is the way i am creating the `tables` in database ``` function wnm_install(){ global $wpdb; global $wnm_db_version; $sms_table = $wpdb->prefix . "smsfactory"; if($wpdb->get_var("show tables like '". $sms_table . "'") != $sms_table){ $sql_sms_table = "CREATE TABLE ". $sms_table . " ( SfID int(11) NOT NULL AUTO_INCREMENT, sf_name varchar(128) NOT NULL, start_duration date NOT NULL, end_duration date NOT NULL, activity varchar(500) NOT NULL, survey_settings varchar(50) NOT NULL, `limit` varchar(50) NOT NULL, goal varchar(100) DEFAULT NULL, PRIMARY KEY (SfID) ) "; } $sms_message_table = $wpdb->prefix . "smsfactorymessagetemplate"; if($wpdb->get_var("show tables like '". $sms_message_table . "'") != $sms_message_table){ $sql = "CREATE TABLE ". $sms_message_table . " ( sfID int(11) NOT NULL AUTO_INCREMENT, sftemplate_name varchar(256) NOT NULL, sftemplate_type varchar(128) NOT NULL, PRIMARY KEY (sfID) ) "; } require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); add_option("wnm_db_version", $wnm_db_version); } ``` Now problem with this code is it creates the second table and skip the first one so please tell me any solution for this
Seems to me you are just executing one query: `dbDelta($sql);`. Have you tried adding `dbDelta($sql_sms_table);`?
218,200
<p>I want to put a variable between two tags, but it puts him out.</p> <p>This is my function: (function.php)</p> <pre><code>/* traer thumb */ function item_thumb() { global $post; if (has_post_format('video')) { $key_1_value = get_post_meta( $post-&gt;ID, 'video', true ); if (!empty( $key_1_value ) ) { $post_video = '&lt;div class="item-video embed-responsive embed-responsive-16by9"&gt;'; $post_video.= wp_oembed_get($key_1_value); $post_video.= '&lt;/div&gt;'; return $post_video; } } else { if (has_post_thumbnail()) { $item_image = '&lt;div class="item-image"&gt;'; $item_image.= the_post_thumbnail( 'thumb_destacado', array( 'class' =&gt; 'img-responsive full-width')); $item_image.= '&lt;/div&gt;'; return $item_image; } } } </code></pre> <p>And get this: The video are okay:</p> <pre><code>&lt;div class="item-video embed-responsive embed-responsive-16by9"&gt; &lt;iframe width="600" height="338" src="https://www.youtube.com/embed/rdlFMPXJ44o?feature=oembed" frameborder="0" allowfullscreen="" class="embed-responsive-item"&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>But the thumbnails appears so:</p> <pre><code>&lt;img width="630" height="300" src="http://localhost/agroverdad.com.ar/wp-content/uploads/2016/02/Carne-Exportacion-630-630x300.jpg" class="img-responsive full-width wp-post-image" alt="Carne-Exportacion-630"&gt; &lt;div class="item-image"&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 218201, "author": "Steven", "author_id": 1447, "author_profile": "https://wordpress.stackexchange.com/users/1447", "pm_score": 1, "selected": false, "text": "<p>It's because you are using <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow\">the_post_thumbnail</a> instead of <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\">get_the_post_thumbnail</a>.</p>\n\n<p>In general in WP, anything starting with <code>the_</code> will output data and anything starting with <code>get_</code> will return data.</p>\n" }, { "answer_id": 218202, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": true, "text": "<p><code>the_post_thumbnail()</code> echoes data immediate, what you want to try is <code>get_the_post_thumbnail()</code> which returns data so that you may concatenate properly.</p>\n\n<p>WordPress core functions that are prefixed with <code>the_</code> usually echo, those prefixed with <code>get_</code> usually return.</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/</a></li>\n</ul>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218200", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87880/" ]
I want to put a variable between two tags, but it puts him out. This is my function: (function.php) ``` /* traer thumb */ function item_thumb() { global $post; if (has_post_format('video')) { $key_1_value = get_post_meta( $post->ID, 'video', true ); if (!empty( $key_1_value ) ) { $post_video = '<div class="item-video embed-responsive embed-responsive-16by9">'; $post_video.= wp_oembed_get($key_1_value); $post_video.= '</div>'; return $post_video; } } else { if (has_post_thumbnail()) { $item_image = '<div class="item-image">'; $item_image.= the_post_thumbnail( 'thumb_destacado', array( 'class' => 'img-responsive full-width')); $item_image.= '</div>'; return $item_image; } } } ``` And get this: The video are okay: ``` <div class="item-video embed-responsive embed-responsive-16by9"> <iframe width="600" height="338" src="https://www.youtube.com/embed/rdlFMPXJ44o?feature=oembed" frameborder="0" allowfullscreen="" class="embed-responsive-item"></iframe> </div> ``` But the thumbnails appears so: ``` <img width="630" height="300" src="http://localhost/agroverdad.com.ar/wp-content/uploads/2016/02/Carne-Exportacion-630-630x300.jpg" class="img-responsive full-width wp-post-image" alt="Carne-Exportacion-630"> <div class="item-image"></div> ```
`the_post_thumbnail()` echoes data immediate, what you want to try is `get_the_post_thumbnail()` which returns data so that you may concatenate properly. WordPress core functions that are prefixed with `the_` usually echo, those prefixed with `get_` usually return. See: * <https://developer.wordpress.org/reference/functions/the_post_thumbnail/> * <https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/>
218,204
<p>I know that password_reset hooks:</p> <pre><code>Runs after the user submits a new password during password reset but before the new password is actually set. </code></pre> <p>but there is a similar hook <em>AFTER</em> the new password is actually set?</p> <p>EDIT: It would be logical to use profile_update but I tried, and profile_update seems not get called in case of password change for a 'lost password' procedure, for example. My real problem is auto login after password reset, and the only solution found till now, was using password_reset hook calling manually a wp_set_password before executing my code, so to be sure that password gets changed and THEN my code gets executed. This is not a clean procedure, and I am wondering if there is a solution that is less 'hacky'... I searched a lot, looking at every action hook in wordpress doc, but i can't find a proper solution.</p>
[ { "answer_id": 218211, "author": "Steven", "author_id": 1447, "author_profile": "https://wordpress.stackexchange.com/users/1447", "pm_score": 2, "selected": false, "text": "<p>It seems that you have to use <code>profile_update</code> hook.</p>\n\n<p>There is a similar question <a href=\"https://wordpress.stackexchange.com/questions/51337/how-can-i-detect-if-a-user-changes-their-password\">here</a>, and <a href=\"https://stackoverflow.com/questions/29641663/execute-a-function-when-password-changed-in-wordpress\">here</a>.</p>\n\n<p>So this post might actually be considered duplicate.</p>\n" }, { "answer_id": 218224, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>I wonder if you're looking for <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086\">this one</a>: </p>\n\n<pre><code> /**\n * Fires after the user's password is reset.\n *\n * @since 4.4.0\n *\n * @param object $user The user.\n * @param string $new_pass New user password.\n */\n do_action( 'after_password_reset', $user, $new_pass );\n</code></pre>\n\n<p>It was introduced in WordPress 4.4 and lives within the <code>reset_password()</code> function. The <code>after_password_reset</code> hook fires after the <code>wp_set_password()</code>.</p>\n\n<h2>Update</h2>\n\n<p>Here's an untested pre 4.4 workaround idea:</p>\n\n<pre><code>/**\n * Support for the 'after_password_reset' hook in WordPress pre 4.4\n */\nadd_action( 'password_reset', function( $user, $new_pass )\n{\n add_filter( 'pre_option_admin_email', \n function( $pre_option, $option ) use ( $user, $new_pass )\n {\n // Setup our 'after_password_reset' hook\n if( ! did_action( 'after_password_reset' ) )\n do_action( 'after_password_reset', $user, $new_pass );\n\n return $pre_option; \n } 10, 2 ); \n}, 10, 2 );\n</code></pre>\n\n<p>where you should now have your own custom <code>after_password_reset</code> hook.</p>\n\n<p>Remember to <strong>backup</strong> database before testing.</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218204", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71652/" ]
I know that password\_reset hooks: ``` Runs after the user submits a new password during password reset but before the new password is actually set. ``` but there is a similar hook *AFTER* the new password is actually set? EDIT: It would be logical to use profile\_update but I tried, and profile\_update seems not get called in case of password change for a 'lost password' procedure, for example. My real problem is auto login after password reset, and the only solution found till now, was using password\_reset hook calling manually a wp\_set\_password before executing my code, so to be sure that password gets changed and THEN my code gets executed. This is not a clean procedure, and I am wondering if there is a solution that is less 'hacky'... I searched a lot, looking at every action hook in wordpress doc, but i can't find a proper solution.
I wonder if you're looking for [this one](https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086): ``` /** * Fires after the user's password is reset. * * @since 4.4.0 * * @param object $user The user. * @param string $new_pass New user password. */ do_action( 'after_password_reset', $user, $new_pass ); ``` It was introduced in WordPress 4.4 and lives within the `reset_password()` function. The `after_password_reset` hook fires after the `wp_set_password()`. Update ------ Here's an untested pre 4.4 workaround idea: ``` /** * Support for the 'after_password_reset' hook in WordPress pre 4.4 */ add_action( 'password_reset', function( $user, $new_pass ) { add_filter( 'pre_option_admin_email', function( $pre_option, $option ) use ( $user, $new_pass ) { // Setup our 'after_password_reset' hook if( ! did_action( 'after_password_reset' ) ) do_action( 'after_password_reset', $user, $new_pass ); return $pre_option; } 10, 2 ); }, 10, 2 ); ``` where you should now have your own custom `after_password_reset` hook. Remember to **backup** database before testing.
218,221
<p>I want to get the slug of the current archive page. I have a slider where I want to echo the products that are in this category. After hours this is all I have and it doesn't work...</p> <pre><code>&lt;?php if ( is_single() ) { $cats = get_the_category(); $cat = $cats[0]; // let's just assume the post has one category } else { // category archives $cat = get_category( get_query_var( 'cat' ) ); } $cat_name = $cat-&gt;name; $cat_slug = $cat-&gt;slug; echo '&lt;h2 style="text-align:center;"&gt;'.$cat_name.' - Spotlight&lt;/h2&gt;'; echo '&lt;h2 style="text-align:center;"&gt;'.$cat_slug.' -- Slug&lt;/h2&gt;'; echo "here: ".$cat_name." - ".$cat_slug; echo do_shortcode('[wpb-product-slider title="" product_type="category" category="'.$cat_slug.'" items="3" items_desktop="3" items_desktop_small="3" items_tablet="2" items_mobile="1" width="320" height="300" crop="true" theme="ben-box" posts="50" orderby="rand" speed="2000" order="ASC"]'); ?&gt; </code></pre> <p>But the $cat is always empty. How can I do that ?</p>
[ { "answer_id": 218211, "author": "Steven", "author_id": 1447, "author_profile": "https://wordpress.stackexchange.com/users/1447", "pm_score": 2, "selected": false, "text": "<p>It seems that you have to use <code>profile_update</code> hook.</p>\n\n<p>There is a similar question <a href=\"https://wordpress.stackexchange.com/questions/51337/how-can-i-detect-if-a-user-changes-their-password\">here</a>, and <a href=\"https://stackoverflow.com/questions/29641663/execute-a-function-when-password-changed-in-wordpress\">here</a>.</p>\n\n<p>So this post might actually be considered duplicate.</p>\n" }, { "answer_id": 218224, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>I wonder if you're looking for <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086\">this one</a>: </p>\n\n<pre><code> /**\n * Fires after the user's password is reset.\n *\n * @since 4.4.0\n *\n * @param object $user The user.\n * @param string $new_pass New user password.\n */\n do_action( 'after_password_reset', $user, $new_pass );\n</code></pre>\n\n<p>It was introduced in WordPress 4.4 and lives within the <code>reset_password()</code> function. The <code>after_password_reset</code> hook fires after the <code>wp_set_password()</code>.</p>\n\n<h2>Update</h2>\n\n<p>Here's an untested pre 4.4 workaround idea:</p>\n\n<pre><code>/**\n * Support for the 'after_password_reset' hook in WordPress pre 4.4\n */\nadd_action( 'password_reset', function( $user, $new_pass )\n{\n add_filter( 'pre_option_admin_email', \n function( $pre_option, $option ) use ( $user, $new_pass )\n {\n // Setup our 'after_password_reset' hook\n if( ! did_action( 'after_password_reset' ) )\n do_action( 'after_password_reset', $user, $new_pass );\n\n return $pre_option; \n } 10, 2 ); \n}, 10, 2 );\n</code></pre>\n\n<p>where you should now have your own custom <code>after_password_reset</code> hook.</p>\n\n<p>Remember to <strong>backup</strong> database before testing.</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84738/" ]
I want to get the slug of the current archive page. I have a slider where I want to echo the products that are in this category. After hours this is all I have and it doesn't work... ``` <?php if ( is_single() ) { $cats = get_the_category(); $cat = $cats[0]; // let's just assume the post has one category } else { // category archives $cat = get_category( get_query_var( 'cat' ) ); } $cat_name = $cat->name; $cat_slug = $cat->slug; echo '<h2 style="text-align:center;">'.$cat_name.' - Spotlight</h2>'; echo '<h2 style="text-align:center;">'.$cat_slug.' -- Slug</h2>'; echo "here: ".$cat_name." - ".$cat_slug; echo do_shortcode('[wpb-product-slider title="" product_type="category" category="'.$cat_slug.'" items="3" items_desktop="3" items_desktop_small="3" items_tablet="2" items_mobile="1" width="320" height="300" crop="true" theme="ben-box" posts="50" orderby="rand" speed="2000" order="ASC"]'); ?> ``` But the $cat is always empty. How can I do that ?
I wonder if you're looking for [this one](https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086): ``` /** * Fires after the user's password is reset. * * @since 4.4.0 * * @param object $user The user. * @param string $new_pass New user password. */ do_action( 'after_password_reset', $user, $new_pass ); ``` It was introduced in WordPress 4.4 and lives within the `reset_password()` function. The `after_password_reset` hook fires after the `wp_set_password()`. Update ------ Here's an untested pre 4.4 workaround idea: ``` /** * Support for the 'after_password_reset' hook in WordPress pre 4.4 */ add_action( 'password_reset', function( $user, $new_pass ) { add_filter( 'pre_option_admin_email', function( $pre_option, $option ) use ( $user, $new_pass ) { // Setup our 'after_password_reset' hook if( ! did_action( 'after_password_reset' ) ) do_action( 'after_password_reset', $user, $new_pass ); return $pre_option; } 10, 2 ); }, 10, 2 ); ``` where you should now have your own custom `after_password_reset` hook. Remember to **backup** database before testing.
218,237
<p>I want to change the upload directory for Wordpress from <code>project.dev/wp-content/uploads</code> to <code>cdn.project.dev</code></p> <p>Where subdomain <strong>cdn</strong> has DocumentRoot: <code>HostPath/project.dev/cdn</code> while Wordpress is located at <code>HostPath/project.dev/public_html</code></p> <p>Any help is much appreciated.</p>
[ { "answer_id": 218211, "author": "Steven", "author_id": 1447, "author_profile": "https://wordpress.stackexchange.com/users/1447", "pm_score": 2, "selected": false, "text": "<p>It seems that you have to use <code>profile_update</code> hook.</p>\n\n<p>There is a similar question <a href=\"https://wordpress.stackexchange.com/questions/51337/how-can-i-detect-if-a-user-changes-their-password\">here</a>, and <a href=\"https://stackoverflow.com/questions/29641663/execute-a-function-when-password-changed-in-wordpress\">here</a>.</p>\n\n<p>So this post might actually be considered duplicate.</p>\n" }, { "answer_id": 218224, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>I wonder if you're looking for <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086\">this one</a>: </p>\n\n<pre><code> /**\n * Fires after the user's password is reset.\n *\n * @since 4.4.0\n *\n * @param object $user The user.\n * @param string $new_pass New user password.\n */\n do_action( 'after_password_reset', $user, $new_pass );\n</code></pre>\n\n<p>It was introduced in WordPress 4.4 and lives within the <code>reset_password()</code> function. The <code>after_password_reset</code> hook fires after the <code>wp_set_password()</code>.</p>\n\n<h2>Update</h2>\n\n<p>Here's an untested pre 4.4 workaround idea:</p>\n\n<pre><code>/**\n * Support for the 'after_password_reset' hook in WordPress pre 4.4\n */\nadd_action( 'password_reset', function( $user, $new_pass )\n{\n add_filter( 'pre_option_admin_email', \n function( $pre_option, $option ) use ( $user, $new_pass )\n {\n // Setup our 'after_password_reset' hook\n if( ! did_action( 'after_password_reset' ) )\n do_action( 'after_password_reset', $user, $new_pass );\n\n return $pre_option; \n } 10, 2 ); \n}, 10, 2 );\n</code></pre>\n\n<p>where you should now have your own custom <code>after_password_reset</code> hook.</p>\n\n<p>Remember to <strong>backup</strong> database before testing.</p>\n" } ]
2016/02/19
[ "https://wordpress.stackexchange.com/questions/218237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I want to change the upload directory for Wordpress from `project.dev/wp-content/uploads` to `cdn.project.dev` Where subdomain **cdn** has DocumentRoot: `HostPath/project.dev/cdn` while Wordpress is located at `HostPath/project.dev/public_html` Any help is much appreciated.
I wonder if you're looking for [this one](https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/user.php#L2086): ``` /** * Fires after the user's password is reset. * * @since 4.4.0 * * @param object $user The user. * @param string $new_pass New user password. */ do_action( 'after_password_reset', $user, $new_pass ); ``` It was introduced in WordPress 4.4 and lives within the `reset_password()` function. The `after_password_reset` hook fires after the `wp_set_password()`. Update ------ Here's an untested pre 4.4 workaround idea: ``` /** * Support for the 'after_password_reset' hook in WordPress pre 4.4 */ add_action( 'password_reset', function( $user, $new_pass ) { add_filter( 'pre_option_admin_email', function( $pre_option, $option ) use ( $user, $new_pass ) { // Setup our 'after_password_reset' hook if( ! did_action( 'after_password_reset' ) ) do_action( 'after_password_reset', $user, $new_pass ); return $pre_option; } 10, 2 ); }, 10, 2 ); ``` where you should now have your own custom `after_password_reset` hook. Remember to **backup** database before testing.
218,286
<p>I'm using option tree for my theme options page. But I can't retrieve uploaded images attribute like alternative text, description,caption etc. </p> <p>How can I do that.</p>
[ { "answer_id": 230701, "author": "asadadin", "author_id": 97157, "author_profile": "https://wordpress.stackexchange.com/users/97157", "pm_score": 3, "selected": true, "text": "<p>Put this code in <code>index.php</code></p>\n\n<hr>\n\n<pre><code>&lt;img class=\"img-resposive\" src=\"&lt;?php \n $logo=get_option_tree( 'logo','','true'); // return src of img\n $id_logo = get_attachment_id_from_src($logo); // This is custom function for getting image id.\n $alt = get_post_meta($id_logo, '_wp_attachment_image_alt', true);// get alt=\"\" from wordpress media.\n if ( function_exists( 'get_option_tree') ) : \n if( get_option_tree( 'logo')) : \n $logo; \n else:\n echo bloginfo('template_directory') .'/assets/images/logo_vp.png'; // else if option is empty get this image.\n endif; \n endif; \n?&gt;\" alt=\"&lt;?php echo $alt; ?&gt;\"/&gt;\n</code></pre>\n\n<p>Put this function code in <code>functions.php</code></p>\n\n<pre><code>//get id from image source\nfunction get_attachment_id_from_src ($image_src) {\n global $wpdb;\n $query = \"SELECT ID FROM {$wpdb-&gt;posts} WHERE guid='$image_src'\";\n $id = $wpdb-&gt;get_var($query);\n return $id;\n}\n</code></pre>\n\n<hr>\n\n<p>This code is tested. Working fine.</p>\n" }, { "answer_id": 244290, "author": "Alireza", "author_id": 46064, "author_profile": "https://wordpress.stackexchange.com/users/46064", "pm_score": 0, "selected": false, "text": "<p>Here is the correct answer for optiontree 2.4+</p>\n\n<p><a href=\"https://github.com/valendesigns/option-tree/issues/112\" rel=\"nofollow\">https://github.com/valendesigns/option-tree/issues/112</a></p>\n\n<p><strong>Note</strong></p>\n\n<pre><code>'class' =&gt; 'ot-upload-attachment-id',\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>array(\n 'id' =&gt; 'demo_upload_attachment_id',\n 'label' =&gt; __( 'Upload Attachment ID', 'option-tree-theme' ),\n 'desc' =&gt; sprintf( __( 'The Upload option type can also be saved as an attachment ID by adding %s to the class attribute.', 'option-tree-theme' ), '&lt;code&gt;ot-upload-attachment-id&lt;/code&gt;' ),\n 'std' =&gt; '',\n 'type' =&gt; 'upload',\n 'section' =&gt; 'option_types',\n 'rows' =&gt; '',\n 'post_type' =&gt; '',\n 'taxonomy' =&gt; '',\n 'min_max_step'=&gt; '',\n 'class' =&gt; 'ot-upload-attachment-id',\n 'condition' =&gt; '',\n 'operator' =&gt; 'and'\n)\n</code></pre>\n" } ]
2016/02/20
[ "https://wordpress.stackexchange.com/questions/218286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68186/" ]
I'm using option tree for my theme options page. But I can't retrieve uploaded images attribute like alternative text, description,caption etc. How can I do that.
Put this code in `index.php` --- ``` <img class="img-resposive" src="<?php $logo=get_option_tree( 'logo','','true'); // return src of img $id_logo = get_attachment_id_from_src($logo); // This is custom function for getting image id. $alt = get_post_meta($id_logo, '_wp_attachment_image_alt', true);// get alt="" from wordpress media. if ( function_exists( 'get_option_tree') ) : if( get_option_tree( 'logo')) : $logo; else: echo bloginfo('template_directory') .'/assets/images/logo_vp.png'; // else if option is empty get this image. endif; endif; ?>" alt="<?php echo $alt; ?>"/> ``` Put this function code in `functions.php` ``` //get id from image source function get_attachment_id_from_src ($image_src) { global $wpdb; $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'"; $id = $wpdb->get_var($query); return $id; } ``` --- This code is tested. Working fine.
218,390
<p>I was using this code:</p> <pre><code>add_filter( 'pre_get_posts','search_only_blog_posts' ); function search_only_blog_posts( $query ) { if ( $query-&gt;is_search ) { $query-&gt;set( 'post_type', 'post' ); } return $query; } </code></pre> <hr> <p>..until I realized that it applies to pretty much any default search in WordPress <em>(including search in post list page in admin area etc)</em>.</p> <p><strong>How could I make the search widget to only search blog posts</strong> <em>(not custom posts, taxonomies, images etc)</em> <strong>so that it doesn't apply to any default WP search</strong> <em>(only widget search)</em> <strong>?</strong></p> <p>Or is it easier to just make my own search widget? </p> <p>I would prefer to utilize everything WordPress has to offer and not to reinvent the wheel.</p>
[ { "answer_id": 218434, "author": "Nik", "author_id": 89023, "author_profile": "https://wordpress.stackexchange.com/users/89023", "pm_score": -1, "selected": false, "text": "<p>Please Refer this code and setting <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-exclude-pages-from-wordpress-search-results/\" rel=\"nofollow\">following link</a></p>\n" }, { "answer_id": 218443, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Your use of <code>pre_get_posts</code> is completely wrong.</p>\n\n<ul>\n<li><p><code>pre_get_posts</code> is an action, not a filter. Check the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/query.php#L2480\" rel=\"nofollow\">source</a></p>\n\n<pre><code>do_action_ref_array( 'pre_get_posts', array( &amp;$this ) );\n</code></pre>\n\n<p>Yes, <code>add_filter</code> works because <code>add_action</code> calls <code>add_filter</code>, that is why your code will work. But as for proper usage, it is just plain wrong. If something is an action, use <code>add_action()</code>. It just makes sense</p></li>\n<li><p><code>WP_Query::is_search</code> (<em>and <code>WP_Query::is_search()</code> for that matter</em>) returns true on <strong>any</strong> query where <code>s</code> is passed to <code>WP_Query</code>. Remember, the conditional tags inside <code>WP_Query</code> are not set according to the URL, but according to the query vars passed to it. For the main query, the query vars passed to <code>WP_Query</code> will come from parsing the URL. </p></li>\n<li><p><code>pre_get_posts</code> alters all instances of <code>WP_Query</code>, <code>query_posts</code> and <code>get_posts</code>, front end and back end regardless, so you would want to target only the main query if you only would want to target the main query. Additionally, you would only want to target the front end, specially for archives and search queries.</p></li>\n</ul>\n\n<p>Here is an example on how to use <code>pre_get_posts</code> correctly for the main query: (<em>You can change the closure to normal spaghetti if you wish, just a note, only use closures if you're sure you would not want to remove the action later as anonymous functions can't be removed</em>)</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target front end,\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n &amp;&amp; $q-&gt;is_search() // Only target the search page\n ) {\n $q-&gt;set( 'post_type', ['my_custom_post_type', 'post'] );\n }\n});\n</code></pre>\n\n<p>To answer your question about the search widget, here is what I have found</p>\n\n<ul>\n<li><p>The <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-search.php\" rel=\"nofollow\">search widget</a> simply call <a href=\"https://developer.wordpress.org/reference/functions/get_search_form/\" rel=\"nofollow\"><code>get_search_form()</code></a></p></li>\n<li><p>There is no useful filter to specifically target the search widget. The filters available in <code>get_search_form()</code> will target all forms which uses <code>get_search_form()</code></p></li>\n</ul>\n\n<p>With the above, you would need to create your own search widget with your own custom form</p>\n\n<p>You can try the following: (<em>Modified from the core search widget, note, everything is untested</em>)</p>\n\n<pre><code>class My_Custom_Search extends WP_Widget {\n /**\n * Sets up a new Search widget instance.\n *\n * @since 1.0.0\n * @access public\n */\n public function __construct() {\n $widget_ops = [\n 'classname' =&gt; 'widget_custom_search', \n 'description' =&gt; __( \"A custom search form for your site.\")\n ];\n parent::__construct( 'custom-search', _x( 'Custom search', 'My custom search widget' ), $widget_ops );\n }\n\n /**\n * Outputs the content for the current Search widget instance.\n *\n * @since 1.0.0\n * @access public\n *\n * @param array $args Display arguments including 'before_title', 'after_title',\n * 'before_widget', and 'after_widget'.\n * @param array $instance Settings for the current Search widget instance.\n */\n public function widget( $args, $instance ) {\n /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */\n $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this-&gt;id_base );\n echo $args['before_widget'];\n\n if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n }\n\n $form = '&lt;form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\"&gt;\n &lt;label&gt;\n &lt;span class=\"screen-reader-text\"&gt;' . _x( 'Search for:', 'label' ) . '&lt;/span&gt;\n &lt;input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &amp;hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" title=\"' . esc_attr_x( 'Search for:', 'label' ) . '\" /&gt;\n &lt;/label&gt;\n &lt;input type=\"hidden\" value=\"post\" name=\"post_type\" id=\"post_type\" /&gt;\n &lt;input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" /&gt;\n &lt;/form&gt;';\n\n echo $form;\n\n echo $args['after_widget'];\n }\n\n /**\n * Outputs the settings form for the Search widget.\n *\n * @since 1.0.0\n * @access public\n *\n * @param array $instance Current settings.\n */\n public function form( $instance ) {\n $instance = wp_parse_args( (array) $instance, ['title' =&gt; '')];\n $title = $instance['title'];\n ?&gt;\n &lt;p&gt;&lt;label for=\"&lt;?php echo $this-&gt;get_field_id('title'); ?&gt;\"&gt;&lt;?php _e('Title:'); ?&gt; &lt;input class=\"widefat\" id=\"&lt;?php echo $this-&gt;get_field_id('title'); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name('title'); ?&gt;\" type=\"text\" value=\"&lt;?php echo esc_attr($title); ?&gt;\" /&gt;&lt;/label&gt;&lt;/p&gt;\n &lt;?php\n }\n\n /**\n * Handles updating settings for the current Search widget instance.\n *\n * @since 1.0.0\n * @access public\n *\n * @param array $new_instance New settings for this instance as input by the user via\n * WP_Widget::form().\n * @param array $old_instance Old settings for this instance.\n * @return array Updated settings.\n */\n public function update( $new_instance, $old_instance ) {\n $instance = $old_instance;\n $new_instance = wp_parse_args((array) $new_instance, ['title' =&gt; '')];\n $instance['title'] = sanitize_text_field( $new_instance['title'] );\n return $instance;\n }\n}\n</code></pre>\n" }, { "answer_id": 218451, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>@PieterGoosen has a good description on why your <code>pre_get_posts</code> callback is giving you a problem. </p>\n\n<p>Here's an alternative workaround to restrict the native <em>search widget</em> to the <em>post</em> post type:</p>\n\n<pre><code>/**\n * Restrict native search widgets to the 'post' post type\n */\nadd_filter( 'widget_title', function( $title, $instance, $id_base )\n{\n // Target the search base\n if( 'search' === $id_base )\n add_filter( 'get_search_form', 'wpse_post_type_restriction' );\n return $title;\n}, 10, 3 );\n\nfunction wpse_post_type_restriction( $html )\n{\n // Only run once\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Inject hidden post_type value\n return str_replace( \n '&lt;/form&gt;', \n '&lt;input type=\"hidden\" name=\"post_type\" value=\"post\" /&gt;&lt;/form&gt;',\n $html \n );\n} \n</code></pre>\n\n<p>where we use adjust the output of the <code>get_search_form()</code> function but only for the search widgets.</p>\n" }, { "answer_id": 223443, "author": "Richard K", "author_id": 92230, "author_profile": "https://wordpress.stackexchange.com/users/92230", "pm_score": 1, "selected": false, "text": "<p>You can simply put this in your functions.php file.</p>\n\n<pre><code>function SearchFilter($query) \n{\n if (($query-&gt;is_search)&amp;&amp;(!is_admin())) {\n $query-&gt;set('post_type', 'post');\n }\n return $query;\n}\n\nadd_filter('pre_get_posts','SearchFilter');\n</code></pre>\n" }, { "answer_id": 280174, "author": "Mentik Yusmantara", "author_id": 127981, "author_profile": "https://wordpress.stackexchange.com/users/127981", "pm_score": 0, "selected": false, "text": "<p>Just Write this code on your functions.php WordPress theme. </p>\n\n<pre><code>function wpdocs_my_search_form( $form ) {\n$form = '&lt;form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" &gt;\n&lt;div&gt;&lt;label class=\"screen-reader-text\" for=\"s\"&gt;' . __( 'Search for:' ) . '&lt;/label&gt;\n&lt;input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" /&gt;\n&lt;input type=\"hidden\" value=\"post\" name=\"post_type\" id=\"post_type\" /&gt;\n&lt;input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" /&gt;\n&lt;/div&gt;\n&lt;/form&gt;';\n\nreturn $form;\n} add_filter( 'get_search_form', 'wpdocs_my_search_form' );\n</code></pre>\n" } ]
2016/02/21
[ "https://wordpress.stackexchange.com/questions/218390", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
I was using this code: ``` add_filter( 'pre_get_posts','search_only_blog_posts' ); function search_only_blog_posts( $query ) { if ( $query->is_search ) { $query->set( 'post_type', 'post' ); } return $query; } ``` --- ..until I realized that it applies to pretty much any default search in WordPress *(including search in post list page in admin area etc)*. **How could I make the search widget to only search blog posts** *(not custom posts, taxonomies, images etc)* **so that it doesn't apply to any default WP search** *(only widget search)* **?** Or is it easier to just make my own search widget? I would prefer to utilize everything WordPress has to offer and not to reinvent the wheel.
@PieterGoosen has a good description on why your `pre_get_posts` callback is giving you a problem. Here's an alternative workaround to restrict the native *search widget* to the *post* post type: ``` /** * Restrict native search widgets to the 'post' post type */ add_filter( 'widget_title', function( $title, $instance, $id_base ) { // Target the search base if( 'search' === $id_base ) add_filter( 'get_search_form', 'wpse_post_type_restriction' ); return $title; }, 10, 3 ); function wpse_post_type_restriction( $html ) { // Only run once remove_filter( current_filter(), __FUNCTION__ ); // Inject hidden post_type value return str_replace( '</form>', '<input type="hidden" name="post_type" value="post" /></form>', $html ); } ``` where we use adjust the output of the `get_search_form()` function but only for the search widgets.
218,393
<p>I'm in the process of writing a plugin and I'm trying to gauge when to use different approaches of handling errors.</p> <p>There are three methods I'm considering:</p> <ul> <li>Throwing an Exception (custom class)</li> <li>Returning an Error Object (extension of WP_Error)</li> <li>Just return null/false</li> </ul> <p>Some situations that I'm considering</p> <ul> <li>Trying to get/set an option stored in the Registry that doesn't exist</li> <li>Passing an invalid value to a method (which should be rare)</li> <li>Calling a method that the class' overloader cannot resolve to</li> </ul> <p>Suggestions? Since writing a WordPress plugin has some special considerations, I'm not sure whether it would be worth asking this on a general PHP board.</p>
[ { "answer_id": 230467, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>I think it's impossible to give a definitive answer here, because choices like this are personal preference.</p>\n\n<p>Consider that what follows is <em>my</em> approach, and I have no presumption it is <em>the right</em> one.</p>\n\n<p>What I can say for sure is that you should avoid your third option:</p>\n\n<blockquote>\n <p>Just return null/false</p>\n</blockquote>\n\n<p>This is bad under different aspect:</p>\n\n<ul>\n<li>return type consinstency</li>\n<li>makes functions harder to unit test</li>\n<li>force conditional check on return type (<code>if (! is_null($thing))...</code>) making code harder to read</li>\n</ul>\n\n<p>I, more than often, use OOP to code plugins, and my object methods often throw exception when something goes wrong.</p>\n\n<p>Doing that, I:</p>\n\n<ul>\n<li>accomplish return type consinstency</li>\n<li>make the code simple to unit test</li>\n<li>don't need conditional check on the returned type</li>\n</ul>\n\n<p>However, throwing exceptions in a WordPress plugin, means that nothing will <em>catch</em> them, ending up in a fatal error that is absolutely <strong>not</strong> desirable, expecially in production.</p>\n\n<p>To avoid this issue, I normally have a \"main routine\" located in main plugin file, that I wrap in a <code>try</code> / <code>catch</code> block. This gives me the chance to catch the exception in production and prevent the fatal error.</p>\n\n<p>A rough example of a class:</p>\n\n<pre><code># myplugin/src/Foo.php\n\nnamespace MyPlugin;\n\nclass Foo {\n\n /**\n * @return bool\n */\n public function doSomething() {\n if ( ! get_option('my_plugin_everything_ok') ) {\n throw new SomethingWentWrongException('Something went wrong.');\n }\n\n // stuff here...\n\n return true;\n }\n}\n</code></pre>\n\n<p>and using it from main plugin file:</p>\n\n<pre><code># myplugin/main-plugin-file.php\n\nnamespace MyPlugin;\n\nfunction initialize() {\n\n try {\n\n $foo = new Foo();\n $foo-&gt;doSomething(); \n\n } catch(SomethingWentWrongException $e) {\n\n // on debug is better to notice when bad things happen\n if (defined('WP_DEBUG') &amp;&amp; WP_DEBUG) {\n throw $e;\n }\n\n // on production just fire an action, making exception accessible e.g. for logging\n do_action('my_plugin_error_shit_happened', $e);\n }\n}\n\nadd_action('wp_loaded', 'MyPlugin\\\\initialize');\n</code></pre>\n\n<p>Of course, in real world you may throw and catch different kinds of exception and behave differently according to the exception, but this should give you a direction.</p>\n\n<p>Another option I often use (and you don't mentioned) is to return objects that contain a flag to verify if no error happen, but keeping the return type consistency.</p>\n\n<p>This is a rough example of an object like that:</p>\n\n<pre><code>namespace MyPlugin;\n\nclass Options {\n\n private $options = [];\n private $ok = false;\n\n public function __construct($key)\n {\n $options = is_string($key) ? get_option($key) : false;\n if (is_array($options) &amp;&amp; $options) {\n $this-&gt;options = $options;\n $this-&gt;ok = true;\n }\n }\n\n public function isOk()\n {\n return $this-&gt;ok;\n }\n}\n</code></pre>\n\n<p>Now, from any place in your plugin, you can do:</p>\n\n<pre><code>/**\n * @return MyPlugin\\Options\n */\nfunction my_plugin_get_options() {\n return new MyPlugin\\Options('my_plugin_options');\n}\n\n$options = my_plugin_get_options();\nif ($options-&gt;isOk()) {\n // do stuff\n}\n</code></pre>\n\n<p>Note how <code>my_plugin_get_options()</code> above always returns an instance of <code>Options</code> class, in this way you can always pass the return value around, and even inject it to other objects that use type-hint with now worries that the type is different.</p>\n\n<p>If the function had returned <code>null</code> / <code>false</code> in case of error, before passing it around you had been forced to check if returned value is valid.</p>\n\n<p>At same time, you have a clearly way to understand is something is wrong with the option instance.</p>\n\n<p>This is a good solution in case the error is something that can be easily recovered, using defaults or whatever fits.</p>\n" }, { "answer_id": 379902, "author": "Shariq Hasan Khan", "author_id": 31670, "author_profile": "https://wordpress.stackexchange.com/users/31670", "pm_score": 0, "selected": false, "text": "<p>The answer by @gmazzap is quite exhaustive.</p>\n<p>Just to add a tiny bit to it:\nConsider an application with a registration form. Lets say you have a function which you use to validate the username submitted by the users.\nNow the supplied username may fail validation for a number of reasons, so returning just <code>false</code> isn't going to help the user much in letting them know what went wrong.\nThe better choice, in this case, would be to use WP_Error and to add error codes for each failed validation.</p>\n<p>Compare this:</p>\n<pre><code>function validate_username( $username ) {\n \n //No empty usernames\n if ( empty( $username ) ) {\n return false;\n }\n \n // Check for spaces\n if ( strpos( $username, ' ' ) !== false ) {\n return false;\n }\n\n // Check for length\n if ( strlen( $username ) &lt; 8 ) {\n return false;\n }\n\n // Check for length\n if ( ( strtolower( $username ) == $username ) || strtoupper( $username ) == $username ) ) {\n return false;\n }\n\n // Everything is fine\n return true;\n}\n</code></pre>\n<p>with this:</p>\n<pre><code>function validate_username( $username ) {\n \n //No empty usernames\n if ( empty( $username ) ) {\n $error-&gt;add( 'empty', 'Username can not be blank' );\n }\n \n // Check for spaces\n if ( strpos( $username, ' ' ) !== false ) {\n $error-&gt;add( 'spaces', 'Username can not contain spaces ' );\n }\n\n // Check for length\n if ( strlen( $username ) &lt; 8 ) {\n $error-&gt;add( 'short', 'Username should be at least 8 characters long ' );\n }\n\n // Check for length\n if ( ( strtolower( $username ) == $username ) || strtoupper( $username ) == $username ) ) {\n $error-&gt;add( 'case', 'Username should contain a mix of uppercase and lowercase characters ' );\n }\n\n // Send the result\n if ( empty( $error-&gt;get_error_codes() ) ) {\n return $error;\n }\n\n // Everything is fine\n return true;\n}\n</code></pre>\n<p>The first version gives the user absolutely no clue about what was wrong with the username they chose.\nThe second version adds description to errors, helping the user a lot.</p>\n<p>Hope this helps a bit.</p>\n" } ]
2016/02/21
[ "https://wordpress.stackexchange.com/questions/218393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87983/" ]
I'm in the process of writing a plugin and I'm trying to gauge when to use different approaches of handling errors. There are three methods I'm considering: * Throwing an Exception (custom class) * Returning an Error Object (extension of WP\_Error) * Just return null/false Some situations that I'm considering * Trying to get/set an option stored in the Registry that doesn't exist * Passing an invalid value to a method (which should be rare) * Calling a method that the class' overloader cannot resolve to Suggestions? Since writing a WordPress plugin has some special considerations, I'm not sure whether it would be worth asking this on a general PHP board.
I think it's impossible to give a definitive answer here, because choices like this are personal preference. Consider that what follows is *my* approach, and I have no presumption it is *the right* one. What I can say for sure is that you should avoid your third option: > > Just return null/false > > > This is bad under different aspect: * return type consinstency * makes functions harder to unit test * force conditional check on return type (`if (! is_null($thing))...`) making code harder to read I, more than often, use OOP to code plugins, and my object methods often throw exception when something goes wrong. Doing that, I: * accomplish return type consinstency * make the code simple to unit test * don't need conditional check on the returned type However, throwing exceptions in a WordPress plugin, means that nothing will *catch* them, ending up in a fatal error that is absolutely **not** desirable, expecially in production. To avoid this issue, I normally have a "main routine" located in main plugin file, that I wrap in a `try` / `catch` block. This gives me the chance to catch the exception in production and prevent the fatal error. A rough example of a class: ``` # myplugin/src/Foo.php namespace MyPlugin; class Foo { /** * @return bool */ public function doSomething() { if ( ! get_option('my_plugin_everything_ok') ) { throw new SomethingWentWrongException('Something went wrong.'); } // stuff here... return true; } } ``` and using it from main plugin file: ``` # myplugin/main-plugin-file.php namespace MyPlugin; function initialize() { try { $foo = new Foo(); $foo->doSomething(); } catch(SomethingWentWrongException $e) { // on debug is better to notice when bad things happen if (defined('WP_DEBUG') && WP_DEBUG) { throw $e; } // on production just fire an action, making exception accessible e.g. for logging do_action('my_plugin_error_shit_happened', $e); } } add_action('wp_loaded', 'MyPlugin\\initialize'); ``` Of course, in real world you may throw and catch different kinds of exception and behave differently according to the exception, but this should give you a direction. Another option I often use (and you don't mentioned) is to return objects that contain a flag to verify if no error happen, but keeping the return type consistency. This is a rough example of an object like that: ``` namespace MyPlugin; class Options { private $options = []; private $ok = false; public function __construct($key) { $options = is_string($key) ? get_option($key) : false; if (is_array($options) && $options) { $this->options = $options; $this->ok = true; } } public function isOk() { return $this->ok; } } ``` Now, from any place in your plugin, you can do: ``` /** * @return MyPlugin\Options */ function my_plugin_get_options() { return new MyPlugin\Options('my_plugin_options'); } $options = my_plugin_get_options(); if ($options->isOk()) { // do stuff } ``` Note how `my_plugin_get_options()` above always returns an instance of `Options` class, in this way you can always pass the return value around, and even inject it to other objects that use type-hint with now worries that the type is different. If the function had returned `null` / `false` in case of error, before passing it around you had been forced to check if returned value is valid. At same time, you have a clearly way to understand is something is wrong with the option instance. This is a good solution in case the error is something that can be easily recovered, using defaults or whatever fits.
218,400
<p>I am using the <a href="http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226" rel="nofollow noreferrer">Avada Theme</a> from Themeforest and I have set up 2 menus under <em>Appearances > Menu</em>: </p> <ul> <li><code>menu-logged-in</code> which contains a parent item (My Account) and then several child items; and</li> <li><code>menu-logged-out</code> which contains a single link to the <code>/my-account</code> page where users can log in or register.</li> </ul> <p>My intention hereafter is to dynamically show the relevant menu in the Theme location called <em>"Top Navigation"</em> depending on whether the user is logged in or is anonymous.</p> <p>I've added this code into my child theme's <code>function.php</code>:</p> <pre><code>add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 ); function add_loginout_link( $items, $args ) { if (is_user_logged_in() &amp;&amp; $args-&gt;theme_location == 'top_navigation') { $items .= '&lt;li&gt;&lt;a href="'. wp_logout_url() .'"&gt;Log Out&lt;/a&gt;&lt;/li&gt;'; //$items .= wp_nav_menu( array('menu' =&gt; 'menu-logged-in', 'container' =&gt; '') ); } elseif (!is_user_logged_in() &amp;&amp; $args-&gt;theme_location == 'top_navigation') { $items .= '&lt;li&gt;&lt;a href="'. site_url('wp-login.php') .'"&gt;Log In&lt;/a&gt;&lt;/li&gt;'; } return $items; } </code></pre> <p>Now this does work, but I would prefer to be able to call a Wordpress menu into the location instead of hard-coding these into the function. In the block above I have commented <strong>line 5</strong> that helps me achieve this, but it then renders a pre-formatted HTML &lt;UL&gt; at the very top of the page, and not where I want it to go.</p> <p><a href="https://i.stack.imgur.com/KR567.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KR567.png" alt="enter image description here"></a> </p> <p>I would be grateful if someone could please point me in the right direction. Thank you.</p>
[ { "answer_id": 230467, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>I think it's impossible to give a definitive answer here, because choices like this are personal preference.</p>\n\n<p>Consider that what follows is <em>my</em> approach, and I have no presumption it is <em>the right</em> one.</p>\n\n<p>What I can say for sure is that you should avoid your third option:</p>\n\n<blockquote>\n <p>Just return null/false</p>\n</blockquote>\n\n<p>This is bad under different aspect:</p>\n\n<ul>\n<li>return type consinstency</li>\n<li>makes functions harder to unit test</li>\n<li>force conditional check on return type (<code>if (! is_null($thing))...</code>) making code harder to read</li>\n</ul>\n\n<p>I, more than often, use OOP to code plugins, and my object methods often throw exception when something goes wrong.</p>\n\n<p>Doing that, I:</p>\n\n<ul>\n<li>accomplish return type consinstency</li>\n<li>make the code simple to unit test</li>\n<li>don't need conditional check on the returned type</li>\n</ul>\n\n<p>However, throwing exceptions in a WordPress plugin, means that nothing will <em>catch</em> them, ending up in a fatal error that is absolutely <strong>not</strong> desirable, expecially in production.</p>\n\n<p>To avoid this issue, I normally have a \"main routine\" located in main plugin file, that I wrap in a <code>try</code> / <code>catch</code> block. This gives me the chance to catch the exception in production and prevent the fatal error.</p>\n\n<p>A rough example of a class:</p>\n\n<pre><code># myplugin/src/Foo.php\n\nnamespace MyPlugin;\n\nclass Foo {\n\n /**\n * @return bool\n */\n public function doSomething() {\n if ( ! get_option('my_plugin_everything_ok') ) {\n throw new SomethingWentWrongException('Something went wrong.');\n }\n\n // stuff here...\n\n return true;\n }\n}\n</code></pre>\n\n<p>and using it from main plugin file:</p>\n\n<pre><code># myplugin/main-plugin-file.php\n\nnamespace MyPlugin;\n\nfunction initialize() {\n\n try {\n\n $foo = new Foo();\n $foo-&gt;doSomething(); \n\n } catch(SomethingWentWrongException $e) {\n\n // on debug is better to notice when bad things happen\n if (defined('WP_DEBUG') &amp;&amp; WP_DEBUG) {\n throw $e;\n }\n\n // on production just fire an action, making exception accessible e.g. for logging\n do_action('my_plugin_error_shit_happened', $e);\n }\n}\n\nadd_action('wp_loaded', 'MyPlugin\\\\initialize');\n</code></pre>\n\n<p>Of course, in real world you may throw and catch different kinds of exception and behave differently according to the exception, but this should give you a direction.</p>\n\n<p>Another option I often use (and you don't mentioned) is to return objects that contain a flag to verify if no error happen, but keeping the return type consistency.</p>\n\n<p>This is a rough example of an object like that:</p>\n\n<pre><code>namespace MyPlugin;\n\nclass Options {\n\n private $options = [];\n private $ok = false;\n\n public function __construct($key)\n {\n $options = is_string($key) ? get_option($key) : false;\n if (is_array($options) &amp;&amp; $options) {\n $this-&gt;options = $options;\n $this-&gt;ok = true;\n }\n }\n\n public function isOk()\n {\n return $this-&gt;ok;\n }\n}\n</code></pre>\n\n<p>Now, from any place in your plugin, you can do:</p>\n\n<pre><code>/**\n * @return MyPlugin\\Options\n */\nfunction my_plugin_get_options() {\n return new MyPlugin\\Options('my_plugin_options');\n}\n\n$options = my_plugin_get_options();\nif ($options-&gt;isOk()) {\n // do stuff\n}\n</code></pre>\n\n<p>Note how <code>my_plugin_get_options()</code> above always returns an instance of <code>Options</code> class, in this way you can always pass the return value around, and even inject it to other objects that use type-hint with now worries that the type is different.</p>\n\n<p>If the function had returned <code>null</code> / <code>false</code> in case of error, before passing it around you had been forced to check if returned value is valid.</p>\n\n<p>At same time, you have a clearly way to understand is something is wrong with the option instance.</p>\n\n<p>This is a good solution in case the error is something that can be easily recovered, using defaults or whatever fits.</p>\n" }, { "answer_id": 379902, "author": "Shariq Hasan Khan", "author_id": 31670, "author_profile": "https://wordpress.stackexchange.com/users/31670", "pm_score": 0, "selected": false, "text": "<p>The answer by @gmazzap is quite exhaustive.</p>\n<p>Just to add a tiny bit to it:\nConsider an application with a registration form. Lets say you have a function which you use to validate the username submitted by the users.\nNow the supplied username may fail validation for a number of reasons, so returning just <code>false</code> isn't going to help the user much in letting them know what went wrong.\nThe better choice, in this case, would be to use WP_Error and to add error codes for each failed validation.</p>\n<p>Compare this:</p>\n<pre><code>function validate_username( $username ) {\n \n //No empty usernames\n if ( empty( $username ) ) {\n return false;\n }\n \n // Check for spaces\n if ( strpos( $username, ' ' ) !== false ) {\n return false;\n }\n\n // Check for length\n if ( strlen( $username ) &lt; 8 ) {\n return false;\n }\n\n // Check for length\n if ( ( strtolower( $username ) == $username ) || strtoupper( $username ) == $username ) ) {\n return false;\n }\n\n // Everything is fine\n return true;\n}\n</code></pre>\n<p>with this:</p>\n<pre><code>function validate_username( $username ) {\n \n //No empty usernames\n if ( empty( $username ) ) {\n $error-&gt;add( 'empty', 'Username can not be blank' );\n }\n \n // Check for spaces\n if ( strpos( $username, ' ' ) !== false ) {\n $error-&gt;add( 'spaces', 'Username can not contain spaces ' );\n }\n\n // Check for length\n if ( strlen( $username ) &lt; 8 ) {\n $error-&gt;add( 'short', 'Username should be at least 8 characters long ' );\n }\n\n // Check for length\n if ( ( strtolower( $username ) == $username ) || strtoupper( $username ) == $username ) ) {\n $error-&gt;add( 'case', 'Username should contain a mix of uppercase and lowercase characters ' );\n }\n\n // Send the result\n if ( empty( $error-&gt;get_error_codes() ) ) {\n return $error;\n }\n\n // Everything is fine\n return true;\n}\n</code></pre>\n<p>The first version gives the user absolutely no clue about what was wrong with the username they chose.\nThe second version adds description to errors, helping the user a lot.</p>\n<p>Hope this helps a bit.</p>\n" } ]
2016/02/21
[ "https://wordpress.stackexchange.com/questions/218400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63160/" ]
I am using the [Avada Theme](http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226) from Themeforest and I have set up 2 menus under *Appearances > Menu*: * `menu-logged-in` which contains a parent item (My Account) and then several child items; and * `menu-logged-out` which contains a single link to the `/my-account` page where users can log in or register. My intention hereafter is to dynamically show the relevant menu in the Theme location called *"Top Navigation"* depending on whether the user is logged in or is anonymous. I've added this code into my child theme's `function.php`: ``` add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 ); function add_loginout_link( $items, $args ) { if (is_user_logged_in() && $args->theme_location == 'top_navigation') { $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>'; //$items .= wp_nav_menu( array('menu' => 'menu-logged-in', 'container' => '') ); } elseif (!is_user_logged_in() && $args->theme_location == 'top_navigation') { $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>'; } return $items; } ``` Now this does work, but I would prefer to be able to call a Wordpress menu into the location instead of hard-coding these into the function. In the block above I have commented **line 5** that helps me achieve this, but it then renders a pre-formatted HTML <UL> at the very top of the page, and not where I want it to go. [![enter image description here](https://i.stack.imgur.com/KR567.png)](https://i.stack.imgur.com/KR567.png) I would be grateful if someone could please point me in the right direction. Thank you.
I think it's impossible to give a definitive answer here, because choices like this are personal preference. Consider that what follows is *my* approach, and I have no presumption it is *the right* one. What I can say for sure is that you should avoid your third option: > > Just return null/false > > > This is bad under different aspect: * return type consinstency * makes functions harder to unit test * force conditional check on return type (`if (! is_null($thing))...`) making code harder to read I, more than often, use OOP to code plugins, and my object methods often throw exception when something goes wrong. Doing that, I: * accomplish return type consinstency * make the code simple to unit test * don't need conditional check on the returned type However, throwing exceptions in a WordPress plugin, means that nothing will *catch* them, ending up in a fatal error that is absolutely **not** desirable, expecially in production. To avoid this issue, I normally have a "main routine" located in main plugin file, that I wrap in a `try` / `catch` block. This gives me the chance to catch the exception in production and prevent the fatal error. A rough example of a class: ``` # myplugin/src/Foo.php namespace MyPlugin; class Foo { /** * @return bool */ public function doSomething() { if ( ! get_option('my_plugin_everything_ok') ) { throw new SomethingWentWrongException('Something went wrong.'); } // stuff here... return true; } } ``` and using it from main plugin file: ``` # myplugin/main-plugin-file.php namespace MyPlugin; function initialize() { try { $foo = new Foo(); $foo->doSomething(); } catch(SomethingWentWrongException $e) { // on debug is better to notice when bad things happen if (defined('WP_DEBUG') && WP_DEBUG) { throw $e; } // on production just fire an action, making exception accessible e.g. for logging do_action('my_plugin_error_shit_happened', $e); } } add_action('wp_loaded', 'MyPlugin\\initialize'); ``` Of course, in real world you may throw and catch different kinds of exception and behave differently according to the exception, but this should give you a direction. Another option I often use (and you don't mentioned) is to return objects that contain a flag to verify if no error happen, but keeping the return type consistency. This is a rough example of an object like that: ``` namespace MyPlugin; class Options { private $options = []; private $ok = false; public function __construct($key) { $options = is_string($key) ? get_option($key) : false; if (is_array($options) && $options) { $this->options = $options; $this->ok = true; } } public function isOk() { return $this->ok; } } ``` Now, from any place in your plugin, you can do: ``` /** * @return MyPlugin\Options */ function my_plugin_get_options() { return new MyPlugin\Options('my_plugin_options'); } $options = my_plugin_get_options(); if ($options->isOk()) { // do stuff } ``` Note how `my_plugin_get_options()` above always returns an instance of `Options` class, in this way you can always pass the return value around, and even inject it to other objects that use type-hint with now worries that the type is different. If the function had returned `null` / `false` in case of error, before passing it around you had been forced to check if returned value is valid. At same time, you have a clearly way to understand is something is wrong with the option instance. This is a good solution in case the error is something that can be easily recovered, using defaults or whatever fits.
218,452
<p>I want to enqueue stylesheet to plugin I'm developing, like this:</p> <pre><code>function utm_user_scripts() { $plugin_url = plugin_dir_url( __FILE__ ); wp_enqueue_style( 'style', $plugin_url . "/css/style.css"); } add_action( 'wp_enqueue_scripts', 'utm_user_scripts' ); </code></pre> <p>I am adding this code in the main file, [plugin_name].php.</p> <p>Nothing is loaded, which part am I doing wrong?</p>
[ { "answer_id": 218459, "author": "Stephen", "author_id": 85776, "author_profile": "https://wordpress.stackexchange.com/users/85776", "pm_score": 2, "selected": false, "text": "<p>I did a quick <a href=\"https://www.google.co.uk/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=wp%20enqueue%20style%20plugins%20url\" rel=\"nofollow noreferrer\">Google Search</a> on how to enqueue styles for Plugins and I've came across these two questions on WordPress StackExchange. You can find them below and hopefully they will help you solve your problem.</p>\n\n<p>Best of Luck :)</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/136655/wp-enqueue-style-for-plugin-with-multiple-stylesheets\">wp_enqueue_style for Plugin with multiple stylesheets</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/21561/where-is-the-right-place-to-register-enqueue-scripts-styles\">Where is the right place to register/enqueue scripts &amp; styles</a></p>\n" }, { "answer_id": 218580, "author": "ivanacorovic", "author_id": 84741, "author_profile": "https://wordpress.stackexchange.com/users/84741", "pm_score": 4, "selected": true, "text": "<p>Add this code in your main file: [plugin-name].php:</p>\n\n<pre><code> function utm_user_scripts() {\n $plugin_url = plugin_dir_url( __FILE__ );\n\n wp_enqueue_style( 'style', $plugin_url . \"/css/style.css\");\n }\n\n add_action( 'admin_print_styles', 'utm_user_scripts' );\n</code></pre>\n\n<p>So basically, you need to use 'admin_print_styles'. At least it did the trick for me.</p>\n" } ]
2016/02/22
[ "https://wordpress.stackexchange.com/questions/218452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84741/" ]
I want to enqueue stylesheet to plugin I'm developing, like this: ``` function utm_user_scripts() { $plugin_url = plugin_dir_url( __FILE__ ); wp_enqueue_style( 'style', $plugin_url . "/css/style.css"); } add_action( 'wp_enqueue_scripts', 'utm_user_scripts' ); ``` I am adding this code in the main file, [plugin\_name].php. Nothing is loaded, which part am I doing wrong?
Add this code in your main file: [plugin-name].php: ``` function utm_user_scripts() { $plugin_url = plugin_dir_url( __FILE__ ); wp_enqueue_style( 'style', $plugin_url . "/css/style.css"); } add_action( 'admin_print_styles', 'utm_user_scripts' ); ``` So basically, you need to use 'admin\_print\_styles'. At least it did the trick for me.
218,474
<p>If you enter <code>:)</code> in WordPress, it automatically replaces it with: </p> <p><a href="https://i.stack.imgur.com/tIOiv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tIOiv.png" alt="enter image description here"></a></p> <p>Is there a way to use a different smiley for the <code>:)</code></p>
[ { "answer_id": 218485, "author": "rob_st", "author_id": 29055, "author_profile": "https://wordpress.stackexchange.com/users/29055", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"https://codex.wordpress.org/Using_Smilies\" rel=\"nofollow\">WordPress Codex on using smilies</a>:</p>\n\n<blockquote>\n <p>Upload the images you want with the same name to your server (say in wp-content/images/smilies) and put this in your theme's function.php:</p>\n \n <p><pre>add_filter( 'smilies_src', 'my_custom_smilies_src', 10, 3 );\n function my_custom_smilies_src($img_src, $img, $siteurl){\n return $siteurl.'/wp-content/images/smilies/'.$img;\n }</pre>\n That will replace <a href=\"http://example.com/wp-includes/images/smilies/icon_question.gif\" rel=\"nofollow\">http://example.com/wp-includes/images/smilies/icon_question.gif</a> with <a href=\"http://example.com/wp-content/images/smilies/icon_question.gif\" rel=\"nofollow\">http://example.com/wp-content/images/smilies/icon_question.gif</a></p>\n</blockquote>\n" }, { "answer_id": 218496, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<h2>Overriding the emoji of :) to </h2>\n\n<p>The content smilies are converted with:</p>\n\n<pre><code>add_filter( 'the_content', 'convert_smilies' );\n</code></pre>\n\n<p>where <a href=\"https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/formatting.php#L2445\" rel=\"nofollow noreferrer\">this part</a> of the <code>convert_smilies()</code> function is of importance:</p>\n\n<pre><code>$content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );\n</code></pre>\n\n<p>If we peek into <code>translate_smiley()</code> then we find the <a href=\"https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/formatting.php#L2391-L2394\" rel=\"nofollow noreferrer\">following</a>:</p>\n\n<pre><code>// Don't convert smilies that aren't images - they're probably emoji.\nif ( ! in_array( $ext, $image_exts ) ) {\n return $img;\n}\n</code></pre>\n\n<p>before the <code>smilies_src</code> filter is applied. </p>\n\n<p>So this filter isn't available in the case of the <code>:)</code> smiley.</p>\n\n<p>We have the smilies initialized with:</p>\n\n<pre><code>add_action( 'init', 'smilies_init', 5 );\n</code></pre>\n\n<p>and within the function description for <code>smilies_init()</code> we can read the <a href=\"https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/functions.php#L3177-L3179\" rel=\"nofollow noreferrer\">following</a>:</p>\n\n<blockquote>\n <p>Plugins may override the default smiley list by setting the <code>$wpsmiliestrans</code>\n to an array, with the key the code the blogger types in and the value the\n image file.</p>\n</blockquote>\n\n<p>Here's the global <a href=\"https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/functions.php#L3200\" rel=\"nofollow noreferrer\"><code>$wpsmiliestrans</code></a> array:</p>\n\n<pre><code>$wpsmiliestrans = array(\n ':mrgreen:' =&gt; 'mrgreen.png',\n ':neutral:' =&gt; \"\\xf0\\x9f\\x98\\x90\",\n ':twisted:' =&gt; \"\\xf0\\x9f\\x98\\x88\",\n ':arrow:' =&gt; \"\\xe2\\x9e\\xa1\",\n ':shock:' =&gt; \"\\xf0\\x9f\\x98\\xaf\",\n ':smile:' =&gt; \"\\xf0\\x9f\\x99\\x82\",\n ':???:' =&gt; \"\\xf0\\x9f\\x98\\x95\",\n ':cool:' =&gt; \"\\xf0\\x9f\\x98\\x8e\",\n ':evil:' =&gt; \"\\xf0\\x9f\\x91\\xbf\",\n ':grin:' =&gt; \"\\xf0\\x9f\\x98\\x80\",\n ':idea:' =&gt; \"\\xf0\\x9f\\x92\\xa1\",\n ':oops:' =&gt; \"\\xf0\\x9f\\x98\\xb3\",\n ':razz:' =&gt; \"\\xf0\\x9f\\x98\\x9b\",\n ':roll:' =&gt; 'rolleyes.png',\n ':wink:' =&gt; \"\\xf0\\x9f\\x98\\x89\",\n ':cry:' =&gt; \"\\xf0\\x9f\\x98\\xa5\",\n ':eek:' =&gt; \"\\xf0\\x9f\\x98\\xae\",\n ':lol:' =&gt; \"\\xf0\\x9f\\x98\\x86\",\n ':mad:' =&gt; \"\\xf0\\x9f\\x98\\xa1\",\n ':sad:' =&gt; \"\\xf0\\x9f\\x99\\x81\",\n '8-)' =&gt; \"\\xf0\\x9f\\x98\\x8e\",\n '8-O' =&gt; \"\\xf0\\x9f\\x98\\xaf\",\n ':-(' =&gt; \"\\xf0\\x9f\\x99\\x81\",\n ':-)' =&gt; \"\\xf0\\x9f\\x99\\x82\",\n ':-?' =&gt; \"\\xf0\\x9f\\x98\\x95\",\n ':-D' =&gt; \"\\xf0\\x9f\\x98\\x80\",\n ':-P' =&gt; \"\\xf0\\x9f\\x98\\x9b\",\n ':-o' =&gt; \"\\xf0\\x9f\\x98\\xae\",\n ':-x' =&gt; \"\\xf0\\x9f\\x98\\xa1\",\n ':-|' =&gt; \"\\xf0\\x9f\\x98\\x90\",\n ';-)' =&gt; \"\\xf0\\x9f\\x98\\x89\",\n // This one transformation breaks regular text with frequency.\n // '8)' =&gt; \"\\xf0\\x9f\\x98\\x8e\",\n '8O' =&gt; \"\\xf0\\x9f\\x98\\xaf\",\n ':(' =&gt; \"\\xf0\\x9f\\x99\\x81\",\n ':)' =&gt; \"\\xf0\\x9f\\x99\\x82\",\n ':?' =&gt; \"\\xf0\\x9f\\x98\\x95\",\n ':D' =&gt; \"\\xf0\\x9f\\x98\\x80\",\n ':P' =&gt; \"\\xf0\\x9f\\x98\\x9b\",\n ':o' =&gt; \"\\xf0\\x9f\\x98\\xae\",\n ':x' =&gt; \"\\xf0\\x9f\\x98\\xa1\",\n ':|' =&gt; \"\\xf0\\x9f\\x98\\x90\",\n ';)' =&gt; \"\\xf0\\x9f\\x98\\x89\",\n ':!:' =&gt; \"\\xe2\\x9d\\x97\",\n ':?:' =&gt; \"\\xe2\\x9d\\x93\",\n);\n</code></pre>\n\n<p>or the nicer ksorted display:</p>\n\n<pre><code>Array\n(\n [;-)] =&gt; \n [;)] =&gt; \n [:|] =&gt; \n [:x] =&gt; \n [:wink:] =&gt; \n [:twisted:] =&gt; \n [:smile:] =&gt; \n [:shock:] =&gt; \n [:sad:] =&gt; \n [:roll:] =&gt; rolleyes.png\n [:razz:] =&gt; \n [:oops:] =&gt; \n [:o] =&gt; \n [:neutral:] =&gt; \n [:mrgreen:] =&gt; mrgreen.png\n [:mad:] =&gt; \n [:lol:] =&gt; \n [:idea:] =&gt; \n [:grin:] =&gt; \n [:evil:] =&gt; \n [:eek:] =&gt; \n [:cry:] =&gt; \n [:cool:] =&gt; \n [:arrow:] =&gt; ➡\n [:P] =&gt; \n [:D] =&gt; \n [:???:] =&gt; \n [:?:] =&gt; ❓\n [:?] =&gt; \n [:-|] =&gt; \n [:-x] =&gt; \n [:-o] =&gt; \n [:-P] =&gt; \n [:-D] =&gt; \n [:-?] =&gt; \n [:-)] =&gt; \n [:-(] =&gt; \n [:)] =&gt; \n [:(] =&gt; \n [:!:] =&gt; ❗\n [8O] =&gt; \n [8-O] =&gt; \n [8-)] =&gt; \n)\n</code></pre>\n\n<p>So if I correctly understand the above core comment, then we could do the following:</p>\n\n<pre><code>/**\n * :) as the cool emoji\n */\nadd_action( 'init', function() use ( &amp;$wpsmiliestrans )\n{\n if( is_array( $wpsmiliestrans ) &amp;&amp; get_option( 'use_smilies' ) )\n $wpsmiliestrans[':)'] = $wpsmiliestrans[':cool:'];\n\n}, 6 );\n</code></pre>\n\n<p>but this only works for predefined smiley keys, for the <code>$wp_smiliessearch</code> to work.</p>\n\n<p><em>But I don't like this suggested approach, modifying the global array! Hopefully there's another one better!</em> </p>\n\n<h2>Demo plugin - </h2>\n\n<p>I tried to come up with an application for this. I'm not sure if this already exists, but here it is:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Santa's Smile In December\n * Description: Change the emoji of :) to the Santa Claus emoji, but only in December\n * Plugin URI: https://wordpress.stackexchange.com/a/218496/26350\n */\nadd_action( 'init', function() use ( &amp;$wpsmiliestrans )\n{\n // :) as Santa Claus\n if( \n is_array( $wpsmiliestrans ) \n &amp;&amp; get_option( 'use_smilies' ) \n &amp;&amp; 12 == current_time( 'n' ) \n )\n $wpsmiliestrans[':)'] = \"\\xF0\\x9F\\x8E\\x85\";\n\n}, 6 );\n</code></pre>\n\n<p>Thanks to <strong>Ismael Miguel</strong> for the global <a href=\"https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319909_218496\">comment</a>, I rewrote the snippets accordingly.</p>\n\n<p>Here's the <a href=\"https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319904_218496\">newly created</a> ticket <a href=\"https://core.trac.wordpress.org/ticket/35905\" rel=\"nofollow noreferrer\">#35905</a> by <strong>Pieter Goosen</strong>, regarding a new <code>smilies_trans</code> filter.</p>\n\n<h2>Update - WordPress 4.7+</h2>\n\n<p>The new filter will be <a href=\"https://core.trac.wordpress.org/ticket/35905\" rel=\"nofollow noreferrer\">available</a> in WordPress 4.7+, but it's name will be <code>smilies</code> not <code>smilies_trans</code>.</p>\n\n<p>Our above examples can be written as:</p>\n\n<pre><code>add_filter( 'smilies', function( $smilies )\n{\n if( isset( $smilies[':cool:'] ) )\n $smilies[':)'] = $smilies[':cool:'];\n\n return $smilies;\n} );\n</code></pre>\n\n<p>or explicitly with:</p>\n\n<pre><code>add_filter( 'smilies', function( $smilies )\n{\n $smilies[':)'] = \"\\xf0\\x9f\\x98\\x8e\";\n\n return $smilies;\n} );\n</code></pre>\n\n<p>The demo plugin becomes:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Santa's Smile In December\n * Description: Change the emoji of :) to the Santa Claus emoji, but only in December\n * Plugin URI: https://wordpress.stackexchange.com/a/218496/26350\n */\n\nadd_filter( 'smilies', function( $smilies )\n{\n // :) as Santa Claus\n if( get_option( 'use_smilies' ) &amp;&amp; 12 == current_time( 'n' ) )\n $smilies[':)'] = \"\\xF0\\x9F\\x8E\\x85\";\n\n return $smilies;\n} );\n</code></pre>\n\n<p>We don't need to mess around with the global <code>$wpsmiliestrans</code> array anymore!</p>\n" } ]
2016/02/22
[ "https://wordpress.stackexchange.com/questions/218474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89209/" ]
If you enter `:)` in WordPress, it automatically replaces it with: [![enter image description here](https://i.stack.imgur.com/tIOiv.png)](https://i.stack.imgur.com/tIOiv.png) Is there a way to use a different smiley for the `:)`
Overriding the emoji of :) to ----------------------------- The content smilies are converted with: ``` add_filter( 'the_content', 'convert_smilies' ); ``` where [this part](https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/formatting.php#L2445) of the `convert_smilies()` function is of importance: ``` $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content ); ``` If we peek into `translate_smiley()` then we find the [following](https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/formatting.php#L2391-L2394): ``` // Don't convert smilies that aren't images - they're probably emoji. if ( ! in_array( $ext, $image_exts ) ) { return $img; } ``` before the `smilies_src` filter is applied. So this filter isn't available in the case of the `:)` smiley. We have the smilies initialized with: ``` add_action( 'init', 'smilies_init', 5 ); ``` and within the function description for `smilies_init()` we can read the [following](https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/functions.php#L3177-L3179): > > Plugins may override the default smiley list by setting the `$wpsmiliestrans` > to an array, with the key the code the blogger types in and the value the > image file. > > > Here's the global [`$wpsmiliestrans`](https://github.com/WordPress/WordPress/blob/ae2657dd32a273a5746354629252bb00c5df689f/wp-includes/functions.php#L3200) array: ``` $wpsmiliestrans = array( ':mrgreen:' => 'mrgreen.png', ':neutral:' => "\xf0\x9f\x98\x90", ':twisted:' => "\xf0\x9f\x98\x88", ':arrow:' => "\xe2\x9e\xa1", ':shock:' => "\xf0\x9f\x98\xaf", ':smile:' => "\xf0\x9f\x99\x82", ':???:' => "\xf0\x9f\x98\x95", ':cool:' => "\xf0\x9f\x98\x8e", ':evil:' => "\xf0\x9f\x91\xbf", ':grin:' => "\xf0\x9f\x98\x80", ':idea:' => "\xf0\x9f\x92\xa1", ':oops:' => "\xf0\x9f\x98\xb3", ':razz:' => "\xf0\x9f\x98\x9b", ':roll:' => 'rolleyes.png', ':wink:' => "\xf0\x9f\x98\x89", ':cry:' => "\xf0\x9f\x98\xa5", ':eek:' => "\xf0\x9f\x98\xae", ':lol:' => "\xf0\x9f\x98\x86", ':mad:' => "\xf0\x9f\x98\xa1", ':sad:' => "\xf0\x9f\x99\x81", '8-)' => "\xf0\x9f\x98\x8e", '8-O' => "\xf0\x9f\x98\xaf", ':-(' => "\xf0\x9f\x99\x81", ':-)' => "\xf0\x9f\x99\x82", ':-?' => "\xf0\x9f\x98\x95", ':-D' => "\xf0\x9f\x98\x80", ':-P' => "\xf0\x9f\x98\x9b", ':-o' => "\xf0\x9f\x98\xae", ':-x' => "\xf0\x9f\x98\xa1", ':-|' => "\xf0\x9f\x98\x90", ';-)' => "\xf0\x9f\x98\x89", // This one transformation breaks regular text with frequency. // '8)' => "\xf0\x9f\x98\x8e", '8O' => "\xf0\x9f\x98\xaf", ':(' => "\xf0\x9f\x99\x81", ':)' => "\xf0\x9f\x99\x82", ':?' => "\xf0\x9f\x98\x95", ':D' => "\xf0\x9f\x98\x80", ':P' => "\xf0\x9f\x98\x9b", ':o' => "\xf0\x9f\x98\xae", ':x' => "\xf0\x9f\x98\xa1", ':|' => "\xf0\x9f\x98\x90", ';)' => "\xf0\x9f\x98\x89", ':!:' => "\xe2\x9d\x97", ':?:' => "\xe2\x9d\x93", ); ``` or the nicer ksorted display: ``` Array ( [;-)] => [;)] => [:|] => [:x] => [:wink:] => [:twisted:] => [:smile:] => [:shock:] => [:sad:] => [:roll:] => rolleyes.png [:razz:] => [:oops:] => [:o] => [:neutral:] => [:mrgreen:] => mrgreen.png [:mad:] => [:lol:] => [:idea:] => [:grin:] => [:evil:] => [:eek:] => [:cry:] => [:cool:] => [:arrow:] => ➡ [:P] => [:D] => [:???:] => [:?:] => ❓ [:?] => [:-|] => [:-x] => [:-o] => [:-P] => [:-D] => [:-?] => [:-)] => [:-(] => [:)] => [:(] => [:!:] => ❗ [8O] => [8-O] => [8-)] => ) ``` So if I correctly understand the above core comment, then we could do the following: ``` /** * :) as the cool emoji */ add_action( 'init', function() use ( &$wpsmiliestrans ) { if( is_array( $wpsmiliestrans ) && get_option( 'use_smilies' ) ) $wpsmiliestrans[':)'] = $wpsmiliestrans[':cool:']; }, 6 ); ``` but this only works for predefined smiley keys, for the `$wp_smiliessearch` to work. *But I don't like this suggested approach, modifying the global array! Hopefully there's another one better!* Demo plugin - ------------- I tried to come up with an application for this. I'm not sure if this already exists, but here it is: ``` <?php /** * Plugin Name: Santa's Smile In December * Description: Change the emoji of :) to the Santa Claus emoji, but only in December * Plugin URI: https://wordpress.stackexchange.com/a/218496/26350 */ add_action( 'init', function() use ( &$wpsmiliestrans ) { // :) as Santa Claus if( is_array( $wpsmiliestrans ) && get_option( 'use_smilies' ) && 12 == current_time( 'n' ) ) $wpsmiliestrans[':)'] = "\xF0\x9F\x8E\x85"; }, 6 ); ``` Thanks to **Ismael Miguel** for the global [comment](https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319909_218496), I rewrote the snippets accordingly. Here's the [newly created](https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319904_218496) ticket [#35905](https://core.trac.wordpress.org/ticket/35905) by **Pieter Goosen**, regarding a new `smilies_trans` filter. Update - WordPress 4.7+ ----------------------- The new filter will be [available](https://core.trac.wordpress.org/ticket/35905) in WordPress 4.7+, but it's name will be `smilies` not `smilies_trans`. Our above examples can be written as: ``` add_filter( 'smilies', function( $smilies ) { if( isset( $smilies[':cool:'] ) ) $smilies[':)'] = $smilies[':cool:']; return $smilies; } ); ``` or explicitly with: ``` add_filter( 'smilies', function( $smilies ) { $smilies[':)'] = "\xf0\x9f\x98\x8e"; return $smilies; } ); ``` The demo plugin becomes: ``` <?php /** * Plugin Name: Santa's Smile In December * Description: Change the emoji of :) to the Santa Claus emoji, but only in December * Plugin URI: https://wordpress.stackexchange.com/a/218496/26350 */ add_filter( 'smilies', function( $smilies ) { // :) as Santa Claus if( get_option( 'use_smilies' ) && 12 == current_time( 'n' ) ) $smilies[':)'] = "\xF0\x9F\x8E\x85"; return $smilies; } ); ``` We don't need to mess around with the global `$wpsmiliestrans` array anymore!
218,488
<p>I have the following code. I have a left div and a right div. How would I edit the below code to pull the first X CPT data and put it in the right column, and the next XX number CPT data to put in the left column? Right now I am just printing same query in the two columns. Any help would be greatly appreciated.</p> <pre><code>&lt;div class="generic-page-container clearfix smallwidth"&gt; &lt;div class="content_left"&gt; &lt;?php $args = array( 'post_type' =&gt; 'testimonials', 'posts_per_page' =&gt; 10 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); //the_title(); echo '&lt;div class="testimonials_block"&gt;'; the_content(); echo '&lt;/div&gt;'; endwhile; ?&gt; &lt;/div&gt;&lt;!--/#content_left --&gt; &lt;div class="content_right"&gt; &lt;?php $args = array( 'post_type' =&gt; 'testimonials', 'posts_per_page' =&gt; 10 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); //the_title(); echo '&lt;div class="testimonials_block"&gt;'; the_content(); echo '&lt;/div&gt;'; endwhile; ?&gt; &lt;/div&gt;&lt;!--/#content_right --&gt; &lt;/div&gt;&lt;!--#generic-page-container --&gt; </code></pre>
[ { "answer_id": 218495, "author": "MartinJJ", "author_id": 3710, "author_profile": "https://wordpress.stackexchange.com/users/3710", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/WordPress_Backups\" rel=\"nofollow\">WP Codex</a> is your friend on this one as the only real answer is to do your back ups the way that you feel most confident with, be that manually or with plugins, if you have multiple sites then manually backing up/creating theme copies/plugin copies etc could become a labor intensive chore.</p>\n\n<p>The codex page i have linked to also contains a link in the opening lines to plugins that do the task should that be the path you require to take, most of them do what you require in one way or another, but one in particular has 600,000 plus installs and user ratings most plugin devs would be envious of, the devs also claim it will back up automatically before any update to WP, Plugins or Themes. </p>\n" }, { "answer_id": 218497, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>This is the reason I always recommend to use the least amount of plugins. This obviously easier to say then do, but if you are a developer you should strive to eliminate all plugins by incorporating the relevant code into a site specific plugin or theme. Integrators obviously have less ability to achieve this.</p>\n\n<p>The problem with the upgrades is not so much with having the dev/staging enviroment. You can probably just keep it, or have some tool that syncs the production into them, the real problem is to have a proper QA plan to verify that nothing broke. QA is a time consuming affair and even if you know how to write unit tests, some things just need a human to use a browser to test them.</p>\n\n<p>The easiest solution to the problem is not to upgrade when new versions come out, but do it only when you upgrade core to bundle all testing together. For this to work without putting yourself in a security risk you need to follow the development of the themes/plugins that are being used to know when an update is done because of security issue or because there is some new feature. If it is a new feature, there is no real need to rush upgrading it.</p>\n" } ]
2016/02/22
[ "https://wordpress.stackexchange.com/questions/218488", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
I have the following code. I have a left div and a right div. How would I edit the below code to pull the first X CPT data and put it in the right column, and the next XX number CPT data to put in the left column? Right now I am just printing same query in the two columns. Any help would be greatly appreciated. ``` <div class="generic-page-container clearfix smallwidth"> <div class="content_left"> <?php $args = array( 'post_type' => 'testimonials', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); //the_title(); echo '<div class="testimonials_block">'; the_content(); echo '</div>'; endwhile; ?> </div><!--/#content_left --> <div class="content_right"> <?php $args = array( 'post_type' => 'testimonials', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); //the_title(); echo '<div class="testimonials_block">'; the_content(); echo '</div>'; endwhile; ?> </div><!--/#content_right --> </div><!--#generic-page-container --> ```
This is the reason I always recommend to use the least amount of plugins. This obviously easier to say then do, but if you are a developer you should strive to eliminate all plugins by incorporating the relevant code into a site specific plugin or theme. Integrators obviously have less ability to achieve this. The problem with the upgrades is not so much with having the dev/staging enviroment. You can probably just keep it, or have some tool that syncs the production into them, the real problem is to have a proper QA plan to verify that nothing broke. QA is a time consuming affair and even if you know how to write unit tests, some things just need a human to use a browser to test them. The easiest solution to the problem is not to upgrade when new versions come out, but do it only when you upgrade core to bundle all testing together. For this to work without putting yourself in a security risk you need to follow the development of the themes/plugins that are being used to know when an update is done because of security issue or because there is some new feature. If it is a new feature, there is no real need to rush upgrading it.
218,610
<p>I've created a child theme and the main style.css works perfectly fine. However, the parent theme has another stylesheet which I want to import and create the same for child theme and use it instead.</p> <blockquote> <p>Parent theme structure - ./woocommerce/woo.css <br> Child theme structure - ./woocommerce/woo.css (Manually created)</p> </blockquote> <p>Now, I enqueued both the stylesheets in the child theme's function.php as below.</p> <pre><code>function fruitful_load_parent_stylesheets() { wp_enqueue_style( 'layout', get_template_directory_uri() . '/woocommerce/woo.css' ); } add_action( 'wp_enqueue_scripts', 'fruitful_load_parent_stylesheets' ); function fruitful_load_child_stylesheets(){ wp_enqueue_style( 'woo', get_stylesheet_directory_uri() . '/woocommerce/woo.css'); } add_action('wp_enqueue_scripts', 'fruitful_load_child_stylesheets'); </code></pre> <p>Now, if I add a style to the child theme's woo.css, it doesn't work until I <strong>!important</strong> it.I just don't want to go doing it on every style I add.</p> <p>is</p>
[ { "answer_id": 218616, "author": "goalsquid", "author_id": 67191, "author_profile": "https://wordpress.stackexchange.com/users/67191", "pm_score": 3, "selected": false, "text": "<p>Perhaps you can try adding a priority value to each add_action to make sure that one executes before the other.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'fruitful_load_parent_stylesheets', 10 );\nadd_action('wp_enqueue_scripts', 'fruitful_load_child_stylesheets', 20 );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"noreferrer\">WordPress Codex add_action()</a></p>\n" }, { "answer_id": 218622, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 4, "selected": true, "text": "<p>Your child theme's <code>stylesheet</code> will usually be loaded automatically. If it is not, you will need to <code>enqueue</code> it as well. Setting 'parent-style' as a dependency will ensure that the child theme <code>stylesheet</code> loads after it.</p>\n\n<pre><code>/**\n * Enqueue theme styles (parent first, child second)\n * \n */\nfunction wpse218610_theme_styles() {\n\n $parent_style = 'parent-style';\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/woocommerce/woo.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/woocommerce/woo.css', array( $parent_style ) );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse218610_theme_styles' );\n</code></pre>\n\n<blockquote>\n <p>Note: take a look in the <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet\" rel=\"nofollow noreferrer\">Theme Developer Handbook</a> for some extra information.</p>\n</blockquote>\n" }, { "answer_id": 298105, "author": "Vemman", "author_id": 45420, "author_profile": "https://wordpress.stackexchange.com/users/45420", "pm_score": 2, "selected": false, "text": "<p>I got to load child theme later like below. I had to dequeue &amp; deregister parent style, then enqueue parent style &amp; child style. Hope this helps</p>\n\n<p>Parent <code>functions.php</code> has </p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'load_parent_style', 10);\nfunction load_parent_style() {\n wp_enqueue_style('parent-theme-style'); // parent theme code\n}\n</code></pre>\n\n<p>Child <code>functions.php</code> has</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'load_child_style', 20);\nfunction load_child_style() {\n //register &amp; enqueue parent with new name \n wp_register_style('parent-style', $url, array($deps));\n wp_enqueue_style('parent-style'); \n\n // dequeue &amp; deregister parent's theme handle\n wp_dequeue_style('parent-theme-style'); // from parent theme\n wp_deregister_style('parent-theme-style'); \n\n // register &amp; enqueue child style\n wp_register_style('child-style', get_stylesheet_uri(), array('parent-style'));\n wp_enqueue_style('child-style');\n}\n</code></pre>\n" } ]
2016/02/23
[ "https://wordpress.stackexchange.com/questions/218610", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33650/" ]
I've created a child theme and the main style.css works perfectly fine. However, the parent theme has another stylesheet which I want to import and create the same for child theme and use it instead. > > Parent theme structure - ./woocommerce/woo.css > > Child theme structure - ./woocommerce/woo.css (Manually created) > > > Now, I enqueued both the stylesheets in the child theme's function.php as below. ``` function fruitful_load_parent_stylesheets() { wp_enqueue_style( 'layout', get_template_directory_uri() . '/woocommerce/woo.css' ); } add_action( 'wp_enqueue_scripts', 'fruitful_load_parent_stylesheets' ); function fruitful_load_child_stylesheets(){ wp_enqueue_style( 'woo', get_stylesheet_directory_uri() . '/woocommerce/woo.css'); } add_action('wp_enqueue_scripts', 'fruitful_load_child_stylesheets'); ``` Now, if I add a style to the child theme's woo.css, it doesn't work until I **!important** it.I just don't want to go doing it on every style I add. is
Your child theme's `stylesheet` will usually be loaded automatically. If it is not, you will need to `enqueue` it as well. Setting 'parent-style' as a dependency will ensure that the child theme `stylesheet` loads after it. ``` /** * Enqueue theme styles (parent first, child second) * */ function wpse218610_theme_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/woocommerce/woo.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/woocommerce/woo.css', array( $parent_style ) ); } add_action( 'wp_enqueue_scripts', 'wpse218610_theme_styles' ); ``` > > Note: take a look in the [Theme Developer Handbook](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet) for some extra information. > > >
218,634
<p>I am having difficulty overriding the title set in the admin panel for a custom template page, and outputting a custom <code>&lt;title&gt;</code> tag.</p> <p>The parent theme is WordPress's stock Twentysixteen, which uses the <a href="https://codex.wordpress.org/Title_Tag" rel="nofollow">title-tag theme feature</a> (as opposed to the soon-to-be deprecated function wp_title() ). According to <a href="https://developer.wordpress.org/reference/functions/wp_title/" rel="nofollow">WordPress Code Reference</a>, the correct hook is the <code>wp_title</code> filter:</p> <blockquote> <p>The wp_title filter is used to filter the title of the page (called with wp_title()). This filters the text appearing in the HTML tag (sometimes called the “title tag” or “meta title”), not the post, page, or category title.</p> </blockquote> <p>So I should be able to simply create a conditional test in my functions.php file and override the title tag created by WordPress there, e.g.:</p> <pre><code> function custom_filter_wp_title( $title, $sep ) { // removed conditional to prove not working anywhere // if ( is_page_template( 'sometemplate.php' ) ) { $title = "My custom template page..."; // } return $title; } add_filter( 'wp_title', 'custom_filter_wp_title', 10, 2 ); </code></pre> <p>Derived from <a href="https://developer.wordpress.org/reference/hooks/wp_title/" rel="nofollow">Codex example</a>.</p> <p>As far as I can tell, this custom filter is working nowhere, the title set in the back end is appearing in the HTML header's title tag. I have elevated the priority to 99999, still nothing. What am I doing wrong?</p>
[ { "answer_id": 237616, "author": "Andrew T", "author_id": 13977, "author_profile": "https://wordpress.stackexchange.com/users/13977", "pm_score": 1, "selected": false, "text": "<p>We have found this for shortcode support in titles (both header and post title):</p>\n\n<pre><code>//shortcode support in titles\nadd_filter( 'the_title', 'do_shortcode' ); //should be post title\nadd_filter( 'wp_title', 'do_shortcode' ); //should be HTML/Browser title\nadd_filter( 'document_title_parts', 'wp44_header_title_function' ); //own function for HTML/Browser title\nfunction wp44_header_title_function($title) {\n if (isset($title['title'])) $title['title'] = do_shortcode($title['title']);\n if (isset($title['page'])) $title['page'] = do_shortcode($title['page']);\n if (isset($title['tagline'])) $title['tagline'] = do_shortcode($title['tagline']);\n if (isset($title['site'])) $title['site'] = do_shortcode($title['site']);\n return $title;\n}\n</code></pre>\n\n<p>I called it wp44 because in /wp-includes/general-template.php it says that this was added in 4.4 to \"Filter the document title before it is generated.\"</p>\n\n<p>I think the standard wp_title filter should work but I know we're using a crazy theme that does its own thing and looks like for that theme at least document_title_parts is the way to go.</p>\n" }, { "answer_id": 255490, "author": "Erin", "author_id": 112725, "author_profile": "https://wordpress.stackexchange.com/users/112725", "pm_score": 2, "selected": false, "text": "<p>If anyone else is having problems with this, it may be due to the Yoast plugin. Use:</p>\n\n<pre><code>add_filter( 'pre_get_document_title', function( $title ){\n // Make any changes here\n return $title;\n}, 999, 1 );\n</code></pre>\n" } ]
2016/02/23
[ "https://wordpress.stackexchange.com/questions/218634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31403/" ]
I am having difficulty overriding the title set in the admin panel for a custom template page, and outputting a custom `<title>` tag. The parent theme is WordPress's stock Twentysixteen, which uses the [title-tag theme feature](https://codex.wordpress.org/Title_Tag) (as opposed to the soon-to-be deprecated function wp\_title() ). According to [WordPress Code Reference](https://developer.wordpress.org/reference/functions/wp_title/), the correct hook is the `wp_title` filter: > > The wp\_title filter is used to filter the title of the page (called > with wp\_title()). This filters the text appearing in the HTML > tag (sometimes called the “title tag” or “meta title”), not the post, > page, or category title. > > > So I should be able to simply create a conditional test in my functions.php file and override the title tag created by WordPress there, e.g.: ``` function custom_filter_wp_title( $title, $sep ) { // removed conditional to prove not working anywhere // if ( is_page_template( 'sometemplate.php' ) ) { $title = "My custom template page..."; // } return $title; } add_filter( 'wp_title', 'custom_filter_wp_title', 10, 2 ); ``` Derived from [Codex example](https://developer.wordpress.org/reference/hooks/wp_title/). As far as I can tell, this custom filter is working nowhere, the title set in the back end is appearing in the HTML header's title tag. I have elevated the priority to 99999, still nothing. What am I doing wrong?
If anyone else is having problems with this, it may be due to the Yoast plugin. Use: ``` add_filter( 'pre_get_document_title', function( $title ){ // Make any changes here return $title; }, 999, 1 ); ```
218,641
<p>Here is a snippet of my code</p> <pre><code> &lt;?php echo apply_filters( 'woocommerce_order_button_html', '&lt;input type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" /&gt;' ); ?&gt; &lt;?php if ( wc_get_page_id( 'terms' ) &gt; 0 &amp;&amp; apply_filters( 'woocommerce_checkout_show_terms', true ) ) : ?&gt; &lt;p class="form-row terms"&gt; &lt;label for="terms" class="checkbox"&gt;&lt;?php printf( __( 'I&amp;rsquo;ve read and accept the &lt;a href="%s" target="_blank"&gt;terms &amp;amp; conditions&lt;/a&gt;', 'yit' ), esc_url( get_permalink( wc_get_page_id( 'terms' ) ) ) ); ?&gt;&lt;/label&gt; &lt;input type="checkbox" class="input-checkbox" name="terms" &lt;?php checked( apply_filters( 'woocommerce_terms_is_checked_default', isset( $_POST['terms'] ) ), true ); ?&gt; id="terms" /&gt; &lt;/p&gt; &lt;p class="subscribe"&gt; Subscribe to get discounts, coupons and tips &lt;?php include "/home/edcthings/public_html/wp-content/plugins/yith-essential-kit-for-woocommerce-1/modules/yith-woocommerce-mailchimp/templates/mailchimp-subscription-checkbox.php" ?&gt; &lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php do_action( 'woocommerce_review_order_after_submit' ); ?&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; </code></pre> <p>I need to disable the submit button but still allow it to process. I've found the javascript that should work with this form but it doesn't.</p> <pre><code>$(function(){ $(".button").click(function () { $(".button").attr("disabled", true); $('#cart-table').submit(); }); }); </code></pre> <p>Receive a console error "Uncaught TypeError: $ is not a function"</p> <p>Edit: I figured out why the errors were occurring. I changed the code to function correct in WordPress...</p> <pre><code> &lt;script type="text/javascript" charset="utf-8"&gt; jQuery(document).ready(function($){ $(".button").click(function () { $(".button").attr("disabled", true); $('#checkout').submit(); }); }); &lt;/script&gt; </code></pre> <p>This makes the button disable but still doesn't allow the form to submit</p>
[ { "answer_id": 218644, "author": "Tom Kentell", "author_id": 88813, "author_profile": "https://wordpress.stackexchange.com/users/88813", "pm_score": 0, "selected": false, "text": "<p>Are you targeting the right class there? Not sure if that's just example code. But I can't see that class on your button.</p>\n\n<p>Also, it should be attr(\"disabled\", \"disabled\") or just the attribute disabled. It doesn't need a value for HTML5.</p>\n" }, { "answer_id": 218655, "author": "bkcol", "author_id": 89127, "author_profile": "https://wordpress.stackexchange.com/users/89127", "pm_score": 1, "selected": false, "text": "<p>Fixed the issue. Was calling the incorrect IDs. Below is the code I used for anybody else wanting to achieve the same outcome.</p>\n\n<pre><code>&lt;script type=\"text/javascript\" charset=\"utf-8\"&gt;\njQuery(document).ready(function($){\n $(\".button#place_order\").click(function () {\n $(\".button#place_order\").attr(\"disabled\", true);\n $('.checkout').submit();\n });\n});\n&lt;/script&gt;\n</code></pre>\n" } ]
2016/02/23
[ "https://wordpress.stackexchange.com/questions/218641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89127/" ]
Here is a snippet of my code ``` <?php echo apply_filters( 'woocommerce_order_button_html', '<input type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" />' ); ?> <?php if ( wc_get_page_id( 'terms' ) > 0 && apply_filters( 'woocommerce_checkout_show_terms', true ) ) : ?> <p class="form-row terms"> <label for="terms" class="checkbox"><?php printf( __( 'I&rsquo;ve read and accept the <a href="%s" target="_blank">terms &amp; conditions</a>', 'yit' ), esc_url( get_permalink( wc_get_page_id( 'terms' ) ) ) ); ?></label> <input type="checkbox" class="input-checkbox" name="terms" <?php checked( apply_filters( 'woocommerce_terms_is_checked_default', isset( $_POST['terms'] ) ), true ); ?> id="terms" /> </p> <p class="subscribe"> Subscribe to get discounts, coupons and tips <?php include "/home/edcthings/public_html/wp-content/plugins/yith-essential-kit-for-woocommerce-1/modules/yith-woocommerce-mailchimp/templates/mailchimp-subscription-checkbox.php" ?> </p> <?php endif; ?> <?php do_action( 'woocommerce_review_order_after_submit' ); ?> </div> <div class="clear"></div> ``` I need to disable the submit button but still allow it to process. I've found the javascript that should work with this form but it doesn't. ``` $(function(){ $(".button").click(function () { $(".button").attr("disabled", true); $('#cart-table').submit(); }); }); ``` Receive a console error "Uncaught TypeError: $ is not a function" Edit: I figured out why the errors were occurring. I changed the code to function correct in WordPress... ``` <script type="text/javascript" charset="utf-8"> jQuery(document).ready(function($){ $(".button").click(function () { $(".button").attr("disabled", true); $('#checkout').submit(); }); }); </script> ``` This makes the button disable but still doesn't allow the form to submit
Fixed the issue. Was calling the incorrect IDs. Below is the code I used for anybody else wanting to achieve the same outcome. ``` <script type="text/javascript" charset="utf-8"> jQuery(document).ready(function($){ $(".button#place_order").click(function () { $(".button#place_order").attr("disabled", true); $('.checkout').submit(); }); }); </script> ```
218,689
<p>On a website made with a purchased template, a custom post-type had an archive page. I didn't want that archive page, so I altered the custom post-type in a child-theme like so:</p> <pre><code>function remove_archive(){ $portfolio = get_post_type_object( 'portfolio' ); $portfolio-&gt;has_archive = FALSE; register_post_type( 'portfolio', $portfolio ); } add_action( 'init', 'remove_archive', 20 ); </code></pre> <p>This removed the custom post-type archive. However, it was my intention that the url /portfolio would be freed up for use for a page. But even after refreshing the permalinks, clearing caches etc. the url doesn't point to the page. Instead it points to the blog page, which hasn't been set in the settings at all.</p> <p>The solution should be a situation in where <code>/portfolio</code> is a page, and <code>/portfolio/*</code> is the URL structure for the posts. However, at this moment, that is not working in any way.</p> <p>Am I missing something?</p> <h2>Edit</h2> <p>As per Pieter's comment, I've added the template filter <code>template_include</code>:</p> <pre><code>function uncode_redirect_page($original_template) { global $is_redirect; $is_redirect_active = ot_get_option('_uncode_redirect'); if ($is_redirect_active === 'on') { if(! is_user_logged_in() ) { $is_redirect = true; return get_template_directory() . '/redirect-page.php'; } } return $original_template; } add_filter('template_include', 'uncode_redirect_page'); </code></pre>
[ { "answer_id": 218821, "author": "Piyush Dhanotiya", "author_id": 74324, "author_profile": "https://wordpress.stackexchange.com/users/74324", "pm_score": 0, "selected": false, "text": "<p>The archive page is created according to the name of slug of post type so if you want to portfolio as simple page not the archive page just change the slug of portfolio post type. It will solve your problem.</p>\n\n<pre><code>$labels = array(\n 'name' =&gt; _x( 'Blog', 'post type general name', 'your-plugin-textdomain' ),\n 'singular_name' =&gt; _x( 'Blog', 'post type singular name', 'your-plugin-textdomain' ),\n 'menu_name' =&gt; _x( 'Blog', 'admin menu', 'your-plugin-textdomain' ),\n 'name_admin_bar' =&gt; _x( 'Blog', 'add new on admin bar', 'your-plugin-textdomain' ),\n 'add_new' =&gt; _x( 'Add New', 'Blog', 'your-plugin-textdomain' ),\n 'add_new_item' =&gt; __( 'Add New Blog', 'your-plugin-textdomain' ),\n 'new_item' =&gt; __( 'New Blog', 'your-plugin-textdomain' ),\n 'edit_item' =&gt; __( 'Edit Blog', 'your-plugin-textdomain' ),\n 'view_item' =&gt; __( 'View Blog', 'your-plugin-textdomain' ),\n 'all_items' =&gt; __( 'All Blog', 'your-plugin-textdomain' ),\n 'search_items' =&gt; __( 'Search Blog', 'your-plugin-textdomain' ),\n 'parent_item_colon' =&gt; __( 'Parent Blog:', 'your-plugin-textdomain' ),\n 'not_found' =&gt; __( 'No Blog found.', 'your-plugin-textdomain' ),\n 'not_found_in_trash' =&gt; __( 'No Blog found in Trash.', 'your-plugin-textdomain' )\n );\n\n $args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'test' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt',)\n );\n register_post_type( 'Blog', $args );\n</code></pre>\n" }, { "answer_id": 218887, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>If you are using WordPress 4.4+ (<em>which you should</em>), you can make use of the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"nofollow\"><code>register_post_type_args</code></a> filter to adjust the arguments passed to <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow\"><code>register_post_type()</code></a> when the post type is registered. In your child theme, you can do the following</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $post_type )\n{\n // Make sure we only target the portfolio post type\n if ( 'portfolio' !== $post_type )\n return $args;\n\n /**\n * We are currently registering the portfolio post type, lets continue\n * For debugging purposes, you can do the following inside the filter\n * ?&gt;&lt;pre&gt;&lt;?php var_dump($args); ?&gt;&lt;/pre&gt;&lt;?php\n *\n * Modify the arguments as needed\n */\n $args['has_archive'] = false;\n $args['rewrite'] = true;\n\n return $args; \n}, PHP_INT_MAX, 2);\n</code></pre>\n\n<p>Just remember to flush your rewrite rules after adding the filter. Make sure you adjust the filter to your needs. This should take care of the template load, you should see the page loaded which you created in the back end when you visit <code>http://example.com/portfolio/</code> (<em>if your created page has a slug of <code>portfolio</code>, ie a permalink structure of <code>http://example.com/portfolio/</code></em>).</p>\n\n<p>If this does not work, you have something inside your theme which is causing this issue, more likely a <code>pre_get_posts</code> action which is suppose to target the <code>portfolio</code> post type page. You should also consider a bad rewrite as well</p>\n\n<h2>EDIT</h2>\n\n<p>The final issue was that the <code>template_include</code> filter as mentioned in the question was causing the issue. Removing the filter in the child theme and reflushing the permalinks solved the issue</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218689", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34027/" ]
On a website made with a purchased template, a custom post-type had an archive page. I didn't want that archive page, so I altered the custom post-type in a child-theme like so: ``` function remove_archive(){ $portfolio = get_post_type_object( 'portfolio' ); $portfolio->has_archive = FALSE; register_post_type( 'portfolio', $portfolio ); } add_action( 'init', 'remove_archive', 20 ); ``` This removed the custom post-type archive. However, it was my intention that the url /portfolio would be freed up for use for a page. But even after refreshing the permalinks, clearing caches etc. the url doesn't point to the page. Instead it points to the blog page, which hasn't been set in the settings at all. The solution should be a situation in where `/portfolio` is a page, and `/portfolio/*` is the URL structure for the posts. However, at this moment, that is not working in any way. Am I missing something? Edit ---- As per Pieter's comment, I've added the template filter `template_include`: ``` function uncode_redirect_page($original_template) { global $is_redirect; $is_redirect_active = ot_get_option('_uncode_redirect'); if ($is_redirect_active === 'on') { if(! is_user_logged_in() ) { $is_redirect = true; return get_template_directory() . '/redirect-page.php'; } } return $original_template; } add_filter('template_include', 'uncode_redirect_page'); ```
If you are using WordPress 4.4+ (*which you should*), you can make use of the [`register_post_type_args`](https://developer.wordpress.org/reference/hooks/register_post_type_args/) filter to adjust the arguments passed to [`register_post_type()`](https://developer.wordpress.org/reference/functions/register_post_type/) when the post type is registered. In your child theme, you can do the following ``` add_filter( 'register_post_type_args', function( $args, $post_type ) { // Make sure we only target the portfolio post type if ( 'portfolio' !== $post_type ) return $args; /** * We are currently registering the portfolio post type, lets continue * For debugging purposes, you can do the following inside the filter * ?><pre><?php var_dump($args); ?></pre><?php * * Modify the arguments as needed */ $args['has_archive'] = false; $args['rewrite'] = true; return $args; }, PHP_INT_MAX, 2); ``` Just remember to flush your rewrite rules after adding the filter. Make sure you adjust the filter to your needs. This should take care of the template load, you should see the page loaded which you created in the back end when you visit `http://example.com/portfolio/` (*if your created page has a slug of `portfolio`, ie a permalink structure of `http://example.com/portfolio/`*). If this does not work, you have something inside your theme which is causing this issue, more likely a `pre_get_posts` action which is suppose to target the `portfolio` post type page. You should also consider a bad rewrite as well EDIT ---- The final issue was that the `template_include` filter as mentioned in the question was causing the issue. Removing the filter in the child theme and reflushing the permalinks solved the issue
218,709
<p>Based on example here <a href="https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/" rel="noreferrer">https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/</a></p> <p>I'd like to modify the query</p> <pre><code>$q = new WP_Query( array( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', 'state_clause' =&gt; array( 'key' =&gt; 'state', 'value' =&gt; 'Wisconsin', ), 'city_clause' =&gt; array( 'key' =&gt; 'city', 'compare' =&gt; 'EXISTS', ), ), 'orderby' =&gt; 'city_clause') ); </code></pre> <p>to be able to get all posts where <code>state</code> is 'Wisconsin' OR <code>timezone</code> is 'central' ORDER BY <code>population</code> DESC </p>
[ { "answer_id": 218718, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": false, "text": "<p>This would be done like this:</p>\n\n<pre><code>$q = new WP_Query( array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'relation' =&gt; 'OR',\n 'state_clause' =&gt; array(\n 'key' =&gt; 'state',\n 'value' =&gt; array( 'Wisconsin' ), //allowed values\n 'compare' =&gt; 'IN' // state must be in array above\n ),\n 'state_clause' =&gt; array(\n 'key' =&gt; 'timezone',\n 'value' =&gt; 'central',\n 'compare' =&gt; '='\n ),\n ),\n 'city_clause' =&gt; array(\n 'key' =&gt; 'city',\n 'compare' =&gt; 'EXISTS',\n ), \n ),\n 'orderby' =&gt; array(\n 'city_clause' =&gt; 'DESC',\n ),\n) );\n</code></pre>\n" }, { "answer_id": 218724, "author": "Bruno Cantuaria", "author_id": 65717, "author_profile": "https://wordpress.stackexchange.com/users/65717", "pm_score": 5, "selected": true, "text": "<p>You can create groups of meta_queries using specific compare operation on them, and since you want to order based in a single custom field, you can keep the order declaration dedicated to the single meta field. So:</p>\n\n<pre><code>$q = new WP_Query( \n array(\n 'meta_key' =&gt; 'population', //setting the meta_key which will be used to order\n 'orderby' =&gt; 'meta_value', //if the meta_key (population) is numeric use meta_value_num instead\n 'order' =&gt; 'DESC', //setting order direction\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND', //setting relation between queries group\n array(\n 'relation' =&gt; 'OR', //setting relation between this inside query\n array(\n 'key' =&gt; 'state',\n 'value' =&gt; 'Wisconsin',\n ),\n array(\n 'key' =&gt; 'timezone',\n 'value' =&gt; 'central',\n )\n ),\n array(\n 'key' =&gt; 'city',\n 'compare' =&gt; 'EXISTS',\n )\n )\n ) \n);\n</code></pre>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218709", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88291/" ]
Based on example here <https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/> I'd like to modify the query ``` $q = new WP_Query( array( 'meta_query' => array( 'relation' => 'AND', 'state_clause' => array( 'key' => 'state', 'value' => 'Wisconsin', ), 'city_clause' => array( 'key' => 'city', 'compare' => 'EXISTS', ), ), 'orderby' => 'city_clause') ); ``` to be able to get all posts where `state` is 'Wisconsin' OR `timezone` is 'central' ORDER BY `population` DESC
You can create groups of meta\_queries using specific compare operation on them, and since you want to order based in a single custom field, you can keep the order declaration dedicated to the single meta field. So: ``` $q = new WP_Query( array( 'meta_key' => 'population', //setting the meta_key which will be used to order 'orderby' => 'meta_value', //if the meta_key (population) is numeric use meta_value_num instead 'order' => 'DESC', //setting order direction 'meta_query' => array( 'relation' => 'AND', //setting relation between queries group array( 'relation' => 'OR', //setting relation between this inside query array( 'key' => 'state', 'value' => 'Wisconsin', ), array( 'key' => 'timezone', 'value' => 'central', ) ), array( 'key' => 'city', 'compare' => 'EXISTS', ) ) ) ); ```
218,713
<p>I'm trying to test if my plugin activates properly with PHPUnit. I have used boilerplate structure generated on this <a href="http://wppb.me/" rel="nofollow">site</a> and added this test:</p> <pre><code>class PluginTest extends WP_UnitTestCase { function test_plugin_activation() { include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); $result = activate_plugin( WP_CONTENT_DIR . '/plugins/example-plugin/example-plugin.php', '', TRUE, FALSE ); $this-&gt;assertNotWPError( $result ); } } </code></pre> <p>But I get this error:</p> <pre><code>1) PluginTest::test_plugin_activation Plugin file does not exist. Failed asserting that WP_Error Object (...) is not an instance of class "WP_Error". </code></pre> <p>I have checked manually and I can activate and deactivate plugin via Wordpress admin panel. </p>
[ { "answer_id": 218730, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 0, "selected": false, "text": "<p>Testing plugin activation/installation and uninstall with the core WordPress test suite can be done more easily and properly with <a href=\"https://github.com/JDGrimes/wp-plugin-uninstall-tester/\" rel=\"nofollow\">these additional utilities</a>. Their main focus is testing uninstallation, but they test activation/installation as well. This is the example test case from there, and shows how you would test install and uninstall:</p>\n\n<pre><code>&lt;?php\n\n/**\n * Test uninstallation.\n */\n\n/**\n * Plugin uninstall test case.\n *\n * Be sure to add \"@group uninstall\", so that the test will run only as part of the\n * uninstall group.\n *\n * @group uninstall\n */\nclass My_Plugin_Uninstall_Test extends WP_Plugin_Uninstall_UnitTestCase {\n\n //\n // Protected properties.\n //\n\n /**\n * The full path to the main plugin file.\n *\n * @type string $plugin_file\n */\n protected $plugin_file;\n\n //\n // Public methods.\n //\n\n /**\n * Set up for the tests.\n */\n public function setUp() {\n\n // You must set the path to your plugin here.\n $this-&gt;plugin_file = dirname( dirname( __FILE__ ) ) . '/myplugin.php';\n\n // Don't forget to call the parent's setUp(), or the plugin won't get installed.\n parent::setUp();\n }\n\n /**\n * Test installation and uninstallation.\n */\n public function test_uninstall() {\n\n /*\n * First test that the plugin installed itself properly.\n */\n\n // Check that a database table was added.\n $this-&gt;assertTableExists( $wpdb-&gt;prefix . 'myplugin_table' );\n\n // Check that an option was added to the database.\n $this-&gt;assertEquals( 'default', get_option( 'myplugin_option' ) );\n\n /*\n * Now, test that it uninstalls itself properly.\n */\n\n // You must call this to perform uninstallation.\n $this-&gt;uninstall();\n\n // Check that the table was deleted.\n $this-&gt;assertTableNotExists( $wpdb-&gt;prefix . 'myplugin_table' );\n\n // Check that all options with a prefix was deleted.\n $this-&gt;assertNoOptionsWithPrefix( 'myplugin' );\n\n // Same for usermeta and comment meta.\n $this-&gt;assertNoUserMetaWithPrefix( 'myplugin' );\n $this-&gt;assertNoCommentMetaWithPrefix( 'myplugin' );\n }\n}\n</code></pre>\n\n<p>I think this is probably what you are trying to achieve.</p>\n\n<hr>\n\n<p>As far why your tests are failing as they are, I'm not sure. To debug it you need to see where that error is coming from in <code>activate_plugin()</code>; what part of the check for the plugin file is failing? Tools like xdebug are invaluable for this sort of thing. If you don't have xdebug installed for the PHP build that you are using (you probably should get it), you'll have to debug it manually by looking at the source code of <code>activate_plugin()</code> et al. and seeing where that error is originating.</p>\n" }, { "answer_id": 319703, "author": "ocReaper", "author_id": 146244, "author_profile": "https://wordpress.stackexchange.com/users/146244", "pm_score": 2, "selected": false, "text": "<p>Actually you cannot activate your plugin using <code>WP_UnitTestCase</code>, because in the <code>bootstrap.php</code> you've already loaded your plugin as a <code>mu-plugin</code>.</p>\n\n<p>What I can suggest you to test your plugin activation is: call the <code>do_action('activate_' . FULL_ABSPATH_TO_YOUR_PLUGIN_PHP)</code>, where <code>FULL_ABSPATH_TO_YOUR_PLUGIN_PHP</code> will be something like: <code>var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php</code></p>\n\n<p>In this example the <code>hello-world</code> plugin revoke's a specified user's capabilities on activation:</p>\n\n<pre><code>class ActivationEventTest extends WP_UnitTestCase {\n\n const PLUGIN_BASENAME = 'var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php';\n\n public function testActivateWithSupport() {\n $this-&gt;factory()-&gt;user-&gt;create( [\n 'user_email' =&gt; '[email protected]',\n 'user_pass' =&gt; 'reallyheavypasword',\n 'user_login' =&gt; 'hello',\n 'user_role' =&gt; 4,\n 'role' =&gt; 4\n ] );\n\n do_action( 'activate_' . static::PLUGIN_BASENAME );\n\n $user = get_user_by( 'login', 'hello' );\n $this-&gt;assertEmpty( $user-&gt;caps );\n $this-&gt;assertEmpty( $user-&gt;roles );\n }\n}\n</code></pre>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218713", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21181/" ]
I'm trying to test if my plugin activates properly with PHPUnit. I have used boilerplate structure generated on this [site](http://wppb.me/) and added this test: ``` class PluginTest extends WP_UnitTestCase { function test_plugin_activation() { include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); $result = activate_plugin( WP_CONTENT_DIR . '/plugins/example-plugin/example-plugin.php', '', TRUE, FALSE ); $this->assertNotWPError( $result ); } } ``` But I get this error: ``` 1) PluginTest::test_plugin_activation Plugin file does not exist. Failed asserting that WP_Error Object (...) is not an instance of class "WP_Error". ``` I have checked manually and I can activate and deactivate plugin via Wordpress admin panel.
Actually you cannot activate your plugin using `WP_UnitTestCase`, because in the `bootstrap.php` you've already loaded your plugin as a `mu-plugin`. What I can suggest you to test your plugin activation is: call the `do_action('activate_' . FULL_ABSPATH_TO_YOUR_PLUGIN_PHP)`, where `FULL_ABSPATH_TO_YOUR_PLUGIN_PHP` will be something like: `var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php` In this example the `hello-world` plugin revoke's a specified user's capabilities on activation: ``` class ActivationEventTest extends WP_UnitTestCase { const PLUGIN_BASENAME = 'var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php'; public function testActivateWithSupport() { $this->factory()->user->create( [ 'user_email' => '[email protected]', 'user_pass' => 'reallyheavypasword', 'user_login' => 'hello', 'user_role' => 4, 'role' => 4 ] ); do_action( 'activate_' . static::PLUGIN_BASENAME ); $user = get_user_by( 'login', 'hello' ); $this->assertEmpty( $user->caps ); $this->assertEmpty( $user->roles ); } } ```
218,719
<p>I added some function code to the functions.php file of my child theme that has now set my entire site blank.</p> <p>Is the only way to get it back via cPanel and changing the theme back to the parent them in PHPMyAdmin under wp-options? (The entire is site is blank on both frontend and admin)</p>
[ { "answer_id": 218730, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 0, "selected": false, "text": "<p>Testing plugin activation/installation and uninstall with the core WordPress test suite can be done more easily and properly with <a href=\"https://github.com/JDGrimes/wp-plugin-uninstall-tester/\" rel=\"nofollow\">these additional utilities</a>. Their main focus is testing uninstallation, but they test activation/installation as well. This is the example test case from there, and shows how you would test install and uninstall:</p>\n\n<pre><code>&lt;?php\n\n/**\n * Test uninstallation.\n */\n\n/**\n * Plugin uninstall test case.\n *\n * Be sure to add \"@group uninstall\", so that the test will run only as part of the\n * uninstall group.\n *\n * @group uninstall\n */\nclass My_Plugin_Uninstall_Test extends WP_Plugin_Uninstall_UnitTestCase {\n\n //\n // Protected properties.\n //\n\n /**\n * The full path to the main plugin file.\n *\n * @type string $plugin_file\n */\n protected $plugin_file;\n\n //\n // Public methods.\n //\n\n /**\n * Set up for the tests.\n */\n public function setUp() {\n\n // You must set the path to your plugin here.\n $this-&gt;plugin_file = dirname( dirname( __FILE__ ) ) . '/myplugin.php';\n\n // Don't forget to call the parent's setUp(), or the plugin won't get installed.\n parent::setUp();\n }\n\n /**\n * Test installation and uninstallation.\n */\n public function test_uninstall() {\n\n /*\n * First test that the plugin installed itself properly.\n */\n\n // Check that a database table was added.\n $this-&gt;assertTableExists( $wpdb-&gt;prefix . 'myplugin_table' );\n\n // Check that an option was added to the database.\n $this-&gt;assertEquals( 'default', get_option( 'myplugin_option' ) );\n\n /*\n * Now, test that it uninstalls itself properly.\n */\n\n // You must call this to perform uninstallation.\n $this-&gt;uninstall();\n\n // Check that the table was deleted.\n $this-&gt;assertTableNotExists( $wpdb-&gt;prefix . 'myplugin_table' );\n\n // Check that all options with a prefix was deleted.\n $this-&gt;assertNoOptionsWithPrefix( 'myplugin' );\n\n // Same for usermeta and comment meta.\n $this-&gt;assertNoUserMetaWithPrefix( 'myplugin' );\n $this-&gt;assertNoCommentMetaWithPrefix( 'myplugin' );\n }\n}\n</code></pre>\n\n<p>I think this is probably what you are trying to achieve.</p>\n\n<hr>\n\n<p>As far why your tests are failing as they are, I'm not sure. To debug it you need to see where that error is coming from in <code>activate_plugin()</code>; what part of the check for the plugin file is failing? Tools like xdebug are invaluable for this sort of thing. If you don't have xdebug installed for the PHP build that you are using (you probably should get it), you'll have to debug it manually by looking at the source code of <code>activate_plugin()</code> et al. and seeing where that error is originating.</p>\n" }, { "answer_id": 319703, "author": "ocReaper", "author_id": 146244, "author_profile": "https://wordpress.stackexchange.com/users/146244", "pm_score": 2, "selected": false, "text": "<p>Actually you cannot activate your plugin using <code>WP_UnitTestCase</code>, because in the <code>bootstrap.php</code> you've already loaded your plugin as a <code>mu-plugin</code>.</p>\n\n<p>What I can suggest you to test your plugin activation is: call the <code>do_action('activate_' . FULL_ABSPATH_TO_YOUR_PLUGIN_PHP)</code>, where <code>FULL_ABSPATH_TO_YOUR_PLUGIN_PHP</code> will be something like: <code>var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php</code></p>\n\n<p>In this example the <code>hello-world</code> plugin revoke's a specified user's capabilities on activation:</p>\n\n<pre><code>class ActivationEventTest extends WP_UnitTestCase {\n\n const PLUGIN_BASENAME = 'var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php';\n\n public function testActivateWithSupport() {\n $this-&gt;factory()-&gt;user-&gt;create( [\n 'user_email' =&gt; '[email protected]',\n 'user_pass' =&gt; 'reallyheavypasword',\n 'user_login' =&gt; 'hello',\n 'user_role' =&gt; 4,\n 'role' =&gt; 4\n ] );\n\n do_action( 'activate_' . static::PLUGIN_BASENAME );\n\n $user = get_user_by( 'login', 'hello' );\n $this-&gt;assertEmpty( $user-&gt;caps );\n $this-&gt;assertEmpty( $user-&gt;roles );\n }\n}\n</code></pre>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88959/" ]
I added some function code to the functions.php file of my child theme that has now set my entire site blank. Is the only way to get it back via cPanel and changing the theme back to the parent them in PHPMyAdmin under wp-options? (The entire is site is blank on both frontend and admin)
Actually you cannot activate your plugin using `WP_UnitTestCase`, because in the `bootstrap.php` you've already loaded your plugin as a `mu-plugin`. What I can suggest you to test your plugin activation is: call the `do_action('activate_' . FULL_ABSPATH_TO_YOUR_PLUGIN_PHP)`, where `FULL_ABSPATH_TO_YOUR_PLUGIN_PHP` will be something like: `var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php` In this example the `hello-world` plugin revoke's a specified user's capabilities on activation: ``` class ActivationEventTest extends WP_UnitTestCase { const PLUGIN_BASENAME = 'var/www/html/wordpress/wp-content/plugins/hello-world/hello-world.php'; public function testActivateWithSupport() { $this->factory()->user->create( [ 'user_email' => '[email protected]', 'user_pass' => 'reallyheavypasword', 'user_login' => 'hello', 'user_role' => 4, 'role' => 4 ] ); do_action( 'activate_' . static::PLUGIN_BASENAME ); $user = get_user_by( 'login', 'hello' ); $this->assertEmpty( $user->caps ); $this->assertEmpty( $user->roles ); } } ```
218,731
<p>Trying to check if <code>$link</code> has <code>http://</code> in front of it or not. If someone puts in <code>www.google.com</code> for the link field it acts as a link within the WordPress site, ie: <code>www.website.com/www.google.com</code>.</p> <pre><code>$link = get_field('advertisement_link'); $ad_code = '&lt;a href="'.$link.'" target="_blank"&gt;Test&lt;/a&gt;'; </code></pre> <p>Sample code above I am working with. This is a general PHP question as well. How do I do this the right way? Tried below, replaces <code>the_content()</code> with the <code>$link</code>.</p> <pre><code>$link = get_field('advertisement_link'); if(strpos($link, 'http://') !== 0) { return 'http://' . $link; } else { return $link; } $ad_code = '&lt;a href="'.$link.'" target="_blank"&gt;Test&lt;/a&gt;'; </code></pre> <p>Edit: I need to keep <code>$ad_code</code> because I'm using it inside <code>return prefix_insert_after_paragraph( $ad_code, 3, $content );</code> to insert this ad into a post every 3 paragraphs.</p>
[ { "answer_id": 218734, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 3, "selected": true, "text": "<p>You must not <code>return</code> the value, but alter the varialbe <code>$link</code></p>\n\n<pre><code>if(strpos($link, 'http://') !== 0) {\n $link = 'http://' . $link;\n} //no else needed\n</code></pre>\n\n<p>Be aware that if your link begins with <code>https://</code> it will also prepend the <code>http://</code> and result in <code>http://https://example.com</code>.</p>\n\n<p>The better way to do this would be from <a href=\"https://stackoverflow.com/a/2762083/1365666\">here</a>, adjusted to your needs:</p>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>function addhttp($url) {\n if (!preg_match(\"~^(?:f|ht)tps?://~i\", $url)) {\n $url = \"http://\" . $url;\n }\n return $url;\n}\n</code></pre>\n\n<p>Code for you: </p>\n\n<pre><code>$link = addhttp( get_field('advertisement_link') );\n$ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;Test&lt;/a&gt;';\n</code></pre>\n" }, { "answer_id": 218736, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 1, "selected": false, "text": "<p>I guess this is a possible duplicate of – or at least similar to \"<a href=\"https://stackoverflow.com/questions/4487794/checking-if-string-contains-http\">Checking if string contains HTTP://</a>\" over at stackoverflow – but still: First instead of checking for \"0\" you should check for \"false\". And then you should also check for \"https://\". I would probably do something like this:</p>\n\n<pre><code>if (substr($link, 0, 7) == 'http://') {\n // do nothing\n} elseif (substr($link, 0, 8) == 'https://') {\n // do nothing\n} else {\n $link = 'http://'.$link;\n}\n</code></pre>\n\n<p>( I'm aware there are more elegant ways to write this )</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88720/" ]
Trying to check if `$link` has `http://` in front of it or not. If someone puts in `www.google.com` for the link field it acts as a link within the WordPress site, ie: `www.website.com/www.google.com`. ``` $link = get_field('advertisement_link'); $ad_code = '<a href="'.$link.'" target="_blank">Test</a>'; ``` Sample code above I am working with. This is a general PHP question as well. How do I do this the right way? Tried below, replaces `the_content()` with the `$link`. ``` $link = get_field('advertisement_link'); if(strpos($link, 'http://') !== 0) { return 'http://' . $link; } else { return $link; } $ad_code = '<a href="'.$link.'" target="_blank">Test</a>'; ``` Edit: I need to keep `$ad_code` because I'm using it inside `return prefix_insert_after_paragraph( $ad_code, 3, $content );` to insert this ad into a post every 3 paragraphs.
You must not `return` the value, but alter the varialbe `$link` ``` if(strpos($link, 'http://') !== 0) { $link = 'http://' . $link; } //no else needed ``` Be aware that if your link begins with `https://` it will also prepend the `http://` and result in `http://https://example.com`. The better way to do this would be from [here](https://stackoverflow.com/a/2762083/1365666), adjusted to your needs: In `functions.php`: ``` function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; } ``` Code for you: ``` $link = addhttp( get_field('advertisement_link') ); $ad_code = '<a href="'.$link.'" target="_blank">Test</a>'; ```
218,746
<p>I have a function, within <code>functions.php</code> (all code below), that adds an advertisement after <code>x</code> amount of paragraphs to any given <code>single.php</code> post. I have a custom-post-type called <code>advertising</code> that has a Title, Image, and URL field for the advertisement post. In any <code>single.php</code> post I have a checkbox to show the ad (true / false) and a number field for the author to choose how many paragraphs to skip before inserting the image advertisement.</p> <p><strong>UPDATED CODE:</strong> code below works, however I am unable to get a random post. It keeps pulling the absolute latest post without rotating to the other ones.</p> <pre><code>// http parser function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; } // filter content with ad add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { // checkbox to show ad, default true if ( get_field('show_advertisement') ) { if ( is_single() &amp;&amp; ! is_admin() ) { // get post-type $random_ad = get_posts(array( 'numberposts' =&gt; 1, 'post_type' =&gt; 'advertising', 'order' =&gt; 'rand', 'posts_per_page'=&gt;'1' )); // get post-type fields $random_ad = array_shift($random_ad); $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID)); $image = get_field('upload_advertisement', $random_ad-&gt;ID); // get html $ad_code = '&lt;a href="'.$link.'" target="_blank"&gt;&lt;img src="'.$image.'" /&gt;&lt;/a&gt;'; // show ad after # paragraphs $show_after = get_field('advertisement_show_after'); // return appended $content return prefix_insert_after_paragraph( $ad_code, $show_after, $content ); } else { // do nothing } } else { return $content; } } // insert ad into post function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '&lt;/p&gt;'; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index =&gt; $paragraph) { if ( trim( $paragraph ) ) { $paragraphs[$index] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); } </code></pre> <p><strong>EDIT:</strong> SOLVED! Changed <code>order</code> to <code>orderby</code> and the above code works.</p>
[ { "answer_id": 218747, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>First get the random advertising post by <code>get_posts</code></p>\n\n<pre><code>$random_ad = get_posts(array(\n 'numberposts' =&gt; 1,\n 'post_type' =&gt; 'advertising',\n 'orderby' =&gt; 'rand'\n));\n</code></pre>\n\n<p>Now get the custom fields from this random post</p>\n\n<pre><code>if (!empty($random_ad)) {\n $random_ad = array_shift($random_ad);\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n}\n</code></pre>\n\n<p>Build your ad HTML and insert where you want!</p>\n\n<pre><code>$ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n</code></pre>\n" }, { "answer_id": 218760, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue.</p>\n\n<p>Because you only need one post from your custom post type, we only need one random ID which we can pass to <code>get_post()</code> in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (<em>or at least all the post ID's</em>), save that into a transient, and then we can just pick a random ID from that option. </p>\n\n<p>Lets look at some code: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>function get_random_id( $post_type = '' )\n{\n $q = [];\n\n // Make sure we have a post type set, check if it exists and sanitize\n $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING );\n\n if ( !$post_type ) \n return $q;\n\n if ( !post_type_exists( $post_type ) )\n return $q;\n\n // The post type exist and is valid, lets continue\n $transient_name = 'rand_ids_' . md5( $post_type );\n\n // Get the transient, if we have one already\n if ( false === ( $q = get_transient ( $transient_name ) ) ) {\n $args = [ \n 'post_type' =&gt; $post_type,\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids', // get only post ID's\n // Add any additional arguments\n ];\n $q = get_posts( $args );\n\n // Set the transient\n set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); \n } // endif get_transient\n\n return $q;\n} \n</code></pre>\n\n<p>What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. </p>\n\n<p>Lets use the <code>transition_post_status</code> action hook: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>add_action( 'transition_post_status', function ( $new_status, $old_status, $post )\n{\n // Make sure we only target our specific post type\n if ( 'advertising' !== $post-&gt;post_type )\n return;\n\n global $wpdb;\n\n // Delete the transients\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_rand_ids_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')\" );\n\n // Lets rebuild the transient\n get_random_id( $post-&gt;post_type );\n\n}, 10, 3 );\n</code></pre>\n\n<p>All we are left with is to get a random post ID from our <code>get_random_id()</code> function and pass that to <code>get_post()</code> to get the post object</p>\n\n<pre><code>// Get the array of post ID's\n$post_type_posts = get_random_id( 'advertising' );\n// Make sure we have posts\nif ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $single_post = get_post( $post_type_posts[0] );\n // Display the post content\n}\n</code></pre>\n\n<p>This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB</p>\n\n<p>Just as example, your advert injector filter can look something like the following</p>\n\n<pre><code>add_filter( 'the_content', 'prefix_insert_post_ads' );\nfunction prefix_insert_post_ads( $content ) {\n\n // checkbox to show ad, default true\n if ( get_field('show_advertisement') ) {\n if ( is_single() &amp;&amp; \n ! is_admin() \n ) {\n // Get the array of post ID's\n $post_type_posts = get_random_id( 'advertising' );\n // Make sure we have posts\n if ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $random_ad = get_post( $post_type_posts[0] );\n\n // Display the post content\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n // get html\n $ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n // show ad after # paragraphs\n $show_after = get_field('advertisement_show_after');\n // return appended $content\n return prefix_insert_after_paragraph( $ad_code, $show_after, $content );\n\n } \n }\n } \n return $content;\n}\n</code></pre>\n" }, { "answer_id": 218769, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Using a random offset might be a faster alternative, than ordering by <code>RAND()</code> in the generated SQL query:</p>\n\n<pre><code>if( $count = wp_count_posts( 'advertising' )-&gt;publish )\n{\n $random_ad = get_posts( \n [\n 'post_status' =&gt; 'publish',\n 'offset' =&gt; rand( 0, $count - 1 ),\n 'posts_per_page' =&gt; 1,\n 'post_type' =&gt; 'advertising'\n ] \n );\n}\n</code></pre>\n\n<p>where we use the <code>offset</code> to set the <code>LIMIT x, 1</code> SQL part, where <code>x</code> depends on the number of posts. </p>\n\n<p>Note that this is might not be so <a href=\"http://devoluk.com/mysql-limit-offset-performance.html\" rel=\"nofollow noreferrer\">great</a> for very large number of rows, but there's also an interesting <a href=\"https://docs.google.com/spreadsheets/d/16nXRHZISDLcOFBLd4D2xUxOzFl7tabTH1jKFZ8bIYBs/edit?hl=en#gid=0\" rel=\"nofollow noreferrer\">benchmark</a> sheet by <a href=\"https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/\" rel=\"nofollow noreferrer\">Josh Hartman</a>.</p>\n\n<p>Pieter Goosen has also an interesting approach in his <a href=\"https://wordpress.stackexchange.com/a/218760/26350\">answer</a>, that should give you much better alternative than ordering by <code>RAND()</code>.</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218746", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88720/" ]
I have a function, within `functions.php` (all code below), that adds an advertisement after `x` amount of paragraphs to any given `single.php` post. I have a custom-post-type called `advertising` that has a Title, Image, and URL field for the advertisement post. In any `single.php` post I have a checkbox to show the ad (true / false) and a number field for the author to choose how many paragraphs to skip before inserting the image advertisement. **UPDATED CODE:** code below works, however I am unable to get a random post. It keeps pulling the absolute latest post without rotating to the other ones. ``` // http parser function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; } // filter content with ad add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { // checkbox to show ad, default true if ( get_field('show_advertisement') ) { if ( is_single() && ! is_admin() ) { // get post-type $random_ad = get_posts(array( 'numberposts' => 1, 'post_type' => 'advertising', 'order' => 'rand', 'posts_per_page'=>'1' )); // get post-type fields $random_ad = array_shift($random_ad); $link = addhttp( get_field('advertisement_link', $random_ad->ID)); $image = get_field('upload_advertisement', $random_ad->ID); // get html $ad_code = '<a href="'.$link.'" target="_blank"><img src="'.$image.'" /></a>'; // show ad after # paragraphs $show_after = get_field('advertisement_show_after'); // return appended $content return prefix_insert_after_paragraph( $ad_code, $show_after, $content ); } else { // do nothing } } else { return $content; } } // insert ad into post function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = '</p>'; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { if ( trim( $paragraph ) ) { $paragraphs[$index] .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); } ``` **EDIT:** SOLVED! Changed `order` to `orderby` and the above code works.
As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue. Because you only need one post from your custom post type, we only need one random ID which we can pass to `get_post()` in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (*or at least all the post ID's*), save that into a transient, and then we can just pick a random ID from that option. Lets look at some code: (*This goes into functions.php*) ``` function get_random_id( $post_type = '' ) { $q = []; // Make sure we have a post type set, check if it exists and sanitize $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING ); if ( !$post_type ) return $q; if ( !post_type_exists( $post_type ) ) return $q; // The post type exist and is valid, lets continue $transient_name = 'rand_ids_' . md5( $post_type ); // Get the transient, if we have one already if ( false === ( $q = get_transient ( $transient_name ) ) ) { $args = [ 'post_type' => $post_type, 'posts_per_page' => -1, 'fields' => 'ids', // get only post ID's // Add any additional arguments ]; $q = get_posts( $args ); // Set the transient set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); } // endif get_transient return $q; } ``` What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. Lets use the `transition_post_status` action hook: (*This goes into functions.php*) ``` add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { // Make sure we only target our specific post type if ( 'advertising' !== $post->post_type ) return; global $wpdb; // Delete the transients $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_rand_ids_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')" ); // Lets rebuild the transient get_random_id( $post->post_type ); }, 10, 3 ); ``` All we are left with is to get a random post ID from our `get_random_id()` function and pass that to `get_post()` to get the post object ``` // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $single_post = get_post( $post_type_posts[0] ); // Display the post content } ``` This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB Just as example, your advert injector filter can look something like the following ``` add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { // checkbox to show ad, default true if ( get_field('show_advertisement') ) { if ( is_single() && ! is_admin() ) { // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $random_ad = get_post( $post_type_posts[0] ); // Display the post content $link = addhttp( get_field('advertisement_link', $random_ad->ID)); $image = get_field('upload_advertisement', $random_ad->ID); // get html $ad_code = '<a href="'.$link.'" target="_blank"><img src="'.$image.'" /></a>'; // show ad after # paragraphs $show_after = get_field('advertisement_show_after'); // return appended $content return prefix_insert_after_paragraph( $ad_code, $show_after, $content ); } } } return $content; } ```
218,750
<p>In my <code>functions.php</code> I have:</p> <pre><code> global $wpdb; $wpdb-&gt;update( $wpdb-&gt;posts, array('post_content' =&gt; $newcontent), array('ID' =&gt; $post_id) ); </code></pre> <p>this code updates the <code>post_content</code> in the WP DB with my <code>$newcontent</code> when I publish a post. In fact I can see the modified content inside the DB and of course I can see it with:</p> <pre><code> echo get_post_field('post_content', $post_id); </code></pre> <p>The issue is that (after publish and update) the post editor continues to show the <em>old</em> content! In a few words... I need a way to force the editor to show the <code>$newcontent</code>, the one stored into the DB (after publish). Any ideas?</p>
[ { "answer_id": 218747, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>First get the random advertising post by <code>get_posts</code></p>\n\n<pre><code>$random_ad = get_posts(array(\n 'numberposts' =&gt; 1,\n 'post_type' =&gt; 'advertising',\n 'orderby' =&gt; 'rand'\n));\n</code></pre>\n\n<p>Now get the custom fields from this random post</p>\n\n<pre><code>if (!empty($random_ad)) {\n $random_ad = array_shift($random_ad);\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n}\n</code></pre>\n\n<p>Build your ad HTML and insert where you want!</p>\n\n<pre><code>$ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n</code></pre>\n" }, { "answer_id": 218760, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue.</p>\n\n<p>Because you only need one post from your custom post type, we only need one random ID which we can pass to <code>get_post()</code> in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (<em>or at least all the post ID's</em>), save that into a transient, and then we can just pick a random ID from that option. </p>\n\n<p>Lets look at some code: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>function get_random_id( $post_type = '' )\n{\n $q = [];\n\n // Make sure we have a post type set, check if it exists and sanitize\n $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING );\n\n if ( !$post_type ) \n return $q;\n\n if ( !post_type_exists( $post_type ) )\n return $q;\n\n // The post type exist and is valid, lets continue\n $transient_name = 'rand_ids_' . md5( $post_type );\n\n // Get the transient, if we have one already\n if ( false === ( $q = get_transient ( $transient_name ) ) ) {\n $args = [ \n 'post_type' =&gt; $post_type,\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids', // get only post ID's\n // Add any additional arguments\n ];\n $q = get_posts( $args );\n\n // Set the transient\n set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); \n } // endif get_transient\n\n return $q;\n} \n</code></pre>\n\n<p>What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. </p>\n\n<p>Lets use the <code>transition_post_status</code> action hook: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>add_action( 'transition_post_status', function ( $new_status, $old_status, $post )\n{\n // Make sure we only target our specific post type\n if ( 'advertising' !== $post-&gt;post_type )\n return;\n\n global $wpdb;\n\n // Delete the transients\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_rand_ids_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')\" );\n\n // Lets rebuild the transient\n get_random_id( $post-&gt;post_type );\n\n}, 10, 3 );\n</code></pre>\n\n<p>All we are left with is to get a random post ID from our <code>get_random_id()</code> function and pass that to <code>get_post()</code> to get the post object</p>\n\n<pre><code>// Get the array of post ID's\n$post_type_posts = get_random_id( 'advertising' );\n// Make sure we have posts\nif ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $single_post = get_post( $post_type_posts[0] );\n // Display the post content\n}\n</code></pre>\n\n<p>This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB</p>\n\n<p>Just as example, your advert injector filter can look something like the following</p>\n\n<pre><code>add_filter( 'the_content', 'prefix_insert_post_ads' );\nfunction prefix_insert_post_ads( $content ) {\n\n // checkbox to show ad, default true\n if ( get_field('show_advertisement') ) {\n if ( is_single() &amp;&amp; \n ! is_admin() \n ) {\n // Get the array of post ID's\n $post_type_posts = get_random_id( 'advertising' );\n // Make sure we have posts\n if ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $random_ad = get_post( $post_type_posts[0] );\n\n // Display the post content\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n // get html\n $ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n // show ad after # paragraphs\n $show_after = get_field('advertisement_show_after');\n // return appended $content\n return prefix_insert_after_paragraph( $ad_code, $show_after, $content );\n\n } \n }\n } \n return $content;\n}\n</code></pre>\n" }, { "answer_id": 218769, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Using a random offset might be a faster alternative, than ordering by <code>RAND()</code> in the generated SQL query:</p>\n\n<pre><code>if( $count = wp_count_posts( 'advertising' )-&gt;publish )\n{\n $random_ad = get_posts( \n [\n 'post_status' =&gt; 'publish',\n 'offset' =&gt; rand( 0, $count - 1 ),\n 'posts_per_page' =&gt; 1,\n 'post_type' =&gt; 'advertising'\n ] \n );\n}\n</code></pre>\n\n<p>where we use the <code>offset</code> to set the <code>LIMIT x, 1</code> SQL part, where <code>x</code> depends on the number of posts. </p>\n\n<p>Note that this is might not be so <a href=\"http://devoluk.com/mysql-limit-offset-performance.html\" rel=\"nofollow noreferrer\">great</a> for very large number of rows, but there's also an interesting <a href=\"https://docs.google.com/spreadsheets/d/16nXRHZISDLcOFBLd4D2xUxOzFl7tabTH1jKFZ8bIYBs/edit?hl=en#gid=0\" rel=\"nofollow noreferrer\">benchmark</a> sheet by <a href=\"https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/\" rel=\"nofollow noreferrer\">Josh Hartman</a>.</p>\n\n<p>Pieter Goosen has also an interesting approach in his <a href=\"https://wordpress.stackexchange.com/a/218760/26350\">answer</a>, that should give you much better alternative than ordering by <code>RAND()</code>.</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89045/" ]
In my `functions.php` I have: ``` global $wpdb; $wpdb->update( $wpdb->posts, array('post_content' => $newcontent), array('ID' => $post_id) ); ``` this code updates the `post_content` in the WP DB with my `$newcontent` when I publish a post. In fact I can see the modified content inside the DB and of course I can see it with: ``` echo get_post_field('post_content', $post_id); ``` The issue is that (after publish and update) the post editor continues to show the *old* content! In a few words... I need a way to force the editor to show the `$newcontent`, the one stored into the DB (after publish). Any ideas?
As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue. Because you only need one post from your custom post type, we only need one random ID which we can pass to `get_post()` in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (*or at least all the post ID's*), save that into a transient, and then we can just pick a random ID from that option. Lets look at some code: (*This goes into functions.php*) ``` function get_random_id( $post_type = '' ) { $q = []; // Make sure we have a post type set, check if it exists and sanitize $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING ); if ( !$post_type ) return $q; if ( !post_type_exists( $post_type ) ) return $q; // The post type exist and is valid, lets continue $transient_name = 'rand_ids_' . md5( $post_type ); // Get the transient, if we have one already if ( false === ( $q = get_transient ( $transient_name ) ) ) { $args = [ 'post_type' => $post_type, 'posts_per_page' => -1, 'fields' => 'ids', // get only post ID's // Add any additional arguments ]; $q = get_posts( $args ); // Set the transient set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); } // endif get_transient return $q; } ``` What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. Lets use the `transition_post_status` action hook: (*This goes into functions.php*) ``` add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { // Make sure we only target our specific post type if ( 'advertising' !== $post->post_type ) return; global $wpdb; // Delete the transients $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_rand_ids_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')" ); // Lets rebuild the transient get_random_id( $post->post_type ); }, 10, 3 ); ``` All we are left with is to get a random post ID from our `get_random_id()` function and pass that to `get_post()` to get the post object ``` // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $single_post = get_post( $post_type_posts[0] ); // Display the post content } ``` This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB Just as example, your advert injector filter can look something like the following ``` add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { // checkbox to show ad, default true if ( get_field('show_advertisement') ) { if ( is_single() && ! is_admin() ) { // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $random_ad = get_post( $post_type_posts[0] ); // Display the post content $link = addhttp( get_field('advertisement_link', $random_ad->ID)); $image = get_field('upload_advertisement', $random_ad->ID); // get html $ad_code = '<a href="'.$link.'" target="_blank"><img src="'.$image.'" /></a>'; // show ad after # paragraphs $show_after = get_field('advertisement_show_after'); // return appended $content return prefix_insert_after_paragraph( $ad_code, $show_after, $content ); } } } return $content; } ```
218,756
<p>I am using Simple Urls to setup redirects on my blog. I am trying to create redirects automatically upon publishing a post. For example, If i publish a post about StudioPress it will be automatically publish a redirect with Title similar to blog post. i.e StudioPress. and the "URL" custom field will update the Redirect url in Simple URLs Plugin.</p> <p>In simple terms, i want to clone blog post for "surl" (CPT name of Simple URLS Plugin) post type with similar title and for redirect url i will setup a Custom Field Named "URL".</p> <p>I am somehow successful in cloning the post title but the redirect url is not copying. Here is my code. Please have a look and correct the error for Custom Field URL.</p> <pre><code>add_action( 'save_post', 'save_postdata_wpse_76945', 10, 2 ); function save_postdata_wpse_76945( $post_id, $post_object ) { // Auto save? if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return; // Correct post_type if ( 'post' != $post_object-&gt;post_type ) return; // Security if ( !isset($_POST['noncename_wpse_76945']) || !wp_verify_nonce( $_POST['noncename_wpse_76945'], plugin_basename( __FILE__ ) ) ) return; // Prepare contents $add_cpt_clone = array( 'post_title' =&gt; $post_object-&gt;post_title, '_surl_redirect' =&gt; get_post_meta( get_the_ID(), 'url' ), 'post_status' =&gt; 'publish', 'post_type' =&gt; 'surl' ); // Insert the post into the database $p_id = wp_insert_post( $add_cpt_clone ); // Use $p_id to insert new terms } </code></pre> <p>I know i am doing some mistake here</p> <pre><code>'_surl_redirect' =&gt; get_post_meta( get_the_ID(), 'url' ), </code></pre> <p>But i don't know how to correct it. I am using ACF for generating custom field URL.</p> <p>Any Ideas. It's very urgent and i am using Genesis and therefore, i don't want to use any other plugin that is not done by Genesis team. Regards</p>
[ { "answer_id": 218747, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>First get the random advertising post by <code>get_posts</code></p>\n\n<pre><code>$random_ad = get_posts(array(\n 'numberposts' =&gt; 1,\n 'post_type' =&gt; 'advertising',\n 'orderby' =&gt; 'rand'\n));\n</code></pre>\n\n<p>Now get the custom fields from this random post</p>\n\n<pre><code>if (!empty($random_ad)) {\n $random_ad = array_shift($random_ad);\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n}\n</code></pre>\n\n<p>Build your ad HTML and insert where you want!</p>\n\n<pre><code>$ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n</code></pre>\n" }, { "answer_id": 218760, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue.</p>\n\n<p>Because you only need one post from your custom post type, we only need one random ID which we can pass to <code>get_post()</code> in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (<em>or at least all the post ID's</em>), save that into a transient, and then we can just pick a random ID from that option. </p>\n\n<p>Lets look at some code: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>function get_random_id( $post_type = '' )\n{\n $q = [];\n\n // Make sure we have a post type set, check if it exists and sanitize\n $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING );\n\n if ( !$post_type ) \n return $q;\n\n if ( !post_type_exists( $post_type ) )\n return $q;\n\n // The post type exist and is valid, lets continue\n $transient_name = 'rand_ids_' . md5( $post_type );\n\n // Get the transient, if we have one already\n if ( false === ( $q = get_transient ( $transient_name ) ) ) {\n $args = [ \n 'post_type' =&gt; $post_type,\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids', // get only post ID's\n // Add any additional arguments\n ];\n $q = get_posts( $args );\n\n // Set the transient\n set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); \n } // endif get_transient\n\n return $q;\n} \n</code></pre>\n\n<p>What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. </p>\n\n<p>Lets use the <code>transition_post_status</code> action hook: (<em>This goes into functions.php</em>)</p>\n\n<pre><code>add_action( 'transition_post_status', function ( $new_status, $old_status, $post )\n{\n // Make sure we only target our specific post type\n if ( 'advertising' !== $post-&gt;post_type )\n return;\n\n global $wpdb;\n\n // Delete the transients\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_rand_ids_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')\" );\n\n // Lets rebuild the transient\n get_random_id( $post-&gt;post_type );\n\n}, 10, 3 );\n</code></pre>\n\n<p>All we are left with is to get a random post ID from our <code>get_random_id()</code> function and pass that to <code>get_post()</code> to get the post object</p>\n\n<pre><code>// Get the array of post ID's\n$post_type_posts = get_random_id( 'advertising' );\n// Make sure we have posts\nif ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $single_post = get_post( $post_type_posts[0] );\n // Display the post content\n}\n</code></pre>\n\n<p>This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB</p>\n\n<p>Just as example, your advert injector filter can look something like the following</p>\n\n<pre><code>add_filter( 'the_content', 'prefix_insert_post_ads' );\nfunction prefix_insert_post_ads( $content ) {\n\n // checkbox to show ad, default true\n if ( get_field('show_advertisement') ) {\n if ( is_single() &amp;&amp; \n ! is_admin() \n ) {\n // Get the array of post ID's\n $post_type_posts = get_random_id( 'advertising' );\n // Make sure we have posts\n if ( $post_type_posts ) {\n // Get the post object of the id first in line\n shuffle( $post_type_posts );\n $random_ad = get_post( $post_type_posts[0] );\n\n // Display the post content\n $link = addhttp( get_field('advertisement_link', $random_ad-&gt;ID));\n $image = get_field('upload_advertisement', $random_ad-&gt;ID);\n // get html\n $ad_code = '&lt;a href=\"'.$link.'\" target=\"_blank\"&gt;&lt;img src=\"'.$image.'\" /&gt;&lt;/a&gt;';\n // show ad after # paragraphs\n $show_after = get_field('advertisement_show_after');\n // return appended $content\n return prefix_insert_after_paragraph( $ad_code, $show_after, $content );\n\n } \n }\n } \n return $content;\n}\n</code></pre>\n" }, { "answer_id": 218769, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Using a random offset might be a faster alternative, than ordering by <code>RAND()</code> in the generated SQL query:</p>\n\n<pre><code>if( $count = wp_count_posts( 'advertising' )-&gt;publish )\n{\n $random_ad = get_posts( \n [\n 'post_status' =&gt; 'publish',\n 'offset' =&gt; rand( 0, $count - 1 ),\n 'posts_per_page' =&gt; 1,\n 'post_type' =&gt; 'advertising'\n ] \n );\n}\n</code></pre>\n\n<p>where we use the <code>offset</code> to set the <code>LIMIT x, 1</code> SQL part, where <code>x</code> depends on the number of posts. </p>\n\n<p>Note that this is might not be so <a href=\"http://devoluk.com/mysql-limit-offset-performance.html\" rel=\"nofollow noreferrer\">great</a> for very large number of rows, but there's also an interesting <a href=\"https://docs.google.com/spreadsheets/d/16nXRHZISDLcOFBLd4D2xUxOzFl7tabTH1jKFZ8bIYBs/edit?hl=en#gid=0\" rel=\"nofollow noreferrer\">benchmark</a> sheet by <a href=\"https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/\" rel=\"nofollow noreferrer\">Josh Hartman</a>.</p>\n\n<p>Pieter Goosen has also an interesting approach in his <a href=\"https://wordpress.stackexchange.com/a/218760/26350\">answer</a>, that should give you much better alternative than ordering by <code>RAND()</code>.</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218756", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75462/" ]
I am using Simple Urls to setup redirects on my blog. I am trying to create redirects automatically upon publishing a post. For example, If i publish a post about StudioPress it will be automatically publish a redirect with Title similar to blog post. i.e StudioPress. and the "URL" custom field will update the Redirect url in Simple URLs Plugin. In simple terms, i want to clone blog post for "surl" (CPT name of Simple URLS Plugin) post type with similar title and for redirect url i will setup a Custom Field Named "URL". I am somehow successful in cloning the post title but the redirect url is not copying. Here is my code. Please have a look and correct the error for Custom Field URL. ``` add_action( 'save_post', 'save_postdata_wpse_76945', 10, 2 ); function save_postdata_wpse_76945( $post_id, $post_object ) { // Auto save? if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // Correct post_type if ( 'post' != $post_object->post_type ) return; // Security if ( !isset($_POST['noncename_wpse_76945']) || !wp_verify_nonce( $_POST['noncename_wpse_76945'], plugin_basename( __FILE__ ) ) ) return; // Prepare contents $add_cpt_clone = array( 'post_title' => $post_object->post_title, '_surl_redirect' => get_post_meta( get_the_ID(), 'url' ), 'post_status' => 'publish', 'post_type' => 'surl' ); // Insert the post into the database $p_id = wp_insert_post( $add_cpt_clone ); // Use $p_id to insert new terms } ``` I know i am doing some mistake here ``` '_surl_redirect' => get_post_meta( get_the_ID(), 'url' ), ``` But i don't know how to correct it. I am using ACF for generating custom field URL. Any Ideas. It's very urgent and i am using Genesis and therefore, i don't want to use any other plugin that is not done by Genesis team. Regards
As already pointed out, random ordering and searching is quite expensive operations to run, so lets look at how we are going to sort that issue. Because you only need one post from your custom post type, we only need one random ID which we can pass to `get_post()` in order to get the desired post. Instead of getting the post randomly from the db, we will query all custom post types (*or at least all the post ID's*), save that into a transient, and then we can just pick a random ID from that option. Lets look at some code: (*This goes into functions.php*) ``` function get_random_id( $post_type = '' ) { $q = []; // Make sure we have a post type set, check if it exists and sanitize $post_type = filter_var( $post_type, FILTER_SANITIZE_STRING ); if ( !$post_type ) return $q; if ( !post_type_exists( $post_type ) ) return $q; // The post type exist and is valid, lets continue $transient_name = 'rand_ids_' . md5( $post_type ); // Get the transient, if we have one already if ( false === ( $q = get_transient ( $transient_name ) ) ) { $args = [ 'post_type' => $post_type, 'posts_per_page' => -1, 'fields' => 'ids', // get only post ID's // Add any additional arguments ]; $q = get_posts( $args ); // Set the transient set_transient( $transient_name, $q, 30*DAY_IN_SECONDS ); } // endif get_transient return $q; } ``` What we have done, we have now saved all custom post type ids into a transient. This will increase performance by a huge amount. The transient is set for 30 days, so we need to flush and recreate the transient as soon as we publish a new custom post type post. Lets use the `transition_post_status` action hook: (*This goes into functions.php*) ``` add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { // Make sure we only target our specific post type if ( 'advertising' !== $post->post_type ) return; global $wpdb; // Delete the transients $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_rand_ids_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_rand_ids_%')" ); // Lets rebuild the transient get_random_id( $post->post_type ); }, 10, 3 ); ``` All we are left with is to get a random post ID from our `get_random_id()` function and pass that to `get_post()` to get the post object ``` // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $single_post = get_post( $post_type_posts[0] ); // Display the post content } ``` This way you save a lot on resources and is much faster than just simply let SQL choose a random post from the DB Just as example, your advert injector filter can look something like the following ``` add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { // checkbox to show ad, default true if ( get_field('show_advertisement') ) { if ( is_single() && ! is_admin() ) { // Get the array of post ID's $post_type_posts = get_random_id( 'advertising' ); // Make sure we have posts if ( $post_type_posts ) { // Get the post object of the id first in line shuffle( $post_type_posts ); $random_ad = get_post( $post_type_posts[0] ); // Display the post content $link = addhttp( get_field('advertisement_link', $random_ad->ID)); $image = get_field('upload_advertisement', $random_ad->ID); // get html $ad_code = '<a href="'.$link.'" target="_blank"><img src="'.$image.'" /></a>'; // show ad after # paragraphs $show_after = get_field('advertisement_show_after'); // return appended $content return prefix_insert_after_paragraph( $ad_code, $show_after, $content ); } } } return $content; } ```
218,765
<p>I have been working on open source plugin and trying to add a new feature to it. For now I have been doing like this</p> <pre><code>else if( $selected_report == "greport" ) { $sql = mysql_query( "SELECT rating_postid FROM {$wpdb-&gt;ratings}" ) or die( mysql_error() ); } generate_csv( $sql ); exit; function generate_csv( $sql ) { header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=data.csv' ); $row = mysql_fetch_assoc( $sql ); $fp = fopen( 'php://output', 'w' ); if( $row ) { fputcsv( $fp, array_keys( $row ) ); mysql_data_seek( $sql, 0 ); } while( $row = mysql_fetch_assoc( $sql ) ) { fputcsv( $fp, $row ); } fclose( $fp ); } </code></pre> <p>This works perfectly but I have been told to use WordPress functions in order to get the data. I changed the query to something like this </p> <pre><code>$sql = $wpdb-&gt; get_results( "SELECT rating_id FROM {$wpdb-&gt;ratings}" ); </code></pre> <p>This is creating problems with downloading function as it does not recognize <code>sql_fetch_assoc</code>. I tried to just iterate the values which also didn't work. This is the first time I am working with WordPress. Any suggestions would be a great help.</p>
[ { "answer_id": 218781, "author": "Mridul Aggarwal", "author_id": 22495, "author_profile": "https://wordpress.stackexchange.com/users/22495", "pm_score": 0, "selected": false, "text": "<p>You should never use any mysql functions in wordpress. When you call wordpress functions, you will get the data directly returned to you. For eg.</p>\n\n<pre><code>$values = $wpdb-&gt;get_col( \"SELECT rating_id FROM {$wpdb-&gt;ratings}\" );\nforeach($values as $value) {\n // $value is the exact value as stored in the mysql database table\n}\n</code></pre>\n\n<p>For more details, refer <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n" }, { "answer_id": 218782, "author": "Wes Moberly", "author_id": 59636, "author_profile": "https://wordpress.stackexchange.com/users/59636", "pm_score": 2, "selected": true, "text": "<p>By default <code>$wpdb-&gt;get_results()</code> returns results in the form of an array of objects. If you want an array of associative arrays instead, just do this:</p>\n\n<pre><code>$results = $wpdb-&gt;get_results( \"...\", ARRAY_A );\n</code></pre>\n\n<p>Obviously I'm not familiar with your project or the code you're using, and I haven't tested this, but you'd probably want to do something like the following:</p>\n\n<pre><code>$results = $wpdb-&gt;get_results(\n \"SELECT rating_postid FROM {$wpdb-&gt;ratings}\",\n ARRAY_A\n);\n\nif ( ! empty( $results ) ) {\n\n header( 'Content-Type: text/csv; charset=utf-8' );\n header( 'Content-Disposition: attachment; filename=data.csv' );\n\n $fp = fopen( 'php://output', 'w' );\n\n fputcsv( $fp, array_keys( $results[0] ) );\n\n foreach ( $results as $row ) {\n fputcsv( $fp, $row );\n }\n\n fclose( $fp );\n\n}\n</code></pre>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88932/" ]
I have been working on open source plugin and trying to add a new feature to it. For now I have been doing like this ``` else if( $selected_report == "greport" ) { $sql = mysql_query( "SELECT rating_postid FROM {$wpdb->ratings}" ) or die( mysql_error() ); } generate_csv( $sql ); exit; function generate_csv( $sql ) { header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=data.csv' ); $row = mysql_fetch_assoc( $sql ); $fp = fopen( 'php://output', 'w' ); if( $row ) { fputcsv( $fp, array_keys( $row ) ); mysql_data_seek( $sql, 0 ); } while( $row = mysql_fetch_assoc( $sql ) ) { fputcsv( $fp, $row ); } fclose( $fp ); } ``` This works perfectly but I have been told to use WordPress functions in order to get the data. I changed the query to something like this ``` $sql = $wpdb-> get_results( "SELECT rating_id FROM {$wpdb->ratings}" ); ``` This is creating problems with downloading function as it does not recognize `sql_fetch_assoc`. I tried to just iterate the values which also didn't work. This is the first time I am working with WordPress. Any suggestions would be a great help.
By default `$wpdb->get_results()` returns results in the form of an array of objects. If you want an array of associative arrays instead, just do this: ``` $results = $wpdb->get_results( "...", ARRAY_A ); ``` Obviously I'm not familiar with your project or the code you're using, and I haven't tested this, but you'd probably want to do something like the following: ``` $results = $wpdb->get_results( "SELECT rating_postid FROM {$wpdb->ratings}", ARRAY_A ); if ( ! empty( $results ) ) { header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=data.csv' ); $fp = fopen( 'php://output', 'w' ); fputcsv( $fp, array_keys( $results[0] ) ); foreach ( $results as $row ) { fputcsv( $fp, $row ); } fclose( $fp ); } ```
218,784
<p>I am building a plugin that uses Stripe for the payment processing. I have included Stripe's PHP library into my plugin and everything works great. But what if someone else makes a plugin that also uses Stripe ... or worse, an older version of Stripe that isn't compatible with mine? Sounds like there could be conflicts if someone had both of our plugins activated at the same time.</p> <p>Do I need to namespace Stripe's classes? Is that advisable? I imagine that being a maintenance nightmare if I ever want to upgrade to a newer version of Stripe's library.</p> <p>I'm totally OK doing that, but I want to make sure I'm following best practices here.</p> <p>Thanks! Tony</p>
[ { "answer_id": 219064, "author": "Tony DeStefano", "author_id": 84214, "author_profile": "https://wordpress.stackexchange.com/users/84214", "pm_score": 2, "selected": false, "text": "<p>I went ahead and namespaced Stripe. Everything worked just great. And now I don't have to worry about any one else's Stripe library messing up my stuff.</p>\n\n<p>Original:</p>\n\n<pre><code>namespace Stripe;\n</code></pre>\n\n<p>New:</p>\n\n<pre><code>namespace MyRadNamespace\\Stripe;\n</code></pre>\n\n<p>If anyone is interested in seeing how it's done, feel free to browse my repo:</p>\n\n<p><a href=\"https://github.com/Spokane-Wordpress-Development/Freezy-Stripe\" rel=\"nofollow\">https://github.com/Spokane-Wordpress-Development/Freezy-Stripe</a></p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 219866, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>As I looked through the <a href=\"https://github.com/Spokane-Wordpress-Development/Freezy-Stripe/blob/86dceeef97aa5eb014cfc9f7c605416c6a08ce82/classes/Stripe/init.php\" rel=\"nofollow\">link to the repo</a> attached in the answer, I noticed the incredible amount of <code>requice</code> statements in a single file. The main problem is that the repo is missing a autoloader that can be optimized project wide and as well as that the plugin includes all those files no matter if needed or not.</p>\n\n<p>When you start using <em>Composer</em> to manage attachments, you will find that it creates an <code>autoload.php</code> file for every single package that you write (or fetch). You can then create complete <em>projects</em> using Composer as package manager, which, as a nice side effect, also creates a <em>centralized</em> <code>autoload.php</code> file instead of one autoloader per included package (plugin/theme/etc). On top of this single autoloader, Composer also builds a \"Class > File\" map as \"cache\" to avoid as many disk reads as possible, which will keep class lookups as fast as possible.</p>\n\n<p>This will avoid having to namespace vendor namespaced classes. Meaning that in case multiple packages have a <a href=\"https://getcomposer.org/doc/04-schema.md\" rel=\"nofollow\"><code>composer.json</code></a> file, there will be only one location where those vendor packages will get saved (therefore saving bandwidth and disk space) and fetched from. Even if one did not ignore vendor files in a VCS controlled package, there is no need to load them anymore. </p>\n\n<pre><code># Before in Package (A)\n$stripe = new \\MyRadNamespace\\Stripe;\n# Before in Package (B)\n$stripe = new \\MyFunkyNamespace\\Stripe;\n\n# After – anywhere!\n$stripe = new \\Stripe;\n</code></pre>\n\n<p>In case a plugin or theme does not support Composer yet, you can simply fetch it via the <a href=\"https://wpackagist.org/\" rel=\"nofollow\">WPackagist</a> proxy/mirror service.</p>\n\n<p>To get a quick start with the Composer package manager, I suggest using <a href=\"https://github.com/wecodemore/wpstarter\" rel=\"nofollow\">wecodemore/wpstarter</a> by @gmazzap – <a href=\"http://wecodemore.github.io/wpstarter/\" rel=\"nofollow\">docs here</a>.</p>\n" } ]
2016/02/24
[ "https://wordpress.stackexchange.com/questions/218784", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84214/" ]
I am building a plugin that uses Stripe for the payment processing. I have included Stripe's PHP library into my plugin and everything works great. But what if someone else makes a plugin that also uses Stripe ... or worse, an older version of Stripe that isn't compatible with mine? Sounds like there could be conflicts if someone had both of our plugins activated at the same time. Do I need to namespace Stripe's classes? Is that advisable? I imagine that being a maintenance nightmare if I ever want to upgrade to a newer version of Stripe's library. I'm totally OK doing that, but I want to make sure I'm following best practices here. Thanks! Tony
I went ahead and namespaced Stripe. Everything worked just great. And now I don't have to worry about any one else's Stripe library messing up my stuff. Original: ``` namespace Stripe; ``` New: ``` namespace MyRadNamespace\Stripe; ``` If anyone is interested in seeing how it's done, feel free to browse my repo: <https://github.com/Spokane-Wordpress-Development/Freezy-Stripe> Cheers!
218,825
<p>I have a warning via WordPress Themecheck plugin WARNING : Found a translation function that is missing a text-domain. Function esc_html__, with the arguments</p> <p>As you can see, there is no arguments listed above and I'm really lost on this.</p> <p>Here's the code function:</p> <pre><code>&lt;?php wp_nonce_field( basename( __FILE__ ), 'matilda_featured_image_nonce' ); $selected = esc_html__( get_post_meta( $object-&gt;ID, 'matilda_featured_image', true ) ); ?&gt; </code></pre> <p>My text domain is "matilda"</p> <p>Thanks for any suggestion.</p>
[ { "answer_id": 219064, "author": "Tony DeStefano", "author_id": 84214, "author_profile": "https://wordpress.stackexchange.com/users/84214", "pm_score": 2, "selected": false, "text": "<p>I went ahead and namespaced Stripe. Everything worked just great. And now I don't have to worry about any one else's Stripe library messing up my stuff.</p>\n\n<p>Original:</p>\n\n<pre><code>namespace Stripe;\n</code></pre>\n\n<p>New:</p>\n\n<pre><code>namespace MyRadNamespace\\Stripe;\n</code></pre>\n\n<p>If anyone is interested in seeing how it's done, feel free to browse my repo:</p>\n\n<p><a href=\"https://github.com/Spokane-Wordpress-Development/Freezy-Stripe\" rel=\"nofollow\">https://github.com/Spokane-Wordpress-Development/Freezy-Stripe</a></p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 219866, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 0, "selected": false, "text": "<p>As I looked through the <a href=\"https://github.com/Spokane-Wordpress-Development/Freezy-Stripe/blob/86dceeef97aa5eb014cfc9f7c605416c6a08ce82/classes/Stripe/init.php\" rel=\"nofollow\">link to the repo</a> attached in the answer, I noticed the incredible amount of <code>requice</code> statements in a single file. The main problem is that the repo is missing a autoloader that can be optimized project wide and as well as that the plugin includes all those files no matter if needed or not.</p>\n\n<p>When you start using <em>Composer</em> to manage attachments, you will find that it creates an <code>autoload.php</code> file for every single package that you write (or fetch). You can then create complete <em>projects</em> using Composer as package manager, which, as a nice side effect, also creates a <em>centralized</em> <code>autoload.php</code> file instead of one autoloader per included package (plugin/theme/etc). On top of this single autoloader, Composer also builds a \"Class > File\" map as \"cache\" to avoid as many disk reads as possible, which will keep class lookups as fast as possible.</p>\n\n<p>This will avoid having to namespace vendor namespaced classes. Meaning that in case multiple packages have a <a href=\"https://getcomposer.org/doc/04-schema.md\" rel=\"nofollow\"><code>composer.json</code></a> file, there will be only one location where those vendor packages will get saved (therefore saving bandwidth and disk space) and fetched from. Even if one did not ignore vendor files in a VCS controlled package, there is no need to load them anymore. </p>\n\n<pre><code># Before in Package (A)\n$stripe = new \\MyRadNamespace\\Stripe;\n# Before in Package (B)\n$stripe = new \\MyFunkyNamespace\\Stripe;\n\n# After – anywhere!\n$stripe = new \\Stripe;\n</code></pre>\n\n<p>In case a plugin or theme does not support Composer yet, you can simply fetch it via the <a href=\"https://wpackagist.org/\" rel=\"nofollow\">WPackagist</a> proxy/mirror service.</p>\n\n<p>To get a quick start with the Composer package manager, I suggest using <a href=\"https://github.com/wecodemore/wpstarter\" rel=\"nofollow\">wecodemore/wpstarter</a> by @gmazzap – <a href=\"http://wecodemore.github.io/wpstarter/\" rel=\"nofollow\">docs here</a>.</p>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33903/" ]
I have a warning via WordPress Themecheck plugin WARNING : Found a translation function that is missing a text-domain. Function esc\_html\_\_, with the arguments As you can see, there is no arguments listed above and I'm really lost on this. Here's the code function: ``` <?php wp_nonce_field( basename( __FILE__ ), 'matilda_featured_image_nonce' ); $selected = esc_html__( get_post_meta( $object->ID, 'matilda_featured_image', true ) ); ?> ``` My text domain is "matilda" Thanks for any suggestion.
I went ahead and namespaced Stripe. Everything worked just great. And now I don't have to worry about any one else's Stripe library messing up my stuff. Original: ``` namespace Stripe; ``` New: ``` namespace MyRadNamespace\Stripe; ``` If anyone is interested in seeing how it's done, feel free to browse my repo: <https://github.com/Spokane-Wordpress-Development/Freezy-Stripe> Cheers!
218,827
<p>I have a post with text then "the more" then text after that.</p> <p>The teaser before the more displays on the archive page, but I don't want to display it on my single post page, only the text after the more should appear.</p> <p>How do I do this? </p> <p>i.e</p> <p>This is my text before the more don't show it.</p> <p>--The More--</p> <p>Text after the more to be displayed on single page.</p>
[ { "answer_id": 218834, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>You probably looking at something like <a href=\"https://codex.wordpress.org/Function_Reference/get_extended\" rel=\"nofollow\"><code>get_extended()</code></a>. It returns the content in an array with the following key=>value pairs</p>\n\n<ul>\n<li><p><code>main</code> => The content before the more tag</p></li>\n<li><p><code>extended</code> => The content after the more tag</p></li>\n<li><p><code>more_text</code> => The custom read more text</p></li>\n</ul>\n\n<p>So you would want to do the following in your single post page inside the loop</p>\n\n<pre><code>$content = get_extended( $post-&gt;post_content );\n$extended = apply_filters( 'the_content', $content['extended'] );\necho $extended;\n</code></pre>\n" }, { "answer_id": 218835, "author": "MrFox", "author_id": 69240, "author_profile": "https://wordpress.stackexchange.com/users/69240", "pm_score": 0, "selected": false, "text": "<p>This seems to be working for me:</p>\n\n<pre><code>$aftermore = 3 + strpos($post-&gt;post_content, '--&gt;');\n$devcontent = substr($post-&gt;post_content,$aftermore);\necho wpautop($devcontent);?&gt;\nendif;\n</code></pre>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69240/" ]
I have a post with text then "the more" then text after that. The teaser before the more displays on the archive page, but I don't want to display it on my single post page, only the text after the more should appear. How do I do this? i.e This is my text before the more don't show it. --The More-- Text after the more to be displayed on single page.
You probably looking at something like [`get_extended()`](https://codex.wordpress.org/Function_Reference/get_extended). It returns the content in an array with the following key=>value pairs * `main` => The content before the more tag * `extended` => The content after the more tag * `more_text` => The custom read more text So you would want to do the following in your single post page inside the loop ``` $content = get_extended( $post->post_content ); $extended = apply_filters( 'the_content', $content['extended'] ); echo $extended; ```
218,843
<p>I have created a custom theme. Now I want to add WooCommerce to that theme but it doesn't work like the way it should.</p> <p>After install of the WooCommerce plugin I followed all provided steps.<br>All pages needed are created and I have added my first product.</p> <p>In the admin panel I get the message:</p> <blockquote> <p>Your theme does not declare woocommerce support</p> </blockquote> <p>In the same message is a link to a WooCommerce page that tells you how to fix it.<br> <a href="https://docs.woothemes.com/document/third-party-custom-theme-compatibility/" rel="nofollow">https://docs.woothemes.com/document/third-party-custom-theme-compatibility/</a></p> <p>So I did this and my page template fort WooCommerce now looks like this:</p> <pre><code>&lt;?php /* Template Name: WooCommerce */ ?&gt; &lt;?php get_header(); ?&gt; &lt;div id="cc_sbr"&gt; &lt;div class="c1_sbr"&gt; &lt;?php woocommerce_content(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>It is called <code>woocommerce.php</code></p> <p>In my <code>functions.php</code> I have added <code>add_theme_support('woocommerce');</code></p> <p>So now my "store" page gives me the following:<br> Title: Shop<br> Content: Only result</p> <p>But no content.<br></p> <p>Can anyone help me by telling me what I do wrong or am missing?</p> <p>M.</p>
[ { "answer_id": 218846, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 1, "selected": false, "text": "<p>Oke found it....</p>\n\n<p>You (I) have to update the permalinks settings.</p>\n\n<p>There is a shoppart added to the default page. <br>\nselect the custom part and add the name of your shop page starting with a <code>/</code><br>\ne.g. <code>/shop</code></p>\n" }, { "answer_id": 218856, "author": "Piyush Dhanotiya", "author_id": 74324, "author_profile": "https://wordpress.stackexchange.com/users/74324", "pm_score": 0, "selected": false, "text": "<p>Add this in your theme functions.php</p>\n\n<p>add_action( 'after_setup_theme', 'woocommerce_support' );\n function woocommerce_support() {\n add_theme_support( 'woocommerce' );\n }</p>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52240/" ]
I have created a custom theme. Now I want to add WooCommerce to that theme but it doesn't work like the way it should. After install of the WooCommerce plugin I followed all provided steps. All pages needed are created and I have added my first product. In the admin panel I get the message: > > Your theme does not declare woocommerce support > > > In the same message is a link to a WooCommerce page that tells you how to fix it. <https://docs.woothemes.com/document/third-party-custom-theme-compatibility/> So I did this and my page template fort WooCommerce now looks like this: ``` <?php /* Template Name: WooCommerce */ ?> <?php get_header(); ?> <div id="cc_sbr"> <div class="c1_sbr"> <?php woocommerce_content(); ?> </div> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` It is called `woocommerce.php` In my `functions.php` I have added `add_theme_support('woocommerce');` So now my "store" page gives me the following: Title: Shop Content: Only result But no content. Can anyone help me by telling me what I do wrong or am missing? M.
Oke found it.... You (I) have to update the permalinks settings. There is a shoppart added to the default page. select the custom part and add the name of your shop page starting with a `/` e.g. `/shop`
218,877
<p>In a custom post type I have set <code>has_archive</code> to <code>false</code>. In the head of a CPT page however I still find a link to a feed like this: </p> <pre><code>&lt;link … title="Page Title | Comments Feed" href="domain/cpt/slug/feed/" /&gt; </code></pre> <p>The feed doesn't exist – the link generates a 404 error. I tried to remove the link with the filter <code>feed_links_show_comments_feed</code> which only had an effect on the regular posts' comment feed:</p> <pre><code>add_filter( 'feed_links_show_comments_feed', '__return_false' ); </code></pre> <p>…the cpt comment feed was still there.</p> <p>I also tried to rmove <strong>all</strong> feeds – which again worked on all feeds but the one I wanted to remove:</p> <pre><code>remove_action( 'wp_head', 'feed_links', 2 ); </code></pre> <p>If I however would set <code>has_archive</code> to <code>true</code> the link would actually lead to a valid rss feed of comments – which I basically wouldn't mind. But I can not have <code>has_archive</code> set to <code>true</code> since I need the base slug for some custom page and I don't want an archives page to appear on the slug's url.</p> <p>I hope somebody can point me in the right direction? All pointers welcome. Thank you!</p>
[ { "answer_id": 235052, "author": "user2100505", "author_id": 100490, "author_profile": "https://wordpress.stackexchange.com/users/100490", "pm_score": 3, "selected": true, "text": "<p>Following command hides comments feed for posts (WP 4.4+ required!), but custom pages still have comments feed displayed, even if comments are disabled for such page:</p>\n\n<pre><code>add_filter( 'feed_links_show_comments_feed', '__return_false' );\n</code></pre>\n\n<p>To resolve this, I had to add this addidtional code too:</p>\n\n<pre><code>function remove_comments_rss( $for_comments ) {\n return;\n}\nadd_filter('post_comments_feed_link','remove_comments_rss');\n</code></pre>\n" }, { "answer_id": 279639, "author": "Jeroen Schmit", "author_id": 53926, "author_profile": "https://wordpress.stackexchange.com/users/53926", "pm_score": 0, "selected": false, "text": "<p>You can remove the comments feed for a custom post type by telling WordPress that comments are closed for a particular post type using the <a href=\"https://developer.wordpress.org/reference/hooks/comments_open/\" rel=\"nofollow noreferrer\"><code>comments_open</code></a> filter:</p>\n\n<pre><code> function close_comments( $open, $post_id ) {\n if ( 'cpt' == get_post_type( $post_id ) ) {\n $open = false;\n }\n return $open;\n }\n add_filter( 'comments_open', 'close_comments', 10, 2 );\n</code></pre>\n\n<p>Make sure you replace 'cpt' with your post type name.</p>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26059/" ]
In a custom post type I have set `has_archive` to `false`. In the head of a CPT page however I still find a link to a feed like this: ``` <link … title="Page Title | Comments Feed" href="domain/cpt/slug/feed/" /> ``` The feed doesn't exist – the link generates a 404 error. I tried to remove the link with the filter `feed_links_show_comments_feed` which only had an effect on the regular posts' comment feed: ``` add_filter( 'feed_links_show_comments_feed', '__return_false' ); ``` …the cpt comment feed was still there. I also tried to rmove **all** feeds – which again worked on all feeds but the one I wanted to remove: ``` remove_action( 'wp_head', 'feed_links', 2 ); ``` If I however would set `has_archive` to `true` the link would actually lead to a valid rss feed of comments – which I basically wouldn't mind. But I can not have `has_archive` set to `true` since I need the base slug for some custom page and I don't want an archives page to appear on the slug's url. I hope somebody can point me in the right direction? All pointers welcome. Thank you!
Following command hides comments feed for posts (WP 4.4+ required!), but custom pages still have comments feed displayed, even if comments are disabled for such page: ``` add_filter( 'feed_links_show_comments_feed', '__return_false' ); ``` To resolve this, I had to add this addidtional code too: ``` function remove_comments_rss( $for_comments ) { return; } add_filter('post_comments_feed_link','remove_comments_rss'); ```
218,885
<p>I am building a plugin. I have to output certain stuff in the header.php file of the theme depending on if/else I will write. However I am not at that point yet. I just learned in order to push the function into header.php I have to use <code>wp_head</code>. Unfortuatenly when I do this I get a lot of extra stuff processed by WordPress jammed into the <code>wp_head</code> function.</p> <pre><code>&lt;meta name='robots' content='noindex,follow' /&gt; &lt;script type="text/javascript"&gt; window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png","source":{"concatemoji":"http:\/\/zachis.it\/client\/wgp-master\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.4.2"}}; !function(a,b,c){function d(a){var c,d=b.createElement("canvas"),e=d.getContext&amp;&amp;d.getContext("2d"),f=String.fromCharCode;return e&amp;&amp;e.fillText?(e.textBaseline="top",e.font="600 32px Arial","flag"===a?(e.fillText(f(55356,56806,55356,56826),0,0),d.toDataURL().length&gt;3e3):"diversity"===a?(e.fillText(f(55356,57221),0,0),c=e.getImageData(16,16,1,1).data.toString(),e.fillText(f(55356,57221,55356,57343),0,0),c!==e.getImageData(16,16,1,1).data.toString()):("simple"===a?e.fillText(f(55357,56835),0,0):e.fillText(f(55356,57135),0,0),0!==e.getImageData(16,16,1,1).data[0])):!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g;c.supports={simple:d("simple"),flag:d("flag"),unicode8:d("unicode8"),diversity:d("diversity")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&amp;&amp;c.supports.flag&amp;&amp;c.supports.unicode8&amp;&amp;c.supports.diversity||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&amp;&amp;c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&amp;&amp;f.twemoji&amp;&amp;(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings); &lt;/script&gt; &lt;style type="text/css"&gt; img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 .07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } &lt;/style&gt; &lt;link rel='stylesheet' id='open-sans-css' href='https://fonts.googleapis.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&amp;#038;subset=latin%2Clatin-ext&amp;#038;ver=4.4.2' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='dashicons-css' href='http://zachis.it/client/wgp-master/wp-includes/css/dashicons.min.css?ver=4.4.2' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='admin-bar-css' href='http://zachis.it/client/wgp-master/wp-includes/css/admin-bar.min.css?ver=4.4.2' type='text/css' media='all' /&gt; &lt;link rel='https://api.w.org/' href='http://zachis.it/client/wgp-master/wp-json/' /&gt; &lt;link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://zachis.it/client/wgp-master/xmlrpc.php?rsd" /&gt; &lt;link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://zachis.it/client/wgp-master/wp-includes/wlwmanifest.xml" /&gt; &lt;meta name="generator" content="WordPress 4.4.2" /&gt; test&lt;style type="text/css" media="print"&gt;#wpadminbar { display:none; }&lt;/style&gt; &lt;style type="text/css" media="screen"&gt; html { margin-top: 32px !important; } * html body { margin-top: 32px !important; } @media screen and ( max-width: 782px ) { html { margin-top: 46px !important; } * html body { margin-top: 46px !important; } } &lt;/style&gt; </code></pre> <p>Is there another way to post variables from a plugin into the header.php without using <code>wp_head</code>?</p>
[ { "answer_id": 218891, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 3, "selected": true, "text": "<p>Removing wp_head will have some negative effects as it won't allow you to use virtually 90% of the plugins on wordpress.org. Also some of that code you are seeing only shows up when you are logged in (unless your theme is specifically adding it). For example, the dashicons, open sans, and admin-bar stylesheets and inline styles at the bottom are all there so you can use the admin bar on the frontend. </p>\n\n<p>Here are some options.</p>\n\n<p><strong>1. Custom header - This is a safe alternative if you don't want wp_head in some of your pages, but still want to be able to use it and other wordpress plugins on other templates.</strong></p>\n\n<ol>\n<li>Create a file <code>header-custom.php</code> in your theme folder that doesn't include <code>wp_head</code></li>\n<li>In your custom <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/\" rel=\"nofollow noreferrer\">page template</a> call that header using <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow noreferrer\"><code>&lt;?php get_header( 'custom' ); ?&gt;</code></a></li>\n<li>If you wan't to be able to hook into this still with through your plugin you can use a custom action instead of wp_head. Basically all you have to do is add <code>&lt;?php do_action('custom_head'); ?&gt;</code> and then in your plugin hook into that the same way you would wp_head.</li>\n</ol>\n\n<p><em>Example</em> </p>\n\n<pre><code>function my_plugin_custom_head_action() {\n // do stuff here\n}\nadd_action('custom_head', 'my_plugin_custom_head_action');\n</code></pre>\n\n<p>There's also a <a href=\"https://wordpress.org/plugins/tha-hooks-interface/\" rel=\"nofollow noreferrer\">plugin</a> that makes this process of using custom hooks/actions very easy.</p>\n\n<hr>\n\n<p><strong>2. Remove stuff you don't want from wp_head</strong> </p>\n\n<pre><code>// Remove emojis\nfunction disable_emojis_wp_head() {\n remove_action( 'wp_head', 'print_emoji_detection_script', 7 );\n remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );\n remove_action( 'wp_print_styles', 'print_emoji_styles' );\n remove_action( 'admin_print_styles', 'print_emoji_styles' ); \n remove_filter( 'the_content_feed', 'wp_staticize_emoji' );\n remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); \n remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );\n add_filter( 'tiny_mce_plugins', 'disable_emojis_wp_tinymce' );\n}\nadd_action( 'init', 'disable_emojis_wp_head' );\n\nfunction disable_emojis_wp_tinymce( $plugins ) {\n if ( is_array( $plugins ) ) {\n return array_diff( $plugins, array( 'wpemoji' ) );\n } else {\n return array();\n }\n}\n\n// Remove other crap in your example\nadd_action( 'get_header', function() {\n remove_action('wp_head', 'rsd_link'); // Really Simple Discovery service endpoint, EditURI link\n remove_action('wp_head', 'wp_generator'); // XHTML generator that is generated on the wp_head hook, WP version\n remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed\n remove_action('wp_head', 'index_rel_link'); // index link\n remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file.\n remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds\n remove_action('wp_head', 'start_post_rel_link', 10, 0); // start link\n remove_action('wp_head', 'parent_post_rel_link', 10, 0); // prev link\n remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // relational links 4 the posts adjacent 2 the currentpost\n remove_action('template_redirect', 'wp_shortlink_header', 11); \n remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );\n}, 99);\n\n// Remove adminbar inline css on frontend\nfunction removeinline_adminbar_css_frontend() {\n if ( has_filter( 'wp_head', '_admin_bar_bump_cb' ) ){\n remove_filter( 'wp_head', '_admin_bar_bump_cb' );\n }\n}\nadd_filter( 'wp_head', 'removeinline_adminbar_css_frontend', 1 );\n</code></pre>\n\n<p>And if you want to remove the rest api link I believe this will work:</p>\n\n<pre><code>remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 );\n</code></pre>\n\n<p>See this <a href=\"https://wordpress.stackexchange.com/questions/211467/remove-json-api-links-in-header-html\">WPSE post here</a> for additional solutions removing rest api.</p>\n" }, { "answer_id": 402388, "author": "arafatgazi", "author_id": 205432, "author_profile": "https://wordpress.stackexchange.com/users/205432", "pm_score": 0, "selected": false, "text": "<p>@bryan-willis has a great answer that allows you to individually remove things from <code>wp_head</code>. This can be a better approach in most cases, but if you don't really need all the extra stuff that come with <code>wp_head()</code>, you may decide to go without it.</p>\n<p>However, if you remove <code>wp_head</code> entirely from your header or template, you won't be able to use hooks like <code>wp_enqueue_scripts</code>, which makes things easy when you want to load your own CSS and JS files in your template. That's why if you keep <code>wp_head</code> in your template but remove everything from it except the ones you need, your template will output a clean head while allowing you to benefit from <code>wp_head()</code>.</p>\n<p>This way, you won't have to identify and remove every specific thing that WordPress or other themes or plugins load on your template.</p>\n<p><strong>Remove all functions from <code>wp_head</code> hook, and maybe from <code>wp_footer</code> hook except the ones you need.</strong></p>\n<pre><code>function unhook_wp_head_footer() {\n\n if ( /* some condition */ ) {\n\n global $wp_filter; // it contains all hooks\n\n foreach ( $wp_filter['wp_head']-&gt;callbacks as $priority =&gt; $wp_head_hooks ) {\n if ( is_array( $wp_head_hooks ) ){\n foreach ( $wp_head_hooks as $idx =&gt; $wp_head_hook ) {\n if ( $wp_head_hook['function'] !== 'wp_enqueue_scripts' // keep functionality of wp_enqueue_scripts\n &amp;&amp; $wp_head_hook['function'] !== 'wp_print_head_scripts' // to allow wp_enqueue_scripts load js inside the head element\n &amp;&amp; $wp_head_hook['function'] !== 'wp_print_styles' ) { // to allow wp_enqueue_scripts load css inside the head element\n remove_action( 'wp_head', $wp_head_hook['function'], $priority );\n }\n }\n }\n }\n\n foreach ( $wp_filter['wp_footer']-&gt;callbacks as $priority =&gt; $wp_footer_hooks ) {\n if ( is_array( $wp_footer_hooks ) ) {\n foreach ( $wp_footer_hooks as $idx =&gt; $wp_footer_hook ) {\n if ( $wp_footer_hook['function'] !== 'wp_print_footer_scripts' ) { // to allow wp_enqueue_scripts load scripts in the footer\n remove_action( 'wp_footer', $wp_footer_hook['function'], $priority );\n }\n }\n }\n }\n }\n}\nadd_action( 'wp', 'unhook_wp_head_footer' );\n</code></pre>\n<p><strong>In case of keeping <code>wp_enqueue_scripts</code>, dequeue all CSS and JS that you don't need.</strong></p>\n<pre><code>// dequeue all assets if not from your plugin\npublic function dequeue_assets() {\n\n if ( /* some condition */ ) {\n\n global $wp_styles, $wp_scripts;\n\n $prefix = 'plugin-handle'; // your plugin name used as prefix in $handle of wp_enqueue_script or wp_enqueue_style function calls\n\n foreach ( $wp_styles-&gt;queue as $handle ) {\n if ( strpos( $handle, $prefix ) !== 0 ) {\n wp_deregister_style( $handle );\n wp_dequeue_style( $handle );\n }\n }\n\n foreach ( $wp_scripts-&gt;queue as $handle ) {\n if ( strpos( $handle, $prefix ) !== 0 ) {\n wp_deregister_script( $handle );\n wp_dequeue_script( $handle );\n }\n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'dequeue_assets', 9999 );\n</code></pre>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
I am building a plugin. I have to output certain stuff in the header.php file of the theme depending on if/else I will write. However I am not at that point yet. I just learned in order to push the function into header.php I have to use `wp_head`. Unfortuatenly when I do this I get a lot of extra stuff processed by WordPress jammed into the `wp_head` function. ``` <meta name='robots' content='noindex,follow' /> <script type="text/javascript"> window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png","source":{"concatemoji":"http:\/\/zachis.it\/client\/wgp-master\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.4.2"}}; !function(a,b,c){function d(a){var c,d=b.createElement("canvas"),e=d.getContext&&d.getContext("2d"),f=String.fromCharCode;return e&&e.fillText?(e.textBaseline="top",e.font="600 32px Arial","flag"===a?(e.fillText(f(55356,56806,55356,56826),0,0),d.toDataURL().length>3e3):"diversity"===a?(e.fillText(f(55356,57221),0,0),c=e.getImageData(16,16,1,1).data.toString(),e.fillText(f(55356,57221,55356,57343),0,0),c!==e.getImageData(16,16,1,1).data.toString()):("simple"===a?e.fillText(f(55357,56835),0,0):e.fillText(f(55356,57135),0,0),0!==e.getImageData(16,16,1,1).data[0])):!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g;c.supports={simple:d("simple"),flag:d("flag"),unicode8:d("unicode8"),diversity:d("diversity")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&&c.supports.flag&&c.supports.unicode8&&c.supports.diversity||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings); </script> <style type="text/css"> img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 .07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } </style> <link rel='stylesheet' id='open-sans-css' href='https://fonts.googleapis.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&#038;subset=latin%2Clatin-ext&#038;ver=4.4.2' type='text/css' media='all' /> <link rel='stylesheet' id='dashicons-css' href='http://zachis.it/client/wgp-master/wp-includes/css/dashicons.min.css?ver=4.4.2' type='text/css' media='all' /> <link rel='stylesheet' id='admin-bar-css' href='http://zachis.it/client/wgp-master/wp-includes/css/admin-bar.min.css?ver=4.4.2' type='text/css' media='all' /> <link rel='https://api.w.org/' href='http://zachis.it/client/wgp-master/wp-json/' /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://zachis.it/client/wgp-master/xmlrpc.php?rsd" /> <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://zachis.it/client/wgp-master/wp-includes/wlwmanifest.xml" /> <meta name="generator" content="WordPress 4.4.2" /> test<style type="text/css" media="print">#wpadminbar { display:none; }</style> <style type="text/css" media="screen"> html { margin-top: 32px !important; } * html body { margin-top: 32px !important; } @media screen and ( max-width: 782px ) { html { margin-top: 46px !important; } * html body { margin-top: 46px !important; } } </style> ``` Is there another way to post variables from a plugin into the header.php without using `wp_head`?
Removing wp\_head will have some negative effects as it won't allow you to use virtually 90% of the plugins on wordpress.org. Also some of that code you are seeing only shows up when you are logged in (unless your theme is specifically adding it). For example, the dashicons, open sans, and admin-bar stylesheets and inline styles at the bottom are all there so you can use the admin bar on the frontend. Here are some options. **1. Custom header - This is a safe alternative if you don't want wp\_head in some of your pages, but still want to be able to use it and other wordpress plugins on other templates.** 1. Create a file `header-custom.php` in your theme folder that doesn't include `wp_head` 2. In your custom [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/) call that header using [`<?php get_header( 'custom' ); ?>`](https://codex.wordpress.org/Function_Reference/get_header) 3. If you wan't to be able to hook into this still with through your plugin you can use a custom action instead of wp\_head. Basically all you have to do is add `<?php do_action('custom_head'); ?>` and then in your plugin hook into that the same way you would wp\_head. *Example* ``` function my_plugin_custom_head_action() { // do stuff here } add_action('custom_head', 'my_plugin_custom_head_action'); ``` There's also a [plugin](https://wordpress.org/plugins/tha-hooks-interface/) that makes this process of using custom hooks/actions very easy. --- **2. Remove stuff you don't want from wp\_head** ``` // Remove emojis function disable_emojis_wp_head() { remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); add_filter( 'tiny_mce_plugins', 'disable_emojis_wp_tinymce' ); } add_action( 'init', 'disable_emojis_wp_head' ); function disable_emojis_wp_tinymce( $plugins ) { if ( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } // Remove other crap in your example add_action( 'get_header', function() { remove_action('wp_head', 'rsd_link'); // Really Simple Discovery service endpoint, EditURI link remove_action('wp_head', 'wp_generator'); // XHTML generator that is generated on the wp_head hook, WP version remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed remove_action('wp_head', 'index_rel_link'); // index link remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file. remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds remove_action('wp_head', 'start_post_rel_link', 10, 0); // start link remove_action('wp_head', 'parent_post_rel_link', 10, 0); // prev link remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // relational links 4 the posts adjacent 2 the currentpost remove_action('template_redirect', 'wp_shortlink_header', 11); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); }, 99); // Remove adminbar inline css on frontend function removeinline_adminbar_css_frontend() { if ( has_filter( 'wp_head', '_admin_bar_bump_cb' ) ){ remove_filter( 'wp_head', '_admin_bar_bump_cb' ); } } add_filter( 'wp_head', 'removeinline_adminbar_css_frontend', 1 ); ``` And if you want to remove the rest api link I believe this will work: ``` remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 ); ``` See this [WPSE post here](https://wordpress.stackexchange.com/questions/211467/remove-json-api-links-in-header-html) for additional solutions removing rest api.
218,896
<p>We discover that our Single Product images as set in Woocommerce> Setting > Products > Display are set to big. Single Product Image: 500 ×750px xHard Crop</p> <p>I have tested plugin regenerate thumbnails but that does not work on the product images. Also test plugins Resize-image-after-upload. But that plugin does it for all images if bigger then a certain size. So not to use either. Try to get a plugin or functions.php code to re-size all existing product images to the right dimension. Without luck.</p> <p>Question: Do you know a plugin or php code for functions.php that does resize all full product images?</p> <p>Would be very helpful.</p>
[ { "answer_id": 218891, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 3, "selected": true, "text": "<p>Removing wp_head will have some negative effects as it won't allow you to use virtually 90% of the plugins on wordpress.org. Also some of that code you are seeing only shows up when you are logged in (unless your theme is specifically adding it). For example, the dashicons, open sans, and admin-bar stylesheets and inline styles at the bottom are all there so you can use the admin bar on the frontend. </p>\n\n<p>Here are some options.</p>\n\n<p><strong>1. Custom header - This is a safe alternative if you don't want wp_head in some of your pages, but still want to be able to use it and other wordpress plugins on other templates.</strong></p>\n\n<ol>\n<li>Create a file <code>header-custom.php</code> in your theme folder that doesn't include <code>wp_head</code></li>\n<li>In your custom <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/\" rel=\"nofollow noreferrer\">page template</a> call that header using <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow noreferrer\"><code>&lt;?php get_header( 'custom' ); ?&gt;</code></a></li>\n<li>If you wan't to be able to hook into this still with through your plugin you can use a custom action instead of wp_head. Basically all you have to do is add <code>&lt;?php do_action('custom_head'); ?&gt;</code> and then in your plugin hook into that the same way you would wp_head.</li>\n</ol>\n\n<p><em>Example</em> </p>\n\n<pre><code>function my_plugin_custom_head_action() {\n // do stuff here\n}\nadd_action('custom_head', 'my_plugin_custom_head_action');\n</code></pre>\n\n<p>There's also a <a href=\"https://wordpress.org/plugins/tha-hooks-interface/\" rel=\"nofollow noreferrer\">plugin</a> that makes this process of using custom hooks/actions very easy.</p>\n\n<hr>\n\n<p><strong>2. Remove stuff you don't want from wp_head</strong> </p>\n\n<pre><code>// Remove emojis\nfunction disable_emojis_wp_head() {\n remove_action( 'wp_head', 'print_emoji_detection_script', 7 );\n remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );\n remove_action( 'wp_print_styles', 'print_emoji_styles' );\n remove_action( 'admin_print_styles', 'print_emoji_styles' ); \n remove_filter( 'the_content_feed', 'wp_staticize_emoji' );\n remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); \n remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );\n add_filter( 'tiny_mce_plugins', 'disable_emojis_wp_tinymce' );\n}\nadd_action( 'init', 'disable_emojis_wp_head' );\n\nfunction disable_emojis_wp_tinymce( $plugins ) {\n if ( is_array( $plugins ) ) {\n return array_diff( $plugins, array( 'wpemoji' ) );\n } else {\n return array();\n }\n}\n\n// Remove other crap in your example\nadd_action( 'get_header', function() {\n remove_action('wp_head', 'rsd_link'); // Really Simple Discovery service endpoint, EditURI link\n remove_action('wp_head', 'wp_generator'); // XHTML generator that is generated on the wp_head hook, WP version\n remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed\n remove_action('wp_head', 'index_rel_link'); // index link\n remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file.\n remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds\n remove_action('wp_head', 'start_post_rel_link', 10, 0); // start link\n remove_action('wp_head', 'parent_post_rel_link', 10, 0); // prev link\n remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // relational links 4 the posts adjacent 2 the currentpost\n remove_action('template_redirect', 'wp_shortlink_header', 11); \n remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );\n}, 99);\n\n// Remove adminbar inline css on frontend\nfunction removeinline_adminbar_css_frontend() {\n if ( has_filter( 'wp_head', '_admin_bar_bump_cb' ) ){\n remove_filter( 'wp_head', '_admin_bar_bump_cb' );\n }\n}\nadd_filter( 'wp_head', 'removeinline_adminbar_css_frontend', 1 );\n</code></pre>\n\n<p>And if you want to remove the rest api link I believe this will work:</p>\n\n<pre><code>remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 );\n</code></pre>\n\n<p>See this <a href=\"https://wordpress.stackexchange.com/questions/211467/remove-json-api-links-in-header-html\">WPSE post here</a> for additional solutions removing rest api.</p>\n" }, { "answer_id": 402388, "author": "arafatgazi", "author_id": 205432, "author_profile": "https://wordpress.stackexchange.com/users/205432", "pm_score": 0, "selected": false, "text": "<p>@bryan-willis has a great answer that allows you to individually remove things from <code>wp_head</code>. This can be a better approach in most cases, but if you don't really need all the extra stuff that come with <code>wp_head()</code>, you may decide to go without it.</p>\n<p>However, if you remove <code>wp_head</code> entirely from your header or template, you won't be able to use hooks like <code>wp_enqueue_scripts</code>, which makes things easy when you want to load your own CSS and JS files in your template. That's why if you keep <code>wp_head</code> in your template but remove everything from it except the ones you need, your template will output a clean head while allowing you to benefit from <code>wp_head()</code>.</p>\n<p>This way, you won't have to identify and remove every specific thing that WordPress or other themes or plugins load on your template.</p>\n<p><strong>Remove all functions from <code>wp_head</code> hook, and maybe from <code>wp_footer</code> hook except the ones you need.</strong></p>\n<pre><code>function unhook_wp_head_footer() {\n\n if ( /* some condition */ ) {\n\n global $wp_filter; // it contains all hooks\n\n foreach ( $wp_filter['wp_head']-&gt;callbacks as $priority =&gt; $wp_head_hooks ) {\n if ( is_array( $wp_head_hooks ) ){\n foreach ( $wp_head_hooks as $idx =&gt; $wp_head_hook ) {\n if ( $wp_head_hook['function'] !== 'wp_enqueue_scripts' // keep functionality of wp_enqueue_scripts\n &amp;&amp; $wp_head_hook['function'] !== 'wp_print_head_scripts' // to allow wp_enqueue_scripts load js inside the head element\n &amp;&amp; $wp_head_hook['function'] !== 'wp_print_styles' ) { // to allow wp_enqueue_scripts load css inside the head element\n remove_action( 'wp_head', $wp_head_hook['function'], $priority );\n }\n }\n }\n }\n\n foreach ( $wp_filter['wp_footer']-&gt;callbacks as $priority =&gt; $wp_footer_hooks ) {\n if ( is_array( $wp_footer_hooks ) ) {\n foreach ( $wp_footer_hooks as $idx =&gt; $wp_footer_hook ) {\n if ( $wp_footer_hook['function'] !== 'wp_print_footer_scripts' ) { // to allow wp_enqueue_scripts load scripts in the footer\n remove_action( 'wp_footer', $wp_footer_hook['function'], $priority );\n }\n }\n }\n }\n }\n}\nadd_action( 'wp', 'unhook_wp_head_footer' );\n</code></pre>\n<p><strong>In case of keeping <code>wp_enqueue_scripts</code>, dequeue all CSS and JS that you don't need.</strong></p>\n<pre><code>// dequeue all assets if not from your plugin\npublic function dequeue_assets() {\n\n if ( /* some condition */ ) {\n\n global $wp_styles, $wp_scripts;\n\n $prefix = 'plugin-handle'; // your plugin name used as prefix in $handle of wp_enqueue_script or wp_enqueue_style function calls\n\n foreach ( $wp_styles-&gt;queue as $handle ) {\n if ( strpos( $handle, $prefix ) !== 0 ) {\n wp_deregister_style( $handle );\n wp_dequeue_style( $handle );\n }\n }\n\n foreach ( $wp_scripts-&gt;queue as $handle ) {\n if ( strpos( $handle, $prefix ) !== 0 ) {\n wp_deregister_script( $handle );\n wp_dequeue_script( $handle );\n }\n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'dequeue_assets', 9999 );\n</code></pre>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78746/" ]
We discover that our Single Product images as set in Woocommerce> Setting > Products > Display are set to big. Single Product Image: 500 ×750px xHard Crop I have tested plugin regenerate thumbnails but that does not work on the product images. Also test plugins Resize-image-after-upload. But that plugin does it for all images if bigger then a certain size. So not to use either. Try to get a plugin or functions.php code to re-size all existing product images to the right dimension. Without luck. Question: Do you know a plugin or php code for functions.php that does resize all full product images? Would be very helpful.
Removing wp\_head will have some negative effects as it won't allow you to use virtually 90% of the plugins on wordpress.org. Also some of that code you are seeing only shows up when you are logged in (unless your theme is specifically adding it). For example, the dashicons, open sans, and admin-bar stylesheets and inline styles at the bottom are all there so you can use the admin bar on the frontend. Here are some options. **1. Custom header - This is a safe alternative if you don't want wp\_head in some of your pages, but still want to be able to use it and other wordpress plugins on other templates.** 1. Create a file `header-custom.php` in your theme folder that doesn't include `wp_head` 2. In your custom [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/) call that header using [`<?php get_header( 'custom' ); ?>`](https://codex.wordpress.org/Function_Reference/get_header) 3. If you wan't to be able to hook into this still with through your plugin you can use a custom action instead of wp\_head. Basically all you have to do is add `<?php do_action('custom_head'); ?>` and then in your plugin hook into that the same way you would wp\_head. *Example* ``` function my_plugin_custom_head_action() { // do stuff here } add_action('custom_head', 'my_plugin_custom_head_action'); ``` There's also a [plugin](https://wordpress.org/plugins/tha-hooks-interface/) that makes this process of using custom hooks/actions very easy. --- **2. Remove stuff you don't want from wp\_head** ``` // Remove emojis function disable_emojis_wp_head() { remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); add_filter( 'tiny_mce_plugins', 'disable_emojis_wp_tinymce' ); } add_action( 'init', 'disable_emojis_wp_head' ); function disable_emojis_wp_tinymce( $plugins ) { if ( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } // Remove other crap in your example add_action( 'get_header', function() { remove_action('wp_head', 'rsd_link'); // Really Simple Discovery service endpoint, EditURI link remove_action('wp_head', 'wp_generator'); // XHTML generator that is generated on the wp_head hook, WP version remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed remove_action('wp_head', 'index_rel_link'); // index link remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file. remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds remove_action('wp_head', 'start_post_rel_link', 10, 0); // start link remove_action('wp_head', 'parent_post_rel_link', 10, 0); // prev link remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // relational links 4 the posts adjacent 2 the currentpost remove_action('template_redirect', 'wp_shortlink_header', 11); remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); }, 99); // Remove adminbar inline css on frontend function removeinline_adminbar_css_frontend() { if ( has_filter( 'wp_head', '_admin_bar_bump_cb' ) ){ remove_filter( 'wp_head', '_admin_bar_bump_cb' ); } } add_filter( 'wp_head', 'removeinline_adminbar_css_frontend', 1 ); ``` And if you want to remove the rest api link I believe this will work: ``` remove_action( 'template_redirect', 'rest_output_link_header', 11, 0 ); ``` See this [WPSE post here](https://wordpress.stackexchange.com/questions/211467/remove-json-api-links-in-header-html) for additional solutions removing rest api.
218,911
<p>I have post type <code>example</code> with 2 records: <code>exam1</code> and <code>exam2</code>. This post type was created by plugin <code>Types Toolset</code> (<code>www.wp-types.com</code>). So link to <code>exam1</code> looks like <code>my_site/example/exam1</code>. Also I have 1 GET-parameter: <code>my_site/example/exam1?get=param</code>.<br> What I need. I need to rewrite URL from <code>my_site/example/exam1?get=param</code> to <code>my_site/param/exam1</code>. I wrote this rule:</p> <pre><code>RewriteRule ^(exam1|exam2)/([^/]+)/?$ /example/$2/?get=$1 [QSA,L] </code></pre> <p>This is the right rule. It should work. But it does not work. When I go to the <code>my_site/param/exam1</code> , it redirects to <code>my_site/example/exam1</code>. <br> I know that it is <code>redirect_canonical</code>. And I can remove it: <br></p> <pre><code>remove_action('template_redirect', 'redirect_canonical'); </code></pre> <p>But my RewriteRule still not working - no redirects from <code>my_site/example/exam1?get=param</code> to <code>my_site/param/exam1</code>.<br> Why? Please help me. I need it very much.</p>
[ { "answer_id": 218923, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 1, "selected": false, "text": "<h2>Terminology</h2>\n<p>I think you have some terminology a little mixed up:</p>\n<ul>\n<li>A URL &quot;rewrite&quot; alters the endpoint of a HTTP request. If <code>http://example.com/param/exam1</code> really serves content from <code>http://example.com/examples/exam1?get=param</code>, then the former is being rewritten to the latter (though not necessarily visible to the end-user).</li>\n<li>In the world of URL-rewriting, a &quot;redirect&quot; is a rewrite that (instead of serving the request from the altered endpoint) kicks back a HTTP <code>300</code>-range status code, telling the client that sent the HTTP request to send a new request to the rewritten URL (thus altering the address visible to the end-user). If a user enters <code>http://example.com/param/exam1</code> in their address bar, and then the browser is forwarded to <code>http://example.com/examples/exam1?get=param</code>, then the former will have been redirected to the latter.</li>\n</ul>\n<hr />\n<h2>RewriteRule Analysis</h2>\n<p>At a glance, I would suspect that your <code>RewriteRule</code> is never matching your URLs; or if it is, not rewriting them as you might expect:</p>\n<pre><code>RewriteRule ^(exam1|exam2)/([^/]+)/?$ /example/$2/?get=$1 [QSA,L]\n</code></pre>\n<ul>\n<li>Match HTTP request paths:\n<ul>\n<li><code>^(exam1|exam2)/</code>: <strong>beginning</strong> with <code>exam1/</code> or <code>exam2/</code> and capture <code>exam1</code>/<code>exam2</code> as sub-group <code>$1</code>...</li>\n<li><code>([^/]+)</code>: ...followed by 1 or more non-<code>/</code> characters, which will captured as sub-group <code>$2</code>...</li>\n<li><code>/?$</code>: ...possibly followed by a <code>/</code> at the <strong>very end</strong>.</li>\n</ul>\n</li>\n<li>Redirect matched request paths to <code>/example/$2/?get=$1</code></li>\n</ul>\n<p>In practice:</p>\n<ul>\n<li>A request sent to <code>http://example.com/param/exam1</code> will not be rewritten as the request path begins with <code>param/</code> and not <code>exam1/</code> or <code>exam2/</code></li>\n<li>A request to <code>http://example.com/exam1/param/</code> will be rewritten to be served by the endpoint <code>http://example.com/example/param/?get=exam1</code></li>\n<li>A request to <code>http://example.com/exam1/param/test</code> will not be rewritten because the request path does not end at the first path segment after <code>exam1</code> or <code>exam2</code></li>\n</ul>\n<hr />\n<h2>Solution</h2>\n<p>To rewrite the URL you've specified, you need to swap the capture groups in your Regex:</p>\n<pre><code>RewriteRule ^([^/]+)/(exam1|exam2)/?$ /example/$2/?get=$1 [QSA,L]\n</code></pre>\n<p>This will match path segments in the desired order and correct your back-references. However, this rule comes with some strange caveats that could cause unexpected behaviors. In practice, requests to:</p>\n<ul>\n<li><code>http://example.com/foo/exam1</code> =&gt; <code>http://example.com/example/exam1?get=foo</code></li>\n<li><code>http://example.com/bar/exam1/</code> =&gt; <code>http://example.com/example/exam1?get=bar</code></li>\n<li><strong><code>http://example.com/posts/exam2_announcement</code> =&gt; <code>http://example.com/example/exam2?get=posts</code></strong></li>\n<li><strong><code>http://example.com/tests/exam120</code> =&gt; <code>http://example.com/example/exam1?get=tests</code></strong></li>\n</ul>\n" }, { "answer_id": 218928, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>It's possible to handle this in WordPress using <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\"><code>add_rewrite_rule()</code></a>. </p>\n\n<p>Drop this in <strong>functions.php</strong> or a <strong>plugin</strong>. It's longer than a simple <code>ReWriteRule</code> but you'll have a little more flexibility and control on the WordPress side.</p>\n\n<pre><code>&lt;?php\n\nif ( ! class_exists( 'ExamRewrite' ) ):\n\n class ExamRewrite {\n const ENDPOINT_QUERY_PARAM = '__redirect_exam';\n\n // WordPress hooks\n public function init() {\n add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 );\n add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 );\n add_action( 'init', array ( $this, 'add_endpoint' ), 0 );\n }\n\n // Add public query vars\n public function add_query_vars( $vars ) {\n $vars[] = static::ENDPOINT_QUERY_PARAM;\n $vars[] = 'get';\n $vars[] = 'exam';\n return $vars;\n }\n\n // Add Endpoint\n public function add_endpoint() {\n add_rewrite_rule( '^example/(exam1|exam2)', 'index.php?' . static::ENDPOINT_QUERY_PARAM . '=1&amp;exam=$matches[1]', 'top' );\n //////////////////////////////////\n flush_rewrite_rules( false ); //// &lt;---------- REMOVE THIS WHEN DONE\n }\n\n // Sniff Requests\n public function sniff_requests( $wp_query ) {\n global $wp;\n\n if ( isset(\n $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM ],\n $wp-&gt;query_vars[ 'get' ] ) ) {\n $get = $wp-&gt;query_vars[ 'get' ];\n $exam = $wp-&gt;query_vars[ 'exam' ];\n $new_url = site_url( \"/$get/$exam\" );\n wp_safe_redirect( $new_url, 301 );\n die();\n }\n }\n }\n\n $wpExamRewrite = new ExamRewrite();\n $wpExamRewrite-&gt;init();\n\nendif; // ExamRewrite\n</code></pre>\n" } ]
2016/02/25
[ "https://wordpress.stackexchange.com/questions/218911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89492/" ]
I have post type `example` with 2 records: `exam1` and `exam2`. This post type was created by plugin `Types Toolset` (`www.wp-types.com`). So link to `exam1` looks like `my_site/example/exam1`. Also I have 1 GET-parameter: `my_site/example/exam1?get=param`. What I need. I need to rewrite URL from `my_site/example/exam1?get=param` to `my_site/param/exam1`. I wrote this rule: ``` RewriteRule ^(exam1|exam2)/([^/]+)/?$ /example/$2/?get=$1 [QSA,L] ``` This is the right rule. It should work. But it does not work. When I go to the `my_site/param/exam1` , it redirects to `my_site/example/exam1`. I know that it is `redirect_canonical`. And I can remove it: ``` remove_action('template_redirect', 'redirect_canonical'); ``` But my RewriteRule still not working - no redirects from `my_site/example/exam1?get=param` to `my_site/param/exam1`. Why? Please help me. I need it very much.
Terminology ----------- I think you have some terminology a little mixed up: * A URL "rewrite" alters the endpoint of a HTTP request. If `http://example.com/param/exam1` really serves content from `http://example.com/examples/exam1?get=param`, then the former is being rewritten to the latter (though not necessarily visible to the end-user). * In the world of URL-rewriting, a "redirect" is a rewrite that (instead of serving the request from the altered endpoint) kicks back a HTTP `300`-range status code, telling the client that sent the HTTP request to send a new request to the rewritten URL (thus altering the address visible to the end-user). If a user enters `http://example.com/param/exam1` in their address bar, and then the browser is forwarded to `http://example.com/examples/exam1?get=param`, then the former will have been redirected to the latter. --- RewriteRule Analysis -------------------- At a glance, I would suspect that your `RewriteRule` is never matching your URLs; or if it is, not rewriting them as you might expect: ``` RewriteRule ^(exam1|exam2)/([^/]+)/?$ /example/$2/?get=$1 [QSA,L] ``` * Match HTTP request paths: + `^(exam1|exam2)/`: **beginning** with `exam1/` or `exam2/` and capture `exam1`/`exam2` as sub-group `$1`... + `([^/]+)`: ...followed by 1 or more non-`/` characters, which will captured as sub-group `$2`... + `/?$`: ...possibly followed by a `/` at the **very end**. * Redirect matched request paths to `/example/$2/?get=$1` In practice: * A request sent to `http://example.com/param/exam1` will not be rewritten as the request path begins with `param/` and not `exam1/` or `exam2/` * A request to `http://example.com/exam1/param/` will be rewritten to be served by the endpoint `http://example.com/example/param/?get=exam1` * A request to `http://example.com/exam1/param/test` will not be rewritten because the request path does not end at the first path segment after `exam1` or `exam2` --- Solution -------- To rewrite the URL you've specified, you need to swap the capture groups in your Regex: ``` RewriteRule ^([^/]+)/(exam1|exam2)/?$ /example/$2/?get=$1 [QSA,L] ``` This will match path segments in the desired order and correct your back-references. However, this rule comes with some strange caveats that could cause unexpected behaviors. In practice, requests to: * `http://example.com/foo/exam1` => `http://example.com/example/exam1?get=foo` * `http://example.com/bar/exam1/` => `http://example.com/example/exam1?get=bar` * **`http://example.com/posts/exam2_announcement` => `http://example.com/example/exam2?get=posts`** * **`http://example.com/tests/exam120` => `http://example.com/example/exam1?get=tests`**
218,926
<p>I have this custom function that get's the manually entered excerpt and trims it down but the problem I'm having is that it is trimming the characters down to 52 and instead I want it to return the first 52 Words like the normal excerpt.</p> <p>Here's the custom that allows me to trim the manually entered excerpt</p> <pre><code>function themeTemplate_trim_excerpt( $content ) { return substr( strip_tags( $content ), 0, 52 ); } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'template_trim_excerpt'); </code></pre> <p>This is the only way I've been able to cut the manually entered excerpt.</p> <p>How do I make it trim it so it only shows the first 52 words?</p> <p>Thanks for any feedback :)</p>
[ { "answer_id": 218929, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://php.net/manual/en/function.explode.php\" rel=\"nofollow\">explode</a>, <a href=\"http://php.net/manual/en/function.array-filter.php\" rel=\"nofollow\">array_filter</a>, <a href=\"http://us3.php.net/manual/en/function.array-slice.php\" rel=\"nofollow\">array_slice</a>, and <a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow\">implode</a> can pull the world by looking operating on the whitespace.</p>\n\n<pre><code>function themeTemplate_trim_excerpt( $content ) {\n\n // split the content by spaces, \n // remove excess whitespace\n // pull the first 52 items, \n // glue back together...\n\n return implode( ' ', array_slice( array_filter( explode( ' ', $content ) ), 0, 52 ) );\n}\n\nremove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );\nadd_filter( 'get_the_excerpt', 'template_trim_excerpt' );\n</code></pre>\n\n<hr>\n\n<h3>Breakdown</h3>\n\n<pre><code>// Convert the string to an array\n$words = explode( ' ', $content );\n\n// Remove any empty values\n$words = array_filter($words);\n\n// Grab the first 10 elements from the array\n$first_x_words = array_slice($words, 0, 10);\n\n// Convert the array to a string\n$output = implode ( ' ', $first_x_words );\n\n// Final value\necho $output;\n</code></pre>\n\n<h3>Cons</h3>\n\n<ul>\n<li>Since these operations act on spaces, if there is HTML in your content, each attribute can be viewed as a word.</li>\n<li>It's much easier to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_trim_words\" rel=\"nofollow\"><code>wp_trim_words()</code></a> - [ <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/formatting.php#L2951\" rel=\"nofollow\">L2951</a> ]</li>\n</ul>\n" }, { "answer_id": 218931, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": true, "text": "<p>The function you want is <a href=\"https://codex.wordpress.org/Function_Reference/wp_trim_words\" rel=\"nofollow\"><strong><code>wp_trim_words()</code></strong></a>, example:</p>\n\n<pre><code>function themeTemplate_trim_excerpt( $content ) {\n $more = '...'; //where $more is optional\n return wp_trim_words($content, 52, $more);\n}\n\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\nadd_filter('get_the_excerpt', 'template_trim_excerpt');\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218926", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85776/" ]
I have this custom function that get's the manually entered excerpt and trims it down but the problem I'm having is that it is trimming the characters down to 52 and instead I want it to return the first 52 Words like the normal excerpt. Here's the custom that allows me to trim the manually entered excerpt ``` function themeTemplate_trim_excerpt( $content ) { return substr( strip_tags( $content ), 0, 52 ); } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'template_trim_excerpt'); ``` This is the only way I've been able to cut the manually entered excerpt. How do I make it trim it so it only shows the first 52 words? Thanks for any feedback :)
The function you want is [**`wp_trim_words()`**](https://codex.wordpress.org/Function_Reference/wp_trim_words), example: ``` function themeTemplate_trim_excerpt( $content ) { $more = '...'; //where $more is optional return wp_trim_words($content, 52, $more); } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'template_trim_excerpt'); ```
218,954
<p>I submit a WordPress theme for Themeforest and one of the reasons for rejection was as follows:</p> <blockquote> <p>Globals should always be within a function or a class and should be used restrictively &amp; only if theme really needs to. It's highly recommended not to use them at all just to keep things out of the global namespace, they're poor coding practice.</p> </blockquote> <p>Im using <a href="https://github.com/syamilmj/Options-Framework" rel="nofollow">Smof Option Framework</a> for theme options and here is a sample code from one of my theme files:</p> <pre><code>global $smof_data; $td_header_manager_wide = $smof_data['td_header_blocks']['enabled']; if ( $td_header_manager_wide ) { foreach ( $td_header_manager_wide as $key=&gt;$value ) { switch( $key ) { case 'block_main_menu_wide': // wide menu echo '&lt;div id="td-sticky" class="wide-menu ' . $td_sticky . '"&gt;'; echo '&lt;div id="wide-menu"&gt;'; include( get_template_directory() . '/parts/menu-header-logo.php'); echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; break; } } </code></pre> <p>It seems that <strong>global $smof_data</strong>; should be within a function but I'm really lost here how to accomplish this task to avoid include global $smof_data; in all of my theme files where I need it.</p> <p>Update code using @jgraup method:</p> <pre><code>function matilda_customize_styles() { $css = '&lt;style type="text/css" media="screen"&gt;'; if ( ! empty( SMOFData::get( 'td_body_font_family' ) ) &amp;&amp; SMOFData::get( 'td_body_font_family' ) != 'none' ) { $css .= 'body{font-family:' . esc_html( SMOFData::get( 'td_body_font_family' ) ) . ';}'; } } </code></pre> <p>Any help will be greatly appreciated. Thanks.</p>
[ { "answer_id": 218955, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>First, I must congratulate the reply from Themeforest, that really deserves a beer. Globals are evil and one should never create globals and dirty the global space anymore that it already is. WordPress has made a huge mess of this already. Don't add to this mess.</p>\n\n<p>One of the easiest ways to get pass the global issue is to create a function which you can use anywhere where you would need it. Here is a sample</p>\n\n<pre><code>function this_is_my_global()\n{\n return $my_global_var = 'This is my global value';\n}\n</code></pre>\n\n<p>You can then simply call <code>this_is_my_global();</code> where you need it. </p>\n\n<p>This is just something very basic. I would recommend that you read @kaiser and @gmazzap answers to the following question</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/q/184235/31545\">Best way of passing PHP variable between partials?</a></li>\n</ul>\n\n<p>That should give a more complex, reliable means to pass variables between templates</p>\n" }, { "answer_id": 218963, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>If you're dealing with framework that holds values in a global variable then there isn't much you can do about it. Here is an example of wrapping the variable in a static getter.</p>\n\n<pre><code>if ( ! class_exists( 'SMOFData' ) ):\n\n class SMOFData {\n\n static public function is( $key, $compare ) {\n $value = static::get( $key );\n return $value === $compare;\n }\n\n static public function not( $key, $compare ) {\n $value = static::get( $key );\n return $value !== $compare;\n }\n\n static public function has( $key ) {\n $value = static::get( $key );\n return ! empty( $value );\n }\n\n static public function get( $key ) {\n\n global $smof_data;\n\n if ( ! isset( $smof_data ) ) {\n return null;\n }\n\n return isset( $smof_data[ $key ] ) ? $smof_data[ $key ] : null;\n }\n\n }\n\nendif; // SMOFData\n</code></pre>\n\n<p>To access the data just use</p>\n\n<pre><code>echo SMOFData::get('td_header_blocks')['enabled'];\n\nfunction matilda_customize_styles() { \n $css = '&lt;style type=\"text/css\" media=\"screen\"&gt;';\n $td_body_font_family = SMOFData::get( 'td_body_font_family' ); \n if ( ! empty( $td_body_font_family ) &amp;&amp; $td_body_font_family != 'none' ) {\n $css .= 'body{font-family:' . esc_html( $td_body_font_family ) . ';}';\n } \n}\n\nfunction matilda_customize_styles() { \n $css = '&lt;style type=\"text/css\" media=\"screen\"&gt;';\n if ( SMOFData::has( 'td_body_font_family' ) &amp;&amp; SMOFData::not( 'td_body_font_family', 'none' ) ) {\n $css .= 'body{font-family:' . esc_html( SMOFData::get( 'td_body_font_family' ) ) . ';}';\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you just want you're own globals you can wrap that in a class as well.</p>\n\n<pre><code>if ( ! class_exists( 'ThemeData' ) ):\n\n class ThemeData {\n private static $_values = array ();\n\n static public function get( $key ) {\n return isset( static::$_values[ $key ] ) ? static::$_values[ $key ] : null;\n }\n\n static public function set( $key, $value ) {\n static::$_values[ $key ] = $value;\n return $value;\n }\n }\nendif; // ThemeData\n\n\n// setter\nThemeData::set('foo', 'bar');\n\n// getter\necho ThemeData::get('foo');\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218954", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33903/" ]
I submit a WordPress theme for Themeforest and one of the reasons for rejection was as follows: > > Globals should always be within a function or a class and should be used restrictively & only if theme really needs to. It's highly recommended not to use them at all just to keep things out of the global namespace, they're poor coding practice. > > > Im using [Smof Option Framework](https://github.com/syamilmj/Options-Framework) for theme options and here is a sample code from one of my theme files: ``` global $smof_data; $td_header_manager_wide = $smof_data['td_header_blocks']['enabled']; if ( $td_header_manager_wide ) { foreach ( $td_header_manager_wide as $key=>$value ) { switch( $key ) { case 'block_main_menu_wide': // wide menu echo '<div id="td-sticky" class="wide-menu ' . $td_sticky . '">'; echo '<div id="wide-menu">'; include( get_template_directory() . '/parts/menu-header-logo.php'); echo '</div>'; echo '</div>'; break; } } ``` It seems that **global $smof\_data**; should be within a function but I'm really lost here how to accomplish this task to avoid include global $smof\_data; in all of my theme files where I need it. Update code using @jgraup method: ``` function matilda_customize_styles() { $css = '<style type="text/css" media="screen">'; if ( ! empty( SMOFData::get( 'td_body_font_family' ) ) && SMOFData::get( 'td_body_font_family' ) != 'none' ) { $css .= 'body{font-family:' . esc_html( SMOFData::get( 'td_body_font_family' ) ) . ';}'; } } ``` Any help will be greatly appreciated. Thanks.
If you're dealing with framework that holds values in a global variable then there isn't much you can do about it. Here is an example of wrapping the variable in a static getter. ``` if ( ! class_exists( 'SMOFData' ) ): class SMOFData { static public function is( $key, $compare ) { $value = static::get( $key ); return $value === $compare; } static public function not( $key, $compare ) { $value = static::get( $key ); return $value !== $compare; } static public function has( $key ) { $value = static::get( $key ); return ! empty( $value ); } static public function get( $key ) { global $smof_data; if ( ! isset( $smof_data ) ) { return null; } return isset( $smof_data[ $key ] ) ? $smof_data[ $key ] : null; } } endif; // SMOFData ``` To access the data just use ``` echo SMOFData::get('td_header_blocks')['enabled']; function matilda_customize_styles() { $css = '<style type="text/css" media="screen">'; $td_body_font_family = SMOFData::get( 'td_body_font_family' ); if ( ! empty( $td_body_font_family ) && $td_body_font_family != 'none' ) { $css .= 'body{font-family:' . esc_html( $td_body_font_family ) . ';}'; } } function matilda_customize_styles() { $css = '<style type="text/css" media="screen">'; if ( SMOFData::has( 'td_body_font_family' ) && SMOFData::not( 'td_body_font_family', 'none' ) ) { $css .= 'body{font-family:' . esc_html( SMOFData::get( 'td_body_font_family' ) ) . ';}'; } } ``` --- If you just want you're own globals you can wrap that in a class as well. ``` if ( ! class_exists( 'ThemeData' ) ): class ThemeData { private static $_values = array (); static public function get( $key ) { return isset( static::$_values[ $key ] ) ? static::$_values[ $key ] : null; } static public function set( $key, $value ) { static::$_values[ $key ] = $value; return $value; } } endif; // ThemeData // setter ThemeData::set('foo', 'bar'); // getter echo ThemeData::get('foo'); ```
218,959
<p>I have multiple forms(contact form 7) in a page and need to reset the recaptcha after the form is submitted via ajax. I checked recaptcha API and it has <code>grecaptcha.reset();</code> but it resets only first recaptcha in a page.</p> <p>Following is the method to target a specific recaptcha according to recaptcha API:</p> <pre><code>grecaptcha.reset( opt_widget_id ) </code></pre> <p>The problem here is that I cannot get hold on the instance(opt_widget_id) of recaptcha because it is created by contact form 7.</p> <p>How do I get opt_widget_id in a page having multiple forms, so that I can reset specific recaptcha.</p>
[ { "answer_id": 219732, "author": "roshan", "author_id": 82786, "author_profile": "https://wordpress.stackexchange.com/users/82786", "pm_score": 2, "selected": false, "text": "<p>Since the recaptcha is created by contact form 7 without assigning the rendered recaptcha to a variable it was not possible to use grecaptcha.reset(opt_widget_id).\nHere is what is did:</p>\n\n<pre><code>$(\".wpcf7-submit\").click(function(event) {\nvar currentForm=$(this).closest(\"form\");\n$( document ).ajaxComplete(function(event,request, settings) {\n var responseObj=JSON.parse(request.responseText);\n if(responseObj.mailSent==true){\n //reset recaptcha\n var recaptchaIFrame=currentForm.find(\"iframe\").eq(0);\n var recaptchaIFrameSrc=recaptchaIFrame.attr(\"src\");\n recaptchaIFrame.attr(\"src\",recaptchaIFrameSrc);\n }\n });\n});\n</code></pre>\n\n<p>I have cleared the iframe source and reassigned the same src so that it reloads the recaptcha once it has been submitted. </p>\n\n<p>I hope this helps someone !</p>\n" }, { "answer_id": 233551, "author": "Maulik Vora", "author_id": 3250, "author_profile": "https://wordpress.stackexchange.com/users/3250", "pm_score": 1, "selected": false, "text": "<p>I have done this by adding below code in 'Additional settings' of contact form.</p>\n\n<pre><code>on_sent_ok: \"grecaptcha.reset()\"\n</code></pre>\n\n<p>Hope this helps to others</p>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218959", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82786/" ]
I have multiple forms(contact form 7) in a page and need to reset the recaptcha after the form is submitted via ajax. I checked recaptcha API and it has `grecaptcha.reset();` but it resets only first recaptcha in a page. Following is the method to target a specific recaptcha according to recaptcha API: ``` grecaptcha.reset( opt_widget_id ) ``` The problem here is that I cannot get hold on the instance(opt\_widget\_id) of recaptcha because it is created by contact form 7. How do I get opt\_widget\_id in a page having multiple forms, so that I can reset specific recaptcha.
Since the recaptcha is created by contact form 7 without assigning the rendered recaptcha to a variable it was not possible to use grecaptcha.reset(opt\_widget\_id). Here is what is did: ``` $(".wpcf7-submit").click(function(event) { var currentForm=$(this).closest("form"); $( document ).ajaxComplete(function(event,request, settings) { var responseObj=JSON.parse(request.responseText); if(responseObj.mailSent==true){ //reset recaptcha var recaptchaIFrame=currentForm.find("iframe").eq(0); var recaptchaIFrameSrc=recaptchaIFrame.attr("src"); recaptchaIFrame.attr("src",recaptchaIFrameSrc); } }); }); ``` I have cleared the iframe source and reassigned the same src so that it reloads the recaptcha once it has been submitted. I hope this helps someone !
218,978
<p>I'm just starting out on a new Wordpress project and for some reason I can't get the previews working. I have disabled all of my plugins and still i always get false when using <code>is_preview()</code>.</p> <p>Currently I'm just creating a page that renders via page.php where I only call <code>var_dump(is_preview())</code> and it always shows false. Doesn't matter if I put it in the loop either, still false. What am I missing here?</p> <p>Shouldn't <code>is_preview()</code> return true when i click "Preview Changes"?</p> <p>EDIT: I'm of course calling <code>var_dump(is_preview())</code> and not "the_preview" as i orginially wrote. and it prints <code>bool(false)</code> every time.</p> <p>RESOLVED: It was actually some misconfiguration in the nginx server running the site. Not sure exactly what it was, it's not my area of expertise so to speak. But the problem is resolved.</p>
[ { "answer_id": 219732, "author": "roshan", "author_id": 82786, "author_profile": "https://wordpress.stackexchange.com/users/82786", "pm_score": 2, "selected": false, "text": "<p>Since the recaptcha is created by contact form 7 without assigning the rendered recaptcha to a variable it was not possible to use grecaptcha.reset(opt_widget_id).\nHere is what is did:</p>\n\n<pre><code>$(\".wpcf7-submit\").click(function(event) {\nvar currentForm=$(this).closest(\"form\");\n$( document ).ajaxComplete(function(event,request, settings) {\n var responseObj=JSON.parse(request.responseText);\n if(responseObj.mailSent==true){\n //reset recaptcha\n var recaptchaIFrame=currentForm.find(\"iframe\").eq(0);\n var recaptchaIFrameSrc=recaptchaIFrame.attr(\"src\");\n recaptchaIFrame.attr(\"src\",recaptchaIFrameSrc);\n }\n });\n});\n</code></pre>\n\n<p>I have cleared the iframe source and reassigned the same src so that it reloads the recaptcha once it has been submitted. </p>\n\n<p>I hope this helps someone !</p>\n" }, { "answer_id": 233551, "author": "Maulik Vora", "author_id": 3250, "author_profile": "https://wordpress.stackexchange.com/users/3250", "pm_score": 1, "selected": false, "text": "<p>I have done this by adding below code in 'Additional settings' of contact form.</p>\n\n<pre><code>on_sent_ok: \"grecaptcha.reset()\"\n</code></pre>\n\n<p>Hope this helps to others</p>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64223/" ]
I'm just starting out on a new Wordpress project and for some reason I can't get the previews working. I have disabled all of my plugins and still i always get false when using `is_preview()`. Currently I'm just creating a page that renders via page.php where I only call `var_dump(is_preview())` and it always shows false. Doesn't matter if I put it in the loop either, still false. What am I missing here? Shouldn't `is_preview()` return true when i click "Preview Changes"? EDIT: I'm of course calling `var_dump(is_preview())` and not "the\_preview" as i orginially wrote. and it prints `bool(false)` every time. RESOLVED: It was actually some misconfiguration in the nginx server running the site. Not sure exactly what it was, it's not my area of expertise so to speak. But the problem is resolved.
Since the recaptcha is created by contact form 7 without assigning the rendered recaptcha to a variable it was not possible to use grecaptcha.reset(opt\_widget\_id). Here is what is did: ``` $(".wpcf7-submit").click(function(event) { var currentForm=$(this).closest("form"); $( document ).ajaxComplete(function(event,request, settings) { var responseObj=JSON.parse(request.responseText); if(responseObj.mailSent==true){ //reset recaptcha var recaptchaIFrame=currentForm.find("iframe").eq(0); var recaptchaIFrameSrc=recaptchaIFrame.attr("src"); recaptchaIFrame.attr("src",recaptchaIFrameSrc); } }); }); ``` I have cleared the iframe source and reassigned the same src so that it reloads the recaptcha once it has been submitted. I hope this helps someone !
218,980
<p>My theme has support for title-tag <code>add_theme_support('title-tag')</code>, but I can't remove the wordpress description <code>bloginfo('description')</code> from <code>&lt;title&gt;</code> on Home page.</p> <p>I'm trying using this filter with no success:</p> <pre><code>add_filter( 'wp_title', function ( $title, $sep ) { global $paged, $page; $title .= get_bloginfo( 'name' ); if ( is_home() || is_front_page() ) $title = "$title"; return $title; }, 10, 2 ); </code></pre>
[ { "answer_id": 218982, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": false, "text": "<p>The problem is the line:</p>\n\n<pre><code>$title = \"$title\";\n</code></pre>\n\n<p>You actually just change the <code>$title</code> to itself. If you change it to</p>\n\n<pre><code>$title = get_bloginfo( 'name' );\n</code></pre>\n\n<p>the returned title on the front page is going to be the name of your blog. You can put any string there. Also, it is not necessary to call the globals here.</p>\n\n<p>Here is some code that should work:</p>\n\n<pre><code>add_filter( 'wp_title', function ( $title, $sep ) {\n\n $title .= get_bloginfo( 'name' );\n\n if ( is_home() || is_front_page() )\n $title = \"Any string you want to have\";\n\n return $title;\n\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 218983, "author": "marcelo2605", "author_id": 38553, "author_profile": "https://wordpress.stackexchange.com/users/38553", "pm_score": 3, "selected": true, "text": "<p>Found a solution:</p>\n\n<pre><code>add_filter( 'pre_get_document_title', function ( $title ) {\n if(is_front_page()){\n $title = get_bloginfo();\n }\n return $title;\n});\n</code></pre>\n" }, { "answer_id": 218987, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://wpseek.com/function/wp_get_document_title/\" rel=\"nofollow noreferrer\"><code>wp_get_document_title()</code></a> has some interesting filters - <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"nofollow noreferrer\"><code>pre_get_document_title</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"nofollow noreferrer\"><code>document_title_parts</code></a>.</p>\n\n<pre><code>/**\n * Filter the parts of the document title.\n *\n * @since 4.4.0\n *\n * @param array $title {\n * The document title parts.\n *\n * @type string $title Title of the viewed page.\n * @type string $page Optional. Page number if paginated.\n * @type string $tagline Optional. Site description when on home page.\n * @type string $site Optional. Site title when not on home page.\n * }\n */\nadd_filter( 'document_title_parts', function ( $title ) {\n\n if ( is_home() || is_front_page() )\n unset($title['tagline']);\n\n return $title;\n\n}, 10, 1 );\n</code></pre>\n\n<hr>\n\n<p>Looking back on this; the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"nofollow noreferrer\"><code>pre_get_document_title</code></a> filter is pretty interesting. Essentially before it processes the title it'll run this filter. If the result isn't empty (which was not expected) then the process is short-circuited.</p>\n\n<pre><code>$title = apply_filters( 'pre_get_document_title', '' );\nif ( ! empty( $title ) ) {\n return $title;\n}\n</code></pre>\n\n<p>That means that if you defined the title, it doesn't have to worry about anything else. The nice thing is that you can make exceptions to the rule. So to answer your original question:</p>\n\n<pre><code>add_filter( 'pre_get_document_title', function( $title ) {\n\n if ( is_home() || is_front_page() ) {\n\n // Return blog title on front page\n\n $title = get_bloginfo( 'name' );\n }\n\n return $title;\n\n} );\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218980", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38553/" ]
My theme has support for title-tag `add_theme_support('title-tag')`, but I can't remove the wordpress description `bloginfo('description')` from `<title>` on Home page. I'm trying using this filter with no success: ``` add_filter( 'wp_title', function ( $title, $sep ) { global $paged, $page; $title .= get_bloginfo( 'name' ); if ( is_home() || is_front_page() ) $title = "$title"; return $title; }, 10, 2 ); ```
Found a solution: ``` add_filter( 'pre_get_document_title', function ( $title ) { if(is_front_page()){ $title = get_bloginfo(); } return $title; }); ```
218,993
<p>I have a custom post <code>estate_property</code> and its has taxonomies <code>property_category</code> ,<code>propert_action</code>.I have installed <code>WPCustom Category Image</code> to upload image for each category of taxonomies. How to display the uploaded image .I search for it but failed to display image My code is </p> <pre><code>$taxonomy_name = 'property_category'; $asd=get_the_terms($post-&gt;ID, $taxonomy_name); var_dump($asd); </code></pre> <p>it returns nothing .Help please</p>
[ { "answer_id": 219009, "author": "Jorin van Vilsteren", "author_id": 68062, "author_profile": "https://wordpress.stackexchange.com/users/68062", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with the WPCustom Category Image plugin, but it probably need another function something like <code>get_category_image($category_id)</code> (or something like that) to retrieve the image. </p>\n" }, { "answer_id": 243568, "author": "PiggyMacPigPig", "author_id": 31637, "author_profile": "https://wordpress.stackexchange.com/users/31637", "pm_score": 1, "selected": false, "text": "<p>From the details page of the WPCustom Category Image Plug-in : <a href=\"https://wordpress.org/support/plugin/wpcustom-category-image\" rel=\"nofollow\">https://wordpress.org/support/plugin/wpcustom-category-image</a></p>\n\n<p><strong>1st</strong> - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options.</p>\n\n<p><strong>2nd</strong> ...depending on whether you want to show a single category image or display several in a loop -</p>\n\n<p>//SINGLE</p>\n\n<pre><code>echo do_shortcode('[wp_custom_image_category onlysrc=\"https://wordpress.org/plugins/wpcustom-category-image/false\" size=\"full\" term_id=\"123\" alt=\"alt :)\"]');\n</code></pre>\n\n<p>//LOOP</p>\n\n<pre><code>foreach( get_categories(['hide_empty' =&gt; false]) as $category) {\n echo $category-&gt;name . '&lt;br&gt;';\n echo do_shortcode(sprintf('[wp_custom_image_category term_id=\"%s\"]',$category-&gt;term_id));\n}\n</code></pre>\n\n<p>In addition there is an example category template here -</p>\n\n<p><a href=\"https://gist.github.com/eduardostuart/b88d6845a1afb78c296c\" rel=\"nofollow\">https://gist.github.com/eduardostuart/b88d6845a1afb78c296c</a></p>\n" }, { "answer_id": 243577, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>If get_the_terms returns nothing, you'll need to check for $wp_error return. This function will return an array of terms objects on success, false if there are no terms or the post does not exist, WP_Error on failure (i.e:taxonomy doesn't exist).</p>\n\n<p>just modify your code like this :</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n}\n</code></pre>\n\n<p>There is many chances that the category image is stored as a term_meta, that you can grab with the get_term_meta() function. This function works like get_post_meta.</p>\n\n<p>The same as above where you'll need to modify the key to get the right meta, or just put the first parameter to get an array of all the metas for the term_id.</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n foreach($asd as $term){\n $term_id = $term-&gt;term_id;\n $term_image = get_term_meta($term_id, 'image_category', true); //false returns an array\n var_dump($term_image);\n }\n} \n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/218993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84928/" ]
I have a custom post `estate_property` and its has taxonomies `property_category` ,`propert_action`.I have installed `WPCustom Category Image` to upload image for each category of taxonomies. How to display the uploaded image .I search for it but failed to display image My code is ``` $taxonomy_name = 'property_category'; $asd=get_the_terms($post->ID, $taxonomy_name); var_dump($asd); ``` it returns nothing .Help please
From the details page of the WPCustom Category Image Plug-in : <https://wordpress.org/support/plugin/wpcustom-category-image> **1st** - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options. **2nd** ...depending on whether you want to show a single category image or display several in a loop - //SINGLE ``` echo do_shortcode('[wp_custom_image_category onlysrc="https://wordpress.org/plugins/wpcustom-category-image/false" size="full" term_id="123" alt="alt :)"]'); ``` //LOOP ``` foreach( get_categories(['hide_empty' => false]) as $category) { echo $category->name . '<br>'; echo do_shortcode(sprintf('[wp_custom_image_category term_id="%s"]',$category->term_id)); } ``` In addition there is an example category template here - <https://gist.github.com/eduardostuart/b88d6845a1afb78c296c>
219,011
<p>So I have a dropdown menu that has a list of all pages using a certain template, when the user selects a dropdown item id like them to be re-directed to that page. </p> <p>Here is what I have so far... </p> <pre><code> &lt;div class="col-md-6 col-md-offset-3"&gt; &lt;?php //create a var using get_pages create an array and get all page names $pages = get_pages(array( 'meta_key' =&gt; '_wp_page_template', 'meta_value' =&gt; 'template-services.php' )); ?&gt; &lt;p&gt;Looking for something else?&lt;/p&gt; &lt;select id="cat" class="form-control"&gt; &lt;?php // for each item in pages array assign to the new var page foreach( $pages as $page ) { //echo out var page for each item in the array echo '&lt;option&gt;' . $page-&gt;post_title . '&lt;/option&gt;'; }?&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Could someone show me how I can achieve this? I know there is a script on the Wordpress codex that allows you to do this for categories but I have no idea how to modify it to work for my needs </p>
[ { "answer_id": 219009, "author": "Jorin van Vilsteren", "author_id": 68062, "author_profile": "https://wordpress.stackexchange.com/users/68062", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with the WPCustom Category Image plugin, but it probably need another function something like <code>get_category_image($category_id)</code> (or something like that) to retrieve the image. </p>\n" }, { "answer_id": 243568, "author": "PiggyMacPigPig", "author_id": 31637, "author_profile": "https://wordpress.stackexchange.com/users/31637", "pm_score": 1, "selected": false, "text": "<p>From the details page of the WPCustom Category Image Plug-in : <a href=\"https://wordpress.org/support/plugin/wpcustom-category-image\" rel=\"nofollow\">https://wordpress.org/support/plugin/wpcustom-category-image</a></p>\n\n<p><strong>1st</strong> - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options.</p>\n\n<p><strong>2nd</strong> ...depending on whether you want to show a single category image or display several in a loop -</p>\n\n<p>//SINGLE</p>\n\n<pre><code>echo do_shortcode('[wp_custom_image_category onlysrc=\"https://wordpress.org/plugins/wpcustom-category-image/false\" size=\"full\" term_id=\"123\" alt=\"alt :)\"]');\n</code></pre>\n\n<p>//LOOP</p>\n\n<pre><code>foreach( get_categories(['hide_empty' =&gt; false]) as $category) {\n echo $category-&gt;name . '&lt;br&gt;';\n echo do_shortcode(sprintf('[wp_custom_image_category term_id=\"%s\"]',$category-&gt;term_id));\n}\n</code></pre>\n\n<p>In addition there is an example category template here -</p>\n\n<p><a href=\"https://gist.github.com/eduardostuart/b88d6845a1afb78c296c\" rel=\"nofollow\">https://gist.github.com/eduardostuart/b88d6845a1afb78c296c</a></p>\n" }, { "answer_id": 243577, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>If get_the_terms returns nothing, you'll need to check for $wp_error return. This function will return an array of terms objects on success, false if there are no terms or the post does not exist, WP_Error on failure (i.e:taxonomy doesn't exist).</p>\n\n<p>just modify your code like this :</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n}\n</code></pre>\n\n<p>There is many chances that the category image is stored as a term_meta, that you can grab with the get_term_meta() function. This function works like get_post_meta.</p>\n\n<p>The same as above where you'll need to modify the key to get the right meta, or just put the first parameter to get an array of all the metas for the term_id.</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n foreach($asd as $term){\n $term_id = $term-&gt;term_id;\n $term_image = get_term_meta($term_id, 'image_category', true); //false returns an array\n var_dump($term_image);\n }\n} \n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/219011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85362/" ]
So I have a dropdown menu that has a list of all pages using a certain template, when the user selects a dropdown item id like them to be re-directed to that page. Here is what I have so far... ``` <div class="col-md-6 col-md-offset-3"> <?php //create a var using get_pages create an array and get all page names $pages = get_pages(array( 'meta_key' => '_wp_page_template', 'meta_value' => 'template-services.php' )); ?> <p>Looking for something else?</p> <select id="cat" class="form-control"> <?php // for each item in pages array assign to the new var page foreach( $pages as $page ) { //echo out var page for each item in the array echo '<option>' . $page->post_title . '</option>'; }?> </select> </div> ``` Could someone show me how I can achieve this? I know there is a script on the Wordpress codex that allows you to do this for categories but I have no idea how to modify it to work for my needs
From the details page of the WPCustom Category Image Plug-in : <https://wordpress.org/support/plugin/wpcustom-category-image> **1st** - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options. **2nd** ...depending on whether you want to show a single category image or display several in a loop - //SINGLE ``` echo do_shortcode('[wp_custom_image_category onlysrc="https://wordpress.org/plugins/wpcustom-category-image/false" size="full" term_id="123" alt="alt :)"]'); ``` //LOOP ``` foreach( get_categories(['hide_empty' => false]) as $category) { echo $category->name . '<br>'; echo do_shortcode(sprintf('[wp_custom_image_category term_id="%s"]',$category->term_id)); } ``` In addition there is an example category template here - <https://gist.github.com/eduardostuart/b88d6845a1afb78c296c>
219,033
<p>I want to do the following in a plugin: - hook to <code>untrash_post</code>with a custom function - do some checking inside custom function - cancel actual post restoring (untrashing)</p> <p>I've tried with <code>remove_action</code> but doesn't seem to work. Can you point me into the right direction?</p> <p>Code sample:</p> <pre><code>add_action( 'untrash_post', array( __CLASS__, 'static_untrash_handler' ) ); </code></pre> <p>.....</p> <pre><code>public static function static_untrash_handler( $post ) { </code></pre> <p><code>// check stuff</code></p> <p><code>// prevent post from being restored. How ?</code></p> <p><code>}</code></p> <p>Should I return something to 'break the cycle' ?</p> <p>Thank you in advance!</p>
[ { "answer_id": 219009, "author": "Jorin van Vilsteren", "author_id": 68062, "author_profile": "https://wordpress.stackexchange.com/users/68062", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with the WPCustom Category Image plugin, but it probably need another function something like <code>get_category_image($category_id)</code> (or something like that) to retrieve the image. </p>\n" }, { "answer_id": 243568, "author": "PiggyMacPigPig", "author_id": 31637, "author_profile": "https://wordpress.stackexchange.com/users/31637", "pm_score": 1, "selected": false, "text": "<p>From the details page of the WPCustom Category Image Plug-in : <a href=\"https://wordpress.org/support/plugin/wpcustom-category-image\" rel=\"nofollow\">https://wordpress.org/support/plugin/wpcustom-category-image</a></p>\n\n<p><strong>1st</strong> - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options.</p>\n\n<p><strong>2nd</strong> ...depending on whether you want to show a single category image or display several in a loop -</p>\n\n<p>//SINGLE</p>\n\n<pre><code>echo do_shortcode('[wp_custom_image_category onlysrc=\"https://wordpress.org/plugins/wpcustom-category-image/false\" size=\"full\" term_id=\"123\" alt=\"alt :)\"]');\n</code></pre>\n\n<p>//LOOP</p>\n\n<pre><code>foreach( get_categories(['hide_empty' =&gt; false]) as $category) {\n echo $category-&gt;name . '&lt;br&gt;';\n echo do_shortcode(sprintf('[wp_custom_image_category term_id=\"%s\"]',$category-&gt;term_id));\n}\n</code></pre>\n\n<p>In addition there is an example category template here -</p>\n\n<p><a href=\"https://gist.github.com/eduardostuart/b88d6845a1afb78c296c\" rel=\"nofollow\">https://gist.github.com/eduardostuart/b88d6845a1afb78c296c</a></p>\n" }, { "answer_id": 243577, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>If get_the_terms returns nothing, you'll need to check for $wp_error return. This function will return an array of terms objects on success, false if there are no terms or the post does not exist, WP_Error on failure (i.e:taxonomy doesn't exist).</p>\n\n<p>just modify your code like this :</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n}\n</code></pre>\n\n<p>There is many chances that the category image is stored as a term_meta, that you can grab with the get_term_meta() function. This function works like get_post_meta.</p>\n\n<p>The same as above where you'll need to modify the key to get the right meta, or just put the first parameter to get an array of all the metas for the term_id.</p>\n\n<pre><code>$taxonomy_name = 'property_category';\n$asd=get_the_terms($post-&gt;ID, $taxonomy_name); \n\nif(is_wp_error($asd){\n $error_string = $asd-&gt;get_error_message();\n var_dump($error_string); \n}\nelse{\n var_dump($asd); \n foreach($asd as $term){\n $term_id = $term-&gt;term_id;\n $term_image = get_term_meta($term_id, 'image_category', true); //false returns an array\n var_dump($term_image);\n }\n} \n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/219033", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71228/" ]
I want to do the following in a plugin: - hook to `untrash_post`with a custom function - do some checking inside custom function - cancel actual post restoring (untrashing) I've tried with `remove_action` but doesn't seem to work. Can you point me into the right direction? Code sample: ``` add_action( 'untrash_post', array( __CLASS__, 'static_untrash_handler' ) ); ``` ..... ``` public static function static_untrash_handler( $post ) { ``` `// check stuff` `// prevent post from being restored. How ?` `}` Should I return something to 'break the cycle' ? Thank you in advance!
From the details page of the WPCustom Category Image Plug-in : <https://wordpress.org/support/plugin/wpcustom-category-image> **1st** - Go to Wp-Admin -> Posts(or post type) -> Categories (or taxonomy) to see Custom Category Image options. **2nd** ...depending on whether you want to show a single category image or display several in a loop - //SINGLE ``` echo do_shortcode('[wp_custom_image_category onlysrc="https://wordpress.org/plugins/wpcustom-category-image/false" size="full" term_id="123" alt="alt :)"]'); ``` //LOOP ``` foreach( get_categories(['hide_empty' => false]) as $category) { echo $category->name . '<br>'; echo do_shortcode(sprintf('[wp_custom_image_category term_id="%s"]',$category->term_id)); } ``` In addition there is an example category template here - <https://gist.github.com/eduardostuart/b88d6845a1afb78c296c>
219,041
<p>I created enclosing shortcodes like this:</p> <pre><code>//[rezept] function rezept_func( $atts, $content = null ){ return '&lt;div class="drl-rezept-wrapper"&gt;'.do_shortcode($content).'&lt;/div&gt;'; } add_shortcode( 'rezept', 'rezept_func' ); function rezept_zutaten_func( $atts, $content = null ){ return '&lt;div class="drl-rezept-left"&gt;'.$content.'&lt;/div&gt;'; } add_shortcode( 'rezept-zutaten', 'rezept_zutaten_func' ); </code></pre> <p>The HTML code is:</p> <pre><code>[rezept] [rezept-zutaten] &lt;span&gt;Zutat 1&lt;/span&gt; &lt;span&gt;Zutat 2&lt;/span&gt; &lt;span&gt;Zutat 3&lt;/span&gt; [/rezept-zutaten] [/rezept] </code></pre> <p>The result is this html code:</p> <pre><code>&lt;div class="drl-rezept-wrapper"&gt;&lt;br&gt; &lt;div class="drl-rezept-left"&gt;&lt;br&gt; &lt;span&gt;Zutat 1&lt;/span&gt;&lt;br&gt; &lt;span&gt;Zutat 2&lt;/span&gt;&lt;br&gt; &lt;span&gt;Zutat 3&lt;/span&gt;&lt;br&gt; &lt;/div&gt;&lt;br&gt; &lt;br&gt; &lt;/div&gt; </code></pre> <p>Where are all the <code>&lt;br&gt;'s</code> are coming from and how can I remove them?</p> <p>Thank you for any help!</p>
[ { "answer_id": 219042, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": -1, "selected": false, "text": "<p><code>&lt;br /&gt;</code> tags coming from the content editor. You added line breaks which are converted to <code>&lt;br /&gt;</code> tags.</p>\n\n<p>Use your shortcode in this way</p>\n\n<pre><code>[rezept][rezept-zutaten]&lt;span&gt;Zutat 1&lt;/span&gt;&lt;span&gt;Zutat 2&lt;/span&gt;&lt;span&gt;Zutat 3&lt;/span&gt;[/rezept-zutaten][/rezept]\n</code></pre>\n\n<p>OR as per @jgraup suggestion you can use <code>strip_tags</code> to allow only certain tags.</p>\n\n<pre><code>function rezept_func( $atts, $content = null ){\n $content = strip_tags($content, '&lt;span&gt;&lt;p&gt;');\n return '&lt;div class=\"drl-rezept-wrapper\"&gt;'.do_shortcode($content).'&lt;/div&gt;';\n}\nadd_shortcode( 'rezept', 'rezept_func' );\n</code></pre>\n\n<p>Remember now user will never be able to add <code>&lt;br /&gt;</code> tags in content. The best to let user understand that WordPress convert line break in <code>&lt;br /&gt;</code>.</p>\n" }, { "answer_id": 219046, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>If you want to just strip the <code>&lt;br /&gt;</code> from the content then you could modify your function to replace that signature with an empty string. It feels like a dirty hack, but it's working for me.</p>\n\n<p>It's worth noting that my Chrome tools show <code>&lt;br&gt;</code> but the actual code is rendering <code>&lt;br /&gt;</code> which is what the expression is checking against.</p>\n\n<pre><code>//[rezept]\nfunction rezept_func( $atts, $content = null ) {\n\n // remove '&lt;br /&gt;'\n $no_br = preg_replace( \"/(&lt;br\\s\\/&gt;)/\", \"\", do_shortcode( $content ) );\n return '&lt;div class=\"drl-rezept-wrapper\"&gt;' . $no_br . '&lt;/div&gt;';\n}\n\nadd_shortcode( 'rezept', 'rezept_func' );\n\nfunction rezept_zutaten_func( $atts, $content = null ) {\n\n // remove '&lt;br /&gt;'\n $no_br = preg_replace( \"/(&lt;br\\s\\/&gt;)/\", \"\", $content );\n return '&lt;div class=\"drl-rezept-left\"&gt;' . $no_br . '&lt;/div&gt;';\n}\n\nadd_shortcode( 'rezept-zutaten', 'rezept_zutaten_func' );\n</code></pre>\n\n<p>The reason this is happening is there is a <a href=\"https://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow\"><code>wpautop</code></a> filter on the <code>$content</code> before it reaches your shortcode. You can actually disable all extra <code>&lt;br /&gt;</code> and <code>&lt;p&gt;</code> tags by adding:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\n</code></pre>\n\n<p>And you can enable the <code>p</code> without <code>br</code> by registering our own filter:</p>\n\n<pre><code>add_filter( 'the_content', 'wpautop_no_br' );\n\nfunction wpautop_no_br ($content, $br){\n return wpautop($content, false);\n}\n</code></pre>\n\n<p>Although if you were to disable <a href=\"https://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow\"><code>wpautop</code></a> then you're affecting more than just your shortcode which is not recommended. To see the difference take a look at the output from these blocks.</p>\n\n<pre><code>echo '&lt;pre&gt;RAW&lt;/pre&gt;&lt;pre&gt;'\n . get_post( get_the_ID() )-&gt;post_content\n . '&lt;/pre&gt;';\n\necho '&lt;pre&gt;Filtered&lt;/pre&gt;&lt;pre&gt;'\n . wpautop( get_post( get_the_ID() )-&gt;post_content )\n . '&lt;/pre&gt;';\n\necho '&lt;pre&gt;Filtered - No BR&lt;/pre&gt;&lt;pre&gt;'\n . wpautop( get_post( get_the_ID() )-&gt;post_content, false )\n . '&lt;/pre&gt;';\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/219041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62987/" ]
I created enclosing shortcodes like this: ``` //[rezept] function rezept_func( $atts, $content = null ){ return '<div class="drl-rezept-wrapper">'.do_shortcode($content).'</div>'; } add_shortcode( 'rezept', 'rezept_func' ); function rezept_zutaten_func( $atts, $content = null ){ return '<div class="drl-rezept-left">'.$content.'</div>'; } add_shortcode( 'rezept-zutaten', 'rezept_zutaten_func' ); ``` The HTML code is: ``` [rezept] [rezept-zutaten] <span>Zutat 1</span> <span>Zutat 2</span> <span>Zutat 3</span> [/rezept-zutaten] [/rezept] ``` The result is this html code: ``` <div class="drl-rezept-wrapper"><br> <div class="drl-rezept-left"><br> <span>Zutat 1</span><br> <span>Zutat 2</span><br> <span>Zutat 3</span><br> </div><br> <br> </div> ``` Where are all the `<br>'s` are coming from and how can I remove them? Thank you for any help!
If you want to just strip the `<br />` from the content then you could modify your function to replace that signature with an empty string. It feels like a dirty hack, but it's working for me. It's worth noting that my Chrome tools show `<br>` but the actual code is rendering `<br />` which is what the expression is checking against. ``` //[rezept] function rezept_func( $atts, $content = null ) { // remove '<br />' $no_br = preg_replace( "/(<br\s\/>)/", "", do_shortcode( $content ) ); return '<div class="drl-rezept-wrapper">' . $no_br . '</div>'; } add_shortcode( 'rezept', 'rezept_func' ); function rezept_zutaten_func( $atts, $content = null ) { // remove '<br />' $no_br = preg_replace( "/(<br\s\/>)/", "", $content ); return '<div class="drl-rezept-left">' . $no_br . '</div>'; } add_shortcode( 'rezept-zutaten', 'rezept_zutaten_func' ); ``` The reason this is happening is there is a [`wpautop`](https://codex.wordpress.org/Function_Reference/wpautop) filter on the `$content` before it reaches your shortcode. You can actually disable all extra `<br />` and `<p>` tags by adding: ``` remove_filter( 'the_content', 'wpautop' ); ``` And you can enable the `p` without `br` by registering our own filter: ``` add_filter( 'the_content', 'wpautop_no_br' ); function wpautop_no_br ($content, $br){ return wpautop($content, false); } ``` Although if you were to disable [`wpautop`](https://codex.wordpress.org/Function_Reference/wpautop) then you're affecting more than just your shortcode which is not recommended. To see the difference take a look at the output from these blocks. ``` echo '<pre>RAW</pre><pre>' . get_post( get_the_ID() )->post_content . '</pre>'; echo '<pre>Filtered</pre><pre>' . wpautop( get_post( get_the_ID() )->post_content ) . '</pre>'; echo '<pre>Filtered - No BR</pre><pre>' . wpautop( get_post( get_the_ID() )->post_content, false ) . '</pre>'; ```
219,049
<p>I'm developing a plugin that use a Google Maps API. The plugin enqueuing script in this way: </p> <p><code>wp_enqueue_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize&amp;language=en-us', array('jquery'), false, true);</code></p> <p>Considering the fact that other plugins/themes may use same maps library, while <code>$handle</code> could be different, the validation <code>wp_script_is($handle,'registered')</code> does not makes sence. Duplicating of enqueued script leads to JS error: <code>You have included the Google Maps API multiple times on this page. This may cause unexpected errors.</code></p> <p>Regarding things described I've build a code that search thought <code>$wp_scripts</code> for Google Maps scripts and unset it, in case if found:</p> <pre><code>global $wp_scripts; foreach ($wp_scripts-&gt;registered as $key =&gt; $script) { if (preg_match('#maps\.google(?:\w+)?\.com/maps/api/js#', $script-&gt;src)) { unset($wp_scripts-&gt;registered[$key]); } } </code></pre> <p>The question is: how can I check and reassign dependencies of the removed scripts (in case if they're set by other plugins/themes). What will happens and how to deal with the fact that multiple plugins may use the same <code>&amp;callback=initialize</code> parameter of Google Maps API script.</p>
[ { "answer_id": 219051, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": false, "text": "<p>Don't stress about it. There are many ways in which plugins and themes can break each other and you just can not avoid it when everything happens in the same execution space/context.</p>\n\n<p>You should test against whatever plugins and themes you want to make sure your code works with but there is just no way to make everybody at every point in time happy. Actually it is kind of hubris from your side to decide that your enqueue should be given priorities over others....</p>\n" }, { "answer_id": 219546, "author": "Khaled Sadek", "author_id": 75122, "author_profile": "https://wordpress.stackexchange.com/users/75122", "pm_score": 4, "selected": true, "text": "<p><strong>EDIT :</strong> \nuse <code>wp_enqueue_script</code> as you want (enqueue in header or footer after jQuery as you want) to enqueue file called something like : <code>gmap.js</code> included in your plugin</p>\n\n<pre><code>wp_enqueue_script('custom-gmap', plugin_dir_url( __FILE__ ).'inc/js/gmap.js', array('jquery'), false, true);//just change your path and name of file\n</code></pre>\n\n<p>write this in your Js file :)</p>\n\n<pre><code>$(document).ready(function() {\n if (typeof google === 'object' &amp;&amp; typeof google.maps === 'object') {\n return;\n }else{\n $.getScript( 'http://maps.google.com/maps/api/js', function() {});\n }\n});\n</code></pre>\n\n<p><a href=\"http://codepen.io/khaled-sadek/pen/WwvOGb\">http://codepen.io/khaled-sadek/pen/WwvOGb</a></p>\n" }, { "answer_id": 220065, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>Rather than removing a script if it has already been enqueued, you could combine your answer to check for the Google Maps script and add the fallback to the javascript check suggested by @Kiki...</p>\n\n<pre><code>add_action('wp_enqueue_scripts','google_maps_script_loader',999);\n\nfunction google_maps_script_loader() {\n global $wp_scripts; $gmapsenqueued = false;\n foreach ($wp_scripts-&gt;registered as $key =&gt; $script) {\n if (preg_match('#maps\\.google(?:\\w+)?\\.com/maps/api/js#', $script-&gt;src)) {\n $gmapsenqueued = true;\n }\n }\n\n if ($gmapsenqueued) {\n wp_enqueue_script('custom-gmap', plugin_dir_url( __FILE__ ).'inc/js/gmap.js', array('jquery'), false, true);\n } else {\n wp_enqueue_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false&amp;callback=initialize&amp;language=en-us', array('jquery'), false, true);\n }\n}\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/219049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38121/" ]
I'm developing a plugin that use a Google Maps API. The plugin enqueuing script in this way: `wp_enqueue_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false&callback=initialize&language=en-us', array('jquery'), false, true);` Considering the fact that other plugins/themes may use same maps library, while `$handle` could be different, the validation `wp_script_is($handle,'registered')` does not makes sence. Duplicating of enqueued script leads to JS error: `You have included the Google Maps API multiple times on this page. This may cause unexpected errors.` Regarding things described I've build a code that search thought `$wp_scripts` for Google Maps scripts and unset it, in case if found: ``` global $wp_scripts; foreach ($wp_scripts->registered as $key => $script) { if (preg_match('#maps\.google(?:\w+)?\.com/maps/api/js#', $script->src)) { unset($wp_scripts->registered[$key]); } } ``` The question is: how can I check and reassign dependencies of the removed scripts (in case if they're set by other plugins/themes). What will happens and how to deal with the fact that multiple plugins may use the same `&callback=initialize` parameter of Google Maps API script.
**EDIT :** use `wp_enqueue_script` as you want (enqueue in header or footer after jQuery as you want) to enqueue file called something like : `gmap.js` included in your plugin ``` wp_enqueue_script('custom-gmap', plugin_dir_url( __FILE__ ).'inc/js/gmap.js', array('jquery'), false, true);//just change your path and name of file ``` write this in your Js file :) ``` $(document).ready(function() { if (typeof google === 'object' && typeof google.maps === 'object') { return; }else{ $.getScript( 'http://maps.google.com/maps/api/js', function() {}); } }); ``` <http://codepen.io/khaled-sadek/pen/WwvOGb>
219,062
<p>I want to display some data from an author on my loop with this code:</p> <ul> <li><p>Avatar</p> <pre><code>&lt;?php echo get_avatar( $q-&gt;ID, 255 ); ?&gt; </code></pre></li> <li><p>Name.</p> <pre><code>&lt;?php echo get_the_author_meta('display_name', $q-&gt;ID);?&gt; </code></pre></li> <li><p>Total post.</p> <pre><code>&lt;?php echo 'Posts made: ' . count_user_posts( get_the_author_meta($q-&gt;ID) ); ?&gt; </code></pre></li> </ul> <p>Full code:</p> <pre><code> &lt;?php $number = $count_post; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $offset = ($paged - 1) * $number; $users = get_users(); $query = get_users('&amp;offset='.$offset.'&amp;number='.$number); $total_users = count($users); $total_query = count($query); foreach($query as $q) { ?&gt; - Avatar &lt;?php echo get_avatar( $q-&gt;ID, 255 ); ?&gt; - Name. &lt;?php echo get_the_author_meta('display_name', $q-&gt;ID);?&gt; - Total post. &lt;?php echo 'Posts made: ' . count_user_posts( get_the_author_meta($q-&gt;ID) ); ?&gt; &lt;?php } ?&gt; </code></pre> <p>The avatar and the author's name is displayed, but the total post failed to display.</p> <p>Anybody know how to resolve the problem? Really appreciate for any idea.</p> <p>Regards</p>
[ { "answer_id": 219063, "author": "Ryan", "author_id": 80192, "author_profile": "https://wordpress.stackexchange.com/users/80192", "pm_score": 1, "selected": true, "text": "<p><strong>the_author_posts()</strong> doesn't accept any parameters see the following codex page for more info:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/the_author_posts#Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/the_author_posts#Parameters</a></p>\n\n<p><strong>* <em>UPDATED</em> *</strong></p>\n\n<p>Someone else had posted a VERY similar question. This should solve your problem:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/8566/show-author-post-count-in-sidebar-variable?rq=1\">Show author post count in sidebar - Variable</a></p>\n" }, { "answer_id": 219066, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": false, "text": "<p>Isn't it just:</p>\n\n<pre><code>&lt;?php echo 'Posts made: ' . count_user_posts( $q-&gt;ID ); ?&gt;\n</code></pre>\n\n<p>Assuming that <code>$q-&gt;ID</code> is your author's ID. <a href=\"https://codex.wordpress.org/Function_Reference/count_user_posts\" rel=\"nofollow\">count_user_posts()</a></p>\n" }, { "answer_id": 391074, "author": "Mohammad Ayoub Khan", "author_id": 207411, "author_profile": "https://wordpress.stackexchange.com/users/207411", "pm_score": 0, "selected": false, "text": "<p>This code will count users posts count and then show it.\nYou have to pass author id as variable <code>$authorID</code></p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php printf(__('%s', 'themetextdoamin'), count_user_posts($authorID, &quot;post&quot;)); ?&gt;\n</code></pre>\n" } ]
2016/02/26
[ "https://wordpress.stackexchange.com/questions/219062", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89109/" ]
I want to display some data from an author on my loop with this code: * Avatar ``` <?php echo get_avatar( $q->ID, 255 ); ?> ``` * Name. ``` <?php echo get_the_author_meta('display_name', $q->ID);?> ``` * Total post. ``` <?php echo 'Posts made: ' . count_user_posts( get_the_author_meta($q->ID) ); ?> ``` Full code: ``` <?php $number = $count_post; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $offset = ($paged - 1) * $number; $users = get_users(); $query = get_users('&offset='.$offset.'&number='.$number); $total_users = count($users); $total_query = count($query); foreach($query as $q) { ?> - Avatar <?php echo get_avatar( $q->ID, 255 ); ?> - Name. <?php echo get_the_author_meta('display_name', $q->ID);?> - Total post. <?php echo 'Posts made: ' . count_user_posts( get_the_author_meta($q->ID) ); ?> <?php } ?> ``` The avatar and the author's name is displayed, but the total post failed to display. Anybody know how to resolve the problem? Really appreciate for any idea. Regards
**the\_author\_posts()** doesn't accept any parameters see the following codex page for more info: <https://codex.wordpress.org/Function_Reference/the_author_posts#Parameters> **\* *UPDATED* \*** Someone else had posted a VERY similar question. This should solve your problem: [Show author post count in sidebar - Variable](https://wordpress.stackexchange.com/questions/8566/show-author-post-count-in-sidebar-variable?rq=1)
219,072
<p>I am looking for a way to embed WordPress <code>comment form</code> to <code>watch.php</code> in order to allow user to comment on a specific video. Can you tell me how?</p> <p><a href="https://i.stack.imgur.com/KGcAR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KGcAR.jpg" alt="Eaxample"></a></p>
[ { "answer_id": 219126, "author": "Jouke Nienhuis", "author_id": 86558, "author_profile": "https://wordpress.stackexchange.com/users/86558", "pm_score": 0, "selected": false, "text": "<p>If the video is embedded in a normal post, you just switch on the option leave comments below your posts when editing or writing a post.\nYou don't see that ? On the right of your edit post on top of the page, you can click on show/hide options. Check Comments.</p>\n" }, { "answer_id": 219131, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>Take a look at rendering a <a href=\"https://codex.wordpress.org/Function_Reference/comment_form\" rel=\"nofollow\"><code>comment_form</code></a>. You can render it anywhere in your page template and there are lots of ways to customize it.</p>\n\n<pre><code>$comments_args = array (\n // change the title of send button\n 'label_submit' =&gt; 'Send',\n // change the title of the reply section\n 'title_reply' =&gt; 'Leave Your Comment',\n // remove \"Text or HTML to be displayed after the set of comment fields\"\n 'comment_notes_after' =&gt; '',\n // redefine your own textarea (the comment body)\n 'comment_field' =&gt; '&lt;p class=\"comment-form-comment\"&gt;&lt;label for=\"comment\"&gt;' . _x( 'Comment', 'noun' ) . '&lt;/label&gt;&lt;br /&gt;&lt;textarea id=\"comment\" name=\"comment\" aria-required=\"true\"&gt;&lt;/textarea&gt;&lt;/p&gt;',\n);\n\ncomment_form( $comments_args );\n</code></pre>\n" } ]
2016/02/27
[ "https://wordpress.stackexchange.com/questions/219072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89567/" ]
I am looking for a way to embed WordPress `comment form` to `watch.php` in order to allow user to comment on a specific video. Can you tell me how? [![Eaxample](https://i.stack.imgur.com/KGcAR.jpg)](https://i.stack.imgur.com/KGcAR.jpg)
Take a look at rendering a [`comment_form`](https://codex.wordpress.org/Function_Reference/comment_form). You can render it anywhere in your page template and there are lots of ways to customize it. ``` $comments_args = array ( // change the title of send button 'label_submit' => 'Send', // change the title of the reply section 'title_reply' => 'Leave Your Comment', // remove "Text or HTML to be displayed after the set of comment fields" 'comment_notes_after' => '', // redefine your own textarea (the comment body) 'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>', ); comment_form( $comments_args ); ```
219,095
<p>When installing a fresh wordpress, one of the things one should do is, updating the salts in <code>wp-config.php</code>. </p> <p>The section looks like this</p> <pre><code>define('AUTH_KEY', 'put your unique phrase here'); define('SECURE_AUTH_KEY', 'put your unique phrase here'); define('LOGGED_IN_KEY', 'put your unique phrase here'); define('NONCE_KEY', 'put your unique phrase here'); define('AUTH_SALT', 'put your unique phrase here'); define('SECURE_AUTH_SALT', 'put your unique phrase here'); define('LOGGED_IN_SALT', 'put your unique phrase here'); define('NONCE_SALT', 'put your unique phrase here'); </code></pre> <p>If the client does change these salts or the constants are missing, wordpress will on save these values inside the database instead.</p> <p>For generating the the salts it uses <code>wp_generate_password(64, true, true)</code> The code doing this can be found in pluggable from line 1993.</p> <p>Now the question is : </p> <ul> <li><p>Is <code>wp_generate_password</code> as safe as the salts generated by the recommended <code>https://api.wordpress.org/secret-key/1.1/salt/</code> </p></li> <li><p>Is there any downgrade in security by having the salts in the database as this method falls back to that.</p></li> <li><p>Does it have any security implications to not set the values and let them be generated randomly on the fly to the db?</p></li> </ul>
[ { "answer_id": 219137, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>It depends on the randomness that can be achieved on your machine. I don't remebmer the exact details, but the wordpress.org API is there if the randomness of your machine is not good enough.</p></li>\n<li><p>Probably not. If someone has that kind of access to your DB or code then you are toast in any case and getting the salts is the least important problem you face.</p></li>\n<li><p>What would be a reason to do that? getting those 8 values from the DB will make every page being served very slightly slower without adding any value to your security.</p></li>\n</ol>\n\n<h1>Edit: why randomness (entropy) matters</h1>\n\n<p>first, maybe this <a href=\"https://security.stackexchange.com/questions/61676/why-do-wordpress-installations-retrieve-the-crypto-secrets-remotely-on-installat\">https://security.stackexchange.com/questions/61676/why-do-wordpress-installations-retrieve-the-crypto-secrets-remotely-on-installat</a> will explain it better then me</p>\n\n<p>The issue is that salts should not be guessed, therefor they are generated by relaying on some random number generator, which most OS has. But not all random generators are created equal and if for example your generator do not take as an input some values from the enviroment it will generate the same sequence of numbers and therefor anyone which inspects the behavior of the OS can come up with say the first 1000 numbers that are going to be generated, use them as salts, and have easier time guessing your password. </p>\n\n<p>This is especially problematic in a shared hosting enviroment where all sites use the same random generator, and therefor have access to the sequence of the randomly generated numbers and based on the knowledge of the OS and the random algorithm employed by it can guess the next and previously generated numbers.</p>\n\n<p>side note: this is the reason why smartphone and other software asks you to do some random input when initializing the devices/software. That random input serves as a base for random number generation and ensures that each device will generate a different sequence of numbers.</p>\n\n<p>The advantage of using wordpress.org as your random number generator, is by knowing that the numbers generated by it are impossible to guess without access to the servers as you don't know which algorithm, is being used, how it was initialized and where in the sequence you currently stand.</p>\n\n<p>But as the question I linked to says, relaying on external service is also a security problem. I find this to border paranoia as this kind of attack avenue requires sophistication most attackers lack (in the context of attacking wordpress sites), and I would not worry about the quality of the random generator, but if you do, all you have to do is generate the salts by yourself, maybe by using some random generator software which is not related to the server, and update the config file.</p>\n" }, { "answer_id": 219217, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 4, "selected": true, "text": "<blockquote>\n <ol>\n <li>Is <code>wp_generate_password()</code> as safe as the salts generated by the recommended <code>https://api.wordpress.org/secret-key/1.1/salt/</code>?</li>\n </ol>\n</blockquote>\n\n<p>Those details can't be answered as for obvious reasons, the internals are unknown by the public. If we could answer that, then details would be known that allow for reverse engineering the process. This <em>could</em> lead to a decrease of security. Note, that someone could still try to set a gazillion of requests to this Url and then try to reverse engineer the process from watching what bubbles to the surface.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Is there any downgrade in security by having the salts in the database as this method falls back to that?</li>\n </ol>\n</blockquote>\n\n<p>Yes. You <strong>do not want</strong> to have security details/authentication credentials saved anywhere where it might be accessible by others. This includes:</p>\n\n<ul>\n<li>Version control</li>\n<li>Command line history</li>\n<li>Database or file backups</li>\n<li>…</li>\n</ul>\n\n<p>Either keep your authentication credentials and related data (like for e.g. \"salt\") in <code>.env</code> files (see <a href=\"https://github.com/vlucas/phpdotenv\" rel=\"nofollow noreferrer\">Dotenv package</a>), in your deployment services secret secure haven, in separate configuration files (for e.g. AWS credentials file) and therefore in only a single location.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>Does it have any security implications to not set the values and let them be generated randomly on the fly <strike>to the db</strike>?</li>\n </ol>\n</blockquote>\n\n<p>Yes. As auth constants are used in Cookies as well, you would <strong>invalidate your users log in sessions</strong> by invalidating your users Cookies. Those are constants for a reason: They should stick and do not change per request.</p>\n\n<p><strong>Edit:</strong> As @gmazzap pointed me to it, I was <em>not</em> talking about values saved to the database, but about <em>\"generated on the fly\"</em> constants. In case you save it to the database, please refer to point <em>2</em> regarding security. </p>\n\n<p>For further additions, please follow <a href=\"https://security.stackexchange.com/a/61754/46854\">the link</a> from @Mark Kaplun and read @gmazzap answer in detail (and upvote both).</p>\n\n<p><strong>Additional Note/Reminder:</strong> Always add some own pseudo random characters to the retrieved data from the API servers. And never ever give your credentials or your database out of hands. You won't believe what people tend to email, save on usb-sticks, their private dropbox accounts or on hard disks on laptops without password…</p>\n\n<p><strong>Edit:</strong> As @stephenharris pointed out in [chat], there's an interesting <a href=\"https://codeseekah.com/2012/04/09/why-wordpress-authentication-unique-keys-and-salts-are-important/\" rel=\"nofollow noreferrer\">blog post around that topic</a> that goes in far more detail than our answers here.</p>\n" }, { "answer_id": 219221, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p><code>Is wp_generate_password()</code> as safe as the salts generated by the recommended <a href=\"https://api.wordpress.org/secret-key/1.1/salt/\" rel=\"nofollow noreferrer\">https://api.wordpress.org/secret-key/1.1/salt/</a></p>\n</blockquote>\n\n<p>As <strong>@kaiser</strong> <a href=\"https://wordpress.stackexchange.com/a/219217/35541\">said</a> the internal details of API salt generation are not known, but -honestly- the API returns a 64 character string where each character is one of the same 92 possible glyphs used by <code>wp_generate_password()</code>.</p>\n\n<p>Note that if the server has PHP 7, random integers used to pick one of the 92 glyphs is generated using <a href=\"http://php.net/manual/en/book.csprng.php\" rel=\"nofollow noreferrer\">PHP 7 CSPRNG</a> and I doubt that API will have something more stronger that that. In older PHP versions, random values are provided by <a href=\"http://php.net/manual/en/function.mt-rand.php\" rel=\"nofollow noreferrer\"><code>mt_rand</code></a>.</p>\n\n<p>Considering this, and considering that strongness of a password resides much more on the encryption algorithm then on the salt used, I can say that, yes, <code>wp_generate_password</code> is very likely as safe as the salts generated by API. </p>\n\n<blockquote>\n <p>Is there any downgrade in security by having the salts in the database as this method falls back to that.</p>\n</blockquote>\n\n<p>For this point, I agree with <strong>@kaiser</strong>.</p>\n\n<p>Let's assume that someone get a copy of your database dump, done for a backup. In that db dump, they can see your users passwords, but encrypted.</p>\n\n<p>If they have access to salts, is easier to them hack your website.</p>\n\n<p>Moreover, by knowing salt used, user IDs and user metas (where session tokens are stored), is very easy to reproduce nonce values for any of the users, without having to know the \"decrypted\" password.</p>\n\n<p>Of course, if a malicious user obtains a copy of your database, your security is very compromised anyway, but by storing salts in db, you make life of that malicious user easier.</p>\n\n<blockquote>\n <p>Does it have any security implications to not set the values and let them be generated randomly on the fly to the db?</p>\n</blockquote>\n\n<p>If salts aren't set at all, they are generated with <code>wp_generate_password()</code> only the first time WP tries to access them, then are stored to database and on subsequent requests, they are pulled from there.</p>\n\n<p>As mentioned earlier, salts generated by <code>wp_generate_password()</code> are not bad per se, but since they are stored in db, the secutity implications are what said in previous point: if someone has access to a copy of your db, it is more dangerous if that db copy contains the salts.</p>\n\n<p>However, the <em>real</em> security implications are when non-secure values are used for salts. In fact, if weak values are set in configuration, WP will not generate any value, but will use that weak values.. In short, if the choose is between no salts in configuration and weak salts, the former is surely better.</p>\n\n<p>Note that in <em>recent</em> versions of WP (not sure since which exact version) the default value <code>'put your unique phrase here'</code> is ignored, so if <code>wp-config.php</code> contains that value for any salt, WordPress will ignore it and use a value generated with <code>wp_generate_password()</code> that is better than a weak value, but worse than a strong value stored in config (because storing salts in db...). Automatically generated values are used even in the case that the same salt value is used for more than once salt.</p>\n\n<h3>Notes</h3>\n\n<ul>\n<li><p>A change in salts will logout any user logged in your site before the change, including those users that are not logged in in the moment you change but that choosed \"remember me\" option when logged in before the change.</p></li>\n<li><p>When WordPress is installed using the \"installer\" (without manual creation of <code>wp-config.php</code>) salts values are generated pulling values from API.</p></li>\n</ul>\n" } ]
2016/02/27
[ "https://wordpress.stackexchange.com/questions/219095", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64782/" ]
When installing a fresh wordpress, one of the things one should do is, updating the salts in `wp-config.php`. The section looks like this ``` define('AUTH_KEY', 'put your unique phrase here'); define('SECURE_AUTH_KEY', 'put your unique phrase here'); define('LOGGED_IN_KEY', 'put your unique phrase here'); define('NONCE_KEY', 'put your unique phrase here'); define('AUTH_SALT', 'put your unique phrase here'); define('SECURE_AUTH_SALT', 'put your unique phrase here'); define('LOGGED_IN_SALT', 'put your unique phrase here'); define('NONCE_SALT', 'put your unique phrase here'); ``` If the client does change these salts or the constants are missing, wordpress will on save these values inside the database instead. For generating the the salts it uses `wp_generate_password(64, true, true)` The code doing this can be found in pluggable from line 1993. Now the question is : * Is `wp_generate_password` as safe as the salts generated by the recommended `https://api.wordpress.org/secret-key/1.1/salt/` * Is there any downgrade in security by having the salts in the database as this method falls back to that. * Does it have any security implications to not set the values and let them be generated randomly on the fly to the db?
> > 1. Is `wp_generate_password()` as safe as the salts generated by the recommended `https://api.wordpress.org/secret-key/1.1/salt/`? > > > Those details can't be answered as for obvious reasons, the internals are unknown by the public. If we could answer that, then details would be known that allow for reverse engineering the process. This *could* lead to a decrease of security. Note, that someone could still try to set a gazillion of requests to this Url and then try to reverse engineer the process from watching what bubbles to the surface. > > 2. Is there any downgrade in security by having the salts in the database as this method falls back to that? > > > Yes. You **do not want** to have security details/authentication credentials saved anywhere where it might be accessible by others. This includes: * Version control * Command line history * Database or file backups * … Either keep your authentication credentials and related data (like for e.g. "salt") in `.env` files (see [Dotenv package](https://github.com/vlucas/phpdotenv)), in your deployment services secret secure haven, in separate configuration files (for e.g. AWS credentials file) and therefore in only a single location. > > 3. Does it have any security implications to not set the values and let them be generated randomly on the fly to the db? > > > Yes. As auth constants are used in Cookies as well, you would **invalidate your users log in sessions** by invalidating your users Cookies. Those are constants for a reason: They should stick and do not change per request. **Edit:** As @gmazzap pointed me to it, I was *not* talking about values saved to the database, but about *"generated on the fly"* constants. In case you save it to the database, please refer to point *2* regarding security. For further additions, please follow [the link](https://security.stackexchange.com/a/61754/46854) from @Mark Kaplun and read @gmazzap answer in detail (and upvote both). **Additional Note/Reminder:** Always add some own pseudo random characters to the retrieved data from the API servers. And never ever give your credentials or your database out of hands. You won't believe what people tend to email, save on usb-sticks, their private dropbox accounts or on hard disks on laptops without password… **Edit:** As @stephenharris pointed out in [chat], there's an interesting [blog post around that topic](https://codeseekah.com/2012/04/09/why-wordpress-authentication-unique-keys-and-salts-are-important/) that goes in far more detail than our answers here.
219,114
<p>I am saving extra profile fields to my users' profiles - not via User admin but via another method (a plugin, but that's not important - all the user data is there properly).</p> <p>Now I do also want to show the extra info on User profiles in the admin backend, and make them editable there, too. I have followed the Justin Tadlock code at <a href="http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields" rel="nofollow">http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields</a> - that means I have added some actions and two functions to functions.php, to support displaying and updating these fields on the backend.</p> <p>The problem is, fields whose names include underscores are not returning results properly.</p> <p>ie. Whilst I can properly return the value of "company", the value of "company_url" is also returned as though it were "company" (eg. "Microsoft" instead of "<a href="http://www.microsoft.com" rel="nofollow">http://www.microsoft.com</a>").</p> <p>My two functions are below. I haven't yet updated the save function as this would just corrupt the User data with a duplicate of the "company" value. I have many field names containing "_", so this will be important.</p> <pre><code> /* * Extra profile fields: Show on user admin backend * http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields */ add_action( 'show_user_profile', 'mysite_show_user_meta' ); add_action( 'edit_user_profile', 'mysite_show_extra_profile_fields' ); function mysite_show_extra_profile_fields( $user ) { ?&gt; &lt;h3&gt;Extra profile information&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="twitter"&gt;Twitter&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="twitter" id="twitter" value="&lt;?php echo esc_attr( get_the_author_meta( 'twitter', $user-&gt;ID ) ); ?&gt;" class="regular-text" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Please enter your Twitter username.&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="company"&gt;Company&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="company" id="company" value="&lt;?php echo esc_attr( get_the_author_meta( 'company', $user-&gt;ID ) ); ?&gt;" class="regular-text" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Please enter your company.&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="company_url"&gt;Company website&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="company_url" id="company_url" value="&lt;?php echo esc_attr( get_the_author_meta( 'company_url', $user-&gt;ID ) ); ?&gt;" class="regular-text" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Please enter your company website URL.&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="photo_url"&gt;Photo URL&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="photo_url" id="photo_url" value="&lt;?php echo esc_attr( get_the_author_meta( 'photo_url', $user-&gt;ID ) ); ?&gt;" class="regular-text" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Please enter your photo URL. &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } /* * Extra profile fields: Save * http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields */ add_action( 'personal_options_update', 'mysite_user_meta' ); add_action( 'edit_user_profile_update', 'mysite_user_meta' ); function mysite_user_meta( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; /* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */ update_usermeta( $user_id, 'twitter', $_POST['twitter'] ); } </code></pre>
[ { "answer_id": 219137, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>It depends on the randomness that can be achieved on your machine. I don't remebmer the exact details, but the wordpress.org API is there if the randomness of your machine is not good enough.</p></li>\n<li><p>Probably not. If someone has that kind of access to your DB or code then you are toast in any case and getting the salts is the least important problem you face.</p></li>\n<li><p>What would be a reason to do that? getting those 8 values from the DB will make every page being served very slightly slower without adding any value to your security.</p></li>\n</ol>\n\n<h1>Edit: why randomness (entropy) matters</h1>\n\n<p>first, maybe this <a href=\"https://security.stackexchange.com/questions/61676/why-do-wordpress-installations-retrieve-the-crypto-secrets-remotely-on-installat\">https://security.stackexchange.com/questions/61676/why-do-wordpress-installations-retrieve-the-crypto-secrets-remotely-on-installat</a> will explain it better then me</p>\n\n<p>The issue is that salts should not be guessed, therefor they are generated by relaying on some random number generator, which most OS has. But not all random generators are created equal and if for example your generator do not take as an input some values from the enviroment it will generate the same sequence of numbers and therefor anyone which inspects the behavior of the OS can come up with say the first 1000 numbers that are going to be generated, use them as salts, and have easier time guessing your password. </p>\n\n<p>This is especially problematic in a shared hosting enviroment where all sites use the same random generator, and therefor have access to the sequence of the randomly generated numbers and based on the knowledge of the OS and the random algorithm employed by it can guess the next and previously generated numbers.</p>\n\n<p>side note: this is the reason why smartphone and other software asks you to do some random input when initializing the devices/software. That random input serves as a base for random number generation and ensures that each device will generate a different sequence of numbers.</p>\n\n<p>The advantage of using wordpress.org as your random number generator, is by knowing that the numbers generated by it are impossible to guess without access to the servers as you don't know which algorithm, is being used, how it was initialized and where in the sequence you currently stand.</p>\n\n<p>But as the question I linked to says, relaying on external service is also a security problem. I find this to border paranoia as this kind of attack avenue requires sophistication most attackers lack (in the context of attacking wordpress sites), and I would not worry about the quality of the random generator, but if you do, all you have to do is generate the salts by yourself, maybe by using some random generator software which is not related to the server, and update the config file.</p>\n" }, { "answer_id": 219217, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 4, "selected": true, "text": "<blockquote>\n <ol>\n <li>Is <code>wp_generate_password()</code> as safe as the salts generated by the recommended <code>https://api.wordpress.org/secret-key/1.1/salt/</code>?</li>\n </ol>\n</blockquote>\n\n<p>Those details can't be answered as for obvious reasons, the internals are unknown by the public. If we could answer that, then details would be known that allow for reverse engineering the process. This <em>could</em> lead to a decrease of security. Note, that someone could still try to set a gazillion of requests to this Url and then try to reverse engineer the process from watching what bubbles to the surface.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Is there any downgrade in security by having the salts in the database as this method falls back to that?</li>\n </ol>\n</blockquote>\n\n<p>Yes. You <strong>do not want</strong> to have security details/authentication credentials saved anywhere where it might be accessible by others. This includes:</p>\n\n<ul>\n<li>Version control</li>\n<li>Command line history</li>\n<li>Database or file backups</li>\n<li>…</li>\n</ul>\n\n<p>Either keep your authentication credentials and related data (like for e.g. \"salt\") in <code>.env</code> files (see <a href=\"https://github.com/vlucas/phpdotenv\" rel=\"nofollow noreferrer\">Dotenv package</a>), in your deployment services secret secure haven, in separate configuration files (for e.g. AWS credentials file) and therefore in only a single location.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>Does it have any security implications to not set the values and let them be generated randomly on the fly <strike>to the db</strike>?</li>\n </ol>\n</blockquote>\n\n<p>Yes. As auth constants are used in Cookies as well, you would <strong>invalidate your users log in sessions</strong> by invalidating your users Cookies. Those are constants for a reason: They should stick and do not change per request.</p>\n\n<p><strong>Edit:</strong> As @gmazzap pointed me to it, I was <em>not</em> talking about values saved to the database, but about <em>\"generated on the fly\"</em> constants. In case you save it to the database, please refer to point <em>2</em> regarding security. </p>\n\n<p>For further additions, please follow <a href=\"https://security.stackexchange.com/a/61754/46854\">the link</a> from @Mark Kaplun and read @gmazzap answer in detail (and upvote both).</p>\n\n<p><strong>Additional Note/Reminder:</strong> Always add some own pseudo random characters to the retrieved data from the API servers. And never ever give your credentials or your database out of hands. You won't believe what people tend to email, save on usb-sticks, their private dropbox accounts or on hard disks on laptops without password…</p>\n\n<p><strong>Edit:</strong> As @stephenharris pointed out in [chat], there's an interesting <a href=\"https://codeseekah.com/2012/04/09/why-wordpress-authentication-unique-keys-and-salts-are-important/\" rel=\"nofollow noreferrer\">blog post around that topic</a> that goes in far more detail than our answers here.</p>\n" }, { "answer_id": 219221, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p><code>Is wp_generate_password()</code> as safe as the salts generated by the recommended <a href=\"https://api.wordpress.org/secret-key/1.1/salt/\" rel=\"nofollow noreferrer\">https://api.wordpress.org/secret-key/1.1/salt/</a></p>\n</blockquote>\n\n<p>As <strong>@kaiser</strong> <a href=\"https://wordpress.stackexchange.com/a/219217/35541\">said</a> the internal details of API salt generation are not known, but -honestly- the API returns a 64 character string where each character is one of the same 92 possible glyphs used by <code>wp_generate_password()</code>.</p>\n\n<p>Note that if the server has PHP 7, random integers used to pick one of the 92 glyphs is generated using <a href=\"http://php.net/manual/en/book.csprng.php\" rel=\"nofollow noreferrer\">PHP 7 CSPRNG</a> and I doubt that API will have something more stronger that that. In older PHP versions, random values are provided by <a href=\"http://php.net/manual/en/function.mt-rand.php\" rel=\"nofollow noreferrer\"><code>mt_rand</code></a>.</p>\n\n<p>Considering this, and considering that strongness of a password resides much more on the encryption algorithm then on the salt used, I can say that, yes, <code>wp_generate_password</code> is very likely as safe as the salts generated by API. </p>\n\n<blockquote>\n <p>Is there any downgrade in security by having the salts in the database as this method falls back to that.</p>\n</blockquote>\n\n<p>For this point, I agree with <strong>@kaiser</strong>.</p>\n\n<p>Let's assume that someone get a copy of your database dump, done for a backup. In that db dump, they can see your users passwords, but encrypted.</p>\n\n<p>If they have access to salts, is easier to them hack your website.</p>\n\n<p>Moreover, by knowing salt used, user IDs and user metas (where session tokens are stored), is very easy to reproduce nonce values for any of the users, without having to know the \"decrypted\" password.</p>\n\n<p>Of course, if a malicious user obtains a copy of your database, your security is very compromised anyway, but by storing salts in db, you make life of that malicious user easier.</p>\n\n<blockquote>\n <p>Does it have any security implications to not set the values and let them be generated randomly on the fly to the db?</p>\n</blockquote>\n\n<p>If salts aren't set at all, they are generated with <code>wp_generate_password()</code> only the first time WP tries to access them, then are stored to database and on subsequent requests, they are pulled from there.</p>\n\n<p>As mentioned earlier, salts generated by <code>wp_generate_password()</code> are not bad per se, but since they are stored in db, the secutity implications are what said in previous point: if someone has access to a copy of your db, it is more dangerous if that db copy contains the salts.</p>\n\n<p>However, the <em>real</em> security implications are when non-secure values are used for salts. In fact, if weak values are set in configuration, WP will not generate any value, but will use that weak values.. In short, if the choose is between no salts in configuration and weak salts, the former is surely better.</p>\n\n<p>Note that in <em>recent</em> versions of WP (not sure since which exact version) the default value <code>'put your unique phrase here'</code> is ignored, so if <code>wp-config.php</code> contains that value for any salt, WordPress will ignore it and use a value generated with <code>wp_generate_password()</code> that is better than a weak value, but worse than a strong value stored in config (because storing salts in db...). Automatically generated values are used even in the case that the same salt value is used for more than once salt.</p>\n\n<h3>Notes</h3>\n\n<ul>\n<li><p>A change in salts will logout any user logged in your site before the change, including those users that are not logged in in the moment you change but that choosed \"remember me\" option when logged in before the change.</p></li>\n<li><p>When WordPress is installed using the \"installer\" (without manual creation of <code>wp-config.php</code>) salts values are generated pulling values from API.</p></li>\n</ul>\n" } ]
2016/02/27
[ "https://wordpress.stackexchange.com/questions/219114", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
I am saving extra profile fields to my users' profiles - not via User admin but via another method (a plugin, but that's not important - all the user data is there properly). Now I do also want to show the extra info on User profiles in the admin backend, and make them editable there, too. I have followed the Justin Tadlock code at <http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields> - that means I have added some actions and two functions to functions.php, to support displaying and updating these fields on the backend. The problem is, fields whose names include underscores are not returning results properly. ie. Whilst I can properly return the value of "company", the value of "company\_url" is also returned as though it were "company" (eg. "Microsoft" instead of "<http://www.microsoft.com>"). My two functions are below. I haven't yet updated the save function as this would just corrupt the User data with a duplicate of the "company" value. I have many field names containing "\_", so this will be important. ``` /* * Extra profile fields: Show on user admin backend * http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields */ add_action( 'show_user_profile', 'mysite_show_user_meta' ); add_action( 'edit_user_profile', 'mysite_show_extra_profile_fields' ); function mysite_show_extra_profile_fields( $user ) { ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="twitter">Twitter</label></th> <td> <input type="text" name="twitter" id="twitter" value="<?php echo esc_attr( get_the_author_meta( 'twitter', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description">Please enter your Twitter username.</span> </td> </tr> <tr> <th><label for="company">Company</label></th> <td> <input type="text" name="company" id="company" value="<?php echo esc_attr( get_the_author_meta( 'company', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description">Please enter your company.</span> </td> </tr> <tr> <th><label for="company_url">Company website</label></th> <td> <input type="text" name="company_url" id="company_url" value="<?php echo esc_attr( get_the_author_meta( 'company_url', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description">Please enter your company website URL.</span> </td> </tr> <tr> <th><label for="photo_url">Photo URL</label></th> <td> <input type="text" name="photo_url" id="photo_url" value="<?php echo esc_attr( get_the_author_meta( 'photo_url', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description">Please enter your photo URL. </span> </td> </tr> </table> <?php } /* * Extra profile fields: Save * http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields */ add_action( 'personal_options_update', 'mysite_user_meta' ); add_action( 'edit_user_profile_update', 'mysite_user_meta' ); function mysite_user_meta( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; /* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */ update_usermeta( $user_id, 'twitter', $_POST['twitter'] ); } ```
> > 1. Is `wp_generate_password()` as safe as the salts generated by the recommended `https://api.wordpress.org/secret-key/1.1/salt/`? > > > Those details can't be answered as for obvious reasons, the internals are unknown by the public. If we could answer that, then details would be known that allow for reverse engineering the process. This *could* lead to a decrease of security. Note, that someone could still try to set a gazillion of requests to this Url and then try to reverse engineer the process from watching what bubbles to the surface. > > 2. Is there any downgrade in security by having the salts in the database as this method falls back to that? > > > Yes. You **do not want** to have security details/authentication credentials saved anywhere where it might be accessible by others. This includes: * Version control * Command line history * Database or file backups * … Either keep your authentication credentials and related data (like for e.g. "salt") in `.env` files (see [Dotenv package](https://github.com/vlucas/phpdotenv)), in your deployment services secret secure haven, in separate configuration files (for e.g. AWS credentials file) and therefore in only a single location. > > 3. Does it have any security implications to not set the values and let them be generated randomly on the fly to the db? > > > Yes. As auth constants are used in Cookies as well, you would **invalidate your users log in sessions** by invalidating your users Cookies. Those are constants for a reason: They should stick and do not change per request. **Edit:** As @gmazzap pointed me to it, I was *not* talking about values saved to the database, but about *"generated on the fly"* constants. In case you save it to the database, please refer to point *2* regarding security. For further additions, please follow [the link](https://security.stackexchange.com/a/61754/46854) from @Mark Kaplun and read @gmazzap answer in detail (and upvote both). **Additional Note/Reminder:** Always add some own pseudo random characters to the retrieved data from the API servers. And never ever give your credentials or your database out of hands. You won't believe what people tend to email, save on usb-sticks, their private dropbox accounts or on hard disks on laptops without password… **Edit:** As @stephenharris pointed out in [chat], there's an interesting [blog post around that topic](https://codeseekah.com/2012/04/09/why-wordpress-authentication-unique-keys-and-salts-are-important/) that goes in far more detail than our answers here.
219,133
<p>I Know this may be the repetitive question, But whatever solutions are given, nothing is helping me..</p> <p>I have created the page </p> <pre><code>http://creditsmart.in/wp-content/themes/voice/emicalc.html </code></pre> <p>I want to add this page to my WordPress Page Only..</p> <p>1) I have tried 'text' mode using iframe. Nothing happened..<br><br> 2) I have directly put my html in WordPress page.. Nothing happened..<br><br> 3) Also, Whatever css and JS the above (emicalc.html) page is referencing to, I have put the same reference to header.php also. and then i tried to put tag in the Wordpress page.. Still Nothing happened..</p> <p>I dont want to use any plugin. Please</p> <p>Video shared for better understanding of problem - <code>http://tinypic.com/r/2d93709/9</code></p> <p>Any help shall be highly appreciated </p>
[ { "answer_id": 219134, "author": "Ittikorn S.", "author_id": 68069, "author_profile": "https://wordpress.stackexchange.com/users/68069", "pm_score": 1, "selected": false, "text": "<p>I tried to insert this <code>iframe</code> code into the text mode and it seems to be working. You can adjust the height value if it does not fit, but try to leave the width value at 100%.</p>\n\n<pre><code>&lt;iframe src=\"//creditsmart.in/wp-content/themes/voice/emicalc.html\" name=\"frame1\" scrolling=\"auto\" frameborder=\"no\" align=\"center\" height = \"300px\" width = \"100%\"&gt;\n&lt;/iframe&gt;\n</code></pre>\n" }, { "answer_id": 219135, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>You can't because it's a non-secure page <code>http</code> but you're loading into an <code>https</code> page. It's called <a href=\"https://developer.mozilla.org/en-US/docs/Security/Mixed_content\" rel=\"nofollow\"><code>Mixed Content</code></a>.</p>\n\n<hr>\n\n<p>Adjust your protocol to <code>//</code> and hope it renders over <code>https</code>.</p>\n\n<pre><code>&lt;iframe src=\"//creditsmart.in/wp-content/themes/voice/emicalc.html\" name=\"frame1\" scrolling=\"auto\" frameborder=\"no\" align=\"center\" height = \"300px\" width = \"100%\"&gt;\n&lt;/iframe&gt;\n</code></pre>\n\n<p>( iframe code modified from @Ittikorn's answer )</p>\n\n<hr>\n\n<p>If the file is in your same theme directory it's possible to create a shortcode:</p>\n\n<pre><code>[emicalc]\n</code></pre>\n\n<p>Then render the local file:</p>\n\n<pre><code>function emicalc__shortcode( $atts ) {\n\n $content = file_get_contents( get_stylesheet_directory() . '/emicalc.html');\n return $content;\n}\n\nadd_shortcode( 'emicalc', 'emicalc__shortcode' );\n</code></pre>\n\n<p>If it's remote you might be able to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_remote_get\" rel=\"nofollow\"><code>wp_remote_get()</code></a> instead of <a href=\"http://php.net/manual/en/function.file-get-contents.php\" rel=\"nofollow\"><code>file_get_contents()</code></a> but it requires you pull the contents using the server instead of allowing the client to do it.</p>\n\n<hr>\n\n<p>There is no other trick / <code>https</code> can only load <code>https</code> / <code>http</code> can always load <code>https</code>.</p>\n" } ]
2016/02/28
[ "https://wordpress.stackexchange.com/questions/219133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89624/" ]
I Know this may be the repetitive question, But whatever solutions are given, nothing is helping me.. I have created the page ``` http://creditsmart.in/wp-content/themes/voice/emicalc.html ``` I want to add this page to my WordPress Page Only.. 1) I have tried 'text' mode using iframe. Nothing happened.. 2) I have directly put my html in WordPress page.. Nothing happened.. 3) Also, Whatever css and JS the above (emicalc.html) page is referencing to, I have put the same reference to header.php also. and then i tried to put tag in the Wordpress page.. Still Nothing happened.. I dont want to use any plugin. Please Video shared for better understanding of problem - `http://tinypic.com/r/2d93709/9` Any help shall be highly appreciated
You can't because it's a non-secure page `http` but you're loading into an `https` page. It's called [`Mixed Content`](https://developer.mozilla.org/en-US/docs/Security/Mixed_content). --- Adjust your protocol to `//` and hope it renders over `https`. ``` <iframe src="//creditsmart.in/wp-content/themes/voice/emicalc.html" name="frame1" scrolling="auto" frameborder="no" align="center" height = "300px" width = "100%"> </iframe> ``` ( iframe code modified from @Ittikorn's answer ) --- If the file is in your same theme directory it's possible to create a shortcode: ``` [emicalc] ``` Then render the local file: ``` function emicalc__shortcode( $atts ) { $content = file_get_contents( get_stylesheet_directory() . '/emicalc.html'); return $content; } add_shortcode( 'emicalc', 'emicalc__shortcode' ); ``` If it's remote you might be able to use [`wp_remote_get()`](https://codex.wordpress.org/Function_Reference/wp_remote_get) instead of [`file_get_contents()`](http://php.net/manual/en/function.file-get-contents.php) but it requires you pull the contents using the server instead of allowing the client to do it. --- There is no other trick / `https` can only load `https` / `http` can always load `https`.
219,171
<p>Im using successfully the google CDN jQuery files instead of the built in files from Wordpress with the following code in my functions.php:</p> <pre><code>function register_jquery() { if (!is_admin()) { wp_deregister_script('jquery-core'); wp_register_script('jquery-core', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js', true, '2.2.0'); wp_enqueue_script('jquery-core'); wp_deregister_script('jquery-migrate'); wp_register_script('jquery-migrate', 'https://cdn.jsdelivr.net/jquery.migrate/1.2.1/jquery-migrate.min.js', true, '1.2.1'); wp_enqueue_script('jquery-migrate'); wp_deregister_script('jquery-ui'); wp_register_script('jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js', true, '1.11.4'); wp_enqueue_script('jquery-ui'); } } add_action( 'wp_enqueue_scripts', 'register_jquery' ); </code></pre> <p>I think, advantages for using the google lib are the google CDN and the client side caching of the library. </p> <p><strong>My Question:</strong> </p> <p>How can i change the code to load the latest jQuery Versions from Google automatically ?</p>
[ { "answer_id": 219178, "author": "markratledge", "author_id": 268, "author_profile": "https://wordpress.stackexchange.com/users/268", "pm_score": 2, "selected": false, "text": "<p>One: Generally, <em>as pointed out in the comments,</em> this is a bad idea for your code, because things will break. <a href=\"https://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/\" rel=\"nofollow noreferrer\">https://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/</a></p>\n\n<p>Two: There were once links to the \"latest\" jQuery libraries at the Google API - i.e., using the file name <code>jquery-latest.js</code> - but no more: <a href=\"https://stackoverflow.com/questions/12608242/latest-jquery-version-on-googles-cdn\">https://stackoverflow.com/questions/12608242/latest-jquery-version-on-googles-cdn</a></p>\n\n<blockquote>\n <p>We know that <a href=\"http://code.jquery.com/jquery-latest.js\" rel=\"nofollow noreferrer\">http://code.jquery.com/jquery-latest.js</a> is abused because\n of the CDN statistics showing it’s the most popular file. That\n wouldn’t be the case if it was only being used by developers to make a\n local copy.</p>\n \n <p>We have decided to stop updating this file, as well as the minified\n copy, keeping both files at version 1.11.1 forever.</p>\n \n <p>The Google CDN team has joined us in this effort to prevent\n inadvertent web breakage and no longer updates the file at\n <a href=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js\" rel=\"nofollow noreferrer\">http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js</a>. That file\n will stay locked at version 1.11.1 as well.</p>\n</blockquote>\n" }, { "answer_id": 219179, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<h2>The Good Answer</h2>\n\n<p>The only good answer to this question is <strong>don't do it</strong> - simple as that.</p>\n\n<p>Software in general expect things to work certain ways and libraries that are constantly evolving can have <code>breaking changes</code>. That means the change will cause another piece of software to stop working correctly which may be limited in scope or break all JS on the page.</p>\n\n<hr>\n\n<p><a href=\"https://developers.google.com/speed/libraries/#jquery\" rel=\"nofollow\">Google CDN</a> does not have directory for <code>latest</code>.</p>\n\n<blockquote>\n <p>versions:</p>\n \n <p>2.2.0, 2.1.4, 2.1.3, 2.1.1, 2.1.0, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 1.12.0, 1.11.3, 1.11.2, 1.11.1, 1.11.0, 1.10.2, 1.10.1, 1.10.0, 1.9.1, 1.9.0, 1.8.3, 1.8.2, 1.8.1, 1.8.0, 1.7.2, 1.7.1, 1.7.0, 1.6.4, 1.6.3, 1.6.2, 1.6.1, 1.6.0, 1.5.2, 1.5.1, 1.5.0, 1.4.4, 1.4.3, 1.4.2, 1.4.1, 1.4.0, 1.3.2, 1.3.1, 1.3.0, 1.2.6, 1.2.3</p>\n</blockquote>\n\n<p>But you can reference the jQuery CDN - <a href=\"https://code.jquery.com/jquery-latest.min.js\" rel=\"nofollow\"><code>https://code.jquery.com/jquery-latest.min.js</code></a> - although it is highly unadvised by jQuery based on their post - <a href=\"https://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/\" rel=\"nofollow\"><code>Don’t Use jquery-latest.js</code></a></p>\n\n<blockquote>\n <p>Earlier this week the jQuery CDN had an issue that made the jquery-latest.js and jquery-latest.min.js files unavailable for a few hours in some geographical areas. (This wasn’t a problem with the CDN itself, but with the repository that provides files for the CDN.) While we always hope to have 100% uptime, this particular outage emphasized the number of production sites following the antipattern of using this file. So let’s be clear: Don’t use jquery-latest.js on a production site.</p>\n</blockquote>\n\n<h2>The Bad Answer</h2>\n\n<p>While everyone you talk to should tell you never to use <code>latest</code> in production, when you decide to throw caution to the wind just be sure to postfix your methods with <code>yolo</code>. This ensures that anyone looking at your code immediately recognizes that you're a rebel and sometimes you gotta break your site to make some omelettes.</p>\n\n<p>Unfortunately, or fortunately depending on who you talk to, the rest of the libraries can't be referenced by <code>latest</code>.</p>\n\n<pre><code>function register_jquery_yolo() {\n\n // FIXME: This conditional should be removed:\n // if ( ! is_admin() ) { \n\n wp_deregister_script( 'jquery-core' );\n wp_register_script( 'jquery-core', 'https://code.jquery.com/jquery-latest.min.js', true, 'latest-yolo' );\n wp_enqueue_script( 'jquery-core' );\n\n wp_deregister_script( 'jquery-migrate' );\n wp_register_script( 'jquery-migrate', 'https://cdn.jsdelivr.net/jquery.migrate/1.2.1/jquery-migrate.min.js', true, '1.2.1' );\n wp_enqueue_script( 'jquery-migrate' );\n\n wp_deregister_script( 'jquery-ui' );\n wp_register_script( 'jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js', true, '1.11.4' );\n wp_enqueue_script( 'jquery-ui' );\n // }\n}\n\nadd_action( 'wp_enqueue_scripts', 'register_jquery_yolo' );\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I think, advantages for using the google lib are the google CDN and the client side caching of the library.</p>\n</blockquote>\n\n<p>One BIG problem with using <code>latest</code> is that you don't actually want to cache the file because the url always needs to point to an up-to-date file. How else would you get the latest if it was cached? </p>\n\n<hr>\n\n<blockquote>\n <p>I still can't understand why anyone still uses if ( ! is_admin() ) when using wp_enqueue_scripts. It is totally useless with no purpose at all – Pieter Goosen</p>\n</blockquote>\n\n<p>As was pointed out <code>if ( ! is_admin() )</code> should not be used in this case. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> is for front-end scripts, <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\"><code>admin_enqueue_scripts</code></a> for admin scripts, and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/login_enqueue_scripts\" rel=\"nofollow\"><code>login_enqueue_scripts</code></a> for login pages.</p>\n" } ]
2016/02/28
[ "https://wordpress.stackexchange.com/questions/219171", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45407/" ]
Im using successfully the google CDN jQuery files instead of the built in files from Wordpress with the following code in my functions.php: ``` function register_jquery() { if (!is_admin()) { wp_deregister_script('jquery-core'); wp_register_script('jquery-core', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js', true, '2.2.0'); wp_enqueue_script('jquery-core'); wp_deregister_script('jquery-migrate'); wp_register_script('jquery-migrate', 'https://cdn.jsdelivr.net/jquery.migrate/1.2.1/jquery-migrate.min.js', true, '1.2.1'); wp_enqueue_script('jquery-migrate'); wp_deregister_script('jquery-ui'); wp_register_script('jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js', true, '1.11.4'); wp_enqueue_script('jquery-ui'); } } add_action( 'wp_enqueue_scripts', 'register_jquery' ); ``` I think, advantages for using the google lib are the google CDN and the client side caching of the library. **My Question:** How can i change the code to load the latest jQuery Versions from Google automatically ?
The Good Answer --------------- The only good answer to this question is **don't do it** - simple as that. Software in general expect things to work certain ways and libraries that are constantly evolving can have `breaking changes`. That means the change will cause another piece of software to stop working correctly which may be limited in scope or break all JS on the page. --- [Google CDN](https://developers.google.com/speed/libraries/#jquery) does not have directory for `latest`. > > versions: > > > 2.2.0, 2.1.4, 2.1.3, 2.1.1, 2.1.0, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 1.12.0, 1.11.3, 1.11.2, 1.11.1, 1.11.0, 1.10.2, 1.10.1, 1.10.0, 1.9.1, 1.9.0, 1.8.3, 1.8.2, 1.8.1, 1.8.0, 1.7.2, 1.7.1, 1.7.0, 1.6.4, 1.6.3, 1.6.2, 1.6.1, 1.6.0, 1.5.2, 1.5.1, 1.5.0, 1.4.4, 1.4.3, 1.4.2, 1.4.1, 1.4.0, 1.3.2, 1.3.1, 1.3.0, 1.2.6, 1.2.3 > > > But you can reference the jQuery CDN - [`https://code.jquery.com/jquery-latest.min.js`](https://code.jquery.com/jquery-latest.min.js) - although it is highly unadvised by jQuery based on their post - [`Don’t Use jquery-latest.js`](https://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/) > > Earlier this week the jQuery CDN had an issue that made the jquery-latest.js and jquery-latest.min.js files unavailable for a few hours in some geographical areas. (This wasn’t a problem with the CDN itself, but with the repository that provides files for the CDN.) While we always hope to have 100% uptime, this particular outage emphasized the number of production sites following the antipattern of using this file. So let’s be clear: Don’t use jquery-latest.js on a production site. > > > The Bad Answer -------------- While everyone you talk to should tell you never to use `latest` in production, when you decide to throw caution to the wind just be sure to postfix your methods with `yolo`. This ensures that anyone looking at your code immediately recognizes that you're a rebel and sometimes you gotta break your site to make some omelettes. Unfortunately, or fortunately depending on who you talk to, the rest of the libraries can't be referenced by `latest`. ``` function register_jquery_yolo() { // FIXME: This conditional should be removed: // if ( ! is_admin() ) { wp_deregister_script( 'jquery-core' ); wp_register_script( 'jquery-core', 'https://code.jquery.com/jquery-latest.min.js', true, 'latest-yolo' ); wp_enqueue_script( 'jquery-core' ); wp_deregister_script( 'jquery-migrate' ); wp_register_script( 'jquery-migrate', 'https://cdn.jsdelivr.net/jquery.migrate/1.2.1/jquery-migrate.min.js', true, '1.2.1' ); wp_enqueue_script( 'jquery-migrate' ); wp_deregister_script( 'jquery-ui' ); wp_register_script( 'jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js', true, '1.11.4' ); wp_enqueue_script( 'jquery-ui' ); // } } add_action( 'wp_enqueue_scripts', 'register_jquery_yolo' ); ``` --- > > I think, advantages for using the google lib are the google CDN and the client side caching of the library. > > > One BIG problem with using `latest` is that you don't actually want to cache the file because the url always needs to point to an up-to-date file. How else would you get the latest if it was cached? --- > > I still can't understand why anyone still uses if ( ! is\_admin() ) when using wp\_enqueue\_scripts. It is totally useless with no purpose at all – Pieter Goosen > > > As was pointed out `if ( ! is_admin() )` should not be used in this case. [`wp_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) is for front-end scripts, [`admin_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts) for admin scripts, and [`login_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/login_enqueue_scripts) for login pages.
219,222
<p>When I do this:</p> <pre><code>function append_album_review_to_title( $title ) { global $post; if ( get_post_type( $post-&gt;ID ) == 'album_review' &amp;&amp; in_the_loop() ){ return 'Album Review: ' . $title; } else { return $title; } } add_filter('the_title', 'append_album_review_to_title'); </code></pre> <p>The title is properly prepended-to, but only when viewing the actual page.</p> <p>When I don't test for the loop by removing <code>&amp;&amp; in_the_loop()</code>, it properly prepends to the titles which are output by the plugin I use to auto-share my Published posts to Twitter. However, the problem is, if I don't test for the loop, the string is also prepended to <em>every single nav menu item name.</em></p> <p>What conditional statements can I use to test for nav menu items and skip them in the filter?</p> <h2>UPDATE 1</h2> <p>Thank you Ittikorn. I tried it but it doesn't work. I can see it's altering the <code>&lt;title&gt;</code> but unfortunately the output with the sharing plugin is still the original title.</p> <h2>UPDATE 2</h2> <p>Much appreciation, and though both would get genuine upvotes from me for the detailed and insightful responses if I could upvote, unfortunately, none of the solutions provided by Sumit or Peter worked. </p> <p>Sumit's solution worked in that it didn't needlessly break nav menu items by applying the filter to them, but it also did not apply the filter to the post-screen auto-social-sharing plugin, which is what I needed. </p> <p>Peter's solution also didn't work and did the exact same thing is Sumit's. I tried playing around with it, but couldn't get it to target the post titles for in_the_loop AND for the social sharing plugin's use but not for nav menu items.</p> <h2>SOLUTION</h2> <p>Peter's and Sumit's answers did truly help me tremendously though and lead to me eventually finding the oslution. </p> <p>Trying both answers I noticed that on the backend, the plugin would return warnings like "missing parameter 2" and "Notice: Trying to get property of non-object...', and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an <code>$id</code> is not being passed to <code>the_title</code> and so I can use this as a conditional. </p> <p>This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify <code>the_title</code> for use by a backend social sharing plugin):</p> <pre><code>function append_album_review_to_title( $title, $id = NULL ) { if ($id) { if ( get_post_type( $id ) == 'album_review' ){ return 'Album Review: ' . $title; } else { return $title; } } else { return 'Album Review: ' . $title; }; } add_filter('the_title', 'append_album_review_to_title', 10, 2); </code></pre> <p>Let me know if you think I can improve this somehow or if this could potentially cause future problems if unattended. And thank you for all your help.</p>
[ { "answer_id": 219231, "author": "Ittikorn S.", "author_id": 68069, "author_profile": "https://wordpress.stackexchange.com/users/68069", "pm_score": -1, "selected": false, "text": "<p>Try to use <code>wp_title</code> filter instead of <code>the_title</code> to rewrite on title meta tag</p>\n\n<pre><code>add_filter('wp_title', 'append_album_review_to_title');\n</code></pre>\n" }, { "answer_id": 219241, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>The problem is global <code>$post</code>. \nAs @Pieter suggested global <code>$post</code> object can be alter anytime with some other plugin or code. Menu items are effected because global <code>$post</code> does not contain the correct object.</p>\n\n<p>Instead of <code>$post</code>, <code>the_title</code> filter also provide you ID of current post in action, so use it in this way </p>\n\n<pre><code>function append_album_review_to_title( $title, $id ) {\n if ( get_post_type( $id ) == 'album_review' ){\n return 'Album Review: ' . $title;\n } else {\n return $title;\n }\n}\nadd_filter('the_title', 'append_album_review_to_title', 10, 2);\n</code></pre>\n" }, { "answer_id": 219293, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<h2>RE-ARRANGED ANSWER TO AVOID CONFUSION</h2>\n\n<p>Although the following solution might work, it is not ideal</p>\n\n<pre><code>add_filter( 'the_title', function ( $title, $post_id )\n{\n if ( 'album_review' === get_post_type( $post_id ) )\n $title = 'Album Review: ' . $title;\n\n return $title;\n}, 10, 2 );\n</code></pre>\n\n<p>The issue is, any post that uses <code>the_title()</code> or <code>get_the_title()</code> will be affected by this filter, and that include all queries and navigation menus. If you have posts from the <code>album_review</code> post type in your navigation menus, this filter will act on those titles as well.</p>\n\n<p>As you correctly pointed out, the <code>in_the_loop()</code> condition only target s the main query, and there is nothing similar to target custom queries and the nav menu items.</p>\n\n<p>The big issue with the template tags like <code>the_title()</code> and <code>the_content()</code> is that they do not know the context in which they are used, this makes them hard to target.</p>\n\n<p>To remove the title filter from only the navigation menus can be quite an issue, because, as I said, <code>the_title()</code> does not know the context in which it is used. The only probable way I can think of is to momentarily remove the title filter within the <code>wp_nav_menu_args</code> filter which runs before the nav menu items' titles, and then adding it back after the titles is added through either the <code>wp_page_menu</code> or the <code>wp_nav_menu</code> filter, depending on whether a fallback is set or not</p>\n\n<p>You can try the following:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_args', function ( $args )\n{\n // Remove the title filter for a while so we do not alter nav menu titles\n remove_filter( 'the_title', 'wpse_219222_customize_title', 10, 2 );\n\n // Re-apply the title filter after we add titles\n $filter = ( 'wp_page_menu' === $args['fallback_cb'] ) ? 'wp_page_menu' : 'wp_nav_menu';\n add_filter( $filter, 'wpse_219222_add_title_filter_back' );\n\n return $args;\n});\n\nfunction wpse_219222_add_title_filter_back( $nav_menu )\n{\n add_filter( 'the_title', 'wpse_219222_customize_title', 10, 2 );\n\n return $nav_menu;\n}\n\n/**\n * Our custom call back function which will be hooked to the_title filter\n */\nfunction wpse_219222_customize_title( $title, $post_id )\n{\n if ( 'album_review' === get_post_type( $post_id ) )\n $title = 'Album Review: ' . $title;\n\n return $title;\n}\n</code></pre>\n\n<h2>ADDITIONAL USEFUL INFO - to remove filter from other queries if needed</h2>\n\n<p>If I need to apply a filter to a specific query, I like to pass a custom query var to the query which I then check for in <code>pre_get_posts</code> and then use that to decide if my filter must be applied or not. Something like the following will work in custom query</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( 1 === $q-&gt;get( 'custom_title' ) )\n {\n add_filter( 'the_title', function ( $title, $post_id )\n {\n if ( 'album_review' === get_post_type( $post_id ) )\n $title = 'Album Review: ' . $title;\n\n return $title;\n }, 10, 2 );\n }\n});\n</code></pre>\n\n<p>You can then simply pass <code>'custom_title' =&gt; 1</code> to your query args to apply the filter to that specific query only</p>\n\n<p>Just for interest sake, and just to play around, you can also do something like this to target the main query on the home page and any custom query where <code>'custom_title' =&gt; 1</code> is passed</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( $q-&gt;is_home()\n &amp;&amp; $q-&gt;is_main_query() \n ) {\n $q-&gt;set( 'custom_title', 1 );\n }\n\n if ( 1 === $q-&gt;get( 'custom_title' ) )\n {\n add_filter( 'the_title', function ( $title, $post_id )\n {\n if ( 'album_review' === get_post_type( $post_id ) )\n $title = 'Album Review: ' . $title;\n\n return $title;\n }, 10, 2 );\n }\n});\n</code></pre>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/218451/31545\">Here</a> is another great filter idea by @birgire which you can adapt and modify if you need to target only post titles in a widget</p>\n\n<p>You can use this in conjunction with all the other methods as well as you see fit</p>\n" }, { "answer_id": 219562, "author": "Andre Bulatov", "author_id": 63378, "author_profile": "https://wordpress.stackexchange.com/users/63378", "pm_score": 1, "selected": true, "text": "<h3>Solution</h3>\n\n<pre><code>function append_album_review_to_title( $title, $id = NULL ) {\n if ($id) {\n if ( get_post_type( $id ) == 'album_review' ){\n return 'Album Review: ' . $title;\n } else {\n return $title;\n }\n } else {\n return 'Album Review: ' . $title;\n };\n}\nadd_filter('the_title', 'append_album_review_to_title', 10, 2);\n</code></pre>\n\n<h3>Explanation</h3>\n\n<p>Though neither solution worked completely, Peter's and Sumit's answers did help me tremendously and lead to me eventually finding the oslution. </p>\n\n<p>Trying both Sumit's and Peter's answers I noticed that on the backend, the plugin would return warnings like <code>missing parameter 2</code> and <code>Notice: Trying to get property of non-object...</code>, and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an <code>$id</code> is not being passed to <code>the_title</code> and so I can use this as a conditional. </p>\n\n<p>This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify <code>the_title</code> for use by a backend social sharing plugin):</p>\n" } ]
2016/02/29
[ "https://wordpress.stackexchange.com/questions/219222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63378/" ]
When I do this: ``` function append_album_review_to_title( $title ) { global $post; if ( get_post_type( $post->ID ) == 'album_review' && in_the_loop() ){ return 'Album Review: ' . $title; } else { return $title; } } add_filter('the_title', 'append_album_review_to_title'); ``` The title is properly prepended-to, but only when viewing the actual page. When I don't test for the loop by removing `&& in_the_loop()`, it properly prepends to the titles which are output by the plugin I use to auto-share my Published posts to Twitter. However, the problem is, if I don't test for the loop, the string is also prepended to *every single nav menu item name.* What conditional statements can I use to test for nav menu items and skip them in the filter? UPDATE 1 -------- Thank you Ittikorn. I tried it but it doesn't work. I can see it's altering the `<title>` but unfortunately the output with the sharing plugin is still the original title. UPDATE 2 -------- Much appreciation, and though both would get genuine upvotes from me for the detailed and insightful responses if I could upvote, unfortunately, none of the solutions provided by Sumit or Peter worked. Sumit's solution worked in that it didn't needlessly break nav menu items by applying the filter to them, but it also did not apply the filter to the post-screen auto-social-sharing plugin, which is what I needed. Peter's solution also didn't work and did the exact same thing is Sumit's. I tried playing around with it, but couldn't get it to target the post titles for in\_the\_loop AND for the social sharing plugin's use but not for nav menu items. SOLUTION -------- Peter's and Sumit's answers did truly help me tremendously though and lead to me eventually finding the oslution. Trying both answers I noticed that on the backend, the plugin would return warnings like "missing parameter 2" and "Notice: Trying to get property of non-object...', and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an `$id` is not being passed to `the_title` and so I can use this as a conditional. This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify `the_title` for use by a backend social sharing plugin): ``` function append_album_review_to_title( $title, $id = NULL ) { if ($id) { if ( get_post_type( $id ) == 'album_review' ){ return 'Album Review: ' . $title; } else { return $title; } } else { return 'Album Review: ' . $title; }; } add_filter('the_title', 'append_album_review_to_title', 10, 2); ``` Let me know if you think I can improve this somehow or if this could potentially cause future problems if unattended. And thank you for all your help.
### Solution ``` function append_album_review_to_title( $title, $id = NULL ) { if ($id) { if ( get_post_type( $id ) == 'album_review' ){ return 'Album Review: ' . $title; } else { return $title; } } else { return 'Album Review: ' . $title; }; } add_filter('the_title', 'append_album_review_to_title', 10, 2); ``` ### Explanation Though neither solution worked completely, Peter's and Sumit's answers did help me tremendously and lead to me eventually finding the oslution. Trying both Sumit's and Peter's answers I noticed that on the backend, the plugin would return warnings like `missing parameter 2` and `Notice: Trying to get property of non-object...`, and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an `$id` is not being passed to `the_title` and so I can use this as a conditional. This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify `the_title` for use by a backend social sharing plugin):
219,230
<p>I'm looking for a way to test out some <a href="http://wp-cli.org" rel="nofollow">WP-CLI</a> commands but from the <a href="https://wordpress.org/plugins/debug-bar-console/" rel="nofollow">Debug Bar Console</a> where I normally test <strong>PHP</strong>. For cases when I don't want to switch windows to <strong>SSH</strong>, this might be a way to reuse/develop effective <strong>CLI</strong> methods outside of the <strong>CLI</strong>.</p> <p>I've seen <a href="http://php.net/manual/en/function.exec.php" rel="nofollow">exec</a> but it only shows me what appears to be the last line of the command.</p> <pre><code>echo exec('ls -la'); // -rw-rw-r-- 1 www-data www-data 18108 Jan 20 21:57 widgets.php </code></pre> <p>Has anyone tried to string a more complex set of commands together and in a way that is more human-readable?</p>
[ { "answer_id": 219233, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>WP-CLI is not different from any other server side utilities in that you need to be able to have the permission to run them out of a webserver enviroment using <code>exec</code>, <code>spawn</code> or friends. For obvious reasons all those kinds of PHP APIs are going to be blocked on most servers and therefor it is unlikely that a server you do not manage (don't have SSH access is an indication) will let you run WP-CLI out of wordpress.</p>\n" }, { "answer_id": 219236, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>It looks like <a href=\"http://php.net/manual/en/function.system.php\" rel=\"nofollow\"><code>exec()</code></a> might still work with the right variables.</p>\n\n<pre><code>$last_line = exec( $command, &amp;$output, &amp;$return_var )\n</code></pre>\n\n<p>The second parameter captures all the return data while the return from the function captures the last line.</p>\n\n<hr>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/function.exec.php\" rel=\"nofollow\"><code>string exec( string $command, array &amp;$output, int &amp;$return_var )</code></a> is for calling a system command, and perhaps dealing with the output yourself.</li>\n<li><a href=\"http://php.net/manual/en/function.shell-exec.php\" rel=\"nofollow\"><code>string shell_exec( string $cmd )</code></a> Execute command via shell and return the complete output as a string.</li>\n<li><a href=\"http://php.net/manual/en/function.system.php\" rel=\"nofollow\"><code>string system( string $command, int &amp;$return_var )</code></a> is for executing a system command and immediately displaying the output - presumably text.</li>\n<li><a href=\"http://php.net/manual/en/function.passthru.php\" rel=\"nofollow\"><code>passthru( string $command, int &amp;$return_var )</code></a> is for executing a system command which you wish the raw return from - presumably something binary.</li>\n</ul>\n\n<hr>\n\n<pre><code>$commands = array(\n 'wp --version',\n 'whoami',\n 'pwd',\n 'ls -la',\n 'wp theme list',\n 'wp plugin list',\n);\n\necho '&lt;pre&gt;'.PHP_EOL;\nforeach ($commands as $command ) { \n\n // run command\n exec($command, $retval);\n\n // convert output array to text\n echo implode(PHP_EOL, $retval) . PHP_EOL;\n\n // clear the var for the next command\n unset($retval);\n}\necho '&lt;/pre&gt;'; \n</code></pre>\n" } ]
2016/02/29
[ "https://wordpress.stackexchange.com/questions/219230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84219/" ]
I'm looking for a way to test out some [WP-CLI](http://wp-cli.org) commands but from the [Debug Bar Console](https://wordpress.org/plugins/debug-bar-console/) where I normally test **PHP**. For cases when I don't want to switch windows to **SSH**, this might be a way to reuse/develop effective **CLI** methods outside of the **CLI**. I've seen [exec](http://php.net/manual/en/function.exec.php) but it only shows me what appears to be the last line of the command. ``` echo exec('ls -la'); // -rw-rw-r-- 1 www-data www-data 18108 Jan 20 21:57 widgets.php ``` Has anyone tried to string a more complex set of commands together and in a way that is more human-readable?
It looks like [`exec()`](http://php.net/manual/en/function.system.php) might still work with the right variables. ``` $last_line = exec( $command, &$output, &$return_var ) ``` The second parameter captures all the return data while the return from the function captures the last line. --- * [`string exec( string $command, array &$output, int &$return_var )`](http://php.net/manual/en/function.exec.php) is for calling a system command, and perhaps dealing with the output yourself. * [`string shell_exec( string $cmd )`](http://php.net/manual/en/function.shell-exec.php) Execute command via shell and return the complete output as a string. * [`string system( string $command, int &$return_var )`](http://php.net/manual/en/function.system.php) is for executing a system command and immediately displaying the output - presumably text. * [`passthru( string $command, int &$return_var )`](http://php.net/manual/en/function.passthru.php) is for executing a system command which you wish the raw return from - presumably something binary. --- ``` $commands = array( 'wp --version', 'whoami', 'pwd', 'ls -la', 'wp theme list', 'wp plugin list', ); echo '<pre>'.PHP_EOL; foreach ($commands as $command ) { // run command exec($command, $retval); // convert output array to text echo implode(PHP_EOL, $retval) . PHP_EOL; // clear the var for the next command unset($retval); } echo '</pre>'; ```
219,277
<p>What I'm trying to achive, is to set 2 loops on one page. <strong>First one</strong> takes 11 latest posts and sort them in rand order. <strong>Second</strong> show the rest of posts ordered by date. </p> <p><strong><em>FIRST LOOP</em></strong></p> <pre><code>$args = array('posts_per_page' =&gt; 11,'orderby' =&gt; 'rand' , 'order' =&gt; 'ASC'); $loop = new WP_Query($args); $do_not_duplicate[] = $post-&gt;ID; while ($loop-&gt; have_posts()) : $loop-&gt;the_post(); $do_not_duplicate[] = $post-&gt;ID; </code></pre> <p><strong><em>SECOND LOOP</em></strong></p> <pre><code>$args2 = array('posts_per_page' =&gt; 22, 'paged' =&gt; $paged, 'post__not_in' =&gt; $do_not_duplicate, 'orderby' =&gt; 'date', 'order' =&gt; 'ASC', 'max_num_pages' =&gt; 5); $loop2 = new WP_Query($args2); while ($loop2-&gt; have_posts()) : $loop2-&gt;the_post(); </code></pre> <p>My problem is that the second loop should show the same posts in same order after every refresh, unfortunately it's not. Any advice?</p>
[ { "answer_id": 219280, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": false, "text": "<p>The second query will not always show the same posts, as it is dependend on the first query, which is random.</p>\n\n<p>For example, you got 50 posts (ID 1 to 50, ordered by date).</p>\n\n<p>First run:</p>\n\n<p>First query takes 1,2,3,4,5,6,7,8,9,10,11 and passes those IDs to the second query, so the second query will show 12,13,14,...</p>\n\n<p>Second run:</p>\n\n<p>The first query randomly selects IDs 39,40,41,42,43,44,45,46,47,48,49,50, and the second query will return IDs 1-22.</p>\n\n<p>Please be also sure to call <code>wp_reset_postdata()</code> to ensure the correct behaviour of all queries. (thanks @PieterGoosen :) )</p>\n" }, { "answer_id": 219282, "author": "Lisa Anderson", "author_id": 49085, "author_profile": "https://wordpress.stackexchange.com/users/49085", "pm_score": 2, "selected": false, "text": "<p>Yes, don't forget the <code>&lt;?php wp_reset_postdata(); ?&gt;</code> between loops. I remember getting stumped on that the first time I ran multiple queries on a page.</p>\n" }, { "answer_id": 219302, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Getting posts randomly is quite expensive and should be avoided where needed. I think we can do this in a better way.</p>\n\n<ul>\n<li><p>Lets query all posts at once, regardless, sorted by date. WE will only query ID's which should be extremely quick</p></li>\n<li><p>Store the query results (<em>post ID's</em>) in two variables</p></li>\n<li><p>Shuffle the one array of ID's to randomize them and then get the first 11 ID's</p></li>\n<li><p>We will then remove those 11 ID's from the second array and get 22 ID's</p></li>\n<li><p>Merge the two arrays and run our final query</p></li>\n</ul>\n\n<p>Lets try the following code</p>\n\n<pre><code>$args = [ // ADJUST THESE AS NEEDED\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'ASC',\n 'fields' =&gt; 'ids' // Only get post ID's, this also bypass object caches\n];\n$array_1 = $array_2 = get_posts( $args );\n// Make sure we have posts and we have more than 11 posts\nif ( $array_1\n &amp;&amp; 11 &lt; count( $array_1 )\n) { \n // Shuffle the first array\n shuffle( $array_1 );\n // Get the first 11 entries sorted randomly\n $array_1_random = array_slice( $array_1, 0, 11 ); \n // Remove the entries from $array_1_random from $array_2\n $difference = array_diff( $array_2, $array_1_random );\n // Get the first 22 entries from $difference\n $diff_22_IDs = array_slice( $difference, 0, 22 ); \n // Merge the two arrays, $array_1_random and $diff_22_IDs\n $ids = array_merge( $array_1_random, $diff_22_IDs );\n\n // Now that we have our ID's sorted to suite our needs, query the posts\n $last_args = [ // DO NOT ADJUST THESE, SHOULD BE FINE\n 'post__in' =&gt; $ids,\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; count( $ids )\n ];\n $q = new WP_Query( $last_args );\n\n // Output your loop\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n the_title();\n\n }\n wp_reset_postdata(); // VERY VERY IMPORTANT\n}\n</code></pre>\n\n<h2>A FEW NOTES</h2>\n\n<ul>\n<li><p>Adjust the code as needed. You should have to change anything in <code>$last_args</code> though</p></li>\n<li><p>You said you needed one page, so there is no need to set the <code>paged</code> parameter as we will not paginate. If you require pagination, you would need to adjust my code slightly</p></li>\n<li><p><code>'max_num_pages'</code> is not a valid parameter</p></li>\n</ul>\n" }, { "answer_id": 219885, "author": "Maciek Wrona", "author_id": 89711, "author_profile": "https://wordpress.stackexchange.com/users/89711", "pm_score": 1, "selected": true, "text": "<p>With some clues from @PieterGoosen I've found working solution. </p>\n\n<p><strong>First loop</strong></p>\n\n<pre><code>$argsR = array(\n 'numberposts' =&gt; 11,\n 'fields' =&gt; 'ids'\n );\n\n$latest_posts = get_posts( $argsR );\nshuffle( $latest_posts );\n\n\n$args = array('posts_per_page' =&gt; 11,\n 'post__in' =&gt; $latest_posts , \n 'orderby' =&gt; 'post__in', \n 'order' =&gt; 'ASC');\n\n$loop = new WP_Query($args);\n$do_not_duplicate[] = $post-&gt;ID;\n\nwhile ($loop-&gt; have_posts()) : $loop-&gt;the_post();\n $do_not_duplicate[] = $post-&gt;ID;\n</code></pre>\n\n<p>So, first loop shows 11 most recent posts in random order and pushes each post ID to <code>$do_not_duplicate[]</code>array which I use to exclude most recent posts from second loop. </p>\n\n<p><strong>Second loop</strong> </p>\n\n<pre><code>$args2 = array(\n 'posts_per_page' =&gt;-1, \n 'post__not_in' =&gt; $do_not_duplicate, \n 'orderby' =&gt; 'date', \n 'order' =&gt; 'ASC');\n\n$loop2 = new WP_Query($args2);\n$num_of_posts = $loop-&gt;post_count;\nwhile ($loop2-&gt; have_posts()) : $loop2-&gt;the_post();\n</code></pre>\n\n<p>Having two seperate loops lets me paginate second posts list as I needed. </p>\n" } ]
2016/02/29
[ "https://wordpress.stackexchange.com/questions/219277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89711/" ]
What I'm trying to achive, is to set 2 loops on one page. **First one** takes 11 latest posts and sort them in rand order. **Second** show the rest of posts ordered by date. ***FIRST LOOP*** ``` $args = array('posts_per_page' => 11,'orderby' => 'rand' , 'order' => 'ASC'); $loop = new WP_Query($args); $do_not_duplicate[] = $post->ID; while ($loop-> have_posts()) : $loop->the_post(); $do_not_duplicate[] = $post->ID; ``` ***SECOND LOOP*** ``` $args2 = array('posts_per_page' => 22, 'paged' => $paged, 'post__not_in' => $do_not_duplicate, 'orderby' => 'date', 'order' => 'ASC', 'max_num_pages' => 5); $loop2 = new WP_Query($args2); while ($loop2-> have_posts()) : $loop2->the_post(); ``` My problem is that the second loop should show the same posts in same order after every refresh, unfortunately it's not. Any advice?
With some clues from @PieterGoosen I've found working solution. **First loop** ``` $argsR = array( 'numberposts' => 11, 'fields' => 'ids' ); $latest_posts = get_posts( $argsR ); shuffle( $latest_posts ); $args = array('posts_per_page' => 11, 'post__in' => $latest_posts , 'orderby' => 'post__in', 'order' => 'ASC'); $loop = new WP_Query($args); $do_not_duplicate[] = $post->ID; while ($loop-> have_posts()) : $loop->the_post(); $do_not_duplicate[] = $post->ID; ``` So, first loop shows 11 most recent posts in random order and pushes each post ID to `$do_not_duplicate[]`array which I use to exclude most recent posts from second loop. **Second loop** ``` $args2 = array( 'posts_per_page' =>-1, 'post__not_in' => $do_not_duplicate, 'orderby' => 'date', 'order' => 'ASC'); $loop2 = new WP_Query($args2); $num_of_posts = $loop->post_count; while ($loop2-> have_posts()) : $loop2->the_post(); ``` Having two seperate loops lets me paginate second posts list as I needed.