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
210,837
<p>Working on a categories/ front page, I would like to display an image and title for posts with an image. When there is no image, it leaves a big blank space -- looks empty, of course ... So I'd like to use bigger text for the title if there is no image. </p> <p>Has anyone found a way to do so with WordPress?</p> <p>My code is:</p> <pre><code> &lt;div class="feature-section-1"&gt; &lt;?php $posts = get_posts( "tag='tagtitle'&amp;numberposts=1" ); ?&gt; &lt;?php if( $posts ) : ?&gt; &lt;?php foreach( $posts as $post ) : setup_postdata( $post ); ?&gt; &lt;a href="&lt;?php echo get_permalink($post-&gt;ID); ?&gt;" &gt; &lt;h3&gt;&lt;?php echo $post-&gt;post_title; ?&gt;&lt;/h3&gt; &lt;div class="false-excerpt-div"&gt;&lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;?php if ( has_post_thumbnail()) : the_post_thumbnail('columner-thumb'); endif; ?&gt; &lt;/a&gt; &lt;?php endforeach; ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 210832, "author": "mrbobbybryant", "author_id": 64953, "author_profile": "https://wordpress.stackexchange.com/users/64953", "pm_score": 0, "selected": false, "text": "<p>WordPress uses the post_parent column in the database to track which posts an attachment is linked to. You can use <code>wp_get_post_parent_id</code> to find an attachment's parent post. Simply pass it the attachment ID.</p>\n" }, { "answer_id": 210834, "author": "Mateusz Hajdziony", "author_id": 15865, "author_profile": "https://wordpress.stackexchange.com/users/15865", "pm_score": 1, "selected": false, "text": "<p>It looks like the image (for which you've done a var_dump) is not attached to any post. If an image is attached to a post - the post's ID would appear as <code>'post_parent'</code>, which in this case equals <code>0</code>. This is often the case if you upload the image directly from withing media library ('Media Library' page in your WP admin) - you can still place such image into post content, use it as post thumbnails, in galleries etc., but this doesn't mean that the image is attached to any post.</p>\n\n<p>To properly attach an image to a post you have to <strong>upload</strong> it by clicking the 'Add Media' button when creating/editing the post. This is the only way that you can be certain that the image will be labelled as post's attachment.</p>\n" }, { "answer_id": 210858, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": 0, "selected": false, "text": "<p>Based on the previously answers, I managed to pull this off. Thanks for the replies stating the issue was based on wrong attachments (non-existing post_parent ID's).</p>\n\n<p>In case someone is struggling with the same issue, here is the solution I ended up with:</p>\n\n<p>The method hooks on Wordpress' <code>template_redirect</code>, check if the specific page has an parent_post, and uses two different approaches towards retriving the correct Product Post ID. It works on all \"~/?attachment_id\" and \"~/variation_product\"**.</p>\n\n<pre><code>/*\n* Redirect Attachment Pages\n*/\nadd_action( 'template_redirect', 'wpse27119_template_redirect' );\nfunction wpse27119_template_redirect() {\n global $post;\n\n /* Assign the specific post ID to local variable */\n $post_id = get_the_ID();\n\n /* If page has no attachment - no need to continue */\n if (!is_attachment() ) return false;\n\n if (empty($post)) $post = get_queried_object();\n\n /* Instantiating the product object based on currenct post ID */\n $_product = new WC_Product_Variation($post_id);\n\n /* Check if specific post got an post_parent ~ proper image-attachments and product_variation */\n if ($post-&gt;post_parent) {\n\n /* Retrieve the permalink ~ from the current product-object */\n $link = get_permalink($_product-&gt;post-&gt;ID);\n\n /* Redirect the user */\n wp_redirect( $link, '301' );\n\n exit();\n\n } else {\n\n /* Retrieve all product-pages */\n $args = array(\n 'post_type' =&gt; 'product',\n 'posts_per_page' =&gt; -1\n );\n\n /* Initialize WP_Query, and retrieve all product-pages */\n $loop = new WP_Query($args);\n\n /* Check if array contains any posts */\n if ($loop-&gt;have_posts()): while ($loop-&gt;have_posts()): $loop-&gt;the_post();\n global $product;\n\n /* Iterate through all children in product */\n foreach ($product-&gt;get_children() as $child_id) {\n\n /* Retrieve all children of the specific product */\n $variation = $product-&gt;get_child($child_id);\n\n /* Check if variation is an instance of product */\n if ($variation instanceof WC_Product_Variation) {\n\n /* Retrieve all image_ids from variation */\n $variation_image_id = $variation-&gt;get_image_id();\n\n /* Compare variation image id with the current post id ~ attachment id */\n if ($variation_image_id == $post_id) {\n\n /* Retrieve the correct product - using the post id */\n $_product = new WC_Product_Variation($post_id);\n\n /* Retrieve the permalink ~ from the current product-object */\n $link = get_permalink($_product-&gt;post-&gt;ID);\n\n /* Redirect the user */\n wp_redirect($link, '301');\n\n exit();\n\n }\n\n\n }\n\n\n }\n\n endwhile; endif; wp_reset_postdata();\n\n }\n\n}\n</code></pre>\n\n<p>I'm trying to parse the variations arguments to the redirect method. I'll update this post, if I find a solution.</p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210837", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77987/" ]
Working on a categories/ front page, I would like to display an image and title for posts with an image. When there is no image, it leaves a big blank space -- looks empty, of course ... So I'd like to use bigger text for the title if there is no image. Has anyone found a way to do so with WordPress? My code is: ``` <div class="feature-section-1"> <?php $posts = get_posts( "tag='tagtitle'&numberposts=1" ); ?> <?php if( $posts ) : ?> <?php foreach( $posts as $post ) : setup_postdata( $post ); ?> <a href="<?php echo get_permalink($post->ID); ?>" > <h3><?php echo $post->post_title; ?></h3> <div class="false-excerpt-div"><?php the_excerpt(); ?> </div> <?php if ( has_post_thumbnail()) : the_post_thumbnail('columner-thumb'); endif; ?> </a> <?php endforeach; ?> <?php endif; ?> </div> ```
It looks like the image (for which you've done a var\_dump) is not attached to any post. If an image is attached to a post - the post's ID would appear as `'post_parent'`, which in this case equals `0`. This is often the case if you upload the image directly from withing media library ('Media Library' page in your WP admin) - you can still place such image into post content, use it as post thumbnails, in galleries etc., but this doesn't mean that the image is attached to any post. To properly attach an image to a post you have to **upload** it by clicking the 'Add Media' button when creating/editing the post. This is the only way that you can be certain that the image will be labelled as post's attachment.
210,859
<p>I am using a static frontpage and a page for my blogposts. In my header.php I want to display the title of the selected page of my blogposts.</p> <p>For example:</p> <pre><code>&lt;?php if( is_home() ) echo '&lt;h1&gt;' . get_the_title() . '&lt;/h1&gt;'; ?&gt;&lt;nav&gt; ... &lt;/nav&gt; </code></pre> <p>But of course <code>get_the_title()</code> returns the first element of the displayed posts and not of the page itself.</p> <p>How can I display the title of the assigned home page?</p>
[ { "answer_id": 210867, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You can make use the queried object to return the title of the page used as blogpage</p>\n\n<p>You can use the following: (<em>Require PHP 5.4+</em>)</p>\n\n<pre><code>$title = get_queried_object()-&gt;post_title;\nvar_dump( $title );\n</code></pre>\n" }, { "answer_id": 210868, "author": "IXN", "author_id": 80031, "author_profile": "https://wordpress.stackexchange.com/users/80031", "pm_score": -1, "selected": false, "text": "<p>If it is just about the home page tile, why don't you hard code the title?</p>\n\n<pre><code>&lt;?php if ( is_home() ) : ?&gt;\n &lt;h1&gt;Your blog posts page title&lt;/h1&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 210883, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>You can get the id from options and then echo the title using that id.</p>\n\n<pre><code>// Blog Page\n$page_for_posts_id = get_option( 'page_for_posts' );\n\necho get_the_title($page_for_posts_id);\n\n// Front Page\n$frontpage_id = get_option('page_on_front');\n\necho get_the_title($frontpage_id);\n</code></pre>\n" }, { "answer_id": 242790, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>A note for those thinking of using @pieter's solution on index.php - On index.php, you'll want to check that a static Page is set to show the posts in Setting > Reading. The <code>is_home()</code> conditional does not work on index.php, so you do need to check the option is set:</p>\n\n<pre><code>&lt;?php\n// See if \"posts page\" is set in Settings &gt; Reading\n$page_for_posts = get_option( 'page_for_posts' ); \nif ($page_for_posts) { ?&gt;\n &lt;header class=\"page-header\"&gt;\n &lt;h1 class=\"page-title\" itemprop=\"headline\"&gt;\n &lt;?php echo get_queried_object()-&gt;post_title; ?&gt;\n &lt;/h1&gt;\n &lt;/header&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>This check is important because index.php is also called when \"Front Page Displays > Your latest posts\" is set. In that case, <code>get_queried_object()-&gt;post_title;</code> will return an object-not-found error.</p>\n" }, { "answer_id": 364797, "author": "ControlZ", "author_id": 97582, "author_profile": "https://wordpress.stackexchange.com/users/97582", "pm_score": 0, "selected": false, "text": "<p>This works for me</p>\n\n<pre><code>&lt;?php if ( is_home() ) : ?&gt;\n\n &lt;section class=\"hero\"&gt;\n&lt;div class=\"container\"&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-md-12 text-center\"&gt;\n\n &lt;h1&gt;news, and personal musings&lt;/h1&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>\n </p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48693/" ]
I am using a static frontpage and a page for my blogposts. In my header.php I want to display the title of the selected page of my blogposts. For example: ``` <?php if( is_home() ) echo '<h1>' . get_the_title() . '</h1>'; ?><nav> ... </nav> ``` But of course `get_the_title()` returns the first element of the displayed posts and not of the page itself. How can I display the title of the assigned home page?
You can make use the queried object to return the title of the page used as blogpage You can use the following: (*Require PHP 5.4+*) ``` $title = get_queried_object()->post_title; var_dump( $title ); ```
210,889
<p>I am unable to change the location of src attribute mentioned below</p> <pre><code>&lt;img class="srcimage" src=server-side4.php/&gt; </code></pre> <p>I want to change it to </p> <pre><code>src=scripts/server-side4.php </code></pre> <p>This is the javascript that is also included in the file</p> <pre><code>jQuery(".preview img").attr("src",base+'?'+jQuery("#realtime-form").serialize()); </code></pre> <p>but it doesn't work</p>
[ { "answer_id": 210895, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": -1, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>jQuery('img.srcimage').attr('src', 'scripts/server-side4.php');\n</code></pre>\n" }, { "answer_id": 210968, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>One problem could be that you're missing <strong>\"</strong></p>\n\n<pre><code> ***&lt;img class=\"srcimage\" src=server-side4.php/&gt;***\n</code></pre>\n\n<p>Change it to</p>\n\n<pre><code>***&lt;img class=\"srcimage\" src=\"http://example.com/your-path/server-side4.php\" /&gt;***\n</code></pre>\n\n<p>Then if that doesn't fix it, try outputting your variables to see what you're working with. Make sure that all these values are giving you the results you're expecting.</p>\n\n<pre><code>console.log(base);\nconsole.log(jQuery(\"#realtime-form\").serialize());\nconsole.log(jQuery(\".preview img\"));\n</code></pre>\n\n<p>If you don't want the src to be dynamic then remove that line of JavaScript.</p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80347/" ]
I am unable to change the location of src attribute mentioned below ``` <img class="srcimage" src=server-side4.php/> ``` I want to change it to ``` src=scripts/server-side4.php ``` This is the javascript that is also included in the file ``` jQuery(".preview img").attr("src",base+'?'+jQuery("#realtime-form").serialize()); ``` but it doesn't work
One problem could be that you're missing **"** ``` ***<img class="srcimage" src=server-side4.php/>*** ``` Change it to ``` ***<img class="srcimage" src="http://example.com/your-path/server-side4.php" />*** ``` Then if that doesn't fix it, try outputting your variables to see what you're working with. Make sure that all these values are giving you the results you're expecting. ``` console.log(base); console.log(jQuery("#realtime-form").serialize()); console.log(jQuery(".preview img")); ``` If you don't want the src to be dynamic then remove that line of JavaScript.
210,896
<p>I need to trying to get the Facebook SDK for JavaScript code inserted just after the tag.</p> <p>What's the easiest way to do this? </p>
[ { "answer_id": 210895, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": -1, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>jQuery('img.srcimage').attr('src', 'scripts/server-side4.php');\n</code></pre>\n" }, { "answer_id": 210968, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>One problem could be that you're missing <strong>\"</strong></p>\n\n<pre><code> ***&lt;img class=\"srcimage\" src=server-side4.php/&gt;***\n</code></pre>\n\n<p>Change it to</p>\n\n<pre><code>***&lt;img class=\"srcimage\" src=\"http://example.com/your-path/server-side4.php\" /&gt;***\n</code></pre>\n\n<p>Then if that doesn't fix it, try outputting your variables to see what you're working with. Make sure that all these values are giving you the results you're expecting.</p>\n\n<pre><code>console.log(base);\nconsole.log(jQuery(\"#realtime-form\").serialize());\nconsole.log(jQuery(\".preview img\"));\n</code></pre>\n\n<p>If you don't want the src to be dynamic then remove that line of JavaScript.</p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80672/" ]
I need to trying to get the Facebook SDK for JavaScript code inserted just after the tag. What's the easiest way to do this?
One problem could be that you're missing **"** ``` ***<img class="srcimage" src=server-side4.php/>*** ``` Change it to ``` ***<img class="srcimage" src="http://example.com/your-path/server-side4.php" />*** ``` Then if that doesn't fix it, try outputting your variables to see what you're working with. Make sure that all these values are giving you the results you're expecting. ``` console.log(base); console.log(jQuery("#realtime-form").serialize()); console.log(jQuery(".preview img")); ``` If you don't want the src to be dynamic then remove that line of JavaScript.
210,899
<p>I'm just getting my feet wet with nginx. In the past I've used an .htaccess file in /wp-content/uploads so if my dev or staging server doesn't have the file it redirects to the production server:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /wp-content/uploads/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) http://production.server.com/m/wp-content/uploads/$1 [L,P] &lt;/IfModule&gt; </code></pre> <p>I'm not having luck with doing this in nginx. It may be in part because this particular time my site is in a subdirectory (/m/).</p> <pre><code># Tells nginx which directory the files for this domain are located root /srv/www/example/htdocs; index index.php; # Subdirectory location settings location /m { index index.php; try_files $uri $uri/ /m/index.php?$args; location /m/wp-content/uploads { try_files $uri $uri/ @prod_svr; } } location @prod_svr { proxy_pass http://production.server.com/m/wp-content/uploads$uri; } </code></pre> <p>Any ideas would be greatly apprciated.</p>
[ { "answer_id": 215189, "author": "Ben Cole", "author_id": 32532, "author_profile": "https://wordpress.stackexchange.com/users/32532", "pm_score": 3, "selected": false, "text": "<p>You could try something like this:</p>\n\n<pre><code>server {\n root /srv/www/example/htdocs;\n index index.php;\n\n # Matches any URL containing /wp-content/uploads/ \n location ~ \"^(.*)/wp-content/uploads/(.*)$\" {\n try_files $uri @prod_serv;\n }\n\n # Will redirect requests to your production server\n location @prod_serv {\n rewrite \"^(.*)/wp-content/uploads/(.*)$\" \"http://yourdomain.com/m/wp-content/uploads/$2\" redirect;\n }\n\n # The rest of your location blocks...\n location /m {\n index index.php;\n try_files $uri $uri/ /m/index.php?$args;\n }\n}\n</code></pre>\n" }, { "answer_id": 301735, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 1, "selected": false, "text": "<p>If useful for anyone, I have a similar setup that I use in my WordPress localhost environments to handle this with some useful differences:</p>\n\n<ol>\n<li>I like to set my production environment using a variable, which allows me to quickly re-use this in multiple server blocks.</li>\n<li>I break on rewrite rather than redirect, which helps avoid issues with other requests that may match the same URL</li>\n</ol>\n\n<p>Here's a basic example:</p>\n\n<pre><code>server {\n server_name mywebsite.dev;\n set $production mywebsite.wpengine.com;\n\n # Redirect requests to /wp-content/uploads/* to production server\n location @prod_uploads {\n rewrite \"^(.*)/wp-content/uploads/(.*)$\" \"https://$production/wp-content/uploads/$2\" break;\n }\n\n # Rule for handling requests to https://mywebsite.dev/wp-content/uploads/\n location ~ \"^/wp-content/uploads/(.*)$\" {\n try_files $uri @prod_uploads;\n }\n}\n</code></pre>\n\n<p>In practice I actually include the <code>location ~ \"^/wp-content/uploads/(.*)$\"</code> rule inside of an included file called <code>wp-common.conf</code>. This allows me to run the $production switch on many different environments with the same set of common WordPress nginx config rules.</p>\n" }, { "answer_id": 408014, "author": "vanooja", "author_id": 224390, "author_profile": "https://wordpress.stackexchange.com/users/224390", "pm_score": 0, "selected": false, "text": "<p>if wordpress site is inside /var/www/html/web/wordpress then nginx config should be</p>\n<pre><code>location ~ ^/web/wordpress/index\\.php$ { }\n\nlocation /web/wordpress/ {\n include snippets/fastcgi-php.conf;\n fastcgi_pass unix:/run/php/php7.2-fpm.sock;\nif (!-e $request_filename){\n rewrite ^/web/wordpress/(.*)$ /web/wordpress/index.php break;\n}\n}\n</code></pre>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210899", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15555/" ]
I'm just getting my feet wet with nginx. In the past I've used an .htaccess file in /wp-content/uploads so if my dev or staging server doesn't have the file it redirects to the production server: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wp-content/uploads/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) http://production.server.com/m/wp-content/uploads/$1 [L,P] </IfModule> ``` I'm not having luck with doing this in nginx. It may be in part because this particular time my site is in a subdirectory (/m/). ``` # Tells nginx which directory the files for this domain are located root /srv/www/example/htdocs; index index.php; # Subdirectory location settings location /m { index index.php; try_files $uri $uri/ /m/index.php?$args; location /m/wp-content/uploads { try_files $uri $uri/ @prod_svr; } } location @prod_svr { proxy_pass http://production.server.com/m/wp-content/uploads$uri; } ``` Any ideas would be greatly apprciated.
You could try something like this: ``` server { root /srv/www/example/htdocs; index index.php; # Matches any URL containing /wp-content/uploads/ location ~ "^(.*)/wp-content/uploads/(.*)$" { try_files $uri @prod_serv; } # Will redirect requests to your production server location @prod_serv { rewrite "^(.*)/wp-content/uploads/(.*)$" "http://yourdomain.com/m/wp-content/uploads/$2" redirect; } # The rest of your location blocks... location /m { index index.php; try_files $uri $uri/ /m/index.php?$args; } } ```
210,901
<p>The hook </p> <pre><code> profile_update </code></pre> <p>gets fired in case the user updates his profile, that is also when he reset the first time his password after registration and when he register.</p> <p>How do I distinguish between the three cases?</p> <p>EDIT: There are, at least, 3 cases to distinguish, in which that hook is called.</p> <ol> <li>user's first registration step <ul> <li>The user fills email and username and save (profile_update gets called here), being presented the request to check email for the verification process</li> </ul></li> <li>user reset password after registration <ul> <li>The user checks his mail, follow the suggested url, reset the password and save (profile_update gets called here)</li> </ul></li> <li>user updates his profile <ul> <li>The user log in and update some data within his profile and save (profile_update gets called here)</li> </ul></li> </ol> <p>I think it is possible to distinguish case 3, verifying if someone his currently logged in calling</p> <pre><code>is_user_logged_in() </code></pre> <p>Still there is the problem to distinguish case 2 from 1. As s_ha_dum points out there is the possibility to check the user_activation_key. If the key is created not at the time 1 but a time 2, the 3 cases are distinguishable. (Even if I personally believe the hook covers too much cases and shouldn't).</p>
[ { "answer_id": 211055, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>Technically, you can't. That filter doesn't pass in any data that will specifically allow you to distinguish between those two cases. </p>\n\n<pre><code>2086 /**\n2087 * Fires immediately after an existing user is updated.\n2088 *\n2089 * @since 2.0.0\n2090 *\n2091 * @param int $user_id User ID.\n2092 * @param object $old_user_data Object containing user's data prior to update.\n2093 */\n2094 do_action( 'profile_update', $user_id, $old_user_data );\n</code></pre>\n\n<p>You notice that the filter does pass through <code>$old_user_data</code> so you could check the <code>user_activation_key</code> in <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_users\" rel=\"nofollow\">the <code>*_users</code> table</a>. That should get you close, however, I think that that field is populated when a user resets the password, and not just when the account is created. </p>\n\n<p>To be absolutely sure you'd probably need to <a href=\"https://codex.wordpress.org/Function_Reference/add_user_meta\" rel=\"nofollow\">set a user meta value</a> on first login then check that for subsequent logins.</p>\n" }, { "answer_id": 211313, "author": "Sasha Grievus", "author_id": 71652, "author_profile": "https://wordpress.stackexchange.com/users/71652", "pm_score": 1, "selected": false, "text": "<p>In order, to distinguish case 1 and 3 i actually used:</p>\n\n<pre><code>add_action( 'profile_update', 'when_profile_update', 10, 2 );\nfunction when_profile_update( $user_id, $old_user_data ) {\n if (is_user_logged_in()) { \n // Updating profile info when logged in \n }else{ \n if (empty($old_user_data-&gt;user_activation_key)) { \n // Registering\n }\n }\n}\n</code></pre>\n\n<p>At this time, in my site profile_update is not fired for password reset, so case 2 is not happening. </p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210901", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71652/" ]
The hook ``` profile_update ``` gets fired in case the user updates his profile, that is also when he reset the first time his password after registration and when he register. How do I distinguish between the three cases? EDIT: There are, at least, 3 cases to distinguish, in which that hook is called. 1. user's first registration step * The user fills email and username and save (profile\_update gets called here), being presented the request to check email for the verification process 2. user reset password after registration * The user checks his mail, follow the suggested url, reset the password and save (profile\_update gets called here) 3. user updates his profile * The user log in and update some data within his profile and save (profile\_update gets called here) I think it is possible to distinguish case 3, verifying if someone his currently logged in calling ``` is_user_logged_in() ``` Still there is the problem to distinguish case 2 from 1. As s\_ha\_dum points out there is the possibility to check the user\_activation\_key. If the key is created not at the time 1 but a time 2, the 3 cases are distinguishable. (Even if I personally believe the hook covers too much cases and shouldn't).
Technically, you can't. That filter doesn't pass in any data that will specifically allow you to distinguish between those two cases. ``` 2086 /** 2087 * Fires immediately after an existing user is updated. 2088 * 2089 * @since 2.0.0 2090 * 2091 * @param int $user_id User ID. 2092 * @param object $old_user_data Object containing user's data prior to update. 2093 */ 2094 do_action( 'profile_update', $user_id, $old_user_data ); ``` You notice that the filter does pass through `$old_user_data` so you could check the `user_activation_key` in [the `*_users` table](https://codex.wordpress.org/Database_Description#Table:_wp_users). That should get you close, however, I think that that field is populated when a user resets the password, and not just when the account is created. To be absolutely sure you'd probably need to [set a user meta value](https://codex.wordpress.org/Function_Reference/add_user_meta) on first login then check that for subsequent logins.
210,904
<p>I'm using <code>wp_dropdown_pages()</code> but would like to number the options returned for the user. So instead of something like...</p> <pre><code>&lt;option value='http://someurl'&gt;item one&lt;/option&gt; &lt;option value='http://someurl'&gt;item two&lt;/option&gt; &lt;option value='http://someurl'&gt;item three&lt;/option&gt; </code></pre> <p>I end up with:</p> <pre><code>&lt;option value='http://someurl'&gt;1. page one&lt;/option&gt; &lt;option value='http://someurl'&gt;2. page two&lt;/option&gt; &lt;option value='http://someurl'&gt;3. page three&lt;/option&gt; </code></pre> <p>How would one go about doing that with the output of <code>wp_dropdown_pages()</code>?</p>
[ { "answer_id": 210906, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>To change</p>\n\n<pre><code>&lt;option value='http://someurl'&gt;item one&lt;/option&gt;\n&lt;option value='http://someurl'&gt;item two&lt;/option&gt;\n&lt;option value='http://someurl'&gt;item three&lt;/option&gt;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>&lt;option value='http://someurl'&gt;1. item one&lt;/option&gt;\n&lt;option value='http://someurl'&gt;2. item two&lt;/option&gt;\n&lt;option value='http://someurl'&gt;3. item three&lt;/option&gt;\n</code></pre>\n\n<p>we can utilize the <code>list_pages</code> filter from the <code>Walker_PageDropdown::start_el()</code> method.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>// Add filter\nadd_filter( 'list_pages', 'wpse_itemize', 10, 2 );\n\n// Display dropdown\nwp_dropdown_pages();\n\n// Remove filter\nremove_filter( 'list_pages', 'wpse_itemize' );\n</code></pre>\n\n<p>where the callback is defined as:</p>\n\n<pre><code>function wpse_itemize( $title, $page )\n{\n static $nr = 1; \n return sprintf( '%d. %s', $nr++, $title );\n}\n</code></pre>\n\n<h2>Update</h2>\n\n<p>For the custom <code>wp_dropdown_posts()</code> function you could try:</p>\n\n<pre><code>if( function_exists( 'wp_dropdown_posts' ) )\n{\n // Add filter\n add_filter( 'esc_html', 'wpse_itemize' );\n\n // Display dropdown\n wp_dropdown_posts();\n\n // Remove filter\n remove_filter( 'esc_html', 'wpse_itemize' );\n}\n</code></pre>\n\n<p>where the callback is defined as:</p>\n\n<pre><code>function wpse_itemize( $safe_text )\n{\n static $nr = 1; \n return sprintf( '%d. %s', $nr++, $safe_text );\n}\n</code></pre>\n\n<h2>Note</h2>\n\n<p>I was just curious how we could add post post type support to <code>wp_dropdown_pages()</code> and got it through with this hack:</p>\n\n<pre><code>global $wp_post_types;\n$wp_post_types['post']-&gt;hierarchical = true;\nwp_dropdown_pages( [ 'post_type' =&gt; 'post' ] );\n$wp_post_types['post']-&gt;hierarchical = false;\n</code></pre>\n\n<p>but I <strong>absolutely don't recommend</strong> this, it was just a test to see if I could find \"any\" theoretical workaround.</p>\n" }, { "answer_id": 247826, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 0, "selected": false, "text": "<p>Just an FYI I created a function to add <code>wp_dropdown_posts()</code>:</p>\n\n<p><a href=\"https://github.com/tripflex/wp_dropdown_posts\" rel=\"nofollow noreferrer\">https://github.com/tripflex/wp_dropdown_posts</a></p>\n" } ]
2015/12/05
[ "https://wordpress.stackexchange.com/questions/210904", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7162/" ]
I'm using `wp_dropdown_pages()` but would like to number the options returned for the user. So instead of something like... ``` <option value='http://someurl'>item one</option> <option value='http://someurl'>item two</option> <option value='http://someurl'>item three</option> ``` I end up with: ``` <option value='http://someurl'>1. page one</option> <option value='http://someurl'>2. page two</option> <option value='http://someurl'>3. page three</option> ``` How would one go about doing that with the output of `wp_dropdown_pages()`?
To change ``` <option value='http://someurl'>item one</option> <option value='http://someurl'>item two</option> <option value='http://someurl'>item three</option> ``` to ``` <option value='http://someurl'>1. item one</option> <option value='http://someurl'>2. item two</option> <option value='http://someurl'>3. item three</option> ``` we can utilize the `list_pages` filter from the `Walker_PageDropdown::start_el()` method. Here's an example: ``` // Add filter add_filter( 'list_pages', 'wpse_itemize', 10, 2 ); // Display dropdown wp_dropdown_pages(); // Remove filter remove_filter( 'list_pages', 'wpse_itemize' ); ``` where the callback is defined as: ``` function wpse_itemize( $title, $page ) { static $nr = 1; return sprintf( '%d. %s', $nr++, $title ); } ``` Update ------ For the custom `wp_dropdown_posts()` function you could try: ``` if( function_exists( 'wp_dropdown_posts' ) ) { // Add filter add_filter( 'esc_html', 'wpse_itemize' ); // Display dropdown wp_dropdown_posts(); // Remove filter remove_filter( 'esc_html', 'wpse_itemize' ); } ``` where the callback is defined as: ``` function wpse_itemize( $safe_text ) { static $nr = 1; return sprintf( '%d. %s', $nr++, $safe_text ); } ``` Note ---- I was just curious how we could add post post type support to `wp_dropdown_pages()` and got it through with this hack: ``` global $wp_post_types; $wp_post_types['post']->hierarchical = true; wp_dropdown_pages( [ 'post_type' => 'post' ] ); $wp_post_types['post']->hierarchical = false; ``` but I **absolutely don't recommend** this, it was just a test to see if I could find "any" theoretical workaround.
210,929
<p>How can I remove the link from the page title in my WordPress theme? </p> <p>Here's the link to my test <a href="http://leon-aver.com/" rel="nofollow">site</a> and below is the code responsible for that:</p> <pre><code>&lt;h1 class='post-title &lt;?php echo $titleClass; ?&gt;'&gt; &lt;a href="&lt;?php echo get_permalink() ?&gt;" rel="bookmark" title="&lt;?php _e('Permanent Link:','avia_framework')?&gt; &lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h1&gt; </code></pre> <p>When I removed <code>&lt;a href=""&gt; &lt;/a&gt;</code>, it removed the complete title and nothing is visible. </p> <p><em>Edit:</em> I want the title to remain on the page, but not linked to the post.</p>
[ { "answer_id": 210932, "author": "Craig Pearson", "author_id": 17295, "author_profile": "https://wordpress.stackexchange.com/users/17295", "pm_score": 1, "selected": false, "text": "<p>Perhaps when you removed your a tag you also remove the nested <code>the_title();</code> function?</p>\n\n<p><code>the_title();</code> is the Wordpress function which spits out the plain text post/page title so having that in your h1 like below should get you the results you're expecting. Of course there may also be some CSS which is affected due to the removal of your <code>&lt;a&gt;</code> tag</p>\n\n<pre><code>&lt;h1 class='post-title &lt;?php echo $titleClass; ?&gt;'&gt;\n &lt;?php the_title(); ?&gt;\n&lt;/h1&gt;\n</code></pre>\n" }, { "answer_id": 292011, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p>remove a <code>&lt;a&gt;</code> teg only use <code>&lt;?php the_title(); ?&gt;</code> in h1 teg \nanother \nbelow code add in function.php</p>\n\n<pre><code>add_action('wp_head' , 'remove_post_list_title_links');\nfunction remove_post_list_title_links() {\n ?&gt;\n &lt;script id=\"remove-links-in-title\" type=\"text/javascript\"&gt;\n jQuery(document).ready(function($) {\n $('.entry-title').each(function() {\n var $title_link = $('a[rel=\"bookmark\"]' , $(this)),\n $title_text = $title_link.text();\n $title_link.remove();\n $(this).prepend($title_text);\n });\n });\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n" } ]
2015/12/06
[ "https://wordpress.stackexchange.com/questions/210929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84831/" ]
How can I remove the link from the page title in my WordPress theme? Here's the link to my test [site](http://leon-aver.com/) and below is the code responsible for that: ``` <h1 class='post-title <?php echo $titleClass; ?>'> <a href="<?php echo get_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link:','avia_framework')?> <?php the_title(); ?>"><?php the_title(); ?></a> </h1> ``` When I removed `<a href=""> </a>`, it removed the complete title and nothing is visible. *Edit:* I want the title to remain on the page, but not linked to the post.
Perhaps when you removed your a tag you also remove the nested `the_title();` function? `the_title();` is the Wordpress function which spits out the plain text post/page title so having that in your h1 like below should get you the results you're expecting. Of course there may also be some CSS which is affected due to the removal of your `<a>` tag ``` <h1 class='post-title <?php echo $titleClass; ?>'> <?php the_title(); ?> </h1> ```
210,933
<p>i have add 4 custom fields in the checkout page (in functions.php )</p> <p>Now i show the value in the Order page with </p> <pre><code>get_post_meta( $order-&gt;id, 'My Field', true ) </code></pre> <p>I need that the customer can edit the Value on the order Page (front-end) if the order status is processing.</p> <p>I dont know who can i make this.</p> <p>I have try to use the acf Plugin (<a href="http://www.advancedcustomfields.com/" rel="nofollow">ACF Plugin</a>)</p> <p>for use this on the checkout page. But i found nothing and the support of acf dont anwser to this topic.</p> <p>The next way was that i try to load the custom filed value as "default_value" of the acf input Plugin. But it dont work.</p> <pre><code>function my_acf_load_field( $field ) { //$acfstrasse = get_field('field_name', $post_id); $acfstrasse = get_post_meta( $order-&gt;id, 'Strasse', true ); $field['default_value'] = $acfstrasse; return $field; } add_filter('acf/load_field/name=field_name', 'my_acf_load_field'); </code></pre> <p>I hope you know a way that the customer can edit the value of the custom field on the order page (front-end)</p> <p>Thanks !!</p> <p>Sorry for my english. (German is my language) </p>
[ { "answer_id": 211074, "author": "kreativcube", "author_id": 84829, "author_profile": "https://wordpress.stackexchange.com/users/84829", "pm_score": 1, "selected": true, "text": "<p>I found a solution.</p>\n\n<p>i have use this code on my order-details.php Page</p>\n\n<pre><code> &lt;?php\n global $post;\n\n $post = $order_id;\n\n if ( isset( $_POST['submit'] ) )\n {\n echo 'Update nicht';\n } else if ( ! empty( $_POST['frontstrasse'] ) ) {\n update_post_meta( $order_id, 'Strasse', sanitize_text_field( $_POST['frontstrasse'] ) );\n update_post_meta( $order_id, 'Haus-Nr', sanitize_text_field( $_POST['fronthausnr'] ) );\n\n\n}\n$istrasse = get_post_meta($order-&gt;id, 'Strasse', true );\n$ihausnr = get_post_meta($order-&gt;id, 'Haus-Nr', true );\n\n ?&gt;\n\n &lt;form method=\"post\" action=\"\"&gt;\n&lt;label&gt;Strasse&lt;/label&gt;&lt;input type='text' name='frontstrasse' value='&lt;?php echo $istrasse ?&gt;' /&gt;\n&lt;label&gt;Haus-Nr&lt;/label&gt;&lt;input type='text' name='fronthausnr' value='&lt;?php echo $ihausnr ?&gt;' /&gt;\n&lt;input type='submit' value='save' name='frontsubmit' /&gt;\n &lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 359568, "author": "figl", "author_id": 183414, "author_profile": "https://wordpress.stackexchange.com/users/183414", "pm_score": 1, "selected": false, "text": "<p>you don't have to edit the <code>order-details.php</code> page the <code>woocommerce_order_details_after_order_table</code> action will achieve the same results.</p>\n\n<pre><code>add_action( 'woocommerce_order_details_after_order_table',\n 'namespace\\custom_field_display_cust_order_meta', 10, 1 );\n\nfunction custom_field_display_cust_order_meta( $order ) {\n echo '&lt;form [whatever]&gt;';\n /* translators: whatever */\n echo '&lt;p&gt;' . sprintf( __( '&lt;strong&gt;Property 1:&lt;/strong&gt; %1$s (%2$s)' ), \n '&lt;input [whatever]&gt;'\n . get_post_meta( $order-&gt;get_order_number(),\n 'property 1.1', true )\n . '&lt;/input&gt;',\n '&lt;input [whatever]&gt;'\n . get_post_meta( $order-&gt;get_order_number(),\n 'property 1.2', true )\n . '&lt;/input&gt;' )\n . '&lt;/p&gt;';\n echo '[whatever]';\n echo '&lt;/form&gt;';\n}\n</code></pre>\n" } ]
2015/12/06
[ "https://wordpress.stackexchange.com/questions/210933", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84829/" ]
i have add 4 custom fields in the checkout page (in functions.php ) Now i show the value in the Order page with ``` get_post_meta( $order->id, 'My Field', true ) ``` I need that the customer can edit the Value on the order Page (front-end) if the order status is processing. I dont know who can i make this. I have try to use the acf Plugin ([ACF Plugin](http://www.advancedcustomfields.com/)) for use this on the checkout page. But i found nothing and the support of acf dont anwser to this topic. The next way was that i try to load the custom filed value as "default\_value" of the acf input Plugin. But it dont work. ``` function my_acf_load_field( $field ) { //$acfstrasse = get_field('field_name', $post_id); $acfstrasse = get_post_meta( $order->id, 'Strasse', true ); $field['default_value'] = $acfstrasse; return $field; } add_filter('acf/load_field/name=field_name', 'my_acf_load_field'); ``` I hope you know a way that the customer can edit the value of the custom field on the order page (front-end) Thanks !! Sorry for my english. (German is my language)
I found a solution. i have use this code on my order-details.php Page ``` <?php global $post; $post = $order_id; if ( isset( $_POST['submit'] ) ) { echo 'Update nicht'; } else if ( ! empty( $_POST['frontstrasse'] ) ) { update_post_meta( $order_id, 'Strasse', sanitize_text_field( $_POST['frontstrasse'] ) ); update_post_meta( $order_id, 'Haus-Nr', sanitize_text_field( $_POST['fronthausnr'] ) ); } $istrasse = get_post_meta($order->id, 'Strasse', true ); $ihausnr = get_post_meta($order->id, 'Haus-Nr', true ); ?> <form method="post" action=""> <label>Strasse</label><input type='text' name='frontstrasse' value='<?php echo $istrasse ?>' /> <label>Haus-Nr</label><input type='text' name='fronthausnr' value='<?php echo $ihausnr ?>' /> <input type='submit' value='save' name='frontsubmit' /> </form> ```
210,937
<p>One can customize single comment markup using the <code>callback</code> argument in <code>wp_list_comments</code> like this:</p> <pre><code>$args = array( 'callback' =&gt; 'my_callback', 'avatar_size' =&gt; 48, 'type' =&gt; 'comment' ); wp_list_comments( $args ); </code></pre> <p>The question is, how to pass arguments to that <code>my_callback</code> function? Already it gets three:</p> <pre><code>function my_callback( $comment, $args, $depth ) </code></pre> <p>But I need to add my own 4th argument</p>
[ { "answer_id": 210939, "author": "Peyman Mohamadpour", "author_id": 75020, "author_profile": "https://wordpress.stackexchange.com/users/75020", "pm_score": 3, "selected": true, "text": "<p>Finally I figured it out. you may simply add your arguments to the <code>wp_list_comments</code> as associative <code>key</code> => <code>value</code> pairs like this:</p>\n\n<pre><code>$args = array( 'callback' =&gt; 'my_callback', 'avatar_size' =&gt; 48, 'type' =&gt; 'comment', 'arg1' =&gt; $arg1 );\nwp_list_comments( $args );\n</code></pre>\n\n<p>and then in your <code>my_callback</code> you have:</p>\n\n<pre><code>function my_callback( $comment, $args, $depth )\n</code></pre>\n\n<p>where you have access to <code>$arg1</code>;</p>\n" }, { "answer_id": 403893, "author": "x_magnet_x", "author_id": 220438, "author_profile": "https://wordpress.stackexchange.com/users/220438", "pm_score": 0, "selected": false, "text": "<p>You may use the <code>use</code> in function:</p>\n<pre><code>function my_callback( $comment, $args, $depth ) use ( $my_arg1, $my_arg2, ... )\n</code></pre>\n" } ]
2015/12/06
[ "https://wordpress.stackexchange.com/questions/210937", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75020/" ]
One can customize single comment markup using the `callback` argument in `wp_list_comments` like this: ``` $args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment' ); wp_list_comments( $args ); ``` The question is, how to pass arguments to that `my_callback` function? Already it gets three: ``` function my_callback( $comment, $args, $depth ) ``` But I need to add my own 4th argument
Finally I figured it out. you may simply add your arguments to the `wp_list_comments` as associative `key` => `value` pairs like this: ``` $args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment', 'arg1' => $arg1 ); wp_list_comments( $args ); ``` and then in your `my_callback` you have: ``` function my_callback( $comment, $args, $depth ) ``` where you have access to `$arg1`;
210,947
<p>I have this permalinks settings: <code>/%postname%/</code></p> <p>I have a custom taxonomy <code>issue</code>.</p> <p>I want replace all my taxonomy links <code>(site.com/category/wordpress)</code> to <code>(site.com/category/wordpress/issue/any-child)</code>. Like tags.</p> <p>Maybe this picture help</p> <p><a href="https://i.stack.imgur.com/0xeTC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0xeTC.png" alt="enter image description here"></a></p>
[ { "answer_id": 210939, "author": "Peyman Mohamadpour", "author_id": 75020, "author_profile": "https://wordpress.stackexchange.com/users/75020", "pm_score": 3, "selected": true, "text": "<p>Finally I figured it out. you may simply add your arguments to the <code>wp_list_comments</code> as associative <code>key</code> => <code>value</code> pairs like this:</p>\n\n<pre><code>$args = array( 'callback' =&gt; 'my_callback', 'avatar_size' =&gt; 48, 'type' =&gt; 'comment', 'arg1' =&gt; $arg1 );\nwp_list_comments( $args );\n</code></pre>\n\n<p>and then in your <code>my_callback</code> you have:</p>\n\n<pre><code>function my_callback( $comment, $args, $depth )\n</code></pre>\n\n<p>where you have access to <code>$arg1</code>;</p>\n" }, { "answer_id": 403893, "author": "x_magnet_x", "author_id": 220438, "author_profile": "https://wordpress.stackexchange.com/users/220438", "pm_score": 0, "selected": false, "text": "<p>You may use the <code>use</code> in function:</p>\n<pre><code>function my_callback( $comment, $args, $depth ) use ( $my_arg1, $my_arg2, ... )\n</code></pre>\n" } ]
2015/12/06
[ "https://wordpress.stackexchange.com/questions/210947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84842/" ]
I have this permalinks settings: `/%postname%/` I have a custom taxonomy `issue`. I want replace all my taxonomy links `(site.com/category/wordpress)` to `(site.com/category/wordpress/issue/any-child)`. Like tags. Maybe this picture help [![enter image description here](https://i.stack.imgur.com/0xeTC.png)](https://i.stack.imgur.com/0xeTC.png)
Finally I figured it out. you may simply add your arguments to the `wp_list_comments` as associative `key` => `value` pairs like this: ``` $args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment', 'arg1' => $arg1 ); wp_list_comments( $args ); ``` and then in your `my_callback` you have: ``` function my_callback( $comment, $args, $depth ) ``` where you have access to `$arg1`;
210,975
<p>I have some code in my loop that will determine the term in my custom taxonomy, if it's a specific term, it will output a specific image. </p> <pre><code>&lt;?php if( has_term('10', 'review-score' ) ) { ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;img src="&lt;?php echo get_stylesheet_directory_uri(); ?&gt; /images/review-scores-thumbs/10.jpeg" /&gt; &lt;/a&gt; </code></pre> <p>It works exactly how I want it to work, but after it, I have an else if for if the term is 9.5, 9, 8.5 ... 1. That's a lot of else ifs, and I'm not sure it will be good for my site's speed. To fix this, I was thinking of getting the term of the current post (I'm doing this inside a custom archive page loop), then doing something like this. </p> <pre><code>&lt;?php $term = get_term($post-&gt;ID, 'review'score'); ?&gt; &lt;img src="&lt;?php echo get_stylesheet_directory_uri(); ?&gt; /images/review-scores-thumbs/$term.jpeg" /&gt; &lt;/a&gt; </code></pre> <p>This would work given my jpegs are all named like that, but I'm having two problems. get_term is weird. I thought it would return only one term, but when I do this. </p> <pre><code>&lt;?php $term = get_term($post-&gt;ID, 'review-score'); ?&gt; &lt;?php if ($term = '10') { ?&gt; It worked &lt;?php } ?&gt; </code></pre> <p>It displays it worked everywere even when the term is 9 or 8 for that specific thing. </p> <p>Then in addition to this, it seems I cannot do </p> <pre><code>&lt;?php $term = get_term($post-&gt;ID, 'review-score'); ?&gt; &lt;img src="&lt;?php echo get_stylesheet_directory_uri(); ?&gt; /images/review-scores-thumbs/$term.jpeg" /&gt; &lt;/a&gt; </code></pre> <p>Because $term is in the quotes. </p> <p>So, is what I'm doing possible? Is it even worth it (i.e., is using all those else ifs that bad)? And how does get_term work?</p>
[ { "answer_id": 210939, "author": "Peyman Mohamadpour", "author_id": 75020, "author_profile": "https://wordpress.stackexchange.com/users/75020", "pm_score": 3, "selected": true, "text": "<p>Finally I figured it out. you may simply add your arguments to the <code>wp_list_comments</code> as associative <code>key</code> => <code>value</code> pairs like this:</p>\n\n<pre><code>$args = array( 'callback' =&gt; 'my_callback', 'avatar_size' =&gt; 48, 'type' =&gt; 'comment', 'arg1' =&gt; $arg1 );\nwp_list_comments( $args );\n</code></pre>\n\n<p>and then in your <code>my_callback</code> you have:</p>\n\n<pre><code>function my_callback( $comment, $args, $depth )\n</code></pre>\n\n<p>where you have access to <code>$arg1</code>;</p>\n" }, { "answer_id": 403893, "author": "x_magnet_x", "author_id": 220438, "author_profile": "https://wordpress.stackexchange.com/users/220438", "pm_score": 0, "selected": false, "text": "<p>You may use the <code>use</code> in function:</p>\n<pre><code>function my_callback( $comment, $args, $depth ) use ( $my_arg1, $my_arg2, ... )\n</code></pre>\n" } ]
2015/12/06
[ "https://wordpress.stackexchange.com/questions/210975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84582/" ]
I have some code in my loop that will determine the term in my custom taxonomy, if it's a specific term, it will output a specific image. ``` <?php if( has_term('10', 'review-score' ) ) { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <img src="<?php echo get_stylesheet_directory_uri(); ?> /images/review-scores-thumbs/10.jpeg" /> </a> ``` It works exactly how I want it to work, but after it, I have an else if for if the term is 9.5, 9, 8.5 ... 1. That's a lot of else ifs, and I'm not sure it will be good for my site's speed. To fix this, I was thinking of getting the term of the current post (I'm doing this inside a custom archive page loop), then doing something like this. ``` <?php $term = get_term($post->ID, 'review'score'); ?> <img src="<?php echo get_stylesheet_directory_uri(); ?> /images/review-scores-thumbs/$term.jpeg" /> </a> ``` This would work given my jpegs are all named like that, but I'm having two problems. get\_term is weird. I thought it would return only one term, but when I do this. ``` <?php $term = get_term($post->ID, 'review-score'); ?> <?php if ($term = '10') { ?> It worked <?php } ?> ``` It displays it worked everywere even when the term is 9 or 8 for that specific thing. Then in addition to this, it seems I cannot do ``` <?php $term = get_term($post->ID, 'review-score'); ?> <img src="<?php echo get_stylesheet_directory_uri(); ?> /images/review-scores-thumbs/$term.jpeg" /> </a> ``` Because $term is in the quotes. So, is what I'm doing possible? Is it even worth it (i.e., is using all those else ifs that bad)? And how does get\_term work?
Finally I figured it out. you may simply add your arguments to the `wp_list_comments` as associative `key` => `value` pairs like this: ``` $args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment', 'arg1' => $arg1 ); wp_list_comments( $args ); ``` and then in your `my_callback` you have: ``` function my_callback( $comment, $args, $depth ) ``` where you have access to `$arg1`;
210,993
<p>I have a problem with some page URLs. The page URL structure is like this:</p> <pre><code>www.example.com/wp/custom-taxonomy/somepagename/?token=12345 </code></pre> <p>I want that when I access the URL above to redirect me to:</p> <pre><code>www.example.com/wp/custom-taxonomy/somepagename/ </code></pre> <p>In <code>/wp/</code> is WordPress installed. I tried this in <code>.htaccess</code>:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /wp/ RewriteCond %{query_string} ^token=12345 RewriteRule (.*) /$1? [R=301,L] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wp/index.php [L] &lt;/IfModule&gt; </code></pre> <p>but it redirects me to:</p> <pre><code>www.example.com/custom-taxonomy/somepagename </code></pre> <p>Any ideas?</p> <p><strong>Later edit</strong>:</p> <p><code>/wp/</code> - the folder where Wordpress is installed;</p> <p><code>/custom-taxonomy/</code> - a custom taxonomy, like <code>/partners/</code> where I enter all my partners.</p> <p><code>/somepagename</code> - a dynamic page, like <code>/xyz-ltd</code>, <code>/abcd...</code> dynamic pages created for the custom taxonomy.</p> <p>I can not put a rule for every page, would need a general rule to remove the query string.</p>
[ { "answer_id": 211001, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">add_rewrite_rule</a> in WordPress to capture the query args or <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add_rewrite_endpoint</a>. If you really just want to redirect based on certain rules then <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow\">template_redirect</a> can be a good place to use a header redirect.</p>\n" }, { "answer_id": 211010, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": -1, "selected": false, "text": "<p>Use this in your .htaccess-</p>\n\n<pre><code>Redirect 301 /slug/somepagename/?token=12345 http://www.example.com/wp/slug/somepagename/\n</code></pre>\n" }, { "answer_id": 211012, "author": "IXN", "author_id": 80031, "author_profile": "https://wordpress.stackexchange.com/users/80031", "pm_score": 0, "selected": false, "text": "<p>I think the problem is in your permalink configuration.\nIt seems that WP redirects </p>\n\n<pre><code>www.example.com/slug/somepagename/\n</code></pre>\n\n<p>to</p>\n\n<pre><code>www.example.com/slug/somepagename\n</code></pre>\n\n<p>anyway.\nIf you solve this, probably by setting your permalinks in wp admin, then the redirect will work.</p>\n\n<p>It's funny but I'm doing the exact same thing right now for my site, redirecting mobile queries (?m=1) to the main pages. So I can confirm that your code is correct. The only thing different I do is add $ at the end of the query, like <code>^token=12345$</code>, but I don't think this makes a difference.</p>\n" }, { "answer_id": 395206, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<blockquote>\n<pre><code>RewriteBase /wp/\nRewriteCond %{query_string} ^token=12345\nRewriteRule (.*) /$1? [R=301,L]\n</code></pre>\n<p>but it redirects me to:</p>\n<pre><code>www.example.com/custom-taxonomy/somepagename\n</code></pre>\n</blockquote>\n<p>There are two issues here with the redirected URL:</p>\n<ol>\n<li><p>The <code>/wp</code> prefix is missing.</p>\n</li>\n<li><p>The trailing slash is missing.</p>\n</li>\n</ol>\n<p>To fix <strong>#1</strong> you can either:</p>\n<ul>\n<li><p>Hardcode the <code>/wp</code> prefix in the substitution string (as is done in the last <code>RewriteRule</code> - part of the WordPress front-controller - although that is arguably incorrect, see the <em>next point</em>). For example:</p>\n<pre><code>RewriteRule (.*) /wp/$1? [R=301,L]\n</code></pre>\n</li>\n<li><p>Since <code>RewriteBase /wp</code> is already defined, you can simply remove the slash prefix on the substitution string (to make it a <em>relative</em> path substitution). ie. <code>$1?</code>. mod_rewrite then prepends the <code>/wp</code> path segment to the resulting <em>substitution</em>. For example:</p>\n<pre><code>RewriteRule (.*) $1? [R=301,L]\n</code></pre>\n<p><em>Aside:</em> This is really how the last <code>RewriteRule</code> should be written. ie. <code>RewriteRule . index.php [L]</code> (since that's the whole point of having <code>RewriteBase /wp</code> defined in the first place).</p>\n</li>\n<li><p>Change the rule to use the <code>REQUEST_URI</code> server variable instead of a backreference (<code>$1</code>). The <code>REQUEST_URI</code> contains the full root-relative URL-path, so already includes the <code>/wp</code> prefix. This is perhaps the preferred method (unless there are additional requirements) since it will work <em>anywhere</em> and is not dependent on the setting of <code>RewriteBase</code>. For example:</p>\n<pre><code>RewriteRule ^ %{REQUEST_URI}? [R=301,L]\n</code></pre>\n</li>\n</ul>\n<p>However, this does not resolve <strong>#2</strong> - the missing trailing slash. This is not caused by this directive - something else is removing the trailing slash (if it is present on the initial request). A possible reason for this is the <em>permalink</em> structure as suggested in <a href=\"https://wordpress.stackexchange.com/a/211012/8259\">@IXN's answer</a>. Providing the trailing slash is part of the initial request (as indicated in the question) then this directive specifically preserves it. If the trailing slash is missing from the initial request then the trailing slash will also be missing from the redirected response (<em>see below</em> on how to fix this). In order to debug this further, you should check for any additional redirects in the network traffic.</p>\n<p><strong>Additional notes:</strong></p>\n<ul>\n<li><p>You should avoid editing the code within the <code># BEGIN WordPress</code> section, since WordPress will try to maintain this and overwrite your edits. This redirect should go near the top of the <code>.htaccess</code> file, before the <code># BEGIN WordPress</code> section.</p>\n</li>\n<li><p><code>^token=12345</code> - Include an and-of-string anchor (<code>$</code>) on the <em>CondPattern</em> to match this query string string only. As it stands, this matches any query string that simply <em>starts</em> with <code>token=12345</code>.</p>\n</li>\n<li><p>On Apache 2.4 use the <code>QSD</code> (Query String Discard) flag instead of appending an empty query string (a lone <code>?</code>) on the <em>substitution</em> string.</p>\n</li>\n<li><p>As it currently stands, this rule matches <em>any</em> URL-path. Including all static resources (images, CSS, JS) etc. It doesn't specifically match <code>/wp/&lt;custom-taxonomy&gt;/&lt;somepagename&gt;/</code> - the URL format as stated. Ideally, your rule should be as specific as possible, to match only the targetted URLs, so as to avoid unnecessary redirects and additional rule processing. For example:</p>\n<pre><code>RewriteRule ^[\\w-]+/[\\w-]+/$ %{REQUEST_URI} [QSD,R=301,L]\n</code></pre>\n<p>The <code>\\w</code> shorthand character class matches the characters <code>a-z</code>, <code>A-Z</code>, <code>0-9</code> and <code>_</code> (underscore) so naturally avoids matching static resources that typically have a file extension prefixed with a <em>dot</em>.</p>\n</li>\n<li><p>To match an <em>optional</em> trailing slash on the initial request, but always include the trailing slash on the redirected URL then you can do something like this:</p>\n<pre><code># Trailing slash optional on request and slash always appended\n# (Dependent on RewriteBase)\nRewriteRule ^([\\w-]+/[\\w-]+)/?$ $1/ [QSD,R=301,L]\n</code></pre>\n<p>However, this is now reliant on the <code>RewriteBase</code> directive (to get the directory prefix) as mentioned above. Although you could use a <em>condition</em> (<code>RewriteCond</code> directive) to remove the dependency on <code>RewriteBase</code>. For example:</p>\n<pre><code># Trailing slash optional on request and slash always appended \n# (Not dependent on RewriteBase)\nRewriteCond %{REQUEST_URI} (.*?)/?$\nRewriteRule ^([\\w-]+/[\\w-]+)/?$ %1/ [QSD,R=301,L]\n</code></pre>\n</li>\n<li><p>Always test with 302 (temporary) redirects to avoid potential caching issues (301s are cached persistently by the browser - including redirects made in error). Clear the browser cache before testing.</p>\n</li>\n</ul>\n<h3>In Summary</h3>\n<pre><code> # Trailing slash optional on request and slash always appended\n # Full URL-path used, including subdirectory preifx\n # Not dependent on RewriteBase\n RewriteCond %{QUERY_STRING} ^token=12345$ [NC]\n RewriteCond %{REQUEST_URI} (.*?)/?$\n RewriteRule ^([\\w-]+/[\\w-]+)/?$ %1/ [QSD,R=301,L]\n\n # BEGIN WordPress\n :\n</code></pre>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/210993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51967/" ]
I have a problem with some page URLs. The page URL structure is like this: ``` www.example.com/wp/custom-taxonomy/somepagename/?token=12345 ``` I want that when I access the URL above to redirect me to: ``` www.example.com/wp/custom-taxonomy/somepagename/ ``` In `/wp/` is WordPress installed. I tried this in `.htaccess`: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wp/ RewriteCond %{query_string} ^token=12345 RewriteRule (.*) /$1? [R=301,L] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wp/index.php [L] </IfModule> ``` but it redirects me to: ``` www.example.com/custom-taxonomy/somepagename ``` Any ideas? **Later edit**: `/wp/` - the folder where Wordpress is installed; `/custom-taxonomy/` - a custom taxonomy, like `/partners/` where I enter all my partners. `/somepagename` - a dynamic page, like `/xyz-ltd`, `/abcd...` dynamic pages created for the custom taxonomy. I can not put a rule for every page, would need a general rule to remove the query string.
> > > ``` > RewriteBase /wp/ > RewriteCond %{query_string} ^token=12345 > RewriteRule (.*) /$1? [R=301,L] > > ``` > > but it redirects me to: > > > > ``` > www.example.com/custom-taxonomy/somepagename > > ``` > > There are two issues here with the redirected URL: 1. The `/wp` prefix is missing. 2. The trailing slash is missing. To fix **#1** you can either: * Hardcode the `/wp` prefix in the substitution string (as is done in the last `RewriteRule` - part of the WordPress front-controller - although that is arguably incorrect, see the *next point*). For example: ``` RewriteRule (.*) /wp/$1? [R=301,L] ``` * Since `RewriteBase /wp` is already defined, you can simply remove the slash prefix on the substitution string (to make it a *relative* path substitution). ie. `$1?`. mod\_rewrite then prepends the `/wp` path segment to the resulting *substitution*. For example: ``` RewriteRule (.*) $1? [R=301,L] ``` *Aside:* This is really how the last `RewriteRule` should be written. ie. `RewriteRule . index.php [L]` (since that's the whole point of having `RewriteBase /wp` defined in the first place). * Change the rule to use the `REQUEST_URI` server variable instead of a backreference (`$1`). The `REQUEST_URI` contains the full root-relative URL-path, so already includes the `/wp` prefix. This is perhaps the preferred method (unless there are additional requirements) since it will work *anywhere* and is not dependent on the setting of `RewriteBase`. For example: ``` RewriteRule ^ %{REQUEST_URI}? [R=301,L] ``` However, this does not resolve **#2** - the missing trailing slash. This is not caused by this directive - something else is removing the trailing slash (if it is present on the initial request). A possible reason for this is the *permalink* structure as suggested in [@IXN's answer](https://wordpress.stackexchange.com/a/211012/8259). Providing the trailing slash is part of the initial request (as indicated in the question) then this directive specifically preserves it. If the trailing slash is missing from the initial request then the trailing slash will also be missing from the redirected response (*see below* on how to fix this). In order to debug this further, you should check for any additional redirects in the network traffic. **Additional notes:** * You should avoid editing the code within the `# BEGIN WordPress` section, since WordPress will try to maintain this and overwrite your edits. This redirect should go near the top of the `.htaccess` file, before the `# BEGIN WordPress` section. * `^token=12345` - Include an and-of-string anchor (`$`) on the *CondPattern* to match this query string string only. As it stands, this matches any query string that simply *starts* with `token=12345`. * On Apache 2.4 use the `QSD` (Query String Discard) flag instead of appending an empty query string (a lone `?`) on the *substitution* string. * As it currently stands, this rule matches *any* URL-path. Including all static resources (images, CSS, JS) etc. It doesn't specifically match `/wp/<custom-taxonomy>/<somepagename>/` - the URL format as stated. Ideally, your rule should be as specific as possible, to match only the targetted URLs, so as to avoid unnecessary redirects and additional rule processing. For example: ``` RewriteRule ^[\w-]+/[\w-]+/$ %{REQUEST_URI} [QSD,R=301,L] ``` The `\w` shorthand character class matches the characters `a-z`, `A-Z`, `0-9` and `_` (underscore) so naturally avoids matching static resources that typically have a file extension prefixed with a *dot*. * To match an *optional* trailing slash on the initial request, but always include the trailing slash on the redirected URL then you can do something like this: ``` # Trailing slash optional on request and slash always appended # (Dependent on RewriteBase) RewriteRule ^([\w-]+/[\w-]+)/?$ $1/ [QSD,R=301,L] ``` However, this is now reliant on the `RewriteBase` directive (to get the directory prefix) as mentioned above. Although you could use a *condition* (`RewriteCond` directive) to remove the dependency on `RewriteBase`. For example: ``` # Trailing slash optional on request and slash always appended # (Not dependent on RewriteBase) RewriteCond %{REQUEST_URI} (.*?)/?$ RewriteRule ^([\w-]+/[\w-]+)/?$ %1/ [QSD,R=301,L] ``` * Always test with 302 (temporary) redirects to avoid potential caching issues (301s are cached persistently by the browser - including redirects made in error). Clear the browser cache before testing. ### In Summary ``` # Trailing slash optional on request and slash always appended # Full URL-path used, including subdirectory preifx # Not dependent on RewriteBase RewriteCond %{QUERY_STRING} ^token=12345$ [NC] RewriteCond %{REQUEST_URI} (.*?)/?$ RewriteRule ^([\w-]+/[\w-]+)/?$ %1/ [QSD,R=301,L] # BEGIN WordPress : ```
211,029
<p>I will that the custome can update in the order the custom fileds (who was insert in the checkout page)</p> <p>I have this code in the order-details.php Page but it show only the value in the input but he don't update with the new value</p> <pre><code>&lt;?php global $post; if ( isset( $_POST['submit'] ) ) { if( ! isset( $post ) ) { echo 'Error: Nichts ausgewählt'; die(); } else if( ! isset( $_POST['frontstrasse'] ) &amp;&amp; ! empty( $_POST['frontstrasse'] ) ){ echo 'Error: Strasse Not Set'; die(); } update_post_meta( $order-&gt;id, 'frontstrasse', sanitize_text_field( $_POST['Strasse'] ) ); } $istrasse = get_post_meta($order-&gt;id, 'Strasse', true ); echo print_r($istrasse); ?&gt; &lt;form method="post" action=""&gt; &lt;input type='text' name='frontstrasse' value='&lt;?php echo isset($istrasse) ? $istrasse : ''; ?&gt;' /&gt; &lt;input type='submit' value='save' /&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 211132, "author": "kreativcube", "author_id": 84829, "author_profile": "https://wordpress.stackexchange.com/users/84829", "pm_score": 1, "selected": true, "text": "<p>This code works for me. Sorry that the code is not good readable.</p>\n<pre><code>&lt;?php\nglobal $post;\n$post = $order_id;\nif ( isset( $_POST['submit'] ) ){\n echo 'Update nicht';\n} else if ( ! empty( $_POST['frontstrasse'] ) ) {\n update_post_meta( $order_id, 'Strasse', sanitize_text_field( $_POST['frontstrasse'] ) );\n update_post_meta( $order_id, 'Haus-Nr', sanitize_text_field( $_POST['fronthausnr'] ) );\n}\n$istrasse = get_post_meta($order-&gt;id, 'Strasse', true );\n$ihausnr = get_post_meta($order-&gt;id, 'Haus-Nr', true );\n?&gt;\n\n&lt;form method=&quot;post&quot; action=&quot;&quot;&gt;\n&lt;label&gt;Strasse&lt;/label&gt;&lt;input type='text' name='frontstrasse' value='&lt;?php echo $istrasse ?&gt;' /&gt;\n&lt;label&gt;Haus-Nr&lt;/label&gt;&lt;input type='text' name='fronthausnr' value='&lt;?php echo $ihausnr ?&gt;' /&gt;\n&lt;input type='submit' value='save' name='frontsubmit' /&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 400538, "author": "lonelioness", "author_id": 172357, "author_profile": "https://wordpress.stackexchange.com/users/172357", "pm_score": 1, "selected": false, "text": "<p>I came across this post looking for a solution for multiple resubmissions due to update_post_meta. Here's my solution after looking at these posts <a href=\"https://stackoverflow.com/questions/4994543/wordpress-get-post-meta-check-if-multiple-values-set\">wordpress get_post_meta check if multiple values set</a> <a href=\"https://stackoverflow.com/questions/51091238/prevent-processing-data-multiple-times-in-woocommerce-thankyou-hook\">Prevent processing data multiple times in Woocommerce thankyou hook</a> :</p>\n<pre><code>&lt;?php\nglobal $post;\n$post = $order_id;\nif ( isset( $_POST['submit'] ) ){\n echo 'Update nicht';\n} else \n \n // Checking if this has already been done avoiding reload\nif ( get_post_meta($order_id,&quot;frontstrasse&quot;,true)!=&quot;&quot; &amp;&amp; get_post_meta($order_id,&quot;fronthausnr&quot;,true)!=&quot;&quot; {\nreturn; // Exit if already processed\n}\n\n update_post_meta( $order_id, 'Strasse', sanitize_text_field( $_POST['frontstrasse'] ) );\n update_post_meta( $order_id, 'Haus-Nr', sanitize_text_field( $_POST['fronthausnr'] ) );\n}\n\n$istrasse = get_post_meta($order-&gt;id, 'Strasse', true );\n$ihausnr = get_post_meta($order-&gt;id, 'Haus-Nr', true );\n?&gt;\n\n&lt;form method=&quot;post&quot; action=&quot;&quot;&gt;\n&lt;label&gt;Strasse&lt;/label&gt;&lt;input type='text' name='frontstrasse' value='&lt;?php echo $istrasse ?&gt;' /&gt;\n&lt;label&gt;Haus-Nr&lt;/label&gt;&lt;input type='text' name='fronthausnr' value='&lt;?php echo $ihausnr ?&gt;' /&gt;\n&lt;input type='submit' value='save' name='frontsubmit' /&gt;\n&lt;/form&gt;\n \n</code></pre>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/211029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84829/" ]
I will that the custome can update in the order the custom fileds (who was insert in the checkout page) I have this code in the order-details.php Page but it show only the value in the input but he don't update with the new value ``` <?php global $post; if ( isset( $_POST['submit'] ) ) { if( ! isset( $post ) ) { echo 'Error: Nichts ausgewählt'; die(); } else if( ! isset( $_POST['frontstrasse'] ) && ! empty( $_POST['frontstrasse'] ) ){ echo 'Error: Strasse Not Set'; die(); } update_post_meta( $order->id, 'frontstrasse', sanitize_text_field( $_POST['Strasse'] ) ); } $istrasse = get_post_meta($order->id, 'Strasse', true ); echo print_r($istrasse); ?> <form method="post" action=""> <input type='text' name='frontstrasse' value='<?php echo isset($istrasse) ? $istrasse : ''; ?>' /> <input type='submit' value='save' /> </form> ```
This code works for me. Sorry that the code is not good readable. ``` <?php global $post; $post = $order_id; if ( isset( $_POST['submit'] ) ){ echo 'Update nicht'; } else if ( ! empty( $_POST['frontstrasse'] ) ) { update_post_meta( $order_id, 'Strasse', sanitize_text_field( $_POST['frontstrasse'] ) ); update_post_meta( $order_id, 'Haus-Nr', sanitize_text_field( $_POST['fronthausnr'] ) ); } $istrasse = get_post_meta($order->id, 'Strasse', true ); $ihausnr = get_post_meta($order->id, 'Haus-Nr', true ); ?> <form method="post" action=""> <label>Strasse</label><input type='text' name='frontstrasse' value='<?php echo $istrasse ?>' /> <label>Haus-Nr</label><input type='text' name='fronthausnr' value='<?php echo $ihausnr ?>' /> <input type='submit' value='save' name='frontsubmit' /> </form> ```
211,032
<p>I want to use check_ajax_referer() to verify a WP_nonce field using AJAX. Here you can find my html element. </p> <pre><code>&lt;input type="hidden" name="login_nonce" value="&lt;?= wp_create_nonce('login_nonce'); ?&gt;"/&gt; </code></pre> <p>Using jQuery I'm sending all the values from input fields to a POST request: </p> <pre><code>request = $.ajax({ type: 'POST', url: 'handle-login.php', data: { user: $('input[name="login_username"]').val(), pass: $('input[name="login_password"]').val(), security: $('input[name="login_nonce"]').val() }, dataType: 'json' }); </code></pre> <p>In handle-login.php I'm try doing the following:</p> <pre><code>require_once $_SERVER['DOCUMENT_ROOT'].'/wp-load.php'; $return = array(); if( check_ajax_referer( 'login_nonce', $_POST['security'], false ) ) $return['nonce'] = $_POST['login_nonce']; echo $return </code></pre> <p>But in return I'll get nothing.. Someone knows what is up?</p>
[ { "answer_id": 219824, "author": "db306", "author_id": 90056, "author_profile": "https://wordpress.stackexchange.com/users/90056", "pm_score": 3, "selected": false, "text": "<p>Difficult to say for sure where the mistake is as you have not mentioned about your <code>add_action('wp_ajax_my_function','whatever_callback');</code>which I think you missed out on that. But your question is missing info in this respect.</p>\n\n<p>This is how I would get on about this:</p>\n\n<p>In your functions.php file or similar:</p>\n\n<pre><code>add_action(wp_ajax_handle_login, 'handle_login_ajax');\nadd_action(wp_ajax_nopriv_handle_login, 'handle_login_ajax');\n</code></pre>\n\n<p><strong>Make sure</strong> your handle-login.php file is declared on your main php file from your plugin or theme such as functions.php</p>\n\n<pre><code>require_once plugin_dir_path(__FILE__) . 'handle-login.php';\n</code></pre>\n\n<p>You should declare nonce variables and the ajax url right after your js file hook, you will be able to access these after:</p>\n\n<pre><code>wp_enqueue_script('wccajs',plugin_dir_url( dirname(__FILE__) ) . 'login.js',array('jquery'),'1.0',false);\n\nwp_localize_script('wccajs','MyAjax',array( \n 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n 'security' =&gt; wp_create_nonce('handle_login')\n) );\n</code></pre>\n\n<p>In your handle-login.php file:</p>\n\n<pre><code>function handle_login_ajax(){\n check_ajax_referer('handle_login', 'security');\n $return = array();\n echo $return;\n wp_die(); // You missed this too\n}\n</code></pre>\n\n<p>Your Javascript file:</p>\n\n<pre><code>function send_stuff_to_server(){\n\nvar data = {\n 'action': 'handle_login', // missed this same as your action hook wp_ajax_{handle_login}\n 'security': MyAjax.security // We can access it this way\n}\n\n$.post(MyAjax.ajax_url, data, function (callBack) {\n console.log(callBack); // Will return nonce\n});\n\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 259478, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 2, "selected": false, "text": "<p>I have been having the same problems and I solved using another related ajax function:\nJust changing your </p>\n\n<p><code>check_ajax_referer( 'login_nonce', $_POST['security'], false )</code> </p>\n\n<p>to </p>\n\n<pre><code>wp_verify_nonce( $_POST['security'], 'login_nonce' )\n</code></pre>\n\n<p>seems to work and return true / false correctly. About if it's more secure one way or other I have found this info: </p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/48110/wp-verify-nonce-vs-check-admin-referer\">wp_verify_nonce vs check_admin_referer</a></p>\n" }, { "answer_id": 369308, "author": "Yosbany Zamora", "author_id": 190206, "author_profile": "https://wordpress.stackexchange.com/users/190206", "pm_score": 1, "selected": false, "text": "<p>In the method <code>check_ajax_referer()</code>, the second parameter is not the nonce value, is the key of the post request param.</p>\n<p><code>check_ajax_referer( 'login_nonce', 'security', false );</code></p>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/211032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57798/" ]
I want to use check\_ajax\_referer() to verify a WP\_nonce field using AJAX. Here you can find my html element. ``` <input type="hidden" name="login_nonce" value="<?= wp_create_nonce('login_nonce'); ?>"/> ``` Using jQuery I'm sending all the values from input fields to a POST request: ``` request = $.ajax({ type: 'POST', url: 'handle-login.php', data: { user: $('input[name="login_username"]').val(), pass: $('input[name="login_password"]').val(), security: $('input[name="login_nonce"]').val() }, dataType: 'json' }); ``` In handle-login.php I'm try doing the following: ``` require_once $_SERVER['DOCUMENT_ROOT'].'/wp-load.php'; $return = array(); if( check_ajax_referer( 'login_nonce', $_POST['security'], false ) ) $return['nonce'] = $_POST['login_nonce']; echo $return ``` But in return I'll get nothing.. Someone knows what is up?
Difficult to say for sure where the mistake is as you have not mentioned about your `add_action('wp_ajax_my_function','whatever_callback');`which I think you missed out on that. But your question is missing info in this respect. This is how I would get on about this: In your functions.php file or similar: ``` add_action(wp_ajax_handle_login, 'handle_login_ajax'); add_action(wp_ajax_nopriv_handle_login, 'handle_login_ajax'); ``` **Make sure** your handle-login.php file is declared on your main php file from your plugin or theme such as functions.php ``` require_once plugin_dir_path(__FILE__) . 'handle-login.php'; ``` You should declare nonce variables and the ajax url right after your js file hook, you will be able to access these after: ``` wp_enqueue_script('wccajs',plugin_dir_url( dirname(__FILE__) ) . 'login.js',array('jquery'),'1.0',false); wp_localize_script('wccajs','MyAjax',array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce('handle_login') ) ); ``` In your handle-login.php file: ``` function handle_login_ajax(){ check_ajax_referer('handle_login', 'security'); $return = array(); echo $return; wp_die(); // You missed this too } ``` Your Javascript file: ``` function send_stuff_to_server(){ var data = { 'action': 'handle_login', // missed this same as your action hook wp_ajax_{handle_login} 'security': MyAjax.security // We can access it this way } $.post(MyAjax.ajax_url, data, function (callBack) { console.log(callBack); // Will return nonce }); } ``` Hope this helps.
211,039
<p>I want every user to get a profile in the front-end of my website. So I want to visit website.com/user/user-name and view all the information of this user. Is this somehow possible? </p> <p>I would like to do this without a plug-in. All things I'll found on Google did include a plug-in like <a href="https://nl.wordpress.org/plugins/front-end-only-users/" rel="nofollow">Front-End Only Users</a>..</p>
[ { "answer_id": 219824, "author": "db306", "author_id": 90056, "author_profile": "https://wordpress.stackexchange.com/users/90056", "pm_score": 3, "selected": false, "text": "<p>Difficult to say for sure where the mistake is as you have not mentioned about your <code>add_action('wp_ajax_my_function','whatever_callback');</code>which I think you missed out on that. But your question is missing info in this respect.</p>\n\n<p>This is how I would get on about this:</p>\n\n<p>In your functions.php file or similar:</p>\n\n<pre><code>add_action(wp_ajax_handle_login, 'handle_login_ajax');\nadd_action(wp_ajax_nopriv_handle_login, 'handle_login_ajax');\n</code></pre>\n\n<p><strong>Make sure</strong> your handle-login.php file is declared on your main php file from your plugin or theme such as functions.php</p>\n\n<pre><code>require_once plugin_dir_path(__FILE__) . 'handle-login.php';\n</code></pre>\n\n<p>You should declare nonce variables and the ajax url right after your js file hook, you will be able to access these after:</p>\n\n<pre><code>wp_enqueue_script('wccajs',plugin_dir_url( dirname(__FILE__) ) . 'login.js',array('jquery'),'1.0',false);\n\nwp_localize_script('wccajs','MyAjax',array( \n 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n 'security' =&gt; wp_create_nonce('handle_login')\n) );\n</code></pre>\n\n<p>In your handle-login.php file:</p>\n\n<pre><code>function handle_login_ajax(){\n check_ajax_referer('handle_login', 'security');\n $return = array();\n echo $return;\n wp_die(); // You missed this too\n}\n</code></pre>\n\n<p>Your Javascript file:</p>\n\n<pre><code>function send_stuff_to_server(){\n\nvar data = {\n 'action': 'handle_login', // missed this same as your action hook wp_ajax_{handle_login}\n 'security': MyAjax.security // We can access it this way\n}\n\n$.post(MyAjax.ajax_url, data, function (callBack) {\n console.log(callBack); // Will return nonce\n});\n\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 259478, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 2, "selected": false, "text": "<p>I have been having the same problems and I solved using another related ajax function:\nJust changing your </p>\n\n<p><code>check_ajax_referer( 'login_nonce', $_POST['security'], false )</code> </p>\n\n<p>to </p>\n\n<pre><code>wp_verify_nonce( $_POST['security'], 'login_nonce' )\n</code></pre>\n\n<p>seems to work and return true / false correctly. About if it's more secure one way or other I have found this info: </p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/48110/wp-verify-nonce-vs-check-admin-referer\">wp_verify_nonce vs check_admin_referer</a></p>\n" }, { "answer_id": 369308, "author": "Yosbany Zamora", "author_id": 190206, "author_profile": "https://wordpress.stackexchange.com/users/190206", "pm_score": 1, "selected": false, "text": "<p>In the method <code>check_ajax_referer()</code>, the second parameter is not the nonce value, is the key of the post request param.</p>\n<p><code>check_ajax_referer( 'login_nonce', 'security', false );</code></p>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/211039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57798/" ]
I want every user to get a profile in the front-end of my website. So I want to visit website.com/user/user-name and view all the information of this user. Is this somehow possible? I would like to do this without a plug-in. All things I'll found on Google did include a plug-in like [Front-End Only Users](https://nl.wordpress.org/plugins/front-end-only-users/)..
Difficult to say for sure where the mistake is as you have not mentioned about your `add_action('wp_ajax_my_function','whatever_callback');`which I think you missed out on that. But your question is missing info in this respect. This is how I would get on about this: In your functions.php file or similar: ``` add_action(wp_ajax_handle_login, 'handle_login_ajax'); add_action(wp_ajax_nopriv_handle_login, 'handle_login_ajax'); ``` **Make sure** your handle-login.php file is declared on your main php file from your plugin or theme such as functions.php ``` require_once plugin_dir_path(__FILE__) . 'handle-login.php'; ``` You should declare nonce variables and the ajax url right after your js file hook, you will be able to access these after: ``` wp_enqueue_script('wccajs',plugin_dir_url( dirname(__FILE__) ) . 'login.js',array('jquery'),'1.0',false); wp_localize_script('wccajs','MyAjax',array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce('handle_login') ) ); ``` In your handle-login.php file: ``` function handle_login_ajax(){ check_ajax_referer('handle_login', 'security'); $return = array(); echo $return; wp_die(); // You missed this too } ``` Your Javascript file: ``` function send_stuff_to_server(){ var data = { 'action': 'handle_login', // missed this same as your action hook wp_ajax_{handle_login} 'security': MyAjax.security // We can access it this way } $.post(MyAjax.ajax_url, data, function (callBack) { console.log(callBack); // Will return nonce }); } ``` Hope this helps.
211,072
<p>I'm working on a website for an artist. He has many images that he would like a user to be able to sort and filter by custom taxonomy. In addition, he would like a user to be able to navigate through a hierarchical gallery with folders (that display a thumbnail) for each level of the hierarchy.</p> <p>I started by creating a custom post type for "Artwork". I then created several custom taxonomies attached to this CPT. Each "Artwork" cpt has has a featured image and custom taxonomy terms. The <a href="http://staging.designs4theweb.com/archive/" rel="nofollow">archive</a> is working well using these terms.</p> <p>As far as the gallery, I'm not sure how to go about it. I'm currently accomplishing it with the NextGen gallery but then I can't sort the images by the custom taxonomies unless the client also uploads them to the CPT with the custom taxonomy terms which seems redundant to me.</p> <p>Here is what the client sent along as a guide: <a href="https://drive.google.com/file/d/0BwsCnZE575aAVnlwdWF1TjVHbWM/view?usp=sharing" rel="nofollow">Website Organization</a></p> <p>Any suggestions?</p>
[ { "answer_id": 211078, "author": "John Ellmore", "author_id": 13649, "author_profile": "https://wordpress.stackexchange.com/users/13649", "pm_score": 1, "selected": false, "text": "<p>NextGen gallery isn't built on top of custom post types, so you won't be able to easily link your custom Artwork taxonomies with NextGen. Your best bet is to create archive template files in your theme that can display the artwork like NextGen would. The nested approach you mentioned could be accomplished using <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy#Arguments\" rel=\"nofollow\">hierarchical taxonomies</a>.</p>\n\n<p>For example, you might create an <code>archive-album.php</code> file in your theme with PHP like the following:</p>\n\n<pre><code>&lt;?php\n// get children of this taxonomy term so we print out folders for them\n$this_term = get_queried_object();\n$children = get_term_children( $this_term-&gt;term_id , 'album' );\nforeach ( $children as $child_term ) {\n $child_term = get_term( $child_term , 'album' );\n\n if ( ! $child_term-&gt;count ) continue; // skip terms with no posts in them\n\n // get one random post in this child term\n $random_term_post = get_posts( array(\n 'posts_per_page' =&gt; 1, // only one post\n 'orderby' =&gt; 'rand', // selected randomly\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'album', // from this child album\n 'terms' =&gt; $child_term-&gt;term_id\n )\n )\n ) );\n\n echo '&lt;a href=\"' . get_term_link( $child_term ) . '\"&gt;';\n echo get_the_post_thumbnail( $random_term_post[0] ); // show the random post's thumbnail\n echo $child_term-&gt;name;\n echo '&lt;/a&gt;';\n}\n\n// now print out all Artwork in this particular term\nif ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n &lt;!-- print out Artwork here --&gt;\n&lt;?php endwhile; else : ?&gt;\n &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 211636, "author": "Mike Oberdick", "author_id": 84806, "author_profile": "https://wordpress.stackexchange.com/users/84806", "pm_score": 0, "selected": false, "text": "<p>Finally gave in and used a plugin called <a href=\"https://wordpress.org/plugins/categories-images/\" rel=\"nofollow\">Categories Images</a>. Worked like a charm. I still have no clue why my code wasn't work being that I was able to use $child->term_id without problem as term for the plugin to get the correct image. Hopefully in the future, WordPress will support category images out of the box. At least I learned quite a bit about terms!</p>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/211072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84806/" ]
I'm working on a website for an artist. He has many images that he would like a user to be able to sort and filter by custom taxonomy. In addition, he would like a user to be able to navigate through a hierarchical gallery with folders (that display a thumbnail) for each level of the hierarchy. I started by creating a custom post type for "Artwork". I then created several custom taxonomies attached to this CPT. Each "Artwork" cpt has has a featured image and custom taxonomy terms. The [archive](http://staging.designs4theweb.com/archive/) is working well using these terms. As far as the gallery, I'm not sure how to go about it. I'm currently accomplishing it with the NextGen gallery but then I can't sort the images by the custom taxonomies unless the client also uploads them to the CPT with the custom taxonomy terms which seems redundant to me. Here is what the client sent along as a guide: [Website Organization](https://drive.google.com/file/d/0BwsCnZE575aAVnlwdWF1TjVHbWM/view?usp=sharing) Any suggestions?
NextGen gallery isn't built on top of custom post types, so you won't be able to easily link your custom Artwork taxonomies with NextGen. Your best bet is to create archive template files in your theme that can display the artwork like NextGen would. The nested approach you mentioned could be accomplished using [hierarchical taxonomies](https://codex.wordpress.org/Function_Reference/register_taxonomy#Arguments). For example, you might create an `archive-album.php` file in your theme with PHP like the following: ``` <?php // get children of this taxonomy term so we print out folders for them $this_term = get_queried_object(); $children = get_term_children( $this_term->term_id , 'album' ); foreach ( $children as $child_term ) { $child_term = get_term( $child_term , 'album' ); if ( ! $child_term->count ) continue; // skip terms with no posts in them // get one random post in this child term $random_term_post = get_posts( array( 'posts_per_page' => 1, // only one post 'orderby' => 'rand', // selected randomly 'tax_query' => array( array( 'taxonomy' => 'album', // from this child album 'terms' => $child_term->term_id ) ) ) ); echo '<a href="' . get_term_link( $child_term ) . '">'; echo get_the_post_thumbnail( $random_term_post[0] ); // show the random post's thumbnail echo $child_term->name; echo '</a>'; } // now print out all Artwork in this particular term if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <!-- print out Artwork here --> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ```
211,082
<p>I am using a plugin that has shortcodes. It is called according shortcodes</p> <pre><code>[accordion] [accordion-item title="Title of accordion item"]Drop-down content goes here.[/accordion-item] [accordion-item title="Second accordion item"]Drop-down content goes here.[/accordion-item] [/accordion] </code></pre> <p>I wanted put it in a wp_query, but i can't seem to figure out how to nest the shortcode. Can someone please help?<br> This is what I already tried:</p> <pre><code>&lt;?php echo do_shortcode ('[accordion]'); ?&gt; &lt;?php $args = array( 'posts_per_page' =&gt; '-1', 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'category__in' =&gt; $quicksand_categories ); $query = new WP_Query( $args ); foreach ($query-&gt;posts as $item) { $categories = wp_get_post_categories($item-&gt;ID); ?&gt; &lt;?php echo do_shortcode ('[accordion-item title="'.get_the_title($item-&gt;ID).'"]'.the_content().'[/accordion-item]'); ?&gt; &lt;?php } ?&gt; &lt;?php echo do_shortcode ('[/accordion]'); ?&gt; </code></pre>
[ { "answer_id": 211087, "author": "coopersita", "author_id": 21258, "author_profile": "https://wordpress.stackexchange.com/users/21258", "pm_score": 1, "selected": true, "text": "<p>I think it needs to be like this:</p>\n\n<pre><code>&lt;?php $output = '[accordion]'; ?&gt; \n &lt;?php \n $args = array(\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'category__in' =&gt; $quicksand_categories \n ); \n $query = new WP_Query( $args ); \n foreach ($query-&gt;posts as $item) { \n $categories = wp_get_post_categories($item-&gt;ID);\n ?&gt;\n&lt;?php $output.='[accordion-item title=\"'.get_the_title($item-&gt;ID).'\"]'.the_content().'[/accordion-item]'; ?&gt; \n\n &lt;?php } ?&gt;\n&lt;?php $output .= '[/accordion]'; ?&gt;\n&lt;?php echo do_shortcode($output); ?&gt;\n</code></pre>\n" }, { "answer_id": 320605, "author": "Mark Chitty", "author_id": 50226, "author_profile": "https://wordpress.stackexchange.com/users/50226", "pm_score": 1, "selected": false, "text": "<p>An alternative approach for using opening/closing shortcodes in a template, that doesn't require a lot of string concatenation:</p>\n\n<pre><code>&lt;?php\n// Buffer the output so that we can use [shortcodes][/shortcodes]\nob_start();\n?&gt;\n\n&lt;h1&gt;A stylish template&lt;/h1&gt;\n[my_whizzy_shortcode param=\"awesome\"]\n&lt;p&gt;&lt;?= the_content() ?&gt;&lt;/p&gt;\n&lt;div&gt;More template html, php tags, etc&lt;/div&gt;\n[/my_whizzy_shortcode]\n\n&lt;?php\n// Now write out the template, including the parsed shortcodes\necho do_shortcode(ob_get_clean());\n?&gt;\n</code></pre>\n" } ]
2015/12/07
[ "https://wordpress.stackexchange.com/questions/211082", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I am using a plugin that has shortcodes. It is called according shortcodes ``` [accordion] [accordion-item title="Title of accordion item"]Drop-down content goes here.[/accordion-item] [accordion-item title="Second accordion item"]Drop-down content goes here.[/accordion-item] [/accordion] ``` I wanted put it in a wp\_query, but i can't seem to figure out how to nest the shortcode. Can someone please help? This is what I already tried: ``` <?php echo do_shortcode ('[accordion]'); ?> <?php $args = array( 'posts_per_page' => '-1', 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => $quicksand_categories ); $query = new WP_Query( $args ); foreach ($query->posts as $item) { $categories = wp_get_post_categories($item->ID); ?> <?php echo do_shortcode ('[accordion-item title="'.get_the_title($item->ID).'"]'.the_content().'[/accordion-item]'); ?> <?php } ?> <?php echo do_shortcode ('[/accordion]'); ?> ```
I think it needs to be like this: ``` <?php $output = '[accordion]'; ?> <?php $args = array( 'posts_per_page' => '-1', 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => $quicksand_categories ); $query = new WP_Query( $args ); foreach ($query->posts as $item) { $categories = wp_get_post_categories($item->ID); ?> <?php $output.='[accordion-item title="'.get_the_title($item->ID).'"]'.the_content().'[/accordion-item]'; ?> <?php } ?> <?php $output .= '[/accordion]'; ?> <?php echo do_shortcode($output); ?> ```
211,106
<p>Is there a function to set WP_POST_REVISIONS from a plugin instead of having to do it in config.php? I was thinking of doing this:</p> <pre><code>runkit_constant_redefine( 'WP_POST_REVISIONS', 0 ); </code></pre> <p>but that puts a dependency on runkit being compiled in with PHP which I'm not sure is usual/typical.</p> <p>I want to turn revisions off completely and I'd like my (narrow use, special purpose) plugin to be as "turnkey" as possible; not requiring other tweaks or manual adjustments.</p>
[ { "answer_id": 211108, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<ol>\n<li>Create a no-revs.php</li>\n<li>Set the contents to <code>&lt;?php defined('WP_POST_REVISIONS') or define ('WP_POST_REVISIONS', false);</code></li>\n<li>Place it in the <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow\">Must Use Plugins Folder</a> located at <code>wp-content/mu-plugins</code>. </li>\n</ol>\n\n<p>Be warned; It is <a href=\"http://www.wpstuffs.com/how-to-limit-post-revisions-in-wordpress-without-plugin/\" rel=\"nofollow\">recommended</a> that you to have at least 3 post revisions to avoid any loss of data.</p>\n" }, { "answer_id": 211117, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You can try the <code>wp_revisions_to_keep</code> filter to override the value of the <code>WP_POST_REVISIONS</code> constant:</p>\n\n<pre><code>/**\n * Turn off revisions\n */\nadd_filter( 'wp_revisions_to_keep', function( $num, $post )\n{\n //---------------------------------\n // Adjust the $num to your needs\n //---------------------------------\n if ( post_type_supports( $post-&gt;post_type, 'revisions' ) )\n $num = 0;\n\n return $num;\n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>If <code>$num</code> is <code>-1</code> then we keep all revisions.\nIf <code>$num</code> is <code>0</code> then we don't keep them.</p>\n\n<p>To turn it off we could also try to remove the <em>revisions support</em> with <a href=\"http://codex.wordpress.org/Function_Reference/remove_post_type_support\" rel=\"nofollow\">remove_post_type_support()</a>:</p>\n\n<pre><code>/**\n * Remove revisions support for posts\n */\nadd_action( 'init', function()\n{\n remove_post_type_support( $post_type = 'post', $supports = 'revisions' );\n} );\n</code></pre>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
Is there a function to set WP\_POST\_REVISIONS from a plugin instead of having to do it in config.php? I was thinking of doing this: ``` runkit_constant_redefine( 'WP_POST_REVISIONS', 0 ); ``` but that puts a dependency on runkit being compiled in with PHP which I'm not sure is usual/typical. I want to turn revisions off completely and I'd like my (narrow use, special purpose) plugin to be as "turnkey" as possible; not requiring other tweaks or manual adjustments.
1. Create a no-revs.php 2. Set the contents to `<?php defined('WP_POST_REVISIONS') or define ('WP_POST_REVISIONS', false);` 3. Place it in the [Must Use Plugins Folder](https://codex.wordpress.org/Must_Use_Plugins) located at `wp-content/mu-plugins`. Be warned; It is [recommended](http://www.wpstuffs.com/how-to-limit-post-revisions-in-wordpress-without-plugin/) that you to have at least 3 post revisions to avoid any loss of data.
211,122
<p>I have customised the standard Wordpress search.php and everything is working fine.</p> <p>Now, my client would like to be able to add some content to the beginning of the search results page in the same way he can add content to any other page he has created in the admin area.</p> <p>So, my thinking is to declare my custom search.php as a template with the name 'Search'. My client can then create a new page using the 'Search' template, add the content he needs and then display the search results.</p> <p>How do I get the standard /?s=my+search+query to redirect to the new page AND deliver the information required to produce the results in my search.php?</p> <p>I have tried this:</p> <pre><code>function fb_change_search_url_rewrite() { if ( is_search() &amp;&amp; ! empty( $_GET['s'] ) ) { wp_redirect( home_url( "/custom-search-page/" ) . urlencode( get_query_var( 's' ) ) ); exit(); } } add_action( 'template_redirect', 'fb_change_search_url_rewrite' ); </code></pre> <p>and this:</p> <pre><code>function add_rewrite_rules_search_query($aRules) { $aNewRules = array('^search/(.+)?$' =&gt; 'index.php?pagename=custom-search-page&amp;s=$matches[1]'); $aRules = $aNewRules + $aRules; return $aRules; } add_filter('rewrite_rules_array', 'add_rewrite_rules_search_query'); </code></pre> <p>but no luck so far.</p> <p>Thanks in advance for any help!</p>
[ { "answer_id": 211114, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Is this practical?</p>\n</blockquote>\n\n<p>If you'd like to take advantage of all WordPress has to offer with regards to content organization, searching, a user-friendly back-end, easy extendability through plugins and themes - then yes, very practical.</p>\n\n<p>If you just want to use WordPress themes/templates, then no - it would be somewhat insane to maintain a separate database, separate search functionality, and try to tack your current code onto WordPress just to display your site with a WordPress theme. It would be far, far more efficient and sensible to find a plain HTML/CSS theme and simply apply it to your site.</p>\n\n<blockquote>\n <p>Would I somehow embed my PHP code inside WordPress pages?</p>\n</blockquote>\n\n<p>A common approach would be to port your data into the WordPress database using WordPress's <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">Custom Post Types</a> and <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">Custom Taxonomies</a>, then create your own <a href=\"https://developer.wordpress.org/themes/getting-started/\" rel=\"nofollow noreferrer\">theme</a> from scratch or modify an existing one using a <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">child-theme</a> in order to produce the markup you're after.</p>\n\n<p>You could just hack your current code into theme templates - but that would largely defeat the purpose of using a WordPress theme in the first place, I'd imagine.</p>\n\n<p>You could also just <a href=\"https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files\">load the WordPress blog header</a> (bootstrap) in you app to gain access to the WordPress environment - but again, kind of pointless if you're not intending to use any of WordPress's features.</p>\n\n<p>Long story short, I'd recommend you spend some time <a href=\"https://wordpress.org/about/features/\" rel=\"nofollow noreferrer\">reading up on WordPress</a> before you commit to it. It doesn't have to be all-or-nothing - but in your situation I don't think the grey area makes a lot of sense.</p>\n" }, { "answer_id": 211116, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Is is practical? Sure, if you like to learn new frameworks. Just spin up a <a href=\"https://c9.io\" rel=\"nofollow\">Cloud9</a> or <a href=\"https://pantheon.io\" rel=\"nofollow\">Pantheon</a> account to test it out. It's PHP so just find a place where you're code fits in.</p>\n\n<p>You'll just have to get used to the way WordPress's <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template Hierarchy</a> works and how it <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">queries posts</a>. </p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\"><img src=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" alt=\"\"></a></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\"><img src=\"https://codex.wordpress.org/images/8/85/avoid_query_posts.png\" alt=\"\"></a></p>\n\n<p><a href=\"http://www.wpbeginner.com/news/whats-coming-in-wordpress-4-4-features-and-screenshots/\" rel=\"nofollow\">WordPress 4.4</a> drops tomorrow with some pretty interesting features out of the box including core support for responsive images and a new REST API. It's pluggable so you can use your own code or find tons of plugins to work with.</p>\n\n<p>If you need help getting started there are generators to <a href=\"https://generatewp.com\" rel=\"nofollow\">create custom code</a>, produce boilerplate <a href=\"http://wppb.me\" rel=\"nofollow\">plugins</a>, <a href=\"http://underscores.me\" rel=\"nofollow\">themes</a> / <a href=\"https://roots.io/sage/\" rel=\"nofollow\">2</a> &amp; <a href=\"http://www.advancedcustomfields.com/pro/\" rel=\"nofollow\">custom fields</a> for adding more descriptive data to your <a href=\"https://generatewp.com/post-type/\" rel=\"nofollow\">custom post types</a>.</p>\n" }, { "answer_id": 211151, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": true, "text": "<p>In my opinion as long as your needs are exclusively about <em>looks</em> it's never a good reason to migrate to entirely different code base. The separation of backend code and frontend site is inherently one of the strengths in web development.</p>\n\n<p>When you you are a lone developer on own project there are roughly three design options:</p>\n\n<ol>\n<li>Custom tailored commercial design [which you typically won't have spare mountain of cash for :)].</li>\n<li>Off the shelf commercial/free design, specific to framework used or provided as generic to be sliced.</li>\n<li>DIY design, preferably starting with off the shelf foundation and customizing to your specifics.</li>\n</ol>\n\n<p>You seem to be interested in framework case of option 2, <em>but</em> resource investment you are considering (switching/integrating with WordPress) will be very considerable.</p>\n\n<p>If you operate with money that cost might be better spent on just getting great custom design.</p>\n\n<p>If you operate with time you might focus it on DIY design update. It won't win design awards, but it will be perfectly <em>usable</em>.</p>\n\n<p>In either case you would have a benefit of <em>individual</em> solution, better fitting your functionality.</p>\n" }, { "answer_id": 211161, "author": "Niels", "author_id": 84949, "author_profile": "https://wordpress.stackexchange.com/users/84949", "pm_score": 0, "selected": false, "text": "<p>I wouldn’t necessarily switch to WordPress. If you want a quick solution that’s relatively easy to use, and you don’t need any particular customisation, it’s a popular choice. However, if you want lots of control, you are in for a mountain of frustration. WordPress themes are hugely complex. As long as you stick to whatever the theme designer had in mind, you will be fine. But if you deviate just a millimeter and want something done differently, you have to dive into the theme code, and this is where the pain starts. (It is much easier to create your own theme completely from scratch, if you need that amount of control.) The same applies to the system of plug-ins/extensions/add-ons.</p>\n\n<p>I’m speaking from the experience of having run my own WP sites and having customised a few themes, and I can tell you that it wasn’t fun at all. At several points, I was very close to throwing it all away and just re-writing the thing myself, as this would have been a lot easier and faster and about a million times more fun. Operating a real-world WP site means constantly having to install updates and keeping track of what’s going on in the themes and plug-ins world. I personally find the WP experience very, well, ugly. (They have recently released a shiny new management UI based on a Node.js single-page application which is nice, but it doesn’t solve the mentioned problems.)</p>\n\n<p>You’re possibly better off keeping your existing code and extending it, or looking at another CMS or framework that doesn’t get in your way so much, even if it means having to do a bit more work yourself. One such solution I’ve personally taken a look at is ProcessWire, although I haven’t actually used it in any project yet and I don’t want to promote it here, it is just an example for what else is out there. There are countless ways to (re)build your site; I’d think twice or three times about moving to WordPress (especially if your choice is purely based on the fact that it is popular), that’s all :)</p>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84924/" ]
I have customised the standard Wordpress search.php and everything is working fine. Now, my client would like to be able to add some content to the beginning of the search results page in the same way he can add content to any other page he has created in the admin area. So, my thinking is to declare my custom search.php as a template with the name 'Search'. My client can then create a new page using the 'Search' template, add the content he needs and then display the search results. How do I get the standard /?s=my+search+query to redirect to the new page AND deliver the information required to produce the results in my search.php? I have tried this: ``` function fb_change_search_url_rewrite() { if ( is_search() && ! empty( $_GET['s'] ) ) { wp_redirect( home_url( "/custom-search-page/" ) . urlencode( get_query_var( 's' ) ) ); exit(); } } add_action( 'template_redirect', 'fb_change_search_url_rewrite' ); ``` and this: ``` function add_rewrite_rules_search_query($aRules) { $aNewRules = array('^search/(.+)?$' => 'index.php?pagename=custom-search-page&s=$matches[1]'); $aRules = $aNewRules + $aRules; return $aRules; } add_filter('rewrite_rules_array', 'add_rewrite_rules_search_query'); ``` but no luck so far. Thanks in advance for any help!
In my opinion as long as your needs are exclusively about *looks* it's never a good reason to migrate to entirely different code base. The separation of backend code and frontend site is inherently one of the strengths in web development. When you you are a lone developer on own project there are roughly three design options: 1. Custom tailored commercial design [which you typically won't have spare mountain of cash for :)]. 2. Off the shelf commercial/free design, specific to framework used or provided as generic to be sliced. 3. DIY design, preferably starting with off the shelf foundation and customizing to your specifics. You seem to be interested in framework case of option 2, *but* resource investment you are considering (switching/integrating with WordPress) will be very considerable. If you operate with money that cost might be better spent on just getting great custom design. If you operate with time you might focus it on DIY design update. It won't win design awards, but it will be perfectly *usable*. In either case you would have a benefit of *individual* solution, better fitting your functionality.
211,156
<p>Recently I have transferred my WordPress from development server to live server. I noticed that I have to change all the "guid" with live domain url. Is there any mysql query or simple function available to change it easily. </p>
[ { "answer_id": 211198, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://wp-cli.org\" rel=\"nofollow\">WP-CLI</a> to <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">search and replace</a>. The plugin <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow\">MigrateDB</a> also has a find and replace on export for the next time you transition.</p>\n" }, { "answer_id": 238086, "author": "Peter Salerno", "author_id": 102147, "author_profile": "https://wordpress.stackexchange.com/users/102147", "pm_score": 6, "selected": true, "text": "<p>It should be something like:</p>\n\n<pre><code>UPDATE wp_posts SET guid = REPLACE(guid, 'oldurl.com', 'newurl.com') WHERE guid LIKE 'http://oldurl.com/%';\n</code></pre>\n\n<ul>\n<li><code>oldurl.com</code> - Previous URL shown in wordpress settings > general options</li>\n<li><code>newurl.com</code> - New URL</li>\n</ul>\n" }, { "answer_id": 238087, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 0, "selected": false, "text": "<p>As you mentioned, there are a few variables that need to be changed in order for you to update to the new URL on your WordPress site.</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder in your <strong>live server</strong> where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://web.site/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point: enter your old URL in the <strong><code>search for…</code></strong> field and the new URL in the <strong><code>replace with…</code></strong> field</li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n" }, { "answer_id": 360311, "author": "George Ts.", "author_id": 184016, "author_profile": "https://wordpress.stackexchange.com/users/184016", "pm_score": 3, "selected": false, "text": "<p>To improve the previous answers you should update all relevant tables such as (here table prefix is wp_):</p>\n\n<pre><code>UPDATE `wp_posts` SET guid = REPLACE(guid, 'oldsiteurl', 'newsiteurl') WHERE guid LIKE 'oldsiteurl%';\n\nUPDATE `wp_postmeta` SET meta_value = REPLACE(meta_value, 'oldsiteurl', 'newsiteurl') WHERE meta_value LIKE 'oldsiteurl%';\n\nUPDATE `wp_options` SET option_value = REPLACE(option_value, 'oldsiteurl', 'newsiteurl') WHERE option_value LIKE 'oldsiteurl%';\n</code></pre>\n\n<p>If you got any plugins that do redirections you should also change the permalinks there:</p>\n\n<pre><code>UPDATE `wp_redirection_404` SET url = REPLACE(url, 'oldsiteurl', 'newsiteurl') WHERE url LIKE 'oldsiteurl%';\n</code></pre>\n" }, { "answer_id": 369758, "author": "user2186232", "author_id": 190597, "author_profile": "https://wordpress.stackexchange.com/users/190597", "pm_score": 1, "selected": false, "text": "<p>WordPress documentation warns about changing guid entries in the WP database: &quot;<em>It is critical that you do NOT change the contents of this field.</em>&quot;</p>\n<p><a href=\"https://wordpress.org/support/article/changing-the-site-url/#important-guid-note\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/#important-guid-note</a></p>\n" }, { "answer_id": 375385, "author": "farinspace", "author_id": 466, "author_profile": "https://wordpress.stackexchange.com/users/466", "pm_score": 2, "selected": false, "text": "<p>I had forgotten that I wrote a SQL generator a few years back for this precise task:</p>\n<p><a href=\"https://farinspace.github.io/wp-migrate-gen/\" rel=\"nofollow noreferrer\">https://farinspace.github.io/wp-migrate-gen/</a></p>\n<p>Essentially the relevant SQL is as follows:</p>\n<pre><code>UPDATE `wp_options` SET `option_value` = REPLACE(`option_value`, 'a', 'b') WHERE `option_value` NOT REGEXP '^([adObis]:|N;)';\nUPDATE `wp_posts` SET `post_content` = REPLACE(`post_content`, 'a', 'b');\nUPDATE `wp_posts` SET `post_excerpt` = REPLACE(`post_excerpt`, 'a', 'b');\nUPDATE `wp_posts` SET `guid` = REPLACE(`guid`, 'a', 'b');\nUPDATE `wp_comments` SET `comment_author_url` = REPLACE(`comment_author_url`, 'a', 'b');\nUPDATE `wp_comments` SET `comment_content` = REPLACE(`comment_content`, 'a', 'b');\nUPDATE `wp_links` SET `link_url` = REPLACE(`link_url`, 'a', 'b');\nUPDATE `wp_postmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';\nUPDATE `wp_usermeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';\nUPDATE `wp_termmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';\nUPDATE `wp_commentmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';\n</code></pre>\n<p>The queries above will check for and skip PHP serialized data.</p>\n<p>Using the generator, you can turn off &quot;skip serialized data&quot; if the old and new string lengths match.</p>\n<p><strong>WARNING:</strong> I would recommend that you always create a backup of your data before running any queries that add/remove/update content.</p>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43308/" ]
Recently I have transferred my WordPress from development server to live server. I noticed that I have to change all the "guid" with live domain url. Is there any mysql query or simple function available to change it easily.
It should be something like: ``` UPDATE wp_posts SET guid = REPLACE(guid, 'oldurl.com', 'newurl.com') WHERE guid LIKE 'http://oldurl.com/%'; ``` * `oldurl.com` - Previous URL shown in wordpress settings > general options * `newurl.com` - New URL
211,164
<p>I've added several customisation options to my theme, and I'm (trying to) use the <code>active_callback</code> argument with <code>$wp_customiser-&gt;add_section()</code>.</p> <p>In the first instance, this appears to be working just fine. The active callbacks that I am using are <code>is_search</code>, <code>is_archive</code> and <code>is_single</code>, so I'd expect for those sections to be hidden when I initially enter the customiser.</p> <p>However, when I actually view any of those templates relevant section does not appear.</p> <p>Below is an example of my code, what am I missing?</p> <pre><code>$wp_customise-&gt;add_section('section_template_single' , array( 'title' =&gt; __('Single Links', $this-&gt;text_domain), 'priority' =&gt; 10, 'panel' =&gt; 'panel_templates', 'active_callback' =&gt; 'is_single' )); </code></pre> <h1>Update</h1> <p>I have no plugins active on the site, and console (both Firebug and Chrome Developer Tools) reports no JS errors.</p> <p>I was running version 4.4-rc1 but now I'm on the full blown release of 4.4.</p> <p>Based on comments pointing me to this post, I have updted my code but the problem persists.</p> <p>Updated instance of <code>$wp_customise-&gt;add_section()</code> -</p> <pre><code>$wp_customise-&gt;add_section('section_template_single' , array( 'title' =&gt; __('Single Links', $this-&gt;text_domain), 'priority' =&gt; 10, 'panel' =&gt; 'panel_templates', 'active_callback' =&gt; array(&amp;$this, '_check_is_single') )); </code></pre> <p>Active callback function -</p> <pre><code>public function _check_is_single(){ return is_single(); } </code></pre> <p>By outputting the result of the active callback, it appears as though the customiser is only actually referencing it on page load, and not on every subsequent page load within the <code>&lt;iframe&gt;</code> displaying the site preview.</p>
[ { "answer_id": 211166, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 2, "selected": false, "text": "<p>The is_single template tag takes an optional parameter and therefore does not work for an active callback. Try this instead:</p>\n\n<pre><code>function callback_single() { return is_single(); }\n\n$wp_customize-&gt;add_section('section_template_single' , array(\n 'title' =&gt; __('Single Links', $this-&gt;text_domain),\n 'priority' =&gt; 10,\n 'panel' =&gt; 'panel_templates',\n 'active_callback' =&gt; 'callback_single'\n));\n</code></pre>\n\n<p>You also have \"wp_customise\" instead of \"wp_customize.\"</p>\n\n<p>Source: <a href=\"http://ottopress.com/2015/whats-new-with-the-customizer/\" rel=\"nofollow\">http://ottopress.com/2015/whats-new-with-the-customizer/</a></p>\n" }, { "answer_id": 211490, "author": "David Gard", "author_id": 10097, "author_profile": "https://wordpress.stackexchange.com/users/10097", "pm_score": 1, "selected": true, "text": "<p>After much hair pulling, swearing my mum would be shocked with, and some totally acceptable man-crying I finally found what the issue here was.</p>\n\n<p>As mentioned in my updated question, no JS errors were reported by either Firefox (Firebug) or Chrome (Developer Tools), but the issue was to be found within a custom JS script.</p>\n\n<p>In short, I have a navigation menu that is hidden whenever the user clicks anywhere away from the menu. In the first instance I was using 2x event handlers to ensure that the page reacted in the way I desire -</p>\n\n<ol>\n<li>Detect a click anywhere within the <code>document</code> and hide the menu</li>\n<li>Detect a click within the navigation menu and stop propagation of the event, thus ensuring that the click event handler described above is not triggered.</li>\n</ol>\n\n<p>So the issue was this -</p>\n\n<pre><code>this.navigation.on('click', function(e){\n e.stopPropagation(); \n});\n</code></pre>\n\n<p>Once I'd discovered the problem I set about finding an alternative method, which shockingly lead me <a href=\"https://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element\">to this Stack Overflow question</a> that recommends users seeking similar functionality implement this exact solution. Simple, yes, but as described in the most accepted answer there most certainly are unintended consequences to using that one little line of code.</p>\n\n<p>So, <a href=\"https://css-tricks.com/dangers-stopping-event-propagation/\" rel=\"nofollow noreferrer\">following the link in the most accepted answer</a>, I've now updated my code (below if anyone is interested) and thankfully the customiser is now working as expected.</p>\n\n<pre><code>/**\n * Handle clicks away from the navigation menu\n * Ignore clicks within the navigation menu, unless it's within the 'Search' box\n */ \n$(document).on('click', function(e) {\n\n if(!$(e.target).closest(t.navigation).length // The click is anywhere outside of the navigation container...\n || $(e.target).closest(t.search).length){ // ...or within the search container nested within the navigation container...\n\n if(t.navigation.hasClass('open')){\n t.navigation.removeClass('open'); // Remove the 'open' class from the navigation element\n t.menuButton.toggleClass('active'); // Toggle he 'active' class on the menu button element\n t.subMenu.css('height', '0'); // Set the height of the sub-menu to 0\n }\n\n }\n\n});\n</code></pre>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10097/" ]
I've added several customisation options to my theme, and I'm (trying to) use the `active_callback` argument with `$wp_customiser->add_section()`. In the first instance, this appears to be working just fine. The active callbacks that I am using are `is_search`, `is_archive` and `is_single`, so I'd expect for those sections to be hidden when I initially enter the customiser. However, when I actually view any of those templates relevant section does not appear. Below is an example of my code, what am I missing? ``` $wp_customise->add_section('section_template_single' , array( 'title' => __('Single Links', $this->text_domain), 'priority' => 10, 'panel' => 'panel_templates', 'active_callback' => 'is_single' )); ``` Update ====== I have no plugins active on the site, and console (both Firebug and Chrome Developer Tools) reports no JS errors. I was running version 4.4-rc1 but now I'm on the full blown release of 4.4. Based on comments pointing me to this post, I have updted my code but the problem persists. Updated instance of `$wp_customise->add_section()` - ``` $wp_customise->add_section('section_template_single' , array( 'title' => __('Single Links', $this->text_domain), 'priority' => 10, 'panel' => 'panel_templates', 'active_callback' => array(&$this, '_check_is_single') )); ``` Active callback function - ``` public function _check_is_single(){ return is_single(); } ``` By outputting the result of the active callback, it appears as though the customiser is only actually referencing it on page load, and not on every subsequent page load within the `<iframe>` displaying the site preview.
After much hair pulling, swearing my mum would be shocked with, and some totally acceptable man-crying I finally found what the issue here was. As mentioned in my updated question, no JS errors were reported by either Firefox (Firebug) or Chrome (Developer Tools), but the issue was to be found within a custom JS script. In short, I have a navigation menu that is hidden whenever the user clicks anywhere away from the menu. In the first instance I was using 2x event handlers to ensure that the page reacted in the way I desire - 1. Detect a click anywhere within the `document` and hide the menu 2. Detect a click within the navigation menu and stop propagation of the event, thus ensuring that the click event handler described above is not triggered. So the issue was this - ``` this.navigation.on('click', function(e){ e.stopPropagation(); }); ``` Once I'd discovered the problem I set about finding an alternative method, which shockingly lead me [to this Stack Overflow question](https://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) that recommends users seeking similar functionality implement this exact solution. Simple, yes, but as described in the most accepted answer there most certainly are unintended consequences to using that one little line of code. So, [following the link in the most accepted answer](https://css-tricks.com/dangers-stopping-event-propagation/), I've now updated my code (below if anyone is interested) and thankfully the customiser is now working as expected. ``` /** * Handle clicks away from the navigation menu * Ignore clicks within the navigation menu, unless it's within the 'Search' box */ $(document).on('click', function(e) { if(!$(e.target).closest(t.navigation).length // The click is anywhere outside of the navigation container... || $(e.target).closest(t.search).length){ // ...or within the search container nested within the navigation container... if(t.navigation.hasClass('open')){ t.navigation.removeClass('open'); // Remove the 'open' class from the navigation element t.menuButton.toggleClass('active'); // Toggle he 'active' class on the menu button element t.subMenu.css('height', '0'); // Set the height of the sub-menu to 0 } } }); ```
211,167
<p>My goal is to lazy load thumbnails. As seen in <a href="http://www.appelsiini.net/projects/lazyload" rel="nofollow">here</a>, I need to add <code>class="lazy"</code>, placeholder has to be in <code>src</code> and lazy loaded image as <code>data-original</code>.</p> <p>This code works perfectly:</p> <pre><code>if ( has_post_thumbnail() ) { $size = 'attachment-thumbnail-400-300'; //Get thumbnail source $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post-&gt;ID), 'thumbnail-400-300' ); $src = $thumb['0']; $placeholder = "//placehold.it/400x300/eee/222/&amp;text=+"; $default_attr = array( 'src' =&gt; $placeholder, 'data-original' =&gt; $src, 'class' =&gt; "lazy $size", ); the_post_thumbnail('thumbnail-400-300', $default_attr); } </code></pre> <hr> <p>This gets source and everything by default:</p> <pre><code>the_post_thumbnail('thumbnail-400-300'); </code></pre> <hr> <p>I tried to modify code in many different ways but I got it to work only with this:</p> <pre><code> $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post-&gt;ID), 'thumbnail-400-300' ); $src = $thumb['0']; </code></pre> <p>It seems like an extra request I don't need (I need to load A LOT of thumbnails). How to modify my code in order to get <code>src</code> directly with <code>the_post_thumbnail</code> and assign it as <code>data-original</code>?</p>
[ { "answer_id": 211178, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 3, "selected": true, "text": "<p>You got everything you need, simply build your own <code>img</code>-element like this:</p>\n\n<pre><code>if ( has_post_thumbnail() ) { \n $class = 'lazy attachment-thumbnail-400-300';\n\n //Get thumbnail source\n $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post-&gt;ID), 'thumbnail-400-300');\n $src = $thumb['0'];\n\n $placeholder = \"//placehold.it/400x300/eee/222/&amp;text=+\";\n\n echo '&lt;img src=\"'.$placeholder.'\" data-original=\"'.$src.'\" class=\"'.$class.'\" /&gt;';\n}\n</code></pre>\n\n<p>Besides that, your main performance issue might be generating a new placeholder every time you want to display an image. Use a local file for that, it´s only a few bytes in size but saves you that extra request (with all the overhead).</p>\n" }, { "answer_id": 211179, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>How to modify my code in order to get src directly with the_post_thumbnail and assign it as data-original?</p>\n</blockquote>\n\n<p>You can use <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow\">str_replace</a> and <a href=\"http://php.net/manual/en/function.preg-match.php\" rel=\"nofollow\">preg_match</a> with <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\">get_the_post_thumbnail</a>.</p>\n\n<pre><code>$size = 'attachment-thumbnail-400-300';\n$placeholder = 'src=\"//placehold.it/400x300/eee/222/&amp;text='.urlencode('+').'\"';\n$pattern = '/src\\s*=\\s*\"(.+?)\"/'; \n\n$thumb = get_the_post_thumbnail($post-&gt;ID , 'thumbnail-400-300'); \n\npreg_match($pattern, $thumb, $matches, PREG_OFFSET_CAPTURE);\n\nif ( ! empty($matches) ){\n\n $src = $matches[0][0];\n\n $thumb = str_replace( $src, $placeholder, $thumb );\n\n $thumb = str_replace( 'class=\"', 'class=\"' . \"lazy $size \", $thumb );\n\n $data_original = str_replace( 'src=\"', 'data-original=\"', $src );\n\n $thumb = str_replace( ' src=\"', $data_original . ' src=\"', $thumb );\n}\n\necho $thumb;\n</code></pre>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211167", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
My goal is to lazy load thumbnails. As seen in [here](http://www.appelsiini.net/projects/lazyload), I need to add `class="lazy"`, placeholder has to be in `src` and lazy loaded image as `data-original`. This code works perfectly: ``` if ( has_post_thumbnail() ) { $size = 'attachment-thumbnail-400-300'; //Get thumbnail source $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail-400-300' ); $src = $thumb['0']; $placeholder = "//placehold.it/400x300/eee/222/&text=+"; $default_attr = array( 'src' => $placeholder, 'data-original' => $src, 'class' => "lazy $size", ); the_post_thumbnail('thumbnail-400-300', $default_attr); } ``` --- This gets source and everything by default: ``` the_post_thumbnail('thumbnail-400-300'); ``` --- I tried to modify code in many different ways but I got it to work only with this: ``` $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail-400-300' ); $src = $thumb['0']; ``` It seems like an extra request I don't need (I need to load A LOT of thumbnails). How to modify my code in order to get `src` directly with `the_post_thumbnail` and assign it as `data-original`?
You got everything you need, simply build your own `img`-element like this: ``` if ( has_post_thumbnail() ) { $class = 'lazy attachment-thumbnail-400-300'; //Get thumbnail source $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail-400-300'); $src = $thumb['0']; $placeholder = "//placehold.it/400x300/eee/222/&text=+"; echo '<img src="'.$placeholder.'" data-original="'.$src.'" class="'.$class.'" />'; } ``` Besides that, your main performance issue might be generating a new placeholder every time you want to display an image. Use a local file for that, it´s only a few bytes in size but saves you that extra request (with all the overhead).
211,173
<p>I have a page where I'm calling event titles based on the current user. I'm calling them into a table and associating a 'credit' with each event. </p> <p>The table gets populated with the events and credits. At the bottom of the page at the moment I'm just bringing in the credits from each event, but I'd like to add up all the relevant event credits. Is there a way to do this?</p> <pre><code>$current_user = get_current_user_id(); ?&gt;&lt;h2&gt;Completed Courses&lt;/h2&gt;&lt;?php $post_args = array( 'post_type' =&gt; 'tribe_events', // 'paged' =&gt; $paged, 'eventDisplay' =&gt; 'past', // 'date_query' =&gt; array( array( 'after' =&gt; '-1 year' ) ), // 'posts_per_page' =&gt; 20, // 'cat' =&gt; '7', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'tribe_events_cat', 'field' =&gt; 'slug', 'terms' =&gt; 'business-skills-personal-and-commercial', ), ), 'meta_query' =&gt; array( array( 'key' =&gt; 'associated_people', 'value' =&gt; $current_user, 'compare' =&gt; 'LIKE' ) ) ); $post_list = new wp_query( $post_args ); ?&gt; &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;td&gt;Business Skills (Personal and Commercial)&lt;/td&gt; &lt;/tr&gt; &lt;?php if ( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post(); ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php the_title(); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php the_field( 'cpd_credits' ); ?&gt;&lt;/td&gt; &lt;td&gt;View Notes&lt;/td&gt; &lt;/tr&gt; &lt;?php endwhile; else : endif; wp_reset_query(); ?&gt; &lt;tr&gt; &lt;td&gt;Total&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php $post_list = new wp_query( $post_args ); ?&gt; &lt;table style="width:100%"&gt; &lt;?php if ( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post(); the_field( 'cpd_credits' ); endwhile; else : endif; wp_reset_query(); ?&gt; &lt;tr&gt; &lt;td&gt;Total&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I attempted this, but no luck:</p> <pre><code>$post_list = new wp_query( $post_args ); ?&gt;&lt;table style="width:100%"&gt;&lt;?php if ( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post(); // First declare total and count before the loop $total = 0; $count = 0; foreach( $posts as $post ) { if ( get_field( 'cpd_credits' ) ) { // If we have a value add it to the total and count it $total += get_field( 'cpd_credits' ); $count++; } } echo 'Count: '. $count; echo 'Total Sum: '. $total; endwhile; else : endif; wp_reset_query(); </code></pre>
[ { "answer_id": 211181, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://www.advancedcustomfields.com\" rel=\"nofollow\">ACF</a> uses <a href=\"http://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow\">get_field</a> so you can get the value before you output it. Just make sure you have a <code>$total_credit</code> variable before you start the loop and just add to it. When the loop is done print the total to your table.</p>\n\n<p><em>NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.</em></p>\n\n<pre><code>&lt;?php \n\n// Define the total credits\n$total_credit = 0; \n\n$post_list = new wp_query( $post_args ); ?&gt;\n&lt;table style=\"width:100%\"&gt;&lt;?php\n if( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post();\n\n// Get the current credits\n$cur_credit = get_field('cpd_credits');\n\n // Add to the total credits\n$total_credit += $cur_credit;\n\n&lt;?php endwhile; else : ?&gt;\n&lt;?php endif; wp_reset_query(); ?&gt;\n\n &lt;tr&gt;\n &lt;td&gt;Total: &lt;?php \n // Print the final total\n echo $total_credit; \n ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 211186, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Create a function what iterates through all the posts what are relevant. While iterating, get the credit field and add it to a counter variable. The last thing you've to do is return the counter variable what should've stored the total amount of credits for those posts.</p>\n\n<p>Your code probably will look like this</p>\n\n<p><strong>in the file included before your view is included, e.g. <code>functions.php</code></strong></p>\n\n<pre><code>function get_total_credit($query_args) {\n $total = 0;\n $posts = get_posts($query_args);\n foreach ($posts as $post) {\n $total += get_field('credit', $post-&gt;ID);\n }\n return $total;\n}\n</code></pre>\n\n<p><strong>in your view</strong></p>\n\n<pre><code>print get_total_credit(array('post_type'=&gt;'page', ...));\n</code></pre>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211173", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84954/" ]
I have a page where I'm calling event titles based on the current user. I'm calling them into a table and associating a 'credit' with each event. The table gets populated with the events and credits. At the bottom of the page at the moment I'm just bringing in the credits from each event, but I'd like to add up all the relevant event credits. Is there a way to do this? ``` $current_user = get_current_user_id(); ?><h2>Completed Courses</h2><?php $post_args = array( 'post_type' => 'tribe_events', // 'paged' => $paged, 'eventDisplay' => 'past', // 'date_query' => array( array( 'after' => '-1 year' ) ), // 'posts_per_page' => 20, // 'cat' => '7', 'tax_query' => array( array( 'taxonomy' => 'tribe_events_cat', 'field' => 'slug', 'terms' => 'business-skills-personal-and-commercial', ), ), 'meta_query' => array( array( 'key' => 'associated_people', 'value' => $current_user, 'compare' => 'LIKE' ) ) ); $post_list = new wp_query( $post_args ); ?> <table style="width:100%"> <tr> <td>Business Skills (Personal and Commercial)</td> </tr> <?php if ( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); ?> <tr> <td><?php the_title(); ?></td> <td><?php the_field( 'cpd_credits' ); ?></td> <td>View Notes</td> </tr> <?php endwhile; else : endif; wp_reset_query(); ?> <tr> <td>Total</td> </tr> </table> <?php $post_list = new wp_query( $post_args ); ?> <table style="width:100%"> <?php if ( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); the_field( 'cpd_credits' ); endwhile; else : endif; wp_reset_query(); ?> <tr> <td>Total</td> </tr> </table> ``` I attempted this, but no luck: ``` $post_list = new wp_query( $post_args ); ?><table style="width:100%"><?php if ( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); // First declare total and count before the loop $total = 0; $count = 0; foreach( $posts as $post ) { if ( get_field( 'cpd_credits' ) ) { // If we have a value add it to the total and count it $total += get_field( 'cpd_credits' ); $count++; } } echo 'Count: '. $count; echo 'Total Sum: '. $total; endwhile; else : endif; wp_reset_query(); ```
[ACF](http://www.advancedcustomfields.com) uses [get\_field](http://www.advancedcustomfields.com/resources/get_field/) so you can get the value before you output it. Just make sure you have a `$total_credit` variable before you start the loop and just add to it. When the loop is done print the total to your table. *NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.* ``` <?php // Define the total credits $total_credit = 0; $post_list = new wp_query( $post_args ); ?> <table style="width:100%"><?php if( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); // Get the current credits $cur_credit = get_field('cpd_credits'); // Add to the total credits $total_credit += $cur_credit; <?php endwhile; else : ?> <?php endif; wp_reset_query(); ?> <tr> <td>Total: <?php // Print the final total echo $total_credit; ?></td> </tr> </table> ```
211,209
<p>I'm trying to convert this to using a $wpdb class. It will return all the enums possible and i have to use this $wpdb due to mysql_query giving me weird error (no database selected) Code is following</p> <pre><code>function getEnumValues($table, $field) { $enum_array = array(); $query = 'SHOW COLUMNS FROM `' . $table . '` LIKE "' . $field . '"'; $result = mysql_query($query); if($result === FALSE) { die(mysql_error()); } $row = mysql_fetch_row($result); preg_match_all('/\'(.*?)\'/', $row[1], $enum_array); if(!empty($enum_array[1])) { //Shift array keys to match original enumerated index in MySQL (allows for use of index values instead of strings) foreach($enum_array[1] as $mkey =&gt; $mval) $enum_fields[$mkey+1] = $mval; return $enum_fields; } else return array(); // Return an empty array to avoid possible errors/warnings if array is passed to foreach() without first being checked with !empty(). } </code></pre> <p>Afterwards I have to use this code snippet to read them out</p> <pre><code>&lt;?php $enums = getEnumValues("property", "form_field_type"); foreach($enums as $enum){ echo '&lt;input type = "radio" name = "form_field_type" value = "'.$enum.'"&gt;'; echo '&lt;label for = "'.$enum.'"&gt; '.$enum.'&lt;/label&gt;&lt;br&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 211181, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://www.advancedcustomfields.com\" rel=\"nofollow\">ACF</a> uses <a href=\"http://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow\">get_field</a> so you can get the value before you output it. Just make sure you have a <code>$total_credit</code> variable before you start the loop and just add to it. When the loop is done print the total to your table.</p>\n\n<p><em>NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.</em></p>\n\n<pre><code>&lt;?php \n\n// Define the total credits\n$total_credit = 0; \n\n$post_list = new wp_query( $post_args ); ?&gt;\n&lt;table style=\"width:100%\"&gt;&lt;?php\n if( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post();\n\n// Get the current credits\n$cur_credit = get_field('cpd_credits');\n\n // Add to the total credits\n$total_credit += $cur_credit;\n\n&lt;?php endwhile; else : ?&gt;\n&lt;?php endif; wp_reset_query(); ?&gt;\n\n &lt;tr&gt;\n &lt;td&gt;Total: &lt;?php \n // Print the final total\n echo $total_credit; \n ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 211186, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Create a function what iterates through all the posts what are relevant. While iterating, get the credit field and add it to a counter variable. The last thing you've to do is return the counter variable what should've stored the total amount of credits for those posts.</p>\n\n<p>Your code probably will look like this</p>\n\n<p><strong>in the file included before your view is included, e.g. <code>functions.php</code></strong></p>\n\n<pre><code>function get_total_credit($query_args) {\n $total = 0;\n $posts = get_posts($query_args);\n foreach ($posts as $post) {\n $total += get_field('credit', $post-&gt;ID);\n }\n return $total;\n}\n</code></pre>\n\n<p><strong>in your view</strong></p>\n\n<pre><code>print get_total_credit(array('post_type'=&gt;'page', ...));\n</code></pre>\n" } ]
2015/12/08
[ "https://wordpress.stackexchange.com/questions/211209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84975/" ]
I'm trying to convert this to using a $wpdb class. It will return all the enums possible and i have to use this $wpdb due to mysql\_query giving me weird error (no database selected) Code is following ``` function getEnumValues($table, $field) { $enum_array = array(); $query = 'SHOW COLUMNS FROM `' . $table . '` LIKE "' . $field . '"'; $result = mysql_query($query); if($result === FALSE) { die(mysql_error()); } $row = mysql_fetch_row($result); preg_match_all('/\'(.*?)\'/', $row[1], $enum_array); if(!empty($enum_array[1])) { //Shift array keys to match original enumerated index in MySQL (allows for use of index values instead of strings) foreach($enum_array[1] as $mkey => $mval) $enum_fields[$mkey+1] = $mval; return $enum_fields; } else return array(); // Return an empty array to avoid possible errors/warnings if array is passed to foreach() without first being checked with !empty(). } ``` Afterwards I have to use this code snippet to read them out ``` <?php $enums = getEnumValues("property", "form_field_type"); foreach($enums as $enum){ echo '<input type = "radio" name = "form_field_type" value = "'.$enum.'">'; echo '<label for = "'.$enum.'"> '.$enum.'</label><br>'; } ?> ```
[ACF](http://www.advancedcustomfields.com) uses [get\_field](http://www.advancedcustomfields.com/resources/get_field/) so you can get the value before you output it. Just make sure you have a `$total_credit` variable before you start the loop and just add to it. When the loop is done print the total to your table. *NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.* ``` <?php // Define the total credits $total_credit = 0; $post_list = new wp_query( $post_args ); ?> <table style="width:100%"><?php if( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); // Get the current credits $cur_credit = get_field('cpd_credits'); // Add to the total credits $total_credit += $cur_credit; <?php endwhile; else : ?> <?php endif; wp_reset_query(); ?> <tr> <td>Total: <?php // Print the final total echo $total_credit; ?></td> </tr> </table> ```
211,226
<p>When I am creating a post from the admin panel and using a youtube link in the Editor, the editor automatically fetching the video from youtube and displaying right away in the editor.</p> <p><a href="https://i.stack.imgur.com/342mk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/342mk.png" alt="enter image description here"></a></p> <p>But When i am using custom code to display the editor in the frontend and putting the youtube URL its not getting the preview of the video.</p> <p><a href="https://i.stack.imgur.com/ki1UN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ki1UN.png" alt="enter image description here"></a></p> <p>Is there any specific parameter to pass to the editor for YouTube videos !!</p> <p>Here is my current code,</p> <pre><code>$settings = array( 'media_buttons' =&gt; false, 'editor_height' =&gt; '140px'); $editor_id = 'video_content'; wp_editor( '', $editor_id, $settings ); </code></pre> <p>Any idea how to accomplish this !!</p>
[ { "answer_id": 211181, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://www.advancedcustomfields.com\" rel=\"nofollow\">ACF</a> uses <a href=\"http://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow\">get_field</a> so you can get the value before you output it. Just make sure you have a <code>$total_credit</code> variable before you start the loop and just add to it. When the loop is done print the total to your table.</p>\n\n<p><em>NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.</em></p>\n\n<pre><code>&lt;?php \n\n// Define the total credits\n$total_credit = 0; \n\n$post_list = new wp_query( $post_args ); ?&gt;\n&lt;table style=\"width:100%\"&gt;&lt;?php\n if( $post_list-&gt;have_posts() ) : while( $post_list-&gt;have_posts() ) : $post_list-&gt;the_post();\n\n// Get the current credits\n$cur_credit = get_field('cpd_credits');\n\n // Add to the total credits\n$total_credit += $cur_credit;\n\n&lt;?php endwhile; else : ?&gt;\n&lt;?php endif; wp_reset_query(); ?&gt;\n\n &lt;tr&gt;\n &lt;td&gt;Total: &lt;?php \n // Print the final total\n echo $total_credit; \n ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 211186, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Create a function what iterates through all the posts what are relevant. While iterating, get the credit field and add it to a counter variable. The last thing you've to do is return the counter variable what should've stored the total amount of credits for those posts.</p>\n\n<p>Your code probably will look like this</p>\n\n<p><strong>in the file included before your view is included, e.g. <code>functions.php</code></strong></p>\n\n<pre><code>function get_total_credit($query_args) {\n $total = 0;\n $posts = get_posts($query_args);\n foreach ($posts as $post) {\n $total += get_field('credit', $post-&gt;ID);\n }\n return $total;\n}\n</code></pre>\n\n<p><strong>in your view</strong></p>\n\n<pre><code>print get_total_credit(array('post_type'=&gt;'page', ...));\n</code></pre>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211226", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44528/" ]
When I am creating a post from the admin panel and using a youtube link in the Editor, the editor automatically fetching the video from youtube and displaying right away in the editor. [![enter image description here](https://i.stack.imgur.com/342mk.png)](https://i.stack.imgur.com/342mk.png) But When i am using custom code to display the editor in the frontend and putting the youtube URL its not getting the preview of the video. [![enter image description here](https://i.stack.imgur.com/ki1UN.png)](https://i.stack.imgur.com/ki1UN.png) Is there any specific parameter to pass to the editor for YouTube videos !! Here is my current code, ``` $settings = array( 'media_buttons' => false, 'editor_height' => '140px'); $editor_id = 'video_content'; wp_editor( '', $editor_id, $settings ); ``` Any idea how to accomplish this !!
[ACF](http://www.advancedcustomfields.com) uses [get\_field](http://www.advancedcustomfields.com/resources/get_field/) so you can get the value before you output it. Just make sure you have a `$total_credit` variable before you start the loop and just add to it. When the loop is done print the total to your table. *NOTE: This is just pseudo code, so don't copy/paste this, just use it as a reference on how to add the value then output the total.* ``` <?php // Define the total credits $total_credit = 0; $post_list = new wp_query( $post_args ); ?> <table style="width:100%"><?php if( $post_list->have_posts() ) : while( $post_list->have_posts() ) : $post_list->the_post(); // Get the current credits $cur_credit = get_field('cpd_credits'); // Add to the total credits $total_credit += $cur_credit; <?php endwhile; else : ?> <?php endif; wp_reset_query(); ?> <tr> <td>Total: <?php // Print the final total echo $total_credit; ?></td> </tr> </table> ```
211,238
<p>I need you help here. After updating to WordPress 4.4 locally all was fine ... but after updating on my server I get the following error:</p> <pre><code>Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 8193 bytes) in /home/proondernemer/public_html/wp-includes/functions.php on line 4461 </code></pre> <p>Anyone know how to fix this error?</p> <p>I tryed to add this code to wp-config:</p> <pre><code>define('WP_MEMORY_LIMIT', '64M'); </code></pre> <p>And I tried to add this code to my htaccess file:</p> <pre><code>php_value memory_limit 64M </code></pre> <p>Thank you for your support.</p>
[ { "answer_id": 211263, "author": "Maruti Mohanty", "author_id": 37890, "author_profile": "https://wordpress.stackexchange.com/users/37890", "pm_score": 1, "selected": false, "text": "<p>This is a memory issue and can be handled from the <strong>wp-config.php</strong> file if the server allows.</p>\n\n<p>From what I see you have tried </p>\n\n<p><code>define('WP_MEMORY_LIMIT', '64M');</code></p>\n\n<p>which takes care of the front end, but if you still have memory issue in the admin end, then try</p>\n\n<p><code>define( 'WP_MAX_MEMORY_LIMIT', '64M' );</code></p>\n\n<blockquote>\n <p>Please note, this has to be put before wp-settings.php inclusion. </p>\n</blockquote>\n\n<p>For a more detailed information check the <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP\" rel=\"nofollow\">codex</a> here.</p>\n" }, { "answer_id": 272629, "author": "Anas Siddiqui", "author_id": 123364, "author_profile": "https://wordpress.stackexchange.com/users/123364", "pm_score": 0, "selected": false, "text": "<p>This error arise just because of memory issue, try to increase the memory</p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '128M');\n</code></pre>\n\n<p>hope it will work fine </p>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211238", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84173/" ]
I need you help here. After updating to WordPress 4.4 locally all was fine ... but after updating on my server I get the following error: ``` Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 8193 bytes) in /home/proondernemer/public_html/wp-includes/functions.php on line 4461 ``` Anyone know how to fix this error? I tryed to add this code to wp-config: ``` define('WP_MEMORY_LIMIT', '64M'); ``` And I tried to add this code to my htaccess file: ``` php_value memory_limit 64M ``` Thank you for your support.
This is a memory issue and can be handled from the **wp-config.php** file if the server allows. From what I see you have tried `define('WP_MEMORY_LIMIT', '64M');` which takes care of the front end, but if you still have memory issue in the admin end, then try `define( 'WP_MAX_MEMORY_LIMIT', '64M' );` > > Please note, this has to be put before wp-settings.php inclusion. > > > For a more detailed information check the [codex](https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP) here.
211,240
<p>When I try to google search my web address, the follow comes up as the meta description </p> <blockquote> <p>"A description for this result is not available because of this site's robots.txt – learn more."</p> </blockquote> <p>The <a href="http://www.kaushakisrealestate.com/" rel="noreferrer">website</a> I have tried to edit the robots.txt (downloaded the WP Robot plugin) and although I have changed it to </p> <pre><code>User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ </code></pre> <p>The <a href="http://kaushakisrealestate.com/robots.txt" rel="noreferrer">robots.txt</a> still appears as </p> <pre><code>User-agent: * Disallow: / </code></pre> <p>I have Yoast SEO, WP Robots, and Salient's Theme Nectar. If anyone might be able to provide me with a solution that would update the robots (or where to go from here) that would be incredibly helpful! </p>
[ { "answer_id": 211241, "author": "Nikhil", "author_id": 26760, "author_profile": "https://wordpress.stackexchange.com/users/26760", "pm_score": 2, "selected": false, "text": "<p>Once I experienced the same issue, this is what I did to fix the issue.</p>\n\n<p>Edit the robots.txt file directly (using FTP/SSH),</p>\n\n<pre><code>User-agent: * \nDisallow: /wp-admin/ \nDisallow: /wp-includes/\n</code></pre>\n\n<p>There are two reasons if the robots files not updated when you edited using a plugin.</p>\n\n<ol>\n<li>File permission.</li>\n<li>Some other plugin is reverting the changes.</li>\n</ol>\n\n<p>Also try to update the search engine visibility settings (this might not be an issue, but just have a look).</p>\n\n<p>Settings -> Reading -> Search Engine Visibility (Uncheck this option) -> Save</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 211262, "author": "Dave Ross", "author_id": 3851, "author_profile": "https://wordpress.stackexchange.com/users/3851", "pm_score": 0, "selected": false, "text": "<p>A WordPress site doesn't need an actual robots.txt file. WordPress itself will intercept requests for robots.txt and respond with its own version, and that's what your plugin is most likely trying to modify. </p>\n\n<p>Delete or rename your actual robots.txt file and try it.</p>\n" }, { "answer_id": 332480, "author": "Gonen", "author_id": 163740, "author_profile": "https://wordpress.stackexchange.com/users/163740", "pm_score": 0, "selected": false, "text": "<p>Happened to me too, try to \"Purge All Caches\" on Wordpress settings/hosting service provider. </p>\n\n<p>Then to check, open a browser in \"Incognito mode\" (chrome, make sure you didn't have any Incognito windows open already, otherwise you'll have to close them all and re-open a new Incognito window), then head over to your www.mydomain.com/robots.txt \nYou should now be able to see the updated content file like expected.</p>\n" }, { "answer_id": 368024, "author": "Vahid", "author_id": 98398, "author_profile": "https://wordpress.stackexchange.com/users/98398", "pm_score": 1, "selected": false, "text": "<p>I had the same issue and for me, I had to purge the Cloudflare cache.</p>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84989/" ]
When I try to google search my web address, the follow comes up as the meta description > > "A description for this result is not available because of this site's > robots.txt – learn more." > > > The [website](http://www.kaushakisrealestate.com/) I have tried to edit the robots.txt (downloaded the WP Robot plugin) and although I have changed it to ``` User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ ``` The [robots.txt](http://kaushakisrealestate.com/robots.txt) still appears as ``` User-agent: * Disallow: / ``` I have Yoast SEO, WP Robots, and Salient's Theme Nectar. If anyone might be able to provide me with a solution that would update the robots (or where to go from here) that would be incredibly helpful!
Once I experienced the same issue, this is what I did to fix the issue. Edit the robots.txt file directly (using FTP/SSH), ``` User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ ``` There are two reasons if the robots files not updated when you edited using a plugin. 1. File permission. 2. Some other plugin is reverting the changes. Also try to update the search engine visibility settings (this might not be an issue, but just have a look). Settings -> Reading -> Search Engine Visibility (Uncheck this option) -> Save I hope this helps.
211,256
<p>I'm trying to insert a post image thumbnail from my php scritp. It's inserting the post, the content, a download link, and I only need to set the thumbnail image to finish my script. This is my code but I can't figure out why is not working, anyhelp would be appreciated:</p> <pre><code> $url = "http://www.test.com/wp-content/uploads/2015/12/".$title[$key1].".png"; $attr = array( 'src' =&gt; basename($url), 'class' =&gt; "alignleft", 'alt' =&gt; '', 'title' =&gt; trim( strip_tags( 'Logo' ) ) ); the_post_thumbnail('thumbnail', $attr ); </code></pre>
[ { "answer_id": 211241, "author": "Nikhil", "author_id": 26760, "author_profile": "https://wordpress.stackexchange.com/users/26760", "pm_score": 2, "selected": false, "text": "<p>Once I experienced the same issue, this is what I did to fix the issue.</p>\n\n<p>Edit the robots.txt file directly (using FTP/SSH),</p>\n\n<pre><code>User-agent: * \nDisallow: /wp-admin/ \nDisallow: /wp-includes/\n</code></pre>\n\n<p>There are two reasons if the robots files not updated when you edited using a plugin.</p>\n\n<ol>\n<li>File permission.</li>\n<li>Some other plugin is reverting the changes.</li>\n</ol>\n\n<p>Also try to update the search engine visibility settings (this might not be an issue, but just have a look).</p>\n\n<p>Settings -> Reading -> Search Engine Visibility (Uncheck this option) -> Save</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 211262, "author": "Dave Ross", "author_id": 3851, "author_profile": "https://wordpress.stackexchange.com/users/3851", "pm_score": 0, "selected": false, "text": "<p>A WordPress site doesn't need an actual robots.txt file. WordPress itself will intercept requests for robots.txt and respond with its own version, and that's what your plugin is most likely trying to modify. </p>\n\n<p>Delete or rename your actual robots.txt file and try it.</p>\n" }, { "answer_id": 332480, "author": "Gonen", "author_id": 163740, "author_profile": "https://wordpress.stackexchange.com/users/163740", "pm_score": 0, "selected": false, "text": "<p>Happened to me too, try to \"Purge All Caches\" on Wordpress settings/hosting service provider. </p>\n\n<p>Then to check, open a browser in \"Incognito mode\" (chrome, make sure you didn't have any Incognito windows open already, otherwise you'll have to close them all and re-open a new Incognito window), then head over to your www.mydomain.com/robots.txt \nYou should now be able to see the updated content file like expected.</p>\n" }, { "answer_id": 368024, "author": "Vahid", "author_id": 98398, "author_profile": "https://wordpress.stackexchange.com/users/98398", "pm_score": 1, "selected": false, "text": "<p>I had the same issue and for me, I had to purge the Cloudflare cache.</p>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69187/" ]
I'm trying to insert a post image thumbnail from my php scritp. It's inserting the post, the content, a download link, and I only need to set the thumbnail image to finish my script. This is my code but I can't figure out why is not working, anyhelp would be appreciated: ``` $url = "http://www.test.com/wp-content/uploads/2015/12/".$title[$key1].".png"; $attr = array( 'src' => basename($url), 'class' => "alignleft", 'alt' => '', 'title' => trim( strip_tags( 'Logo' ) ) ); the_post_thumbnail('thumbnail', $attr ); ```
Once I experienced the same issue, this is what I did to fix the issue. Edit the robots.txt file directly (using FTP/SSH), ``` User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ ``` There are two reasons if the robots files not updated when you edited using a plugin. 1. File permission. 2. Some other plugin is reverting the changes. Also try to update the search engine visibility settings (this might not be an issue, but just have a look). Settings -> Reading -> Search Engine Visibility (Uncheck this option) -> Save I hope this helps.
211,271
<p>I'm trying to remove a filter on the register_url hook a parent theme added, that seems to have a class nomenclature I can't figure out.</p> <p>Ordinarily, a filter for this hook would be easily added like so:</p> <pre><code> add_filter( 'register_url', 'custom_register_url' ); function custom_register_url( $register_url ) { $register_url = "YOUR_PAGE_URL"; return $register_url; } </code></pre> <p>However, the parent theme has added its own filter to this hook, and due to loading sequence, my child theme can't overwrite that filter (this issue is discussed <a href="https://wordpress.stackexchange.com/questions/204551/how-to-override-filter-in-child-theme">here</a> and demonstrated <a href="https://wordpress.stackexchange.com/questions/7557/how-to-override-parent-functions-in-child-themes">here</a> and in detail <a href="http://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623" rel="nofollow noreferrer">here</a>).</p> <p>That process is relatively straightforward, but the parent theme I am working from has placed this filter and function within object oriented programming, which has my brain aching. WordPress <a href="https://codex.wordpress.org/Function_Reference/remove_filter" rel="nofollow noreferrer">Codex</a> says</p> <blockquote> <p>If a filter has been added from within a class, for example by a plugin, removing it will require accessing the class variable.</p> <pre><code> global $my_class; remove_filter( 'the_content', array($my_class, 'class_filter_function') ); </code></pre> </blockquote> <p>But I can't figure out the correct nomenclature to access this function. Here is a snippet of the parent theme:</p> <pre><code> class APP_Registration extends APP_Login_Base { private static $_template; private $error; function get_action() { return 'register'; } function __construct( $template ) { self::$_template = $template; parent::__construct( $template, __( 'Register', APP_TD ) ); add_action( 'appthemes_after_registration', 'wp_new_user_notification', 10, 2 ); add_filter( 'register_url', array( $this, '_change_register_url' ), 10, 1 ); } function _change_register_url( $url ) { return self::get_url( 'raw' ); } . . . </code></pre> <p>Trying to remove the filter just listing the function (_change_register_url) doesn't work:</p> <pre><code> function custom_register_url( $register_url ) { $register_url = "YOUR_PAGE_URL"; return $register_url; } add_filter( 'register_url', 'custom_register_url' ); function remove_parent_filters() { remove_filter( 'register_url', '_change_register_url' ); add_filter( 'register_url', 'custom_register_url' ); } add_action( 'after_setup_theme', 'remove_parent_filters' ); </code></pre> <p>Because I assume, I need to indicate the function hooked by it's correct class name.</p> <p>Can anyone help me figure out the proper remove filter syntax for this line?</p> <pre><code> remove_filter( 'register_url', '_change_register_url' ); </code></pre>
[ { "answer_id": 211275, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>It looks like the plugin doesn't want you do access the <code>APP_Registration</code> instance, so you can try this:</p>\n\n<pre><code>add_filter( 'register_url', function( $url )\n{\n // Adjust this to your needs\n $url = site_url( 'wp-login.php?action=register', 'login' );\n\n return $url;\n}, 11 );\n</code></pre>\n\n<p>to override the plugin's modifications, where we use a <em>priority</em> > 10.</p>\n" }, { "answer_id": 211276, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Filters and actions should always be static methods exactly to make them easy to remove. If they are not static and the object is not a singleton (seems that way in your case) then there are no options but to remove all the hooks for that action/filter and add yours (@birgre's answer is a variation on this theme). While far from being elegant this might work if you do the child theme for yourself and therefor know in advance what plugins there are and what hooks they use.</p>\n\n<p>The reason why the remove_filter do not work in case of non singleton object is that there have to be an exact match beetwen the pair of (object, method) used in <code>add_action</code> and <code>remove_action</code> and if you don't know the value of object you are doomed.</p>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31403/" ]
I'm trying to remove a filter on the register\_url hook a parent theme added, that seems to have a class nomenclature I can't figure out. Ordinarily, a filter for this hook would be easily added like so: ``` add_filter( 'register_url', 'custom_register_url' ); function custom_register_url( $register_url ) { $register_url = "YOUR_PAGE_URL"; return $register_url; } ``` However, the parent theme has added its own filter to this hook, and due to loading sequence, my child theme can't overwrite that filter (this issue is discussed [here](https://wordpress.stackexchange.com/questions/204551/how-to-override-filter-in-child-theme) and demonstrated [here](https://wordpress.stackexchange.com/questions/7557/how-to-override-parent-functions-in-child-themes) and in detail [here](http://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623)). That process is relatively straightforward, but the parent theme I am working from has placed this filter and function within object oriented programming, which has my brain aching. WordPress [Codex](https://codex.wordpress.org/Function_Reference/remove_filter) says > > If a filter has been added from within a class, for example by a plugin, removing it will require accessing the class variable. > > > > ``` > global $my_class; > remove_filter( 'the_content', array($my_class, 'class_filter_function') ); > > ``` > > But I can't figure out the correct nomenclature to access this function. Here is a snippet of the parent theme: ``` class APP_Registration extends APP_Login_Base { private static $_template; private $error; function get_action() { return 'register'; } function __construct( $template ) { self::$_template = $template; parent::__construct( $template, __( 'Register', APP_TD ) ); add_action( 'appthemes_after_registration', 'wp_new_user_notification', 10, 2 ); add_filter( 'register_url', array( $this, '_change_register_url' ), 10, 1 ); } function _change_register_url( $url ) { return self::get_url( 'raw' ); } . . . ``` Trying to remove the filter just listing the function (\_change\_register\_url) doesn't work: ``` function custom_register_url( $register_url ) { $register_url = "YOUR_PAGE_URL"; return $register_url; } add_filter( 'register_url', 'custom_register_url' ); function remove_parent_filters() { remove_filter( 'register_url', '_change_register_url' ); add_filter( 'register_url', 'custom_register_url' ); } add_action( 'after_setup_theme', 'remove_parent_filters' ); ``` Because I assume, I need to indicate the function hooked by it's correct class name. Can anyone help me figure out the proper remove filter syntax for this line? ``` remove_filter( 'register_url', '_change_register_url' ); ```
It looks like the plugin doesn't want you do access the `APP_Registration` instance, so you can try this: ``` add_filter( 'register_url', function( $url ) { // Adjust this to your needs $url = site_url( 'wp-login.php?action=register', 'login' ); return $url; }, 11 ); ``` to override the plugin's modifications, where we use a *priority* > 10.
211,303
<p>During theme or plugin upgrades, maintenance mode is enabled and then disabled once complete.</p> <p>Is it possible to manually enable / disable maintenance mode?</p> <p><code>Enabling Maintenance mode... Downloading update from xxxx Disabling Maintenance mode...</code></p>
[ { "answer_id": 211317, "author": "Daniel Bachhuber", "author_id": 82349, "author_profile": "https://wordpress.stackexchange.com/users/82349", "pm_score": 3, "selected": false, "text": "<p>You can enable maintenance mode in WordPress by adding a <code>.maintenance</code> file to your root WordPress directory. It will need to include:</p>\n\n<pre><code>&lt;?php\n$upgrading = time();\n</code></pre>\n\n<p>With this file in place, your site will be in maintenance mode until you remove the file.</p>\n" }, { "answer_id": 219168, "author": "Dominic", "author_id": 89618, "author_profile": "https://wordpress.stackexchange.com/users/89618", "pm_score": 2, "selected": false, "text": "<p>I use a <a href=\"https://wordpress.org/plugins/ultimate-maintenance-mode/\" rel=\"nofollow\">plug-in</a> for maintenance mode and always leave it \"in\" maintenance mode.</p>\n\n<p>Practically you can then turn on/off the actual maintenance mode by turning on/off that plugi-in — which is easy through wp-cli:</p>\n\n<pre><code># activate maintenance mode, flush caches and stuff\nwp plugin activate ultimate-maintenance-mode\n# do maintenance things\nwp plugin deactivate ultimate-maintenance-mode\n# flush caches again so the maintenance page does not show up\n</code></pre>\n" }, { "answer_id": 336304, "author": "Luke Cavanagh", "author_id": 166760, "author_profile": "https://wordpress.stackexchange.com/users/166760", "pm_score": 4, "selected": true, "text": "<p>WP-CLI now has native commands for it.</p>\n\n<pre><code># Activate Maintenance mode\n$ wp maintenance-mode activate\n# Deactivate Maintenance mode\n$ wp maintenance-mode deactivate\n</code></pre>\n\n<p>See <a href=\"https://github.com/wp-cli/maintenance-mode-command/blob/master/README.md\" rel=\"nofollow noreferrer\"><code>wp-cli/maintenance-mode-command</code></a> for more information.</p>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85027/" ]
During theme or plugin upgrades, maintenance mode is enabled and then disabled once complete. Is it possible to manually enable / disable maintenance mode? `Enabling Maintenance mode... Downloading update from xxxx Disabling Maintenance mode...`
WP-CLI now has native commands for it. ``` # Activate Maintenance mode $ wp maintenance-mode activate # Deactivate Maintenance mode $ wp maintenance-mode deactivate ``` See [`wp-cli/maintenance-mode-command`](https://github.com/wp-cli/maintenance-mode-command/blob/master/README.md) for more information.
211,305
<p>Ok, I am building this membership plugin. </p> <p>Plugin sends user to a digital payment site and this one is sending user after the operation back to the wp site with a code (POST), to a page that was chosen by user (on plugin's options panel). Plugin listens to this POST, grabs the code and makes a <code>wp_remote_get</code> request to digital payment API, who informs plugin if the payment was successful or not.</p> <p>My goal is to display to the user on this same page he/she was sent back by the gateway the status of the payment (ACTIVE, PENDING or CANCELLED).</p> <p>My code is something like this (variables are omitted):</p> <pre><code>function wxy_listener(){ if( !isset( $_GET['code'] ) ){ return false; } if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ return false; } $code = $_GET['code']; global $wxy_options; $psToken = ...; $psEmail = ...; $psSandbox = ...; //URL for the first HTTP POST request $psUrl = ...; //If Sandbox is on, we should set different URL... if ($psSandbox === "1") { $psToken = ...; $psEmail = ...; $psUrl = ...; } $user_info = wp_get_current_user(); $user_email = $user_info-&gt;user_email; $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) ); if( is_wp_error( $response ) ) { // There was an error $error_message = $response-&gt;get_error_message(); wxyLog($error_message); return false; } $resp_xml = simplexml_load_string($response); if ($resp_xml === false) { wxyLog('Failed loading RESP_XML'); return false; } $subsc_status = $resp_xml-&gt;status; // HOW TO ECHO THE STATUS AT THIS MOMENT ON THE PAGE, INSIDE THE CONTENT (AFTER OR BEFORE)? } add_action('init','wxy_listener'); </code></pre> <p>I could use <code>the_content</code> filter, but inside a function? As far as I've read, I am not supposed to do this. </p> <p>I do think it is a silly question, but...</p>
[ { "answer_id": 211343, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>Your code runs on <code>init</code> which is well before the <code>the_content</code> filter is called. There is no reason you can't hook into it. It should be as easy as:</p>\n\n<pre><code>add_filter(\n 'the_content',\n function ($content) use ($subsc_status) {\n return $content.' || '. $subsc_status;\n }\n);\n</code></pre>\n" }, { "answer_id": 211355, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>If you have to add our message before/after content then you're stuck with 'the_content' filter. It would be better if you put your message in a shortcode or hook so the theme customizations were more integrated. But essentially after you run your logic to get the status you just need to wait till the message makes sense to display.</p>\n\n<pre><code>add_action('init','wxy_listener');\n\nfunction wxy_before_the_content ( $content ) {\n $status = get_subsc_status_message();\n if(!empty($status)){\n $custom_content = '&lt;div class=\"my-plugin-message\"&gt;'.$status.'&lt;/div&gt;';\n } else return $content; // no status info\n $custom_content .= $content;\n return $custom_content;\n}\n\nfunction wxy_after_the_content ( $content ) {\n $custom_content = 'AFTER CONTENT GOES HERE';\n $content .= $custom_content;\n return $content;\n}\n\nfunction get_subsc_status_message()\n{\n global $subsc_status;\n if ( empty( $subsc_status) ) return '';\n\n $messages = array (\n 'ACTIVE' =&gt; __('Your stuff is active.', 'text_domain'),\n 'PENDING' =&gt; __('Your stuff is pending.', 'text_domain'),\n 'CANCELLED' =&gt; __('Your stuff is cancelled.', 'text_domain'),\n );\n\n if ( isset( $messages[ $subsc_status ] ) {\n return $messages[ $subsc_status ];\n }\n\n return '';\n}\n\nfunction wxy_listener(){\n\n if( !isset( $_GET['code'] ) ){ \nreturn; // nobody is listening\n }\n\n if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ \nreturn; // nobody is listening\n }\n\n $code = $_GET['code'];\n\n global $wxy_options;\n $psToken = ...;\n $psEmail = ...;\n $psSandbox = ...;\n\n // URL for the first HTTP POST request\n $psUrl = ...;\n\n // If Sandbox is on, we should set different URL...\n if ($psSandbox === \"1\") {\n $psToken = ...;\n $psEmail = ...;\n $psUrl = ...;\n }\n\n $user_info = wp_get_current_user();\n $user_email = $user_info-&gt;user_email;\n\n $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) );\n if( is_wp_error( $response ) ) {\n // There was an error\n $error_message = $response-&gt;get_error_message();\n wxyLog($error_message);\nreturn; // nobody is listening\n }\n\n $resp_xml = simplexml_load_string($response);\n if ($resp_xml === false) {\n wxyLog('Failed loading RESP_XML'); \nreturn; // nobody is listening \n } \n\n // store the response for later\n global $subsc_status;\n $subsc_status = $resp_xml-&gt;status; \n\n // add hooks to the content\n add_filter( 'the_content', 'wxy_before_the_content', 0 );\n add_filter( 'the_content', 'wxy_after_the_content', 99 );\n}\n</code></pre>\n" } ]
2015/12/09
[ "https://wordpress.stackexchange.com/questions/211305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67000/" ]
Ok, I am building this membership plugin. Plugin sends user to a digital payment site and this one is sending user after the operation back to the wp site with a code (POST), to a page that was chosen by user (on plugin's options panel). Plugin listens to this POST, grabs the code and makes a `wp_remote_get` request to digital payment API, who informs plugin if the payment was successful or not. My goal is to display to the user on this same page he/she was sent back by the gateway the status of the payment (ACTIVE, PENDING or CANCELLED). My code is something like this (variables are omitted): ``` function wxy_listener(){ if( !isset( $_GET['code'] ) ){ return false; } if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ return false; } $code = $_GET['code']; global $wxy_options; $psToken = ...; $psEmail = ...; $psSandbox = ...; //URL for the first HTTP POST request $psUrl = ...; //If Sandbox is on, we should set different URL... if ($psSandbox === "1") { $psToken = ...; $psEmail = ...; $psUrl = ...; } $user_info = wp_get_current_user(); $user_email = $user_info->user_email; $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) ); if( is_wp_error( $response ) ) { // There was an error $error_message = $response->get_error_message(); wxyLog($error_message); return false; } $resp_xml = simplexml_load_string($response); if ($resp_xml === false) { wxyLog('Failed loading RESP_XML'); return false; } $subsc_status = $resp_xml->status; // HOW TO ECHO THE STATUS AT THIS MOMENT ON THE PAGE, INSIDE THE CONTENT (AFTER OR BEFORE)? } add_action('init','wxy_listener'); ``` I could use `the_content` filter, but inside a function? As far as I've read, I am not supposed to do this. I do think it is a silly question, but...
If you have to add our message before/after content then you're stuck with 'the\_content' filter. It would be better if you put your message in a shortcode or hook so the theme customizations were more integrated. But essentially after you run your logic to get the status you just need to wait till the message makes sense to display. ``` add_action('init','wxy_listener'); function wxy_before_the_content ( $content ) { $status = get_subsc_status_message(); if(!empty($status)){ $custom_content = '<div class="my-plugin-message">'.$status.'</div>'; } else return $content; // no status info $custom_content .= $content; return $custom_content; } function wxy_after_the_content ( $content ) { $custom_content = 'AFTER CONTENT GOES HERE'; $content .= $custom_content; return $content; } function get_subsc_status_message() { global $subsc_status; if ( empty( $subsc_status) ) return ''; $messages = array ( 'ACTIVE' => __('Your stuff is active.', 'text_domain'), 'PENDING' => __('Your stuff is pending.', 'text_domain'), 'CANCELLED' => __('Your stuff is cancelled.', 'text_domain'), ); if ( isset( $messages[ $subsc_status ] ) { return $messages[ $subsc_status ]; } return ''; } function wxy_listener(){ if( !isset( $_GET['code'] ) ){ return; // nobody is listening } if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ return; // nobody is listening } $code = $_GET['code']; global $wxy_options; $psToken = ...; $psEmail = ...; $psSandbox = ...; // URL for the first HTTP POST request $psUrl = ...; // If Sandbox is on, we should set different URL... if ($psSandbox === "1") { $psToken = ...; $psEmail = ...; $psUrl = ...; } $user_info = wp_get_current_user(); $user_email = $user_info->user_email; $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) ); if( is_wp_error( $response ) ) { // There was an error $error_message = $response->get_error_message(); wxyLog($error_message); return; // nobody is listening } $resp_xml = simplexml_load_string($response); if ($resp_xml === false) { wxyLog('Failed loading RESP_XML'); return; // nobody is listening } // store the response for later global $subsc_status; $subsc_status = $resp_xml->status; // add hooks to the content add_filter( 'the_content', 'wxy_before_the_content', 0 ); add_filter( 'the_content', 'wxy_after_the_content', 99 ); } ```
211,354
<p>Pages :</p> <ul> <li>Home - set as static home page;</li> <li>blog - for blog posts;</li> <li>About ;</li> <li>Contact;</li> <li>Projects;</li> </ul> <p>List of templates:</p> <ul> <li>front-page.php - for Home page;</li> <li>home.php - for blog page;</li> <li>about.php;</li> <li>contact.php;</li> <li>projects.php</li> </ul> <p>I have dummy text set up for About and Contact page which shows up when respective pages are opened. Now, I want that :</p> <p>When Projects page is opened it shows all the project posts through loop, the same way it shows posts in blog page (whose content type is post). My question is for blog page posts we simply click "Add New" in Posts and publish it. How do I add posts and description for my projects page? </p> <p>Here is loop code in projects.php file : </p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'projects' ); $the_query = new WP_Query($args); ?&gt; &lt;?php if(have_posts()) : while($the_query-&gt;have_posts()) : $the_query-&gt;the_post(); ?&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink();?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;?php the_field('description'); ?&gt; &lt;hr&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;There are no posts or pages here&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 211343, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>Your code runs on <code>init</code> which is well before the <code>the_content</code> filter is called. There is no reason you can't hook into it. It should be as easy as:</p>\n\n<pre><code>add_filter(\n 'the_content',\n function ($content) use ($subsc_status) {\n return $content.' || '. $subsc_status;\n }\n);\n</code></pre>\n" }, { "answer_id": 211355, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>If you have to add our message before/after content then you're stuck with 'the_content' filter. It would be better if you put your message in a shortcode or hook so the theme customizations were more integrated. But essentially after you run your logic to get the status you just need to wait till the message makes sense to display.</p>\n\n<pre><code>add_action('init','wxy_listener');\n\nfunction wxy_before_the_content ( $content ) {\n $status = get_subsc_status_message();\n if(!empty($status)){\n $custom_content = '&lt;div class=\"my-plugin-message\"&gt;'.$status.'&lt;/div&gt;';\n } else return $content; // no status info\n $custom_content .= $content;\n return $custom_content;\n}\n\nfunction wxy_after_the_content ( $content ) {\n $custom_content = 'AFTER CONTENT GOES HERE';\n $content .= $custom_content;\n return $content;\n}\n\nfunction get_subsc_status_message()\n{\n global $subsc_status;\n if ( empty( $subsc_status) ) return '';\n\n $messages = array (\n 'ACTIVE' =&gt; __('Your stuff is active.', 'text_domain'),\n 'PENDING' =&gt; __('Your stuff is pending.', 'text_domain'),\n 'CANCELLED' =&gt; __('Your stuff is cancelled.', 'text_domain'),\n );\n\n if ( isset( $messages[ $subsc_status ] ) {\n return $messages[ $subsc_status ];\n }\n\n return '';\n}\n\nfunction wxy_listener(){\n\n if( !isset( $_GET['code'] ) ){ \nreturn; // nobody is listening\n }\n\n if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ \nreturn; // nobody is listening\n }\n\n $code = $_GET['code'];\n\n global $wxy_options;\n $psToken = ...;\n $psEmail = ...;\n $psSandbox = ...;\n\n // URL for the first HTTP POST request\n $psUrl = ...;\n\n // If Sandbox is on, we should set different URL...\n if ($psSandbox === \"1\") {\n $psToken = ...;\n $psEmail = ...;\n $psUrl = ...;\n }\n\n $user_info = wp_get_current_user();\n $user_email = $user_info-&gt;user_email;\n\n $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) );\n if( is_wp_error( $response ) ) {\n // There was an error\n $error_message = $response-&gt;get_error_message();\n wxyLog($error_message);\nreturn; // nobody is listening\n }\n\n $resp_xml = simplexml_load_string($response);\n if ($resp_xml === false) {\n wxyLog('Failed loading RESP_XML'); \nreturn; // nobody is listening \n } \n\n // store the response for later\n global $subsc_status;\n $subsc_status = $resp_xml-&gt;status; \n\n // add hooks to the content\n add_filter( 'the_content', 'wxy_before_the_content', 0 );\n add_filter( 'the_content', 'wxy_after_the_content', 99 );\n}\n</code></pre>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211354", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85056/" ]
Pages : * Home - set as static home page; * blog - for blog posts; * About ; * Contact; * Projects; List of templates: * front-page.php - for Home page; * home.php - for blog page; * about.php; * contact.php; * projects.php I have dummy text set up for About and Contact page which shows up when respective pages are opened. Now, I want that : When Projects page is opened it shows all the project posts through loop, the same way it shows posts in blog page (whose content type is post). My question is for blog page posts we simply click "Add New" in Posts and publish it. How do I add posts and description for my projects page? Here is loop code in projects.php file : ``` <?php $args = array( 'post_type' => 'projects' ); $the_query = new WP_Query($args); ?> <?php if(have_posts()) : while($the_query->have_posts()) : $the_query->the_post(); ?> <h3><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h3> <?php the_field('description'); ?> <hr> <?php endwhile; else: ?> <p>There are no posts or pages here</p> <?php endif; ?> ```
If you have to add our message before/after content then you're stuck with 'the\_content' filter. It would be better if you put your message in a shortcode or hook so the theme customizations were more integrated. But essentially after you run your logic to get the status you just need to wait till the message makes sense to display. ``` add_action('init','wxy_listener'); function wxy_before_the_content ( $content ) { $status = get_subsc_status_message(); if(!empty($status)){ $custom_content = '<div class="my-plugin-message">'.$status.'</div>'; } else return $content; // no status info $custom_content .= $content; return $custom_content; } function wxy_after_the_content ( $content ) { $custom_content = 'AFTER CONTENT GOES HERE'; $content .= $custom_content; return $content; } function get_subsc_status_message() { global $subsc_status; if ( empty( $subsc_status) ) return ''; $messages = array ( 'ACTIVE' => __('Your stuff is active.', 'text_domain'), 'PENDING' => __('Your stuff is pending.', 'text_domain'), 'CANCELLED' => __('Your stuff is cancelled.', 'text_domain'), ); if ( isset( $messages[ $subsc_status ] ) { return $messages[ $subsc_status ]; } return ''; } function wxy_listener(){ if( !isset( $_GET['code'] ) ){ return; // nobody is listening } if( !isset( $_GET['returnfrom'] ) || 'ps' != $_GET['returnfrom'] ){ return; // nobody is listening } $code = $_GET['code']; global $wxy_options; $psToken = ...; $psEmail = ...; $psSandbox = ...; // URL for the first HTTP POST request $psUrl = ...; // If Sandbox is on, we should set different URL... if ($psSandbox === "1") { $psToken = ...; $psEmail = ...; $psUrl = ...; } $user_info = wp_get_current_user(); $user_email = $user_info->user_email; $response = wp_remote_retrieve_body( wp_remote_get( $psUrl ) ); if( is_wp_error( $response ) ) { // There was an error $error_message = $response->get_error_message(); wxyLog($error_message); return; // nobody is listening } $resp_xml = simplexml_load_string($response); if ($resp_xml === false) { wxyLog('Failed loading RESP_XML'); return; // nobody is listening } // store the response for later global $subsc_status; $subsc_status = $resp_xml->status; // add hooks to the content add_filter( 'the_content', 'wxy_before_the_content', 0 ); add_filter( 'the_content', 'wxy_after_the_content', 99 ); } ```
211,363
<p>I want to add functionality like Add member record with birthrate and as per the current date it shows on page.</p> <p><strong>Ex :</strong> </p> <p>Add record - [name] [birth_date] [position]</p> <p>And on the front page we can shows all the member list who have birthday today.</p> <p>Is there any way to achieve that?</p>
[ { "answer_id": 211370, "author": "Nikhil", "author_id": 26760, "author_profile": "https://wordpress.stackexchange.com/users/26760", "pm_score": 1, "selected": false, "text": "<p><strong>Step - 1</strong></p>\n\n<p>Create a custom post type called Birthday</p>\n\n<pre><code>add_action( 'init', 'register_birthday_content_type' );\nfunction register_birthday_content_type() {\n register_post_type( 'birthday', array(\n 'labels' =&gt; array(\n 'name' =&gt; 'Birthdays',\n 'singular_name' =&gt; 'Birthday',\n ),\n 'description' =&gt; 'Your description',\n 'public' =&gt; true,\n 'menu_position' =&gt; 20,\n 'supports' =&gt; array( 'title', 'editor', 'custom-fields' )\n ));\n}\n</code></pre>\n\n<p><strong>Step - 2</strong></p>\n\n<p>Since you have a birthday date field, I prefer using ACF (<a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">http://www.advancedcustomfields.com/</a>)</p>\n\n<p>Install ACF and add additional fields such as birth date and position</p>\n\n<p><strong>Step - 3</strong></p>\n\n<p>Write query to fetch the posts which has birth date = Today.</p>\n\n<p>Here is the documetation: <a href=\"http://www.advancedcustomfields.com/resources/query-posts-custom-fields/\" rel=\"nofollow noreferrer\">http://www.advancedcustomfields.com/resources/query-posts-custom-fields/</a></p>\n\n<p>This is one of the quickest way.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 211373, "author": "Carl Alberto", "author_id": 60720, "author_profile": "https://wordpress.stackexchange.com/users/60720", "pm_score": 0, "selected": false, "text": "<p>There are a lot of ways to do it but I will approach it by creating a custom post type first for the <strong>Members</strong>, you can create that by pasting this code in your theme's functions.php using the code below:</p>\n\n<pre><code> function member_name() {\n\n $labels = array(\n 'name' =&gt; _x( 'Member Name', 'Post Type General Name', 'text_domain' ),\n 'singular_name' =&gt; _x( 'Member Name', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' =&gt; __( 'Members', 'text_domain' ),\n 'name_admin_bar' =&gt; __( 'Member Name', 'text_domain' ),\n 'parent_item_colon' =&gt; __( 'Member', 'text_domain' ),\n 'all_items' =&gt; __( 'All Members', 'text_domain' ),\n 'add_new_item' =&gt; __( 'Add New Member ', 'text_domain' ),\n 'add_new' =&gt; __( 'Add New', 'text_domain' ),\n 'new_item' =&gt; __( 'New Member ', 'text_domain' ),\n 'edit_item' =&gt; __( 'Edit Member ', 'text_domain' ),\n 'update_item' =&gt; __( 'Update Member ', 'text_domain' ),\n 'view_item' =&gt; __( 'View Member ', 'text_domain' ),\n 'search_items' =&gt; __( 'Search Member ', 'text_domain' ),\n 'not_found' =&gt; __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ),\n 'items_list' =&gt; __( 'Member list', 'text_domain' ),\n 'items_list_navigation' =&gt; __( 'Member list navigation', 'text_domain' ),\n 'filter_items_list' =&gt; __( 'Filter Member list', 'text_domain' ),\n );\n $args = array(\n 'label' =&gt; __( 'Member Name', 'text_domain' ),\n 'description' =&gt; __( 'Member Description', 'text_domain' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 5,\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'can_export' =&gt; true,\n 'has_archive' =&gt; true,\n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'capability_type' =&gt; 'page',\n );\n register_post_type( 'member_name', $args );\n\n}\nadd_action( 'init', 'member_name', 0 );\n</code></pre>\n\n<p>Please refer here for the full documentation of the post type: codex.wordpress.org/Post_Types</p>\n\n<p>After you have a custom post type, The easiest way to add fields (birthday, position,etc) associated with custom post type is using the ACF plugin www.advancedcustomfields.com/ or you can code it by understanding for the meta boxes works with a custom post type, please refer here: codex.wordpress.org/Function_Reference/add_meta_box </p>\n\n<p>Lastly, after setting your member list, associating it with the proper fields and populating your data, you can display it in your theme, for example in your default homepage, let's use index.php for example in your theme folder, you can insert this example code to use wp_query to display and sort the custom meta associated with a custom post type:</p>\n\n<pre><code>$args = array (\n 'post_type' =&gt; array( 'member_name' ),\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'date',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'birthdate',\n 'type' =&gt; 'DATE',\n ),\n ),\n);\n\n// The Query\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Please refer with Wp_query's documentation for indepth usage: codex.wordpress.org/Class_Reference/WP_Query</p>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82575/" ]
I want to add functionality like Add member record with birthrate and as per the current date it shows on page. **Ex :** Add record - [name] [birth\_date] [position] And on the front page we can shows all the member list who have birthday today. Is there any way to achieve that?
**Step - 1** Create a custom post type called Birthday ``` add_action( 'init', 'register_birthday_content_type' ); function register_birthday_content_type() { register_post_type( 'birthday', array( 'labels' => array( 'name' => 'Birthdays', 'singular_name' => 'Birthday', ), 'description' => 'Your description', 'public' => true, 'menu_position' => 20, 'supports' => array( 'title', 'editor', 'custom-fields' ) )); } ``` **Step - 2** Since you have a birthday date field, I prefer using ACF (<http://www.advancedcustomfields.com/>) Install ACF and add additional fields such as birth date and position **Step - 3** Write query to fetch the posts which has birth date = Today. Here is the documetation: <http://www.advancedcustomfields.com/resources/query-posts-custom-fields/> This is one of the quickest way. I hope this helps.
211,368
<p>I'm glad that WP 4.4. ships with a built-in responsive image feature. But I'm not that happy with it.</p> <p>I have set up some custom image sizes in my <code>functions.php</code>:</p> <pre>add_image_size('post-thumbnails', 600, 600, true); add_image_size('news-large', 1024, false); add_image_size('news-small', 500, false); add_image_size('3-col', 500, 375, true); add_image_size('presscutting', 600, 850, true); add_image_size('medium-large', 768, false); // just added today for devices support add_image_size('full-feature-image', 2000, false); add_image_size('gallery-image', 800, 600, true);</pre> <p>As I figured, images that aren't cropped (cropping set to <code>false</code>) are added to the <code>srcset</code>. An image is output in the frontend like (line breaks added for better readability):</p> <pre>&lt;img width="2000" height="1335" src="http://mywebsite.com/cms/wp-content/uploads/2015/03/image-2000x1335.jpg" class="attachment-full-feature-image size-full-feature-image" alt="asdf" srcset=" http://mywebsite.com/cms/wp-content/uploads/2015/03/image-300x200.jpg 300w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-768x513.jpg 768w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-1024x683.jpg 1024w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-500x334.jpg 500w" sizes="(max-width: 2000px) 100vw, 2000px"> </pre> <p>But now my problem: On my screen, only the images specified with 1024px width are shown, although it hast a 1600px screen resolution. So all the images look blurry.</p> <p><strong>How can i make WP and/or my browser use the 2kpx image instead?</strong> Would I have to add new image sizes for, let's say 1280px, 1440px, 1600px, 1968px? Or is there a simpler way of telling WP / the browser to use the larger image instead of showing a blurry and way too small version?</p>
[ { "answer_id": 211405, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 4, "selected": true, "text": "<p>Concerning documentation there is this blog post on the Make Blog:</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/\">Responsive Images in WordPress 4.4</a></p>\n\n<p>To increase the 1600px limit mentioned in the comments try this:</p>\n\n<pre><code>add_filter('max_srcset_image_width', function($max_srcset_image_width, $size_array){\n return 2000;\n}, 10, 2);\n</code></pre>\n\n<p>Finally as already mentioned you should fix your calls to <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\"><code>add_image_size</code></a></p>\n\n<blockquote>\n <p><strike>add_image_size('news-large', 1024, false);</strike></p>\n</blockquote>\n\n<p>needs to be</p>\n\n<pre><code>add_image_size('news-large', 1024, 0, false);\n</code></pre>\n" }, { "answer_id": 211453, "author": "user1895954", "author_id": 85113, "author_profile": "https://wordpress.stackexchange.com/users/85113", "pm_score": 1, "selected": false, "text": "<p>I solved the same issue by adding an extra size to the <code>srcset</code> with a filter function that you can add in your <code>functions.php</code>:</p>\n\n<pre><code>function filter_max_srcset( $max_width, $size_array ) {\n if ( $size_array[0] === 1800 ) {\n $max_width = 1800;\n }\n return $max_width;\n}\nadd_filter( 'max_srcset_image_width', 'filter_max_srcset', 10, 2 );\n</code></pre>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211368", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29055/" ]
I'm glad that WP 4.4. ships with a built-in responsive image feature. But I'm not that happy with it. I have set up some custom image sizes in my `functions.php`: ``` add_image_size('post-thumbnails', 600, 600, true); add_image_size('news-large', 1024, false); add_image_size('news-small', 500, false); add_image_size('3-col', 500, 375, true); add_image_size('presscutting', 600, 850, true); add_image_size('medium-large', 768, false); // just added today for devices support add_image_size('full-feature-image', 2000, false); add_image_size('gallery-image', 800, 600, true); ``` As I figured, images that aren't cropped (cropping set to `false`) are added to the `srcset`. An image is output in the frontend like (line breaks added for better readability): ``` <img width="2000" height="1335" src="http://mywebsite.com/cms/wp-content/uploads/2015/03/image-2000x1335.jpg" class="attachment-full-feature-image size-full-feature-image" alt="asdf" srcset=" http://mywebsite.com/cms/wp-content/uploads/2015/03/image-300x200.jpg 300w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-768x513.jpg 768w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-1024x683.jpg 1024w, http://mywebsite.com/cms/wp-content/uploads/2015/03/image-500x334.jpg 500w" sizes="(max-width: 2000px) 100vw, 2000px"> ``` But now my problem: On my screen, only the images specified with 1024px width are shown, although it hast a 1600px screen resolution. So all the images look blurry. **How can i make WP and/or my browser use the 2kpx image instead?** Would I have to add new image sizes for, let's say 1280px, 1440px, 1600px, 1968px? Or is there a simpler way of telling WP / the browser to use the larger image instead of showing a blurry and way too small version?
Concerning documentation there is this blog post on the Make Blog: [Responsive Images in WordPress 4.4](https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/) To increase the 1600px limit mentioned in the comments try this: ``` add_filter('max_srcset_image_width', function($max_srcset_image_width, $size_array){ return 2000; }, 10, 2); ``` Finally as already mentioned you should fix your calls to [`add_image_size`](https://developer.wordpress.org/reference/functions/add_image_size/) > > add\_image\_size('news-large', 1024, false); > > > needs to be ``` add_image_size('news-large', 1024, 0, false); ```
211,375
<p>I succesfully converted my 4.3.1 install to all https. After updating to 4.4. I have a problem with the new <code>srcset</code> attribute. While the <code>src</code> attribute for images is set using https, the <code>srcset</code> attribute is http. This causes browsers to not display any image at all. </p> <p>While waiting for a better fix, I wish to disable setting the <code>srcset</code> attribute altogether so that all images only have a <code>src</code> attribute. How do I do that?</p>
[ { "answer_id": 211376, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 6, "selected": true, "text": "<p>Here are few things you could try to remove the responsive image support in 4.4:</p>\n\n<pre><code>/**\n * Disable responsive image support (test!)\n */\n\n// Clean the up the image from wp_get_attachment_image()\nadd_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['sizes'] ) )\n unset( $attr['sizes'] );\n\n if( isset( $attr['srcset'] ) )\n unset( $attr['srcset'] );\n\n return $attr;\n\n }, PHP_INT_MAX );\n\n// Override the calculated image sizes\nadd_filter( 'wp_calculate_image_sizes', '__return_empty_array', PHP_INT_MAX );\n\n// Override the calculated image sources\nadd_filter( 'wp_calculate_image_srcset', '__return_empty_array', PHP_INT_MAX );\n\n// Remove the reponsive stuff from the content\nremove_filter( 'the_content', 'wp_make_content_images_responsive' );\n</code></pre>\n\n<p>but as mentioned by @cybmeta the problem may be elsewhere.</p>\n\n<h2>Force https on <code>srcset</code></h2>\n\n<p>You could do some debugging with the <code>wp_calculate_image_srcset</code> filter and even try this <em>quick-fix</em>:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset', function( $sources )\n{\n foreach( $sources as &amp;$source )\n {\n if( isset( $source['url'] ) )\n $source['url'] = set_url_scheme( $source['url'], 'https' );\n }\n return $sources;\n\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>to set the <em>url scheme</em> to <code>https</code>. Another approach would be to have it schemeless <code>//</code>.</p>\n\n<p>Check out the Codex for other <a href=\"http://codex.wordpress.org/Function_Reference/set_url_scheme\" rel=\"noreferrer\"><code>set_url_scheme()</code></a> options:</p>\n\n<pre><code>$source['url'] = set_url_scheme( $source['url'], null ); \n$source['url'] = set_url_scheme( $source['url'], 'relative' );\n</code></pre>\n\n<p>But you should try to dig deeper and find the root cause.</p>\n\n<h2>Update:</h2>\n\n<p>We could bail out earlier from the <code>wp_calculate_image_srcset()</code> function with:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset_meta', '__return_empty_array' );\n</code></pre>\n\n<p>then using the <code>wp_calculate_image_srcset</code> or <code>max_srcset_image_width</code> filters.</p>\n\n<p>Also updated according to ticket <a href=\"https://core.trac.wordpress.org/ticket/41895\" rel=\"noreferrer\">#41895</a>, to return an empty array instead of false/null.</p>\n" }, { "answer_id": 211418, "author": "joemcgill", "author_id": 85092, "author_profile": "https://wordpress.stackexchange.com/users/85092", "pm_score": 3, "selected": false, "text": "<p>Most likely, the reason the URLs in your <code>srcset</code> attributes are incorrectly showing HTTPS is because the URLs for all images are built using the value of the siteurl option in your wp_options table. If you're serving your front end over HTTPS, you should also change those values (via Settings > General).</p>\n\n<p>Here's the related ticket on the WordPress issue tracking system: <a href=\"https://core.trac.wordpress.org/ticket/34945\">https://core.trac.wordpress.org/ticket/34945</a></p>\n" }, { "answer_id": 211472, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 3, "selected": false, "text": "<p>This will disable the srcset code by eliminating any images wider than 1 pixel.</p>\n\n<pre><code>add_filter( 'max_srcset_image_width', create_function( '', 'return 1;' ) );\n</code></pre>\n\n<p>In the long run, you should try to fix the actual problem. Still, this works if you need a quick fix.</p>\n" }, { "answer_id": 211985, "author": "Trevor", "author_id": 17461, "author_profile": "https://wordpress.stackexchange.com/users/17461", "pm_score": 4, "selected": false, "text": "<p>The simplest and cleanest way to do this is simply this:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset', '__return_false' );\n</code></pre>\n\n<p>To echo what most other folks are saying though, srcset is a good idea and is the future (best practice now), but if you need a quick fix to keep your site working, the above snippet does the job without any hacking.</p>\n\n<p><em>source: <a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/#comment-28662\" rel=\"nofollow noreferrer\">WP Core Blog</a></em></p>\n" }, { "answer_id": 212042, "author": "user2969141", "author_id": 63875, "author_profile": "https://wordpress.stackexchange.com/users/63875", "pm_score": 2, "selected": false, "text": "<p>In Settings/General make sure your WordPress Address (URL) and Site Address (URL) are set to the <a href=\"https://yourdomain.com\" rel=\"nofollow\">https://yourdomain.com</a></p>\n\n<p>See <a href=\"http://wptavern.com/how-to-fix-images-not-loading-in-wordpress-4-4-while-using-ssl\" rel=\"nofollow\">http://wptavern.com/how-to-fix-images-not-loading-in-wordpress-4-4-while-using-ssl</a></p>\n\n<blockquote>\n <p>Joe McGill, who helped lead the effort to get responsive images into\n WordPress, also responded in the forum thread and confirms Cree’s\n suggestion is correct, “If you’re running HTTPS on the front end, you\n should change the URLS for your home and site URL in Settings >\n General so they use the HTTPS scheme,” he said.</p>\n</blockquote>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27184/" ]
I succesfully converted my 4.3.1 install to all https. After updating to 4.4. I have a problem with the new `srcset` attribute. While the `src` attribute for images is set using https, the `srcset` attribute is http. This causes browsers to not display any image at all. While waiting for a better fix, I wish to disable setting the `srcset` attribute altogether so that all images only have a `src` attribute. How do I do that?
Here are few things you could try to remove the responsive image support in 4.4: ``` /** * Disable responsive image support (test!) */ // Clean the up the image from wp_get_attachment_image() add_filter( 'wp_get_attachment_image_attributes', function( $attr ) { if( isset( $attr['sizes'] ) ) unset( $attr['sizes'] ); if( isset( $attr['srcset'] ) ) unset( $attr['srcset'] ); return $attr; }, PHP_INT_MAX ); // Override the calculated image sizes add_filter( 'wp_calculate_image_sizes', '__return_empty_array', PHP_INT_MAX ); // Override the calculated image sources add_filter( 'wp_calculate_image_srcset', '__return_empty_array', PHP_INT_MAX ); // Remove the reponsive stuff from the content remove_filter( 'the_content', 'wp_make_content_images_responsive' ); ``` but as mentioned by @cybmeta the problem may be elsewhere. Force https on `srcset` ----------------------- You could do some debugging with the `wp_calculate_image_srcset` filter and even try this *quick-fix*: ``` add_filter( 'wp_calculate_image_srcset', function( $sources ) { foreach( $sources as &$source ) { if( isset( $source['url'] ) ) $source['url'] = set_url_scheme( $source['url'], 'https' ); } return $sources; }, PHP_INT_MAX ); ``` to set the *url scheme* to `https`. Another approach would be to have it schemeless `//`. Check out the Codex for other [`set_url_scheme()`](http://codex.wordpress.org/Function_Reference/set_url_scheme) options: ``` $source['url'] = set_url_scheme( $source['url'], null ); $source['url'] = set_url_scheme( $source['url'], 'relative' ); ``` But you should try to dig deeper and find the root cause. Update: ------- We could bail out earlier from the `wp_calculate_image_srcset()` function with: ``` add_filter( 'wp_calculate_image_srcset_meta', '__return_empty_array' ); ``` then using the `wp_calculate_image_srcset` or `max_srcset_image_width` filters. Also updated according to ticket [#41895](https://core.trac.wordpress.org/ticket/41895), to return an empty array instead of false/null.
211,393
<p>I installed wp-cli back in April on my Windows box using composer. I believe with the following command: <code>composer create-project wp-cli/wp-cli --no-dev</code> as outlined in the alternate install methods on <a href="https://github.com/wp-cli/wp-cli/wiki/Alternative-Install-Methods" rel="nofollow">here</a>.</p> <p>I have since used "<code>composer update --no-dev</code>" to update but just realized that it is only updating the dependencies and not the wp-cli package itself. If I run a "<code>wp cli version</code>" it reports version WP-CLI 0.18.0, yet v0.20.4 is the latest released version.</p> <p>I can't seem to find any way to update wp-cli. I suppose I could just install a new copy each time but that seems silly. Regardless, I did test and if I issue a "<code>composer create-project wp-cli/wp-cli --no-dev</code>" in a new directory it downloads the latest version. I also tried "<code>wp cli update</code>" but it reports back "Error: You can only self-update PHARs."</p>
[ { "answer_id": 211376, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 6, "selected": true, "text": "<p>Here are few things you could try to remove the responsive image support in 4.4:</p>\n\n<pre><code>/**\n * Disable responsive image support (test!)\n */\n\n// Clean the up the image from wp_get_attachment_image()\nadd_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['sizes'] ) )\n unset( $attr['sizes'] );\n\n if( isset( $attr['srcset'] ) )\n unset( $attr['srcset'] );\n\n return $attr;\n\n }, PHP_INT_MAX );\n\n// Override the calculated image sizes\nadd_filter( 'wp_calculate_image_sizes', '__return_empty_array', PHP_INT_MAX );\n\n// Override the calculated image sources\nadd_filter( 'wp_calculate_image_srcset', '__return_empty_array', PHP_INT_MAX );\n\n// Remove the reponsive stuff from the content\nremove_filter( 'the_content', 'wp_make_content_images_responsive' );\n</code></pre>\n\n<p>but as mentioned by @cybmeta the problem may be elsewhere.</p>\n\n<h2>Force https on <code>srcset</code></h2>\n\n<p>You could do some debugging with the <code>wp_calculate_image_srcset</code> filter and even try this <em>quick-fix</em>:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset', function( $sources )\n{\n foreach( $sources as &amp;$source )\n {\n if( isset( $source['url'] ) )\n $source['url'] = set_url_scheme( $source['url'], 'https' );\n }\n return $sources;\n\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>to set the <em>url scheme</em> to <code>https</code>. Another approach would be to have it schemeless <code>//</code>.</p>\n\n<p>Check out the Codex for other <a href=\"http://codex.wordpress.org/Function_Reference/set_url_scheme\" rel=\"noreferrer\"><code>set_url_scheme()</code></a> options:</p>\n\n<pre><code>$source['url'] = set_url_scheme( $source['url'], null ); \n$source['url'] = set_url_scheme( $source['url'], 'relative' );\n</code></pre>\n\n<p>But you should try to dig deeper and find the root cause.</p>\n\n<h2>Update:</h2>\n\n<p>We could bail out earlier from the <code>wp_calculate_image_srcset()</code> function with:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset_meta', '__return_empty_array' );\n</code></pre>\n\n<p>then using the <code>wp_calculate_image_srcset</code> or <code>max_srcset_image_width</code> filters.</p>\n\n<p>Also updated according to ticket <a href=\"https://core.trac.wordpress.org/ticket/41895\" rel=\"noreferrer\">#41895</a>, to return an empty array instead of false/null.</p>\n" }, { "answer_id": 211418, "author": "joemcgill", "author_id": 85092, "author_profile": "https://wordpress.stackexchange.com/users/85092", "pm_score": 3, "selected": false, "text": "<p>Most likely, the reason the URLs in your <code>srcset</code> attributes are incorrectly showing HTTPS is because the URLs for all images are built using the value of the siteurl option in your wp_options table. If you're serving your front end over HTTPS, you should also change those values (via Settings > General).</p>\n\n<p>Here's the related ticket on the WordPress issue tracking system: <a href=\"https://core.trac.wordpress.org/ticket/34945\">https://core.trac.wordpress.org/ticket/34945</a></p>\n" }, { "answer_id": 211472, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 3, "selected": false, "text": "<p>This will disable the srcset code by eliminating any images wider than 1 pixel.</p>\n\n<pre><code>add_filter( 'max_srcset_image_width', create_function( '', 'return 1;' ) );\n</code></pre>\n\n<p>In the long run, you should try to fix the actual problem. Still, this works if you need a quick fix.</p>\n" }, { "answer_id": 211985, "author": "Trevor", "author_id": 17461, "author_profile": "https://wordpress.stackexchange.com/users/17461", "pm_score": 4, "selected": false, "text": "<p>The simplest and cleanest way to do this is simply this:</p>\n\n<pre><code>add_filter( 'wp_calculate_image_srcset', '__return_false' );\n</code></pre>\n\n<p>To echo what most other folks are saying though, srcset is a good idea and is the future (best practice now), but if you need a quick fix to keep your site working, the above snippet does the job without any hacking.</p>\n\n<p><em>source: <a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/#comment-28662\" rel=\"nofollow noreferrer\">WP Core Blog</a></em></p>\n" }, { "answer_id": 212042, "author": "user2969141", "author_id": 63875, "author_profile": "https://wordpress.stackexchange.com/users/63875", "pm_score": 2, "selected": false, "text": "<p>In Settings/General make sure your WordPress Address (URL) and Site Address (URL) are set to the <a href=\"https://yourdomain.com\" rel=\"nofollow\">https://yourdomain.com</a></p>\n\n<p>See <a href=\"http://wptavern.com/how-to-fix-images-not-loading-in-wordpress-4-4-while-using-ssl\" rel=\"nofollow\">http://wptavern.com/how-to-fix-images-not-loading-in-wordpress-4-4-while-using-ssl</a></p>\n\n<blockquote>\n <p>Joe McGill, who helped lead the effort to get responsive images into\n WordPress, also responded in the forum thread and confirms Cree’s\n suggestion is correct, “If you’re running HTTPS on the front end, you\n should change the URLS for your home and site URL in Settings >\n General so they use the HTTPS scheme,” he said.</p>\n</blockquote>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64298/" ]
I installed wp-cli back in April on my Windows box using composer. I believe with the following command: `composer create-project wp-cli/wp-cli --no-dev` as outlined in the alternate install methods on [here](https://github.com/wp-cli/wp-cli/wiki/Alternative-Install-Methods). I have since used "`composer update --no-dev`" to update but just realized that it is only updating the dependencies and not the wp-cli package itself. If I run a "`wp cli version`" it reports version WP-CLI 0.18.0, yet v0.20.4 is the latest released version. I can't seem to find any way to update wp-cli. I suppose I could just install a new copy each time but that seems silly. Regardless, I did test and if I issue a "`composer create-project wp-cli/wp-cli --no-dev`" in a new directory it downloads the latest version. I also tried "`wp cli update`" but it reports back "Error: You can only self-update PHARs."
Here are few things you could try to remove the responsive image support in 4.4: ``` /** * Disable responsive image support (test!) */ // Clean the up the image from wp_get_attachment_image() add_filter( 'wp_get_attachment_image_attributes', function( $attr ) { if( isset( $attr['sizes'] ) ) unset( $attr['sizes'] ); if( isset( $attr['srcset'] ) ) unset( $attr['srcset'] ); return $attr; }, PHP_INT_MAX ); // Override the calculated image sizes add_filter( 'wp_calculate_image_sizes', '__return_empty_array', PHP_INT_MAX ); // Override the calculated image sources add_filter( 'wp_calculate_image_srcset', '__return_empty_array', PHP_INT_MAX ); // Remove the reponsive stuff from the content remove_filter( 'the_content', 'wp_make_content_images_responsive' ); ``` but as mentioned by @cybmeta the problem may be elsewhere. Force https on `srcset` ----------------------- You could do some debugging with the `wp_calculate_image_srcset` filter and even try this *quick-fix*: ``` add_filter( 'wp_calculate_image_srcset', function( $sources ) { foreach( $sources as &$source ) { if( isset( $source['url'] ) ) $source['url'] = set_url_scheme( $source['url'], 'https' ); } return $sources; }, PHP_INT_MAX ); ``` to set the *url scheme* to `https`. Another approach would be to have it schemeless `//`. Check out the Codex for other [`set_url_scheme()`](http://codex.wordpress.org/Function_Reference/set_url_scheme) options: ``` $source['url'] = set_url_scheme( $source['url'], null ); $source['url'] = set_url_scheme( $source['url'], 'relative' ); ``` But you should try to dig deeper and find the root cause. Update: ------- We could bail out earlier from the `wp_calculate_image_srcset()` function with: ``` add_filter( 'wp_calculate_image_srcset_meta', '__return_empty_array' ); ``` then using the `wp_calculate_image_srcset` or `max_srcset_image_width` filters. Also updated according to ticket [#41895](https://core.trac.wordpress.org/ticket/41895), to return an empty array instead of false/null.
211,415
<p>On the checkout page I have a custom field that gets saved to the order meta data. I need to grab the order meta data and create a custom post type and fill the custom fields with order meta data.</p> <pre><code>add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 ); function my_custom_checkout_field_display_admin_order_meta($order){ global $mypass; echo '&lt;p&gt;&lt;strong&gt;'.__('My Field').':&lt;/strong&gt; ' . get_post_meta( $order-&gt;id, 'My Field', true ) . '&lt;/p&gt;'; $mypass = get_post_meta( $order-&gt;id, 'My Field', true ); } </code></pre> <p>The following functions creates the post on checkout but does not pull in the meta field set in the function above </p> <pre><code>add_action( 'woocommerce_checkout_update_order_meta', 'create_custom_post' ); function create_custom_post($order, $order_id, $posts) { global $posts; $my_post = array( 'post_title' =&gt; 'Page Title', 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_type' =&gt; 'sale', ); $website_url = get_post_meta($order_id-&gt;id, 'My Field', true); $new_post_id = wp_insert_post( $my_post ); update_post_meta($new_post_id, 'My Field', $website_url ); } </code></pre> <p>I have also tried to set a global variable on the function that saves the meta order data</p> <pre><code>function recent_post_page($order_status, $order_id, $post, $checkout ) { global $mypass; $order = new WC_Order( $order_id ); $my_post = array( 'post_title' =&gt; 'Page title', 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_type' =&gt; 'sale', ); $new_post_id = wp_insert_post( $my_post ); update_post_meta($new_post_id, 'My Field', $mypass ); } add_action( 'woocommerce_payment_complete_order_status', 'recent_post_page', 10, 2 ); </code></pre> <p>Any feedback appreciated. </p>
[ { "answer_id": 211424, "author": "Tim Plummer", "author_id": 15236, "author_profile": "https://wordpress.stackexchange.com/users/15236", "pm_score": 0, "selected": false, "text": "<p>Check out <code>$website_url = get_post_meta($order_id-&gt;id, 'My Field', true);</code> You're trying to get the <code>id</code> of <code>$order_id</code>.</p>\n\n<p><code>$order_id</code> is, or should be a string. You will need to do either:</p>\n\n<pre><code>get_post_meta($order_id, 'My Field', true);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>get_post_meta($order-&gt;ID, 'My Field', true);\n</code></pre>\n" }, { "answer_id": 211587, "author": "Nwar", "author_id": 85089, "author_profile": "https://wordpress.stackexchange.com/users/85089", "pm_score": 2, "selected": false, "text": "<p>I managed to figure it out by placing the wp_insert_post function in the same function that saves the order meta data </p>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85089/" ]
On the checkout page I have a custom field that gets saved to the order meta data. I need to grab the order meta data and create a custom post type and fill the custom fields with order meta data. ``` add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 ); function my_custom_checkout_field_display_admin_order_meta($order){ global $mypass; echo '<p><strong>'.__('My Field').':</strong> ' . get_post_meta( $order->id, 'My Field', true ) . '</p>'; $mypass = get_post_meta( $order->id, 'My Field', true ); } ``` The following functions creates the post on checkout but does not pull in the meta field set in the function above ``` add_action( 'woocommerce_checkout_update_order_meta', 'create_custom_post' ); function create_custom_post($order, $order_id, $posts) { global $posts; $my_post = array( 'post_title' => 'Page Title', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_type' => 'sale', ); $website_url = get_post_meta($order_id->id, 'My Field', true); $new_post_id = wp_insert_post( $my_post ); update_post_meta($new_post_id, 'My Field', $website_url ); } ``` I have also tried to set a global variable on the function that saves the meta order data ``` function recent_post_page($order_status, $order_id, $post, $checkout ) { global $mypass; $order = new WC_Order( $order_id ); $my_post = array( 'post_title' => 'Page title', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_type' => 'sale', ); $new_post_id = wp_insert_post( $my_post ); update_post_meta($new_post_id, 'My Field', $mypass ); } add_action( 'woocommerce_payment_complete_order_status', 'recent_post_page', 10, 2 ); ``` Any feedback appreciated.
I managed to figure it out by placing the wp\_insert\_post function in the same function that saves the order meta data
211,436
<p>I'm attempting to modify a WordPress theme so that it appends a version number to a particular stylesheet. This is all done on a local development machine, tested on a staging server, too, for good measure. Following the instructions here: <a href="https://www.mojowill.com/developer/get-your-wordpress-css-changes-noticed-immediately/" rel="nofollow">https://www.mojowill.com/developer/get-your-wordpress-css-changes-noticed-immediately/</a>, I added <code>filemtime( get_template_directory() . '/css/main.css' )</code> into the arguments passed through <code>wp_register_style</code></p> <p>From:</p> <p><code>wp_register_style('style', get_template_directory_uri() . '/css/style.css', array(), '', 'all');</code></p> <p>to</p> <p><code>wp_register_style('style', get_template_directory_uri() . '/css/style.css', array(), 'filemtime( get_template_directory_uri() . '/css/style.css'', 'all');</code></p> <p>No soap. Viewing the source of the rendered page, I see the stylesheet link has no version appended to it.</p> <p>I tried pulling the <code>filemtime</code> function out of the <code>$ver</code> slot, and replacing it with a static value like 1.0, and that didn't work, either. Finally, I skipped the <code>$ver</code> argument, and changed the path to a versioned file, like so:</p> <p><code>wp_register_style('style', get_template_directory_uri() . '/css/style.css?ver=1.0', array(), '', 'all');</code></p> <p>Still nothing. Why would WordPress refuse to acknowledge these updates? No server-side caching or plugins that I could imagine would influence this process. Is there something very simple I'm missing?</p> <p>Thanks much</p> <p>James</p> <p>edit: Here's the entire relevant code block.</p> <pre><code>function minikit_register_js_and_css() { if (!is_admin()) { wp_register_style('style', get_template_directory_uri() . '/css/style.css?ver=1.1', array(), '', 'all'); wp_enqueue_style('style'); } } </code></pre>
[ { "answer_id": 211438, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Make sure to <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow\">wp_enqueue_style ('unique-style-name' )</a>.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );\n\nfunction register_plugin_styles() {\n wp_register_style( 'unique-style-name', plugins_url( 'my-plugin/css/plugin.css' ) );\n wp_enqueue_style( 'unique-style-name' );\n}\n</code></pre>\n" }, { "answer_id": 211440, "author": "Felix", "author_id": 69880, "author_profile": "https://wordpress.stackexchange.com/users/69880", "pm_score": 0, "selected": false, "text": "<p>Some possibilities:</p>\n\n<ul>\n<li>Try a different identifier other than 'style', make it unique to your plugin, something like 'myplugin_styles'</li>\n<li>Is <code>wp_head()</code> called on you <code>header.php</code> file? Maybe the stylesheet code is hardcoded on the template.</li>\n<li>Are you running any caching plugins? If so deactivate them.</li>\n<li>This one is trickier, but are you sure this is the only <code>wp_register_style</code> declaration on your plugin? Maybe is being set again later on the same file or on another file.</li>\n</ul>\n\n<p>Those are the first ideas that come to mind. I hope it helps</p>\n" }, { "answer_id": 225232, "author": "jamesfacts", "author_id": 76674, "author_profile": "https://wordpress.stackexchange.com/users/76674", "pm_score": 3, "selected": true, "text": "<p>At long last, I have identified the issue. The theme I was working in used the <a href=\"https://github.com/stefanolaru/minikit\" rel=\"nofollow\">Minikit theme starter</a>, which has a function that strips version numbers. </p>\n\n<p><code>function minikit_remove_wp_ver_css_js($src) {\n if (strpos($src, 'ver='))\n $src = remove_query_arg('ver', $src);\n return $src;\n}\n</code></p>\n\n<p>Naturally, the version numbers returned once I stopped calling this function. </p>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211436", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76674/" ]
I'm attempting to modify a WordPress theme so that it appends a version number to a particular stylesheet. This is all done on a local development machine, tested on a staging server, too, for good measure. Following the instructions here: <https://www.mojowill.com/developer/get-your-wordpress-css-changes-noticed-immediately/>, I added `filemtime( get_template_directory() . '/css/main.css' )` into the arguments passed through `wp_register_style` From: `wp_register_style('style', get_template_directory_uri() . '/css/style.css', array(), '', 'all');` to `wp_register_style('style', get_template_directory_uri() . '/css/style.css', array(), 'filemtime( get_template_directory_uri() . '/css/style.css'', 'all');` No soap. Viewing the source of the rendered page, I see the stylesheet link has no version appended to it. I tried pulling the `filemtime` function out of the `$ver` slot, and replacing it with a static value like 1.0, and that didn't work, either. Finally, I skipped the `$ver` argument, and changed the path to a versioned file, like so: `wp_register_style('style', get_template_directory_uri() . '/css/style.css?ver=1.0', array(), '', 'all');` Still nothing. Why would WordPress refuse to acknowledge these updates? No server-side caching or plugins that I could imagine would influence this process. Is there something very simple I'm missing? Thanks much James edit: Here's the entire relevant code block. ``` function minikit_register_js_and_css() { if (!is_admin()) { wp_register_style('style', get_template_directory_uri() . '/css/style.css?ver=1.1', array(), '', 'all'); wp_enqueue_style('style'); } } ```
At long last, I have identified the issue. The theme I was working in used the [Minikit theme starter](https://github.com/stefanolaru/minikit), which has a function that strips version numbers. `function minikit_remove_wp_ver_css_js($src) { if (strpos($src, 'ver=')) $src = remove_query_arg('ver', $src); return $src; }` Naturally, the version numbers returned once I stopped calling this function.
211,467
<p>Does anyone know how to remove the WordPress JSON API links in the header tag?</p> <pre><code>&lt;head&gt; ... &lt;link rel='https://api.w.org/' href='http://example.com/wp-json/' /&gt; &lt;link rel="alternate" type="application/json+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=..." /&gt; &lt;link rel="alternate" type="text/xml+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=..." /&gt; &lt;/head&gt; </code></pre> <p>I'd like to avoid using a plugin. If possible, is there a way to remove them with the remove_action function?</p> <pre><code>remove_action( 'wp_head', 'rsd_link' ); </code></pre>
[ { "answer_id": 211469, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 6, "selected": true, "text": "<p>I see in filters.php \"add_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 )\" Which makes me think this should do the trick to remove <code>rel='https://api.w.org/'</code>.</p>\n\n<pre><code>remove_action( 'wp_head', 'rest_output_link_wp_head' );\n</code></pre>\n\n<p>The rest... * <em>cough</em> * seem to be in default-filters.php</p>\n\n<pre><code>remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );\n</code></pre>\n\n<p>To remove the <a href=\"https://developer.wordpress.org/reference/functions/rest_output_link_header/\" rel=\"noreferrer\">rest_output_link_header</a></p>\n\n<pre><code>remove_action( 'template_redirect', 'rest_output_link_header', 11 );\n</code></pre>\n\n<p>Reference</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_oembed_add_discovery_links/\" rel=\"noreferrer\">wp_oembed_add_discovery_links</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/rest_output_link_wp_head/\" rel=\"noreferrer\">rest_output_link_wp_head</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/rest_output_link_header/\" rel=\"noreferrer\">rest_output_link_header</a></li>\n</ul>\n" }, { "answer_id": 212472, "author": "Jentan Bernardus", "author_id": 34502, "author_profile": "https://wordpress.stackexchange.com/users/34502", "pm_score": 5, "selected": false, "text": "<p>This custom function should help removing all links in the header and footer - you may put it inside the <code>functions.php</code> file of your active theme;</p>\n\n<pre><code>function remove_json_api () {\n\n // Remove the REST API lines from the HTML Header\n remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );\n remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );\n\n // Remove the REST API endpoint.\n remove_action( 'rest_api_init', 'wp_oembed_register_route' );\n\n // Turn off oEmbed auto discovery.\n add_filter( 'embed_oembed_discover', '__return_false' );\n\n // Don't filter oEmbed results.\n remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );\n\n // Remove oEmbed discovery links.\n remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );\n\n // Remove oEmbed-specific JavaScript from the front-end and back-end.\n remove_action( 'wp_head', 'wp_oembed_add_host_js' );\n\n // Remove all embeds rewrite rules.\n add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );\n\n}\nadd_action( 'after_setup_theme', 'remove_json_api' );\n</code></pre>\n\n<p>And this snippet completely disable the REST API and shows the content below when you visit <code>http://example.com/wp-json/</code>, were <code>example.com</code> is the domain name of your website;</p>\n\n<pre><code>{\"code\":\"rest_disabled\",\"message\":\"The REST API is disabled on this site.\"}\n</code></pre>\n\n<p>In order to disable WordPress REST API, use the snippet below;</p>\n\n<pre><code>function disable_json_api () {\n\n // Filters for WP-API version 1.x\n add_filter( 'json_enabled', '__return_false' );\n add_filter( 'json_jsonp_enabled', '__return_false' );\n\n // Filters for WP-API version 2.x\n add_filter( 'rest_enabled', '__return_false' );\n add_filter( 'rest_jsonp_enabled', '__return_false' );\n\n}\nadd_action( 'after_setup_theme', 'disable_json_api' );\n</code></pre>\n" }, { "answer_id": 366296, "author": "Jodyshop", "author_id": 127580, "author_profile": "https://wordpress.stackexchange.com/users/127580", "pm_score": 2, "selected": false, "text": "<p>The best solution and easy way to disable oEmbed discovery links and wp-embed.min.js is by adding this code snippet in your theme (<code>function.php</code>).</p>\n\n<p><code>remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );\nremove_action( 'wp_head', 'wp_oembed_add_host_js' );\nremove_action('rest_api_init', 'wp_oembed_register_route');\nremove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);</code></p>\n\n<p>Hope this can help someone as the above solutions don't work for me while using the latest version of WordPress.</p>\n" } ]
2015/12/10
[ "https://wordpress.stackexchange.com/questions/211467", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18814/" ]
Does anyone know how to remove the WordPress JSON API links in the header tag? ``` <head> ... <link rel='https://api.w.org/' href='http://example.com/wp-json/' /> <link rel="alternate" type="application/json+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=..." /> <link rel="alternate" type="text/xml+oembed" href="http://example.com/wp-json/oembed/1.0/embed?url=..." /> </head> ``` I'd like to avoid using a plugin. If possible, is there a way to remove them with the remove\_action function? ``` remove_action( 'wp_head', 'rsd_link' ); ```
I see in filters.php "add\_action( 'wp\_head', 'rest\_output\_link\_wp\_head', 10, 0 )" Which makes me think this should do the trick to remove `rel='https://api.w.org/'`. ``` remove_action( 'wp_head', 'rest_output_link_wp_head' ); ``` The rest... \* *cough* \* seem to be in default-filters.php ``` remove_action( 'wp_head', 'wp_oembed_add_discovery_links' ); ``` To remove the [rest\_output\_link\_header](https://developer.wordpress.org/reference/functions/rest_output_link_header/) ``` remove_action( 'template_redirect', 'rest_output_link_header', 11 ); ``` Reference * [wp\_oembed\_add\_discovery\_links](https://developer.wordpress.org/reference/functions/wp_oembed_add_discovery_links/) * [rest\_output\_link\_wp\_head](https://developer.wordpress.org/reference/functions/rest_output_link_wp_head/) * [rest\_output\_link\_header](https://developer.wordpress.org/reference/functions/rest_output_link_header/)
211,481
<p>I'm currently trying to work on a WordPress theme based on <a href="https://roots.io/sage/" rel="nofollow">Sage</a>. The stage I'm at is creating custom controls to display on the customize screen for WordPress where you typically change things like the site title or theme colors if you're an end user. </p> <p>It seems that the new setting I'm trying to add with <code>add_setting</code> isn't actually creating a database entry (Calling <code>get_theme_mod</code> on that particular setting returns nothing). I'm thinking that it has something to do with the add_control method but I've checked the <a href="https://codex.wordpress.org/Class_Reference%5CWP_Customize_Manager%5Cadd_control" rel="nofollow">WordPress Documentation</a> on this and I have it matching as far I can tell.</p> <pre><code>namespace Roots\Sage\Customizer; use Roots\Sage\Assets; /** * Add customization settings for the theme */ function customize_register($wp_customize) { ////////////////////////// // WIDGET STYLE OPTIONS // ////////////////////////// $wp_customize-&gt;add_section( 'widget_style_section', array( 'title' =&gt; __('Widget Styling', __NAMESPACE__), 'priority' =&gt; 115, )); $wp_customize-&gt;add_setting( 'widget_list_style', array( 'default' =&gt; 'hide', 'transport' =&gt; 'postMessage', )); $wp_customize-&gt;add_control( 'widget_list_style_control', array( 'label' =&gt; __( 'Display List Style?', __NAMESPACE__), 'Description' =&gt; __('Removes the symbols next to bulleted and unbulleted lists in Widgets', __NAMESPACE__), 'section' =&gt; 'widget_style_section', 'settings' =&gt; 'widget_list_style', 'type' =&gt; 'radio', // TODO: CONTROL IS CONFUSED ABOUT WHAT TYPE IT IS, THATS WHY NO REFRESH 'choices' =&gt; array( 'hide' =&gt; __('Hide'), 'show' =&gt; __('Show'), ), )); // Add postMessage support $wp_customize-&gt;get_setting('blogname')-&gt;transport = 'postMessage'; $wp_customize-&gt;get_setting('blogdescription')-&gt;transport = 'postMessage'; // TEST - To see if widget_list_style is storing properly echo get_theme_mod('widget_list_style'); } add_action('customize_register', __NAMESPACE__ . '\\customize_register'); </code></pre>
[ { "answer_id": 211482, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": -1, "selected": false, "text": "<p>From <a href=\"https://codex.wordpress.org/Theme_Customization_API\" rel=\"nofollow\">Theme_Customization_API</a>:<br>\nTo add your own options to the customizer, you need to use a minimum of 2 hooks:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/customize_register\" rel=\"nofollow\">customize_register</a><br>\nThis hook allows you define new customizer panels, sections, settings, and controls.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\">wp_head</a><br>\nThis hook allows you to output custom-generated CSS so that your changes show up correctly on the live website.</p>\n\n<p>So your <code>customize_register</code> action look like(replace your theme name with <em>mytheme</em>):</p>\n\n<pre><code>function mytheme_customize_register( $wp_customize ) {\n //All our sections, settings, and controls will be added here\n}\nadd_action( 'customize_register', 'mytheme_customize_register' );\n</code></pre>\n\n<p>Next, you need to define your settings, then your sections, then your controls (controls need a section and a setting to function).</p>\n\n<p><strong>Note</strong>: Only set this to '<em>postMessage</em>' if you are writing custom <em>Javascript</em> to control the Theme Customizer's live preview.</p>\n" }, { "answer_id": 257236, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 1, "selected": false, "text": "<p>The problem with the code sample is that the setting is using <code>widget_</code> as the prefix. This is a reserved prefix for <em>widgets</em>, per the <a href=\"https://developer.wordpress.org/themes/customize-api/customizer-objects/#settings\" rel=\"nofollow noreferrer\">customizer handbook</a>:</p>\n\n<blockquote>\n <p><strong>Important:</strong> Do not use a setting ID that looks like <code>widget_*</code>, <code>sidebars_widgets[*]</code>, <code>nav_menu[*]</code>, or <code>nav_menu_item[*]</code>. These setting ID patterns are reserved for widget instances, sidebars, nav menus, and nav menu items respectively. If you need to use “widget” in your setting ID, use it as a suffix instead of a prefix, for example “<code>homepage_widget</code>”.</p>\n</blockquote>\n\n<p>Here is the modified code which works as expected:</p>\n\n<pre><code>&lt;?php\n\nnamespace Roots\\Sage\\Customizer;\n\nuse Roots\\Sage\\Assets;\n\n/**\n * Add customization settings for the theme\n */\nfunction customize_register($wp_customize) {\n //////////////////////////\n // WIDGET STYLE OPTIONS //\n //////////////////////////\n $wp_customize-&gt;add_section( 'style_section_widget', array(\n 'title' =&gt; __('Widget Styling', __NAMESPACE__),\n 'priority' =&gt; 115,\n ));\n\n $wp_customize-&gt;add_setting( 'list_style_widget', array(\n 'default' =&gt; 'hide',\n 'transport' =&gt; 'postMessage',\n ));\n\n $wp_customize-&gt;add_control( 'widget_list_style_control', array(\n 'label' =&gt; __( 'Display List Style?', __NAMESPACE__),\n 'Description' =&gt; __('Removes the symbols next to bulleted and unbulleted lists in Widgets', __NAMESPACE__),\n 'section' =&gt; 'style_section_widget',\n 'settings' =&gt; 'list_style_widget',\n 'type' =&gt; 'radio',\n 'choices' =&gt; array(\n 'hide' =&gt; __('Hide'),\n 'show' =&gt; __('Show'),\n ),\n ));\n\n // Add postMessage support\n $wp_customize-&gt;get_setting('blogname')-&gt;transport = 'postMessage';\n $wp_customize-&gt;get_setting('blogdescription')-&gt;transport = 'postMessage';\n}\n\nadd_action('customize_register', __NAMESPACE__ . '\\\\customize_register', 11);\n</code></pre>\n\n<p>Note also that I changed the priority for <code>customize_register</code> from 10 (the default) to 11 since the <code>blogname</code> and <code>blogdescription</code> settings may not be registered at that point.</p>\n" } ]
2015/12/11
[ "https://wordpress.stackexchange.com/questions/211481", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85138/" ]
I'm currently trying to work on a WordPress theme based on [Sage](https://roots.io/sage/). The stage I'm at is creating custom controls to display on the customize screen for WordPress where you typically change things like the site title or theme colors if you're an end user. It seems that the new setting I'm trying to add with `add_setting` isn't actually creating a database entry (Calling `get_theme_mod` on that particular setting returns nothing). I'm thinking that it has something to do with the add\_control method but I've checked the [WordPress Documentation](https://codex.wordpress.org/Class_Reference%5CWP_Customize_Manager%5Cadd_control) on this and I have it matching as far I can tell. ``` namespace Roots\Sage\Customizer; use Roots\Sage\Assets; /** * Add customization settings for the theme */ function customize_register($wp_customize) { ////////////////////////// // WIDGET STYLE OPTIONS // ////////////////////////// $wp_customize->add_section( 'widget_style_section', array( 'title' => __('Widget Styling', __NAMESPACE__), 'priority' => 115, )); $wp_customize->add_setting( 'widget_list_style', array( 'default' => 'hide', 'transport' => 'postMessage', )); $wp_customize->add_control( 'widget_list_style_control', array( 'label' => __( 'Display List Style?', __NAMESPACE__), 'Description' => __('Removes the symbols next to bulleted and unbulleted lists in Widgets', __NAMESPACE__), 'section' => 'widget_style_section', 'settings' => 'widget_list_style', 'type' => 'radio', // TODO: CONTROL IS CONFUSED ABOUT WHAT TYPE IT IS, THATS WHY NO REFRESH 'choices' => array( 'hide' => __('Hide'), 'show' => __('Show'), ), )); // Add postMessage support $wp_customize->get_setting('blogname')->transport = 'postMessage'; $wp_customize->get_setting('blogdescription')->transport = 'postMessage'; // TEST - To see if widget_list_style is storing properly echo get_theme_mod('widget_list_style'); } add_action('customize_register', __NAMESPACE__ . '\\customize_register'); ```
The problem with the code sample is that the setting is using `widget_` as the prefix. This is a reserved prefix for *widgets*, per the [customizer handbook](https://developer.wordpress.org/themes/customize-api/customizer-objects/#settings): > > **Important:** Do not use a setting ID that looks like `widget_*`, `sidebars_widgets[*]`, `nav_menu[*]`, or `nav_menu_item[*]`. These setting ID patterns are reserved for widget instances, sidebars, nav menus, and nav menu items respectively. If you need to use “widget” in your setting ID, use it as a suffix instead of a prefix, for example “`homepage_widget`”. > > > Here is the modified code which works as expected: ``` <?php namespace Roots\Sage\Customizer; use Roots\Sage\Assets; /** * Add customization settings for the theme */ function customize_register($wp_customize) { ////////////////////////// // WIDGET STYLE OPTIONS // ////////////////////////// $wp_customize->add_section( 'style_section_widget', array( 'title' => __('Widget Styling', __NAMESPACE__), 'priority' => 115, )); $wp_customize->add_setting( 'list_style_widget', array( 'default' => 'hide', 'transport' => 'postMessage', )); $wp_customize->add_control( 'widget_list_style_control', array( 'label' => __( 'Display List Style?', __NAMESPACE__), 'Description' => __('Removes the symbols next to bulleted and unbulleted lists in Widgets', __NAMESPACE__), 'section' => 'style_section_widget', 'settings' => 'list_style_widget', 'type' => 'radio', 'choices' => array( 'hide' => __('Hide'), 'show' => __('Show'), ), )); // Add postMessage support $wp_customize->get_setting('blogname')->transport = 'postMessage'; $wp_customize->get_setting('blogdescription')->transport = 'postMessage'; } add_action('customize_register', __NAMESPACE__ . '\\customize_register', 11); ``` Note also that I changed the priority for `customize_register` from 10 (the default) to 11 since the `blogname` and `blogdescription` settings may not be registered at that point.
211,496
<p>I'm using Visual Composer, but I think it has more to do with WordPress than VC ;-) I did a shortcode (with the <a href="https://wpbakery.atlassian.net/wiki/display/VC/Adding+Custom+Shortcode+to+Grid+Builder" rel="nofollow noreferrer">VC API</a>) to get the content of a post. Here it is (in functions.php):</p> <pre><code>add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' ); function my_module_add_grid_shortcodes( $shortcodes ) { $shortcodes['vc_post_id'] = array( 'name' =&gt; __( 'Post content', 'fluidtopics' ), 'base' =&gt; 'vc_post_content', 'category' =&gt; __( 'Content', 'fluidtopics' ), 'description' =&gt; __( 'Show current post content', 'fluidtopics' ), 'post_type' =&gt; Vc_Grid_Item_Editor::postType(), ); return $shortcodes; } add_shortcode( 'vc_post_content', 'vc_post_content_render' ); function vc_post_content_render() { return '{{ post_data:post_content }}'; } </code></pre> <p>The content is really rendered. The layout provided by VC is achieved through shortcodes too... which are not parsed and displayed with the content. I wonder if it's possible to get these shortcodes parsed ?</p> <p>This can be viewed here: <a href="https://www.fluidtopics.com/whats-new-2/" rel="nofollow noreferrer">https://www.fluidtopics.com/whats-new-2/</a> (third tab, you'll see [vc_row] etc.)</p> <p>Thanks a lot for any help !</p>
[ { "answer_id": 211519, "author": "Douglas.Sesar", "author_id": 19945, "author_profile": "https://wordpress.stackexchange.com/users/19945", "pm_score": -1, "selected": false, "text": "<p>you could try <code>do_shortcode()</code> - <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow\">Code Reference</a></p>\n\n<pre><code>add_shortcode( 'vc_post_content', 'vc_post_content_render' );\nfunction vc_post_content_render() {\nreturn do_shortcode('{{ post_data:post_content }}');\n}\n</code></pre>\n\n<p>That should filter out the remaining shortcodes within the returned content.</p>\n" }, { "answer_id": 279325, "author": "Valentin", "author_id": 85151, "author_profile": "https://wordpress.stackexchange.com/users/85151", "pm_score": 2, "selected": false, "text": "<p>Here's the code given by the VC team. And it works.</p>\n\n<pre><code>// display content in grid\nadd_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' );\nfunction my_module_add_grid_shortcodes( $shortcodes ) {\n$shortcodes['vc_post_content'] = array(\n 'name' =&gt; __( 'Post content', 'fluidtopics' ),\n 'base' =&gt; 'vc_post_content',\n 'category' =&gt; __( 'Content', 'fluidtopics' ),\n 'description' =&gt; __( 'Show current post content', 'fluidtopics' ),\n 'post_type' =&gt; Vc_Grid_Item_Editor::postType(),\n);\n\nreturn $shortcodes;\n}\n\nadd_shortcode( 'vc_post_content', 'vc_post_content_render' );\nfunction vc_post_content_render() {\nreturn '{{ do_shortcode_post_content }}';\n}\n\nadd_filter( 'vc_gitem_template_attribute_do_shortcode_post_content', 'vc_gitem_template_attribute_do_shortcode_post_content', 10, 2 );\n\nfunction vc_gitem_template_attribute_do_shortcode_post_content( $value, $data ) {\n/**\n * @var null|Wp_Post $post ;\n * @var string $data ;\n */\nextract( array_merge( array(\n 'post' =&gt; null,\n 'data' =&gt; '',\n), $data ) );\n$atts_extended = array();\nparse_str( $data, $atts_extended );\n\nWPBMap::addAllMappedShortcodes();\n\n$output = do_shortcode( $post-&gt;post_content );\nob_start();\n// do_action( 'wp_enqueue_scripts' );\n// wp_print_styles();\n// wp_print_scripts();\n// wp_print_footer_scripts();\n$output .= ob_get_clean();\n\nreturn $output;\n}\n</code></pre>\n" } ]
2015/12/11
[ "https://wordpress.stackexchange.com/questions/211496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85151/" ]
I'm using Visual Composer, but I think it has more to do with WordPress than VC ;-) I did a shortcode (with the [VC API](https://wpbakery.atlassian.net/wiki/display/VC/Adding+Custom+Shortcode+to+Grid+Builder)) to get the content of a post. Here it is (in functions.php): ``` add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' ); function my_module_add_grid_shortcodes( $shortcodes ) { $shortcodes['vc_post_id'] = array( 'name' => __( 'Post content', 'fluidtopics' ), 'base' => 'vc_post_content', 'category' => __( 'Content', 'fluidtopics' ), 'description' => __( 'Show current post content', 'fluidtopics' ), 'post_type' => Vc_Grid_Item_Editor::postType(), ); return $shortcodes; } add_shortcode( 'vc_post_content', 'vc_post_content_render' ); function vc_post_content_render() { return '{{ post_data:post_content }}'; } ``` The content is really rendered. The layout provided by VC is achieved through shortcodes too... which are not parsed and displayed with the content. I wonder if it's possible to get these shortcodes parsed ? This can be viewed here: <https://www.fluidtopics.com/whats-new-2/> (third tab, you'll see [vc\_row] etc.) Thanks a lot for any help !
Here's the code given by the VC team. And it works. ``` // display content in grid add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' ); function my_module_add_grid_shortcodes( $shortcodes ) { $shortcodes['vc_post_content'] = array( 'name' => __( 'Post content', 'fluidtopics' ), 'base' => 'vc_post_content', 'category' => __( 'Content', 'fluidtopics' ), 'description' => __( 'Show current post content', 'fluidtopics' ), 'post_type' => Vc_Grid_Item_Editor::postType(), ); return $shortcodes; } add_shortcode( 'vc_post_content', 'vc_post_content_render' ); function vc_post_content_render() { return '{{ do_shortcode_post_content }}'; } add_filter( 'vc_gitem_template_attribute_do_shortcode_post_content', 'vc_gitem_template_attribute_do_shortcode_post_content', 10, 2 ); function vc_gitem_template_attribute_do_shortcode_post_content( $value, $data ) { /** * @var null|Wp_Post $post ; * @var string $data ; */ extract( array_merge( array( 'post' => null, 'data' => '', ), $data ) ); $atts_extended = array(); parse_str( $data, $atts_extended ); WPBMap::addAllMappedShortcodes(); $output = do_shortcode( $post->post_content ); ob_start(); // do_action( 'wp_enqueue_scripts' ); // wp_print_styles(); // wp_print_scripts(); // wp_print_footer_scripts(); $output .= ob_get_clean(); return $output; } ```
211,505
<p>I am trying to change the background for a the 'recent posts' widget in my Wordpress theme. </p> <p>My problem is that Wordpress generates ids like <code>recent-posts-2</code> and so on, so how can I address this id in css. I intend to create an inclusive id in css to address which includes all automatically generated IDs.</p> <p>Something like:</p> <pre><code>#recent-posts-*{ background-color: #eee; } </code></pre> <p>which, of course does not work.</p> <p>Any ideas will be appreciated.</p>
[ { "answer_id": 211506, "author": "ajax20", "author_id": 85160, "author_profile": "https://wordpress.stackexchange.com/users/85160", "pm_score": 0, "selected": false, "text": "<p>Ok, I seem to have found the answer to my own question with the help of the following link.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5110249/wildcard-in-css-for-classes\">Wildcard in css for classes</a></li>\n</ul>\n\n<p>Here is the code:</p>\n\n<pre><code>li[id^=\"recent-posts-\"], li[id*=\" recent-posts-\"] {\n background-color:#eee; \n}\n</code></pre>\n" }, { "answer_id": 211514, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 1, "selected": false, "text": "<p>Use a plugin to add custom css classes. This plugin does just that and a little more: <a href=\"https://wordpress.org/plugins/widget-css-classes/\" rel=\"nofollow\">https://wordpress.org/plugins/widget-css-classes/</a></p>\n\n<p>For example, add the class <code>.recent-posts</code> to the recent posts widgets. Then you should be able to style them just like any other css class.</p>\n" } ]
2015/12/11
[ "https://wordpress.stackexchange.com/questions/211505", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85160/" ]
I am trying to change the background for a the 'recent posts' widget in my Wordpress theme. My problem is that Wordpress generates ids like `recent-posts-2` and so on, so how can I address this id in css. I intend to create an inclusive id in css to address which includes all automatically generated IDs. Something like: ``` #recent-posts-*{ background-color: #eee; } ``` which, of course does not work. Any ideas will be appreciated.
Use a plugin to add custom css classes. This plugin does just that and a little more: <https://wordpress.org/plugins/widget-css-classes/> For example, add the class `.recent-posts` to the recent posts widgets. Then you should be able to style them just like any other css class.
211,556
<p>Some call it light OCD, some might call it security risk. I just don't like how it throws it all in there, especially template names. </p> <p>How to only assign page id or even better - slug?</p> <p>Note that this is in header template, it should output current page's id / slug.</p> <p>All "professional", high quality WP sites I've examined, doesn't have that kind of mess.</p> <pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt; | v &lt;body class="home page page-id-495 page-template page-template-template-home-slideshow page-template-template-home-slideshow-php logged-in"&gt; </code></pre>
[ { "answer_id": 211558, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>Honestly, it's source code. The only people who see it are you and other developers. Anybody casually visiting your website will never know or understand this stuff so really there's no harm keeping it there. <em>Buttttt...</em> if you want to get rid of it you could filter <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\"><code>body_class</code></a>:</p>\n\n<pre><code>function custom_body_class( $classes ) {\n global $post;\n\n if( isset( $post ) &amp;&amp; is_object( $post ) ) {\n $classes = array( \"page-{$post-&gt;ID}\" );\n }\n\n return $classes;\n}\nadd_filter( 'body_class', 'custom_body_class' );\n</code></pre>\n" }, { "answer_id": 211560, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 0, "selected": false, "text": "<p>Here's how to filter the body_class(). This will only use the page slug if you have it, (and whatever classes that are added through additional filters in your functions, such as customize-support). </p>\n\n<pre><code> function wpse211556_body_classes($classes) {\n unset($classes);\n $slug = strtolower(str_replace(' ', '-', trim(get_bloginfo('name'))));\n $classes[] = $slug;\n return $classes;\n }\n add_filter('body_class', 'wpse211556_body_classes');\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class</a></p>\n" }, { "answer_id": 211563, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>\"Some\" may call this all kinds of things, but that doesn't make \"them\" correct. </p>\n\n<p>As a \"page load\" problem, these classes are trivial. They add very few characters to a page. </p>\n\n<p>As a security problem, also trivial. Most have zero security consequence at all-- so what it this is a \"page\"--, and those that do have only minor consequences and only if the custom template is written very, very poorly. Additionally, most template names can be guessed by thinking about the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a> built into Core, so removing the classes gains you very little. What you've got is something closely related to <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow\">\"premature optimization\"</a>.</p>\n\n<p>You should also be aware that removing the classes could potentially break formatting provided by themes or plugins, as these can, and reasonable should be able to, depend upon Core classes. </p>\n\n<p>You are also removing <code>admin-bar</code> and <code>logged-in</code> classes, which could effect <code>Core</code> functionality. </p>\n\n<p>However, the <code>body_class</code> filter lets you do what you want. The following will very aggressively remove all but the <code>postid-{ID}</code> class.</p>\n\n<pre><code>function body_class_wpse_211556($classes) {\n $qobj = get_queried_object();\n // var_dump($qobj); die;\n $classes = array();\n if (!empty($qobj) &amp;&amp; is_a($qobj,'wp_post')) {\n $classes[] ='postid-'.$qobj-&gt;ID;\n }\n return $classes;\n}\nadd_filter('body_class','body_class_wpse_211556',PHP_INT_MAX);\n</code></pre>\n" } ]
2015/12/11
[ "https://wordpress.stackexchange.com/questions/211556", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
Some call it light OCD, some might call it security risk. I just don't like how it throws it all in there, especially template names. How to only assign page id or even better - slug? Note that this is in header template, it should output current page's id / slug. All "professional", high quality WP sites I've examined, doesn't have that kind of mess. ``` <body <?php body_class(); ?>> | v <body class="home page page-id-495 page-template page-template-template-home-slideshow page-template-template-home-slideshow-php logged-in"> ```
Honestly, it's source code. The only people who see it are you and other developers. Anybody casually visiting your website will never know or understand this stuff so really there's no harm keeping it there. *Buttttt...* if you want to get rid of it you could filter [`body_class`](https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class): ``` function custom_body_class( $classes ) { global $post; if( isset( $post ) && is_object( $post ) ) { $classes = array( "page-{$post->ID}" ); } return $classes; } add_filter( 'body_class', 'custom_body_class' ); ```
211,565
<h1>Update 2016-01-21</h1> <p>All current testing on my end is being done on fresh installs of 4.4.1 with the following settings: <code>Plain permalinks</code> <code>Twentysixteen Theme</code> <code>No plugins activated</code></p> <p><strong>If the post only has 1 page</strong> (ie <code>&lt;!--nextpage--&gt;</code> doesn't appear in the post) then the <strong>extra pages are appended successfully</strong> (even if you append multiple extra pages&sup1;).</p> <pre><code>Welcome to WordPress. This is your first post. Edit or delete it, then start writing! </code></pre> <p><strong>If the post has 2+ pages</strong> then the extra pages <strong>404 and canonical redirect</strong> to page 1 of the post.</p> <pre><code>Welcome to WordPress. This is your first post. Edit or delete it, then start writing! &lt;!--nextpage--&gt; This is page 2 </code></pre> <p>In the second case <code>$wp_query-&gt;queried_object</code> is empty once you hit the extra pages. You'll need to disable the canonical redirect to see this <code>remove_filter('template_redirect', 'redirect_canonical');</code></p> <p>Both of the following core fixes have been tried, separately and together, with no change in behavior: <a href="https://core.trac.wordpress.org/ticket/35344#comment:16">https://core.trac.wordpress.org/ticket/35344#comment:16</a></p> <p><a href="https://core.trac.wordpress.org/ticket/35344#comment:34">https://core.trac.wordpress.org/ticket/35344#comment:34</a></p> <p>For ease of use this is the code I'm currently testing with:</p> <pre><code>add_action('template_redirect', 'custom_content_one'); function custom_content_one() { global $post; $content = "\n&lt;!--nextpage--&gt;\nThis is the extra page v1"; $post-&gt;post_content .= $content; } add_filter('content_pagination', 'custom_content_two', 10, 2); function custom_content_two($pages, $post) { if ( in_the_loop() &amp;&amp; 'post' === $post-&gt;post_type ) { $content = "This is the extra page v2"; $pages[] = $content; } return $pages; } add_action('the_post', 'custom_content_three'); function custom_content_three() { global $multipage, $numpages, $pages; $content = "This is the extra page v3"; $multipage = 1; $numpages++; $pages[] = $content; } </code></pre> <p>&sup1;This is the code I used to test multiple extra pages on a single page post</p> <pre><code>add_action('template_redirect', 'custom_content_one'); function custom_content_one() { global $post; $content = "\n&lt;!--nextpage--&gt;\nThis is the extra page v1-1\n&lt;!--nextpage--&gt;\nThis is the extra page v1-2\n&lt;!--nextpage--&gt;\nThis is the extra page v1-3"; $post-&gt;post_content .= $content; } </code></pre> <h1>Original Question</h1> <p>Prior to 4.4 I was able to append an additional page to a mutlipage post with the following:</p> <pre><code>add_action('template_redirect', 'custom_content'); function custom_content() { global $post; $content = html_entity_decode(stripslashes(get_option('custom_content'))); $post-&gt;post_content .= $content; } </code></pre> <p>With get_option('custom_content') being something like:</p> <pre><code>&lt;!--nextpage--&gt; Hello World </code></pre> <p>Since upgrading to 4.4 the code has not worked; navigating to the additional page triggers a 404 error and <a href="https://developer.wordpress.org/reference/functions/redirect_canonical/">redirect_canonical</a> sends them back to the permalink of the post. Disabling redirect_canonical allows me to view the extra page and the additonal content is there, but it still triggers a 404 error.</p> <p>I've tried a number of workarounds, none of which resolve the 404 error, including:</p> <pre><code>add_action('the_post', 'custom_content'); function custom_content() { global $multipage, $numpages, $pages; $content = html_entity_decode(stripslashes(get_option('custom_content'))); $multipage = 1; // ensure post is considered multipage: needed for single page posts $numpages++; // increment number of pages $pages[] = $content; } </code></pre> <p>Also tried leveraging the new <a href="https://developer.wordpress.org/reference/hooks/content_pagination/">content_pagination</a> filter that was added in 4.4:</p> <pre><code>add_filter('content_pagination', 'custom_content', 10, 2); function custom_content($pages, $post) { $content = html_entity_decode(stripslashes(get_option('custom_content'))); $pages[] = $content; return $pages; } </code></pre> <p>At this point I'm out of ideas on how to restore this functionality and any assistance would be appreciated.</p>
[ { "answer_id": 211579, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Note that there's a syntax error for all those three examples you provided:</p>\n\n<pre><code>add_filter('content_pagination', 'custom_content'), 10, 2);\n\nadd_action('the_post', 'custom_content'));\n\nadd_action('template_redirect', 'custom_content'));\n</code></pre>\n\n<p>where an extra <code>)</code> is added.</p>\n\n<p>Replace these lines to:</p>\n\n<pre><code>add_filter( 'content_pagination', 'custom_content', 10, 2);\n\nadd_action( 'the_post', 'custom_content' );\n\nadd_action( 'template_redirect', 'custom_content' );\n</code></pre>\n\n<p>I would not recommend messing around with global objects in general, so I think your last example with the <code>content_pagination</code> filter is the way to go here.</p>\n\n<p>You might also want to avoid appending empty pages with:</p>\n\n<pre><code>if( ! empty( $content ) )\n $pages[] = $content;\n</code></pre>\n\n<p>There's also a missing <code>)</code> here:</p>\n\n<pre><code>$content = html_entity_decode(stripslashes(get_option('custom_content'));\n</code></pre>\n" }, { "answer_id": 215031, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<h1>UPDATE 21-01-2016 19:35 SA TIME - BUG FOUND!!!!! YEAH!!!!!!</h1>\n\n<p>I finally found the bug. As you stated in your last update, the failure only happens when <code>$post_content</code> has a <code>&lt;!--nextpage--&gt;</code> tag in the content. I tested it, and did confirm that any other page after the page after the <code>&lt;!--nextpage--&gt;</code> returns a 404 and then the page gets redirects back to the first page. </p>\n\n<p>This is due to <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp.php#L652\" rel=\"nofollow\">the following lines of code</a> in the <code>handle_404()</code> method which was introduced in the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp.php\" rel=\"nofollow\"><code>WP</code> class</a> in WordPress 4.4</p>\n\n<pre><code>// check for paged content that exceeds the max number of pages\n$next = '&lt;!--nextpage--&gt;';\nif ( $p &amp;&amp; false !== strpos( $p-&gt;post_content, $next ) &amp;&amp; ! empty( $this-&gt;query_vars['page'] ) ) {\n $page = trim( $this-&gt;query_vars['page'], '/' );\n $success = (int) $page &lt;= ( substr_count( $p-&gt;post_content, $next ) + 1 );\n}\n</code></pre>\n\n<p>What this code does is, whenever the <code>&lt;!--nextpage--&gt;</code> tag is set in the <code>post_content</code>, it will return a 404 when any page is accessed which is appended after the content via the <code>content_pagination</code> filter. Because of a 404 being set, <code>redirect_canonical()</code> redirects any appended page back to the first page</p>\n\n<p>I have filed a trac ticket about this issue which you can check out here</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/35562\" rel=\"nofollow\">trac ticket #35562</a></li>\n</ul>\n\n<p>At the time of writing there weren't any feedback yet, so make sure to regularly check out the status of the ticket</p>\n\n<h2>CURRENT SOLUTION - A/W TRAC TICKET FEEDBACK</h2>\n\n<p>For now, until we get any feedback and possible fixes in future releases, simply delete those lines from the <code>WP</code> class until further notice</p>\n\n<h1>WHAT TIME IS IT......IT'S DEBUGGING TIME!!!!!</h1>\n\n<p>I had time to fully test this. I took your code and tested it on:</p>\n\n<ul>\n<li><p>My v4.3 local install</p></li>\n<li><p>My v4.4.0 local install</p></li>\n<li><p>My v4.4.1 local install</p></li>\n<li><p>Complete new v4.4.1 local install with only the <code>Hello World</code> post and the <code>Sample Page</code> page</p></li>\n</ul>\n\n<p>with my permalinks set to </p>\n\n<ul>\n<li><p><code>default</code> and</p></li>\n<li><p><code>Post Name</code></p></li>\n</ul>\n\n<p>Here is my test code to create 4 pages with inside my test post.</p>\n\n<pre><code>add_filter('content_pagination', 'custom_content', 10, 2);\nfunction custom_content($pages, $post) {\n $pages_to_add = [\n 'Hello World Page 2',\n 'Hello World Page 3',\n 'Hello World Page 4',\n ];\n\n foreach ( $pages_to_add as $page_to_add ){\n $pages[] = html_entity_decode(\n stripslashes(\n $page_to_add\n )\n );\n }\n\n return $pages;\n}\n</code></pre>\n\n<p>I also tested </p>\n\n<pre><code>add_filter('content_pagination', 'custom_content', 10, 2);\nfunction custom_content($pages, $post) {\n $pages_to_add = [\n '&lt;!--nextpage--&gt; Hello World Page 2',\n '&lt;!--nextpage--&gt; Hello World Page 3',\n '&lt;!--nextpage--&gt; Hello World Page 4',\n ];\n\n foreach ( $pages_to_add as $page_to_add ){\n $pages[] = html_entity_decode(\n stripslashes(\n $page_to_add\n )\n );\n }\n\n return $pages;\n}\n</code></pre>\n\n<p>for good measure</p>\n\n<p>On each and every install and permalink structure, all of your code work (<em>except the <code>content_pagination</code> on v4.3 which is expected</em>).</p>\n\n<p>I also set <code>Sample Page</code> as a static front page, but that failed on page 2 as conformation to the bug as described in my <strong>ORIGINAL ANSWER and **EDIT</strong></p>\n\n<p>So the conclusion is that this has nothing to do with the bug in core or any other bug in core. From comments, something is unsetting the queried object on paged post pages, and that is something we need to debug. Unfortunately as this problem is now localized, I cannot give exact solutions. </p>\n\n<h2>DEBUGGING THE ISSUE</h2>\n\n<p>You need to use the following works flow to debug the issue</p>\n\n<ul>\n<li><p>Get yourself a huge amount of high caffeine coffee with lots of sugar</p></li>\n<li><p>Take a backup of you db</p></li>\n<li><p>Download and install the following plugins (<em>I have no affiliation to any plugin</em>)</p>\n\n<ul>\n<li><p><a href=\"https://wordpress.org/plugins/debug-objects/\" rel=\"nofollow\">Debug Objects</a> for normal debugging. Once installed and setup, repair all obvious bugs that might be highlighted by the plugin. Do not continue to the next main bullet point if you have obvious bugs. Fix them first</p></li>\n<li><p><a href=\"https://wordpress.org/plugins/wp-dbmanager/\" rel=\"nofollow\">DB Manager</a> which you will use to repair and cleanup your DB before you continue to the next bullet point</p></li>\n</ul></li>\n<li><p>Clear all caches, browsers and plugins</p></li>\n<li><p>Deactivate all plugins and clear all caches again for good measure. Because this issue looks like a redirection issue, I would probably first deactivate all plugins which might have something to do with redirection. It might be that one plugin is not yet compatible with v4.4. Check if the issue persist, if it does, continue to the next bullet point, else, lets look at this in more detail</p>\n\n<p>Start by deactivating all plugins, you can also start of by just deactivating the plugins that might be obvious for causing the issue. Properly test your install after activation of each and every plugin. The first plugin activated that caused the issue will be the culprit. In that case, contact the plugin author with the debugging details. Just make sure to clear your caches after each and every plugin activation just for good measure</p></li>\n<li><p>If you reached this point, the previous bullet point did not solve your issue. The next step should be to switch to a bundled theme to eliminate your theme as the issue. Just again, clear caches.</p></li>\n<li><p>If everything failed, you are left with two more options</p>\n\n<ul>\n<li><p>Delete <code>.htaccess</code> and let WordPress create a new one</p></li>\n<li><p>Reinstall WordPress</p></li>\n</ul></li>\n</ul>\n\n<p>This should solve your issue. If it does not, you need to consider a bug in WordPress core which might be causing the issue. </p>\n\n<p>I hope this helps in catching the bug</p>\n\n<h2>UPDATE</h2>\n\n<p>I should have actually linked to the fiollowing trac ticket which has seems to explain everything more in detail</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/35344\" rel=\"nofollow\">trac ticket 35344</a></li>\n</ul>\n\n<p>Interesting and quite relevant patches from the above trac ticket</p>\n\n<ul>\n<li><p><a href=\"https://core.trac.wordpress.org/ticket/35344#comment:16\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/35344#comment:16</a></p></li>\n<li><p><a href=\"https://core.trac.wordpress.org/ticket/35344#comment:34\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/35344#comment:34</a></p></li>\n</ul>\n\n<p>I cannot concretely test anything as such at this moment, but you should work through the suggested patches and test them. What I can pick up is that the same code in <a href=\"https://developer.wordpress.org/reference/functions/redirect_canonical/\" rel=\"nofollow\"><code>redirect_canonical()</code></a> which is responsible for the pagination of static front pages is also responsible for pagination on single pages.</p>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>Single pages (<em>like static front pages</em>) uses <code>get_query_var( 'page' )</code> to paginate. With WordPress 4.4 (<em>and in v4.4.1</em>), there came a bug which causes issues with pagination when using <code>get_query_var( 'page' )</code> for pagination.</p>\n\n<p>The current bug reports, like <a href=\"https://core.trac.wordpress.org/ticket/35365\" rel=\"nofollow\">trac ticket # 35365</a>, only mentions static front pages which have problems with pagination, but as the bug relates to <code>get_query_var( 'page' )</code>, I would think that this would also cause issues with single post pagination which also uses <code>get_query_var( 'page' )</code>.</p>\n\n<p>You should try the patches as described in the trac tickets. If this work, you can apply the patch and wait for v4.4.2 which will have this bug fixed </p>\n" } ]
2015/12/11
[ "https://wordpress.stackexchange.com/questions/211565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85182/" ]
Update 2016-01-21 ================= All current testing on my end is being done on fresh installs of 4.4.1 with the following settings: `Plain permalinks` `Twentysixteen Theme` `No plugins activated` **If the post only has 1 page** (ie `<!--nextpage-->` doesn't appear in the post) then the **extra pages are appended successfully** (even if you append multiple extra pages¹). ``` Welcome to WordPress. This is your first post. Edit or delete it, then start writing! ``` **If the post has 2+ pages** then the extra pages **404 and canonical redirect** to page 1 of the post. ``` Welcome to WordPress. This is your first post. Edit or delete it, then start writing! <!--nextpage--> This is page 2 ``` In the second case `$wp_query->queried_object` is empty once you hit the extra pages. You'll need to disable the canonical redirect to see this `remove_filter('template_redirect', 'redirect_canonical');` Both of the following core fixes have been tried, separately and together, with no change in behavior: <https://core.trac.wordpress.org/ticket/35344#comment:16> <https://core.trac.wordpress.org/ticket/35344#comment:34> For ease of use this is the code I'm currently testing with: ``` add_action('template_redirect', 'custom_content_one'); function custom_content_one() { global $post; $content = "\n<!--nextpage-->\nThis is the extra page v1"; $post->post_content .= $content; } add_filter('content_pagination', 'custom_content_two', 10, 2); function custom_content_two($pages, $post) { if ( in_the_loop() && 'post' === $post->post_type ) { $content = "This is the extra page v2"; $pages[] = $content; } return $pages; } add_action('the_post', 'custom_content_three'); function custom_content_three() { global $multipage, $numpages, $pages; $content = "This is the extra page v3"; $multipage = 1; $numpages++; $pages[] = $content; } ``` ¹This is the code I used to test multiple extra pages on a single page post ``` add_action('template_redirect', 'custom_content_one'); function custom_content_one() { global $post; $content = "\n<!--nextpage-->\nThis is the extra page v1-1\n<!--nextpage-->\nThis is the extra page v1-2\n<!--nextpage-->\nThis is the extra page v1-3"; $post->post_content .= $content; } ``` Original Question ================= Prior to 4.4 I was able to append an additional page to a mutlipage post with the following: ``` add_action('template_redirect', 'custom_content'); function custom_content() { global $post; $content = html_entity_decode(stripslashes(get_option('custom_content'))); $post->post_content .= $content; } ``` With get\_option('custom\_content') being something like: ``` <!--nextpage--> Hello World ``` Since upgrading to 4.4 the code has not worked; navigating to the additional page triggers a 404 error and [redirect\_canonical](https://developer.wordpress.org/reference/functions/redirect_canonical/) sends them back to the permalink of the post. Disabling redirect\_canonical allows me to view the extra page and the additonal content is there, but it still triggers a 404 error. I've tried a number of workarounds, none of which resolve the 404 error, including: ``` add_action('the_post', 'custom_content'); function custom_content() { global $multipage, $numpages, $pages; $content = html_entity_decode(stripslashes(get_option('custom_content'))); $multipage = 1; // ensure post is considered multipage: needed for single page posts $numpages++; // increment number of pages $pages[] = $content; } ``` Also tried leveraging the new [content\_pagination](https://developer.wordpress.org/reference/hooks/content_pagination/) filter that was added in 4.4: ``` add_filter('content_pagination', 'custom_content', 10, 2); function custom_content($pages, $post) { $content = html_entity_decode(stripslashes(get_option('custom_content'))); $pages[] = $content; return $pages; } ``` At this point I'm out of ideas on how to restore this functionality and any assistance would be appreciated.
UPDATE 21-01-2016 19:35 SA TIME - BUG FOUND!!!!! YEAH!!!!!! =========================================================== I finally found the bug. As you stated in your last update, the failure only happens when `$post_content` has a `<!--nextpage-->` tag in the content. I tested it, and did confirm that any other page after the page after the `<!--nextpage-->` returns a 404 and then the page gets redirects back to the first page. This is due to [the following lines of code](https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp.php#L652) in the `handle_404()` method which was introduced in the [`WP` class](https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp.php) in WordPress 4.4 ``` // check for paged content that exceeds the max number of pages $next = '<!--nextpage-->'; if ( $p && false !== strpos( $p->post_content, $next ) && ! empty( $this->query_vars['page'] ) ) { $page = trim( $this->query_vars['page'], '/' ); $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 ); } ``` What this code does is, whenever the `<!--nextpage-->` tag is set in the `post_content`, it will return a 404 when any page is accessed which is appended after the content via the `content_pagination` filter. Because of a 404 being set, `redirect_canonical()` redirects any appended page back to the first page I have filed a trac ticket about this issue which you can check out here * [trac ticket #35562](https://core.trac.wordpress.org/ticket/35562) At the time of writing there weren't any feedback yet, so make sure to regularly check out the status of the ticket CURRENT SOLUTION - A/W TRAC TICKET FEEDBACK ------------------------------------------- For now, until we get any feedback and possible fixes in future releases, simply delete those lines from the `WP` class until further notice WHAT TIME IS IT......IT'S DEBUGGING TIME!!!!! ============================================= I had time to fully test this. I took your code and tested it on: * My v4.3 local install * My v4.4.0 local install * My v4.4.1 local install * Complete new v4.4.1 local install with only the `Hello World` post and the `Sample Page` page with my permalinks set to * `default` and * `Post Name` Here is my test code to create 4 pages with inside my test post. ``` add_filter('content_pagination', 'custom_content', 10, 2); function custom_content($pages, $post) { $pages_to_add = [ 'Hello World Page 2', 'Hello World Page 3', 'Hello World Page 4', ]; foreach ( $pages_to_add as $page_to_add ){ $pages[] = html_entity_decode( stripslashes( $page_to_add ) ); } return $pages; } ``` I also tested ``` add_filter('content_pagination', 'custom_content', 10, 2); function custom_content($pages, $post) { $pages_to_add = [ '<!--nextpage--> Hello World Page 2', '<!--nextpage--> Hello World Page 3', '<!--nextpage--> Hello World Page 4', ]; foreach ( $pages_to_add as $page_to_add ){ $pages[] = html_entity_decode( stripslashes( $page_to_add ) ); } return $pages; } ``` for good measure On each and every install and permalink structure, all of your code work (*except the `content_pagination` on v4.3 which is expected*). I also set `Sample Page` as a static front page, but that failed on page 2 as conformation to the bug as described in my **ORIGINAL ANSWER and \*\*EDIT** So the conclusion is that this has nothing to do with the bug in core or any other bug in core. From comments, something is unsetting the queried object on paged post pages, and that is something we need to debug. Unfortunately as this problem is now localized, I cannot give exact solutions. DEBUGGING THE ISSUE ------------------- You need to use the following works flow to debug the issue * Get yourself a huge amount of high caffeine coffee with lots of sugar * Take a backup of you db * Download and install the following plugins (*I have no affiliation to any plugin*) + [Debug Objects](https://wordpress.org/plugins/debug-objects/) for normal debugging. Once installed and setup, repair all obvious bugs that might be highlighted by the plugin. Do not continue to the next main bullet point if you have obvious bugs. Fix them first + [DB Manager](https://wordpress.org/plugins/wp-dbmanager/) which you will use to repair and cleanup your DB before you continue to the next bullet point * Clear all caches, browsers and plugins * Deactivate all plugins and clear all caches again for good measure. Because this issue looks like a redirection issue, I would probably first deactivate all plugins which might have something to do with redirection. It might be that one plugin is not yet compatible with v4.4. Check if the issue persist, if it does, continue to the next bullet point, else, lets look at this in more detail Start by deactivating all plugins, you can also start of by just deactivating the plugins that might be obvious for causing the issue. Properly test your install after activation of each and every plugin. The first plugin activated that caused the issue will be the culprit. In that case, contact the plugin author with the debugging details. Just make sure to clear your caches after each and every plugin activation just for good measure * If you reached this point, the previous bullet point did not solve your issue. The next step should be to switch to a bundled theme to eliminate your theme as the issue. Just again, clear caches. * If everything failed, you are left with two more options + Delete `.htaccess` and let WordPress create a new one + Reinstall WordPress This should solve your issue. If it does not, you need to consider a bug in WordPress core which might be causing the issue. I hope this helps in catching the bug UPDATE ------ I should have actually linked to the fiollowing trac ticket which has seems to explain everything more in detail * [trac ticket 35344](https://core.trac.wordpress.org/ticket/35344) Interesting and quite relevant patches from the above trac ticket * <https://core.trac.wordpress.org/ticket/35344#comment:16> * <https://core.trac.wordpress.org/ticket/35344#comment:34> I cannot concretely test anything as such at this moment, but you should work through the suggested patches and test them. What I can pick up is that the same code in [`redirect_canonical()`](https://developer.wordpress.org/reference/functions/redirect_canonical/) which is responsible for the pagination of static front pages is also responsible for pagination on single pages. ORIGINAL ANSWER --------------- Single pages (*like static front pages*) uses `get_query_var( 'page' )` to paginate. With WordPress 4.4 (*and in v4.4.1*), there came a bug which causes issues with pagination when using `get_query_var( 'page' )` for pagination. The current bug reports, like [trac ticket # 35365](https://core.trac.wordpress.org/ticket/35365), only mentions static front pages which have problems with pagination, but as the bug relates to `get_query_var( 'page' )`, I would think that this would also cause issues with single post pagination which also uses `get_query_var( 'page' )`. You should try the patches as described in the trac tickets. If this work, you can apply the patch and wait for v4.4.2 which will have this bug fixed
211,581
<p>When creating a new term in a custom taxonomy with wp_insert_term, i've noticed that name should be unique. I get a wp error message if it is not :</p> <pre><code>A term with the name provided already exists with this parent </code></pre> <p>I would like a way to automatically check if name is already exist and append it if yes.</p> <p>So check :</p> <pre><code>get_term_by('name', $term_id, $taxonomy); </code></pre> <p>and if term exists append the name.</p> <p>but is there a way to auto this with WP ? Like WP does with slug ? Why should the name be unique, don't understand as the slug is.</p> <p>thanks a lot !</p> <p>François</p>
[ { "answer_id": 211599, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<h2>EDIT</h2>\n\n<h2><a href=\"http://askville.amazon.com/deux-part-speech-sense-carry/AnswerViewer.do?requestId=13424467\" rel=\"nofollow\">PART DEUX</a> OR <a href=\"http://www.urbandictionary.com/define.php?term=part%20deux\" rel=\"nofollow\">PART DEUX</a> - The Dirty Sequal, The Term Saga Continues...</h2>\n\n<p>Before anyone read this section, I will urge you to read everything I explained in <strong>ORIGINAL ANSWER</strong>. <code>wp_insert_term()</code> does not allow duplicate term names in non hierarchical taxonomies or in hierarchical taxonomies within the same hierarchy.</p>\n\n<p>From comments to my answer, the answer from OP and from the OP</p>\n\n<blockquote>\n <p>What i need is a way to have the same Name in the Taxonomy Hierarchy.</p>\n</blockquote>\n\n<p>There is a way to achieve this, lets look at how:</p>\n\n<h2>CAUTION - caution - CAUTION - caution !!!!</h2>\n\n<p>I went with a modified class of the <code>wp_insert_term()</code> function. As I said, there are protection inside <code>wp_insert_term()</code> to avoid duplicate term names. What I have done is to get rid of this protection in order to allow duplicate names within the same hierarchy. You basically need to remove the name check section and then the section that delete accidental duplicates when the term is already inserted.</p>\n\n<p>Because of this, this class will allow an unlimited amount of terms with the same name, so it should be used with <strong>great care</strong>. 100 accidental page loads will insert 100 terms with the same name. </p>\n\n<p>Here is the class with a few notes </p>\n\n<p><strong>NOTE:</strong> </p>\n\n<ul>\n<li><p>This requires at least PHP 5.4. </p></li>\n<li><p>Although I ran a few test to check the class' operation, I have not run any complete test on this, so PLEASE PLEASE PLEASE, run this on a local test install first and verify everything properly</p></li>\n<li><p>The class can be improved and modified as needed. I might have mixed syntaxes and scrambled code. This is just a very basic backbone with only the essentials</p></li>\n</ul>\n\n<p>Lets look at the code:</p>\n\n<pre><code>/**\n * WPInsertTerm class\n *\n * Class to insert terms into the db\n * \n * If term names are identical, in stead of throwing an error like\n * wp_insert_term(), the function will add valid term meta_key\n * \n * @author Pieter Goosen\n * @version 1.0.0\n * @access public\n*/ \n\nclass WPInsertTerm \n{\n /**\n * Arguments to hold defaults\n * @since 1.0.0\n * @var array\n */\n protected $defaults = [\n 'alias_of' =&gt; '', \n 'description' =&gt; '', \n 'parent' =&gt; 0, \n 'slug' =&gt; ''\n ];\n\n /**\n * Arguments set by user\n * @since 1.0.0\n * @var array\n */\n protected $args = [];\n\n /**\n * Term to insert\n * @since 1.0.0\n * @var string\n */\n protected $term = null;\n\n /**\n * Taxonomy the term should belong to\n * @since 1.0.0\n * @var string\n */\n protected $taxonomy = null;\n\n /**\n * Constructor\n *\n * @param string $term = null\n * @param string $taxonomy = null\n * @param array $args = []\n * @since 1.0.0\n */ \n public function __construct( $term = null, $taxonomy = null, $args = [] ) \n {\n $this-&gt;term = $term;\n $this-&gt;taxonomy = $taxonomy;\n if ( is_array( $args ) ) {\n $this-&gt;args = array_merge( $this-&gt;defaults, $args );\n } else { \n $this-&gt;args = $this-&gt;defaults;\n }\n }\n\n /**\n * Public method wpdb()\n *\n * Returns the global wpdb class\n *\n * @since 1.0.0\n * @return $wpdb\n */\n public function wpdb()\n {\n global $wpdb;\n\n return $wpdb;\n }\n\n /**\n * Private method validateVersion()\n *\n * Validate the current WordPress version\n *\n * @since 1.0.0\n * @return $validateVersion\n */\n private function validateVersion()\n {\n global $wp_version;\n\n $validateVersion = false;\n\n if ( '4.4' &gt; $wp_version ) {\n throw new InvalidArgumentException( \n sprintf(\n __( 'Your WordpPress version is too old. A minimum version of WordPress 4.4 is expected. Please upgrade' ),\n __METHOD__\n )\n );\n }\n\n return $validateVersion = true;\n }\n\n /**\n * Private method validateTaxonomy()\n *\n * Validate the $taxonomy value\n *\n * @since 1.0.0\n * @return $validateTaxonomy\n */\n private function validateTaxonomy()\n { \n $validateTaxonomy = filter_var( $this-&gt;taxonomy, FILTER_SANITIZE_STRING );\n // Check if taxonomy is valid\n if ( !taxonomy_exists( $validateTaxonomy ) ) {\n throw new InvalidArgumentException( \n sprintf(\n __( 'Your taxonomy does not exists, please add a valid taxonomy' ),\n __METHOD__\n )\n );\n }\n\n return $validateTaxonomy;\n }\n\n /**\n * Private method validateTerm()\n *\n * Validate the $term value\n *\n * @since 1.0.0\n * @return $validateTerm\n */\n private function validateTerm()\n {\n /**\n * Filter a term before it is sanitized and inserted into the database.\n *\n * @since 1.0.0\n *\n * @param string $term The term to add or update.\n * @param string $taxonomy Taxonomy slug.\n */\n $validateTerm = apply_filters( 'pre_insert_term', $this-&gt;term, $this-&gt;validateTaxonomy() ); \n\n // Check if the term is not empty\n if ( empty( $validateTerm ) ) {\n throw new InvalidArgumentException( \n sprintf(\n __( '$term should not be empty, please add a valid value' ),\n __METHOD__\n )\n );\n }\n\n // Check if term is a valid integer if integer is passed\n if ( is_int( $validateTerm )\n &amp;&amp; 0 == $validateTerm\n ){\n throw new InvalidArgumentException( \n sprintf(\n __('Invalid term id supplied, please asdd a valid value'),\n __METHOD__\n )\n );\n }\n\n // Term is not empty, sanitize the term and trim any white spaces\n $validateTerm = filter_var( trim( $validateTerm ), FILTER_SANITIZE_STRING );\n if ( empty( $validateTerm ) ){\n throw new InvalidArgumentException( \n sprintf(\n __( 'Invalid term supplied, please asdd a valid term name' ),\n __METHOD__\n )\n );\n }\n\n return $validateTerm;\n }\n\n /**\n * Private method parentExist()\n *\n * Validate if the parent term exist if passed\n *\n * @since 1.0.0\n * @return $parentexist\n */\n private function parentExist()\n {\n $parentExist = $this-&gt;args['parent'];\n\n if ( $parentExist &gt; 0\n &amp;&amp; !term_exists( (int) $parentExist ) \n ) {\n throw new InvalidArgumentException( \n sprintf(\n __( 'Invalid parent ID supplied, no term exists with parent ID passed. Please add a valid parent ID' ),\n __METHOD__\n )\n );\n }\n\n return $parentExist;\n }\n\n /**\n * Private method sanitizeTerm()\n *\n * Sanitize the term to insert\n *\n * @since 1.0.0\n * @return $sanitizeTerm\n */\n private function sanitizeTerm()\n {\n $taxonomy = $this-&gt;validateTaxonomy();\n $arguments = $this-&gt;args;\n\n $arguments['taxonomy'] = $taxonomy;\n $arguments['name'] = $this-&gt;validateTerm();\n $arguments['parent'] = $this-&gt;parentExist();\n\n // Santize the term \n $arguments = sanitize_term( $arguments, $taxonomy, 'db' );\n\n // Unslash name and description fields and cast parent to integer\n $arguments['name'] = wp_unslash( $arguments['name'] );\n $arguments['description'] = wp_unslash( $arguments['description'] );\n $arguments['parent'] = (int) $arguments['parent'];\n\n return (object) $arguments;\n }\n\n /**\n * Private method slug()\n *\n * Get or create a slug if no slug is set\n *\n * @since 1.0.0\n * @return $slug\n */\n private function slug()\n {\n $term = $this-&gt;sanitizeTerm();\n $new_slug = $term-&gt;slug;\n if ( !$new_slug ) {\n $slug = sanitize_title( $term-&gt;name );\n } else {\n $slug = $new_slug;\n }\n\n return $slug;\n }\n\n /**\n * Public method addTerm()\n *\n * Add the term to db\n *\n * @since 1.0.0\n */\n public function addTerm()\n {\n $wpdb = $this-&gt;wpdb();\n $term = $this-&gt;sanitizeTerm();\n $taxonomy = $term-&gt;taxonomy;\n $name = $term-&gt;name;\n $parent = $term-&gt;parent;\n $term_group = $term-&gt;term_group;\n\n $term_group = 0;\n\n if ( $term-&gt;alias_of ) {\n $alias = get_term_by( \n 'slug', \n $term-&gt;alias_of, \n $term-&gt;taxonomy \n );\n if ( !empty( $alias-&gt;term_group ) ) {\n // The alias we want is already in a group, so let's use that one.\n $term_group = $alias-&gt;term_group;\n } elseif ( ! empty( $alias-&gt;term_id ) ) {\n /*\n * The alias is not in a group, so we create a new one\n * and add the alias to it.\n */\n $term_group = $wpdb-&gt;get_var(\n \"SELECT MAX(term_group) \n FROM $wpdb-&gt;terms\"\n ) + 1;\n\n wp_update_term( \n $alias-&gt;term_id, \n $this-&gt;args['taxonomy'], \n [\n 'term_group' =&gt; $term_group,\n ] \n );\n }\n }\n\n $slug = wp_unique_term_slug( \n $this-&gt;slug(), \n $term\n );\n\n if ( false === $wpdb-&gt;insert( $wpdb-&gt;terms, compact( 'name', 'slug', 'term_group' ) ) ) {\n return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb-&gt;last_error );\n }\n\n $term_id = (int) $wpdb-&gt;insert_id;\n\n // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.\n if ( empty( $slug ) ) {\n $slug = sanitize_title( \n $slug, \n $term_id \n );\n\n /** This action is documented in wp-includes/taxonomy.php */\n do_action( 'edit_terms', $term_id, $taxonomy );\n $wpdb-&gt;update( $wpdb-&gt;terms, compact( 'slug' ), compact( 'term_id' ) );\n\n /** This action is documented in wp-includes/taxonomy.php */\n do_action( 'edited_terms', $term_id, $taxonomy );\n }\n\n $tt_id = $wpdb-&gt;get_var( \n $wpdb-&gt;prepare( \"\n SELECT tt.term_taxonomy_id \n FROM $wpdb-&gt;term_taxonomy AS tt \n INNER JOIN $wpdb-&gt;terms AS t \n ON tt.term_id = t.term_id \n WHERE tt.taxonomy = %s \n AND t.term_id = %d\n \", \n $taxonomy, \n $term_id \n ) \n );\n\n if ( !empty($tt_id) ) {\n return [\n 'term_id' =&gt; $term_id, \n 'term_taxonomy_id' =&gt; $tt_id\n ];\n }\n\n $wpdb-&gt;insert( \n $wpdb-&gt;term_taxonomy, \n compact( 'term_id', 'taxonomy', 'description', 'parent') + ['count' =&gt; 0] \n );\n $tt_id = (int) $wpdb-&gt;insert_id;\n\n\n /**\n * Fires immediately after a new term is created, before the term cache is cleaned.\n *\n * @since 2.3.0\n *\n * @param int $term_id Term ID.\n * @param int $tt_id Term taxonomy ID.\n * @param string $taxonomy Taxonomy slug.\n */\n do_action( \"create_term\", $term_id, $tt_id, $taxonomy );\n\n /**\n * Fires after a new term is created for a specific taxonomy.\n *\n * The dynamic portion of the hook name, `$taxonomy`, refers\n * to the slug of the taxonomy the term was created for.\n *\n * @since 2.3.0\n *\n * @param int $term_id Term ID.\n * @param int $tt_id Term taxonomy ID.\n */\n do_action( \"create_$taxonomy\", $term_id, $tt_id );\n\n /**\n * Filter the term ID after a new term is created.\n *\n * @since 2.3.0\n *\n * @param int $term_id Term ID.\n * @param int $tt_id Taxonomy term ID.\n */\n $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );\n\n clean_term_cache($term_id, $taxonomy);\n\n /**\n * Fires after a new term is created, and after the term cache has been cleaned.\n *\n * @since 2.3.0\n *\n * @param int $term_id Term ID.\n * @param int $tt_id Term taxonomy ID.\n * @param string $taxonomy Taxonomy slug.\n */\n do_action( 'created_term', $term_id, $tt_id, $taxonomy );\n\n /**\n * Fires after a new term in a specific taxonomy is created, and after the term\n * cache has been cleaned.\n *\n * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.\n *\n * @since 2.3.0\n *\n * @param int $term_id Term ID.\n * @param int $tt_id Term taxonomy ID.\n */\n do_action( \"created_$taxonomy\", $term_id, $tt_id );\n\n return [\n 'term_id' =&gt; $term_id, \n 'term_taxonomy_id' =&gt; $tt_id\n ]; \n }\n}\n</code></pre>\n\n<p>You can then use it as follow:</p>\n\n<pre><code>$q = new WPInsertTerm( 'My Term', 'category', ['parent' =&gt; 1] );\n$q-&gt;addTerm();\n</code></pre>\n\n<p>Here we add our term, <code>My Term</code> to the parent term with ID <code>1</code> in build in taxonomy <code>category</code>. </p>\n\n<p>Note, running this 100 times will add 100 terms called <code>My Term</code> under parent term <code>1</code>.</p>\n\n<h2>ADDITIONAL NOTES</h2>\n\n<ul>\n<li><p>With the above, everything term name related queries should be avoided</p>\n\n<ul>\n<li><p>By default, there are already an issue with term names in a <code>tax_query</code> in <code>WP_Query</code>. This class addition would make the use of the <code>name</code> field absolutely impossible</p></li>\n<li><p>Getting terms by name should also be avoided at all costs as the wrong term will in all probability be returned.</p></li>\n</ul></li>\n</ul>\n\n<p>A final note, having several terms with the same name will be very very confusing and might open a few cans of rotten worms, so you will need to be absolutely sure that this is what you want</p>\n\n<h1>ORIGINAL ANSWER</h1>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_insert_term/\" rel=\"nofollow\"><code>wp_insert_term()</code></a> is quite a busy function with a lot of stuff that goes on before a term is successfully added to a taxonomy. </p>\n\n<p>The first important section is this:</p>\n\n<pre><code>$slug_provided = ! empty( $args['slug'] );\nif ( ! $slug_provided ) {\n $slug = sanitize_title( $name );\n} else {\n $slug = $args['slug'];\n}\n</code></pre>\n\n<p>In short, what this means is, if you haven't explicitly set a slug, a slug will be created from the name given via the <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"nofollow\"><code>santitize_title()</code></a> function. This is the basis which will decide whether a term will be added or not as the slug is the important part moving forward.</p>\n\n<p>So if we would want to insert a term with the name <code>My Term</code>, we would end up with a slug like <code>my-term</code> if we did not set a slug.</p>\n\n<p>The next important part is this: (<em>Which runs regardless if slug being where set or not</em>)</p>\n\n<pre><code>/*\n * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,\n * unless a unique slug has been explicitly provided.\n */\n$name_matches = get_terms( $taxonomy, array(\n 'name' =&gt; $name,\n 'hide_empty' =&gt; false,\n) );\n\n/*\n * The `name` match in `get_terms()` doesn't differentiate accented characters,\n * so we do a stricter comparison here.\n */\n$name_match = null;\nif ( $name_matches ) {\n foreach ( $name_matches as $_match ) {\n if ( strtolower( $name ) === strtolower( $_match-&gt;name ) ) {\n $name_match = $_match;\n break;\n }\n }\n}\n</code></pre>\n\n<p><code>$name</code> (<em>$name = wp_unslash( $args['name'] );</em>) which is the name you have explicitely set is used to return all terms with a name matching <code>$name</code> to compare to the term you are trying to insert, if there are any. If there are any terms that exists by <code>$name</code>, a more exact match is done to match terms. </p>\n\n<p>As the description/docblock says <em><code>get_terms()</code> doesn't differentiate accented characters</em>, so we might end up with terms having names like <code>my Term</code> and <code>My terM</code>. All letters are set to lower in this match, so all term names are set to <code>my term</code> for matching. This makes sense, because if those terms (<em>or any of the returned terms</em>) were created (<em>either back end or front end or programmically</em>) without having a slug set, names like <code>my Term</code> and <code>My terM</code> and our term <code>My Term</code> would all produce the same slug, <code>my-term</code>, so we would need elimanate such issues.</p>\n\n<p>The last important section here before a unique slug is created and the term inserted, is the following section</p>\n\n<pre><code>if ( $name_match ) {\n $slug_match = get_term_by( 'slug', $slug, $taxonomy );\n if ( ! $slug_provided || $name_match-&gt;slug === $slug || $slug_match ) {\n if ( is_taxonomy_hierarchical( $taxonomy ) ) {\n $siblings = get_terms( $taxonomy, array( 'get' =&gt; 'all', 'parent' =&gt; $parent ) );\n\n $existing_term = null;\n if ( $name_match-&gt;slug === $slug &amp;&amp; in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {\n $existing_term = $name_match;\n } elseif ( $slug_match &amp;&amp; in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {\n $existing_term = $slug_match;\n }\n\n if ( $existing_term ) {\n return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term-&gt;term_id );\n }\n } else {\n return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match-&gt;term_id );\n }\n }\n}\n</code></pre>\n\n<p>This section only runs when we have positively identified any other term with the same name as the one we would like to insert. Again, this section runs regardless whther a slug has been set or not. </p>\n\n<p>The first thing that this section do is to return any matching term from db which matches our slug from the term we would want to insert which comes from the first section of code in the answer. Our slug is <code>my-term</code>. <a href=\"https://developer.wordpress.org/reference/functions/get_term_by/\" rel=\"nofollow\"><code>get_term_by()</code></a> either return a term object if there is a term that already in db which matches the term by slug of the term we would want to insert, or false if there is no term that already matches our term by slug.</p>\n\n<p>Now a lot of check is done here, the first is a condition that runs the following checks</p>\n\n<ul>\n<li><p>Check if we have explicitely set a slug (<code>! $slug_provided</code>), return true if haven't</p></li>\n<li><p>If the slug from a matching term (<em>from the second block of code in this answer</em>) matches the slug from the term we want to insert (<em>in this case <code>my-term</code></em>). Retruns true if there is a match</p></li>\n<li><p>Whether we have a term object returned from <code>get_term_by()</code>.</p></li>\n</ul>\n\n<p>If any of these three conditions return true, a check is then done to check if our taxonomy is hierarchical. If this returns false, ie, our taxonomy is non hierarchical like tags, the following error is returned:</p>\n\n<blockquote>\n <p>A term with the name provided already exists in this taxonomy.</p>\n</blockquote>\n\n<p>quite obviously as we cannot have terms with the same name in a non hierarchical taxonomy.</p>\n\n<p>If this returns true, ie our taxonomy is hierarchical, all sibling terms is queried by parent (<em>which will be either <code>0</code> or whatever integer value we have explicitely set</em>).</p>\n\n<p><code>wp_insert_term()</code> now do its final check before deciding to go ahead with inserting the term or not. A failure here would throw the error message you are refering to in your question</p>\n\n<blockquote>\n <p>A term with the name provided already exists with this parent</p>\n</blockquote>\n\n<p>This is what the final check does:</p>\n\n<p>All the direct child terms are queried from db from the given taxonomy and parent (<em>which is either <code>0</code> or the value specified by you</em>). Remember that we are still inside the condition which states that there are terms matching the name of the term we want to insert. Two checks are done on the returned array of child categories:</p>\n\n<ul>\n<li><p>The first check involves the following: The term's slug from the matched term <code>$name_match</code> are checked against the slug from our term, <code>my-term</code> (<em>remember this comes from block one of code in the answer</em>). Also, our term name that we have set, <code>My Term</code> are checked against all names from the direct children from our parent. </p></li>\n<li><p>The second check is the following: A check is done to see if there was a term returned by <code>get_term_by()</code> and if the slug from the first block of code in this answer matches any slugs from the direct children from the parent term.</p></li>\n</ul>\n\n<p>If any of these conditions returns true, the </p>\n\n<blockquote>\n <p>A term with the name provided already exists with this parent.</p>\n</blockquote>\n\n<p>error message is thrown and the term is not inserted. A false will in all probably lead to the term successfully being created and inserted.</p>\n\n<p>Now we can look at your question</p>\n\n<blockquote>\n <p>Why should the name be unique, don't understand as the slug is.</p>\n</blockquote>\n\n<p>You can have duplicate names within a hierarchical taxonomy if, and <strong>only if</strong></p>\n\n<ul>\n<li><p>There are no term with a matching name on the same level in the hierarchy. So any two top level terms, or any two direct children from the same parent term cannot have the same name. This line:</p>\n\n<pre><code>if ( $name_match-&gt;slug === $slug &amp;&amp; in_array( $name, wp_list_pluck( $siblings, 'name' ) ) )\n</code></pre>\n\n<p>of code prohibits that. </p></li>\n<li><p>You can have the same names for terms in a hierarchical taxonomy if the term is in one top level parent, a child to that top level parent and one grandchild to that specific child, if and <strong>only if</strong> their slugs are unique. This line </p>\n\n<pre><code>elseif ( $slug_match &amp;&amp; in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) )\n</code></pre>\n\n<p>prohibits terms with the same name having the same slug</p></li>\n</ul>\n\n<p>You cannot have terms with the same name in a non hierarchical taxonomy as they do not have parent/child type relationships</p>\n\n<p>So, if you are sure your taxonomy is hierarchical, and you slug is unique, it still does not mean you can have the same name, as you need to take parent into consideration. If your parent remain the same, regardless of unique slug being set, your term will not be inserted and will throw the error message you are seeing</p>\n\n<h2>POSSIBLE WORKAROUND TO MAKE NAME UNIQUE</h2>\n\n<p>The best will be to write a wrapper function where you use the same logic as <code>wp_insert_term()</code> to first check if there are already a term with the same name with the same parent, and if so, take the name and run some kind of function on the name to make it unique. </p>\n\n<p>I would encourage you to take all the logic in this answer, use it in a custom wrapper function to create a unique name, and play around with ideas. If you get stuck, feel free to post waht you have in a new question, and I'll be happy to take a look at it when I have time.</p>\n\n<p>Best of luck </p>\n" }, { "answer_id": 211652, "author": "Polykrom", "author_id": 85162, "author_profile": "https://wordpress.stackexchange.com/users/85162", "pm_score": 1, "selected": false, "text": "<p>After @PieterGoosen advices, i figure out my issue, here is the complete function that check if a term name already exists in a Taxonomy.</p>\n\n<p>It doesn't provide yet a name substitution if name already exists in the parent term.</p>\n\n<p>I don't need to check for the slug as i've let WP create one automatically for me.</p>\n\n<pre><code>function check_term_name($term_name,$taxonomy,$parent) \n{\n\n$name_matches = get_terms( $taxonomy, array(\n 'name' =&gt; $term_name,\n 'hide_empty' =&gt; false,\n) );\n\n\n$name_match = null;\nif ( $name_matches ) {\n foreach ( $name_matches as $_match ) {\n if ( strtolower( $term_name ) === strtolower( $_match-&gt;name ) ) {\n $name_match = $_match;\n break;\n }\n }\n}\n\n\nif ( $name_match ) {\n\n if ( is_taxonomy_hierarchical( $taxonomy ) ) {\n $siblings = get_terms( $taxonomy, array( 'get' =&gt; 'all', 'parent' =&gt; $parent-&gt;term_id ) );\n $existing_term = null;\n if ( in_array( $term_name, wp_list_pluck( $siblings, 'name' ) ) ) {\n $existing_term = $name_match;\n }\n\n if ( $existing_term ) {\n return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term-&gt;term_id );\n }\n } else {\n return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match-&gt;term_id );\n }\n\n}\n\n\nreturn $term_name;\n\n}\n</code></pre>\n\n<p>I wonder if it wouldn't possible to add a custom meta to the term (new in WP 4.4) with the original name in place of the name property of the term.\nSo i could add a unique id to the term name and create a category selector which display the custom meta in place of the name.</p>\n\n<pre><code>add_term_meta($term_id,'name',$name);\n</code></pre>\n\n<p>and retrieve it to populate my selector :</p>\n\n<pre><code>get_term_meta($term_id,'name');\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>I've put my hands in the </p>\n\n<pre><code>add_term_meta\n</code></pre>\n\n<p>and put together the suggestions you can find <a href=\"http://themehybrid.com/weblog/introduction-to-wordpress-term-meta\" rel=\"nofollow\">here</a></p>\n\n<p>So , if we want to have the same name even if term name is different, we have to add a custom meta 'real_name' to the term.</p>\n\n<p>So first, we register the meta :</p>\n\n<pre><code>add_action( 'init', 'blaamy_register_meta' );\n\nfunction blaamy_register_meta() {\n\n register_meta( 'term', 'real_name' );\n\n}\n</code></pre>\n\n<p>then we add a new column to our taxonomy, say we have a object_category taxonomy :</p>\n\n<pre><code>add_filter( 'manage_edit-object_category_columns', 'blaamy_edit_term_columns' );\n\nfunction blaamy_edit_term_columns( $columns ) {\n\n $columns['real_name'] = __( 'Real Name', 'blaamy' );\n\n return $columns;\n}\n</code></pre>\n\n<p>Now we need to manage the custom column :</p>\n\n<pre><code>add_filter( 'manage_object_category_custom_column', 'blaamy_manage_term_custom_column', 10, 3 );\n\nfunction blaamy_manage_term_custom_column( $out, $column, $term_id ) {\n\n if('real_name' === $column){\n\n $real_name = blaamy_get_term_real_name( $term_id, true );\n\n if ( ! $real_name )\n $real_name = '';\n\n $out = sprintf( '&lt;span class=\"real_name-block\"&gt;%s&lt;/span&gt;', esc_attr( $real_name ));\n\n\n }\n\n return $out;\n}\n</code></pre>\n\n<p>We need also something to get the real_name meta value :</p>\n\n<pre><code>function blaamy_get_term_real_name( $term_id, $hash = false ) {\n\n $real_name = get_term_meta( $term_id, 'real_name', true );\n\n return $real_name;\n}\n</code></pre>\n\n<p>Now we create the real name form field :</p>\n\n<pre><code>add_action( 'object_category_add_form_fields', 'blaamy_new_term_real_name_field' );\n\nfunction blaamy_new_term_real_name_field() {\n\n wp_nonce_field( basename( __FILE__ ), 'blaamy_term_real_name_nonce' ); ?&gt;\n\n &lt;div class=\"form-field blaamy-term-real-name-wrap\"&gt;\n &lt;label for=\"blaamy-term-real-name\"&gt;Real Name&lt;/label&gt;\n &lt;input type=\"text\" name=\"blaamy_term_real_name\" id=\"blaamy_term_real_name\" value=\"\" class=\"blaamy-real-name-field\" data-default-real-name=\"\" /&gt;\n &lt;/div&gt;\n&lt;?php }\n</code></pre>\n\n<p>and then we have to create the real name edit form field :</p>\n\n<pre><code>add_action( 'object_category_edit_form_fields', 'blaamy_edit_term_real_name_field' );\n\nfunction blaamy_edit_term_real_name_field( $term ) {\n\n $default = \"\";\n $real_name = blaamy_get_term_real_name( $term-&gt;term_id, true );\n\n if ( ! $author )\n $real_name = $real_name; ?&gt;\n\n &lt;tr class=\"form-field blaamy-term-real-name-wrap\"&gt;\n &lt;th scope=\"row\"&gt;&lt;label for=\"blaamy-term-real-name\"&gt;Real Name&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;?php wp_nonce_field( basename( __FILE__ ), 'blaamy_term_real_name_nonce' ); ?&gt;\n &lt;input type=\"text\" name=\"blaamy_term_real_name\" id=\"blaamy-term-real-name\" value=\"&lt;?php echo esc_attr( $real_name ); ?&gt;\" data-default-real-name=\"&lt;?php echo esc_attr( $default ); ?&gt;\" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;?php } \n</code></pre>\n\n<p>and finally the real name create and update functions :</p>\n\n<pre><code>add_action( 'edit_object_category', 'blaamy_save_term_real_name' );\nadd_action( 'create_object_category', 'blaamy_save_term_real_name' );\n\nfunction blaamy_save_term_real_name( $term_id ) {\n\n if ( ! isset( $_POST['blaamy_term_real_name_nonce'] ) || ! wp_verify_nonce( $_POST['blaamy_term_real_name_nonce'], basename( __FILE__ ) ) )\n return;\n\n $old_real_name = blaamy_get_term_real_name( $term_id );\n $new_real_name = isset( $_POST['blaamy_term_real_name'] ) ? $_POST['blaamy_term_real_name'] : '';\n\n if ( $old_real_name &amp;&amp; '' === $new_real_name )\n delete_term_meta( $term_id, 'real_name' );\n\n else if ( $old_real_name !== $new_real_name )\n update_term_meta( $term_id, 'real_name', $new_real_name );\n}\n</code></pre>\n\n<p>We have just to create a combobox or anything else on frontend which is populated by our real_name meta ! </p>\n" } ]
2015/12/12
[ "https://wordpress.stackexchange.com/questions/211581", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85162/" ]
When creating a new term in a custom taxonomy with wp\_insert\_term, i've noticed that name should be unique. I get a wp error message if it is not : ``` A term with the name provided already exists with this parent ``` I would like a way to automatically check if name is already exist and append it if yes. So check : ``` get_term_by('name', $term_id, $taxonomy); ``` and if term exists append the name. but is there a way to auto this with WP ? Like WP does with slug ? Why should the name be unique, don't understand as the slug is. thanks a lot ! François
EDIT ---- [PART DEUX](http://askville.amazon.com/deux-part-speech-sense-carry/AnswerViewer.do?requestId=13424467) OR [PART DEUX](http://www.urbandictionary.com/define.php?term=part%20deux) - The Dirty Sequal, The Term Saga Continues... --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Before anyone read this section, I will urge you to read everything I explained in **ORIGINAL ANSWER**. `wp_insert_term()` does not allow duplicate term names in non hierarchical taxonomies or in hierarchical taxonomies within the same hierarchy. From comments to my answer, the answer from OP and from the OP > > What i need is a way to have the same Name in the Taxonomy Hierarchy. > > > There is a way to achieve this, lets look at how: CAUTION - caution - CAUTION - caution !!!! ------------------------------------------ I went with a modified class of the `wp_insert_term()` function. As I said, there are protection inside `wp_insert_term()` to avoid duplicate term names. What I have done is to get rid of this protection in order to allow duplicate names within the same hierarchy. You basically need to remove the name check section and then the section that delete accidental duplicates when the term is already inserted. Because of this, this class will allow an unlimited amount of terms with the same name, so it should be used with **great care**. 100 accidental page loads will insert 100 terms with the same name. Here is the class with a few notes **NOTE:** * This requires at least PHP 5.4. * Although I ran a few test to check the class' operation, I have not run any complete test on this, so PLEASE PLEASE PLEASE, run this on a local test install first and verify everything properly * The class can be improved and modified as needed. I might have mixed syntaxes and scrambled code. This is just a very basic backbone with only the essentials Lets look at the code: ``` /** * WPInsertTerm class * * Class to insert terms into the db * * If term names are identical, in stead of throwing an error like * wp_insert_term(), the function will add valid term meta_key * * @author Pieter Goosen * @version 1.0.0 * @access public */ class WPInsertTerm { /** * Arguments to hold defaults * @since 1.0.0 * @var array */ protected $defaults = [ 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '' ]; /** * Arguments set by user * @since 1.0.0 * @var array */ protected $args = []; /** * Term to insert * @since 1.0.0 * @var string */ protected $term = null; /** * Taxonomy the term should belong to * @since 1.0.0 * @var string */ protected $taxonomy = null; /** * Constructor * * @param string $term = null * @param string $taxonomy = null * @param array $args = [] * @since 1.0.0 */ public function __construct( $term = null, $taxonomy = null, $args = [] ) { $this->term = $term; $this->taxonomy = $taxonomy; if ( is_array( $args ) ) { $this->args = array_merge( $this->defaults, $args ); } else { $this->args = $this->defaults; } } /** * Public method wpdb() * * Returns the global wpdb class * * @since 1.0.0 * @return $wpdb */ public function wpdb() { global $wpdb; return $wpdb; } /** * Private method validateVersion() * * Validate the current WordPress version * * @since 1.0.0 * @return $validateVersion */ private function validateVersion() { global $wp_version; $validateVersion = false; if ( '4.4' > $wp_version ) { throw new InvalidArgumentException( sprintf( __( 'Your WordpPress version is too old. A minimum version of WordPress 4.4 is expected. Please upgrade' ), __METHOD__ ) ); } return $validateVersion = true; } /** * Private method validateTaxonomy() * * Validate the $taxonomy value * * @since 1.0.0 * @return $validateTaxonomy */ private function validateTaxonomy() { $validateTaxonomy = filter_var( $this->taxonomy, FILTER_SANITIZE_STRING ); // Check if taxonomy is valid if ( !taxonomy_exists( $validateTaxonomy ) ) { throw new InvalidArgumentException( sprintf( __( 'Your taxonomy does not exists, please add a valid taxonomy' ), __METHOD__ ) ); } return $validateTaxonomy; } /** * Private method validateTerm() * * Validate the $term value * * @since 1.0.0 * @return $validateTerm */ private function validateTerm() { /** * Filter a term before it is sanitized and inserted into the database. * * @since 1.0.0 * * @param string $term The term to add or update. * @param string $taxonomy Taxonomy slug. */ $validateTerm = apply_filters( 'pre_insert_term', $this->term, $this->validateTaxonomy() ); // Check if the term is not empty if ( empty( $validateTerm ) ) { throw new InvalidArgumentException( sprintf( __( '$term should not be empty, please add a valid value' ), __METHOD__ ) ); } // Check if term is a valid integer if integer is passed if ( is_int( $validateTerm ) && 0 == $validateTerm ){ throw new InvalidArgumentException( sprintf( __('Invalid term id supplied, please asdd a valid value'), __METHOD__ ) ); } // Term is not empty, sanitize the term and trim any white spaces $validateTerm = filter_var( trim( $validateTerm ), FILTER_SANITIZE_STRING ); if ( empty( $validateTerm ) ){ throw new InvalidArgumentException( sprintf( __( 'Invalid term supplied, please asdd a valid term name' ), __METHOD__ ) ); } return $validateTerm; } /** * Private method parentExist() * * Validate if the parent term exist if passed * * @since 1.0.0 * @return $parentexist */ private function parentExist() { $parentExist = $this->args['parent']; if ( $parentExist > 0 && !term_exists( (int) $parentExist ) ) { throw new InvalidArgumentException( sprintf( __( 'Invalid parent ID supplied, no term exists with parent ID passed. Please add a valid parent ID' ), __METHOD__ ) ); } return $parentExist; } /** * Private method sanitizeTerm() * * Sanitize the term to insert * * @since 1.0.0 * @return $sanitizeTerm */ private function sanitizeTerm() { $taxonomy = $this->validateTaxonomy(); $arguments = $this->args; $arguments['taxonomy'] = $taxonomy; $arguments['name'] = $this->validateTerm(); $arguments['parent'] = $this->parentExist(); // Santize the term $arguments = sanitize_term( $arguments, $taxonomy, 'db' ); // Unslash name and description fields and cast parent to integer $arguments['name'] = wp_unslash( $arguments['name'] ); $arguments['description'] = wp_unslash( $arguments['description'] ); $arguments['parent'] = (int) $arguments['parent']; return (object) $arguments; } /** * Private method slug() * * Get or create a slug if no slug is set * * @since 1.0.0 * @return $slug */ private function slug() { $term = $this->sanitizeTerm(); $new_slug = $term->slug; if ( !$new_slug ) { $slug = sanitize_title( $term->name ); } else { $slug = $new_slug; } return $slug; } /** * Public method addTerm() * * Add the term to db * * @since 1.0.0 */ public function addTerm() { $wpdb = $this->wpdb(); $term = $this->sanitizeTerm(); $taxonomy = $term->taxonomy; $name = $term->name; $parent = $term->parent; $term_group = $term->term_group; $term_group = 0; if ( $term->alias_of ) { $alias = get_term_by( 'slug', $term->alias_of, $term->taxonomy ); if ( !empty( $alias->term_group ) ) { // The alias we want is already in a group, so let's use that one. $term_group = $alias->term_group; } elseif ( ! empty( $alias->term_id ) ) { /* * The alias is not in a group, so we create a new one * and add the alias to it. */ $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1; wp_update_term( $alias->term_id, $this->args['taxonomy'], [ 'term_group' => $term_group, ] ); } } $slug = wp_unique_term_slug( $this->slug(), $term ); if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) { return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error ); } $term_id = (int) $wpdb->insert_id; // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string. if ( empty( $slug ) ) { $slug = sanitize_title( $slug, $term_id ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_terms', $term_id, $taxonomy ); $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_terms', $term_id, $taxonomy ); } $tt_id = $wpdb->get_var( $wpdb->prepare( " SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d ", $taxonomy, $term_id ) ); if ( !empty($tt_id) ) { return [ 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id ]; } $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + ['count' => 0] ); $tt_id = (int) $wpdb->insert_id; /** * Fires immediately after a new term is created, before the term cache is cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( "create_term", $term_id, $tt_id, $taxonomy ); /** * Fires after a new term is created for a specific taxonomy. * * The dynamic portion of the hook name, `$taxonomy`, refers * to the slug of the taxonomy the term was created for. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "create_$taxonomy", $term_id, $tt_id ); /** * Filter the term ID after a new term is created. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Taxonomy term ID. */ $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id ); clean_term_cache($term_id, $taxonomy); /** * Fires after a new term is created, and after the term cache has been cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( 'created_term', $term_id, $tt_id, $taxonomy ); /** * Fires after a new term in a specific taxonomy is created, and after the term * cache has been cleaned. * * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "created_$taxonomy", $term_id, $tt_id ); return [ 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id ]; } } ``` You can then use it as follow: ``` $q = new WPInsertTerm( 'My Term', 'category', ['parent' => 1] ); $q->addTerm(); ``` Here we add our term, `My Term` to the parent term with ID `1` in build in taxonomy `category`. Note, running this 100 times will add 100 terms called `My Term` under parent term `1`. ADDITIONAL NOTES ---------------- * With the above, everything term name related queries should be avoided + By default, there are already an issue with term names in a `tax_query` in `WP_Query`. This class addition would make the use of the `name` field absolutely impossible + Getting terms by name should also be avoided at all costs as the wrong term will in all probability be returned. A final note, having several terms with the same name will be very very confusing and might open a few cans of rotten worms, so you will need to be absolutely sure that this is what you want ORIGINAL ANSWER =============== [`wp_insert_term()`](https://developer.wordpress.org/reference/functions/wp_insert_term/) is quite a busy function with a lot of stuff that goes on before a term is successfully added to a taxonomy. The first important section is this: ``` $slug_provided = ! empty( $args['slug'] ); if ( ! $slug_provided ) { $slug = sanitize_title( $name ); } else { $slug = $args['slug']; } ``` In short, what this means is, if you haven't explicitly set a slug, a slug will be created from the name given via the [`santitize_title()`](https://developer.wordpress.org/reference/functions/sanitize_title/) function. This is the basis which will decide whether a term will be added or not as the slug is the important part moving forward. So if we would want to insert a term with the name `My Term`, we would end up with a slug like `my-term` if we did not set a slug. The next important part is this: (*Which runs regardless if slug being where set or not*) ``` /* * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy, * unless a unique slug has been explicitly provided. */ $name_matches = get_terms( $taxonomy, array( 'name' => $name, 'hide_empty' => false, ) ); /* * The `name` match in `get_terms()` doesn't differentiate accented characters, * so we do a stricter comparison here. */ $name_match = null; if ( $name_matches ) { foreach ( $name_matches as $_match ) { if ( strtolower( $name ) === strtolower( $_match->name ) ) { $name_match = $_match; break; } } } ``` `$name` (*$name = wp\_unslash( $args['name'] );*) which is the name you have explicitely set is used to return all terms with a name matching `$name` to compare to the term you are trying to insert, if there are any. If there are any terms that exists by `$name`, a more exact match is done to match terms. As the description/docblock says *`get_terms()` doesn't differentiate accented characters*, so we might end up with terms having names like `my Term` and `My terM`. All letters are set to lower in this match, so all term names are set to `my term` for matching. This makes sense, because if those terms (*or any of the returned terms*) were created (*either back end or front end or programmically*) without having a slug set, names like `my Term` and `My terM` and our term `My Term` would all produce the same slug, `my-term`, so we would need elimanate such issues. The last important section here before a unique slug is created and the term inserted, is the following section ``` if ( $name_match ) { $slug_match = get_term_by( 'slug', $slug, $taxonomy ); if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) { if ( is_taxonomy_hierarchical( $taxonomy ) ) { $siblings = get_terms( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) ); $existing_term = null; if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) { $existing_term = $name_match; } elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) { $existing_term = $slug_match; } if ( $existing_term ) { return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id ); } } else { return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id ); } } } ``` This section only runs when we have positively identified any other term with the same name as the one we would like to insert. Again, this section runs regardless whther a slug has been set or not. The first thing that this section do is to return any matching term from db which matches our slug from the term we would want to insert which comes from the first section of code in the answer. Our slug is `my-term`. [`get_term_by()`](https://developer.wordpress.org/reference/functions/get_term_by/) either return a term object if there is a term that already in db which matches the term by slug of the term we would want to insert, or false if there is no term that already matches our term by slug. Now a lot of check is done here, the first is a condition that runs the following checks * Check if we have explicitely set a slug (`! $slug_provided`), return true if haven't * If the slug from a matching term (*from the second block of code in this answer*) matches the slug from the term we want to insert (*in this case `my-term`*). Retruns true if there is a match * Whether we have a term object returned from `get_term_by()`. If any of these three conditions return true, a check is then done to check if our taxonomy is hierarchical. If this returns false, ie, our taxonomy is non hierarchical like tags, the following error is returned: > > A term with the name provided already exists in this taxonomy. > > > quite obviously as we cannot have terms with the same name in a non hierarchical taxonomy. If this returns true, ie our taxonomy is hierarchical, all sibling terms is queried by parent (*which will be either `0` or whatever integer value we have explicitely set*). `wp_insert_term()` now do its final check before deciding to go ahead with inserting the term or not. A failure here would throw the error message you are refering to in your question > > A term with the name provided already exists with this parent > > > This is what the final check does: All the direct child terms are queried from db from the given taxonomy and parent (*which is either `0` or the value specified by you*). Remember that we are still inside the condition which states that there are terms matching the name of the term we want to insert. Two checks are done on the returned array of child categories: * The first check involves the following: The term's slug from the matched term `$name_match` are checked against the slug from our term, `my-term` (*remember this comes from block one of code in the answer*). Also, our term name that we have set, `My Term` are checked against all names from the direct children from our parent. * The second check is the following: A check is done to see if there was a term returned by `get_term_by()` and if the slug from the first block of code in this answer matches any slugs from the direct children from the parent term. If any of these conditions returns true, the > > A term with the name provided already exists with this parent. > > > error message is thrown and the term is not inserted. A false will in all probably lead to the term successfully being created and inserted. Now we can look at your question > > Why should the name be unique, don't understand as the slug is. > > > You can have duplicate names within a hierarchical taxonomy if, and **only if** * There are no term with a matching name on the same level in the hierarchy. So any two top level terms, or any two direct children from the same parent term cannot have the same name. This line: ``` if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) ``` of code prohibits that. * You can have the same names for terms in a hierarchical taxonomy if the term is in one top level parent, a child to that top level parent and one grandchild to that specific child, if and **only if** their slugs are unique. This line ``` elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) ``` prohibits terms with the same name having the same slug You cannot have terms with the same name in a non hierarchical taxonomy as they do not have parent/child type relationships So, if you are sure your taxonomy is hierarchical, and you slug is unique, it still does not mean you can have the same name, as you need to take parent into consideration. If your parent remain the same, regardless of unique slug being set, your term will not be inserted and will throw the error message you are seeing POSSIBLE WORKAROUND TO MAKE NAME UNIQUE --------------------------------------- The best will be to write a wrapper function where you use the same logic as `wp_insert_term()` to first check if there are already a term with the same name with the same parent, and if so, take the name and run some kind of function on the name to make it unique. I would encourage you to take all the logic in this answer, use it in a custom wrapper function to create a unique name, and play around with ideas. If you get stuck, feel free to post waht you have in a new question, and I'll be happy to take a look at it when I have time. Best of luck
211,626
<p>I want to use static HTML for a landing page on a WordPress site. For example:</p> <ul> <li><code>example.com</code> - WordPress already running in root folder</li> <li><code>landingPage.example.com</code> - I purchased this static landing page using ThemeForest</li> </ul>
[ { "answer_id": 211630, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>Just name the landing page file <code>index.html</code> and place it (and any assets) in the root directory, then add this to your <code>.htaccess</code> (assuming you're using Apache):</p>\n\n<pre><code>DirectoryIndex index.html index.php\n</code></pre>\n\n<p>When accessing <code>http://example.com</code>, Apache will serve <code>index.html</code>. WordPress will scoop up all other requests with it's rewrite rules.</p>\n" }, { "answer_id": 238719, "author": "user102499", "author_id": 102499, "author_profile": "https://wordpress.stackexchange.com/users/102499", "pm_score": -1, "selected": false, "text": "<ol>\n<li>extract the template's files and rename the index.html file to index.php</li>\n<li>add all the files to a .ZIP archive again</li>\n<li>create a new empty folder in the root folder of your WordPress website and upload your .ZIP file into the folder you’ve just created</li>\n<li>unzip them and don't forget to delete the .ZIP file</li>\n</ol>\n\n<p>Source with screenshots: <a href=\"http://www.templatemonster.com/blog/integrate-static-html-wordpress/\" rel=\"nofollow\">http://www.templatemonster.com/blog/integrate-static-html-wordpress/</a></p>\n" }, { "answer_id": 238721, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Go to your <strong>hosting cpanel</strong></li>\n<li>Go to <strong>domains</strong> section</li>\n<li>Create a <strong>sub domain</strong> for your <code>(example.com)</code> domain</li>\n<li>Enter the name of the domain <code>landingpage</code></li>\n</ol>\n\n<p>After creating sub domain it will add <code>landingPage</code> folder in the root of your hosting filemanager. place the template there and it will be accessed through <code>landingPage.example.com</code></p>\n" } ]
2015/12/12
[ "https://wordpress.stackexchange.com/questions/211626", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85229/" ]
I want to use static HTML for a landing page on a WordPress site. For example: * `example.com` - WordPress already running in root folder * `landingPage.example.com` - I purchased this static landing page using ThemeForest
Just name the landing page file `index.html` and place it (and any assets) in the root directory, then add this to your `.htaccess` (assuming you're using Apache): ``` DirectoryIndex index.html index.php ``` When accessing `http://example.com`, Apache will serve `index.html`. WordPress will scoop up all other requests with it's rewrite rules.
211,628
<p>Just upgraded to WordPress 4.4 and I notice now my users' profile page in admin, there's a section called "profile picture", with a link to Gravatar.</p> <p>The plugin I'm developing restricts a lot of things in profile.php; unfortunately by deleting from the DOM via jQuery:</p> <pre><code>jQuery( document ).ready(function() { jQuery( "h2:contains('Personal Options')" ).remove(); jQuery( "h2:contains('Name')" ).remove(); jQuery( "h2:contains('Contact Info')" ).remove(); jQuery( "h2:contains('About Yourself')" ).remove(); jQuery( "h2:contains('Account Management')" ).remove(); jQuery( "tr.show-admin-bar" ).parents("table:first").remove(); jQuery( "tr.user-first-name-wrap" ).remove(); jQuery( "tr.user-last-name-wrap" ).remove(); jQuery( "tr.user-nickname-wrap" ).remove(); jQuery( "tr.user-display-name-wrap" ).remove(); jQuery( "tr.user-url-wrap" ).remove(); jQuery( "tr.user-description-wrap").parents("table:first").remove(); jQuery( ".user-sessions-wrap" ).remove(); }); </code></pre> <p>Before I continue on the jQuery addiction, is there a better way to do this (aside from output buffer replacement)? Also, is there some other setting specifically for the user profile picture, or is this jQuery solution going to be the answer for now?</p>
[ { "answer_id": 211650, "author": "Por", "author_id": 31832, "author_profile": "https://wordpress.stackexchange.com/users/31832", "pm_score": 0, "selected": false, "text": "<p>Here is simple solutions for that, add more ids to hide more fields</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;/* &lt;![CDATA[ */\nvar hideFields = [ \"aim\", \"yim\", \"jabber\" ];\njQuery.each( jQuery( \"form#your-profile tr\" ), function() {\n var field = jQuery( this ).find( \"input,textarea,select\" ).attr( \"id\" );\n if ( hideFields.indexOf( field ) != -1 ) {\n jQuery( this ).remove();\n }\n});\n/* ]]&gt; */&lt;/script&gt;\n</code></pre>\n\n<p>Or you could use <a href=\"https://wordpress.org/plugins/hide-user-profile-fields\" rel=\"nofollow\">Hide Profile fields plugin</a></p>\n" }, { "answer_id": 211653, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Deleting things from DOM is not truly deleting them. If all you want is better GUI then it can be a valid technique but if you want to actually prevent people from messing around with those fields (lets say for security reason) then it is not enough.</p>\n\n<p>Maybe a bigger problem with your code is that you try to identify text which means that the plugin will fail for non english installs and sometimes even for english ones.</p>\n\n<p>Next problem is that other plugins might add their own fields leaving the page with a strange display.</p>\n\n<p>If you need a very tightly controlled profile page then you should write one and let user access only it. The built-in profile page is not flexible enough right now to easily add/remove or change permissions for its various components (this is a general statement, some components are more flexible then others).</p>\n" }, { "answer_id": 211955, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>We can use the <code>show_avatars</code> option to remove the <em>Profile Picture</em> section.</p>\n\n<ul>\n<li><p>We can visit <code>/wp-admin/options.php</code> to turn it off manually.</p></li>\n<li><p>Or update it with:</p>\n\n<pre><code>update_option( 'show_avatars', 0 );\n</code></pre></li>\n<li><p>Or modify it through a filter:</p>\n\n<pre><code>add_filter( 'option_show_avatars', '__return_false' );\n</code></pre></li>\n<li><p>We could also restrict it to the <code>profile.php</code> page:</p>\n\n<pre><code>add_action( 'load-profile.php', function()\n{\n add_filter( 'option_show_avatars', '__return_false' );\n} );\n</code></pre></li>\n</ul>\n" }, { "answer_id": 323814, "author": "Phill Healey", "author_id": 55152, "author_profile": "https://wordpress.stackexchange.com/users/55152", "pm_score": 2, "selected": false, "text": "<p>There are some hooks to remove certain parts of the profile page. Additionally you can just use php to buffer the page output and then strip the relevant content. </p>\n\n<pre><code>// Remove fields from Admin profile page\nif (!function_exists('CCK_remove_profile_options')) {\nfunction CCK_remove_profile_options($subject)\n{\n $subject = preg_replace('#&lt;h2&gt;' . __(\"Personal Options\") . '&lt;/h2&gt;#s', '', $subject, 1); // Remove the \"Personal Options\" title\n $subject = preg_replace('#&lt;tr class=\"user-syntax-highlighting-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Syntax Highlighting\" field\n $subject = preg_replace('#&lt;tr class=\"user-rich-editing-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Visual Editor\" field\n $subject = preg_replace('#&lt;tr class=\"user-comment-shortcuts-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Keyboard Shortcuts\" field\n $subject = preg_replace('#&lt;tr class=\"show-admin-bar(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Toolbar\" field\n //$subject = preg_replace('#&lt;h2&gt;'.__(\"Name\").'&lt;/h2&gt;#s', '', $subject, 1); // Remove the \"Name\" title\n //$subject = preg_replace('#&lt;tr class=\"user-display-name-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Display name publicly as\" field\n $subject = preg_replace('#&lt;h2&gt;' . __(\"Contact Info\") . '&lt;/h2&gt;#s', '&lt;h2&gt;' . __(\"Login Management\") . '&lt;/h2&gt;', $subject, 1); // Remove the \"Contact Info\" title\n $subject = preg_replace('#&lt;tr class=\"user-url-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Website\" field\n $subject = preg_replace('#&lt;tr class=\"user-googleplus-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Google+\" field\n $subject = preg_replace('#&lt;tr class=\"user-twitter-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Website\" field\n $subject = preg_replace('#&lt;tr class=\"user-facebook-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Website\" field\n $subject = preg_replace('#&lt;h2&gt;' . __(\"Account Management\") . '&lt;/h2&gt;#s', '', $subject, 1); // Remove the \"About Yourself\" title\n $subject = preg_replace('#&lt;h2&gt;' . __(\"About Yourself\") . '&lt;/h2&gt;#s', '', $subject, 1); // Remove the \"About Yourself\" title\n $subject = preg_replace('#&lt;h2&gt;' . __(\"About the user\") . '&lt;/h2&gt;#s', '', $subject, 1); // Remove the \"About Yourself\" title\n $subject = preg_replace('#&lt;tr class=\"user-description-wrap(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Biographical Info\" field\n //$subject = preg_replace('#&lt;tr class=\"user-profile-picture(.*?)&lt;/tr&gt;#s', '', $subject, 1); // Remove the \"Profile Picture\" field\n\n //$subject = preg_replace('#&lt;h3&gt;' . __(\"User Expiry Information\") . '&lt;/h3&gt;#s', '', $subject, 1); // Remove the \"Expire Users Data\" title\n return $subject;\n}\n\nfunction CCK_profile_subject_start()\n{\n //if ( /*!*/ current_user_can('manage_options') ) {\n ob_start('CCK_remove_profile_options');\n //}\n}\n\nfunction CCK_profile_subject_end()\n{\n //if ( /*!*/ current_user_can('manage_options') ) {\n ob_end_flush();\n //}\n}\n}\nadd_action('admin_head', 'CCK_profile_subject_start');\nadd_action('admin_footer', 'CCK_profile_subject_end');\n// Removes ability to change Theme color for the users\nremove_action('admin_color_scheme_picker', 'admin_color_scheme_picker'); \n</code></pre>\n" } ]
2015/12/12
[ "https://wordpress.stackexchange.com/questions/211628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
Just upgraded to WordPress 4.4 and I notice now my users' profile page in admin, there's a section called "profile picture", with a link to Gravatar. The plugin I'm developing restricts a lot of things in profile.php; unfortunately by deleting from the DOM via jQuery: ``` jQuery( document ).ready(function() { jQuery( "h2:contains('Personal Options')" ).remove(); jQuery( "h2:contains('Name')" ).remove(); jQuery( "h2:contains('Contact Info')" ).remove(); jQuery( "h2:contains('About Yourself')" ).remove(); jQuery( "h2:contains('Account Management')" ).remove(); jQuery( "tr.show-admin-bar" ).parents("table:first").remove(); jQuery( "tr.user-first-name-wrap" ).remove(); jQuery( "tr.user-last-name-wrap" ).remove(); jQuery( "tr.user-nickname-wrap" ).remove(); jQuery( "tr.user-display-name-wrap" ).remove(); jQuery( "tr.user-url-wrap" ).remove(); jQuery( "tr.user-description-wrap").parents("table:first").remove(); jQuery( ".user-sessions-wrap" ).remove(); }); ``` Before I continue on the jQuery addiction, is there a better way to do this (aside from output buffer replacement)? Also, is there some other setting specifically for the user profile picture, or is this jQuery solution going to be the answer for now?
We can use the `show_avatars` option to remove the *Profile Picture* section. * We can visit `/wp-admin/options.php` to turn it off manually. * Or update it with: ``` update_option( 'show_avatars', 0 ); ``` * Or modify it through a filter: ``` add_filter( 'option_show_avatars', '__return_false' ); ``` * We could also restrict it to the `profile.php` page: ``` add_action( 'load-profile.php', function() { add_filter( 'option_show_avatars', '__return_false' ); } ); ```
211,647
<p>I'm a developer of a private Wp plugin that has been running for 3+ yrs. The plugin displays in table format users custom information. I just upgraded to v 4.4 and now I'm getting a fatal error: Fatal error: Call to undefined method stdClass::render_screen_reader_content() in .../wp-admin/includes/class-wp-list-table.php on line 760</p> <p>This is from $myclassextention->display();</p> <p>If I look at earlier versions the public display function is completely different now from the earlier versions.</p> <p>I'm not sure what to do...apparently I'm not the only one ... <a href="https://wordpress.org/support/topic/fatal-error-in-admin-pages-after-upgrading-to-wordpress-44">https://wordpress.org/support/topic/fatal-error-in-admin-pages-after-upgrading-to-wordpress-44</a></p> <p>Any thoughts? I was thinking of building the table in Bootstrap...and need to get this resolved ASAP...I have over 1100 users using this. The support tickets will start rolling in soon. </p> <p>BTW this is on a multi-site and rollback is not an option. </p> <p>Thanks for looking.</p> <p>PS...I can't post to WordPress tag because I don't have enough points? Really! That's just weird!</p> <p>EDIT: Here is the format I'm using ...I can't show the exact code.</p> <p>I tried posting the code and turned into a big mess...here is the template I based it on <a href="https://wordpress.org/plugins/custom-list-table-example/">https://wordpress.org/plugins/custom-list-table-example/</a> ...like I said this has been working for 3yrs with over 1100+ users. </p>
[ { "answer_id": 211695, "author": "TECC1", "author_id": 83840, "author_profile": "https://wordpress.stackexchange.com/users/83840", "pm_score": 3, "selected": false, "text": "<p>This has been resolved</p>\n\n<p>Had to add 2 new files ...looks like Wordpress moved some methods to new locations. </p>\n\n<p>These are the files that worked for me</p>\n\n<pre><code>// Include WP's list table class\nif(!class_exists('WP_List_Table')){\n require_once( ABSPATH . 'wp-admin/includes/class-wp-screen.php' );//added\n require_once( ABSPATH . 'wp-admin/includes/screen.php' );//added\n require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );\n require_once( ABSPATH . 'wp-admin/includes/template.php' );\n}\n</code></pre>\n\n<p>Thanks for all who looked. </p>\n" }, { "answer_id": 212368, "author": "Adi Kusuma", "author_id": 85591, "author_profile": "https://wordpress.stackexchange.com/users/85591", "pm_score": 3, "selected": false, "text": "<p>Nice solution you have there. But you must define a $screen property inside WP_List_Table class (or its child class) before pagination method is invoked.</p>\n\n<p>You want to make the $screen property as WP_Screen instance using this function :</p>\n\n<pre><code>$this-&gt;screen = get_current_screen();\n</code></pre>\n\n<p>There you go, and your table is ready to go.</p>\n\n<p>Thanks</p>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83840/" ]
I'm a developer of a private Wp plugin that has been running for 3+ yrs. The plugin displays in table format users custom information. I just upgraded to v 4.4 and now I'm getting a fatal error: Fatal error: Call to undefined method stdClass::render\_screen\_reader\_content() in .../wp-admin/includes/class-wp-list-table.php on line 760 This is from $myclassextention->display(); If I look at earlier versions the public display function is completely different now from the earlier versions. I'm not sure what to do...apparently I'm not the only one ... <https://wordpress.org/support/topic/fatal-error-in-admin-pages-after-upgrading-to-wordpress-44> Any thoughts? I was thinking of building the table in Bootstrap...and need to get this resolved ASAP...I have over 1100 users using this. The support tickets will start rolling in soon. BTW this is on a multi-site and rollback is not an option. Thanks for looking. PS...I can't post to WordPress tag because I don't have enough points? Really! That's just weird! EDIT: Here is the format I'm using ...I can't show the exact code. I tried posting the code and turned into a big mess...here is the template I based it on <https://wordpress.org/plugins/custom-list-table-example/> ...like I said this has been working for 3yrs with over 1100+ users.
This has been resolved Had to add 2 new files ...looks like Wordpress moved some methods to new locations. These are the files that worked for me ``` // Include WP's list table class if(!class_exists('WP_List_Table')){ require_once( ABSPATH . 'wp-admin/includes/class-wp-screen.php' );//added require_once( ABSPATH . 'wp-admin/includes/screen.php' );//added require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); require_once( ABSPATH . 'wp-admin/includes/template.php' ); } ``` Thanks for all who looked.
211,655
<p>I am trying to create a member directory and using a custom post type members. I am familiar on how to use the ACF plugin but is there any methods on how to associate a custom field for a specific custom post type to have a simple input box like phone number and address?</p>
[ { "answer_id": 211760, "author": "Carl Alberto", "author_id": 60720, "author_profile": "https://wordpress.stackexchange.com/users/60720", "pm_score": 4, "selected": true, "text": "<p>If you don't want to use a plugin, you can try implementing a meta box to be associated with that custom post type, This is the code that I use if I want to add a simple input field for a certain post type, in the example below, I assume that the <strong>member_post_type</strong> is your declared post type:</p>\n\n<pre><code>function member_add_meta_box() {\n//this will add the metabox for the member post type\n$screens = array( 'member_post_type' );\n\nforeach ( $screens as $screen ) {\n\n add_meta_box(\n 'member_sectionid',\n __( 'Member Details', 'member_textdomain' ),\n 'member_meta_box_callback',\n $screen\n );\n }\n}\nadd_action( 'add_meta_boxes', 'member_add_meta_box' );\n\n/**\n * Prints the box content.\n *\n * @param WP_Post $post The object for the current post/page.\n */\nfunction member_meta_box_callback( $post ) {\n\n// Add a nonce field so we can check for it later.\nwp_nonce_field( 'member_save_meta_box_data', 'member_meta_box_nonce' );\n\n/*\n * Use get_post_meta() to retrieve an existing value\n * from the database and use the value for the form.\n */\n$value = get_post_meta( $post-&gt;ID, '_my_meta_value_key', true );\n\necho '&lt;label for=\"member_new_field\"&gt;';\n_e( 'Phone Number', 'member_textdomain' );\necho '&lt;/label&gt; ';\necho '&lt;input type=\"text\" id=\"member_new_field\" name=\"member_new_field\" value=\"' . esc_attr( $value ) . '\" size=\"25\" /&gt;';\n}\n\n/**\n * When the post is saved, saves our custom data.\n *\n * @param int $post_id The ID of the post being saved.\n */\n function member_save_meta_box_data( $post_id ) {\n\n if ( ! isset( $_POST['member_meta_box_nonce'] ) ) {\n return;\n }\n\n if ( ! wp_verify_nonce( $_POST['member_meta_box_nonce'], 'member_save_meta_box_data' ) ) {\n return;\n }\n\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n // Check the user's permissions.\n if ( isset( $_POST['post_type'] ) &amp;&amp; 'page' == $_POST['post_type'] ) {\n\n if ( ! current_user_can( 'edit_page', $post_id ) ) {\n return;\n }\n\n } else {\n\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return;\n }\n }\n\n if ( ! isset( $_POST['member_new_field'] ) ) {\n return;\n }\n\n $my_data = sanitize_text_field( $_POST['member_new_field'] );\n\n update_post_meta( $post_id, '_my_meta_value_key', $my_data );\n}\nadd_action( 'save_post', 'member_save_meta_box_data' );\n</code></pre>\n\n<p><strong>Additional Resources for the WordPress Metaboxes:</strong></p>\n\n<p>please see documentation <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 211796, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>As I already stated in comments, </p>\n\n<blockquote>\n <p><a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow\">Custom fields</a> are already a build in feature. You just need to add support for it when registering your custom post type ;-)</p>\n</blockquote>\n\n<p>You have two options here:</p>\n\n<ul>\n<li><p>When you <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow\">register your custom post type</a>, simply add <code>custom-fields</code> to the <code>supports</code> parameter</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'init', 'codex_custom_init' );\nfunction codex_custom_init() {\n $args = [\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'supports' =&gt; ['title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields']\n ];\n register_post_type( 'book', $args );\n}\n</code></pre></li>\n<li><p>You can simply use <a href=\"https://codex.wordpress.org/Function_Reference/add_post_type_support\" rel=\"nofollow\"><code>add_post_type_support()</code></a> to add custom fields to your custom post type</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'init', 'wpcodex_add_custom_fileds_support_for_cpt', 11 );\nfunction wpcodex_add_custom_fileds_support_for_cpt() {\n add_post_type_support( 'cpt', 'custom-fields' ); // Change cpt to your post type\n}\n</code></pre></li>\n</ul>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211655", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85192/" ]
I am trying to create a member directory and using a custom post type members. I am familiar on how to use the ACF plugin but is there any methods on how to associate a custom field for a specific custom post type to have a simple input box like phone number and address?
If you don't want to use a plugin, you can try implementing a meta box to be associated with that custom post type, This is the code that I use if I want to add a simple input field for a certain post type, in the example below, I assume that the **member\_post\_type** is your declared post type: ``` function member_add_meta_box() { //this will add the metabox for the member post type $screens = array( 'member_post_type' ); foreach ( $screens as $screen ) { add_meta_box( 'member_sectionid', __( 'Member Details', 'member_textdomain' ), 'member_meta_box_callback', $screen ); } } add_action( 'add_meta_boxes', 'member_add_meta_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function member_meta_box_callback( $post ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'member_save_meta_box_data', 'member_meta_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_my_meta_value_key', true ); echo '<label for="member_new_field">'; _e( 'Phone Number', 'member_textdomain' ); echo '</label> '; echo '<input type="text" id="member_new_field" name="member_new_field" value="' . esc_attr( $value ) . '" size="25" />'; } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function member_save_meta_box_data( $post_id ) { if ( ! isset( $_POST['member_meta_box_nonce'] ) ) { return; } if ( ! wp_verify_nonce( $_POST['member_meta_box_nonce'], 'member_save_meta_box_data' ) ) { return; } if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } if ( ! isset( $_POST['member_new_field'] ) ) { return; } $my_data = sanitize_text_field( $_POST['member_new_field'] ); update_post_meta( $post_id, '_my_meta_value_key', $my_data ); } add_action( 'save_post', 'member_save_meta_box_data' ); ``` **Additional Resources for the WordPress Metaboxes:** please see documentation [here](https://codex.wordpress.org/Function_Reference/add_meta_box)
211,662
<p>I upgraded from Windows 7 to Windows 10, and had to reinstall WampServer to get it running.</p> <p>I'd like to reinstall Wordpress for a local WampServer site.</p> <p>I have deleted the old database and username, and created a new user + associated database of the same name. I left the password blank.</p> <p>When I try to run the install, I get to <code>http://ssdhdd/wp-admin/setup-config.php?step=2</code> and the error:</p> <blockquote> <p>Can’t select database </p> <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the example database.</p> <p>Are you sure it exists? Does the user example have permission to use the example database? On some systems the name of your database is prefixed with your username, so it would be like username_example. Could that be the problem?</p> </blockquote> <p>I have confirmed the database name is correct.</p> <p>I've confirmed the user has correct privileges to the database + global privileges.</p> <p>Any ideas?</p>
[ { "answer_id": 211760, "author": "Carl Alberto", "author_id": 60720, "author_profile": "https://wordpress.stackexchange.com/users/60720", "pm_score": 4, "selected": true, "text": "<p>If you don't want to use a plugin, you can try implementing a meta box to be associated with that custom post type, This is the code that I use if I want to add a simple input field for a certain post type, in the example below, I assume that the <strong>member_post_type</strong> is your declared post type:</p>\n\n<pre><code>function member_add_meta_box() {\n//this will add the metabox for the member post type\n$screens = array( 'member_post_type' );\n\nforeach ( $screens as $screen ) {\n\n add_meta_box(\n 'member_sectionid',\n __( 'Member Details', 'member_textdomain' ),\n 'member_meta_box_callback',\n $screen\n );\n }\n}\nadd_action( 'add_meta_boxes', 'member_add_meta_box' );\n\n/**\n * Prints the box content.\n *\n * @param WP_Post $post The object for the current post/page.\n */\nfunction member_meta_box_callback( $post ) {\n\n// Add a nonce field so we can check for it later.\nwp_nonce_field( 'member_save_meta_box_data', 'member_meta_box_nonce' );\n\n/*\n * Use get_post_meta() to retrieve an existing value\n * from the database and use the value for the form.\n */\n$value = get_post_meta( $post-&gt;ID, '_my_meta_value_key', true );\n\necho '&lt;label for=\"member_new_field\"&gt;';\n_e( 'Phone Number', 'member_textdomain' );\necho '&lt;/label&gt; ';\necho '&lt;input type=\"text\" id=\"member_new_field\" name=\"member_new_field\" value=\"' . esc_attr( $value ) . '\" size=\"25\" /&gt;';\n}\n\n/**\n * When the post is saved, saves our custom data.\n *\n * @param int $post_id The ID of the post being saved.\n */\n function member_save_meta_box_data( $post_id ) {\n\n if ( ! isset( $_POST['member_meta_box_nonce'] ) ) {\n return;\n }\n\n if ( ! wp_verify_nonce( $_POST['member_meta_box_nonce'], 'member_save_meta_box_data' ) ) {\n return;\n }\n\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n // Check the user's permissions.\n if ( isset( $_POST['post_type'] ) &amp;&amp; 'page' == $_POST['post_type'] ) {\n\n if ( ! current_user_can( 'edit_page', $post_id ) ) {\n return;\n }\n\n } else {\n\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return;\n }\n }\n\n if ( ! isset( $_POST['member_new_field'] ) ) {\n return;\n }\n\n $my_data = sanitize_text_field( $_POST['member_new_field'] );\n\n update_post_meta( $post_id, '_my_meta_value_key', $my_data );\n}\nadd_action( 'save_post', 'member_save_meta_box_data' );\n</code></pre>\n\n<p><strong>Additional Resources for the WordPress Metaboxes:</strong></p>\n\n<p>please see documentation <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 211796, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>As I already stated in comments, </p>\n\n<blockquote>\n <p><a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow\">Custom fields</a> are already a build in feature. You just need to add support for it when registering your custom post type ;-)</p>\n</blockquote>\n\n<p>You have two options here:</p>\n\n<ul>\n<li><p>When you <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow\">register your custom post type</a>, simply add <code>custom-fields</code> to the <code>supports</code> parameter</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'init', 'codex_custom_init' );\nfunction codex_custom_init() {\n $args = [\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'supports' =&gt; ['title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields']\n ];\n register_post_type( 'book', $args );\n}\n</code></pre></li>\n<li><p>You can simply use <a href=\"https://codex.wordpress.org/Function_Reference/add_post_type_support\" rel=\"nofollow\"><code>add_post_type_support()</code></a> to add custom fields to your custom post type</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'init', 'wpcodex_add_custom_fileds_support_for_cpt', 11 );\nfunction wpcodex_add_custom_fileds_support_for_cpt() {\n add_post_type_support( 'cpt', 'custom-fields' ); // Change cpt to your post type\n}\n</code></pre></li>\n</ul>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
I upgraded from Windows 7 to Windows 10, and had to reinstall WampServer to get it running. I'd like to reinstall Wordpress for a local WampServer site. I have deleted the old database and username, and created a new user + associated database of the same name. I left the password blank. When I try to run the install, I get to `http://ssdhdd/wp-admin/setup-config.php?step=2` and the error: > > Can’t select database > > > We were able to connect to the database server > (which means your username and password is okay) but not able to > select the example database. > > > Are you sure it exists? Does the user example have permission to use > the example database? On some systems the name of your database is > prefixed with your username, so it would be like username\_example. > Could that be the problem? > > > I have confirmed the database name is correct. I've confirmed the user has correct privileges to the database + global privileges. Any ideas?
If you don't want to use a plugin, you can try implementing a meta box to be associated with that custom post type, This is the code that I use if I want to add a simple input field for a certain post type, in the example below, I assume that the **member\_post\_type** is your declared post type: ``` function member_add_meta_box() { //this will add the metabox for the member post type $screens = array( 'member_post_type' ); foreach ( $screens as $screen ) { add_meta_box( 'member_sectionid', __( 'Member Details', 'member_textdomain' ), 'member_meta_box_callback', $screen ); } } add_action( 'add_meta_boxes', 'member_add_meta_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function member_meta_box_callback( $post ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'member_save_meta_box_data', 'member_meta_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_my_meta_value_key', true ); echo '<label for="member_new_field">'; _e( 'Phone Number', 'member_textdomain' ); echo '</label> '; echo '<input type="text" id="member_new_field" name="member_new_field" value="' . esc_attr( $value ) . '" size="25" />'; } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function member_save_meta_box_data( $post_id ) { if ( ! isset( $_POST['member_meta_box_nonce'] ) ) { return; } if ( ! wp_verify_nonce( $_POST['member_meta_box_nonce'], 'member_save_meta_box_data' ) ) { return; } if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } if ( ! isset( $_POST['member_new_field'] ) ) { return; } $my_data = sanitize_text_field( $_POST['member_new_field'] ); update_post_meta( $post_id, '_my_meta_value_key', $my_data ); } add_action( 'save_post', 'member_save_meta_box_data' ); ``` **Additional Resources for the WordPress Metaboxes:** please see documentation [here](https://codex.wordpress.org/Function_Reference/add_meta_box)
211,666
<p>I want to add a front end post editing functionality to one of my Wordpress sites. I found a few plugins that do this, but they don't fits all my needs, so I decided to adapt <a href="http://voodoopress.com/edit-and-delete-posts-from-front-end-with-no-plugin-part-2/" rel="nofollow">an existing solution</a> to develop a my own plugin that will return with a shortcode a front end editing form. My plugin works, I can edit and save posts, but <strong>I can't solve a warning</strong> and <strong>I don't have (yet) sufficient knowledge to make this plugin more secure</strong>. Any suggestions?</p> <p>The warning:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at .../wp-content/plugins/front-post-edit.php:139) in .../wp-includes/pluggable.php on line 1228</p> </blockquote> <p><em>P.S. The 139 line is the last line in my plugin (a line without code).</em></p> <p>My plugin code:</p> <pre><code>&lt;?php /* * Plugin Name: Front Post Editor * */ add_shortcode( 'front_post_edit', 'post_shortcode' ); function post_shortcode() { return getForm(); } function getForm() { if ( !is_user_logged_in()) { echo '&lt;p class="alert-box notice"&gt;You must be &lt;a href="' . esc_url( wp_login_url( get_permalink() ) ) . '" title="Login"&gt;logged in&lt;/a&gt;!'; } else { if( 'POST' == $_SERVER['REQUEST_METHOD'] &amp;&amp; !empty( $_POST['action'] ) &amp;&amp; $_POST['action'] == "edit_post" &amp;&amp; isset($_POST['postid'])) { $post_to_edit = array(); $post_to_edit = get_post($_POST['postid']); /* these are the fields that we are editing in the form below */ $title = $_POST['item_title']; $description = $_POST['item_description']; $category = $_POST['item_category']; $location = $_POST['item_location']; $location2 = $_POST['item_location2']; /* this code will save the title and description into the post_to_edit array */ $post_to_edit-&gt;post_title = $title; $post_to_edit-&gt;post_content = $description; /* this code is a must */ $pid = wp_update_post($post_to_edit); /* save taxonomies: post ID, form field name, taxonomy name, if it appends(true) or rewrite(false) */ wp_set_post_terms($pid, array($_POST['item_category']),'category',false); wp_set_post_terms($pid, array($_POST['item_location']),'location',false); /* update custom fields with the new info */ update_post_meta($pid, 'item_location2', $location2); /* redirect user after done editing */ wp_redirect( home_url( '/myposts' ) ); } /* get post to edit */ $post_to_edit = get_post($_POST['postid']); /* get this post's category taxonomy term id */ $term_name = strip_tags( get_the_term_list( $post_to_edit-&gt;ID, 'category', '', ', ', '' ) ); $term_obj = get_term_by('name', $term_name, 'category'); $term_id = $term_obj-&gt;term_id; /* array for wp_dropdown_category to display with the current post category selected by default */ $args_cat = array( 'selected' =&gt; $term_id, 'name' =&gt; 'item_category', 'class' =&gt; 'postform', 'tab_index' =&gt; 10, 'depth' =&gt; 2, 'hierarchical' =&gt; 1, 'taxonomy' =&gt; 'category', 'hide_empty' =&gt; false ); /* get this post's location taxonomy term id */ $term_name2 = strip_tags( get_the_term_list( $post_to_edit-&gt;ID, 'location', '', ', ', '' ) ); $term_obj2 = get_term_by('name', $term_name2, 'location'); $term_id2 = $term_obj2-&gt;term_id; $args_loc = array( 'selected' =&gt; $term_id2, 'name' =&gt; 'item_location', 'class' =&gt; 'postform', 'tab_index' =&gt; 10, 'depth' =&gt; 2, 'hierarchical' =&gt; 1, 'taxonomy' =&gt; 'location', 'hide_empty' =&gt; false ); ?&gt; &lt;!-- EDIT FORM --&gt; &lt;form id="edit_post" name="edit_post" method="post" action="" enctype="multipart/form-data"&gt; &lt;!-- post name --&gt; &lt;fieldset name="item_title"&gt; &lt;label for="item_title"&gt;Item title:&lt;/label&gt;&lt;br /&gt; &lt;input type="text" id="item_title" value="&lt;?php echo $post_to_edit-&gt;post_title; ?&gt;" tabindex="5" name="item_title" /&gt; &lt;/fieldset&gt; &lt;!-- post Content --&gt; &lt;fieldset class="item_description"&gt; &lt;label for="item_description"&gt;Item description:&lt;/label&gt;&lt;br /&gt; &lt;textarea id="item_description" tabindex="15" name="item_description"&gt;&lt;?php echo $post_to_edit-&gt;post_content; ?&gt;&lt;/textarea&gt; &lt;/fieldset&gt; &lt;!-- post Category --&gt; &lt;fieldset id="item_category"&gt; &lt;label for="item_category"&gt;Item category:&lt;/label&gt; &lt;?php wp_dropdown_categories( $args_cat ); ?&gt; &lt;/fieldset&gt; &lt;!-- post Location --&gt; &lt;fieldset id="item_location"&gt; &lt;label for="item_location"&gt;Item location:&lt;/label&gt; &lt;?php wp_dropdown_categories( $args_loc ); ?&gt; &lt;/fieldset&gt; &lt;!-- custom fields --&gt; &lt;fieldset class="item_location2"&gt; &lt;label for="item_location2"&gt;Location 2:&lt;/label&gt;&lt;br /&gt; &lt;input type="text" value="&lt;?php echo get_post_meta($post_to_edit-&gt;ID,'item_location2', true); ?&gt;" id="item_location2" tabindex="20" name="item_location2" /&gt; &lt;/fieldset&gt; &lt;!-- submit button --&gt; &lt;fieldset class="submit"&gt; &lt;input type="submit" value="Save Post" tabindex="40" id="submit" name="submit" /&gt; &lt;/fieldset&gt; &lt;input type="hidden" name="postid" value="&lt;?php echo $post_to_edit-&gt;ID; ?&gt;" /&gt; &lt;!-- DONT REMOVE OR CHANGE --&gt; &lt;input type="hidden" name="action" value="edit_post" /&gt; &lt;!-- DONT REMOVE OR CHANGE --&gt; &lt;input type="hidden" name="change_cat" value="" /&gt; &lt;!-- DONT REMOVE OR CHANGE --&gt; &lt;?php // wp_nonce_field( 'new-post' ); ?&gt; &lt;/form&gt; &lt;!-- END OF FORM --&gt; &lt;?php } ?&gt;&lt;!-- user is logged in --&gt; &lt;?php } ?&gt;&lt;!-- getForm --&gt; </code></pre> <p>An <em>Edit</em> button was added to the footer of each entry generated by a loop with this form:</p> <pre><code>&lt;form class="edit-post" action="&lt;?php echo home_url( '/edit'); ?&gt;" method="post"&gt; &lt;input type="hidden" name="postid" value="&lt;?php the_ID(); ?&gt;" /&gt; &lt;input type="submit" value="Edit" /&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 211674, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>From the code it seems like your warning comes from doing the redirect too late. redirects should be done, as a rule of thumb, not later then the init action. And after the redirect you should die() (I don't think the <code>wp_redirect</code> does it for you)</p>\n\n<p>As for security, it is not enough to check that the user is logged-in, you need to check if he has the capability to edit the post, something like <code>if current_user_can('edit_post',$post_id)</code>. You need to check it both on the UI side and server side. just because you do not show the ability to the hacker doesn't mean he will not construct a special HTTP request to change the post if you don't have protection on the server side.</p>\n" }, { "answer_id": 212165, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 0, "selected": false, "text": "<p>After some learning and research I abandoned the approach described in my question, indeed I figured out how to add the front end editing functionality using the @TheDeadMedic <a href=\"https://wordpress.stackexchange.com/a/210662/25187\">solution</a>. Now <strong>I have only two little questions</strong>:</p>\n\n<p>1) Is there a better way to use/set the post ID and the post date? I used for this two hidden inputs: <code>foo_id</code> and <code>foo_date</code>.</p>\n\n<p>2) How secure is the communication between forms?</p>\n\n<p>This is the form that gets the post ID into the \"postid\" variable and pass it to the \"post-form\" page:</p>\n\n<pre><code>&lt;form action=\"&lt;?php echo home_url( '/post-form'); ?&gt;\" method=\"post\"&gt;\n &lt;input type=\"hidden\" name=\"postid\" value=\"&lt;?php the_ID(); ?&gt;\" /&gt; \n &lt;input type=\"submit\" value=\"Edit\" /&gt;\n&lt;/form&gt;\n\n&lt;?php\n</code></pre>\n\n<p>This is the front end form for posting an editing posts (code added by me is marked with <code>// MY CODE</code>):</p>\n\n<pre><code>class WPSE_Submit_From_Front {\n const NONCE_VALUE = 'front_end_new_post';\n const NONCE_FIELD = 'fenp_nonce';\n\n protected $pluginPath;\n protected $pluginUrl;\n protected $errors = array();\n protected $data = array();\n\n function __construct() {\n $this-&gt;pluginPath = plugin_dir_path( __file__ );\n $this-&gt;pluginUrl = plugins_url( '', __file__ );\n\n add_action( 'wp_enqueue_scripts', array( $this, 'addStyles' ) );\n add_shortcode( 'post_from_front', array( $this, 'shortcode' ) );\n\n // Listen for the form submit &amp; process before headers output\n add_action( 'template_redirect', array( $this, 'handleForm' ) );\n }\n\n function addStyles() {\n wp_enqueue_style( 'submitform-style', \"$this-&gt;pluginUrl/submitfromfront.css\" );\n }\n\n /**\n * Shortcodes should return data, NOT echo it.\n *\n * @return string\n */\n function shortcode() {\n if ( ! current_user_can( 'publish_posts' ) )\n return sprintf( '&lt;p&gt;Please &lt;a href=\"%s\"&gt;login&lt;/a&gt; to post links.&lt;/p&gt;', esc_url( wp_login_url( get_permalink() ) ) );\n elseif ( $this-&gt;isFormSuccess() )\n return '&lt;p class=\"success\"&gt;Nice one, post created.&lt;/p&gt;';\n else\n return $this-&gt;getForm();\n }\n\n /**\n * Process the form and redirect if sucessful.\n */\n function handleForm() {\n if ( ! $this-&gt;isFormSubmitted() )\n return false;\n\n // http://php.net/manual/en/function.filter-input-array.php\n $data = filter_input_array( INPUT_POST, array(\n // MY CODE\n 'foo_id' =&gt; FILTER_DEFAULT,\n 'foo_date' =&gt; FILTER_DEFAULT,\n // END MY CODE\n 'postTitle' =&gt; FILTER_DEFAULT,\n 'postContent' =&gt; FILTER_DEFAULT,\n 'location2' =&gt; FILTER_DEFAULT,\n ));\n\n $data = wp_unslash( $data );\n $data = array_map( 'trim', $data );\n\n // You might also want to more aggressively sanitize these fields\n // By default WordPress will handle it pretty well, based on the current user's \"unfiltered_html\" capability\n\n $data['postTitle'] = sanitize_text_field( $data['postTitle'] );\n $data['postContent'] = wp_check_invalid_utf8( $data['postContent'] );\n $data['location2'] = sanitize_text_field( $data['location2'] );\n\n $this-&gt;data = $data;\n\n if ( ! $this-&gt;isNonceValid() )\n $this-&gt;errors[] = 'Security check failed, please try again.';\n\n if ( ! $data['postTitle'] )\n $this-&gt;errors[] = 'Please enter a title.';\n\n if ( ! $data['postContent'] )\n $this-&gt;errors[] = 'Please enter the content.';\n\n if ( ! $this-&gt;errors ) {\n $post_id = wp_insert_post( array(\n // MY CODE\n 'ID' =&gt; $data['foo_id'],\n 'post_date' =&gt; $data['foo_date'],\n // END MY CODE\n 'post_title' =&gt; $data['postTitle'],\n 'post_content' =&gt; $data['postContent'],\n 'post_status' =&gt; 'publish',\n ));\n\n if ( $post_id ) {\n add_post_meta( $post_id, 'location2', $data['location2'] );\n\n // Redirect to avoid duplicate form submissions\n wp_redirect( add_query_arg( 'success', 'true' ) );\n exit;\n\n } else {\n $this-&gt;errors[] = 'Whoops, please try again.';\n }\n }\n }\n\n /**\n * Use output buffering to *return* the form HTML, not echo it.\n *\n * @return string\n */\n function getForm() {\n\n // MY CODE\n if( 'POST' == $_SERVER['REQUEST_METHOD'] &amp;&amp; isset( $_POST['postid'] ) ) {\n $post_to_edit = array();\n $post_to_edit = get_post( $_POST['postid'] );\n $this-&gt;data['foo_id'] = $post_to_edit-&gt;ID;\n $this-&gt;data['foo_date'] = $post_to_edit-&gt;post_date;\n $this-&gt;data['item_name'] = $post_to_edit-&gt;post_title;\n $this-&gt;data['item_description'] = $post_to_edit-&gt;post_content;\n }\n // END MY CODE\n\n ob_start();\n ?&gt;\n\n&lt;div id =\"frontpostform\"&gt;\n &lt;?php foreach ( $this-&gt;errors as $error ) : ?&gt;\n\n &lt;p class=\"error\"&gt;&lt;?php echo $error ?&gt;&lt;/p&gt;\n\n &lt;?php endforeach ?&gt;\n\n &lt;form id=\"formpost\" method=\"post\"&gt;\n &lt;fieldset&gt;\n &lt;label for=\"postTitle\"&gt;Post Title&lt;/label&gt;\n &lt;input type=\"text\" name=\"postTitle\" id=\"postTitle\" value=\"&lt;?php\n\n // \"Sticky\" field, will keep value from last POST if there were errors\n if ( isset( $this-&gt;data['postTitle'] ) )\n echo esc_attr( $this-&gt;data['postTitle'] );\n\n ?&gt;\" /&gt;\n &lt;/fieldset&gt;\n\n &lt;fieldset&gt;\n &lt;label for=\"postContent\"&gt;Content&lt;/label&gt;\n &lt;textarea name=\"postContent\" id=\"postContent\" rows=\"10\" cols=\"35\" &gt;&lt;?php\n\n if ( isset( $this-&gt;data['postContent'] ) )\n echo esc_textarea( $this-&gt;data['postContent'] );\n\n ?&gt;&lt;/textarea&gt;\n &lt;/fieldset&gt;\n\n &lt;fieldset&gt;\n &lt;label for=\"location2\"&gt;Location 2&lt;/label&gt;\n &lt;input type=\"text\" name=\"location2\" id=\"location2\" title=\"Location 2 (opțional)\" value=\"&lt;?php\n\n // \"Sticky\" field, will keep value from last POST if there were errors\n if ( isset( $this-&gt;data['location2'] ) )\n echo esc_attr( $this-&gt;data['location2'] );\n\n ?&gt;\" /&gt;\n &lt;/fieldset&gt;\n\n &lt;fieldset&gt;\n // MY CODE\n &lt;input type=\"hidden\" name=\"foo_id\" id=\"foo_id\" value=\"&lt;?php\n\n // \"Sticky\" field, will keep value from last POST if there were errors\n if ( isset( $this-&gt;data['foo_id'] ) )\n echo esc_attr( $this-&gt;data['foo_id'] );\n\n ?&gt;\" /&gt;\n\n &lt;input type=\"hidden\" name=\"foo_date\" id=\"foo_date\" value=\"&lt;?php\n\n // \"Sticky\" field, will keep value from last POST if there were errors\n if ( isset( $this-&gt;data['foo_date'] ) )\n echo esc_attr( $this-&gt;data['foo_date'] );\n\n ?&gt;\" /&gt;\n // END MY CODE\n &lt;button type=\"submit\" name=\"submitForm\" &gt;Create Post&lt;/button&gt;\n &lt;/fieldset&gt;\n\n &lt;?php wp_nonce_field( self::NONCE_VALUE , self::NONCE_FIELD ) ?&gt;\n &lt;/form&gt;\n&lt;/div&gt;\n\n &lt;?php\n return ob_get_clean();\n }\n\n /**\n * Has the form been submitted?\n *\n * @return bool\n */\n function isFormSubmitted() {\n return isset( $_POST['submitForm'] );\n }\n\n /**\n * Has the form been successfully processed?\n *\n * @return bool\n */\n function isFormSuccess() {\n return filter_input( INPUT_GET, 'success' ) === 'true';\n }\n\n /**\n * Is the nonce field valid?\n *\n * @return bool\n */\n function isNonceValid() {\n return isset( $_POST[ self::NONCE_FIELD ] ) &amp;&amp; wp_verify_nonce( $_POST[ self::NONCE_FIELD ], self::NONCE_VALUE );\n }\n}\n\nnew WPSE_Submit_From_Front;\n</code></pre>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I want to add a front end post editing functionality to one of my Wordpress sites. I found a few plugins that do this, but they don't fits all my needs, so I decided to adapt [an existing solution](http://voodoopress.com/edit-and-delete-posts-from-front-end-with-no-plugin-part-2/) to develop a my own plugin that will return with a shortcode a front end editing form. My plugin works, I can edit and save posts, but **I can't solve a warning** and **I don't have (yet) sufficient knowledge to make this plugin more secure**. Any suggestions? The warning: > > Warning: Cannot modify header information - headers already sent by > (output started at .../wp-content/plugins/front-post-edit.php:139) in > .../wp-includes/pluggable.php on line 1228 > > > *P.S. The 139 line is the last line in my plugin (a line without code).* My plugin code: ``` <?php /* * Plugin Name: Front Post Editor * */ add_shortcode( 'front_post_edit', 'post_shortcode' ); function post_shortcode() { return getForm(); } function getForm() { if ( !is_user_logged_in()) { echo '<p class="alert-box notice">You must be <a href="' . esc_url( wp_login_url( get_permalink() ) ) . '" title="Login">logged in</a>!'; } else { if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "edit_post" && isset($_POST['postid'])) { $post_to_edit = array(); $post_to_edit = get_post($_POST['postid']); /* these are the fields that we are editing in the form below */ $title = $_POST['item_title']; $description = $_POST['item_description']; $category = $_POST['item_category']; $location = $_POST['item_location']; $location2 = $_POST['item_location2']; /* this code will save the title and description into the post_to_edit array */ $post_to_edit->post_title = $title; $post_to_edit->post_content = $description; /* this code is a must */ $pid = wp_update_post($post_to_edit); /* save taxonomies: post ID, form field name, taxonomy name, if it appends(true) or rewrite(false) */ wp_set_post_terms($pid, array($_POST['item_category']),'category',false); wp_set_post_terms($pid, array($_POST['item_location']),'location',false); /* update custom fields with the new info */ update_post_meta($pid, 'item_location2', $location2); /* redirect user after done editing */ wp_redirect( home_url( '/myposts' ) ); } /* get post to edit */ $post_to_edit = get_post($_POST['postid']); /* get this post's category taxonomy term id */ $term_name = strip_tags( get_the_term_list( $post_to_edit->ID, 'category', '', ', ', '' ) ); $term_obj = get_term_by('name', $term_name, 'category'); $term_id = $term_obj->term_id; /* array for wp_dropdown_category to display with the current post category selected by default */ $args_cat = array( 'selected' => $term_id, 'name' => 'item_category', 'class' => 'postform', 'tab_index' => 10, 'depth' => 2, 'hierarchical' => 1, 'taxonomy' => 'category', 'hide_empty' => false ); /* get this post's location taxonomy term id */ $term_name2 = strip_tags( get_the_term_list( $post_to_edit->ID, 'location', '', ', ', '' ) ); $term_obj2 = get_term_by('name', $term_name2, 'location'); $term_id2 = $term_obj2->term_id; $args_loc = array( 'selected' => $term_id2, 'name' => 'item_location', 'class' => 'postform', 'tab_index' => 10, 'depth' => 2, 'hierarchical' => 1, 'taxonomy' => 'location', 'hide_empty' => false ); ?> <!-- EDIT FORM --> <form id="edit_post" name="edit_post" method="post" action="" enctype="multipart/form-data"> <!-- post name --> <fieldset name="item_title"> <label for="item_title">Item title:</label><br /> <input type="text" id="item_title" value="<?php echo $post_to_edit->post_title; ?>" tabindex="5" name="item_title" /> </fieldset> <!-- post Content --> <fieldset class="item_description"> <label for="item_description">Item description:</label><br /> <textarea id="item_description" tabindex="15" name="item_description"><?php echo $post_to_edit->post_content; ?></textarea> </fieldset> <!-- post Category --> <fieldset id="item_category"> <label for="item_category">Item category:</label> <?php wp_dropdown_categories( $args_cat ); ?> </fieldset> <!-- post Location --> <fieldset id="item_location"> <label for="item_location">Item location:</label> <?php wp_dropdown_categories( $args_loc ); ?> </fieldset> <!-- custom fields --> <fieldset class="item_location2"> <label for="item_location2">Location 2:</label><br /> <input type="text" value="<?php echo get_post_meta($post_to_edit->ID,'item_location2', true); ?>" id="item_location2" tabindex="20" name="item_location2" /> </fieldset> <!-- submit button --> <fieldset class="submit"> <input type="submit" value="Save Post" tabindex="40" id="submit" name="submit" /> </fieldset> <input type="hidden" name="postid" value="<?php echo $post_to_edit->ID; ?>" /> <!-- DONT REMOVE OR CHANGE --> <input type="hidden" name="action" value="edit_post" /> <!-- DONT REMOVE OR CHANGE --> <input type="hidden" name="change_cat" value="" /> <!-- DONT REMOVE OR CHANGE --> <?php // wp_nonce_field( 'new-post' ); ?> </form> <!-- END OF FORM --> <?php } ?><!-- user is logged in --> <?php } ?><!-- getForm --> ``` An *Edit* button was added to the footer of each entry generated by a loop with this form: ``` <form class="edit-post" action="<?php echo home_url( '/edit'); ?>" method="post"> <input type="hidden" name="postid" value="<?php the_ID(); ?>" /> <input type="submit" value="Edit" /> </form> ```
From the code it seems like your warning comes from doing the redirect too late. redirects should be done, as a rule of thumb, not later then the init action. And after the redirect you should die() (I don't think the `wp_redirect` does it for you) As for security, it is not enough to check that the user is logged-in, you need to check if he has the capability to edit the post, something like `if current_user_can('edit_post',$post_id)`. You need to check it both on the UI side and server side. just because you do not show the ability to the hacker doesn't mean he will not construct a special HTTP request to change the post if you don't have protection on the server side.
211,672
<p><a href="http://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow">The Codex page for <code>register_taxonomy</code> says that</a></p> <blockquote> <p>This function adds or overwrites a taxonomy.</p> </blockquote> <p>How can I use it to overwrite a core taxonomy without redefining all the parameters ?</p> <p>For example, let's imagine that I want to make the core posts categories read-only for everybody. I can achieve that by setting the <code>edit_terms</code> capability for this taxonomy to <code>do_not_allow</code>.</p> <p>My first guest was to call the <code>register_taxonomy</code> with only the parameter I want to change :</p> <pre><code>add_action( 'init', 'u16975_disable_category_creation' ); function u16975_disable_category_creation(){ register_taxonomy( 'category', 'post', array( 'capabilities' =&gt; array( 'edit_terms' =&gt; 'do_not_allow', ), ) ); } </code></pre> <p>But this does not work as it also overwrites all other parameters and set them to the default value (ex: <code>hierarchical</code> is set back to <code>false</code>).</p> <p>The only way I found to achieve this is to use the global variable that stores all registered taxonomies.</p> <pre><code>add_action( 'init', 'u16975_use_global_var' ); function u16975_use_global_var(){ global $wp_taxonomies; $wp_taxonomies['category']-&gt;cap-&gt;edit_terms = 'do_not_allow'; } </code></pre>
[ { "answer_id": 211676, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Version 4.4 saw the introduction of the <code>register_taxonomy_args</code> filter in <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\"><code>register_taxonomy()</code></a> which you can use to filter the arguments used to register a taxonomy</p>\n\n<pre><code>/**\n * Filter the arguments for registering a taxonomy.\n *\n * @since 4.4.0\n *\n * @param array $args Array of arguments for registering a taxonomy.\n * @param array $object_type Array of names of object types for the taxonomy.\n * @param string $taxonomy Taxonomy key.\n */\n$args = apply_filters( 'register_taxonomy_args', $args, $taxonomy, (array) $object_type );\n</code></pre>\n\n<p>So you can do the following:</p>\n\n<pre><code>add_filter( 'register_taxonomy_args', function ( $args, $taxonomy, $object_type )\n{\n // Only target the built-in taxonomy 'category'\n if ( 'category' !== $taxonomy )\n return $args;\n\n // Set our capability 'edit_terms' to our value\n $args[\"capabilities\"][\"edit_terms\"] = 'do_not_allow';\n\n return $args;\n}, 10, 3);\n</code></pre>\n\n<p>On all older versions, you would either need to re-register the complete 'category' taxonomy or use the way you have done it in your question</p>\n\n<h2>EDIT</h2>\n\n<blockquote>\n <p>The Codex page for <code>register_taxonomy</code> says that</p>\n \n <ul>\n <li>This function adds or overwrites a taxonomy.</li>\n </ul>\n</blockquote>\n\n<p>That is exactly what it does, it either creates a custom taxonomy or completely overrides and register a core taxonomy, it does not add any extra arguments to the existing taxonomy</p>\n" }, { "answer_id": 211729, "author": "Fabien Quatravaux", "author_id": 16975, "author_profile": "https://wordpress.stackexchange.com/users/16975", "pm_score": 2, "selected": true, "text": "<p>I found another reliable way to overwrite a taxonomy : I can just get the registered one before and change only the parameter I want. Registered taxonomies can be retrieved by <code>get_taxonomy</code>. But there are two catches :</p>\n\n<ol>\n<li><code>get_taxonomy</code> returns an object, whereas <code>register_taxonomy</code> ask for an associative array, so we need a type cast.</li>\n<li>the <code>capabilities</code> parameter is stored as <code>cap</code> internally, so we need to change its name.</li>\n</ol>\n\n<p>Here is the code :</p>\n\n<pre><code>add_action( 'init', 'u16975_disable_category_creation' );\nfunction u16975_disable_category_creation(){\n $tax = get_taxonomy( 'category' );\n $tax-&gt;capabilities = (array)$tax-&gt;cap;\n $tax-&gt;capabilities['edit_terms'] = 'do_not_allow';\n register_taxonomy( 'category', 'post', (array)$tax );\n}\n</code></pre>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16975/" ]
[The Codex page for `register_taxonomy` says that](http://codex.wordpress.org/Function_Reference/register_taxonomy) > > This function adds or overwrites a taxonomy. > > > How can I use it to overwrite a core taxonomy without redefining all the parameters ? For example, let's imagine that I want to make the core posts categories read-only for everybody. I can achieve that by setting the `edit_terms` capability for this taxonomy to `do_not_allow`. My first guest was to call the `register_taxonomy` with only the parameter I want to change : ``` add_action( 'init', 'u16975_disable_category_creation' ); function u16975_disable_category_creation(){ register_taxonomy( 'category', 'post', array( 'capabilities' => array( 'edit_terms' => 'do_not_allow', ), ) ); } ``` But this does not work as it also overwrites all other parameters and set them to the default value (ex: `hierarchical` is set back to `false`). The only way I found to achieve this is to use the global variable that stores all registered taxonomies. ``` add_action( 'init', 'u16975_use_global_var' ); function u16975_use_global_var(){ global $wp_taxonomies; $wp_taxonomies['category']->cap->edit_terms = 'do_not_allow'; } ```
I found another reliable way to overwrite a taxonomy : I can just get the registered one before and change only the parameter I want. Registered taxonomies can be retrieved by `get_taxonomy`. But there are two catches : 1. `get_taxonomy` returns an object, whereas `register_taxonomy` ask for an associative array, so we need a type cast. 2. the `capabilities` parameter is stored as `cap` internally, so we need to change its name. Here is the code : ``` add_action( 'init', 'u16975_disable_category_creation' ); function u16975_disable_category_creation(){ $tax = get_taxonomy( 'category' ); $tax->capabilities = (array)$tax->cap; $tax->capabilities['edit_terms'] = 'do_not_allow'; register_taxonomy( 'category', 'post', (array)$tax ); } ```
211,688
<p>Is there any way to redirect WooCommerce default '<a href="http://website.com/shop/" rel="nofollow noreferrer">http://website.com/shop/</a>' URL to '<a href="http://website.com/shop/all/" rel="nofollow noreferrer">http://website.com/shop/all/</a>'?</p> <p>After a long research found this : <a href="https://wordpress.stackexchange.com/questions/151397/how-does-wordpress-redirect-to-woocommerce-shop-page">How does Wordpress redirect to WooCommerce shop page?</a> but not works as i expect</p> <p>So you Have any idea?</p>
[ { "answer_id": 211931, "author": "Scarecrow", "author_id": 52025, "author_profile": "https://wordpress.stackexchange.com/users/52025", "pm_score": 2, "selected": false, "text": "<p>You can use woocommerce_return_to_shop_redirect filter to overwrite the redirection url. </p>\n\n<pre><code>add_filter( 'woocommerce_return_to_shop_redirect', \"custom_woocommerce_return_to_shop_redirect\" ,20 );\nfunction custom_woocommerce_return_to_shop_redirect(){\n return site_url().\"shop/all/\";\n}\n</code></pre>\n" }, { "answer_id": 269453, "author": "paramir", "author_id": 34834, "author_profile": "https://wordpress.stackexchange.com/users/34834", "pm_score": 1, "selected": false, "text": "<p>@Swarnendu Paul answer is great, I'd just replace <strong>site_url().'shop/all'</strong> with <strong>home_url('/shop/all')</strong> in case the home url and site url are not the same :)</p>\n\n<p>so, it'd be:</p>\n\n<pre><code>add_filter( 'woocommerce_return_to_shop_redirect', \"custom_woocommerce_return_to_shop_redirect\" ,20 ); \nfunction custom_woocommerce_return_to_shop_redirect(){\n return home_url('shop/all/');\n}\n</code></pre>\n" }, { "answer_id": 289076, "author": "Tino Rüb", "author_id": 108682, "author_profile": "https://wordpress.stackexchange.com/users/108682", "pm_score": -1, "selected": false, "text": "<p>for 2017 try:</p>\n\n<pre><code>function custom_shop_page_redirect() {\n if( is_shop() ){\n wp_redirect( home_url( '/shop/all/' ) );\n exit();\n }\n}\nadd_action( 'template_redirect', 'custom_shop_page_redirect' );\n</code></pre>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82575/" ]
Is there any way to redirect WooCommerce default '<http://website.com/shop/>' URL to '<http://website.com/shop/all/>'? After a long research found this : [How does Wordpress redirect to WooCommerce shop page?](https://wordpress.stackexchange.com/questions/151397/how-does-wordpress-redirect-to-woocommerce-shop-page) but not works as i expect So you Have any idea?
You can use woocommerce\_return\_to\_shop\_redirect filter to overwrite the redirection url. ``` add_filter( 'woocommerce_return_to_shop_redirect', "custom_woocommerce_return_to_shop_redirect" ,20 ); function custom_woocommerce_return_to_shop_redirect(){ return site_url()."shop/all/"; } ```
211,701
<p><strong>Question</strong></p> <ol> <li>What does the <code>wp-embed.min.js</code> file do? I noticed it is added to the end of my blog page footer.</li> <li>How can I get rid of it?</li> </ol> <p><strong>Effort</strong></p> <p>After some googling and I found <a href="https://codex.wordpress.org/Embeds">Embeds</a> on the Codex. Why does WordPress think I want to add videos, etc. to my page by default?</p> <p><strong>Environment</strong></p> <p>WordPress 4.4</p>
[ { "answer_id": 211705, "author": "Peyman Mohamadpour", "author_id": 75020, "author_profile": "https://wordpress.stackexchange.com/users/75020", "pm_score": 7, "selected": true, "text": "<h2>What is it?</h2>\n<p>It is responsible for converting links into embed frames.</p>\n<p>For example you can paste a Youtube video link into the editor content section and the Youtube embed will be generated for you when your page is viewed.</p>\n<p>More information on <a href=\"https://wordpress.org/support/article/embeds/\" rel=\"noreferrer\">WordPress Documentation</a></p>\n<h2>How to get rid of it?</h2>\n<p>I could finally get rid of that using this:</p>\n<pre><code>function my_deregister_scripts(){\n wp_deregister_script( 'wp-embed' );\n}\nadd_action( 'wp_footer', 'my_deregister_scripts' );\n</code></pre>\n" }, { "answer_id": 214320, "author": "Nadeem Khan", "author_id": 48380, "author_profile": "https://wordpress.stackexchange.com/users/48380", "pm_score": 3, "selected": false, "text": "<p>Trix's answer didn't work out for me on WordPress <code>4.4.1</code>, but I found a solution in the code of <a href=\"https://wordpress.org/plugins/disable-embeds/\" rel=\"noreferrer\">Disable Embeds</a> WordPress plugin. Add this code (modified) in your theme's <code>functions.php</code> file to remove the <code>wp-embed.min.js</code> file from the frontend completely:</p>\n\n<pre><code>add_action( 'init', function() {\n\n // Remove the REST API endpoint.\n remove_action('rest_api_init', 'wp_oembed_register_route');\n\n // Turn off oEmbed auto discovery.\n // Don't filter oEmbed results.\n remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);\n\n // Remove oEmbed discovery links.\n remove_action('wp_head', 'wp_oembed_add_discovery_links');\n\n // Remove oEmbed-specific JavaScript from the front-end and back-end.\n remove_action('wp_head', 'wp_oembed_add_host_js');\n}, PHP_INT_MAX - 1 );\n</code></pre>\n" }, { "answer_id": 247671, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 2, "selected": false, "text": "<p>I think this part is still missing.</p>\n\n<blockquote>\n <p>What does the wp-embed.min.js file do? I noticed it is added to the end of my blog page footer.</p>\n</blockquote>\n\n<p>The answer to this question is in the track. \n<a href=\"https://core.trac.wordpress.org/changeset/35708\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/changeset/35708</a></p>\n\n<blockquote>\n <p><strong>Embeds: Remove &amp; characters from the inline embed JS.</strong></p>\n \n <p>Older versions of WordPress will convert those &amp; characters to &#038;, which makes for some non-functional JS. If folks are running an older release, let's not make their lives more difficult than it already is.</p>\n</blockquote>\n\n<p>It will also try to sniff the user agent.</p>\n" }, { "answer_id": 285907, "author": "Jonathan Nicol", "author_id": 10752, "author_profile": "https://wordpress.stackexchange.com/users/10752", "pm_score": 5, "selected": false, "text": "<p>I arrived at this thread with the same question: What does the wp-embed.min.js file do? None of the current answers accurately address this question.</p>\n\n<p>Firstly, I am fairly certain that embed.min.js does not relate to embedding oEmbed content from other providers: Vimeo, YouTube etc. You can remove embed.min.js and those embeds will continue to function.</p>\n\n<p>It relates specifically to embeding <em>WordPress posts</em> from other people's blogs/websites. Embedding WordPress posts inside WordPress posts: so meta! <a href=\"https://make.wordpress.org/core/2015/10/28/new-embeds-feature-in-wordpress-4-4/\" rel=\"noreferrer\">This feature was introduced in WordPress 4.4</a>.</p>\n\n<p>Disabling embed.min.js will stop that feature from working on your site. </p>\n\n<p>You can test this easily: Paste the URL of someone else's WordPress post into one of your own posts. WP should convert that URL into an embedded widget. When you view your post on the front-end you will notice that your markup contains a blockquote and an iframe. The blockquote is a text-only link to the blog post you embedded, while the source of the iFrame is the blog post's URL with <code>/embed/</code> appended: its oEmbed endpoint.</p>\n\n<p>embed.min.js hides the blockquote and reveals the iframe. It also does some other shenanigans to make the iframe play nice.</p>\n\n<p>Now, try removing the embed.min.js script from your page using one of the methods described in the other answers. Reload your page and you'll notice that the blockquote is visible but the iframe is hidden.</p>\n\n<p>In short: if you want to embed other people's WordPress posts into your own WordPress posts, leave embed.min.js alone. If you don't care about this feature then you can safely remove it.</p>\n" }, { "answer_id": 408393, "author": "Dexter", "author_id": 102678, "author_profile": "https://wordpress.stackexchange.com/users/102678", "pm_score": 1, "selected": false, "text": "<h1>Aug 2022 - WordPress 6.0.1</h1>\n<p>Others have given answers to OP's doubt.<br />\nI am just giving more insight into <code>wp-embed</code></p>\n<h2>What does the wp-embed.min.js file do?</h2>\n<p>In short, It will <strong>make your link pretty</strong></p>\n<blockquote>\n<p>Add a block that displays content pulled from other sites, like Twitter or YouTube.<br />\n<em>WordPress Block</em></p>\n</blockquote>\n<h2>Example</h2>\n<h3>With <code>wp-embed</code></h3>\n<p><a href=\"https://i.stack.imgur.com/rp5FI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rp5FI.png\" alt=\"enter image description here\" /></a></p>\n<h3>Without <code>wp-embed</code></h3>\n<p>If you turn off the <code>wp-embed</code> in the functions, this is how it looks in the front end.\n<a href=\"https://i.stack.imgur.com/wQpgI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wQpgI.png\" alt=\"enter image description here\" /></a></p>\n<h2>How can I get rid of it?</h2>\n<p>Something to know that this script sits in your footer</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script type='text/javascript' src='http://YOURSITE/wp-includes/js/wp-embed.min.js?ver=6.0.1' id='wp-embed-js'&gt;&lt;/script&gt;\n</code></pre>\n<p>So you have two options. One is using <code>wp_enqueue_scripts</code> and another is to use the <code>wp_footer</code>.</p>\n<h3>Using <code>wp_enqueue_scripts</code></h3>\n<pre class=\"lang-php prettyprint-override\"><code>function deregister_style_scripts() {\n wp_deregister_script( 'wp-embed' );\n}\nadd_action( 'wp_enqueue_scripts', 'deregister_style_scripts', 100 );\n</code></pre>\n<h3>Using <code>wp_footer</code></h3>\n<pre class=\"lang-php prettyprint-override\"><code>function deregister_style_scripts() {\n wp_deregister_script( 'wp-embed' );\n}\nadd_action( 'wp_footer', 'deregister_style_scripts' );\n</code></pre>\n<h2>How to embed the link</h2>\n<p>Use the <code>Embed</code> block</p>\n<p><a href=\"https://i.stack.imgur.com/RDioa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RDioa.png\" alt=\"enter image description here\" /></a></p>\n<h2>Embed doesn't work?</h2>\n<p>This usually happens when they do not want to embed their content within their site or outside. This can be controlled via <code>X-Frame-Options</code>, there are two directives <code>DENY</code> and <code>SAMEORIGIN</code></p>\n<h3>Refused to connect</h3>\n<blockquote>\n<p>x-frame-options: DENY</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/VsA57.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VsA57.png\" alt=\"enter image description here\" /></a></p>\n<h3>Sorry, this content could not be embedded.</h3>\n<blockquote>\n<p>x-frame-options: SAMEORIGIN</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/08ZFm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/08ZFm.png\" alt=\"enter image description here\" /></a></p>\n<h2>Read more</h2>\n<p><strong>About Embeds</strong>: <a href=\"https://wordpress.org/support/article/embeds/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/embeds/</a><br />\n<strong>x-Frame-Options</strong>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options</a></p>\n" } ]
2015/12/13
[ "https://wordpress.stackexchange.com/questions/211701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75020/" ]
**Question** 1. What does the `wp-embed.min.js` file do? I noticed it is added to the end of my blog page footer. 2. How can I get rid of it? **Effort** After some googling and I found [Embeds](https://codex.wordpress.org/Embeds) on the Codex. Why does WordPress think I want to add videos, etc. to my page by default? **Environment** WordPress 4.4
What is it? ----------- It is responsible for converting links into embed frames. For example you can paste a Youtube video link into the editor content section and the Youtube embed will be generated for you when your page is viewed. More information on [WordPress Documentation](https://wordpress.org/support/article/embeds/) How to get rid of it? --------------------- I could finally get rid of that using this: ``` function my_deregister_scripts(){ wp_deregister_script( 'wp-embed' ); } add_action( 'wp_footer', 'my_deregister_scripts' ); ```
211,710
<p>Yes, I know that we have <code>get_template_directory_uri();</code> in referencing to the theme's directory. It's working when I put the following code inside <code>index.php</code> or in <code>header.php</code>:</p> <pre><code>&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/sample.png"&gt; </code></pre> <p>But when I'm adding an image inside pages when editing via text, not in visual, it isn't working. How can I get the images from theme's images directory into the pages?</p> <p>Thanks!</p>
[ { "answer_id": 211711, "author": "Por", "author_id": 31832, "author_profile": "https://wordpress.stackexchange.com/users/31832", "pm_score": 1, "selected": false, "text": "<p>The answer is yes. You could run php code in editor. But that is not for proper way of adding images. Instead, you should create shortcodes to get those images from theme folder or use like below codes</p>\n\n<pre><code>&lt;img src=\"/wp-content/themes/your-theme/assets/images/1.jpg\" /&gt;\n</code></pre>\n\n<p>By removing domain name, it could even benefit of http requests. If removing domain doesn't work, you could even install php <strong><em>wordpress execute plugins</em></strong>. There are some plugins about it. To understand more, you should read <a href=\"http://www.hongkiat.com/blog/execute-php-in-wordpress-post-page-and-widget-sidebar/\" rel=\"nofollow\">this article</a>. I hope that could solve your problems :). Good luck in codes.</p>\n" }, { "answer_id": 256278, "author": "imranhunzai", "author_id": 62459, "author_profile": "https://wordpress.stackexchange.com/users/62459", "pm_score": 0, "selected": false, "text": "<p>Didn't Matt announce <a href=\"https://codex.wordpress.org/Writing_Code_in_Your_Posts\" rel=\"nofollow noreferrer\">PHP won't work inside a Wordpress post</a>?</p>\n" }, { "answer_id": 260458, "author": "Ajay Tank", "author_id": 115567, "author_profile": "https://wordpress.stackexchange.com/users/115567", "pm_score": 2, "selected": false, "text": "<p>It's not possible to use PHP code in editor. You can use an image with full path.</p>\n\n<pre><code>&lt;img src=\"/wp-content/themes/your-theme/assets/images/1.jpg\" /&gt;\n</code></pre>\n\n<p>In general I would avoid using theme specific images in the content, because when you change and delete the old theme, then they are gone. So I would consider using /wp-content/uploads/ for content images.</p>\n" }, { "answer_id": 294264, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p><strong>Shortcode</strong> is the way to go, something like this (in functions.php or as plugin) would work:</p>\n\n<pre><code>// [template_dir image=\"something.jpg\"]\nadd_shortcode( 'template_dir', function( $atts ){\n return get_template_directory_uri() . '/images/' . $atts['image'];\n});\n</code></pre>\n" }, { "answer_id": 385612, "author": "Kaif Ahmad", "author_id": 203686, "author_profile": "https://wordpress.stackexchange.com/users/203686", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;img src=&quot;&lt;?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?&gt;&quot; alt=&quot;&quot; &gt;\n</code></pre>\n<p>Try this. It should work.\nYou have to concatenate the results from <code>get_template_directory_uri()</code> and your images directory in echo.</p>\n" }, { "answer_id": 405058, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p><strong>get_template_directory_uri()</strong></p>\n<p>Quick search through WordPress core code, shows two different treatments. This function needs escaping when it’s used inside of tag attribute.</p>\n<p><code>&lt;img src=&quot;&lt;?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?&gt;&quot; alt=&quot;&quot; &gt;</code></p>\n<p>When used inside wp_enqueue_style() or wp_enqueue_script(), it is not escaped:</p>\n<p><code>wp_enqueue_script( 'theme-customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '', true );</code></p>\n<p>However, looking at the function itself, it has filter right before returning values which makes it suspicious – it can be filtered in plugins and we don’t know exactly what’s returned. Rule of thumb in this situation would be better safe than sorry and always escape.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211710", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85242/" ]
Yes, I know that we have `get_template_directory_uri();` in referencing to the theme's directory. It's working when I put the following code inside `index.php` or in `header.php`: ``` <img src="<?php echo get_template_directory_uri(); ?>/images/sample.png"> ``` But when I'm adding an image inside pages when editing via text, not in visual, it isn't working. How can I get the images from theme's images directory into the pages? Thanks!
``` <img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" > ``` Try this. It should work. You have to concatenate the results from `get_template_directory_uri()` and your images directory in echo.
211,728
<p>I'm developing a plugin and I've started from <a href="http://wppb.io/" rel="nofollow">WPPB</a> and Wordpress 4.3.1. I've named it dogmaweb. I need to submit a form to the plugin via Ajax. The form is created by the plugin itself. In my class-dogmaweb.php I'm trying to add the action that processes the form data server side, and here is what I've come up with, until now:</p> <pre><code>public function enqueue_scripts() { $script_handle = 'userprofilesumbit'; add_action( 'wp_ajax_'.$script_handle, array($this, 'userprofileform_process') ); add_action( 'wp_ajax_nopriv_'.$script_handle, array($this, 'userprofileform_process') ); wp_register_script( $script_handle, plugins_url() . '/public/js/dogmaweb-public.js' ); $userprofilesumbit_data = array('ajax_url' =&gt; admin_url( 'admin-ajax.php' ), 'form_action' =&gt; $script_handle, 'form_id' =&gt; '#'.Dogmaweb::$userprofileform_id); wp_localize_script($script_handle, 'submit_params', $userprofilesumbit_data); wp_enqueue_script($script_handle); } </code></pre> <p>The symptom of the problem is that admin-ajax.php is not calling my function and it is returning 0. I've stepped through the wordpress code to understand why (I'm using Netbeans and xdebug). The problem is that <a href="https://github.com/WordPress/WordPress/blob/4.3-branch/wp-includes/plugin.php#L475-L479" rel="nofollow">these lines of code in plugin.php</a> do not find the <code>$tag</code> in the <code>$wp_filter</code> array. The <code>$tag</code> variable at that point contains <code>"wp_ajax_userprofilesumbit"</code>, which is exactly what I specified for the <code>$hook</code> argument to the add_action function (I've used the same <code>$script_handle</code> variable as you can see in my code). I've also stepped through the <code>add_action</code> code and I'm sure the global <code>$wp_filter</code> array does contain <code>"wp_ajax_userprofilesumbit"</code> key when <code>add_action</code> returns after I call it. However I'm also sure that it does not contain that key anymore when plugin.php executes (called by admin-ajax.php).</p> <p>Why is my filter being removed from <code>$wp_filter</code>? What am I doing wrong?</p>
[ { "answer_id": 211711, "author": "Por", "author_id": 31832, "author_profile": "https://wordpress.stackexchange.com/users/31832", "pm_score": 1, "selected": false, "text": "<p>The answer is yes. You could run php code in editor. But that is not for proper way of adding images. Instead, you should create shortcodes to get those images from theme folder or use like below codes</p>\n\n<pre><code>&lt;img src=\"/wp-content/themes/your-theme/assets/images/1.jpg\" /&gt;\n</code></pre>\n\n<p>By removing domain name, it could even benefit of http requests. If removing domain doesn't work, you could even install php <strong><em>wordpress execute plugins</em></strong>. There are some plugins about it. To understand more, you should read <a href=\"http://www.hongkiat.com/blog/execute-php-in-wordpress-post-page-and-widget-sidebar/\" rel=\"nofollow\">this article</a>. I hope that could solve your problems :). Good luck in codes.</p>\n" }, { "answer_id": 256278, "author": "imranhunzai", "author_id": 62459, "author_profile": "https://wordpress.stackexchange.com/users/62459", "pm_score": 0, "selected": false, "text": "<p>Didn't Matt announce <a href=\"https://codex.wordpress.org/Writing_Code_in_Your_Posts\" rel=\"nofollow noreferrer\">PHP won't work inside a Wordpress post</a>?</p>\n" }, { "answer_id": 260458, "author": "Ajay Tank", "author_id": 115567, "author_profile": "https://wordpress.stackexchange.com/users/115567", "pm_score": 2, "selected": false, "text": "<p>It's not possible to use PHP code in editor. You can use an image with full path.</p>\n\n<pre><code>&lt;img src=\"/wp-content/themes/your-theme/assets/images/1.jpg\" /&gt;\n</code></pre>\n\n<p>In general I would avoid using theme specific images in the content, because when you change and delete the old theme, then they are gone. So I would consider using /wp-content/uploads/ for content images.</p>\n" }, { "answer_id": 294264, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p><strong>Shortcode</strong> is the way to go, something like this (in functions.php or as plugin) would work:</p>\n\n<pre><code>// [template_dir image=\"something.jpg\"]\nadd_shortcode( 'template_dir', function( $atts ){\n return get_template_directory_uri() . '/images/' . $atts['image'];\n});\n</code></pre>\n" }, { "answer_id": 385612, "author": "Kaif Ahmad", "author_id": 203686, "author_profile": "https://wordpress.stackexchange.com/users/203686", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;img src=&quot;&lt;?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?&gt;&quot; alt=&quot;&quot; &gt;\n</code></pre>\n<p>Try this. It should work.\nYou have to concatenate the results from <code>get_template_directory_uri()</code> and your images directory in echo.</p>\n" }, { "answer_id": 405058, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p><strong>get_template_directory_uri()</strong></p>\n<p>Quick search through WordPress core code, shows two different treatments. This function needs escaping when it’s used inside of tag attribute.</p>\n<p><code>&lt;img src=&quot;&lt;?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?&gt;&quot; alt=&quot;&quot; &gt;</code></p>\n<p>When used inside wp_enqueue_style() or wp_enqueue_script(), it is not escaped:</p>\n<p><code>wp_enqueue_script( 'theme-customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '', true );</code></p>\n<p>However, looking at the function itself, it has filter right before returning values which makes it suspicious – it can be filtered in plugins and we don’t know exactly what’s returned. Rule of thumb in this situation would be better safe than sorry and always escape.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm developing a plugin and I've started from [WPPB](http://wppb.io/) and Wordpress 4.3.1. I've named it dogmaweb. I need to submit a form to the plugin via Ajax. The form is created by the plugin itself. In my class-dogmaweb.php I'm trying to add the action that processes the form data server side, and here is what I've come up with, until now: ``` public function enqueue_scripts() { $script_handle = 'userprofilesumbit'; add_action( 'wp_ajax_'.$script_handle, array($this, 'userprofileform_process') ); add_action( 'wp_ajax_nopriv_'.$script_handle, array($this, 'userprofileform_process') ); wp_register_script( $script_handle, plugins_url() . '/public/js/dogmaweb-public.js' ); $userprofilesumbit_data = array('ajax_url' => admin_url( 'admin-ajax.php' ), 'form_action' => $script_handle, 'form_id' => '#'.Dogmaweb::$userprofileform_id); wp_localize_script($script_handle, 'submit_params', $userprofilesumbit_data); wp_enqueue_script($script_handle); } ``` The symptom of the problem is that admin-ajax.php is not calling my function and it is returning 0. I've stepped through the wordpress code to understand why (I'm using Netbeans and xdebug). The problem is that [these lines of code in plugin.php](https://github.com/WordPress/WordPress/blob/4.3-branch/wp-includes/plugin.php#L475-L479) do not find the `$tag` in the `$wp_filter` array. The `$tag` variable at that point contains `"wp_ajax_userprofilesumbit"`, which is exactly what I specified for the `$hook` argument to the add\_action function (I've used the same `$script_handle` variable as you can see in my code). I've also stepped through the `add_action` code and I'm sure the global `$wp_filter` array does contain `"wp_ajax_userprofilesumbit"` key when `add_action` returns after I call it. However I'm also sure that it does not contain that key anymore when plugin.php executes (called by admin-ajax.php). Why is my filter being removed from `$wp_filter`? What am I doing wrong?
``` <img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" > ``` Try this. It should work. You have to concatenate the results from `get_template_directory_uri()` and your images directory in echo.
211,734
<p>I have a simple function in functions.php that creates a custom shortcode:</p> <pre><code>function my_line_break() { return "&lt;br&gt;"; } add_shortcode( 'new line', 'my_line_break' ); </code></pre> <p>Now, I don't know if this happened after upgrading to 4.4 but it's not longer working and pages just render <code>[new line]</code> in plain text.</p> <p>Anyone can help with this? I looked at <a href="https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/" rel="nofollow">https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/</a> but I'm not sure it relates?</p> <p>P.S. I know this wouldn't be the right way to handle line breaks, but I did it as a way to make life simpler for my customer (so as a little side question, if there is a valid and simple to use alternative, could you please let me know it so I can also bypass this problem completely?).</p>
[ { "answer_id": 211749, "author": "Danial", "author_id": 85280, "author_profile": "https://wordpress.stackexchange.com/users/85280", "pm_score": 1, "selected": false, "text": "<p>Your shortcode name is incorrect . <a href=\"https://codex.wordpress.org/Shortcode_API#Names\" rel=\"nofollow\">Shortcode API - WordPress Codex</a></p>\n\n<p>So you can write like :</p>\n\n<pre><code>function my_line_break() {\n return \"&lt;br&gt;\";\n}\nadd_shortcode( 'newline', 'my_line_break' );\n</code></pre>\n\n<p>Then : </p>\n\n<pre><code>[newline]\n</code></pre>\n" }, { "answer_id": 211759, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 3, "selected": true, "text": "<p>Converting the comment to an answer,</p>\n\n<p>please rename your Shortcode to not contain spaces (<code>new_line</code>):</p>\n\n<pre><code>function my_line_break() {\n return \"&lt;br&gt;\";\n}\nadd_shortcode( 'new_line', 'my_line_break' );\n</code></pre>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211734", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44953/" ]
I have a simple function in functions.php that creates a custom shortcode: ``` function my_line_break() { return "<br>"; } add_shortcode( 'new line', 'my_line_break' ); ``` Now, I don't know if this happened after upgrading to 4.4 but it's not longer working and pages just render `[new line]` in plain text. Anyone can help with this? I looked at <https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/> but I'm not sure it relates? P.S. I know this wouldn't be the right way to handle line breaks, but I did it as a way to make life simpler for my customer (so as a little side question, if there is a valid and simple to use alternative, could you please let me know it so I can also bypass this problem completely?).
Converting the comment to an answer, please rename your Shortcode to not contain spaces (`new_line`): ``` function my_line_break() { return "<br>"; } add_shortcode( 'new_line', 'my_line_break' ); ```
211,742
<p>The goal is very simple - to print page content on a page. I tried:</p> <pre><code>&lt;?php the_content() ?&gt; &lt;?= get_the_content() ?&gt; </code></pre> <p>then</p> <pre><code>&lt;?php the_content(get_the_ID()) ?&gt; &lt;?= get_the_content(get_the_ID()) ?&gt; </code></pre> <p>None of them worked.</p> <p>Then I found this bizarre solution:</p> <pre><code>&lt;?= apply_filters('the_content', get_post_field('post_content', get_the_ID() )) ?&gt; </code></pre> <p>Why the_content() and get_the_content() didn't work?</p> <p>Is there cleaner solution to display page content then the last one?</p>
[ { "answer_id": 211747, "author": "Danial", "author_id": 85280, "author_profile": "https://wordpress.stackexchange.com/users/85280", "pm_score": 1, "selected": false, "text": "<p>Displays the contents of the current post. This template tag must be within while loop.</p>\n\n<pre><code>&lt;?php \n if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n the_content(); \n } // end while\n } // end if\n?&gt;\n</code></pre>\n\n<p>More : <a href=\"https://codex.wordpress.org/Function_Reference/the_content\" rel=\"nofollow\">the_content() - WordPress Codex</a></p>\n" }, { "answer_id": 211752, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>A few notes before I start</p>\n\n<ul>\n<li><p>NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (<em>which doesn't mean much</em>) also \"prohibits\" the use of shorttags. Use proper php tags and forget that shorttags even exists</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow\"><code>the_content()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_content/\" rel=\"nofollow\"><code>get_the_content()</code></a> does not accept the post ID, the firts parameter for both these template tags are <code>$more_link_text</code></p></li>\n<li><p><code>get_the_content()</code> as well as the the content retrieved from the post_content field are unfiltered content, <code>the_content</code> filters are a set of filters that are applied to this unfiltered content and they include filters like <code>wpautop</code> which apply <code>p</code> tags to <code>the_content()</code></p></li>\n</ul>\n\n<p>Popular believe is that <code>the_content()</code> and <code>get_the_content()</code> <strong>MUST</strong> be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID()</code></a>, <code>get_the_content()</code> expects global post data to be set up (<em><code>$post = get_post()</code></em>), so if there are postdata available outside the loop in global scope, it will return the data. </p>\n\n<p>Your issue is quite strange, if we look at source codes here, both <code>get_the_ID()</code> and <code>get_the_content()</code> calls <code>$post = get_post()</code>, and <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\"><code>get_post()</code></a> returns <code>$GLOBALS['post']</code> if no ID is passed and if <code>$GLOBALS['post']</code> are set, which seems to be the case here. <code>get_post_field()</code> successfully returns the page content according to you which means <code>get_the_ID()</code> returns the correct page ID that we are one, which means that <code>get_the_content()</code> should have worked and should have returned unfiltered page content (<em><code>the_content()</code> should have displayed filtered page content</em>)</p>\n\n<p>Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the <code>$post_content</code> property, apply the content filters to it and display the content. Just one note, this will not work if you are using <code>query_posts</code> in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use <code>query_posts</code></p>\n\n<pre><code>$current_page = get_queried_object();\n$content = apply_filters( 'the_content', $current_page-&gt;post_content );\necho $content;\n</code></pre>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85230/" ]
The goal is very simple - to print page content on a page. I tried: ``` <?php the_content() ?> <?= get_the_content() ?> ``` then ``` <?php the_content(get_the_ID()) ?> <?= get_the_content(get_the_ID()) ?> ``` None of them worked. Then I found this bizarre solution: ``` <?= apply_filters('the_content', get_post_field('post_content', get_the_ID() )) ?> ``` Why the\_content() and get\_the\_content() didn't work? Is there cleaner solution to display page content then the last one?
A few notes before I start * NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (*which doesn't mean much*) also "prohibits" the use of shorttags. Use proper php tags and forget that shorttags even exists * [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) and [`get_the_content()`](https://developer.wordpress.org/reference/functions/get_the_content/) does not accept the post ID, the firts parameter for both these template tags are `$more_link_text` * `get_the_content()` as well as the the content retrieved from the post\_content field are unfiltered content, `the_content` filters are a set of filters that are applied to this unfiltered content and they include filters like `wpautop` which apply `p` tags to `the_content()` Popular believe is that `the_content()` and `get_the_content()` **MUST** be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like [`get_the_ID()`](https://developer.wordpress.org/reference/functions/get_the_id/), `get_the_content()` expects global post data to be set up (*`$post = get_post()`*), so if there are postdata available outside the loop in global scope, it will return the data. Your issue is quite strange, if we look at source codes here, both `get_the_ID()` and `get_the_content()` calls `$post = get_post()`, and [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/) returns `$GLOBALS['post']` if no ID is passed and if `$GLOBALS['post']` are set, which seems to be the case here. `get_post_field()` successfully returns the page content according to you which means `get_the_ID()` returns the correct page ID that we are one, which means that `get_the_content()` should have worked and should have returned unfiltered page content (*`the_content()` should have displayed filtered page content*) Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the `$post_content` property, apply the content filters to it and display the content. Just one note, this will not work if you are using `query_posts` in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use `query_posts` ``` $current_page = get_queried_object(); $content = apply_filters( 'the_content', $current_page->post_content ); echo $content; ```
211,767
<p>I have a custom plugin that I have written to manage a lot of stuff. I want to use this for the main website.com. I don't want any of the subdomain sites e.g. website.com/site1 to have access to this plugin. I was thinking of implementing something in the plugin itself so it would check the URL and wouldn't do anything if it was not the main website, but this isn't what I really want. I want to completely hide this plugin from all sub websites. I plan on having multiple plugins in the future so I would like to have some control over what sub sites get access to particular plugins. </p> <p>To further clarify. I'm not looking to give people options I want to decide what options the sub sites have. I have a dirty solution that I do not like.</p> <pre><code>if(get_site_url() != "http://website.com") exit; </code></pre> <p>This will cause a fatal exception when the plugin is installed on anything other than the main site, but its really ugly. I want a cleaner way to hide this plugin from the plugin menu for sub sites.</p>
[ { "answer_id": 211747, "author": "Danial", "author_id": 85280, "author_profile": "https://wordpress.stackexchange.com/users/85280", "pm_score": 1, "selected": false, "text": "<p>Displays the contents of the current post. This template tag must be within while loop.</p>\n\n<pre><code>&lt;?php \n if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n the_content(); \n } // end while\n } // end if\n?&gt;\n</code></pre>\n\n<p>More : <a href=\"https://codex.wordpress.org/Function_Reference/the_content\" rel=\"nofollow\">the_content() - WordPress Codex</a></p>\n" }, { "answer_id": 211752, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>A few notes before I start</p>\n\n<ul>\n<li><p>NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (<em>which doesn't mean much</em>) also \"prohibits\" the use of shorttags. Use proper php tags and forget that shorttags even exists</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow\"><code>the_content()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_content/\" rel=\"nofollow\"><code>get_the_content()</code></a> does not accept the post ID, the firts parameter for both these template tags are <code>$more_link_text</code></p></li>\n<li><p><code>get_the_content()</code> as well as the the content retrieved from the post_content field are unfiltered content, <code>the_content</code> filters are a set of filters that are applied to this unfiltered content and they include filters like <code>wpautop</code> which apply <code>p</code> tags to <code>the_content()</code></p></li>\n</ul>\n\n<p>Popular believe is that <code>the_content()</code> and <code>get_the_content()</code> <strong>MUST</strong> be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID()</code></a>, <code>get_the_content()</code> expects global post data to be set up (<em><code>$post = get_post()</code></em>), so if there are postdata available outside the loop in global scope, it will return the data. </p>\n\n<p>Your issue is quite strange, if we look at source codes here, both <code>get_the_ID()</code> and <code>get_the_content()</code> calls <code>$post = get_post()</code>, and <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\"><code>get_post()</code></a> returns <code>$GLOBALS['post']</code> if no ID is passed and if <code>$GLOBALS['post']</code> are set, which seems to be the case here. <code>get_post_field()</code> successfully returns the page content according to you which means <code>get_the_ID()</code> returns the correct page ID that we are one, which means that <code>get_the_content()</code> should have worked and should have returned unfiltered page content (<em><code>the_content()</code> should have displayed filtered page content</em>)</p>\n\n<p>Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the <code>$post_content</code> property, apply the content filters to it and display the content. Just one note, this will not work if you are using <code>query_posts</code> in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use <code>query_posts</code></p>\n\n<pre><code>$current_page = get_queried_object();\n$content = apply_filters( 'the_content', $current_page-&gt;post_content );\necho $content;\n</code></pre>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211767", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have a custom plugin that I have written to manage a lot of stuff. I want to use this for the main website.com. I don't want any of the subdomain sites e.g. website.com/site1 to have access to this plugin. I was thinking of implementing something in the plugin itself so it would check the URL and wouldn't do anything if it was not the main website, but this isn't what I really want. I want to completely hide this plugin from all sub websites. I plan on having multiple plugins in the future so I would like to have some control over what sub sites get access to particular plugins. To further clarify. I'm not looking to give people options I want to decide what options the sub sites have. I have a dirty solution that I do not like. ``` if(get_site_url() != "http://website.com") exit; ``` This will cause a fatal exception when the plugin is installed on anything other than the main site, but its really ugly. I want a cleaner way to hide this plugin from the plugin menu for sub sites.
A few notes before I start * NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (*which doesn't mean much*) also "prohibits" the use of shorttags. Use proper php tags and forget that shorttags even exists * [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) and [`get_the_content()`](https://developer.wordpress.org/reference/functions/get_the_content/) does not accept the post ID, the firts parameter for both these template tags are `$more_link_text` * `get_the_content()` as well as the the content retrieved from the post\_content field are unfiltered content, `the_content` filters are a set of filters that are applied to this unfiltered content and they include filters like `wpautop` which apply `p` tags to `the_content()` Popular believe is that `the_content()` and `get_the_content()` **MUST** be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like [`get_the_ID()`](https://developer.wordpress.org/reference/functions/get_the_id/), `get_the_content()` expects global post data to be set up (*`$post = get_post()`*), so if there are postdata available outside the loop in global scope, it will return the data. Your issue is quite strange, if we look at source codes here, both `get_the_ID()` and `get_the_content()` calls `$post = get_post()`, and [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/) returns `$GLOBALS['post']` if no ID is passed and if `$GLOBALS['post']` are set, which seems to be the case here. `get_post_field()` successfully returns the page content according to you which means `get_the_ID()` returns the correct page ID that we are one, which means that `get_the_content()` should have worked and should have returned unfiltered page content (*`the_content()` should have displayed filtered page content*) Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the `$post_content` property, apply the content filters to it and display the content. Just one note, this will not work if you are using `query_posts` in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use `query_posts` ``` $current_page = get_queried_object(); $content = apply_filters( 'the_content', $current_page->post_content ); echo $content; ```
211,771
<p>I have a search form which searches the DB and returns back some data. I have managed to use Wordpress wpdb to connect and use select statement on the table and retrieve data. Everything works fine..But..I have page refresh issue. I want to add AJAX code in order to get my data without refreshing. So, I have followed along with <a href="http://www.makeuseof.com/tag/tutorial-ajax-wordpress/" rel="nofollow">this</a>, <a href="http://bordoni.me/ajax-wordpress/#comments" rel="nofollow">this</a> and tutorials. But,I'm facing some problems with them. So, here's what I got:</p> <p>My JS code:</p> <pre><code>var j$ = jQuery; var search_text = j$(".cv__text").val(); j$.post({ url: "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;", data: ({ action: "search_cv", search_text: search_text }), success: function (response){ console.log(response); j$("#search_results").html(response); } }); </code></pre> <p>My functions.php:</p> <pre><code>function search_cv(){ $search_text = ucfirst($_POST["search_text"]); //Creating New DB Connection $database_name = "employee_cv"; $mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST); $mydb -&gt; show_errors(); if ($_POST["search_text"] != null){ $result = $mydb -&gt; get_results( $mydb -&gt; prepare( 'SELECT * FROM employee WHERE Experience = %s', $search_text ) ); } foreach ($result as $employee){ //Here I just echo html blocks (divs, paragraphs etc.) } die(); } add_action( 'wp_ajax_search_cv', 'search_cv' ); add_action( 'wp_ajax_nopriv_search_cv', 'search_cv' ); </code></pre> <p>My HTML:</p> <pre><code>&lt;form class="searchCV_form" role="form" action=""&gt; &lt;div&gt; &lt;input type="text" id="search_text" name="search_text" class="cv__text"&gt; &lt;span class="input-group-btn"&gt; &lt;button type="submit" class="btn btn-default btn-primary cv__button search--form-btn"&gt;SUBMIT&lt;/button&gt; &lt;/span&gt; &lt;/div&gt; &lt;/form&gt; &lt;div id="search_results"&gt;&lt;/div&gt; </code></pre> <p>So, after all this changes, I still get the refresh on page and also, my query is not working at all. I'm not sure what I'm doing wrong here. I've used AJAX before on my projects but never with Wordpress and php.</p> <p><strong>EDIT</strong></p> <p>Apparently either I'm doing something wrong or the question is wrong. Can someone just point me on how to use AJAX with wpdb requests to MySQL? On own experience? preferably with some details? all the tutorials i found seems to fail me here.</p>
[ { "answer_id": 211747, "author": "Danial", "author_id": 85280, "author_profile": "https://wordpress.stackexchange.com/users/85280", "pm_score": 1, "selected": false, "text": "<p>Displays the contents of the current post. This template tag must be within while loop.</p>\n\n<pre><code>&lt;?php \n if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n the_content(); \n } // end while\n } // end if\n?&gt;\n</code></pre>\n\n<p>More : <a href=\"https://codex.wordpress.org/Function_Reference/the_content\" rel=\"nofollow\">the_content() - WordPress Codex</a></p>\n" }, { "answer_id": 211752, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>A few notes before I start</p>\n\n<ul>\n<li><p>NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (<em>which doesn't mean much</em>) also \"prohibits\" the use of shorttags. Use proper php tags and forget that shorttags even exists</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow\"><code>the_content()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_content/\" rel=\"nofollow\"><code>get_the_content()</code></a> does not accept the post ID, the firts parameter for both these template tags are <code>$more_link_text</code></p></li>\n<li><p><code>get_the_content()</code> as well as the the content retrieved from the post_content field are unfiltered content, <code>the_content</code> filters are a set of filters that are applied to this unfiltered content and they include filters like <code>wpautop</code> which apply <code>p</code> tags to <code>the_content()</code></p></li>\n</ul>\n\n<p>Popular believe is that <code>the_content()</code> and <code>get_the_content()</code> <strong>MUST</strong> be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID()</code></a>, <code>get_the_content()</code> expects global post data to be set up (<em><code>$post = get_post()</code></em>), so if there are postdata available outside the loop in global scope, it will return the data. </p>\n\n<p>Your issue is quite strange, if we look at source codes here, both <code>get_the_ID()</code> and <code>get_the_content()</code> calls <code>$post = get_post()</code>, and <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\"><code>get_post()</code></a> returns <code>$GLOBALS['post']</code> if no ID is passed and if <code>$GLOBALS['post']</code> are set, which seems to be the case here. <code>get_post_field()</code> successfully returns the page content according to you which means <code>get_the_ID()</code> returns the correct page ID that we are one, which means that <code>get_the_content()</code> should have worked and should have returned unfiltered page content (<em><code>the_content()</code> should have displayed filtered page content</em>)</p>\n\n<p>Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the <code>$post_content</code> property, apply the content filters to it and display the content. Just one note, this will not work if you are using <code>query_posts</code> in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use <code>query_posts</code></p>\n\n<pre><code>$current_page = get_queried_object();\n$content = apply_filters( 'the_content', $current_page-&gt;post_content );\necho $content;\n</code></pre>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211771", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85213/" ]
I have a search form which searches the DB and returns back some data. I have managed to use Wordpress wpdb to connect and use select statement on the table and retrieve data. Everything works fine..But..I have page refresh issue. I want to add AJAX code in order to get my data without refreshing. So, I have followed along with [this](http://www.makeuseof.com/tag/tutorial-ajax-wordpress/), [this](http://bordoni.me/ajax-wordpress/#comments) and tutorials. But,I'm facing some problems with them. So, here's what I got: My JS code: ``` var j$ = jQuery; var search_text = j$(".cv__text").val(); j$.post({ url: "<?php echo admin_url('admin-ajax.php'); ?>", data: ({ action: "search_cv", search_text: search_text }), success: function (response){ console.log(response); j$("#search_results").html(response); } }); ``` My functions.php: ``` function search_cv(){ $search_text = ucfirst($_POST["search_text"]); //Creating New DB Connection $database_name = "employee_cv"; $mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST); $mydb -> show_errors(); if ($_POST["search_text"] != null){ $result = $mydb -> get_results( $mydb -> prepare( 'SELECT * FROM employee WHERE Experience = %s', $search_text ) ); } foreach ($result as $employee){ //Here I just echo html blocks (divs, paragraphs etc.) } die(); } add_action( 'wp_ajax_search_cv', 'search_cv' ); add_action( 'wp_ajax_nopriv_search_cv', 'search_cv' ); ``` My HTML: ``` <form class="searchCV_form" role="form" action=""> <div> <input type="text" id="search_text" name="search_text" class="cv__text"> <span class="input-group-btn"> <button type="submit" class="btn btn-default btn-primary cv__button search--form-btn">SUBMIT</button> </span> </div> </form> <div id="search_results"></div> ``` So, after all this changes, I still get the refresh on page and also, my query is not working at all. I'm not sure what I'm doing wrong here. I've used AJAX before on my projects but never with Wordpress and php. **EDIT** Apparently either I'm doing something wrong or the question is wrong. Can someone just point me on how to use AJAX with wpdb requests to MySQL? On own experience? preferably with some details? all the tutorials i found seems to fail me here.
A few notes before I start * NEVER EVER use php shortcodes, they are bad, confusing and not supported by default on some servers. IMHO, they should have never made it into PHP in the first place. WordPress Standards (*which doesn't mean much*) also "prohibits" the use of shorttags. Use proper php tags and forget that shorttags even exists * [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) and [`get_the_content()`](https://developer.wordpress.org/reference/functions/get_the_content/) does not accept the post ID, the firts parameter for both these template tags are `$more_link_text` * `get_the_content()` as well as the the content retrieved from the post\_content field are unfiltered content, `the_content` filters are a set of filters that are applied to this unfiltered content and they include filters like `wpautop` which apply `p` tags to `the_content()` Popular believe is that `the_content()` and `get_the_content()` **MUST** be used inside the loop. That is not entirely true, although it really is not recommended to use it outside the loop. Just like [`get_the_ID()`](https://developer.wordpress.org/reference/functions/get_the_id/), `get_the_content()` expects global post data to be set up (*`$post = get_post()`*), so if there are postdata available outside the loop in global scope, it will return the data. Your issue is quite strange, if we look at source codes here, both `get_the_ID()` and `get_the_content()` calls `$post = get_post()`, and [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/) returns `$GLOBALS['post']` if no ID is passed and if `$GLOBALS['post']` are set, which seems to be the case here. `get_post_field()` successfully returns the page content according to you which means `get_the_ID()` returns the correct page ID that we are one, which means that `get_the_content()` should have worked and should have returned unfiltered page content (*`the_content()` should have displayed filtered page content*) Anyways, you will need to debug this why things does not want to work as expected. To answer your question as to displaying page content without the loop correctly and reliably, you can access the queried object, get the `$post_content` property, apply the content filters to it and display the content. Just one note, this will not work if you are using `query_posts` in any way as it breaks the main query object which hold the queried object. This is the main reason why do must never ever use `query_posts` ``` $current_page = get_queried_object(); $content = apply_filters( 'the_content', $current_page->post_content ); echo $content; ```
211,774
<p>I need a code that causes: <code>&lt;?php while ( have_posts() ) : the_post(); ?&gt;</code> List according to the amount of VIEW, is like to list popular posts only that it will enter the table <strong>mh_postmeta</strong>, and list according to who has the most <strong>view</strong>.</p> <p><a href="https://i.stack.imgur.com/bvqdm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvqdm.png" alt="inserir a descrição da imagem aqui"></a></p> <p>The staff uses the 'orderby' => 'comment_count', to list according to the comments, but need it to search for another table, <strong>BUT</strong>, this can only happen to certain category .. Let's say you have 40 <strong>CAT</strong> it should only list by <strong>VIEW</strong> instead of <strong>DATE</strong> in <strong>CAT 3</strong></p>
[ { "answer_id": 211787, "author": "Bram_Boterham", "author_id": 81263, "author_profile": "https://wordpress.stackexchange.com/users/81263", "pm_score": 0, "selected": false, "text": "<p>If you don't want to register your own meta-boxes: give <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow\">advanced custom fields</a> a go. </p>\n\n<p>You can easily add meta-boxes in the sidebar (or the default: below the main editor screen)</p>\n" }, { "answer_id": 211792, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>As usual with WordPress there is a short answer and a complete answer. :)</p>\n\n<p>In a nutshell if you want something that functions <em>exactly</em> like categories — you can create a new <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow\">taxonomy</a>. You can customize a lot about it, but WP also takes care about a lot of it, including providing you with ready–made meta box.</p>\n\n<p>However! Not all kinds of data are <em>suitable</em> as taxonomy. Some things make more sense as post meta... Which has no easy/native way to provide UI for you. That is realm of building completely custom meta box (or using third party plugin/framework for such).</p>\n\n<p>Learning how to get data architecture right is one of the core skills in WordPress development. It is hard to guess how deep rabbit hole can go in your case. I would say start with taxonomies and see how it works out from there.</p>\n" }, { "answer_id": 211793, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>If you want a meta box, this will do it. It'll be up to you what you want to put in it and how each field is saved / rendered.</p>\n\n<p>This example was adapted from <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow\">add_meta_box</a>.</p>\n\n<pre><code>if ( is_admin() ) {\n add_action( 'load-post.php', 'BoxPost::init' );\n add_action( 'load-post-new.php', 'BoxPost::init' );\n}\n\nif( ! class_exists('BoxPost')) :\n/**\n * The Class.\n */\nclass BoxPost {\n\n const SLUG = \"boxpost_meta_box_name\";\n const NONCE_SLUG = \"boxpost_inner_custom_box\";\n const NONCE = \"boxpost_inner_custom_box_nonce\";\n const TEXT_DOMAIN = 'text_domain';\n\n /**\n * Hook into the appropriate actions when the class is constructed.\n */\n static public function init() {\n add_action( 'add_meta_boxes', 'BoxPost::add_meta_box' );\n add_action( 'save_post', 'BoxPost::save' );\n }\n\n /**\n * Adds the meta box container.\n */\n static public function add_meta_box( $post_type ) {\n $post_types = array('post', 'page'); //limit meta box to certain post types\n if ( in_array( $post_type, $post_types )) {\n add_meta_box(\n self::SLUG\n , __( 'BoxPost Headline', self::TEXT_DOMAIN )\n , 'BoxPost::render_meta_box_content'\n , $post_type\n , 'advanced'\n , 'high' // 'high', 'core', 'default' or 'low'\n );\n }\n }\n\n /**\n * Save the meta when the post is saved.\n *\n * @param int $post_id The ID of the post being saved.\n */\n static public function save( $post_id ) {\n\n /*\n * We need to verify this came from the our screen and with proper authorization,\n * because save_post can be triggered at other times.\n */\n\n // Check if our nonce is set.\n if ( ! isset( $_POST[ self::NONCE ] ) )\n return $post_id;\n\n $nonce = $_POST[ self::NONCE ];\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $nonce, self::NONCE_SLUG ) )\n return $post_id;\n\n // If this is an autosave, our form has not been submitted,\n // so we don't want to do anything.\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return $post_id;\n\n // Check the user's permissions.\n if ( 'page' == $_POST['post_type'] ) {\n\n if ( ! current_user_can( 'edit_page', $post_id ) )\n return $post_id;\n\n } else {\n\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return $post_id;\n }\n\n /* OK, its safe for us to save the data now. */\n\n // Sanitize the user input.\n $mydata = sanitize_text_field( $_POST['boxpost_meta_field'] );\n\n // Update the meta field.\n update_post_meta( $post_id, '_boxpost_meta_field_value_key', $mydata );\n }\n\n\n /**\n * Render Meta Box content.\n *\n * @param WP_Post $post The post object.\n */\n static public function render_meta_box_content( $post ) {\n\n // Add an nonce field so we can check for it later.\n wp_nonce_field( self::NONCE_SLUG, self::NONCE );\n\n // Use get_post_meta to retrieve an existing value from the database.\n $value = get_post_meta( $post-&gt;ID, '_boxpost_meta_field_value_key', true );\n\n // Display the form, using the current value.\n echo '&lt;label for=\"boxpost_meta_field\"&gt;';\n _e( 'Description for this field', self::TEXT_DOMAIN );\n echo '&lt;/label&gt; ';\n echo '&lt;input type=\"text\" id=\"boxpost_meta_field\" name=\"boxpost_meta_field\"';\n echo ' value=\"' . esc_attr( $value ) . '\" size=\"25\" /&gt;';\n }\n}\n\nendif; //BoxPost\n</code></pre>\n\n<p>To get the value later:</p>\n\n<pre><code>$value = get_post_meta( $post-&gt;ID, '_boxpost_meta_field_value_key', true );\n</code></pre>\n" }, { "answer_id": 212707, "author": "Will", "author_id": 44795, "author_profile": "https://wordpress.stackexchange.com/users/44795", "pm_score": 2, "selected": true, "text": "<p>Seems like you already have the custom field for views set up since that's a phpMyAdmin screenshot. If so, you can use <code>order_by=\"post_views_count\"</code> in most <code>wp_query</code> based calls. For instance:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'your_post_type',\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; 'post_views_count',\n);\n$query = new WP_Query( $args );\n\n//...and on with the loop\n&lt;?php while ( have_posts() ) : the_post(); ?&gt;...\n</code></pre>\n\n<p>Limiting this behavior to category 3 is pretty easy but how go about it depends on the context and your template setup.</p>\n\n<p>More on <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\"><code>orderby</code> in the WP Codex</a></p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85291/" ]
I need a code that causes: `<?php while ( have_posts() ) : the_post(); ?>` List according to the amount of VIEW, is like to list popular posts only that it will enter the table **mh\_postmeta**, and list according to who has the most **view**. [![inserir a descrição da imagem aqui](https://i.stack.imgur.com/bvqdm.png)](https://i.stack.imgur.com/bvqdm.png) The staff uses the 'orderby' => 'comment\_count', to list according to the comments, but need it to search for another table, **BUT**, this can only happen to certain category .. Let's say you have 40 **CAT** it should only list by **VIEW** instead of **DATE** in **CAT 3**
Seems like you already have the custom field for views set up since that's a phpMyAdmin screenshot. If so, you can use `order_by="post_views_count"` in most `wp_query` based calls. For instance: ``` $args = array( 'post_type' => 'your_post_type', 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count', ); $query = new WP_Query( $args ); //...and on with the loop <?php while ( have_posts() ) : the_post(); ?>... ``` Limiting this behavior to category 3 is pretty easy but how go about it depends on the context and your template setup. More on [`orderby` in the WP Codex](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters)
211,802
<p>How can I set a post's featured image using the content of a shortcode? For instance, the following shortcode should set the post's featured image to the image at <code>www.google.de/nicepic.jpg</code>:</p> <pre><code>[post_image]www.google.de/nicepic.jpg[/post_image] </code></pre>
[ { "answer_id": 211808, "author": "Manu", "author_id": 22963, "author_profile": "https://wordpress.stackexchange.com/users/22963", "pm_score": 0, "selected": false, "text": "<p>Not a full answer, but maybe a hint in the right direction...</p>\n\n<p>In terms of saved data, a featured image is actually a custom field named <code>_thumbnail_id</code> that holds the numeric ID of the image attachment.</p>\n\n<p>When exporting your posts as XML, it shows up like this:</p>\n\n<pre><code>&lt;wp:postmeta&gt;\n &lt;wp:meta_key&gt;_thumbnail_id&lt;/wp:meta_key&gt;\n &lt;wp:meta_value&gt;&lt;![CDATA[1497]]&gt;&lt;/wp:meta_value&gt;\n&lt;/wp:postmeta&gt;`\n</code></pre>\n\n<p>So you could try to add images programmatically by using <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">add_post_meta()</a>.</p>\n\n<p>Using external image URLs won't be that easy though, as WordPress doesn't allow them for Featured Images.</p>\n" }, { "answer_id": 212093, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": true, "text": "<p>The Shortcode API is more geared for altering post content rather than performing actions in response to content, and as such tend to require more creativity to alter other post data - though it can still be done. Ultimately, using a shortcode to set a featured image is kind of bizarre considering that you can do the same thing by clicking a button in the post editor UI.</p>\n<p><em>I emphasize that my solutions below are untested hacks that rely on using WordPress components in non-standard ways</em></p>\n<hr />\n<h2>Solution</h2>\n<p>Use <a href=\"https://codex.wordpress.org/Plugin_API\" rel=\"nofollow noreferrer\">the Plugin API</a> to <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">write a plugin</a> that uses <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">the Shortcode API</a> to <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow noreferrer\">register your shortcode</a>.</p>\n<p>In order to set a remote image as the featured image, you'll need to download the image, move it to a permanent location (such as <code>wp-content/uploads</code>), attach it to the post, then set the featured image. There are a few ways to accomplish this, but I think the most straightforward would be to</p>\n<ol>\n<li>Use <a href=\"https://codex.wordpress.org/Function_Reference/download_url\" rel=\"nofollow noreferrer\"><code>download_url()</code></a> to download the remote image to the temporary directory.</li>\n<li>Pass the temporary filepath to <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_sideload\" rel=\"nofollow noreferrer\"><code>handle_media_sideload()</code></a> to move the file to <code>wp-content/uploads</code>, generate attachment metadata, and attach it to the post.</li>\n<li>Pass the returned attachment ID to <a href=\"https://codex.wordpress.org/Function_Reference/set_post_thumbnail\" rel=\"nofollow noreferrer\"><code>set_post_thumbnail()</code></a> to specify it as the featured image.</li>\n</ol>\n<p>The tricky part about applying the above in a shortcode's callback function is that <code>handle_media_sideload()</code> and <code>set_post_thumbnail()</code> both require the post's ID, and shortcode callbacks are not passed the post ID nor the post object itself. The have access to this data when shortcodes are applied to posts getting displayed in The Loop by way of the global <code>$post</code> object, however applying the above operation at that point could result in the image being downloaded and set every time the post was displayed.</p>\n<p>One possible work-around to achieve the hack would be to use a class property to pass the post ID, and return early from the shortcode callback the shortcode's contents weren't modified.</p>\n<hr />\n<h2>Alternate Solution</h2>\n<p>A simpler hack may be to manually extract the remote image URL from the post's contents on an action hook that fires when a post is saved (such as <code>save_post</code>). A shortcode could still be registered to return a blank string. Something along the lines of</p>\n<pre><code>$featured_image_shortcode = 'post_image';\n\nwpse_211802_featured_image_shortcode( $atts, $content ) {\n return '';\n}\n\nadd_shortcode( $featured_image_shortcode, 'wpse_211802_featured_image_shortcode' );\n\nwpse_211802_featured_image_from_shortcode_url( $post_id ) {\n $content = get_the_content( $post_id );\n $shortcode_matches = array();\n \n if( ! has_shortcode( $content, 'post_image' ) )\n return;\n \n preg_match_all( '\\[' . $featured_image_shortcode . '\\](.*)\\[\\/' . $featured_image_shortcode . '\\]', $content, $shortcode_matches );\n \n $url = $shortcode_matches[ 1 ][ 0 ];\n $tempfile = download_url( $url );\n \n if( is_wp_error( $tempfile ) ){\n // download failed, handle error\n return;\n }\n\n // Set variables for storage\n preg_match( '/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches );\n\n $desc = 'Featured Image for Post ' . $post_id;\n $file_array = array(\n 'name' =&gt; basename( $matches[0] ),\n 'tmp_name' =&gt; $tempfile\n );\n\n // Sideload the downloaded file as an attachment to this post\n $attachment_id = media_handle_sideload( $file_array, $post_id, $desc );\n\n // If errors encountered while sideloading, delete the downloaded file\n if ( is_wp_error( $attachment_id ) ) {\n @unlink( $tempfile );\n return;\n }\n \n // If all went well, set the featured image\n set_post_thumbnail( $post_id, $attachment_id );\n}\n\nadd_action( 'save_post', 'wpse_211802_featured_image_from_shortcode_url' );\n</code></pre>\n<p>You may need to <code>require_once()</code> additional files in order for the above to function. If you do something similar, I'd recommend expanding upon the error handling and URL validation.</p>\n<p>Still though - far easier to just set the featured image with the button on the post editor UI.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85306/" ]
How can I set a post's featured image using the content of a shortcode? For instance, the following shortcode should set the post's featured image to the image at `www.google.de/nicepic.jpg`: ``` [post_image]www.google.de/nicepic.jpg[/post_image] ```
The Shortcode API is more geared for altering post content rather than performing actions in response to content, and as such tend to require more creativity to alter other post data - though it can still be done. Ultimately, using a shortcode to set a featured image is kind of bizarre considering that you can do the same thing by clicking a button in the post editor UI. *I emphasize that my solutions below are untested hacks that rely on using WordPress components in non-standard ways* --- Solution -------- Use [the Plugin API](https://codex.wordpress.org/Plugin_API) to [write a plugin](https://codex.wordpress.org/Writing_a_Plugin) that uses [the Shortcode API](https://codex.wordpress.org/Shortcode_API) to [register your shortcode](https://codex.wordpress.org/Function_Reference/add_shortcode). In order to set a remote image as the featured image, you'll need to download the image, move it to a permanent location (such as `wp-content/uploads`), attach it to the post, then set the featured image. There are a few ways to accomplish this, but I think the most straightforward would be to 1. Use [`download_url()`](https://codex.wordpress.org/Function_Reference/download_url) to download the remote image to the temporary directory. 2. Pass the temporary filepath to [`handle_media_sideload()`](https://codex.wordpress.org/Function_Reference/media_handle_sideload) to move the file to `wp-content/uploads`, generate attachment metadata, and attach it to the post. 3. Pass the returned attachment ID to [`set_post_thumbnail()`](https://codex.wordpress.org/Function_Reference/set_post_thumbnail) to specify it as the featured image. The tricky part about applying the above in a shortcode's callback function is that `handle_media_sideload()` and `set_post_thumbnail()` both require the post's ID, and shortcode callbacks are not passed the post ID nor the post object itself. The have access to this data when shortcodes are applied to posts getting displayed in The Loop by way of the global `$post` object, however applying the above operation at that point could result in the image being downloaded and set every time the post was displayed. One possible work-around to achieve the hack would be to use a class property to pass the post ID, and return early from the shortcode callback the shortcode's contents weren't modified. --- Alternate Solution ------------------ A simpler hack may be to manually extract the remote image URL from the post's contents on an action hook that fires when a post is saved (such as `save_post`). A shortcode could still be registered to return a blank string. Something along the lines of ``` $featured_image_shortcode = 'post_image'; wpse_211802_featured_image_shortcode( $atts, $content ) { return ''; } add_shortcode( $featured_image_shortcode, 'wpse_211802_featured_image_shortcode' ); wpse_211802_featured_image_from_shortcode_url( $post_id ) { $content = get_the_content( $post_id ); $shortcode_matches = array(); if( ! has_shortcode( $content, 'post_image' ) ) return; preg_match_all( '\[' . $featured_image_shortcode . '\](.*)\[\/' . $featured_image_shortcode . '\]', $content, $shortcode_matches ); $url = $shortcode_matches[ 1 ][ 0 ]; $tempfile = download_url( $url ); if( is_wp_error( $tempfile ) ){ // download failed, handle error return; } // Set variables for storage preg_match( '/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches ); $desc = 'Featured Image for Post ' . $post_id; $file_array = array( 'name' => basename( $matches[0] ), 'tmp_name' => $tempfile ); // Sideload the downloaded file as an attachment to this post $attachment_id = media_handle_sideload( $file_array, $post_id, $desc ); // If errors encountered while sideloading, delete the downloaded file if ( is_wp_error( $attachment_id ) ) { @unlink( $tempfile ); return; } // If all went well, set the featured image set_post_thumbnail( $post_id, $attachment_id ); } add_action( 'save_post', 'wpse_211802_featured_image_from_shortcode_url' ); ``` You may need to `require_once()` additional files in order for the above to function. If you do something similar, I'd recommend expanding upon the error handling and URL validation. Still though - far easier to just set the featured image with the button on the post editor UI.
211,803
<p>My plugin uses camelCase in file and folder like</p> <pre><code>myPlugin/myPlugin.php </code></pre> <p>I've encountered several issues with this on plugin updates. Most of them work just fine and it's more a cosmetic thing but on some places I just like to go with all lowercase.</p> <p>What's the best way (or is there any) to update the plugin to</p> <pre><code>myplugin/myplugin.php </code></pre> <p><em>without</em> hazzle the users?</p> <p>Please note this is a custom plugin and not available on the repo and yes I had to do it lowercase in the first place.</p>
[ { "answer_id": 211915, "author": "grappler", "author_id": 17937, "author_profile": "https://wordpress.stackexchange.com/users/17937", "pm_score": 1, "selected": false, "text": "<p>If you just wanted to just change the filename you would have both <code>myPlugin.php</code> and <code>myplugin.php</code> in the plugin and then update the option <code>active_plugins</code> in the database to the new name. Once all of the users have updated you can remove <code>myPlugin.php</code>.</p>\n\n<p>But you want to rename both the folder and filename.</p>\n\n<p>I would get <code>myPlugin/myPlugin.php</code> to install and activate <code>myplugin/myplugin.php</code>. Once <code>myplugin/myplugin.php</code> is installed <code>myplugin/myplugin.php</code> can delete <code>myPlugin/myPlugin.php</code></p>\n\n<p>You can use <a href=\"http://tgmpluginactivation.com/\" rel=\"nofollow\">TGM Plugin Activation</a> for installing and activating the new plugin. Make to include a check so that the new and old version are not running at the same time.</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>deactivate_plugins()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>delete_plugins()</code></a> to deactivate and uninstall the plugin.</p>\n" }, { "answer_id": 211934, "author": "Xaver", "author_id": 18981, "author_profile": "https://wordpress.stackexchange.com/users/18981", "pm_score": 1, "selected": true, "text": "<p>Ok, I did some research/testing on it an in short terms:</p>\n\n<p><strong>Don't use uppercase in the first place!</strong></p>\n\n<p>I've currently noticed only one problem where the ajax based update from the plugins overview (introduced in WP 4.2) throws a JS error but it may be a problem in the future.</p>\n\n<p>This is because the ajax response uses <code>sanitize_key</code> in the <code>wp_ajax_update_plugin</code> method (<a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/ajax-actions.php#L3073\" rel=\"nofollow\">browse in trac</a>).</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src//wp-includes/formatting.php#L1486\" rel=\"nofollow\">The <code>sanitize_key</code> method</a> does next to sanitization a <code>strtolower</code> which causes the \"<code>myPlugin</code>\" gets a \"<code>myplugin</code>\".</p>\n\n<p>The <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src//wp-admin/js/updates.js#L200\" rel=\"nofollow\"><code>updateSuccess</code></a> method tries now to update the row where the slug is \"<code>myplugin</code>\" instead of \"<code>myPlugin</code>\".</p>\n\n<p>This could be prevented by changing <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src///wp-admin/includes/class-wp-plugins-list-table.php#L694\" rel=\"nofollow\">line 694</a> in <code>wp-admin/includes/class-wp-plugins-list-table.php</code> from</p>\n\n<pre><code> printf( \"&lt;tr id='%s' class='%s' data-slug='%s'&gt;\",\n $id,\n $class,\n $plugin_slug\n );\n</code></pre>\n\n<p>to</p>\n\n<pre><code> printf( \"&lt;tr id='%s' class='%s' data-slug='%s'&gt;\",\n $id,\n $class,\n sanitize_key($plugin_slug)\n );\n</code></pre>\n\n<p><del><em>todo: open ticket</em></del> <a href=\"https://core.trac.wordpress.org/ticket/35032\" rel=\"nofollow\">Ticket #35032</a></p>\n\n<p><strong>To answer the initial question</strong></p>\n\n<p>You can change the slug on a plugin update but you have to take care of following:</p>\n\n<ul>\n<li>the following code must be included in the old version (eg.\n`myPlugin/myPlugin.php)</li>\n<li>the updated version <strong>must</strong> have a slug of `myplugin/myplugin.php</li>\n<li>don't use <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>delete_plugin()</code></a> which may trigger an uninstall.php and removes plugins data</li>\n</ul>\n\n<p>Here's the code you can start with:</p>\n\n<pre><code>//hook into when new plugin has been successfully updated\nadd_filter( 'upgrader_post_install', 'my_move_plugin_slug', 10 ,3 );\n\nfunction my_move_plugin_slug($should_be_true, $hook_extra, $result){\n\n global $wpdb, $wp_filesystem;\n\n $from = 'myPlugin/myPlugin.php';\n $to = 'myplugin/myplugin.php';\n\n //some general checks\n if(!$should_be_true || !isset($hook_extra['plugin']) || $hook_extra['plugin'] != $to) return $should_be_true;\n\n $old_destination = $result['local_destination'].'/'.dirname($from).'/';\n\n //old location doesn't exist (anymore)\n if(!is_dir($old_destination)) return $should_be_true;\n //new location is the same as the old one\n if($old_destination == $result['destination']) return $should_be_true;\n\n //do the magic\n\n //rewrite location in the database\n echo '&lt;p&gt;Moving the plugin to new location… ';\n if(false !== $wpdb-&gt;query($wpdb-&gt;prepare(\"UPDATE {$wpdb-&gt;options} SET `option_value` = replace(option_value, %s, %s)\", $from, $to))){\n echo '&lt;strong&gt;done&lt;/strong&gt;';\n }\n echo '&lt;/p&gt;';\n\n //delete folder\n echo '&lt;p&gt;Removing the old directory of the plugin… ';\n if($wp_filesystem-&gt;delete( $old_destination , true )){\n echo '&lt;strong&gt;done&lt;/strong&gt;';\n }\n echo '&lt;/p&gt;';\n\n}\n</code></pre>\n\n<p><strong>Second method</strong></p>\n\n<p>If you have a dedicate batch update progress in you plugin like I have you can use this code which is in my opinion a bit safer as it's triggered by explicit user interaction and doesn't require wp_filesystem:</p>\n\n<pre><code>function do_change_plugin_slug(){\n\n global $wpdb;\n\n $from = 'myMail/myMail.php';\n $to = 'mymail/mymail.php';\n\n $old_destination = WP_PLUGIN_DIR.'/'.$from;\n $new_destination = WP_PLUGIN_DIR.'/'.$to;\n\n //old location doesn't exist (anymore)\n if(!file_exists($old_destination)) return true;\n //new location is the same as the old one\n if($old_destination == $new_destination) return true;\n\n //do the magic\n\n echo 'Removing the old file of the plugin… ';\n if(rename( $old_destination , dirname($old_destination).'/'.basename($new_destination) )){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n echo 'Removing the old directory of the plugin… ';\n if(rename( dirname($old_destination) , dirname($new_destination) )){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n //rewrite location in the database\n echo 'Moving the plugin to new location… ';\n if(false !== $wpdb-&gt;query($wpdb-&gt;prepare(\"UPDATE {$wpdb-&gt;options} SET `option_value` = replace(option_value, %s, %s)\", $from, $to))){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n return true;\n\n}\n</code></pre>\n\n<p>In the end you should always make sure the user understands what's going on and/or why this is a necessary step.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211803", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18981/" ]
My plugin uses camelCase in file and folder like ``` myPlugin/myPlugin.php ``` I've encountered several issues with this on plugin updates. Most of them work just fine and it's more a cosmetic thing but on some places I just like to go with all lowercase. What's the best way (or is there any) to update the plugin to ``` myplugin/myplugin.php ``` *without* hazzle the users? Please note this is a custom plugin and not available on the repo and yes I had to do it lowercase in the first place.
Ok, I did some research/testing on it an in short terms: **Don't use uppercase in the first place!** I've currently noticed only one problem where the ajax based update from the plugins overview (introduced in WP 4.2) throws a JS error but it may be a problem in the future. This is because the ajax response uses `sanitize_key` in the `wp_ajax_update_plugin` method ([browse in trac](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/ajax-actions.php#L3073)). [The `sanitize_key` method](https://core.trac.wordpress.org/browser/tags/4.4/src//wp-includes/formatting.php#L1486) does next to sanitization a `strtolower` which causes the "`myPlugin`" gets a "`myplugin`". The [`updateSuccess`](https://core.trac.wordpress.org/browser/tags/4.4/src//wp-admin/js/updates.js#L200) method tries now to update the row where the slug is "`myplugin`" instead of "`myPlugin`". This could be prevented by changing [line 694](https://core.trac.wordpress.org/browser/tags/4.4/src///wp-admin/includes/class-wp-plugins-list-table.php#L694) in `wp-admin/includes/class-wp-plugins-list-table.php` from ``` printf( "<tr id='%s' class='%s' data-slug='%s'>", $id, $class, $plugin_slug ); ``` to ``` printf( "<tr id='%s' class='%s' data-slug='%s'>", $id, $class, sanitize_key($plugin_slug) ); ``` ~~*todo: open ticket*~~ [Ticket #35032](https://core.trac.wordpress.org/ticket/35032) **To answer the initial question** You can change the slug on a plugin update but you have to take care of following: * the following code must be included in the old version (eg. `myPlugin/myPlugin.php) * the updated version **must** have a slug of `myplugin/myplugin.php * don't use [`delete_plugin()`](https://developer.wordpress.org/reference/functions/delete_plugins/) which may trigger an uninstall.php and removes plugins data Here's the code you can start with: ``` //hook into when new plugin has been successfully updated add_filter( 'upgrader_post_install', 'my_move_plugin_slug', 10 ,3 ); function my_move_plugin_slug($should_be_true, $hook_extra, $result){ global $wpdb, $wp_filesystem; $from = 'myPlugin/myPlugin.php'; $to = 'myplugin/myplugin.php'; //some general checks if(!$should_be_true || !isset($hook_extra['plugin']) || $hook_extra['plugin'] != $to) return $should_be_true; $old_destination = $result['local_destination'].'/'.dirname($from).'/'; //old location doesn't exist (anymore) if(!is_dir($old_destination)) return $should_be_true; //new location is the same as the old one if($old_destination == $result['destination']) return $should_be_true; //do the magic //rewrite location in the database echo '<p>Moving the plugin to new location… '; if(false !== $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET `option_value` = replace(option_value, %s, %s)", $from, $to))){ echo '<strong>done</strong>'; } echo '</p>'; //delete folder echo '<p>Removing the old directory of the plugin… '; if($wp_filesystem->delete( $old_destination , true )){ echo '<strong>done</strong>'; } echo '</p>'; } ``` **Second method** If you have a dedicate batch update progress in you plugin like I have you can use this code which is in my opinion a bit safer as it's triggered by explicit user interaction and doesn't require wp\_filesystem: ``` function do_change_plugin_slug(){ global $wpdb; $from = 'myMail/myMail.php'; $to = 'mymail/mymail.php'; $old_destination = WP_PLUGIN_DIR.'/'.$from; $new_destination = WP_PLUGIN_DIR.'/'.$to; //old location doesn't exist (anymore) if(!file_exists($old_destination)) return true; //new location is the same as the old one if($old_destination == $new_destination) return true; //do the magic echo 'Removing the old file of the plugin… '; if(rename( $old_destination , dirname($old_destination).'/'.basename($new_destination) )){ echo 'done'; }else{ echo 'failed'; } echo "\n"; echo 'Removing the old directory of the plugin… '; if(rename( dirname($old_destination) , dirname($new_destination) )){ echo 'done'; }else{ echo 'failed'; } echo "\n"; //rewrite location in the database echo 'Moving the plugin to new location… '; if(false !== $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET `option_value` = replace(option_value, %s, %s)", $from, $to))){ echo 'done'; }else{ echo 'failed'; } echo "\n"; return true; } ``` In the end you should always make sure the user understands what's going on and/or why this is a necessary step.
211,804
<p>PHP noob here. I've got this query I've written to get the information of all child pages of the page you're currently on:</p> <pre><code> &lt;?php $pages = get_pages('child_of=1015&amp;sort_column=post_title'); $count = 0; foreach($pages as $page) { ?&gt; &lt;div class="position-info"&gt;&lt;h4&gt;&lt;a href="&lt;?php echo get_page_link($page-&gt;ID) ?&gt;"&gt;&lt;?php echo $page-&gt;post_title ?&gt;&lt;/a&gt;&lt;/h4&gt;&lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>But I don't know the correct syntax to turn this into an if statement, followed by an else statement so I can say "There's no content here. Check back later." Or something like that.</p> <p>This query is inside of the page's main loop.</p> <p>Can any PHP masters out there help?</p>
[ { "answer_id": 211915, "author": "grappler", "author_id": 17937, "author_profile": "https://wordpress.stackexchange.com/users/17937", "pm_score": 1, "selected": false, "text": "<p>If you just wanted to just change the filename you would have both <code>myPlugin.php</code> and <code>myplugin.php</code> in the plugin and then update the option <code>active_plugins</code> in the database to the new name. Once all of the users have updated you can remove <code>myPlugin.php</code>.</p>\n\n<p>But you want to rename both the folder and filename.</p>\n\n<p>I would get <code>myPlugin/myPlugin.php</code> to install and activate <code>myplugin/myplugin.php</code>. Once <code>myplugin/myplugin.php</code> is installed <code>myplugin/myplugin.php</code> can delete <code>myPlugin/myPlugin.php</code></p>\n\n<p>You can use <a href=\"http://tgmpluginactivation.com/\" rel=\"nofollow\">TGM Plugin Activation</a> for installing and activating the new plugin. Make to include a check so that the new and old version are not running at the same time.</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>deactivate_plugins()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>delete_plugins()</code></a> to deactivate and uninstall the plugin.</p>\n" }, { "answer_id": 211934, "author": "Xaver", "author_id": 18981, "author_profile": "https://wordpress.stackexchange.com/users/18981", "pm_score": 1, "selected": true, "text": "<p>Ok, I did some research/testing on it an in short terms:</p>\n\n<p><strong>Don't use uppercase in the first place!</strong></p>\n\n<p>I've currently noticed only one problem where the ajax based update from the plugins overview (introduced in WP 4.2) throws a JS error but it may be a problem in the future.</p>\n\n<p>This is because the ajax response uses <code>sanitize_key</code> in the <code>wp_ajax_update_plugin</code> method (<a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/ajax-actions.php#L3073\" rel=\"nofollow\">browse in trac</a>).</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src//wp-includes/formatting.php#L1486\" rel=\"nofollow\">The <code>sanitize_key</code> method</a> does next to sanitization a <code>strtolower</code> which causes the \"<code>myPlugin</code>\" gets a \"<code>myplugin</code>\".</p>\n\n<p>The <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src//wp-admin/js/updates.js#L200\" rel=\"nofollow\"><code>updateSuccess</code></a> method tries now to update the row where the slug is \"<code>myplugin</code>\" instead of \"<code>myPlugin</code>\".</p>\n\n<p>This could be prevented by changing <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src///wp-admin/includes/class-wp-plugins-list-table.php#L694\" rel=\"nofollow\">line 694</a> in <code>wp-admin/includes/class-wp-plugins-list-table.php</code> from</p>\n\n<pre><code> printf( \"&lt;tr id='%s' class='%s' data-slug='%s'&gt;\",\n $id,\n $class,\n $plugin_slug\n );\n</code></pre>\n\n<p>to</p>\n\n<pre><code> printf( \"&lt;tr id='%s' class='%s' data-slug='%s'&gt;\",\n $id,\n $class,\n sanitize_key($plugin_slug)\n );\n</code></pre>\n\n<p><del><em>todo: open ticket</em></del> <a href=\"https://core.trac.wordpress.org/ticket/35032\" rel=\"nofollow\">Ticket #35032</a></p>\n\n<p><strong>To answer the initial question</strong></p>\n\n<p>You can change the slug on a plugin update but you have to take care of following:</p>\n\n<ul>\n<li>the following code must be included in the old version (eg.\n`myPlugin/myPlugin.php)</li>\n<li>the updated version <strong>must</strong> have a slug of `myplugin/myplugin.php</li>\n<li>don't use <a href=\"https://developer.wordpress.org/reference/functions/delete_plugins/\" rel=\"nofollow\"><code>delete_plugin()</code></a> which may trigger an uninstall.php and removes plugins data</li>\n</ul>\n\n<p>Here's the code you can start with:</p>\n\n<pre><code>//hook into when new plugin has been successfully updated\nadd_filter( 'upgrader_post_install', 'my_move_plugin_slug', 10 ,3 );\n\nfunction my_move_plugin_slug($should_be_true, $hook_extra, $result){\n\n global $wpdb, $wp_filesystem;\n\n $from = 'myPlugin/myPlugin.php';\n $to = 'myplugin/myplugin.php';\n\n //some general checks\n if(!$should_be_true || !isset($hook_extra['plugin']) || $hook_extra['plugin'] != $to) return $should_be_true;\n\n $old_destination = $result['local_destination'].'/'.dirname($from).'/';\n\n //old location doesn't exist (anymore)\n if(!is_dir($old_destination)) return $should_be_true;\n //new location is the same as the old one\n if($old_destination == $result['destination']) return $should_be_true;\n\n //do the magic\n\n //rewrite location in the database\n echo '&lt;p&gt;Moving the plugin to new location… ';\n if(false !== $wpdb-&gt;query($wpdb-&gt;prepare(\"UPDATE {$wpdb-&gt;options} SET `option_value` = replace(option_value, %s, %s)\", $from, $to))){\n echo '&lt;strong&gt;done&lt;/strong&gt;';\n }\n echo '&lt;/p&gt;';\n\n //delete folder\n echo '&lt;p&gt;Removing the old directory of the plugin… ';\n if($wp_filesystem-&gt;delete( $old_destination , true )){\n echo '&lt;strong&gt;done&lt;/strong&gt;';\n }\n echo '&lt;/p&gt;';\n\n}\n</code></pre>\n\n<p><strong>Second method</strong></p>\n\n<p>If you have a dedicate batch update progress in you plugin like I have you can use this code which is in my opinion a bit safer as it's triggered by explicit user interaction and doesn't require wp_filesystem:</p>\n\n<pre><code>function do_change_plugin_slug(){\n\n global $wpdb;\n\n $from = 'myMail/myMail.php';\n $to = 'mymail/mymail.php';\n\n $old_destination = WP_PLUGIN_DIR.'/'.$from;\n $new_destination = WP_PLUGIN_DIR.'/'.$to;\n\n //old location doesn't exist (anymore)\n if(!file_exists($old_destination)) return true;\n //new location is the same as the old one\n if($old_destination == $new_destination) return true;\n\n //do the magic\n\n echo 'Removing the old file of the plugin… ';\n if(rename( $old_destination , dirname($old_destination).'/'.basename($new_destination) )){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n echo 'Removing the old directory of the plugin… ';\n if(rename( dirname($old_destination) , dirname($new_destination) )){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n //rewrite location in the database\n echo 'Moving the plugin to new location… ';\n if(false !== $wpdb-&gt;query($wpdb-&gt;prepare(\"UPDATE {$wpdb-&gt;options} SET `option_value` = replace(option_value, %s, %s)\", $from, $to))){\n echo 'done';\n }else{\n echo 'failed';\n }\n echo \"\\n\";\n\n return true;\n\n}\n</code></pre>\n\n<p>In the end you should always make sure the user understands what's going on and/or why this is a necessary step.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66039/" ]
PHP noob here. I've got this query I've written to get the information of all child pages of the page you're currently on: ``` <?php $pages = get_pages('child_of=1015&sort_column=post_title'); $count = 0; foreach($pages as $page) { ?> <div class="position-info"><h4><a href="<?php echo get_page_link($page->ID) ?>"><?php echo $page->post_title ?></a></h4></div> <?php } ?> ``` But I don't know the correct syntax to turn this into an if statement, followed by an else statement so I can say "There's no content here. Check back later." Or something like that. This query is inside of the page's main loop. Can any PHP masters out there help?
Ok, I did some research/testing on it an in short terms: **Don't use uppercase in the first place!** I've currently noticed only one problem where the ajax based update from the plugins overview (introduced in WP 4.2) throws a JS error but it may be a problem in the future. This is because the ajax response uses `sanitize_key` in the `wp_ajax_update_plugin` method ([browse in trac](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/ajax-actions.php#L3073)). [The `sanitize_key` method](https://core.trac.wordpress.org/browser/tags/4.4/src//wp-includes/formatting.php#L1486) does next to sanitization a `strtolower` which causes the "`myPlugin`" gets a "`myplugin`". The [`updateSuccess`](https://core.trac.wordpress.org/browser/tags/4.4/src//wp-admin/js/updates.js#L200) method tries now to update the row where the slug is "`myplugin`" instead of "`myPlugin`". This could be prevented by changing [line 694](https://core.trac.wordpress.org/browser/tags/4.4/src///wp-admin/includes/class-wp-plugins-list-table.php#L694) in `wp-admin/includes/class-wp-plugins-list-table.php` from ``` printf( "<tr id='%s' class='%s' data-slug='%s'>", $id, $class, $plugin_slug ); ``` to ``` printf( "<tr id='%s' class='%s' data-slug='%s'>", $id, $class, sanitize_key($plugin_slug) ); ``` ~~*todo: open ticket*~~ [Ticket #35032](https://core.trac.wordpress.org/ticket/35032) **To answer the initial question** You can change the slug on a plugin update but you have to take care of following: * the following code must be included in the old version (eg. `myPlugin/myPlugin.php) * the updated version **must** have a slug of `myplugin/myplugin.php * don't use [`delete_plugin()`](https://developer.wordpress.org/reference/functions/delete_plugins/) which may trigger an uninstall.php and removes plugins data Here's the code you can start with: ``` //hook into when new plugin has been successfully updated add_filter( 'upgrader_post_install', 'my_move_plugin_slug', 10 ,3 ); function my_move_plugin_slug($should_be_true, $hook_extra, $result){ global $wpdb, $wp_filesystem; $from = 'myPlugin/myPlugin.php'; $to = 'myplugin/myplugin.php'; //some general checks if(!$should_be_true || !isset($hook_extra['plugin']) || $hook_extra['plugin'] != $to) return $should_be_true; $old_destination = $result['local_destination'].'/'.dirname($from).'/'; //old location doesn't exist (anymore) if(!is_dir($old_destination)) return $should_be_true; //new location is the same as the old one if($old_destination == $result['destination']) return $should_be_true; //do the magic //rewrite location in the database echo '<p>Moving the plugin to new location… '; if(false !== $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET `option_value` = replace(option_value, %s, %s)", $from, $to))){ echo '<strong>done</strong>'; } echo '</p>'; //delete folder echo '<p>Removing the old directory of the plugin… '; if($wp_filesystem->delete( $old_destination , true )){ echo '<strong>done</strong>'; } echo '</p>'; } ``` **Second method** If you have a dedicate batch update progress in you plugin like I have you can use this code which is in my opinion a bit safer as it's triggered by explicit user interaction and doesn't require wp\_filesystem: ``` function do_change_plugin_slug(){ global $wpdb; $from = 'myMail/myMail.php'; $to = 'mymail/mymail.php'; $old_destination = WP_PLUGIN_DIR.'/'.$from; $new_destination = WP_PLUGIN_DIR.'/'.$to; //old location doesn't exist (anymore) if(!file_exists($old_destination)) return true; //new location is the same as the old one if($old_destination == $new_destination) return true; //do the magic echo 'Removing the old file of the plugin… '; if(rename( $old_destination , dirname($old_destination).'/'.basename($new_destination) )){ echo 'done'; }else{ echo 'failed'; } echo "\n"; echo 'Removing the old directory of the plugin… '; if(rename( dirname($old_destination) , dirname($new_destination) )){ echo 'done'; }else{ echo 'failed'; } echo "\n"; //rewrite location in the database echo 'Moving the plugin to new location… '; if(false !== $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET `option_value` = replace(option_value, %s, %s)", $from, $to))){ echo 'done'; }else{ echo 'failed'; } echo "\n"; return true; } ``` In the end you should always make sure the user understands what's going on and/or why this is a necessary step.
211,811
<p>This is sort of a follow up to <a href="https://wordpress.stackexchange.com/questions/211632/can-i-put-my-wordpress-theme-files-in-another-folder">Can I put my Wordpress theme files in another folder?</a></p> <p>I found that following</p> <pre><code>...\wp-content\themes\MyTheme - \dist - \lib - \src - \wp - All my Wordpress files like index.php, style.css, functions.php, etc. - .gitignore - README.md - many other non-Wordpress files </code></pre> <p>Generally works in better grouping my Wordpress files into its own folder. However, it also changes <code>get_template_directory_uri()</code> to now point to <code>...\themes\MyTheme\wp</code> which means somewhere in my <code>header.php</code> I am calling</p> <pre><code>&lt;script src="&lt;?php echo get_template_directory_uri(); ?&gt;/../dist/bundle.js"&gt;&lt;/script&gt; </code></pre> <p>I'd like for <code>get_template_directory_uri()</code> to point to <code>...\themes\MyTheme</code> so I can avoid having to use the <code>/../</code> thing in the path.</p>
[ { "answer_id": 211813, "author": "Thomas Withers", "author_id": 85307, "author_profile": "https://wordpress.stackexchange.com/users/85307", "pm_score": 0, "selected": false, "text": "<p>well you could probably create a variable at the start of your header.php and assign its value string as your desired path....</p>\n\n<pre><code>&lt;?php $dir = your_path_here ?&gt;\n</code></pre>\n\n<p>theoretically this should work :) best not to change wordpress stuff as it might be used somewhere else</p>\n" }, { "answer_id": 211815, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>If you look at the function <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L319\" rel=\"nofollow\">in source</a>, you'll see the <code>template_directory_uri</code> hook <a href=\"https://codex.wordpress.org/Function_Reference/add_filter\" rel=\"nofollow\">you can filter</a> to modify output.</p>\n\n<pre><code>return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri );\n</code></pre>\n" }, { "answer_id": 329946, "author": "Bradan", "author_id": 162048, "author_profile": "https://wordpress.stackexchange.com/users/162048", "pm_score": 2, "selected": false, "text": "<p>I'd like to contribute a more detailed answer as I found figuring out 'add_filter()' was quite frustrating.</p>\n\n<p>In order to edit the hook for get_template_directory_uri(), you need to add filter as</p>\n\n<pre><code>add_filter('template_directory_uri', 'yourFunction', 10, 2);\n</code></pre>\n\n<p>where function is the function you are calling to edit the string, as such:</p>\n\n<pre><code>function yourFunction($string) {\n //Modify the string here\n return $string;\n}\n</code></pre>\n\n<p>Hope this helps anyone who stumbles across this question in the future!</p>\n" }, { "answer_id": 339351, "author": "zundi", "author_id": 169285, "author_profile": "https://wordpress.stackexchange.com/users/169285", "pm_score": -1, "selected": false, "text": "<p>I was searching for this when doing a migration to a site with another domain name. I fixed this by searching the database. These values are set in the <code>wp_options</code> table of your database. In my case, rows with <code>option_name</code> equal to <code>siteurl</code> and <code>home</code>. I updated the values and everything now works as expected.</p>\n" } ]
2015/12/14
[ "https://wordpress.stackexchange.com/questions/211811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70599/" ]
This is sort of a follow up to [Can I put my Wordpress theme files in another folder?](https://wordpress.stackexchange.com/questions/211632/can-i-put-my-wordpress-theme-files-in-another-folder) I found that following ``` ...\wp-content\themes\MyTheme - \dist - \lib - \src - \wp - All my Wordpress files like index.php, style.css, functions.php, etc. - .gitignore - README.md - many other non-Wordpress files ``` Generally works in better grouping my Wordpress files into its own folder. However, it also changes `get_template_directory_uri()` to now point to `...\themes\MyTheme\wp` which means somewhere in my `header.php` I am calling ``` <script src="<?php echo get_template_directory_uri(); ?>/../dist/bundle.js"></script> ``` I'd like for `get_template_directory_uri()` to point to `...\themes\MyTheme` so I can avoid having to use the `/../` thing in the path.
If you look at the function [in source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L319), you'll see the `template_directory_uri` hook [you can filter](https://codex.wordpress.org/Function_Reference/add_filter) to modify output. ``` return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri ); ```
211,830
<p>The admin bar displays on the dashboard, but does not display on pages or posts.</p> <p>I'm working with a child theme of Twenty Thirteen that I did not code. I'm a beginning level coder and work mostly with builders. So the builder plugin I installed is also not showing up either.</p> <p>I've read some potential causes and checked those off. There are things I've tried that did not correct the problem:</p> <p>The display is set correctly in the user settings.</p> <p>I logged out as an admin, logged in as a subscriber and logged back in as an admin.</p> <p>The index.php file contains '' (the code is not displaying, but it is the php call for the footer)</p> <p>The <code>function.php</code> file does not have any code pertaining to the admin bar.</p> <p>The <code>footer.php</code> file does not have any code pertaining to the admin bar.</p> <p>I do not have access to the client's files on their server, so I cannot use <code>wp_debug</code>. I installed a debug plugin, but it runs on the admin bar, which I cannot see, and needs <code>wp_debug</code> to be activated.</p> <p>Any suggestions?</p>
[ { "answer_id": 211813, "author": "Thomas Withers", "author_id": 85307, "author_profile": "https://wordpress.stackexchange.com/users/85307", "pm_score": 0, "selected": false, "text": "<p>well you could probably create a variable at the start of your header.php and assign its value string as your desired path....</p>\n\n<pre><code>&lt;?php $dir = your_path_here ?&gt;\n</code></pre>\n\n<p>theoretically this should work :) best not to change wordpress stuff as it might be used somewhere else</p>\n" }, { "answer_id": 211815, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>If you look at the function <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L319\" rel=\"nofollow\">in source</a>, you'll see the <code>template_directory_uri</code> hook <a href=\"https://codex.wordpress.org/Function_Reference/add_filter\" rel=\"nofollow\">you can filter</a> to modify output.</p>\n\n<pre><code>return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri );\n</code></pre>\n" }, { "answer_id": 329946, "author": "Bradan", "author_id": 162048, "author_profile": "https://wordpress.stackexchange.com/users/162048", "pm_score": 2, "selected": false, "text": "<p>I'd like to contribute a more detailed answer as I found figuring out 'add_filter()' was quite frustrating.</p>\n\n<p>In order to edit the hook for get_template_directory_uri(), you need to add filter as</p>\n\n<pre><code>add_filter('template_directory_uri', 'yourFunction', 10, 2);\n</code></pre>\n\n<p>where function is the function you are calling to edit the string, as such:</p>\n\n<pre><code>function yourFunction($string) {\n //Modify the string here\n return $string;\n}\n</code></pre>\n\n<p>Hope this helps anyone who stumbles across this question in the future!</p>\n" }, { "answer_id": 339351, "author": "zundi", "author_id": 169285, "author_profile": "https://wordpress.stackexchange.com/users/169285", "pm_score": -1, "selected": false, "text": "<p>I was searching for this when doing a migration to a site with another domain name. I fixed this by searching the database. These values are set in the <code>wp_options</code> table of your database. In my case, rows with <code>option_name</code> equal to <code>siteurl</code> and <code>home</code>. I updated the values and everything now works as expected.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211830", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85318/" ]
The admin bar displays on the dashboard, but does not display on pages or posts. I'm working with a child theme of Twenty Thirteen that I did not code. I'm a beginning level coder and work mostly with builders. So the builder plugin I installed is also not showing up either. I've read some potential causes and checked those off. There are things I've tried that did not correct the problem: The display is set correctly in the user settings. I logged out as an admin, logged in as a subscriber and logged back in as an admin. The index.php file contains '' (the code is not displaying, but it is the php call for the footer) The `function.php` file does not have any code pertaining to the admin bar. The `footer.php` file does not have any code pertaining to the admin bar. I do not have access to the client's files on their server, so I cannot use `wp_debug`. I installed a debug plugin, but it runs on the admin bar, which I cannot see, and needs `wp_debug` to be activated. Any suggestions?
If you look at the function [in source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L319), you'll see the `template_directory_uri` hook [you can filter](https://codex.wordpress.org/Function_Reference/add_filter) to modify output. ``` return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri ); ```
211,831
<p>I'm trying to echo the post ID in a post Javascript and not having any luck.</p> <pre><code>var post_id = '123'; // works fine var post_id = '&lt;?php global $post; echo $post-&gt;ID; ?&gt;'; // echos 'ID; ?&gt;' var post_id = '&lt;?php echo $post-&gt;ID;?&gt;'; // echos 'ID; ?&gt;' </code></pre> <p>Is there a correct way to echo the post ID?</p>
[ { "answer_id": 211832, "author": "Fid", "author_id": 43105, "author_profile": "https://wordpress.stackexchange.com/users/43105", "pm_score": 2, "selected": false, "text": "<p>Ok, got it. Maybe this'll help someone. In theme functions.php:</p>\n\n<pre><code>function pid() {\n\nglobal $current_screen;\n$type = $current_screen-&gt;post_type;\n\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var post_id = '&lt;?php global $post; echo $post-&gt;ID; ?&gt;';\n &lt;/script&gt;\n &lt;?php\n\n} \nadd_action('wp_head','pid');\n</code></pre>\n" }, { "answer_id": 211837, "author": "Pabamato", "author_id": 60079, "author_profile": "https://wordpress.stackexchange.com/users/60079", "pm_score": 4, "selected": false, "text": "<p>You can pass variables to javascript using wp_localize_script function:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_localize_script</a></p>\n\n<p>Add the following to functions.php</p>\n\n<pre>if(!function_exists('load_my_script')){\n function load_my_script() {\n global $post;\n $deps = array('jquery');\n $version= '1.0'; \n $in_footer = true;\n wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', $deps, $version, $in_footer);\n wp_localize_script('my-script', 'my_script_vars', array(\n 'postID' => $post->ID\n )\n );\n }\n}\nadd_action('wp_enqueue_scripts', 'load_my_script');\n</pre>\n\n<p>And your js file (theme-name/js/my-script.js):</p>\n\n<pre>\njQuery(document).ready(function($) {\n alert( my_script_vars.postID );\n});\n\n</pre>\n\n<p>Note: </p>\n\n<p>If you are trying to pass integers you will need to call the JavaScript parseInt() function.</p>\n" }, { "answer_id": 270143, "author": "Stranger", "author_id": 109889, "author_profile": "https://wordpress.stackexchange.com/users/109889", "pm_score": 3, "selected": false, "text": "<p>It is available in the <code>post_ID</code> hidden field for both published and new posts. You can get it by using this simple jQuery code.</p>\n\n<pre><code>jQuery(\"#post_ID\").val()\n</code></pre>\n" }, { "answer_id": 346621, "author": "SpritsDracula", "author_id": 44335, "author_profile": "https://wordpress.stackexchange.com/users/44335", "pm_score": 2, "selected": false, "text": "<p>I use this -</p>\n\n<pre><code>document.querySelector('.status-publish').getAttribute('id');\n</code></pre>\n\n<p>This gives you <code>post-xxx</code> where <code>xxx</code> is the post number. You can then replace <code>post-</code> with an empty string.</p>\n\n<pre><code>var id = document.querySelector('.status-publish').getAttribute('id').replace(\"post-\", \"\");\n</code></pre>\n" }, { "answer_id": 359189, "author": "demopix", "author_id": 174561, "author_profile": "https://wordpress.stackexchange.com/users/174561", "pm_score": 1, "selected": false, "text": "<p>to frontend postID = jQuery('article').attr('id').slice(5);</p>\n\n<p>to backend post_ID = jQuery('#post_ID').val();</p>\n" }, { "answer_id": 383634, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 0, "selected": false, "text": "<p>On the post edit screens when Gutenberg is enabled, you may use a JS variable set by the <code>wp.media</code> object.</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.view.settings.post.id,\n</code></pre>\n<p>On the front end, the best approach <a href=\"https://wordpress.stackexchange.com/a/211837/129914\">was already outlined</a> above.</p>\n" }, { "answer_id": 387763, "author": "renWeb", "author_id": 178027, "author_profile": "https://wordpress.stackexchange.com/users/178027", "pm_score": 1, "selected": false, "text": "<p>NB. As of WP 4.5 it is recommended to use wp_add_inline_script(), rather than wp_localize_script() - the later being intended for localization.</p>\n<p>See:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/#more-information\" rel=\"nofollow noreferrer\">wp_localize_script() &gt; More Info</a></p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">wp_add_inline_script()</a></p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43105/" ]
I'm trying to echo the post ID in a post Javascript and not having any luck. ``` var post_id = '123'; // works fine var post_id = '<?php global $post; echo $post->ID; ?>'; // echos 'ID; ?>' var post_id = '<?php echo $post->ID;?>'; // echos 'ID; ?>' ``` Is there a correct way to echo the post ID?
You can pass variables to javascript using wp\_localize\_script function: <https://codex.wordpress.org/Function_Reference/wp_localize_script> Add the following to functions.php ``` if(!function_exists('load_my_script')){ function load_my_script() { global $post; $deps = array('jquery'); $version= '1.0'; $in_footer = true; wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', $deps, $version, $in_footer); wp_localize_script('my-script', 'my_script_vars', array( 'postID' => $post->ID ) ); } } add_action('wp_enqueue_scripts', 'load_my_script'); ``` And your js file (theme-name/js/my-script.js): ``` jQuery(document).ready(function($) { alert( my_script_vars.postID ); }); ``` Note: If you are trying to pass integers you will need to call the JavaScript parseInt() function.
211,833
<p>I decided to organize my work in FTP because I've got over 25 templates by now and the list of files/directories in theme's root is getting really long. </p> <p>I stumbled on <a href="https://developer.wordpress.org/themes/basics/organizing-theme-files/" rel="nofollow">article</a> where I learned that <em>page-templates</em> directory in theme's root is read by default and everything should be fine. </p> <p>I manage all my 3rd party enqueued scripts, css and much more with <code>is_page_template()</code> in order to load them only when needed. </p> <p>Problem is that <code>is_page_template()</code> doesn't read templates now.. <strong>Why?</strong> Do I need to declare or define anything in functions.php or something?</p> <blockquote> <p><strong>Currently:</strong> wp-content/themes/my-theme/page-templates/templates.php</p> <p><strong>Previously:</strong> wp-content/themes/my-theme/templates.php</p> </blockquote>
[ { "answer_id": 211832, "author": "Fid", "author_id": 43105, "author_profile": "https://wordpress.stackexchange.com/users/43105", "pm_score": 2, "selected": false, "text": "<p>Ok, got it. Maybe this'll help someone. In theme functions.php:</p>\n\n<pre><code>function pid() {\n\nglobal $current_screen;\n$type = $current_screen-&gt;post_type;\n\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var post_id = '&lt;?php global $post; echo $post-&gt;ID; ?&gt;';\n &lt;/script&gt;\n &lt;?php\n\n} \nadd_action('wp_head','pid');\n</code></pre>\n" }, { "answer_id": 211837, "author": "Pabamato", "author_id": 60079, "author_profile": "https://wordpress.stackexchange.com/users/60079", "pm_score": 4, "selected": false, "text": "<p>You can pass variables to javascript using wp_localize_script function:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_localize_script</a></p>\n\n<p>Add the following to functions.php</p>\n\n<pre>if(!function_exists('load_my_script')){\n function load_my_script() {\n global $post;\n $deps = array('jquery');\n $version= '1.0'; \n $in_footer = true;\n wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', $deps, $version, $in_footer);\n wp_localize_script('my-script', 'my_script_vars', array(\n 'postID' => $post->ID\n )\n );\n }\n}\nadd_action('wp_enqueue_scripts', 'load_my_script');\n</pre>\n\n<p>And your js file (theme-name/js/my-script.js):</p>\n\n<pre>\njQuery(document).ready(function($) {\n alert( my_script_vars.postID );\n});\n\n</pre>\n\n<p>Note: </p>\n\n<p>If you are trying to pass integers you will need to call the JavaScript parseInt() function.</p>\n" }, { "answer_id": 270143, "author": "Stranger", "author_id": 109889, "author_profile": "https://wordpress.stackexchange.com/users/109889", "pm_score": 3, "selected": false, "text": "<p>It is available in the <code>post_ID</code> hidden field for both published and new posts. You can get it by using this simple jQuery code.</p>\n\n<pre><code>jQuery(\"#post_ID\").val()\n</code></pre>\n" }, { "answer_id": 346621, "author": "SpritsDracula", "author_id": 44335, "author_profile": "https://wordpress.stackexchange.com/users/44335", "pm_score": 2, "selected": false, "text": "<p>I use this -</p>\n\n<pre><code>document.querySelector('.status-publish').getAttribute('id');\n</code></pre>\n\n<p>This gives you <code>post-xxx</code> where <code>xxx</code> is the post number. You can then replace <code>post-</code> with an empty string.</p>\n\n<pre><code>var id = document.querySelector('.status-publish').getAttribute('id').replace(\"post-\", \"\");\n</code></pre>\n" }, { "answer_id": 359189, "author": "demopix", "author_id": 174561, "author_profile": "https://wordpress.stackexchange.com/users/174561", "pm_score": 1, "selected": false, "text": "<p>to frontend postID = jQuery('article').attr('id').slice(5);</p>\n\n<p>to backend post_ID = jQuery('#post_ID').val();</p>\n" }, { "answer_id": 383634, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 0, "selected": false, "text": "<p>On the post edit screens when Gutenberg is enabled, you may use a JS variable set by the <code>wp.media</code> object.</p>\n<pre class=\"lang-js prettyprint-override\"><code>wp.media.view.settings.post.id,\n</code></pre>\n<p>On the front end, the best approach <a href=\"https://wordpress.stackexchange.com/a/211837/129914\">was already outlined</a> above.</p>\n" }, { "answer_id": 387763, "author": "renWeb", "author_id": 178027, "author_profile": "https://wordpress.stackexchange.com/users/178027", "pm_score": 1, "selected": false, "text": "<p>NB. As of WP 4.5 it is recommended to use wp_add_inline_script(), rather than wp_localize_script() - the later being intended for localization.</p>\n<p>See:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/#more-information\" rel=\"nofollow noreferrer\">wp_localize_script() &gt; More Info</a></p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">wp_add_inline_script()</a></p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
I decided to organize my work in FTP because I've got over 25 templates by now and the list of files/directories in theme's root is getting really long. I stumbled on [article](https://developer.wordpress.org/themes/basics/organizing-theme-files/) where I learned that *page-templates* directory in theme's root is read by default and everything should be fine. I manage all my 3rd party enqueued scripts, css and much more with `is_page_template()` in order to load them only when needed. Problem is that `is_page_template()` doesn't read templates now.. **Why?** Do I need to declare or define anything in functions.php or something? > > **Currently:** > wp-content/themes/my-theme/page-templates/templates.php > > > **Previously:** wp-content/themes/my-theme/templates.php > > >
You can pass variables to javascript using wp\_localize\_script function: <https://codex.wordpress.org/Function_Reference/wp_localize_script> Add the following to functions.php ``` if(!function_exists('load_my_script')){ function load_my_script() { global $post; $deps = array('jquery'); $version= '1.0'; $in_footer = true; wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', $deps, $version, $in_footer); wp_localize_script('my-script', 'my_script_vars', array( 'postID' => $post->ID ) ); } } add_action('wp_enqueue_scripts', 'load_my_script'); ``` And your js file (theme-name/js/my-script.js): ``` jQuery(document).ready(function($) { alert( my_script_vars.postID ); }); ``` Note: If you are trying to pass integers you will need to call the JavaScript parseInt() function.
211,861
<p><strong>How to pass the custom field values which were stored while creating a new user into the <code>wp_get_current_user</code> array function</strong></p> <p>When I call the <code>wp_get_current_user()</code> function the result which I found is as follows: </p> <pre><code>WP_User Object ( [data] =&gt; stdClass Object ( [ID] =&gt; 20 [user_login] =&gt; testing [user_pass] =&gt; $P$BAfSwYFZEUKIkQyF30Eq7GN3HOUXFW/ [user_nicename] =&gt; testing [user_email] =&gt; [email protected] [user_url] =&gt; [user_registered] =&gt; 2015-12-15 07:11:35 [user_activation_key] =&gt; 1450163495:$P$Br7QHNREuY.esEZdB3c92fK2CrW9QH. [user_status] =&gt; 0 [display_name] =&gt; testing testing [token_key] =&gt; ) [ID] =&gt; 20 [caps] =&gt; Array ( [subscriber] =&gt; 1 ) [cap_key] =&gt; wp_capabilities [roles] =&gt; Array ( [0] =&gt; subscriber ) [allcaps] =&gt; Array ( [read] =&gt; 1 [level_0] =&gt; 1 [subscriber] =&gt; 1 ) [filter] =&gt; ) </code></pre> <p>But I want the answer to be as </p> <pre><code>WP_User Object ( [data] =&gt; stdClass Object ( [ID] =&gt; 20 [user_login] =&gt; testing [user_pass] =&gt; $P$BAfSwYFZEUKIkQyF30Eq7GN3HOUXFW/ [user_nicename] =&gt; testing [user_email] =&gt; [email protected] [user_url] =&gt; [user_registered] =&gt; 2015-12-15 07:11:35 [user_activation_key] =&gt; 1450163495:$P$Br7QHNREuY.esEZdB3c92fK2CrW9QH. [user_status] =&gt; 0 [display_name] =&gt; testing testing [token_key] =&gt; [client] =&gt; abc [user_groups] =&gt; test ) [ID] =&gt; 20 [caps] =&gt; Array ( [subscriber] =&gt; 1 ) [cap_key] =&gt; wp_capabilities [roles] =&gt; Array ( [0] =&gt; subscriber ) [allcaps] =&gt; Array ( [read] =&gt; 1 [level_0] =&gt; 1 [subscriber] =&gt; 1 ) [filter] =&gt; ) </code></pre> <p>Compare the <strong>[data]</strong> part of both the array</p> <p>How do I achieve this?</p> <p>Thanks for the help in advance</p>
[ { "answer_id": 212006, "author": "1991wp", "author_id": 80381, "author_profile": "https://wordpress.stackexchange.com/users/80381", "pm_score": 0, "selected": false, "text": "<p>I found the answer for my question. No need to pass the values in the array we can call the separate function to get the values of the custom fields based on the current user for e.g. <code>get_user_meta($current-&gt;ID);</code></p>\n" }, { "answer_id": 354746, "author": "Hasan Uj Jaman", "author_id": 179656, "author_profile": "https://wordpress.stackexchange.com/users/179656", "pm_score": 1, "selected": false, "text": "<p>You can simply do this like.</p>\n\n<pre><code>$user = wp_get_current_user();\n$user-&gt;data-&gt;client = $user-&gt;client; // $user-&gt;meta_key\n$user-&gt;data-&gt;user_groups = $user-&gt;user_groups; // $user-&gt;meta_key\n</code></pre>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80381/" ]
**How to pass the custom field values which were stored while creating a new user into the `wp_get_current_user` array function** When I call the `wp_get_current_user()` function the result which I found is as follows: ``` WP_User Object ( [data] => stdClass Object ( [ID] => 20 [user_login] => testing [user_pass] => $P$BAfSwYFZEUKIkQyF30Eq7GN3HOUXFW/ [user_nicename] => testing [user_email] => [email protected] [user_url] => [user_registered] => 2015-12-15 07:11:35 [user_activation_key] => 1450163495:$P$Br7QHNREuY.esEZdB3c92fK2CrW9QH. [user_status] => 0 [display_name] => testing testing [token_key] => ) [ID] => 20 [caps] => Array ( [subscriber] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => subscriber ) [allcaps] => Array ( [read] => 1 [level_0] => 1 [subscriber] => 1 ) [filter] => ) ``` But I want the answer to be as ``` WP_User Object ( [data] => stdClass Object ( [ID] => 20 [user_login] => testing [user_pass] => $P$BAfSwYFZEUKIkQyF30Eq7GN3HOUXFW/ [user_nicename] => testing [user_email] => [email protected] [user_url] => [user_registered] => 2015-12-15 07:11:35 [user_activation_key] => 1450163495:$P$Br7QHNREuY.esEZdB3c92fK2CrW9QH. [user_status] => 0 [display_name] => testing testing [token_key] => [client] => abc [user_groups] => test ) [ID] => 20 [caps] => Array ( [subscriber] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => subscriber ) [allcaps] => Array ( [read] => 1 [level_0] => 1 [subscriber] => 1 ) [filter] => ) ``` Compare the **[data]** part of both the array How do I achieve this? Thanks for the help in advance
You can simply do this like. ``` $user = wp_get_current_user(); $user->data->client = $user->client; // $user->meta_key $user->data->user_groups = $user->user_groups; // $user->meta_key ```
211,876
<p>I once had a Wordpress that completely went broke after just updating Wordpress itself. The theme wasn't compatible yet. Glad I had a back-up, with a loss of 2 weeks of development.. Ever since I'm unsure whether I should update anything.</p> <p>Because of that I would like to have a way of automatic backups of the complete website. I prefer incremental backups, so only the changed files, but complete backups aren't much of a problem either, though. Especially when you can change the frequency on a folder basis.</p> <p>I've got a Synology NAS (<em>preferred store location</em>), but my VPS' contain enough space too.</p> <p><strong>My question</strong> How do I automatically backup my complete Wordpress websites on at least a weekly basis? </p>
[ { "answer_id": 211885, "author": "Clay Hill", "author_id": 83648, "author_profile": "https://wordpress.stackexchange.com/users/83648", "pm_score": 2, "selected": true, "text": "<p>As mentioned you can use a plugin to do this that will make backups\n to a directory or sftp location.</p>\n\n<hr>\n\n<p>I don't really like using a plugin to do this, so I use rsnapshot to backup my MySQL database and specified directories (including wordpress).</p>\n\n<ul>\n<li>Rsnapshot is way to complicated to give you instructions in a post, so I would google Synology NAS Rsnapshot for details about your NAS setup to acheive this.</li>\n<li>I am not sure what OS you are using, but I have tutorial on how to backup my Server to my desktop using Ubuntu on both. This should help get you in the right direction if you want to use Rsnapshot. <a href=\"http://swkstudios.com/tutorials/ubuntu/ubuntu-14-04-rsnapshot/\" rel=\"nofollow\">Here is my guide</a></li>\n<li>You can use a plugin to backup your mysql database or setup <a href=\"https://www.a2hosting.com/kb/developer-corner/mysql/mysql-database-backups-using-cron-jobs\" rel=\"nofollow\">crontab</a>. </li>\n</ul>\n\n<hr>\n\n<p>In order for you to backup your wordpress MySQL database the way I did you must have a <code> .my.conf </code> file under /home/user/ with the username and password of a mysql user that has the following access <code> select, lock tables, show view, trigger, and events </code> (may or may not need trigger/events).</p>\n\n<pre><code>[client]\nuser=username\npassword=\"password\"\n</code></pre>\n\n<hr>\n\n<p>Here is my cron job for my wordpress MySQL Database which runs twice a day (I have a full dump as well):</p>\n\n<pre><code>20 0,12 * * * /home/user/.scripts/mysql/wp.sh\n</code></pre>\n\n<hr>\n\n<p>Here is my script that it calls:</p>\n\n<pre><code>#!/bin/sh\nmysqldump wp | gzip -9 &gt; /home/user/.backups/mysql/wp-$( date '+%Y-%m-%d_%H-%M-%S' \n).sql.gz\n</code></pre>\n\n<hr>\n\n<p>I hope this helps get you in the right direction. Their is probably a better way to backup your MySQL to a file, but I set this up on someone's shared hosting, so I was limited on what I could and could not do. The drawback to dumping MySQL is that it locks the the database while dumping it to a file in order to not corrupt things. This means that your site may be inaccessible for a second or two during this time.</p>\n" }, { "answer_id": 211947, "author": "Christopher Eller", "author_id": 44710, "author_profile": "https://wordpress.stackexchange.com/users/44710", "pm_score": 0, "selected": false, "text": "<p>Some hosting platforms allow one-click full site and database backups at any time. And that one-click backup of the site and database can become a one-click full restore in a minute if an update broke something.</p>\n\n<p>I always do the one click backups before doing ANY updates for plugins, themes, adding functions, new post templates, etc.</p>\n\n<p>Then I do ONE UPDATE AT A TIME. </p>\n\n<p>Then I test the tings that the ONE update would affect on the site.</p>\n\n<p>If everything is looking and working good then you can do the next update (AFTER backing up everything with one click).</p>\n\n<p>Don't bother trying to make a complex Rube Goldberg, incremental backup system when the goal is to back everything up before a change so that the site can be rolled back if there's a failure. A simple one-click full site and database backup is the easy solution.</p>\n\n<p>An alternative to choosing a robust host is to use a service like ManageWP or CMS Commander to create full or partial backups and save them to DropBox, Server, FTP, Amazon, etc (I use both for other things as well).</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211876", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24727/" ]
I once had a Wordpress that completely went broke after just updating Wordpress itself. The theme wasn't compatible yet. Glad I had a back-up, with a loss of 2 weeks of development.. Ever since I'm unsure whether I should update anything. Because of that I would like to have a way of automatic backups of the complete website. I prefer incremental backups, so only the changed files, but complete backups aren't much of a problem either, though. Especially when you can change the frequency on a folder basis. I've got a Synology NAS (*preferred store location*), but my VPS' contain enough space too. **My question** How do I automatically backup my complete Wordpress websites on at least a weekly basis?
As mentioned you can use a plugin to do this that will make backups to a directory or sftp location. --- I don't really like using a plugin to do this, so I use rsnapshot to backup my MySQL database and specified directories (including wordpress). * Rsnapshot is way to complicated to give you instructions in a post, so I would google Synology NAS Rsnapshot for details about your NAS setup to acheive this. * I am not sure what OS you are using, but I have tutorial on how to backup my Server to my desktop using Ubuntu on both. This should help get you in the right direction if you want to use Rsnapshot. [Here is my guide](http://swkstudios.com/tutorials/ubuntu/ubuntu-14-04-rsnapshot/) * You can use a plugin to backup your mysql database or setup [crontab](https://www.a2hosting.com/kb/developer-corner/mysql/mysql-database-backups-using-cron-jobs). --- In order for you to backup your wordpress MySQL database the way I did you must have a `.my.conf` file under /home/user/ with the username and password of a mysql user that has the following access `select, lock tables, show view, trigger, and events` (may or may not need trigger/events). ``` [client] user=username password="password" ``` --- Here is my cron job for my wordpress MySQL Database which runs twice a day (I have a full dump as well): ``` 20 0,12 * * * /home/user/.scripts/mysql/wp.sh ``` --- Here is my script that it calls: ``` #!/bin/sh mysqldump wp | gzip -9 > /home/user/.backups/mysql/wp-$( date '+%Y-%m-%d_%H-%M-%S' ).sql.gz ``` --- I hope this helps get you in the right direction. Their is probably a better way to backup your MySQL to a file, but I set this up on someone's shared hosting, so I was limited on what I could and could not do. The drawback to dumping MySQL is that it locks the the database while dumping it to a file in order to not corrupt things. This means that your site may be inaccessible for a second or two during this time.
211,881
<p>I am using the Theme Customizer to let users customize how their website looks.</p> <p>I noticed on the Twenty Fifteen theme there is a panel for Widgets. I have seen this on quite a few other themes too, and the code for the panel has not been added to <code>customizer.php</code> (as far as I can tell)</p> <p>On my theme, I have a few sidebars on the homepage. You can customize the widgets through <code>Appearance &gt; Widgets</code> menus, however the Widgets panel in the customizer is not displaying.</p> <p>How can I get it to show in the customizer so the user does not have to keep switching out to change the widgets?</p> <p>My code for registering the sidebar:</p> <pre><code>function widgets_init_mysite() { register_sidebar( array( 'name' =&gt; __( 'Main Sidebar', 'mytheme' ), 'id' =&gt; 'sidebar-1', 'before_widget' =&gt; '&lt;div&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); } add_action( 'widgets_init', 'widgets_init_mysite' ); </code></pre> <p>I add the sidebar to the page using <code>dynamic_sidebar( 'sidebar-1' )</code></p> <p>It is definitely displayed because I added widgets through <code>Appearance &gt; Widgets</code> and I can see them in the customizer. </p> <p><strong>Note:</strong> One interesting thing I did find. I registered 5 Sidebars, with IDs of <code>sidebar-1</code>, <code>sidebar-2</code> etc. In Firefix, I went to the theme customizer and Inspect Element. I found the Widgets panel existed, but had <code>display: none</code>. What is more interesting, in the <code>ul</code> sub-navigation, there were 5 <code>li</code> elements with the class <code>section-sidebar-widgets-sidebar-1</code> (the last number changed for all the sidebars).</p> <p>I checked the other sections I had made, and the class always started with <code>section-</code>, and then the section ID. I tried changing the panel of the sidebars to my panel like so:</p> <p><code>$wp_customize-&gt;get_section( 'sidebar-widgets-sidebar-1' )-&gt;panel = 'my-panel';</code></p> <p>But nothing happened. This is weird because I know pretty much definitely know the names of the Sidebar Sections, but changing their panel does nothing...</p>
[ { "answer_id": 211901, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Most likely you are not displaying the sidebar when the costumizer is active which prevents the costumizer from detecting its existence on the page.</p>\n\n<p>The costumizer detects the sidebar by hooking on various sidebar related hooks that are supposed to be triggered when the page is generated. If for some reason your sidebar display code do not trigger the hooks the costumizer will not know it is there even if the actual content is being displayed. This can happen for example if you cache your sidebar and instead of calling <code>dynamic_display</code> you just output the sidebar.</p>\n" }, { "answer_id": 212566, "author": "Jentan Bernardus", "author_id": 34502, "author_profile": "https://wordpress.stackexchange.com/users/34502", "pm_score": 2, "selected": false, "text": "<p>I see you're talking about the <code>dynamic_sidebar</code> function but I don't see you mention the sidebar file (eg. <code>sidebar.php</code> or <code>sidebar-single.php</code>).</p>\n\n<p>There are basically 3 steps I follow to display sidebar widgets and they're always visible in customizer. If yours is not showing up, you probably may have missed something.</p>\n\n<p><strong>1. The register part in functions.php</strong></p>\n\n<hr>\n\n<pre><code>$args = array(\n 'name' =&gt; __( 'Main Sidebar', 'mytheme' ),\n 'id' =&gt; 'sidebar-1',\n 'before_widget' =&gt; '&lt;div id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; '&lt;h3 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h3&gt;'\n);\nregister_sidebar( $args );\n</code></pre>\n\n<p><strong>2. The function call in a sidebar file (eg. <code>sidebar.php</code> or <code>sidebar-single.php</code>)</strong></p>\n\n<hr>\n\n<pre><code>&lt;?php\n// Dynamic Sidebar\nif ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar-1') ) :\n // Sidebar fallback content\n get_sidebar();\nendif;\n// End Dynamic Sidebar Single posts\n?&gt;\n</code></pre>\n\n<p><strong>3. Call the sidebar in the post/page template</strong></p>\n\n<hr>\n\n<p><code>&lt;?php get_sidebar(); ?&gt;</code> or <code>&lt;?php get_sidebar('single'); ?&gt;</code> for <code>sidebar-single.php</code></p>\n\n<p>I would advise you to re-check your code to make sure you haven't left anything out. All the best!</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84836/" ]
I am using the Theme Customizer to let users customize how their website looks. I noticed on the Twenty Fifteen theme there is a panel for Widgets. I have seen this on quite a few other themes too, and the code for the panel has not been added to `customizer.php` (as far as I can tell) On my theme, I have a few sidebars on the homepage. You can customize the widgets through `Appearance > Widgets` menus, however the Widgets panel in the customizer is not displaying. How can I get it to show in the customizer so the user does not have to keep switching out to change the widgets? My code for registering the sidebar: ``` function widgets_init_mysite() { register_sidebar( array( 'name' => __( 'Main Sidebar', 'mytheme' ), 'id' => 'sidebar-1', 'before_widget' => '<div>', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'widgets_init_mysite' ); ``` I add the sidebar to the page using `dynamic_sidebar( 'sidebar-1' )` It is definitely displayed because I added widgets through `Appearance > Widgets` and I can see them in the customizer. **Note:** One interesting thing I did find. I registered 5 Sidebars, with IDs of `sidebar-1`, `sidebar-2` etc. In Firefix, I went to the theme customizer and Inspect Element. I found the Widgets panel existed, but had `display: none`. What is more interesting, in the `ul` sub-navigation, there were 5 `li` elements with the class `section-sidebar-widgets-sidebar-1` (the last number changed for all the sidebars). I checked the other sections I had made, and the class always started with `section-`, and then the section ID. I tried changing the panel of the sidebars to my panel like so: `$wp_customize->get_section( 'sidebar-widgets-sidebar-1' )->panel = 'my-panel';` But nothing happened. This is weird because I know pretty much definitely know the names of the Sidebar Sections, but changing their panel does nothing...
I see you're talking about the `dynamic_sidebar` function but I don't see you mention the sidebar file (eg. `sidebar.php` or `sidebar-single.php`). There are basically 3 steps I follow to display sidebar widgets and they're always visible in customizer. If yours is not showing up, you probably may have missed something. **1. The register part in functions.php** --- ``` $args = array( 'name' => __( 'Main Sidebar', 'mytheme' ), 'id' => 'sidebar-1', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ); register_sidebar( $args ); ``` **2. The function call in a sidebar file (eg. `sidebar.php` or `sidebar-single.php`)** --- ``` <?php // Dynamic Sidebar if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar-1') ) : // Sidebar fallback content get_sidebar(); endif; // End Dynamic Sidebar Single posts ?> ``` **3. Call the sidebar in the post/page template** --- `<?php get_sidebar(); ?>` or `<?php get_sidebar('single'); ?>` for `sidebar-single.php` I would advise you to re-check your code to make sure you haven't left anything out. All the best!
211,889
<p>The homepage on a site we've developed has four pieces of content: the parent page and three further "pages" of text which we bring into the parent page using PHP. Call them Foo, Bar1, Bar2, Bar3 if you like.</p> <p>Maybe this is or isn't the correct way to solve the problem of a complex page but it works for us and for the client and he's used to it now.</p> <p><a href="https://i.stack.imgur.com/e0WmF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e0WmF.png" alt="enter image description here"></a></p> <p>The small problem is that these pseudo-mini-pages Bar1, Bar2 and Bar3 are indexed by Google and can be served as pages in their own right. They don't look terrible when served that way but we'd like to avoid it if possible.</p> <p>I figure I can fix this by:</p> <p>1) redirecting mysite/bar1 to mysite/foo in htaccess<br> OR<br> 2) via our SEO plugin (<a href="https://yoast.com/wordpress/plugins/seo/" rel="nofollow noreferrer">Yoast</a>) apply a robot noindex</p> <p>But I'm asking here which approach is more correct or whether there's a better way?</p>
[ { "answer_id": 211896, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Well those are two different things:</p>\n\n<ol>\n<li><p>A redirect means they are not accessible any more at all.</p></li>\n<li><p>noindex just means that search engines ignore it while it is still accessible if you access the URL.</p></li>\n</ol>\n\n<p>So I'd recommend option 1.\nThis is a simple way of doing this that you can improve an. (E.g. this expects to have a static front page set and doesn't handle any other situation)</p>\n\n<pre><code>function wpse_211889_template_redirect()\n{\n if ( ! is_page() ){\n return;\n }\n\n $frontpage_ID = get_option('page_on_front');\n\n global $post;\n if( $post-&gt;post_parent &amp;&amp; $frontpage_ID === $post-&gt;post_parent )\n {\n wp_redirect( home_url() );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'wpse_211889_template_redirect' );\n</code></pre>\n" }, { "answer_id": 211911, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>The pages should not be indexed if there are no direct links to them. Search engines don't guess at URLs, so I am guessing that a large part of your problem here is with your own code-- that is, you are generating links somewhere that the engines can follow. </p>\n\n<p>If it were me, I'd <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Parameters\" rel=\"nofollow\">create a new post type</a> for this usage and register it with <code>'public'-&gt;false</code> so that the \"pages\" would only be accessible if you explicitly write code to display them. This should avoid issues with such things are generated search results, RSS feeds, and other potential issues as Core code will help to control what is displayed.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/875/" ]
The homepage on a site we've developed has four pieces of content: the parent page and three further "pages" of text which we bring into the parent page using PHP. Call them Foo, Bar1, Bar2, Bar3 if you like. Maybe this is or isn't the correct way to solve the problem of a complex page but it works for us and for the client and he's used to it now. [![enter image description here](https://i.stack.imgur.com/e0WmF.png)](https://i.stack.imgur.com/e0WmF.png) The small problem is that these pseudo-mini-pages Bar1, Bar2 and Bar3 are indexed by Google and can be served as pages in their own right. They don't look terrible when served that way but we'd like to avoid it if possible. I figure I can fix this by: 1) redirecting mysite/bar1 to mysite/foo in htaccess OR 2) via our SEO plugin ([Yoast](https://yoast.com/wordpress/plugins/seo/)) apply a robot noindex But I'm asking here which approach is more correct or whether there's a better way?
Well those are two different things: 1. A redirect means they are not accessible any more at all. 2. noindex just means that search engines ignore it while it is still accessible if you access the URL. So I'd recommend option 1. This is a simple way of doing this that you can improve an. (E.g. this expects to have a static front page set and doesn't handle any other situation) ``` function wpse_211889_template_redirect() { if ( ! is_page() ){ return; } $frontpage_ID = get_option('page_on_front'); global $post; if( $post->post_parent && $frontpage_ID === $post->post_parent ) { wp_redirect( home_url() ); exit(); } } add_action( 'template_redirect', 'wpse_211889_template_redirect' ); ```
211,891
<p>I want to use a shortcode to replace it with an image form a url.</p> <p>My idea:</p> <pre><code>[shortcode url="http://google.de/aImage.jpg"] </code></pre> <p>I post this shortcode usinbg IFTTT. After publishing the article the shortcode should be replaced by the image. But the image should come from my "local" library. So the shortcode should download the image, replace it self with a html tag for the image in the library ... that's it :-D</p> <p>Is it possible to use a shortcode that way? How?</p>
[ { "answer_id": 211896, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Well those are two different things:</p>\n\n<ol>\n<li><p>A redirect means they are not accessible any more at all.</p></li>\n<li><p>noindex just means that search engines ignore it while it is still accessible if you access the URL.</p></li>\n</ol>\n\n<p>So I'd recommend option 1.\nThis is a simple way of doing this that you can improve an. (E.g. this expects to have a static front page set and doesn't handle any other situation)</p>\n\n<pre><code>function wpse_211889_template_redirect()\n{\n if ( ! is_page() ){\n return;\n }\n\n $frontpage_ID = get_option('page_on_front');\n\n global $post;\n if( $post-&gt;post_parent &amp;&amp; $frontpage_ID === $post-&gt;post_parent )\n {\n wp_redirect( home_url() );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'wpse_211889_template_redirect' );\n</code></pre>\n" }, { "answer_id": 211911, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>The pages should not be indexed if there are no direct links to them. Search engines don't guess at URLs, so I am guessing that a large part of your problem here is with your own code-- that is, you are generating links somewhere that the engines can follow. </p>\n\n<p>If it were me, I'd <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Parameters\" rel=\"nofollow\">create a new post type</a> for this usage and register it with <code>'public'-&gt;false</code> so that the \"pages\" would only be accessible if you explicitly write code to display them. This should avoid issues with such things are generated search results, RSS feeds, and other potential issues as Core code will help to control what is displayed.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85306/" ]
I want to use a shortcode to replace it with an image form a url. My idea: ``` [shortcode url="http://google.de/aImage.jpg"] ``` I post this shortcode usinbg IFTTT. After publishing the article the shortcode should be replaced by the image. But the image should come from my "local" library. So the shortcode should download the image, replace it self with a html tag for the image in the library ... that's it :-D Is it possible to use a shortcode that way? How?
Well those are two different things: 1. A redirect means they are not accessible any more at all. 2. noindex just means that search engines ignore it while it is still accessible if you access the URL. So I'd recommend option 1. This is a simple way of doing this that you can improve an. (E.g. this expects to have a static front page set and doesn't handle any other situation) ``` function wpse_211889_template_redirect() { if ( ! is_page() ){ return; } $frontpage_ID = get_option('page_on_front'); global $post; if( $post->post_parent && $frontpage_ID === $post->post_parent ) { wp_redirect( home_url() ); exit(); } } add_action( 'template_redirect', 'wpse_211889_template_redirect' ); ```
211,913
<p>I have a sticky post that gets the image from background URL, but doesn't resize the image and leaves <a href="http://brancadenoiva.com.br/2015/" rel="nofollow">my blog</a> heavy. Here is the code:</p> <pre><code>// is sticky if ( ( is_home() || is_front_page() ) ) { $sticky = get_option( 'sticky_posts' ); $query = new WP_Query( 'p=' . $sticky[0] );; $args = array( 'posts_per_page' =&gt; 1, //get all post 'post__in' =&gt; get_option( 'sticky_posts' ), //are they sticky post 'ignore_sticky_posts'=&gt; 1 ); // The Query $the_query = new WP_Query( $args ); // The Loop // We are only getting a list of the title as a li, see the loop docs for details // on the loop, or copy this from index.php (or posts.php) while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'slide-home' ); ?&gt; &lt;div class="post post-big" style="background:url(&lt;?php echo $image[0]; ?&gt;) no-repeat center; background-size: cover"&gt; &lt;a href="&lt;?php echo get_permalink(); ?&gt;"&gt; &lt;div class="info info-big"&gt; &lt;div class="overlay"&gt;&lt;/div&gt; &lt;h2 class="title-post centered"&gt; &lt;div&gt; &lt;?php foreach( ( get_the_category() ) as $category ) { if ( $category-&gt;category_parent == 0 ) { echo '&lt;i class="icon icon-ico-categoria-' . $category-&gt;cat_ID . '"&gt;&lt;/i&gt;'; } } ?&gt; &lt;/div&gt; &lt;?php the_title(); ?&gt; &lt;/h2&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php } wp_reset_query(); } ?&gt;&lt;/div&gt; </code></pre> <p>How can I get the images regenerated, to set the site lighter?</p>
[ { "answer_id": 211939, "author": "victor", "author_id": 85366, "author_profile": "https://wordpress.stackexchange.com/users/85366", "pm_score": -1, "selected": false, "text": "<p>I've already fixed the problem. Sorry for posting in portuguese.\nI've had some problems with CSS because i needed to put some gradient in the image, but its ok now.</p>\n\n<pre><code> &lt;?php \n //is sticky \n if((is_home() || is_front_page()) ){\n\n $sticky = get_option( 'sticky_posts' );\n $query = new WP_Query( 'p=' . $sticky[0] );;\n $args = array(\n 'posts_per_page' =&gt; 1, //get all post\n 'post__in' =&gt; get_option( 'sticky_posts' ), //are they sticky post\n 'ignore_sticky_posts'=&gt; 1\n );\n\n // The Query\n $the_query = new WP_Query( $args );\n\n // The Loop //we are only getting a list of the title as a li see the loop docs for details on the loop or copy this from index.php (or posts.php)\n\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n\n ?&gt; \n &lt;?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'slide-home' ); ?&gt; \n &lt;div class=\"post post-big\"&gt;\n\n &lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\"&gt;\n &lt;div class=\"info info-big\"&gt;\n &lt;div class=\"behind\"&gt;&lt;/div&gt;\n &lt;div class=\"overlay\"&gt;&lt;/div&gt;\n &lt;div class=\"ahead\"&gt;\n &lt;?php if( has_post_thumbnail() ) {\n if( is_sticky() ) the_post_thumbnail( 'sticky-post-thumbnail' );\n else the_post_thumbnail();\n }?&gt;\n &lt;/div&gt;\n &lt;h2 class=\"title-post centered\"&gt;\n &lt;div&gt;\n &lt;?php\n foreach((get_the_category()) as $category) {\n if ($category-&gt;category_parent == 0) {\n echo '&lt;i class=\"icon icon-ico-categoria-' . $category-&gt;cat_ID . '\"&gt;&lt;/i&gt;';\n }\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/h2&gt;\n\n\n &lt;/div&gt;\n &lt;/a&gt;\n\n &lt;/div&gt;\n &lt;?php\n }\n wp_reset_query();\n }\n ?&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 211950, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>You're going to want to use responsive images in WP 4.4. Not a heck of a lot of documentation out yet but refer to this WP Core article <a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/\" rel=\"nofollow\">Responsive Images in WordPress 4.4</a>.</p>\n\n<p>Here is the example they give.</p>\n\n<pre><code>&lt;?php\n$img_src = wp_get_attachment_image_url( $attachment_id, 'medium' );\n$img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'medium' );\n?&gt;\n&lt;img src=\"&lt;?php echo esc_url( $img_src ); ?&gt;\"\n srcset=\"&lt;?php echo esc_attr( $img_srcset ); ?&gt;\"\n sizes=\"(max-width: 50em) 87vw, 680px\" alt=\"A rad wolf\"&gt;\n</code></pre>\n\n<p>If you go the lazy loading route check out <a href=\"http://afarkas.github.io/lazysizes/#examples\" rel=\"nofollow\">lazySizes</a> - <a href=\"https://github.com/aFarkas/lazysizes/tree/gh-pages/plugins/bgset\" rel=\"nofollow\">bgset plugin</a> / <a href=\"http://jsfiddle.net/trixta/bfqqnosp/embedded/result/\" rel=\"nofollow\">DEMO</a>. That would reduce your code to:</p>\n\n<pre><code>&lt;?php\n $img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'medium' );\n ?&gt;\n&lt;div class=\"lazyload\" data-bgset=\"&lt;?php echo $img_srcset; ?&gt;\" data-sizes=\"auto\"&gt;\n</code></pre>\n\n<p>This method ensures a smaller screen size won't require a full image, thus reducing your page load and site speed.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211913", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85366/" ]
I have a sticky post that gets the image from background URL, but doesn't resize the image and leaves [my blog](http://brancadenoiva.com.br/2015/) heavy. Here is the code: ``` // is sticky if ( ( is_home() || is_front_page() ) ) { $sticky = get_option( 'sticky_posts' ); $query = new WP_Query( 'p=' . $sticky[0] );; $args = array( 'posts_per_page' => 1, //get all post 'post__in' => get_option( 'sticky_posts' ), //are they sticky post 'ignore_sticky_posts'=> 1 ); // The Query $the_query = new WP_Query( $args ); // The Loop // We are only getting a list of the title as a li, see the loop docs for details // on the loop, or copy this from index.php (or posts.php) while ( $the_query->have_posts() ) { $the_query->the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'slide-home' ); ?> <div class="post post-big" style="background:url(<?php echo $image[0]; ?>) no-repeat center; background-size: cover"> <a href="<?php echo get_permalink(); ?>"> <div class="info info-big"> <div class="overlay"></div> <h2 class="title-post centered"> <div> <?php foreach( ( get_the_category() ) as $category ) { if ( $category->category_parent == 0 ) { echo '<i class="icon icon-ico-categoria-' . $category->cat_ID . '"></i>'; } } ?> </div> <?php the_title(); ?> </h2> </div> </a> </div> <?php } wp_reset_query(); } ?></div> ``` How can I get the images regenerated, to set the site lighter?
You're going to want to use responsive images in WP 4.4. Not a heck of a lot of documentation out yet but refer to this WP Core article [Responsive Images in WordPress 4.4](https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/). Here is the example they give. ``` <?php $img_src = wp_get_attachment_image_url( $attachment_id, 'medium' ); $img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'medium' ); ?> <img src="<?php echo esc_url( $img_src ); ?>" srcset="<?php echo esc_attr( $img_srcset ); ?>" sizes="(max-width: 50em) 87vw, 680px" alt="A rad wolf"> ``` If you go the lazy loading route check out [lazySizes](http://afarkas.github.io/lazysizes/#examples) - [bgset plugin](https://github.com/aFarkas/lazysizes/tree/gh-pages/plugins/bgset) / [DEMO](http://jsfiddle.net/trixta/bfqqnosp/embedded/result/). That would reduce your code to: ``` <?php $img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'medium' ); ?> <div class="lazyload" data-bgset="<?php echo $img_srcset; ?>" data-sizes="auto"> ``` This method ensures a smaller screen size won't require a full image, thus reducing your page load and site speed.
211,916
<p>I used this code to get all the products of a specific category, but how can I show only the author's products of a specific category?</p> <pre><code>&lt;div class="author_products"&gt; &lt;ul class="author_pubproducts"&gt; &lt;?php $args = array( 'post_type' =&gt; 'product', 'posts_per_page' =&gt; 12, 'product_cat' =&gt; 'pants' ); $loop = new WP_Query( $args ); if ( $loop-&gt;have_posts() ) { while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); woocommerce_get_template_part( 'content', 'product' ); endwhile; } else { echo __( 'No products found' ); } wp_reset_postdata(); ?&gt; &lt;/ul&gt; &lt;div&gt; </code></pre>
[ { "answer_id": 211918, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">Pass author data to the query</a>. It should be that hard.</p>\n\n<blockquote>\n <p><h3>Author\n Parameters</h3> <p>Show posts associated with certain author.\n </p> <ul> <li> <b>author</b> (<i>int</i>) - use author id.\n </li> <li> <b>author_name</b> (<i>string</i>) - use\n 'user_nicename' - NOT name. </li> <li>\n <b>author__in</b> (<i>array</i>) - use author id (available\n since <a href=\"/Version_3.7\" title=\"Version 3.7\">Version 3.7</a>).\n </li> <li> <b>author__not_in</b> (<i>array</i>) - use author\n id (available since <a href=\"/Version_3.7\" title=\"Version 3.7\">Version\n 3.7</a>). </li> </ul></p>\n</blockquote>\n\n<p>Of course, I don't know what page you are on or how you are determining, or needing to determine, the \"author\" so I'm not quite sure how to guess at the code. </p>\n" }, { "answer_id": 311312, "author": "Andrius Vlasovas", "author_id": 147625, "author_profile": "https://wordpress.stackexchange.com/users/147625", "pm_score": 1, "selected": false, "text": "<p>As @s_ha_dum mentioned, you can just add additional query args parameter.</p>\n\n<p>I assume, you wish to display single author products on the profile page of that author.</p>\n\n<p>To do that, you would modify your code to look something this (which also fixes HTML, since in a case where there are no products, you are echoing text without <li> element within a list):</p>\n\n<pre><code>&lt;?php\n\n$authorID = get_the_author_meta('ID');\n\n$args = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish'\n 'posts_per_page' =&gt; 12,\n 'product_cat' =&gt; 'pants'\n 'author' =&gt; $authorID\n);\n\n$loop = new WP_Query( $args );\n\n?&gt; \n&lt;div class=\"author_products\"&gt;\n &lt;?php if ( $loop-&gt;have_posts() ) { ?&gt;\n &lt;ul class=\"author_pubproducts\"&gt;\n &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n woocommerce_get_template_part( 'content', 'product' );\n endwhile; ?&gt;\n &lt;/ul&gt;\n &lt;?php\n } else {\n echo __( 'No products found', 'mytheme' );\n }\n wp_reset_postdata();\n ?&gt;\n&lt;div&gt;\n</code></pre>\n\n<p>Again, this would work if you are using this piece of code on author page, otherwise you would need to retrieve and assign Author ID to variable $authorID using another method.\nFor example, if you would be using ACF in some way, then it would be:</p>\n\n<pre><code>$authorID = get_field('author_id_field');\n</code></pre>\n\n<p>Hopefully that was helpful and will provide you some ideas.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211916", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85367/" ]
I used this code to get all the products of a specific category, but how can I show only the author's products of a specific category? ``` <div class="author_products"> <ul class="author_pubproducts"> <?php $args = array( 'post_type' => 'product', 'posts_per_page' => 12, 'product_cat' => 'pants' ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); woocommerce_get_template_part( 'content', 'product' ); endwhile; } else { echo __( 'No products found' ); } wp_reset_postdata(); ?> </ul> <div> ```
[Pass author data to the query](https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters). It should be that hard. > > ### Author > Parameters > > Show posts associated with certain author. > > > * **author** (*int*) - use author id. > * **author\_name** (*string*) - use > 'user\_nicename' - NOT name. > * **author\_\_in** (*array*) - use author id (available > since [Version 3.7](/Version_3.7 "Version 3.7")). > * **author\_\_not\_in** (*array*) - use author > id (available since [Version > 3.7](/Version_3.7 "Version 3.7")). > > > > Of course, I don't know what page you are on or how you are determining, or needing to determine, the "author" so I'm not quite sure how to guess at the code.
211,954
<p>I have a new WP install with the <a href="http://themeforest.net/item/jupiter-multipurpose-responsive-theme/5177775" rel="nofollow">Jupiter Theme</a> installed. I have a contact form created in Sharpspring, a CRM that purports to work perfectly with WP, and automatically generates embed codes for plugging into any page. I'm no JS whiz and can't figure out how to get the form to actually embed.</p> <p>I've got a tracking code provided to me form Sharpspring, which I have included in the header file:</p> <pre><code>&lt;script type="text/javascript"&gt; var _ss = _ss || []; _ss.push(['_setDomain', 'domain.com']); _ss.push(['_setAccount', 'TrackingIDHere']); _ss.push(['_trackPageView']); (function() { var ss = document.createElement('script'); ss.type = 'text/javascript'; ss.async = true; ss.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'marketingservices.com/client/ss.js?ver=1.1.1'; var scr = document.getElementsByTagName('script')[0]; scr.parentNode.insertBefore(ss, scr); })(); &lt;/script&gt; </code></pre> <p>Then, I have a couple embed codes for a couple different forms, which look like this:</p> <pre><code>&lt;!-- SharpSpring Form for General Contact Form --&gt; &lt;script type="text/javascript"&gt; var ss_form = {'account': 'AccountID', 'formID': 'FormID'}; ss_form.width = '100%'; ss_form.height = '1000'; ss_form.domain = 'domain.services'; // ss_form.hidden = {'Company': 'Anon'}; // Modify this for sending hidden variables, or overriding values &lt;/script&gt; &lt;script type="text/javascript" src="https://marketing.services/client/form.js?ver=1.1.1"&gt;&lt;/script&gt; </code></pre> <p>How can I embed codes like this directly onto pages so the associated forms display and the submitted information enters directly into Sharpspring, like their pitch promises?</p>
[ { "answer_id": 211918, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">Pass author data to the query</a>. It should be that hard.</p>\n\n<blockquote>\n <p><h3>Author\n Parameters</h3> <p>Show posts associated with certain author.\n </p> <ul> <li> <b>author</b> (<i>int</i>) - use author id.\n </li> <li> <b>author_name</b> (<i>string</i>) - use\n 'user_nicename' - NOT name. </li> <li>\n <b>author__in</b> (<i>array</i>) - use author id (available\n since <a href=\"/Version_3.7\" title=\"Version 3.7\">Version 3.7</a>).\n </li> <li> <b>author__not_in</b> (<i>array</i>) - use author\n id (available since <a href=\"/Version_3.7\" title=\"Version 3.7\">Version\n 3.7</a>). </li> </ul></p>\n</blockquote>\n\n<p>Of course, I don't know what page you are on or how you are determining, or needing to determine, the \"author\" so I'm not quite sure how to guess at the code. </p>\n" }, { "answer_id": 311312, "author": "Andrius Vlasovas", "author_id": 147625, "author_profile": "https://wordpress.stackexchange.com/users/147625", "pm_score": 1, "selected": false, "text": "<p>As @s_ha_dum mentioned, you can just add additional query args parameter.</p>\n\n<p>I assume, you wish to display single author products on the profile page of that author.</p>\n\n<p>To do that, you would modify your code to look something this (which also fixes HTML, since in a case where there are no products, you are echoing text without <li> element within a list):</p>\n\n<pre><code>&lt;?php\n\n$authorID = get_the_author_meta('ID');\n\n$args = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish'\n 'posts_per_page' =&gt; 12,\n 'product_cat' =&gt; 'pants'\n 'author' =&gt; $authorID\n);\n\n$loop = new WP_Query( $args );\n\n?&gt; \n&lt;div class=\"author_products\"&gt;\n &lt;?php if ( $loop-&gt;have_posts() ) { ?&gt;\n &lt;ul class=\"author_pubproducts\"&gt;\n &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n woocommerce_get_template_part( 'content', 'product' );\n endwhile; ?&gt;\n &lt;/ul&gt;\n &lt;?php\n } else {\n echo __( 'No products found', 'mytheme' );\n }\n wp_reset_postdata();\n ?&gt;\n&lt;div&gt;\n</code></pre>\n\n<p>Again, this would work if you are using this piece of code on author page, otherwise you would need to retrieve and assign Author ID to variable $authorID using another method.\nFor example, if you would be using ACF in some way, then it would be:</p>\n\n<pre><code>$authorID = get_field('author_id_field');\n</code></pre>\n\n<p>Hopefully that was helpful and will provide you some ideas.</p>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211954", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85384/" ]
I have a new WP install with the [Jupiter Theme](http://themeforest.net/item/jupiter-multipurpose-responsive-theme/5177775) installed. I have a contact form created in Sharpspring, a CRM that purports to work perfectly with WP, and automatically generates embed codes for plugging into any page. I'm no JS whiz and can't figure out how to get the form to actually embed. I've got a tracking code provided to me form Sharpspring, which I have included in the header file: ``` <script type="text/javascript"> var _ss = _ss || []; _ss.push(['_setDomain', 'domain.com']); _ss.push(['_setAccount', 'TrackingIDHere']); _ss.push(['_trackPageView']); (function() { var ss = document.createElement('script'); ss.type = 'text/javascript'; ss.async = true; ss.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'marketingservices.com/client/ss.js?ver=1.1.1'; var scr = document.getElementsByTagName('script')[0]; scr.parentNode.insertBefore(ss, scr); })(); </script> ``` Then, I have a couple embed codes for a couple different forms, which look like this: ``` <!-- SharpSpring Form for General Contact Form --> <script type="text/javascript"> var ss_form = {'account': 'AccountID', 'formID': 'FormID'}; ss_form.width = '100%'; ss_form.height = '1000'; ss_form.domain = 'domain.services'; // ss_form.hidden = {'Company': 'Anon'}; // Modify this for sending hidden variables, or overriding values </script> <script type="text/javascript" src="https://marketing.services/client/form.js?ver=1.1.1"></script> ``` How can I embed codes like this directly onto pages so the associated forms display and the submitted information enters directly into Sharpspring, like their pitch promises?
[Pass author data to the query](https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters). It should be that hard. > > ### Author > Parameters > > Show posts associated with certain author. > > > * **author** (*int*) - use author id. > * **author\_name** (*string*) - use > 'user\_nicename' - NOT name. > * **author\_\_in** (*array*) - use author id (available > since [Version 3.7](/Version_3.7 "Version 3.7")). > * **author\_\_not\_in** (*array*) - use author > id (available since [Version > 3.7](/Version_3.7 "Version 3.7")). > > > > Of course, I don't know what page you are on or how you are determining, or needing to determine, the "author" so I'm not quite sure how to guess at the code.
211,974
<p>I created an MU Plugin which will only display the posts from certain tags in the loop like this:</p> <pre><code>function custom_tags( $query ) { $query-&gt;set( 'tag', array( 'custom', 'general' ) ); } add_action( 'pre_get_posts', 'custom_tags' ); </code></pre> <p>It works fine when I remove the array and only check for 1 tag, but how do I get it to work with more than 1 tag like I'm trying to above?</p> <p>The Error I'm getting is:</p> <p><code>Warning: strpos() expects parameter 1 to be string, array given in /srv/users/s/wp-includes/query.php on line 1966</code></p> <p><code>Warning: preg_split() expects parameter 2 to be string, array given in /srv/users/s/wp-includes/query.php on line 1967</code></p> <p>Updated Code:</p> <pre><code>$current = substr($_SERVER[HTTP_HOST], 0, -4); function custom_tags( $query ) { $query-&gt;set( 'tag', 'general,{$current}' ); } add_action( 'pre_get_posts', 'custom_tags' ); </code></pre>
[ { "answer_id": 211975, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>As Milo ( and your errors ) point out: you're passing an array where a string is expected. According to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\"nofollow noreferrer\">WP_Query tag parameter</a></p>\n<blockquote>\n<p>Show posts associated with certain tags.</p>\n<ul>\n<li>tag (<strong>string</strong>) - use tag slug.</li>\n</ul>\n</blockquote>\n<p>To get around this you just need to pass a comma separated string:</p>\n<pre><code>function custom_tags( $query ) {\n $query-&gt;set( 'tag', 'custom,general' );\n}\nadd_action( 'pre_get_posts', 'custom_tags' );\n</code></pre>\n" }, { "answer_id": 211984, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>Create a proper <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code></a>, for example:</p>\n\n<pre><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'people',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'bob',\n ),\n),\n</code></pre>\n\n<p>But your code \"update code\" is going to fail for other reasons too. </p>\n\n<ol>\n<li><code>$current</code> is out of scope.</li>\n<li>And your variable won't expand inside single quotes</li>\n</ol>\n\n<p>The bare bones changes you need are:</p>\n\n<pre><code>function custom_tags( $query ) {\n $current = substr($_SERVER[HTTP_HOST], 0, -4);\n $query-&gt;set( 'tag', \"general,{$current}\" );\n}\nadd_action( 'pre_get_posts', 'custom_tags' );\n</code></pre>\n\n<p>But as mentioned, I'd create a proper <code>tax_query</code></p>\n\n<pre><code>function custom_tags( $query ) {\n $current = substr($_SERVER[HTTP_HOST], 0, -4);\n $tax = array(\n array(\n 'taxonomy' =&gt; 'tag',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $current,\n 'operator' =&gt; 'IN' // This is default\n ),\n );\n $query-&gt;set( 'tag', \"general,{$current}\" );\n}\nadd_action( 'pre_get_posts', 'custom_tags' );\n</code></pre>\n\n<p>The operator can be changed to get different behavior:</p>\n\n<blockquote>\n <p><b>operator</b> (<i>string</i>) - Operator to test. Possible\n values are 'IN', 'NOT IN', 'AND', 'EXISTS' and 'NOT EXISTS'. Default\n value is 'IN'. </li></p>\n</blockquote>\n\n<p>And your code is going to run on every query on the site, just about. That is going to <strong><em>alter a lot of things</em></strong>, and will certainly break things. You need to restrict it to only those locations you need it. I don't know exactly where or when this is supposed to run but this should be a start:</p>\n\n<pre><code>function custom_tags( $query ) {\n if (is_admin() \n || $query-&gt;is_main_query()\n ) {\n return;\n }\n $current = substr($_SERVER[HTTP_HOST], 0, -4);\n $tax = array(\n array(\n 'taxonomy' =&gt; 'tag',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $current,\n 'operator' =&gt; 'IN' // This is default\n ),\n );\n $query-&gt;set( 'tag', \"general,{$current}\" );\n}\nadd_action( 'pre_get_posts', 'custom_tags' );\n</code></pre>\n" } ]
2015/12/15
[ "https://wordpress.stackexchange.com/questions/211974", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15330/" ]
I created an MU Plugin which will only display the posts from certain tags in the loop like this: ``` function custom_tags( $query ) { $query->set( 'tag', array( 'custom', 'general' ) ); } add_action( 'pre_get_posts', 'custom_tags' ); ``` It works fine when I remove the array and only check for 1 tag, but how do I get it to work with more than 1 tag like I'm trying to above? The Error I'm getting is: `Warning: strpos() expects parameter 1 to be string, array given in /srv/users/s/wp-includes/query.php on line 1966` `Warning: preg_split() expects parameter 2 to be string, array given in /srv/users/s/wp-includes/query.php on line 1967` Updated Code: ``` $current = substr($_SERVER[HTTP_HOST], 0, -4); function custom_tags( $query ) { $query->set( 'tag', 'general,{$current}' ); } add_action( 'pre_get_posts', 'custom_tags' ); ```
As Milo ( and your errors ) point out: you're passing an array where a string is expected. According to [WP\_Query tag parameter](https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters) > > Show posts associated with certain tags. > > > * tag (**string**) - use tag slug. > > > To get around this you just need to pass a comma separated string: ``` function custom_tags( $query ) { $query->set( 'tag', 'custom,general' ); } add_action( 'pre_get_posts', 'custom_tags' ); ```
212,003
<p>Different pages often need different set of scripts and styles for them.</p> <p>I use functions.php and construction like this to load scripts and styles:</p> <pre><code>function load_assets() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css'); wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js'); } add_action( 'wp_enqueue_scripts', 'load_assets' ); </code></pre> <p>I know I can put some condition here like this:</p> <pre><code>is_page() </code></pre> <p>but is there a better way?</p> <p>Suggestion:</p> <p>Can wp_register_script() be used to target specific pages?</p>
[ { "answer_id": 212004, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 1, "selected": false, "text": "<p>For admin you can do in this way.</p>\n\n<pre><code>function load_assets( $hook ) {\n\n global $post;\n\n if ( $hook == 'post-new.php' || $hook == 'post.php' ) {\n // enqueue here\n }\n}\nadd_action( 'admin_enqueue_scripts', 'load_assets', 10, 1 );\n</code></pre>\n" }, { "answer_id": 212008, "author": "sxalexander", "author_id": 1992, "author_profile": "https://wordpress.stackexchange.com/users/1992", "pm_score": 3, "selected": true, "text": "<p>Yes, you may add <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">conditional tags</a> to the <code>wp_enqueue_scripts</code> action. See the examples below: </p>\n\n<pre><code>function load_assets() {\n wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css');\n\n // loads on any 'page' post type\n if( is_page() ){\n wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js');\n }\n\n // only loads on the page with a slug of 'home'\n if( is_page('home') ){\n wp_enqueue_script('home-js', get_template_directory_uri() . '/js/home.js');\n }\n\n\n}\nadd_action( 'wp_enqueue_scripts', 'load_assets' );\n</code></pre>\n\n<p>For other examples of <code>is_page()</code> usage, see the codex page: \n<a href=\"https://codex.wordpress.org/Function_Reference/is_page\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/is_page</a></p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85230/" ]
Different pages often need different set of scripts and styles for them. I use functions.php and construction like this to load scripts and styles: ``` function load_assets() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css'); wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js'); } add_action( 'wp_enqueue_scripts', 'load_assets' ); ``` I know I can put some condition here like this: ``` is_page() ``` but is there a better way? Suggestion: Can wp\_register\_script() be used to target specific pages?
Yes, you may add [conditional tags](https://codex.wordpress.org/Conditional_Tags) to the `wp_enqueue_scripts` action. See the examples below: ``` function load_assets() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css'); // loads on any 'page' post type if( is_page() ){ wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js'); } // only loads on the page with a slug of 'home' if( is_page('home') ){ wp_enqueue_script('home-js', get_template_directory_uri() . '/js/home.js'); } } add_action( 'wp_enqueue_scripts', 'load_assets' ); ``` For other examples of `is_page()` usage, see the codex page: <https://codex.wordpress.org/Function_Reference/is_page>
212,012
<p>Just a small question. Is there any difference in using</p> <pre><code>&lt;?php the_title() ?&gt; </code></pre> <p>or</p> <pre><code>&lt;?= get_the_title() ?&gt; </code></pre> <p>Yeah, I know somebody can consider using short echo tag a bad practice, I just want to know is there any difference in result of calling these two functions.</p>
[ { "answer_id": 212013, "author": "TommyBs", "author_id": 9278, "author_profile": "https://wordpress.stackexchange.com/users/9278", "pm_score": 2, "selected": false, "text": "<pre><code>the_title()\n</code></pre>\n\n<p>will echo the title for you and can only be used within 'the loop' <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/the_title</a></p>\n\n<pre><code>get_the_title()\n</code></pre>\n\n<p>without the <code>echo</code> or <code>&lt;?=</code> will simply return the title. So you could store it in a variable and manipulate it if you needed to \n<a href=\"https://codex.wordpress.org/Function_Reference/get_the_title\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_title</a></p>\n" }, { "answer_id": 212040, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 5, "selected": true, "text": "<p>The two are not 100% identical, though they are close.</p>\n<ol>\n<li><code>the_title()</code> will <code>echo</code> content <em>by default</em> but the third\nparameter can be used to change that default.</li>\n<li><code>the_title()</code> prepends the optional <code>$before</code> and appends the\noptional <code>$after</code> arguments. If theme or plugin code uses these\narguments the output of the two functions will be different.</li>\n</ol>\n<p>If you <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post-template.php#L32\" rel=\"noreferrer\">take a look at the source</a>, the differences are easy to spot:</p>\n<pre><code>32 /**\n33 * Display or retrieve the current post title with optional content.\n34 *\n35 * @since 0.71\n36 *\n37 * @param string $before Optional. Content to prepend to the title.\n38 * @param string $after Optional. Content to append to the title.\n39 * @param bool $echo Optional, default to true.Whether to display or return.\n40 * @return string|void String if $echo parameter is false.\n41 */\n42 function the_title( $before = '', $after = '', $echo = true ) {\n43 $title = get_the_title();\n44 \n45 if ( strlen($title) == 0 )\n46 return;\n47 \n48 $title = $before . $title . $after;\n49 \n50 if ( $echo )\n51 echo $title;\n52 else\n53 return $title;\n54 }\n</code></pre>\n<p>You can see that <code>the_title()</code> pulls data using <code>get_the_title()</code> on its first line, so at that point the two are the same. But <code>the_title()</code> then does additional manipulation, potentially.</p>\n<p>The same is true of some of the other &quot;echo&quot;/&quot;not echo&quot; functions such as <code>the_content()</code> and <code>get_the_content()</code>. While close, they are not exactly the same.</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85230/" ]
Just a small question. Is there any difference in using ``` <?php the_title() ?> ``` or ``` <?= get_the_title() ?> ``` Yeah, I know somebody can consider using short echo tag a bad practice, I just want to know is there any difference in result of calling these two functions.
The two are not 100% identical, though they are close. 1. `the_title()` will `echo` content *by default* but the third parameter can be used to change that default. 2. `the_title()` prepends the optional `$before` and appends the optional `$after` arguments. If theme or plugin code uses these arguments the output of the two functions will be different. If you [take a look at the source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post-template.php#L32), the differences are easy to spot: ``` 32 /** 33 * Display or retrieve the current post title with optional content. 34 * 35 * @since 0.71 36 * 37 * @param string $before Optional. Content to prepend to the title. 38 * @param string $after Optional. Content to append to the title. 39 * @param bool $echo Optional, default to true.Whether to display or return. 40 * @return string|void String if $echo parameter is false. 41 */ 42 function the_title( $before = '', $after = '', $echo = true ) { 43 $title = get_the_title(); 44 45 if ( strlen($title) == 0 ) 46 return; 47 48 $title = $before . $title . $after; 49 50 if ( $echo ) 51 echo $title; 52 else 53 return $title; 54 } ``` You can see that `the_title()` pulls data using `get_the_title()` on its first line, so at that point the two are the same. But `the_title()` then does additional manipulation, potentially. The same is true of some of the other "echo"/"not echo" functions such as `the_content()` and `get_the_content()`. While close, they are not exactly the same.
212,026
<p>I have large number of images in media library so I am accessing images in chunks via pagination in my Ruby on Rails application. I pass page number and offset to <code>wp.getMediaLibrary</code> API and it returns fixed number of images. So counting returned images is useless.</p> <p>Here is my approach to get total number of images.</p> <p>If we call <code>wp.getMediaLibrary</code> without passing <code>number</code> and <code>offset</code>, it will return all images and we can get count of images from results. </p> <p>But the problem with this approach is that the site has huge number of images and so something goes wrong at server end and API return empty response.</p> <p>Can anybody please guide me how to get count of images without getting all images information?</p>
[ { "answer_id": 212061, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p><strong>VERSION 1</strong> will query all the images and give you a count by checking the size of the returned array. <strong>VERSION 2</strong> is a much faster method introduced by <a href=\"https://wordpress.stackexchange.com/users/26350/birgire\">birgire</a>. </p>\n\n<pre><code>// VERSION 1\n\n $images = get_posts(array(\n 'post_type' =&gt; 'attachment',\n 'post_status' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'fields' =&gt; 'ids',\n 'post_mime_type' =&gt; 'image/jpeg,image/gif,image/jpg,image/png',\n ));\n\n echo count($images) . ' images total';\n\n// VERSION 2\n\n $count = array_sum( (array) wp_count_attachments( 'image' ) );\n\n echo \"{$count} images total\";\n</code></pre>\n\n<hr>\n\n<p><strong>ORIGINAL</strong> - For a full <a href=\"https://codex.wordpress.org/XML-RPC_WordPress_API\" rel=\"nofollow noreferrer\">XML-RPC</a> solution, create a custom method.</p>\n\n<pre><code>function xml_add_method( $methods ) {\n $methods['myNamespace.attachmentCount'] = 'get_attachment_count';\n return $methods;\n}\nadd_filter( 'xmlrpc_methods', 'xml_add_method' );\n\nfunction get_attachment_count( $args ) {\n // good to know it's here\n // global $wpdb; \n\n // params passed in the call - not needed in this example\n $params = $args[3];\n\n // count the posts then return the total value\n $images = get_posts(array(\n 'post_type' =&gt; 'attachment',\n 'post_status' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'fields' =&gt; 'ids',\n 'post_mime_type' =&gt; 'image/jpeg,image/gif,image/jpg,image/png',\n ));\n\n // images total\n return count($images); \n}\n</code></pre>\n\n<p>Then do the RPC</p>\n\n<pre><code>global $current_user;\n\n$user = $current_user-&gt;user_login;\n$password = $user-&gt;data-&gt;user_pass;\n\ninclude_once( ABSPATH . WPINC . '/class-IXR.php' );\ninclude_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );\n$xmlrpc_url = home_url('xmlrpc.php');\n$client = new WP_HTTP_IXR_CLIENT( $xmlrpc_url );\n\n// set this to true if you need help\n// $client-&gt;debug = true;\n\n$response = $client-&gt;query( 'myNamespace.attachmentCount', array(\n 0,\n $user,\n $password,\n array(\n 'post_type' =&gt; 'attachment',\n 'post_status' =&gt; 'any',\n )\n) );\n\nif ( is_wp_error( $response ) ) {\n $error_message = $response-&gt;get_error_message();\n echo \"Something went wrong: $error_message\";\n} else {\n echo 'Response:&lt;pre&gt;'; \n $count = $client-&gt;message-&gt;params[0]; // our return value is here\n print_r( $count . ' images total' );\n echo '&lt;/pre&gt;';\n}\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong> \nMerging <a href=\"https://wordpress.stackexchange.com/users/26350/birgire\">@birgire's</a> solution into this one.</p>\n\n<hr>\n\n<pre><code>add_filter('xmlrpc_methods', function ($methods) {\n $methods['myNamespace.getTotalImageCount'] = 'rpc_myNamespace_getTotalImageCount';\n return $methods;\n});\n\nfunction rpc_myNamespace_getTotalImageCount($args)\n{\n return array_sum((array)wp_count_attachments('image'));\n}\n\nadd_action('parse_request', function () {\n\n // PULL USER CREDS FROM CURRENT USER\n global $current_user;\n\n $user = $current_user-&gt;user_login;\n $password = $user-&gt;data-&gt;user_pass;\n\n include_once(ABSPATH . WPINC . '/class-IXR.php');\n include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');\n $xmlrpc_url = home_url('xmlrpc.php');\n $client = new WP_HTTP_IXR_CLIENT($xmlrpc_url);\n\n // CALL OUR CUSTOM METHOD\n $response = $client-&gt;query('myNamespace.getTotalImageCount', array(0, $user, $password));\n\n echo 'Response:&lt;pre&gt;';\n $count = $client-&gt;message-&gt;params[0];\n print_r(\"{$count} total images\");\n echo '&lt;/pre&gt;';\n\n wp_die('FIN');\n});\n</code></pre>\n" }, { "answer_id": 212314, "author": "Viren Dave", "author_id": 85563, "author_profile": "https://wordpress.stackexchange.com/users/85563", "pm_score": -1, "selected": false, "text": "<p>I don't think WordPress has any functions to return just the count of images from Media Library.</p>\n\n<p>I'm not familiar with XML RPC, but based on <a href=\"https://kovshenin.com/2010/custom-xml-rpc-methods-in-wordpress\" rel=\"nofollow\">this post</a> and <a href=\"https://josephscott.org/archives/2008/11/adding-xml-rpc-methods-to-wordpress/\" rel=\"nofollow\">this post</a>, I think you can add custom methods.</p>\n\n<p>If it works for you, then you can use the below query to get a count of images from Media Library:</p>\n\n<pre><code>global $wpdb;\n\n$wpquery = $wpdb-&gt;get_results(\n \"SELECT COUNT(*) FROM wp_posts WHERE post_type ='attachment' AND post_status = 'inherit'\"\n);\n$count = mysql_fetch_array( $wpquery );\n\n$wpdb-&gt;get_results( \n \"SELECT * FROM wp_posts WHERE post_type ='attachment' AND post_status = 'inherit'\" \n);\n$count = $wpdb-&gt;num_rows;\n</code></pre>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84678/" ]
I have large number of images in media library so I am accessing images in chunks via pagination in my Ruby on Rails application. I pass page number and offset to `wp.getMediaLibrary` API and it returns fixed number of images. So counting returned images is useless. Here is my approach to get total number of images. If we call `wp.getMediaLibrary` without passing `number` and `offset`, it will return all images and we can get count of images from results. But the problem with this approach is that the site has huge number of images and so something goes wrong at server end and API return empty response. Can anybody please guide me how to get count of images without getting all images information?
**VERSION 1** will query all the images and give you a count by checking the size of the returned array. **VERSION 2** is a much faster method introduced by [birgire](https://wordpress.stackexchange.com/users/26350/birgire). ``` // VERSION 1 $images = get_posts(array( 'post_type' => 'attachment', 'post_status' => 'any', 'numberposts' => -1, 'fields' => 'ids', 'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png', )); echo count($images) . ' images total'; // VERSION 2 $count = array_sum( (array) wp_count_attachments( 'image' ) ); echo "{$count} images total"; ``` --- **ORIGINAL** - For a full [XML-RPC](https://codex.wordpress.org/XML-RPC_WordPress_API) solution, create a custom method. ``` function xml_add_method( $methods ) { $methods['myNamespace.attachmentCount'] = 'get_attachment_count'; return $methods; } add_filter( 'xmlrpc_methods', 'xml_add_method' ); function get_attachment_count( $args ) { // good to know it's here // global $wpdb; // params passed in the call - not needed in this example $params = $args[3]; // count the posts then return the total value $images = get_posts(array( 'post_type' => 'attachment', 'post_status' => 'any', 'numberposts' => -1, 'fields' => 'ids', 'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png', )); // images total return count($images); } ``` Then do the RPC ``` global $current_user; $user = $current_user->user_login; $password = $user->data->user_pass; include_once( ABSPATH . WPINC . '/class-IXR.php' ); include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' ); $xmlrpc_url = home_url('xmlrpc.php'); $client = new WP_HTTP_IXR_CLIENT( $xmlrpc_url ); // set this to true if you need help // $client->debug = true; $response = $client->query( 'myNamespace.attachmentCount', array( 0, $user, $password, array( 'post_type' => 'attachment', 'post_status' => 'any', ) ) ); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); echo "Something went wrong: $error_message"; } else { echo 'Response:<pre>'; $count = $client->message->params[0]; // our return value is here print_r( $count . ' images total' ); echo '</pre>'; } ``` --- **UPDATE** Merging [@birgire's](https://wordpress.stackexchange.com/users/26350/birgire) solution into this one. --- ``` add_filter('xmlrpc_methods', function ($methods) { $methods['myNamespace.getTotalImageCount'] = 'rpc_myNamespace_getTotalImageCount'; return $methods; }); function rpc_myNamespace_getTotalImageCount($args) { return array_sum((array)wp_count_attachments('image')); } add_action('parse_request', function () { // PULL USER CREDS FROM CURRENT USER global $current_user; $user = $current_user->user_login; $password = $user->data->user_pass; include_once(ABSPATH . WPINC . '/class-IXR.php'); include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php'); $xmlrpc_url = home_url('xmlrpc.php'); $client = new WP_HTTP_IXR_CLIENT($xmlrpc_url); // CALL OUR CUSTOM METHOD $response = $client->query('myNamespace.getTotalImageCount', array(0, $user, $password)); echo 'Response:<pre>'; $count = $client->message->params[0]; print_r("{$count} total images"); echo '</pre>'; wp_die('FIN'); }); ```
212,030
<p>Updating my WordPress to 4.4 I have that error: </p> <blockquote> <p>Fatal error: Class 'WP_Rewrite' not found</p> </blockquote> <p>The page who have the error is my custom ajax with the following code:</p> <pre><code>&lt;?php // Constantes propias para ajax define("SHORTINIT",true); define('WP_USE_THEMES', false); define('WP_ALLOW_MULTISITE', false); if (!defined("AUTH_COOKIE")){ define("AUTH_COOKIE",false); } if (!defined("LOGGED_IN_COOKIE")){ define("LOGGED_IN_COOKIE",false); } require_once ("../../../../wp-load.php"); //Loading code from wp-settings after SHORTINIT require( ABSPATH . WPINC . '/l10n.php' ); require( ABSPATH . WPINC . '/formatting.php' ); require( ABSPATH . WPINC . '/capabilities.php' ); require( ABSPATH . WPINC . '/query.php' ); require( ABSPATH . WPINC . '/user.php' ); require( ABSPATH . WPINC . '/meta.php' ); require( ABSPATH . WPINC . '/general-template.php' ); require( ABSPATH . WPINC . '/link-template.php' ); require( ABSPATH . WPINC . '/post.php' ); require( ABSPATH . WPINC . '/comment.php' ); require( ABSPATH . WPINC . '/rewrite.php' ); require( ABSPATH . WPINC . '/script-loader.php' ); require( ABSPATH . WPINC . '/taxonomy.php' ); require( ABSPATH . WPINC . '/theme.php' ); require( ABSPATH . WPINC . '/class-wp-walker.php' ); require( ABSPATH . WPINC . '/post-template.php' ); require( ABSPATH . WPINC . '/post-thumbnail-template.php' ); require( ABSPATH . WPINC . '/shortcodes.php' ); require( ABSPATH . WPINC . '/media.php' ); create_initial_taxonomies(); create_initial_post_types(); require( ABSPATH . WPINC . '/pluggable.php' ); wp_set_internal_encoding(); wp_functionality_constants( ); $GLOBALS['wp_the_query'] = new WP_Query(); $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; $GLOBALS['wp_rewrite'] = new WP_Rewrite(); $GLOBALS['wp'] = new WP(); $GLOBALS['wp']-&gt;init(); wp(); if (!defined("WP_CONTENT_URL")){ define("WP_CONTENT_URL",get_option('siteurl').'/wp-content'); } require_once ('ajax-funciones.php'); // There I have some acctions die(); ?&gt; </code></pre> <p>Before update Wordpress that works but now, I have the error with WP_Rewrite(). That class is in the file rewrite.php if you looking for in the codex and that is include.</p> <p>What can be the problem?</p>
[ { "answer_id": 212039, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>The <code>WP_Rewrite</code> class definition has been moved to it's own file:</p>\n\n<pre><code>/wp-includes/class-wp-rewrite.php\n</code></pre>\n\n<p>This is how it's included within the <code>wp-settings.php</code> file:</p>\n\n<pre><code>require( ABSPATH . WPINC . '/class-wp-rewrite.php' );\n</code></pre>\n\n<p>... but I'm a little bit scared of your setup and wonder why you need to do it this way, rather than using more native ways to get data from a WordPress site.</p>\n" }, { "answer_id": 212046, "author": "Marcos", "author_id": 60178, "author_profile": "https://wordpress.stackexchange.com/users/60178", "pm_score": 2, "selected": false, "text": "<p>I can fixed the problem including this files:</p>\n\n<pre><code>require( ABSPATH . WPINC . '/class-wp-rewrite.php' );\nrequire( ABSPATH . WPINC . '/class-wp-user.php' );\nrequire( ABSPATH . WPINC . '/class-wp-tax-query.php' );\nrequire( ABSPATH . WPINC . '/class-wp-meta-query.php' );\nrequire( ABSPATH . WPINC . '/class-wp-term.php' );\nrequire( ABSPATH . WPINC . '/class-wp-post.php' );\nrequire( ABSPATH . WPINC . '/class-wp-roles.php' );\nrequire( ABSPATH . WPINC . '/class-wp-role.php' );\n</code></pre>\n\n<p>Following the errors in the code and looking for in the wordpress codex.</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60178/" ]
Updating my WordPress to 4.4 I have that error: > > Fatal error: Class 'WP\_Rewrite' not found > > > The page who have the error is my custom ajax with the following code: ``` <?php // Constantes propias para ajax define("SHORTINIT",true); define('WP_USE_THEMES', false); define('WP_ALLOW_MULTISITE', false); if (!defined("AUTH_COOKIE")){ define("AUTH_COOKIE",false); } if (!defined("LOGGED_IN_COOKIE")){ define("LOGGED_IN_COOKIE",false); } require_once ("../../../../wp-load.php"); //Loading code from wp-settings after SHORTINIT require( ABSPATH . WPINC . '/l10n.php' ); require( ABSPATH . WPINC . '/formatting.php' ); require( ABSPATH . WPINC . '/capabilities.php' ); require( ABSPATH . WPINC . '/query.php' ); require( ABSPATH . WPINC . '/user.php' ); require( ABSPATH . WPINC . '/meta.php' ); require( ABSPATH . WPINC . '/general-template.php' ); require( ABSPATH . WPINC . '/link-template.php' ); require( ABSPATH . WPINC . '/post.php' ); require( ABSPATH . WPINC . '/comment.php' ); require( ABSPATH . WPINC . '/rewrite.php' ); require( ABSPATH . WPINC . '/script-loader.php' ); require( ABSPATH . WPINC . '/taxonomy.php' ); require( ABSPATH . WPINC . '/theme.php' ); require( ABSPATH . WPINC . '/class-wp-walker.php' ); require( ABSPATH . WPINC . '/post-template.php' ); require( ABSPATH . WPINC . '/post-thumbnail-template.php' ); require( ABSPATH . WPINC . '/shortcodes.php' ); require( ABSPATH . WPINC . '/media.php' ); create_initial_taxonomies(); create_initial_post_types(); require( ABSPATH . WPINC . '/pluggable.php' ); wp_set_internal_encoding(); wp_functionality_constants( ); $GLOBALS['wp_the_query'] = new WP_Query(); $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; $GLOBALS['wp_rewrite'] = new WP_Rewrite(); $GLOBALS['wp'] = new WP(); $GLOBALS['wp']->init(); wp(); if (!defined("WP_CONTENT_URL")){ define("WP_CONTENT_URL",get_option('siteurl').'/wp-content'); } require_once ('ajax-funciones.php'); // There I have some acctions die(); ?> ``` Before update Wordpress that works but now, I have the error with WP\_Rewrite(). That class is in the file rewrite.php if you looking for in the codex and that is include. What can be the problem?
I can fixed the problem including this files: ``` require( ABSPATH . WPINC . '/class-wp-rewrite.php' ); require( ABSPATH . WPINC . '/class-wp-user.php' ); require( ABSPATH . WPINC . '/class-wp-tax-query.php' ); require( ABSPATH . WPINC . '/class-wp-meta-query.php' ); require( ABSPATH . WPINC . '/class-wp-term.php' ); require( ABSPATH . WPINC . '/class-wp-post.php' ); require( ABSPATH . WPINC . '/class-wp-roles.php' ); require( ABSPATH . WPINC . '/class-wp-role.php' ); ``` Following the errors in the code and looking for in the wordpress codex.
212,054
<p>I have a site with 900+ posts, each with about 3-5 categories. I would like to copy each of the categories to be a tag and am looking for the SQL code to do just that. I do not want to delete or overwrite the categories. (I assume that's the best thing to do for SEO purposes?)</p> <p>I am having a hard time figuring out exactly what needs to be INSERTed. </p> <p>What I have so far... It's the comments at the end I need help with.</p> <pre><code>global $wpdb; $query = " SELECT $wpdb-&gt;posts.ID, $wpdb-&gt;term_relationships.object_id, $wpdb-&gt;term_relationships.term_taxonomy_id, $wpdb-&gt;term_taxonomy.term_taxonomy_id, $wpdb-&gt;terms.term_id, $wpdb-&gt;terms.name, $wpdb-&gt;terms.slug FROM $wpdb-&gt;posts LEFT JOIN $wpdb-&gt;term_relationships ON ($wpdb_posts.ID = $wpdb-&gt;term_relationships.object_id) LEFT JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id) LEFT JOIN $wpdb-&gt;terms ON ($wpdb-&gt;term_taxonomy.term_taxonomy_id = $wpdb-&gt;terms.term_id) WHERE $wpdb-&gt;posts.post_status = 'publish' AND $wpdb-&gt;posts.post_type = 'post' AND $wpdb-&gt;term_taxonomy.taxonomy = 'category' AND $wpdb-&gt;terms.name NOT LIKE '*%' ORDER BY post_date DESC "; $results = $wpdb-&gt;get_results($query); $insert = ""; $wpdb-&gt;query($insert); -- Next steps: -- LOOP? { -- INSERT INTO $wpdb-&gt;terms (name, slug) -- VALUES (terms.name, terms.slug) -- } -- SELECT new term_id's for the above inserted names and slugs -- LOOP? { -- INSERT INTO $wpdb-&gt;term_taxonomy (term_id, taxonomy) -- VALUES (terms.term_id, post_tag) -- } -- SELECT new term_taxonomy_id's for the above inserted term_id's -- LOOP? { -- INSERT INTO $wpdb-&gt;term_relationships (term_taxonomy_id, object_id) -- VALUES (term_taxonomy.term_taxonomy_id, post_id) -- } </code></pre>
[ { "answer_id": 212062, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 1, "selected": false, "text": "<p>You requested SQL solution but SQL is not (yet) my speciality but I might still help you. SQL also seems pointless in your case because WordPress provides all nessecary tools to achieve this.</p>\n\n<p>I don't recommend to run this more than once if you remove comments from the end of code. You'll understand when you'll get there.</p>\n\n<p>This code \"copies\" all the categories of all your posts and saves them as tags. It doesn't delete categories and it also doesn't set new tags to posts. If you also want to set tags to posts, let me know.</p>\n\n<p><strong>PS! It only works correctly if categories are not hierarchical aka without parents!</strong></p>\n\n<p>Please let me know if there are any problems. This code should not do any harm as far as you don't remove comments from the end of the code.</p>\n\n<hr>\n\n<pre><code>&lt;?php\nglobal $post;\n\n//Get ALL the posts with query\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'any' //Change to 'publish', 'draft' or 'pending' if you don't want to get ALL post STATUSES\n );\n\n$post_query = new WP_Query( $args );\n\n//Declare new array of our categories which eventually become tags\n$new_tags = array();\n\nwhile ($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n\n //Get all the categories names of the post and save as an array variable\n $post_categories = wp_get_post_categories($post-&gt;ID, array('fields' =&gt; 'names') );\n\n //Loop through all categories\n foreach ( $post_categories as $category ) {\n\n //Check if category is already in array\n if ( ! in_array($category , $new_tags ) ) {\n\n //Push category to array if it isn't in array yet\n array_push( $new_tags, $category );\n }\n }\n\nendwhile;\nwp_reset_postdata();\n\n//VERY IMPORTANT - test first without making new tags and check if everything seems to be correct \n//PS! Compare the count of items in array (starts with 0 - it's 1 less because of that) with category count in WP admin area\nprint_r($new_tags);\n\n\n//Add new tags programmatically - don't do it if you're sure that array is correct!!\n/*\nforeach ( $new_tags as $tag ) {\n wp_insert_term( $tag, 'post_tag' );\n} \n*/\n?&gt;\n</code></pre>\n" }, { "answer_id": 212084, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>As I said, we would rather use native functions here, which is safer and already does all the hard work for you. We need to be very careful here as this is a very expensive operation to run. Not doing this correctly can crash your site due to timing out</p>\n\n<p>Your worksflow is also wrong here. I would first create all the tags, and after that, insert the tags into the posts. You are trying to do all at once. </p>\n\n<p>Lets us first grab all the categories and use that info to create tags. Just note:</p>\n\n<ul>\n<li><p><code>post_tag</code> being a non hierarchical taxonomy cannot have any duplicate names, hierarchical taxonomies like <code>category</code> can have duplicate term names within different hierarchies. If you have categories with same names, you will get a <code>WP_Error</code> object back if you are going to try to insert tags with duplicate names. To avoid that, we will simply check if a tag exists before we try to insert it</p></li>\n<li><p>Tags cannot have parent/child relationships, categories can. So when we duplicate a category to be a term, we should set all parents explicitly to <code>0</code></p></li>\n</ul>\n\n<p>Here is the code: (<strong><em>NOTE</strong>: We would require PHP 5.4+</em>)</p>\n\n<pre><code>// Lets create our tags. We will use wp_insert_term hooked to init\nadd_action( 'init', function ()\n{\n // Get all categories\n $categories = get_categories( ['hide_empty' =&gt; 0] );\n\n // Probably totally unnecessary, but check for empty $categories\n if ( !$categories )\n return;\n\n // Loop through the categories and create our tags\n foreach ( $categories as $category ) {\n // First make sure that there is no tag that exist with the same name\n if ( term_exists( $category-&gt;name, 'post_tag' ) )\n continue;\n\n // Set our arguments for our terms from $category\n $args = [\n 'description' =&gt; $category-&gt;description,\n 'parent' =&gt; 0, // We can drop this, default is 0\n 'slug' =&gt; $category-&gt;slug,\n ];\n wp_insert_term( $category-&gt;name, 'post_tag', $args );\n } //endforeach\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>You should now see these tags in your <em>Tag</em> admin page. You can also remove the code as it is no more necessary.</p>\n\n<p>Now that we have our tags created, we need to add them to our posts. Here we would need to be careful as you are talking about 900+ posts, so we do not want to break the bank. </p>\n\n<p>What we will do is, we will query all of those posts, but only the post ID's which saves a lot on resources. Also, we will use <code>get_the_category</code> which are cached, so it does not require extra db calls, <code>wp_get_post_categories</code> are not cached, so it is really expensive</p>\n\n<p>Due to <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_terms\" rel=\"noreferrer\"><code>wp_set_post_terms</code></a> being expensive, you would maybe need to split the following into a couple of queries, but I believe one query should be enough</p>\n\n<p>Lets attach the tags to our posts</p>\n\n<pre><code>add_action( 'template_redirect', function ()\n{\n // Get all our posts\n $args = [\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids', // Make the query lean\n // Add any additional query args here\n ];\n $q = new WP_Query( $args );\n\n if ( !$q-&gt;have_posts() )\n return;\n\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n // Get all the categories attached to the post\n $categories = get_the_category();\n if ( !$categories )\n continue;\n\n // Get the names from the categories into an array\n $names = wp_list_pluck( $categories, 'name' );\n // Loop through the names and make sure that the post does not already has the tag attached\n foreach ( $names as $key=&gt;$name ) {\n if ( has_tag( $name ) )\n unset ( $names[$key] );\n }\n // Make sure we still have a valid $names array\n if ( !$names )\n continue; \n\n // Finally, attach our tags to the posts\n wp_set_post_terms( \n get_the_ID(), // Post ID \n $names, // Array of tag names to attach\n 'post_tag',\n true // Only add the tags, do not override\n );\n }\n wp_reset_postdata();\n});\n</code></pre>\n\n<p>Your posts should now have tags attached to them matching the categories. You can also now remove the function as we are done</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85438/" ]
I have a site with 900+ posts, each with about 3-5 categories. I would like to copy each of the categories to be a tag and am looking for the SQL code to do just that. I do not want to delete or overwrite the categories. (I assume that's the best thing to do for SEO purposes?) I am having a hard time figuring out exactly what needs to be INSERTed. What I have so far... It's the comments at the end I need help with. ``` global $wpdb; $query = " SELECT $wpdb->posts.ID, $wpdb->term_relationships.object_id, $wpdb->term_relationships.term_taxonomy_id, $wpdb->term_taxonomy.term_taxonomy_id, $wpdb->terms.term_id, $wpdb->terms.name, $wpdb->terms.slug FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships ON ($wpdb_posts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) LEFT JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_taxonomy_id = $wpdb->terms.term_id) WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->terms.name NOT LIKE '*%' ORDER BY post_date DESC "; $results = $wpdb->get_results($query); $insert = ""; $wpdb->query($insert); -- Next steps: -- LOOP? { -- INSERT INTO $wpdb->terms (name, slug) -- VALUES (terms.name, terms.slug) -- } -- SELECT new term_id's for the above inserted names and slugs -- LOOP? { -- INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy) -- VALUES (terms.term_id, post_tag) -- } -- SELECT new term_taxonomy_id's for the above inserted term_id's -- LOOP? { -- INSERT INTO $wpdb->term_relationships (term_taxonomy_id, object_id) -- VALUES (term_taxonomy.term_taxonomy_id, post_id) -- } ```
As I said, we would rather use native functions here, which is safer and already does all the hard work for you. We need to be very careful here as this is a very expensive operation to run. Not doing this correctly can crash your site due to timing out Your worksflow is also wrong here. I would first create all the tags, and after that, insert the tags into the posts. You are trying to do all at once. Lets us first grab all the categories and use that info to create tags. Just note: * `post_tag` being a non hierarchical taxonomy cannot have any duplicate names, hierarchical taxonomies like `category` can have duplicate term names within different hierarchies. If you have categories with same names, you will get a `WP_Error` object back if you are going to try to insert tags with duplicate names. To avoid that, we will simply check if a tag exists before we try to insert it * Tags cannot have parent/child relationships, categories can. So when we duplicate a category to be a term, we should set all parents explicitly to `0` Here is the code: (***NOTE***: We would require PHP 5.4+) ``` // Lets create our tags. We will use wp_insert_term hooked to init add_action( 'init', function () { // Get all categories $categories = get_categories( ['hide_empty' => 0] ); // Probably totally unnecessary, but check for empty $categories if ( !$categories ) return; // Loop through the categories and create our tags foreach ( $categories as $category ) { // First make sure that there is no tag that exist with the same name if ( term_exists( $category->name, 'post_tag' ) ) continue; // Set our arguments for our terms from $category $args = [ 'description' => $category->description, 'parent' => 0, // We can drop this, default is 0 'slug' => $category->slug, ]; wp_insert_term( $category->name, 'post_tag', $args ); } //endforeach }, PHP_INT_MAX ); ``` You should now see these tags in your *Tag* admin page. You can also remove the code as it is no more necessary. Now that we have our tags created, we need to add them to our posts. Here we would need to be careful as you are talking about 900+ posts, so we do not want to break the bank. What we will do is, we will query all of those posts, but only the post ID's which saves a lot on resources. Also, we will use `get_the_category` which are cached, so it does not require extra db calls, `wp_get_post_categories` are not cached, so it is really expensive Due to [`wp_set_post_terms`](https://codex.wordpress.org/Function_Reference/wp_set_post_terms) being expensive, you would maybe need to split the following into a couple of queries, but I believe one query should be enough Lets attach the tags to our posts ``` add_action( 'template_redirect', function () { // Get all our posts $args = [ 'posts_per_page' => -1, 'fields' => 'ids', // Make the query lean // Add any additional query args here ]; $q = new WP_Query( $args ); if ( !$q->have_posts() ) return; while ( $q->have_posts() ) { $q->the_post(); // Get all the categories attached to the post $categories = get_the_category(); if ( !$categories ) continue; // Get the names from the categories into an array $names = wp_list_pluck( $categories, 'name' ); // Loop through the names and make sure that the post does not already has the tag attached foreach ( $names as $key=>$name ) { if ( has_tag( $name ) ) unset ( $names[$key] ); } // Make sure we still have a valid $names array if ( !$names ) continue; // Finally, attach our tags to the posts wp_set_post_terms( get_the_ID(), // Post ID $names, // Array of tag names to attach 'post_tag', true // Only add the tags, do not override ); } wp_reset_postdata(); }); ``` Your posts should now have tags attached to them matching the categories. You can also now remove the function as we are done
212,055
<p>I'm adding a custom menu to my wordpress theme. I need to add custom html to the final submenu item - before the primary sub-menu closes <code>&lt;/ul&gt;</code> </p> <p>I have registered my new menu</p> <pre><code>//functions.php function register_my_menus() { register_nav_menus( array( 'accessories' =&gt; __( 'Accessories Menu' ) ) ); } </code></pre> <p>and I have called my new menu in my header </p> <pre><code>//header.php wp_nav_menu( array( 'theme_location' =&gt; 'accessories', 'walker' =&gt; BENZ_Walker_Nav_Menu_ACC ) ); </code></pre> <p>I have attempted to modify a new Walker to add this div to my submenu, however this added the div for each menu item </p> <pre><code>// functions.php ==this adds one div foreach li==comment out class BENZ_Walker_Nav_Menu_ACC extends Walker_Nav_Menu { function start_lvl(&amp;$output, $depth) { $output .= '&lt;ul class="sub-menu"&gt;'; } function end_lvl(&amp;$output, $depth) { //$output .='&lt;div&gt;the div that I want to show only once&lt;/div&gt;&lt;/ul&gt;'; $output .= '&lt;/ul&gt;'; } } } </code></pre> <p>Again the above example is commented out because it does not work for my needs</p> <p>I have also tried to add append some html at the end of the menu with the following two eaxmples...</p> <pre><code>//functions.php == this shows custom html after the top-level `&lt;li&gt;` function BENZ_menu_extras($menu, $args) { if( 'accessories' !== $args-&gt;theme_location ) return $menu; return $menu . '&lt;div&gt;the div that I want to show only once&lt;/div&gt;'; } add_filter('wp_nav_menu_items','BENZ_menu_extras', 10, 2); </code></pre> <p>this is very close, however I do not need the html in the top level of hierarchy in the menu, but instead one level deeper. </p> <p>I have also tried this example..</p> <pre><code>function add_last_nav_item($items, $args) { if (!is_admin() &amp;&amp; $args-&gt;theme_location == 'accessories') { $items .= '&lt;div&gt;the div that I want to show only once&lt;/div&gt;'; } return $items; } add_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2 ); </code></pre> <p>however this does the same as the first example listed... </p> <p>How can we use either of the above functions with the <code>$depth</code> variable to add my div here....</p> <pre><code>&lt;div class="accessories menu"&gt; &lt;ul id="menu-accessories" class="menu sf-menu"&gt; &lt;li id="menu-item-1905"&gt; &lt;a class="sf-with-ul" href="http://#"&gt;ACCESSORIES&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li id="menu-item-1897"&gt; &lt;a class="sf-with-ul" href="http://#"&gt;stuff&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li id="menu-item-1899"&gt;stuff1&lt;/li&gt; &lt;li id="menu-item-1898"&gt;stuff1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li id="menu-item-1903"&gt; &lt;a class="sf-with-ul" href="http://#"&gt;other stuff&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li id="menu-item-1906"&gt;other stuff1&lt;/li&gt; &lt;li id="menu-item-1907"&gt;other stuff2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li id="menu-item-1911"&gt; &lt;a class="sf-with-ul" href="http://#"&gt;blue stuff&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li id="menu-item-1912"&gt;blue stuff 1&lt;/li&gt; &lt;li id="menu-item-1913"&gt;blut stuff 2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;!--This is where i want to put one div so its in the main submenu--&gt; &lt;div&gt;the div that I want to show only once&lt;/div&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><a href="https://jsfiddle.net/qpbpofpp/3/" rel="nofollow">https://jsfiddle.net/qpbpofpp/3/</a></p> <p>Thanks for reading. </p> <p>--BEGIN EDIT-- This is the closest I have gotten..</p> <pre><code> //functions.php class BENZ_Walker_Nav_Menu_ACC extends Walker_Nav_Menu { function start_lvl(&amp;$output, $depth) { $output .= '&lt;ul class="sub-menu"&gt;'; } function end_lvl(&amp;$output, $depth) { if ($depth = 2){ $output .= '&lt;div&gt;the div that I want to show only once&lt;/div&gt;&lt;/ul&gt;'; } else { $output .= '&lt;/ul&gt;'; } } } </code></pre> <p>except for now shows after all three of the sub menus, i just need it to show once</p>
[ { "answer_id": 212062, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 1, "selected": false, "text": "<p>You requested SQL solution but SQL is not (yet) my speciality but I might still help you. SQL also seems pointless in your case because WordPress provides all nessecary tools to achieve this.</p>\n\n<p>I don't recommend to run this more than once if you remove comments from the end of code. You'll understand when you'll get there.</p>\n\n<p>This code \"copies\" all the categories of all your posts and saves them as tags. It doesn't delete categories and it also doesn't set new tags to posts. If you also want to set tags to posts, let me know.</p>\n\n<p><strong>PS! It only works correctly if categories are not hierarchical aka without parents!</strong></p>\n\n<p>Please let me know if there are any problems. This code should not do any harm as far as you don't remove comments from the end of the code.</p>\n\n<hr>\n\n<pre><code>&lt;?php\nglobal $post;\n\n//Get ALL the posts with query\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'any' //Change to 'publish', 'draft' or 'pending' if you don't want to get ALL post STATUSES\n );\n\n$post_query = new WP_Query( $args );\n\n//Declare new array of our categories which eventually become tags\n$new_tags = array();\n\nwhile ($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n\n //Get all the categories names of the post and save as an array variable\n $post_categories = wp_get_post_categories($post-&gt;ID, array('fields' =&gt; 'names') );\n\n //Loop through all categories\n foreach ( $post_categories as $category ) {\n\n //Check if category is already in array\n if ( ! in_array($category , $new_tags ) ) {\n\n //Push category to array if it isn't in array yet\n array_push( $new_tags, $category );\n }\n }\n\nendwhile;\nwp_reset_postdata();\n\n//VERY IMPORTANT - test first without making new tags and check if everything seems to be correct \n//PS! Compare the count of items in array (starts with 0 - it's 1 less because of that) with category count in WP admin area\nprint_r($new_tags);\n\n\n//Add new tags programmatically - don't do it if you're sure that array is correct!!\n/*\nforeach ( $new_tags as $tag ) {\n wp_insert_term( $tag, 'post_tag' );\n} \n*/\n?&gt;\n</code></pre>\n" }, { "answer_id": 212084, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>As I said, we would rather use native functions here, which is safer and already does all the hard work for you. We need to be very careful here as this is a very expensive operation to run. Not doing this correctly can crash your site due to timing out</p>\n\n<p>Your worksflow is also wrong here. I would first create all the tags, and after that, insert the tags into the posts. You are trying to do all at once. </p>\n\n<p>Lets us first grab all the categories and use that info to create tags. Just note:</p>\n\n<ul>\n<li><p><code>post_tag</code> being a non hierarchical taxonomy cannot have any duplicate names, hierarchical taxonomies like <code>category</code> can have duplicate term names within different hierarchies. If you have categories with same names, you will get a <code>WP_Error</code> object back if you are going to try to insert tags with duplicate names. To avoid that, we will simply check if a tag exists before we try to insert it</p></li>\n<li><p>Tags cannot have parent/child relationships, categories can. So when we duplicate a category to be a term, we should set all parents explicitly to <code>0</code></p></li>\n</ul>\n\n<p>Here is the code: (<strong><em>NOTE</strong>: We would require PHP 5.4+</em>)</p>\n\n<pre><code>// Lets create our tags. We will use wp_insert_term hooked to init\nadd_action( 'init', function ()\n{\n // Get all categories\n $categories = get_categories( ['hide_empty' =&gt; 0] );\n\n // Probably totally unnecessary, but check for empty $categories\n if ( !$categories )\n return;\n\n // Loop through the categories and create our tags\n foreach ( $categories as $category ) {\n // First make sure that there is no tag that exist with the same name\n if ( term_exists( $category-&gt;name, 'post_tag' ) )\n continue;\n\n // Set our arguments for our terms from $category\n $args = [\n 'description' =&gt; $category-&gt;description,\n 'parent' =&gt; 0, // We can drop this, default is 0\n 'slug' =&gt; $category-&gt;slug,\n ];\n wp_insert_term( $category-&gt;name, 'post_tag', $args );\n } //endforeach\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>You should now see these tags in your <em>Tag</em> admin page. You can also remove the code as it is no more necessary.</p>\n\n<p>Now that we have our tags created, we need to add them to our posts. Here we would need to be careful as you are talking about 900+ posts, so we do not want to break the bank. </p>\n\n<p>What we will do is, we will query all of those posts, but only the post ID's which saves a lot on resources. Also, we will use <code>get_the_category</code> which are cached, so it does not require extra db calls, <code>wp_get_post_categories</code> are not cached, so it is really expensive</p>\n\n<p>Due to <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_terms\" rel=\"noreferrer\"><code>wp_set_post_terms</code></a> being expensive, you would maybe need to split the following into a couple of queries, but I believe one query should be enough</p>\n\n<p>Lets attach the tags to our posts</p>\n\n<pre><code>add_action( 'template_redirect', function ()\n{\n // Get all our posts\n $args = [\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids', // Make the query lean\n // Add any additional query args here\n ];\n $q = new WP_Query( $args );\n\n if ( !$q-&gt;have_posts() )\n return;\n\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n // Get all the categories attached to the post\n $categories = get_the_category();\n if ( !$categories )\n continue;\n\n // Get the names from the categories into an array\n $names = wp_list_pluck( $categories, 'name' );\n // Loop through the names and make sure that the post does not already has the tag attached\n foreach ( $names as $key=&gt;$name ) {\n if ( has_tag( $name ) )\n unset ( $names[$key] );\n }\n // Make sure we still have a valid $names array\n if ( !$names )\n continue; \n\n // Finally, attach our tags to the posts\n wp_set_post_terms( \n get_the_ID(), // Post ID \n $names, // Array of tag names to attach\n 'post_tag',\n true // Only add the tags, do not override\n );\n }\n wp_reset_postdata();\n});\n</code></pre>\n\n<p>Your posts should now have tags attached to them matching the categories. You can also now remove the function as we are done</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85437/" ]
I'm adding a custom menu to my wordpress theme. I need to add custom html to the final submenu item - before the primary sub-menu closes `</ul>` I have registered my new menu ``` //functions.php function register_my_menus() { register_nav_menus( array( 'accessories' => __( 'Accessories Menu' ) ) ); } ``` and I have called my new menu in my header ``` //header.php wp_nav_menu( array( 'theme_location' => 'accessories', 'walker' => BENZ_Walker_Nav_Menu_ACC ) ); ``` I have attempted to modify a new Walker to add this div to my submenu, however this added the div for each menu item ``` // functions.php ==this adds one div foreach li==comment out class BENZ_Walker_Nav_Menu_ACC extends Walker_Nav_Menu { function start_lvl(&$output, $depth) { $output .= '<ul class="sub-menu">'; } function end_lvl(&$output, $depth) { //$output .='<div>the div that I want to show only once</div></ul>'; $output .= '</ul>'; } } } ``` Again the above example is commented out because it does not work for my needs I have also tried to add append some html at the end of the menu with the following two eaxmples... ``` //functions.php == this shows custom html after the top-level `<li>` function BENZ_menu_extras($menu, $args) { if( 'accessories' !== $args->theme_location ) return $menu; return $menu . '<div>the div that I want to show only once</div>'; } add_filter('wp_nav_menu_items','BENZ_menu_extras', 10, 2); ``` this is very close, however I do not need the html in the top level of hierarchy in the menu, but instead one level deeper. I have also tried this example.. ``` function add_last_nav_item($items, $args) { if (!is_admin() && $args->theme_location == 'accessories') { $items .= '<div>the div that I want to show only once</div>'; } return $items; } add_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2 ); ``` however this does the same as the first example listed... How can we use either of the above functions with the `$depth` variable to add my div here.... ``` <div class="accessories menu"> <ul id="menu-accessories" class="menu sf-menu"> <li id="menu-item-1905"> <a class="sf-with-ul" href="http://#">ACCESSORIES</a> <ul class="sub-menu"> <li id="menu-item-1897"> <a class="sf-with-ul" href="http://#">stuff</a> <ul class="sub-menu"> <li id="menu-item-1899">stuff1</li> <li id="menu-item-1898">stuff1</li> </ul> </li> <li id="menu-item-1903"> <a class="sf-with-ul" href="http://#">other stuff</a> <ul class="sub-menu"> <li id="menu-item-1906">other stuff1</li> <li id="menu-item-1907">other stuff2</li> </ul> </li> <li id="menu-item-1911"> <a class="sf-with-ul" href="http://#">blue stuff</a> <ul class="sub-menu"> <li id="menu-item-1912">blue stuff 1</li> <li id="menu-item-1913">blut stuff 2</li> </ul> </li> <!--This is where i want to put one div so its in the main submenu--> <div>the div that I want to show only once</div> </ul> </li> </ul> </div> ``` <https://jsfiddle.net/qpbpofpp/3/> Thanks for reading. --BEGIN EDIT-- This is the closest I have gotten.. ``` //functions.php class BENZ_Walker_Nav_Menu_ACC extends Walker_Nav_Menu { function start_lvl(&$output, $depth) { $output .= '<ul class="sub-menu">'; } function end_lvl(&$output, $depth) { if ($depth = 2){ $output .= '<div>the div that I want to show only once</div></ul>'; } else { $output .= '</ul>'; } } } ``` except for now shows after all three of the sub menus, i just need it to show once
As I said, we would rather use native functions here, which is safer and already does all the hard work for you. We need to be very careful here as this is a very expensive operation to run. Not doing this correctly can crash your site due to timing out Your worksflow is also wrong here. I would first create all the tags, and after that, insert the tags into the posts. You are trying to do all at once. Lets us first grab all the categories and use that info to create tags. Just note: * `post_tag` being a non hierarchical taxonomy cannot have any duplicate names, hierarchical taxonomies like `category` can have duplicate term names within different hierarchies. If you have categories with same names, you will get a `WP_Error` object back if you are going to try to insert tags with duplicate names. To avoid that, we will simply check if a tag exists before we try to insert it * Tags cannot have parent/child relationships, categories can. So when we duplicate a category to be a term, we should set all parents explicitly to `0` Here is the code: (***NOTE***: We would require PHP 5.4+) ``` // Lets create our tags. We will use wp_insert_term hooked to init add_action( 'init', function () { // Get all categories $categories = get_categories( ['hide_empty' => 0] ); // Probably totally unnecessary, but check for empty $categories if ( !$categories ) return; // Loop through the categories and create our tags foreach ( $categories as $category ) { // First make sure that there is no tag that exist with the same name if ( term_exists( $category->name, 'post_tag' ) ) continue; // Set our arguments for our terms from $category $args = [ 'description' => $category->description, 'parent' => 0, // We can drop this, default is 0 'slug' => $category->slug, ]; wp_insert_term( $category->name, 'post_tag', $args ); } //endforeach }, PHP_INT_MAX ); ``` You should now see these tags in your *Tag* admin page. You can also remove the code as it is no more necessary. Now that we have our tags created, we need to add them to our posts. Here we would need to be careful as you are talking about 900+ posts, so we do not want to break the bank. What we will do is, we will query all of those posts, but only the post ID's which saves a lot on resources. Also, we will use `get_the_category` which are cached, so it does not require extra db calls, `wp_get_post_categories` are not cached, so it is really expensive Due to [`wp_set_post_terms`](https://codex.wordpress.org/Function_Reference/wp_set_post_terms) being expensive, you would maybe need to split the following into a couple of queries, but I believe one query should be enough Lets attach the tags to our posts ``` add_action( 'template_redirect', function () { // Get all our posts $args = [ 'posts_per_page' => -1, 'fields' => 'ids', // Make the query lean // Add any additional query args here ]; $q = new WP_Query( $args ); if ( !$q->have_posts() ) return; while ( $q->have_posts() ) { $q->the_post(); // Get all the categories attached to the post $categories = get_the_category(); if ( !$categories ) continue; // Get the names from the categories into an array $names = wp_list_pluck( $categories, 'name' ); // Loop through the names and make sure that the post does not already has the tag attached foreach ( $names as $key=>$name ) { if ( has_tag( $name ) ) unset ( $names[$key] ); } // Make sure we still have a valid $names array if ( !$names ) continue; // Finally, attach our tags to the posts wp_set_post_terms( get_the_ID(), // Post ID $names, // Array of tag names to attach 'post_tag', true // Only add the tags, do not override ); } wp_reset_postdata(); }); ``` Your posts should now have tags attached to them matching the categories. You can also now remove the function as we are done
212,063
<p>How can I make a code show the number of posts you have on my site, adding all fair categories??</p>
[ { "answer_id": 212066, "author": "user5477769", "author_id": 84959, "author_profile": "https://wordpress.stackexchange.com/users/84959", "pm_score": 0, "selected": false, "text": "<p>This forum thread has a great answer: <a href=\"https://wordpress.org/support/topic/show-number-of-post?replies=4\" rel=\"nofollow\">https://wordpress.org/support/topic/show-number-of-post?replies=4</a></p>\n\n<p>Here's the code they posted for echoing the amount:</p>\n\n<pre><code>&lt;?php\necho $wpdb-&gt;get_var(\"SELECT COUNT(ID) FROM $wpdb-&gt;posts WHERE post_type = 'post' AND post_status = 'publish'\");\n?&gt;\n</code></pre>\n" }, { "answer_id": 212074, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>Using a query could give you easier customization without having to use SQL directly.</p>\n\n<pre><code>$posts = get_posts( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'fields' =&gt; 'ids',\n));\n\n$total_count = count( $posts );\n\nprint_r ( $total_count );\n</code></pre>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85291/" ]
How can I make a code show the number of posts you have on my site, adding all fair categories??
Using a query could give you easier customization without having to use SQL directly. ``` $posts = get_posts( array( 'post_type' => 'post', 'post_status' => 'any', 'numberposts' => -1, 'fields' => 'ids', )); $total_count = count( $posts ); print_r ( $total_count ); ```
212,086
<p>I have a special situation and need some help achieving the final step.</p> <p><strong>Background:</strong></p> <p>When I access <em>mydomain.com/category/postname</em>, I get the post as expected.</p> <p>When I access <em>mydomain.com/category/postname?ajax=1</em>, I get the post html (baked into and including its corresponding page template markup, which is extremely important for this use case), but I get it rendered <strong>without</strong> its header and footer (I did this on purpose, with a $_GET['ajax']==1 conditional inside the header.php and footer.php files to suppress them).</p> <p><strong>This all works as expected.</strong> However, it leaves me with a new small problem... Browsers won't properly cache content from URLs that end with a GET parameter string.</p> <p><strong>Therefore,</strong> I would like to create a rewrite rule that achieves the following...</p> <p><em>mydomain.com/ajax/category/postname</em> <strong>becomes</strong> <em>mydomain.com/category/postname?ajax=1</em></p> <p><strong>Here's from my functions.php:</strong></p> <pre><code>function dynaload_rewrite() { add_rewrite_rule('ajax/(.*)/?', '$matches[1]?ajax=1', 'bottom'); } add_action('init', 'dynaload_rewrite'); </code></pre> <p><strong>This results in .htaccess file as follows:</strong></p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^ajax/(.*)/? /$matches[1]?ajax=1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p><strong>Expected Result:</strong> When I access <em>/ajax/category/postname</em> I want the content from <em>/category/postname</em> to render, minus the header and footer, as they do if I access normally with <em>?ajax=1</em></p> <p><strong>Actual Result:</strong> I am receiving the content from my WordPress 404 page, however the header and footer <strong>are</strong> omitted (so I know that the parameter ajax=1 is being passed correctly, it's just loading the wrong page).</p> <p>Successful help is appreciated and will be deemed to be impressive. Thank you.</p>
[ { "answer_id": 212066, "author": "user5477769", "author_id": 84959, "author_profile": "https://wordpress.stackexchange.com/users/84959", "pm_score": 0, "selected": false, "text": "<p>This forum thread has a great answer: <a href=\"https://wordpress.org/support/topic/show-number-of-post?replies=4\" rel=\"nofollow\">https://wordpress.org/support/topic/show-number-of-post?replies=4</a></p>\n\n<p>Here's the code they posted for echoing the amount:</p>\n\n<pre><code>&lt;?php\necho $wpdb-&gt;get_var(\"SELECT COUNT(ID) FROM $wpdb-&gt;posts WHERE post_type = 'post' AND post_status = 'publish'\");\n?&gt;\n</code></pre>\n" }, { "answer_id": 212074, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>Using a query could give you easier customization without having to use SQL directly.</p>\n\n<pre><code>$posts = get_posts( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'fields' =&gt; 'ids',\n));\n\n$total_count = count( $posts );\n\nprint_r ( $total_count );\n</code></pre>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85452/" ]
I have a special situation and need some help achieving the final step. **Background:** When I access *mydomain.com/category/postname*, I get the post as expected. When I access *mydomain.com/category/postname?ajax=1*, I get the post html (baked into and including its corresponding page template markup, which is extremely important for this use case), but I get it rendered **without** its header and footer (I did this on purpose, with a $\_GET['ajax']==1 conditional inside the header.php and footer.php files to suppress them). **This all works as expected.** However, it leaves me with a new small problem... Browsers won't properly cache content from URLs that end with a GET parameter string. **Therefore,** I would like to create a rewrite rule that achieves the following... *mydomain.com/ajax/category/postname* **becomes** *mydomain.com/category/postname?ajax=1* **Here's from my functions.php:** ``` function dynaload_rewrite() { add_rewrite_rule('ajax/(.*)/?', '$matches[1]?ajax=1', 'bottom'); } add_action('init', 'dynaload_rewrite'); ``` **This results in .htaccess file as follows:** ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^ajax/(.*)/? /$matches[1]?ajax=1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` **Expected Result:** When I access */ajax/category/postname* I want the content from */category/postname* to render, minus the header and footer, as they do if I access normally with *?ajax=1* **Actual Result:** I am receiving the content from my WordPress 404 page, however the header and footer **are** omitted (so I know that the parameter ajax=1 is being passed correctly, it's just loading the wrong page). Successful help is appreciated and will be deemed to be impressive. Thank you.
Using a query could give you easier customization without having to use SQL directly. ``` $posts = get_posts( array( 'post_type' => 'post', 'post_status' => 'any', 'numberposts' => -1, 'fields' => 'ids', )); $total_count = count( $posts ); print_r ( $total_count ); ```
212,092
<p>(Wordpress 4.3.1) </p> <p>I'm running a custom loop and only want to include posts that have file uploaded to a custom field: audio_file.</p> <p>I have tried many solutions around the web and so far nothing works. </p> <p>Can I use meta_query to check if a key has a value? </p> <p>Here is my current attempt:</p> <pre><code> global $post; $args = array( 'post_type' =&gt; array ( 'podcast', 'event', ), 'posts_per_page' =&gt; 10, 'post_status' =&gt; 'publish', 'paged' =&gt; get_query_var( 'paged' ), 'meta_query' =&gt; array ( 'key' =&gt; 'audio_file', 'value' =&gt; '' , 'compare' =&gt; '!=', //'type' =&gt; 'date', ), ); global $wp_query; $wp_query = new WP_Query( $args ); if ( have_posts() ) { while ( have_posts() ) { the_post(); </code></pre> <p>The intended result here is to display posts where 'audio_file' is not empty.</p> <p>Thanks. (Wordpress 4.3.1)</p>
[ { "answer_id": 212095, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Can I use meta_query to check if a key has a value?</p>\n</blockquote>\n\n<p>Any value? <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">Use <code>EXISTS</code></a></p>\n\n<pre><code>'meta_query' =&gt; array (\n 'key' =&gt; 'audio_file',\n 'value' =&gt; '' ,\n 'compare' =&gt; 'EXISTS',\n 'type' =&gt; 'date',\n ),\n);\n</code></pre>\n\n<p>I don't know why your uploaded file would be a <code>date</code> type though. I'd expect it to <code>binary</code> or maybe <code>char</code></p>\n" }, { "answer_id": 212107, "author": "AJD", "author_id": 59712, "author_profile": "https://wordpress.stackexchange.com/users/59712", "pm_score": 4, "selected": true, "text": "<p>I figured it out, meta_query must be an array <strong>within</strong> an array as it is intended for advanced queries using 'relation'.</p>\n\n<pre><code>meta_query =&gt; array (\n array (\n //'relation' =&gt; 'OR',\n 'key' =&gt; 'audio_file', //The field to check.\n 'value' =&gt; '', //The value of the field.\n 'compare' =&gt; '!=', //Conditional statement used on the value.\n ), \n),\n</code></pre>\n\n<p>The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded. </p>\n" }, { "answer_id": 370000, "author": "Timo L", "author_id": 190794, "author_profile": "https://wordpress.stackexchange.com/users/190794", "pm_score": 2, "selected": false, "text": "<p>This might help someone. This will look for meta value, if exists and is not empty.</p>\n<pre><code>'meta_query' =&gt; [\n 'relation' =&gt; 'AND',\n [\n 'key' =&gt; 'your_key',\n 'compare' =&gt; 'EXISTS',\n ],\n // Don't want empty values\n [\n 'key' =&gt; 'your_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ],\n],\n</code></pre>\n" }, { "answer_id": 398859, "author": "Showhan Ahmed", "author_id": 102213, "author_profile": "https://wordpress.stackexchange.com/users/102213", "pm_score": 2, "selected": false, "text": "<p>It seems the <em><strong>type</strong></em> of value is essential now. I couldn't get the meta query working correctly without using the type. Significantly, while checking the value existence.</p>\n<p>This code doesn't work now.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ),\n),\n</code></pre>\n<p>This one works.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n 'type' =&gt; 'NUMERIC'\n ),\n),\n</code></pre>\n<p>The only difference is the <em><strong>type</strong></em>.</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59712/" ]
(Wordpress 4.3.1) I'm running a custom loop and only want to include posts that have file uploaded to a custom field: audio\_file. I have tried many solutions around the web and so far nothing works. Can I use meta\_query to check if a key has a value? Here is my current attempt: ``` global $post; $args = array( 'post_type' => array ( 'podcast', 'event', ), 'posts_per_page' => 10, 'post_status' => 'publish', 'paged' => get_query_var( 'paged' ), 'meta_query' => array ( 'key' => 'audio_file', 'value' => '' , 'compare' => '!=', //'type' => 'date', ), ); global $wp_query; $wp_query = new WP_Query( $args ); if ( have_posts() ) { while ( have_posts() ) { the_post(); ``` The intended result here is to display posts where 'audio\_file' is not empty. Thanks. (Wordpress 4.3.1)
I figured it out, meta\_query must be an array **within** an array as it is intended for advanced queries using 'relation'. ``` meta_query => array ( array ( //'relation' => 'OR', 'key' => 'audio_file', //The field to check. 'value' => '', //The value of the field. 'compare' => '!=', //Conditional statement used on the value. ), ), ``` The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded.
212,099
<p>I want users who don't have permission to view content to be redirected to a page when they are presented with the default "Nothing Found" page. I've already redirected 404s but this is not exactly a 404. The content exists, they just don't have permission to view it. </p>
[ { "answer_id": 212095, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Can I use meta_query to check if a key has a value?</p>\n</blockquote>\n\n<p>Any value? <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">Use <code>EXISTS</code></a></p>\n\n<pre><code>'meta_query' =&gt; array (\n 'key' =&gt; 'audio_file',\n 'value' =&gt; '' ,\n 'compare' =&gt; 'EXISTS',\n 'type' =&gt; 'date',\n ),\n);\n</code></pre>\n\n<p>I don't know why your uploaded file would be a <code>date</code> type though. I'd expect it to <code>binary</code> or maybe <code>char</code></p>\n" }, { "answer_id": 212107, "author": "AJD", "author_id": 59712, "author_profile": "https://wordpress.stackexchange.com/users/59712", "pm_score": 4, "selected": true, "text": "<p>I figured it out, meta_query must be an array <strong>within</strong> an array as it is intended for advanced queries using 'relation'.</p>\n\n<pre><code>meta_query =&gt; array (\n array (\n //'relation' =&gt; 'OR',\n 'key' =&gt; 'audio_file', //The field to check.\n 'value' =&gt; '', //The value of the field.\n 'compare' =&gt; '!=', //Conditional statement used on the value.\n ), \n),\n</code></pre>\n\n<p>The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded. </p>\n" }, { "answer_id": 370000, "author": "Timo L", "author_id": 190794, "author_profile": "https://wordpress.stackexchange.com/users/190794", "pm_score": 2, "selected": false, "text": "<p>This might help someone. This will look for meta value, if exists and is not empty.</p>\n<pre><code>'meta_query' =&gt; [\n 'relation' =&gt; 'AND',\n [\n 'key' =&gt; 'your_key',\n 'compare' =&gt; 'EXISTS',\n ],\n // Don't want empty values\n [\n 'key' =&gt; 'your_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ],\n],\n</code></pre>\n" }, { "answer_id": 398859, "author": "Showhan Ahmed", "author_id": 102213, "author_profile": "https://wordpress.stackexchange.com/users/102213", "pm_score": 2, "selected": false, "text": "<p>It seems the <em><strong>type</strong></em> of value is essential now. I couldn't get the meta query working correctly without using the type. Significantly, while checking the value existence.</p>\n<p>This code doesn't work now.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ),\n),\n</code></pre>\n<p>This one works.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n 'type' =&gt; 'NUMERIC'\n ),\n),\n</code></pre>\n<p>The only difference is the <em><strong>type</strong></em>.</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212099", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85457/" ]
I want users who don't have permission to view content to be redirected to a page when they are presented with the default "Nothing Found" page. I've already redirected 404s but this is not exactly a 404. The content exists, they just don't have permission to view it.
I figured it out, meta\_query must be an array **within** an array as it is intended for advanced queries using 'relation'. ``` meta_query => array ( array ( //'relation' => 'OR', 'key' => 'audio_file', //The field to check. 'value' => '', //The value of the field. 'compare' => '!=', //Conditional statement used on the value. ), ), ``` The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded.
212,102
<pre><code>$locations = get_the_terms( $post_id, 'location' ); foreach ( $locations as $location ) { echo '&lt;a href="'.site_url().'/location/'.$location-&gt;slug.'"&gt;'. $location-&gt;name .'&lt;/a&gt;'; break; } </code></pre> <hr> <p>How to also get all parent taxonomies if there are any?</p> <p>For example:</p> <ol> <li><p>Current code outputs <code>London</code> in front-end.</p></li> <li><p>What I would need to output <code>Europe &gt; England &gt; London</code>.</p></li> </ol> <hr> <p>What I managed to dig up or have tried is that <code>get_the_terms()</code> also have <code>parent</code> property which could be used as <code>$location-&gt;parent</code>. This only has ID property, I didn't manage to squeeze name or slug out of it. Also there's no way to use it to retrieve it's parent if it has any. </p> <hr> <p><strong>Update after some experimenting:</strong></p> <pre><code>//Parent if( $location-&gt;parent != "" ) { $location_parent_id = $location-&gt;parent; $location_parent = get_term_by( 'id', $location_parent_id, 'location' ); echo $location_parent-&gt;name; //Here it is } //If I need parent of parent if( $location_parent-&gt;parent != "" ) { $location_parent_parent_id = $location_parent-&gt;parent; $location_parent_parent = get_term_by( 'id', $location_parent_parent_id, 'location' ); echo $location_parent_parent-&gt;name; //Here it is } //etc </code></pre> <p><strong>Is this very <em>grazy</em> approach?</strong> </p>
[ { "answer_id": 212095, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Can I use meta_query to check if a key has a value?</p>\n</blockquote>\n\n<p>Any value? <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">Use <code>EXISTS</code></a></p>\n\n<pre><code>'meta_query' =&gt; array (\n 'key' =&gt; 'audio_file',\n 'value' =&gt; '' ,\n 'compare' =&gt; 'EXISTS',\n 'type' =&gt; 'date',\n ),\n);\n</code></pre>\n\n<p>I don't know why your uploaded file would be a <code>date</code> type though. I'd expect it to <code>binary</code> or maybe <code>char</code></p>\n" }, { "answer_id": 212107, "author": "AJD", "author_id": 59712, "author_profile": "https://wordpress.stackexchange.com/users/59712", "pm_score": 4, "selected": true, "text": "<p>I figured it out, meta_query must be an array <strong>within</strong> an array as it is intended for advanced queries using 'relation'.</p>\n\n<pre><code>meta_query =&gt; array (\n array (\n //'relation' =&gt; 'OR',\n 'key' =&gt; 'audio_file', //The field to check.\n 'value' =&gt; '', //The value of the field.\n 'compare' =&gt; '!=', //Conditional statement used on the value.\n ), \n),\n</code></pre>\n\n<p>The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded. </p>\n" }, { "answer_id": 370000, "author": "Timo L", "author_id": 190794, "author_profile": "https://wordpress.stackexchange.com/users/190794", "pm_score": 2, "selected": false, "text": "<p>This might help someone. This will look for meta value, if exists and is not empty.</p>\n<pre><code>'meta_query' =&gt; [\n 'relation' =&gt; 'AND',\n [\n 'key' =&gt; 'your_key',\n 'compare' =&gt; 'EXISTS',\n ],\n // Don't want empty values\n [\n 'key' =&gt; 'your_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ],\n],\n</code></pre>\n" }, { "answer_id": 398859, "author": "Showhan Ahmed", "author_id": 102213, "author_profile": "https://wordpress.stackexchange.com/users/102213", "pm_score": 2, "selected": false, "text": "<p>It seems the <em><strong>type</strong></em> of value is essential now. I couldn't get the meta query working correctly without using the type. Significantly, while checking the value existence.</p>\n<p>This code doesn't work now.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n ),\n),\n</code></pre>\n<p>This one works.</p>\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'meta_key',\n 'value' =&gt; '',\n 'compare' =&gt; '!=',\n 'type' =&gt; 'NUMERIC'\n ),\n),\n</code></pre>\n<p>The only difference is the <em><strong>type</strong></em>.</p>\n" } ]
2015/12/16
[ "https://wordpress.stackexchange.com/questions/212102", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
``` $locations = get_the_terms( $post_id, 'location' ); foreach ( $locations as $location ) { echo '<a href="'.site_url().'/location/'.$location->slug.'">'. $location->name .'</a>'; break; } ``` --- How to also get all parent taxonomies if there are any? For example: 1. Current code outputs `London` in front-end. 2. What I would need to output `Europe > England > London`. --- What I managed to dig up or have tried is that `get_the_terms()` also have `parent` property which could be used as `$location->parent`. This only has ID property, I didn't manage to squeeze name or slug out of it. Also there's no way to use it to retrieve it's parent if it has any. --- **Update after some experimenting:** ``` //Parent if( $location->parent != "" ) { $location_parent_id = $location->parent; $location_parent = get_term_by( 'id', $location_parent_id, 'location' ); echo $location_parent->name; //Here it is } //If I need parent of parent if( $location_parent->parent != "" ) { $location_parent_parent_id = $location_parent->parent; $location_parent_parent = get_term_by( 'id', $location_parent_parent_id, 'location' ); echo $location_parent_parent->name; //Here it is } //etc ``` **Is this very *grazy* approach?**
I figured it out, meta\_query must be an array **within** an array as it is intended for advanced queries using 'relation'. ``` meta_query => array ( array ( //'relation' => 'OR', 'key' => 'audio_file', //The field to check. 'value' => '', //The value of the field. 'compare' => '!=', //Conditional statement used on the value. ), ), ``` The conditional '!=' not-equal to '' (null) returns true if a file has been uploaded.
212,109
<p>Creating redirects as a client has merged many sites into a single site.</p> <p>How would I set up a rule to redirect to a parent page if the child does not exist - rather than directly to 404.</p> <p><strong>Eg</strong> Redirect from</p> <pre><code>example.com/au/location1/staff (Does not exist) </code></pre> <p>to</p> <pre><code>example.com/au/location1 </code></pre> <p>(there are a lot of these subpages which no longer exist)</p>
[ { "answer_id": 212118, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Grab the 404 during the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow\">template_redirect</a> and if it's not a file, redirect to the parent. Be careful, if someone is looking for site exploits then every 404 will render your home page.</p>\n\n<pre><code>function __404_template_redirect()\n{\n if( is_404() )\n {\n $req = $_SERVER['REQUEST_URI'];\n\n if ( is_file( $req )) {\n return; // don't reduce perf by redirecting files to home url\n }\n\n // pull the parent directory and convert to site url\n $base_dir = dirname( $req );\n $parent_url = site_url( $base_dir );\n\n // redirect to parent directory\n wp_redirect( $parent_url, 301 );\n exit();\n }\n}\n\nadd_action( 'template_redirect', '__404_template_redirect' );\n</code></pre>\n" }, { "answer_id": 333715, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 1, "selected": false, "text": "<p>If you want to do this in your .htaccess file to ensure an early redirect, the method is as follows.</p>\n\n<p>First check if the page does not exist using the rewrite condition:</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\n</code></pre>\n\n<p>Next comes the rewrite rule for the page that does not exist</p>\n\n<pre><code>RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]\n</code></pre>\n\n<p>Putting this all together:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f \nRewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]\n</code></pre>\n\n<p>Now if the page example.com/au/location1/staff exists then there will be no redirect, however if the page example.com/au/location1/staff does not exist the the user will be redirected to example.com/au/location1/.</p>\n\n<p>Notice that this will apply to all child pages off example.com/au/location1/ i.e. any child pages that do not exist will redirect to the parent page.</p>\n\n<p>I hope that I have interpreted your question correctly and that this helps.</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85462/" ]
Creating redirects as a client has merged many sites into a single site. How would I set up a rule to redirect to a parent page if the child does not exist - rather than directly to 404. **Eg** Redirect from ``` example.com/au/location1/staff (Does not exist) ``` to ``` example.com/au/location1 ``` (there are a lot of these subpages which no longer exist)
If you want to do this in your .htaccess file to ensure an early redirect, the method is as follows. First check if the page does not exist using the rewrite condition: ``` RewriteCond %{REQUEST_FILENAME} !-f ``` Next comes the rewrite rule for the page that does not exist ``` RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L] ``` Putting this all together: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L] ``` Now if the page example.com/au/location1/staff exists then there will be no redirect, however if the page example.com/au/location1/staff does not exist the the user will be redirected to example.com/au/location1/. Notice that this will apply to all child pages off example.com/au/location1/ i.e. any child pages that do not exist will redirect to the parent page. I hope that I have interpreted your question correctly and that this helps.
212,127
<p>Nothing happens when I select the datepicker field.</p> <p>This is the code for the field:</p> <pre><code>&lt;input id="sticky_date" name="sticky_date" class="datepicker hasDatepicker" type="text"&gt; </code></pre> <p>The javascript</p> <pre><code>jQuery(function() { jQuery( '.datepicker' ).datepicker({ changeMonth: true, changeYear: true, yearRange: "-100:-10" }); }); </code></pre> <p>The include code</p> <pre><code>add_action('admin_head', 'admin_datepicker'); function admin_datepicker() { wp_register_script( 'pub-datepicker', get_template_directory_uri().'/js/datepicker.js', array( 'jquery-ui-core', 'jquery-ui-datepicker' ), false, true ); wp_enqueue_script('pub-datepicker'); } </code></pre> <p>I'm not really sure if I'm missing something, there's no error on the js console, nothing happens</p>
[ { "answer_id": 212118, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Grab the 404 during the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow\">template_redirect</a> and if it's not a file, redirect to the parent. Be careful, if someone is looking for site exploits then every 404 will render your home page.</p>\n\n<pre><code>function __404_template_redirect()\n{\n if( is_404() )\n {\n $req = $_SERVER['REQUEST_URI'];\n\n if ( is_file( $req )) {\n return; // don't reduce perf by redirecting files to home url\n }\n\n // pull the parent directory and convert to site url\n $base_dir = dirname( $req );\n $parent_url = site_url( $base_dir );\n\n // redirect to parent directory\n wp_redirect( $parent_url, 301 );\n exit();\n }\n}\n\nadd_action( 'template_redirect', '__404_template_redirect' );\n</code></pre>\n" }, { "answer_id": 333715, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 1, "selected": false, "text": "<p>If you want to do this in your .htaccess file to ensure an early redirect, the method is as follows.</p>\n\n<p>First check if the page does not exist using the rewrite condition:</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\n</code></pre>\n\n<p>Next comes the rewrite rule for the page that does not exist</p>\n\n<pre><code>RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]\n</code></pre>\n\n<p>Putting this all together:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f \nRewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]\n</code></pre>\n\n<p>Now if the page example.com/au/location1/staff exists then there will be no redirect, however if the page example.com/au/location1/staff does not exist the the user will be redirected to example.com/au/location1/.</p>\n\n<p>Notice that this will apply to all child pages off example.com/au/location1/ i.e. any child pages that do not exist will redirect to the parent page.</p>\n\n<p>I hope that I have interpreted your question correctly and that this helps.</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74564/" ]
Nothing happens when I select the datepicker field. This is the code for the field: ``` <input id="sticky_date" name="sticky_date" class="datepicker hasDatepicker" type="text"> ``` The javascript ``` jQuery(function() { jQuery( '.datepicker' ).datepicker({ changeMonth: true, changeYear: true, yearRange: "-100:-10" }); }); ``` The include code ``` add_action('admin_head', 'admin_datepicker'); function admin_datepicker() { wp_register_script( 'pub-datepicker', get_template_directory_uri().'/js/datepicker.js', array( 'jquery-ui-core', 'jquery-ui-datepicker' ), false, true ); wp_enqueue_script('pub-datepicker'); } ``` I'm not really sure if I'm missing something, there's no error on the js console, nothing happens
If you want to do this in your .htaccess file to ensure an early redirect, the method is as follows. First check if the page does not exist using the rewrite condition: ``` RewriteCond %{REQUEST_FILENAME} !-f ``` Next comes the rewrite rule for the page that does not exist ``` RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L] ``` Putting this all together: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L] ``` Now if the page example.com/au/location1/staff exists then there will be no redirect, however if the page example.com/au/location1/staff does not exist the the user will be redirected to example.com/au/location1/. Notice that this will apply to all child pages off example.com/au/location1/ i.e. any child pages that do not exist will redirect to the parent page. I hope that I have interpreted your question correctly and that this helps.
212,130
<p>I want to try the new REST API but I'm not used to this kind of things. Basically, I want to use it to GET custom posts via ajax and show on the website frontend (I'm building an ajax product filtering system).</p> <p>I can't figure out how to authenticate from php and how to test authenticating from command line.</p> <p>I guess I don't need OAuth here, as for the official v2 docs, but the docs say that I would use nonce system (no problem here) from an authenticated user. Obviously, being a website script asking for posts, there's no human user authenticating in my case, so how can I do it via php or js, and in a decently secure way?</p>
[ { "answer_id": 212134, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>GET requests, like listing posts, doesn't need authentication at least you need to get private posts. Your problem is that you are using a route/endpoint that doesn't exist.</p>\n\n<p>In WordPress 4.4, WP REST API infrastructure was merged, endpoints didn't; they will be merged in WordPress 4.5 (as WordPress 4.6 it seems endpoints are still don't included in core). You need to <a href=\"http://v2.wp-api.org/extending/adding/\" rel=\"nofollow\">define your own endpoints</a> or install the plugin to use the default endpoints it provides.</p>\n\n<p>For example (not tested, just written here):</p>\n\n<pre><code>add_action( 'rest_api_init', 'cyb_register_api_endpoints' );\nfunction cyb_register_api_endpoints() {\n\n $namespace = 'myplugin/v1';\n\n register_rest_route( $namespace, '/posts/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'cyb_get_posts',\n ) );\n\n}\n\nfunction cyb_get_posts() {\n\n $args = array(\n // WP_Query arguments\n );\n\n $posts = new WP_Query( $args );\n\n $response = new WP_REST_Response( $posts );\n\n return $response;\n\n}\n</code></pre>\n\n<p>Then, you can get the posts:</p>\n\n<pre><code>https://example.com/myplugin/v1/posts/\n</code></pre>\n" }, { "answer_id": 245552, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>There is a <a href=\"http://wp-cli.org/\" rel=\"nofollow noreferrer\">WP-CLI</a> package <a href=\"https://github.com/wp-cli/restful\" rel=\"nofollow noreferrer\">wp-cli/restful</a> that opens up rest endpoints to the CLI.</p>\n\n<p>Listing the custom post type like <code>product</code> while authenticated as an administrator is as easy as:</p>\n\n<pre><code>wp post list --post-type=product --user=admin\n</code></pre>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212130", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
I want to try the new REST API but I'm not used to this kind of things. Basically, I want to use it to GET custom posts via ajax and show on the website frontend (I'm building an ajax product filtering system). I can't figure out how to authenticate from php and how to test authenticating from command line. I guess I don't need OAuth here, as for the official v2 docs, but the docs say that I would use nonce system (no problem here) from an authenticated user. Obviously, being a website script asking for posts, there's no human user authenticating in my case, so how can I do it via php or js, and in a decently secure way?
GET requests, like listing posts, doesn't need authentication at least you need to get private posts. Your problem is that you are using a route/endpoint that doesn't exist. In WordPress 4.4, WP REST API infrastructure was merged, endpoints didn't; they will be merged in WordPress 4.5 (as WordPress 4.6 it seems endpoints are still don't included in core). You need to [define your own endpoints](http://v2.wp-api.org/extending/adding/) or install the plugin to use the default endpoints it provides. For example (not tested, just written here): ``` add_action( 'rest_api_init', 'cyb_register_api_endpoints' ); function cyb_register_api_endpoints() { $namespace = 'myplugin/v1'; register_rest_route( $namespace, '/posts/', array( 'methods' => 'GET', 'callback' => 'cyb_get_posts', ) ); } function cyb_get_posts() { $args = array( // WP_Query arguments ); $posts = new WP_Query( $args ); $response = new WP_REST_Response( $posts ); return $response; } ``` Then, you can get the posts: ``` https://example.com/myplugin/v1/posts/ ```
212,132
<p>I have several posts that share the same layout but have different title and content.</p> <p>This layout is different from that on the site.</p> <p>I can use single.php to render them, but then ALL posts will have this layout.</p> <p>If I add some category for this posts, could I render all post in this category in the same way?</p> <p>I tried using category-{category-name}.php but it just rendered the page for this category.</p>
[ { "answer_id": 212135, "author": "Craig", "author_id": 85474, "author_profile": "https://wordpress.stackexchange.com/users/85474", "pm_score": 1, "selected": false, "text": "<p>The category templates are just for post archives listing you would need to do this within the single.php template.</p>\n\n<p>You can use has_category()within the single.php template to detect if the post has the category. Then just include different files. eg:</p>\n\n<pre><code>if ( has_category( $category, $post ) ) {\n include \"template-one.php\";\n} else {\n include \"template-two.php\";\n}\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/has_category\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/has_category</a></p>\n" }, { "answer_id": 212137, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so <code>single-{$category}.php</code> does not exist. </p>\n\n<p>To make <code>single-{$category}.php</code> work, we can make use of the <code>single_template</code> filter</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n global $post;\n // Check if our post has our specific category\n if ( !has_category( 1, $post ) ) // Change to your specific category\n return $template;\n\n // Locate and load our single-{$category}.php template\n $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name\n if ( !$locate_template ) \n return $template;\n\n // single-my_category.php exists, load it\n return $locate_template;\n});\n</code></pre>\n\n<p>You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212132", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85230/" ]
I have several posts that share the same layout but have different title and content. This layout is different from that on the site. I can use single.php to render them, but then ALL posts will have this layout. If I add some category for this posts, could I render all post in this category in the same way? I tried using category-{category-name}.php but it just rendered the page for this category.
I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so `single-{$category}.php` does not exist. To make `single-{$category}.php` work, we can make use of the `single_template` filter ``` add_filter( 'single_template', function ( $template ) { global $post; // Check if our post has our specific category if ( !has_category( 1, $post ) ) // Change to your specific category return $template; // Locate and load our single-{$category}.php template $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name if ( !$locate_template ) return $template; // single-my_category.php exists, load it return $locate_template; }); ``` You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target
212,143
<p>I use the following link to delete a post in the frontend of wordpress: </p> <pre><code>&lt;a href="&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;"&gt;Delete Post&lt;/a&gt; </code></pre> <p>This works fine. But after i delete the post its just showing a blank page of the index.php. I want to redirect the author who deletetd the post to a category site like /post-archive. Any idea how i can do that?</p> <p>Thx for your help and best regards.</p>
[ { "answer_id": 212135, "author": "Craig", "author_id": 85474, "author_profile": "https://wordpress.stackexchange.com/users/85474", "pm_score": 1, "selected": false, "text": "<p>The category templates are just for post archives listing you would need to do this within the single.php template.</p>\n\n<p>You can use has_category()within the single.php template to detect if the post has the category. Then just include different files. eg:</p>\n\n<pre><code>if ( has_category( $category, $post ) ) {\n include \"template-one.php\";\n} else {\n include \"template-two.php\";\n}\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/has_category\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/has_category</a></p>\n" }, { "answer_id": 212137, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so <code>single-{$category}.php</code> does not exist. </p>\n\n<p>To make <code>single-{$category}.php</code> work, we can make use of the <code>single_template</code> filter</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n global $post;\n // Check if our post has our specific category\n if ( !has_category( 1, $post ) ) // Change to your specific category\n return $template;\n\n // Locate and load our single-{$category}.php template\n $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name\n if ( !$locate_template ) \n return $template;\n\n // single-my_category.php exists, load it\n return $locate_template;\n});\n</code></pre>\n\n<p>You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212143", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81609/" ]
I use the following link to delete a post in the frontend of wordpress: ``` <a href="<?php echo get_delete_post_link( $post->ID ) ?>">Delete Post</a> ``` This works fine. But after i delete the post its just showing a blank page of the index.php. I want to redirect the author who deletetd the post to a category site like /post-archive. Any idea how i can do that? Thx for your help and best regards.
I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so `single-{$category}.php` does not exist. To make `single-{$category}.php` work, we can make use of the `single_template` filter ``` add_filter( 'single_template', function ( $template ) { global $post; // Check if our post has our specific category if ( !has_category( 1, $post ) ) // Change to your specific category return $template; // Locate and load our single-{$category}.php template $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name if ( !$locate_template ) return $template; // single-my_category.php exists, load it return $locate_template; }); ``` You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target
212,152
<p>I am using Wordpress with Advanced Custom Fields. I have a custom post called "event" with a custom field "date" (I have added the field through ACF). The date field is formatted in the following way: "yyyy-mm-dd." Until now, sorting the custom posts worked fine using the following snippet:</p> <pre><code>$query = new WP_Query([ 'post_type' =&gt; 'event', 'meta_key' =&gt; 'tq_event_date', 'meta_value' =&gt; date('Y-m-d'), 'meta_compare' =&gt; '&lt;', 'orderby' =&gt; ['meta_key' =&gt; 'tq_event_date'], 'posts_per_page' =&gt; '-1' ]); if($query-&gt;have_posts()) { $posts = $query-&gt;get_posts(); foreach($posts as $post) { echo get_field('tq_event_date', $post-&gt;ID). ' '; } } </code></pre> <p>Now I have added a new event post with date "2015-12-03." The sorting for some reason does not sort this post. Here are the results of this query:</p> <pre><code>2015-08-15 2015-07-15 2015-06-02 2015-05-18 2015-04-21 2015-04-18 2015-04-17 2015-04-02 2015-03-28 2014-11-25 2014-07-14 2014-07-04 2014-06-08 2014-05-31 2014-04-25 2014-04-26 2014-03-14 2014-03-15 2014-02-23 2014-02-23 2013-12-16 2013-11-19 2013-11-12 2013-07-24 2013-06-09 2013-05-12 2013-04-26 2013-04-19 2013-04-10 2013-04-05 2012-12-08 2012-11-02 2012-10-22 2012-10-09 2012-10-07 2012-06-23 2012-03-07 2012-02-12 2012-02-07 2011-06-18 2011-05-26 2011-04-30 2011-04-06 2011-02-26 2011-02-11 2011-01-28 2010-12-28 2010-11-22 2010-10-30 2010-10-16 2010-09-16 2010-05-29 2010-05-05 2010-03-29 2010-03-23 2015-12-03 </code></pre> <p>For some reason, the last post is the one that I just added. I really cannot find the reason for this problem's existence... What am I doing wrong?</p> <p>EDIT: Changed the custom field from <code>date</code> to <code>tq_event_date</code> but still didn't work.</p>
[ { "answer_id": 212135, "author": "Craig", "author_id": 85474, "author_profile": "https://wordpress.stackexchange.com/users/85474", "pm_score": 1, "selected": false, "text": "<p>The category templates are just for post archives listing you would need to do this within the single.php template.</p>\n\n<p>You can use has_category()within the single.php template to detect if the post has the category. Then just include different files. eg:</p>\n\n<pre><code>if ( has_category( $category, $post ) ) {\n include \"template-one.php\";\n} else {\n include \"template-two.php\";\n}\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/has_category\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/has_category</a></p>\n" }, { "answer_id": 212137, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so <code>single-{$category}.php</code> does not exist. </p>\n\n<p>To make <code>single-{$category}.php</code> work, we can make use of the <code>single_template</code> filter</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n global $post;\n // Check if our post has our specific category\n if ( !has_category( 1, $post ) ) // Change to your specific category\n return $template;\n\n // Locate and load our single-{$category}.php template\n $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name\n if ( !$locate_template ) \n return $template;\n\n // single-my_category.php exists, load it\n return $locate_template;\n});\n</code></pre>\n\n<p>You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67305/" ]
I am using Wordpress with Advanced Custom Fields. I have a custom post called "event" with a custom field "date" (I have added the field through ACF). The date field is formatted in the following way: "yyyy-mm-dd." Until now, sorting the custom posts worked fine using the following snippet: ``` $query = new WP_Query([ 'post_type' => 'event', 'meta_key' => 'tq_event_date', 'meta_value' => date('Y-m-d'), 'meta_compare' => '<', 'orderby' => ['meta_key' => 'tq_event_date'], 'posts_per_page' => '-1' ]); if($query->have_posts()) { $posts = $query->get_posts(); foreach($posts as $post) { echo get_field('tq_event_date', $post->ID). ' '; } } ``` Now I have added a new event post with date "2015-12-03." The sorting for some reason does not sort this post. Here are the results of this query: ``` 2015-08-15 2015-07-15 2015-06-02 2015-05-18 2015-04-21 2015-04-18 2015-04-17 2015-04-02 2015-03-28 2014-11-25 2014-07-14 2014-07-04 2014-06-08 2014-05-31 2014-04-25 2014-04-26 2014-03-14 2014-03-15 2014-02-23 2014-02-23 2013-12-16 2013-11-19 2013-11-12 2013-07-24 2013-06-09 2013-05-12 2013-04-26 2013-04-19 2013-04-10 2013-04-05 2012-12-08 2012-11-02 2012-10-22 2012-10-09 2012-10-07 2012-06-23 2012-03-07 2012-02-12 2012-02-07 2011-06-18 2011-05-26 2011-04-30 2011-04-06 2011-02-26 2011-02-11 2011-01-28 2010-12-28 2010-11-22 2010-10-30 2010-10-16 2010-09-16 2010-05-29 2010-05-05 2010-03-29 2010-03-23 2015-12-03 ``` For some reason, the last post is the one that I just added. I really cannot find the reason for this problem's existence... What am I doing wrong? EDIT: Changed the custom field from `date` to `tq_event_date` but still didn't work.
I believe you are talking about single post pages. The template hierarchy does not make provision for single templates according to the category a post belongs to, so `single-{$category}.php` does not exist. To make `single-{$category}.php` work, we can make use of the `single_template` filter ``` add_filter( 'single_template', function ( $template ) { global $post; // Check if our post has our specific category if ( !has_category( 1, $post ) ) // Change to your specific category return $template; // Locate and load our single-{$category}.php template $locate_template = locate_template( 'single-my_category.php' ); // Change to your exact template name if ( !$locate_template ) return $template; // single-my_category.php exists, load it return $locate_template; }); ``` You can now just create our own custom single template and use it for any single post that belongs to the specific category you need to target
212,155
<p>I have a form on wordpress page with a <code>POST</code> method. I need to add an extra field to the form after submission but before it is sent to the URL in the action attribute. </p> <p>I was thinking to use an actin hook, not sure which one would be the best for this case? or if it's the correct tool in the first place?</p> <p>Thank you</p> <p><strong>Edit</strong><br> The form data is going to an e-banking service. the bank requires an extra field which is the hash value of all the variables concatenated together. the bank does the same operation when they receive a submission and compare with the extra field to ensure data integrity.</p>
[ { "answer_id": 212162, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 3, "selected": true, "text": "<p>Im not entirely sure there is such action hook for custom forms (someone else might know) but there are definately other ways if form is submitted <em>normally</em>, without ajax.</p>\n\n<p>Let me know if you have any questions.</p>\n\n<pre><code>//This applies if you want it to happen only if form is submited and page refreshed\n//It doesn't work if user comes back later - there's no extra field later on\n\n$form_submitted = false;\n\n//If submit is pressed\nif( isset( $_POST['submit'] ) ) {\n\n //There should also be a nonce check here\n\n $form_submitted = true; \n}\n\n//All your form html here\n\n//Check if form is submitted\nif ( $form_submitted ) {\n\n //Show your extra fields\n}\n\n\n\n/*If you want it to be a bit more \"permanent\"\n\n1. update_usermeta() to save the bool that user has submitted the form - logged-in users only\n2. Use cookies which might not work properly in browser \"stealth mode\" and is gone if user deletes browser history with cookies \n3. Use sessions which destroys itselves if user closes the browser\n\n*/\n</code></pre>\n" }, { "answer_id": 212164, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 1, "selected": false, "text": "<p>Form submission is all client-side, there will not be a hook in WordPress that will handle this. Best bet is to use jQuery to trap the #element.submit() action, then populate a hidden field on your form with whatever data you need.</p>\n\n<p>Note that you will have to utilize the preventDefault() action in jQuery, to trap the actual form submission from happening. Do what you need to do, then have jQuery finally submit the form. Documentation is here:</p>\n\n<p><a href=\"https://api.jquery.com/submit/\" rel=\"nofollow\">https://api.jquery.com/submit/</a></p>\n\n<p>The example they show on that page is almost exactly what you are looking to do.</p>\n\n<p>This really is not a typical/usual situation, however (aside from input validation). You really should be doing your data manipulation on the server sided, after the form is posted back to the receiving .php code...</p>\n" }, { "answer_id": 212176, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>The only way to do this \"server side\" is to post the form to a script on your server then make a request to the bank from there. </p>\n\n<p><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">You would need to post to <code>admin-ajax.php</code></a>. There are numerous Q/As here explaining how to do that <a href=\"https://wordpress.stackexchange.com/a/108145/21376\">such as this one I wrote</a>.</p>\n\n<p>What I don't know are the <a href=\"https://www.pcisecuritystandards.org/\" rel=\"nofollow noreferrer\">PCI Standards</a> implications of doing that, and I am not about to start writing code for that reason.</p>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212155", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64116/" ]
I have a form on wordpress page with a `POST` method. I need to add an extra field to the form after submission but before it is sent to the URL in the action attribute. I was thinking to use an actin hook, not sure which one would be the best for this case? or if it's the correct tool in the first place? Thank you **Edit** The form data is going to an e-banking service. the bank requires an extra field which is the hash value of all the variables concatenated together. the bank does the same operation when they receive a submission and compare with the extra field to ensure data integrity.
Im not entirely sure there is such action hook for custom forms (someone else might know) but there are definately other ways if form is submitted *normally*, without ajax. Let me know if you have any questions. ``` //This applies if you want it to happen only if form is submited and page refreshed //It doesn't work if user comes back later - there's no extra field later on $form_submitted = false; //If submit is pressed if( isset( $_POST['submit'] ) ) { //There should also be a nonce check here $form_submitted = true; } //All your form html here //Check if form is submitted if ( $form_submitted ) { //Show your extra fields } /*If you want it to be a bit more "permanent" 1. update_usermeta() to save the bool that user has submitted the form - logged-in users only 2. Use cookies which might not work properly in browser "stealth mode" and is gone if user deletes browser history with cookies 3. Use sessions which destroys itselves if user closes the browser */ ```
212,190
<p>Im storing using add_user_meta custom values that get sent to the front page of the website. Here is the php code.</p> <pre><code>$user_query = new WP_User_Query( array( 'fields' =&gt; 'ID' ) ); $user_ids = $user_query-&gt;get_results(); foreach( $user_object-&gt;_custom_link as $user_id ) { $user_object = get_userdata( $user_ids ); echo '&lt;li class="quick-link custom"&gt;&lt;img src="http://compass/wp-content/uploads/2015/12/add-icon.png" /&gt;&lt;h2&gt;&lt;a href="'.$user_object-&gt;_custom_link.'"&gt;Custom Link&lt;/a&gt;&lt;/h2&gt;&lt;/li&gt;'; } </code></pre> <p>When everything generates, only one meta value is returned, but multiple values can be stored.<a href="https://i.stack.imgur.com/YKtZC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YKtZC.png" alt="enter image description here"></a></p> <p>My question is, right now my loops is checking ID only, im not entirely sure how to get it to check id, then check how many meta_keys of _custom_link there are. <a href="https://i.stack.imgur.com/adRrQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/adRrQ.png" alt="enter image description here"></a> </p> <p>This shows that only one meta_key is being returned. ALso if you have a better method that would be greatly appreciated. </p>
[ { "answer_id": 212201, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Here is an example of getting the user IDs, looping through each, grabbing a meta_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys.</p>\n\n<pre><code>$user_query = new WP_User_Query( array( 'fields' =&gt; 'ID' ));\n$user_ids = $user_query-&gt;get_results();\n\necho \"&lt;ul&gt;\";\n\nforeach ( $user_ids as $user_id ) {\n\n // all meta for user\n $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) );\n\n echo \"&lt;pre&gt;\";\n print_r ( $all_meta_for_user ); // see all the values\n echo \"&lt;/pre&gt;\";\n\n $key = '__TEST_KEY';\n $value_set = array();\n if( isset( $all_meta_for_user [ $key ] )) {\n $value_set = get_user_meta ( $user_id, $key, true );\n if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array\n }\n\n // add to existing values\n $value_set[] = timer_stop(4);\n\n // remove old items\n if( count ($value_set) &gt; 4 ) array_shift ($value_set);\n\n // set the meta\n update_user_meta($user_id, $key, $value_set );\n\n // LATEST VALUES\n $value_set = get_user_meta ( $user_id, $key, true );\n\n echo \"&lt;pre&gt;\";\n print_r ( $value_set ); // the value set currently in our meta\n echo \"&lt;/pre&gt;\";\n\n foreach ( $value_set as $inx =&gt; $value ){\n echo \"&lt;li&gt;{$user_id} - {$key} - {$inx} - {$value}&lt;/li&gt;\";\n }\n echo \"&lt;/ul&gt;\";\n}\n\necho \"&lt;/ul&gt;\";\n</code></pre>\n" }, { "answer_id": 261675, "author": "DiBritto", "author_id": 116109, "author_profile": "https://wordpress.stackexchange.com/users/116109", "pm_score": 0, "selected": false, "text": "<p>I was a long time looking for a solution to this type of query in wp_usermeta and now I can sort the values for each registered user creating a query and making use of a LEFT JOIN using the wpdb class, I know that this post is a bit outdated but I felt compelled to share my script because your post makes me persist until I find a solution, I hope it can help.</p>\n\n<pre><code>&lt;?php\n $sql_query =&lt;&lt;&lt;SQL\n SELECT\n {$wpdb-&gt;users}.user_email,\n {$wpdb-&gt;users}.user_nicename,\n {$wpdb-&gt;usermeta}.meta_value\n FROM\n {$wpdb-&gt;users}\n LEFT JOIN {$wpdb-&gt;usermeta} ON {$wpdb-&gt;users}.ID = {$wpdb-&gt;usermeta}.user_id\n WHERE 1=1\n AND {$wpdb-&gt;users}.user_status = '0'\n AND {$wpdb-&gt;usermeta}.meta_key = 'ma_deposito'\n /* AND {$wpdb-&gt;usermeta}.meta_value = '50'// busca meta_value pelo valor*/ \n SQL;\n $users = $wpdb-&gt;get_results($sql_query);\n //header('Content-type:text/plain');\n // print_r($usersemails);\n foreach ( $users as $indce =&gt; $valor ) :\n echo 'Apelido: '. $valor-&gt;user_nicename . ' - E-mail: '. $valor-&gt;user_email. ' - Valor: '. $valor-&gt;meta_value.'&lt;br /&gt;';\n endforeach;\n ?&gt;\n</code></pre>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65437/" ]
Im storing using add\_user\_meta custom values that get sent to the front page of the website. Here is the php code. ``` $user_query = new WP_User_Query( array( 'fields' => 'ID' ) ); $user_ids = $user_query->get_results(); foreach( $user_object->_custom_link as $user_id ) { $user_object = get_userdata( $user_ids ); echo '<li class="quick-link custom"><img src="http://compass/wp-content/uploads/2015/12/add-icon.png" /><h2><a href="'.$user_object->_custom_link.'">Custom Link</a></h2></li>'; } ``` When everything generates, only one meta value is returned, but multiple values can be stored.[![enter image description here](https://i.stack.imgur.com/YKtZC.png)](https://i.stack.imgur.com/YKtZC.png) My question is, right now my loops is checking ID only, im not entirely sure how to get it to check id, then check how many meta\_keys of \_custom\_link there are. [![enter image description here](https://i.stack.imgur.com/adRrQ.png)](https://i.stack.imgur.com/adRrQ.png) This shows that only one meta\_key is being returned. ALso if you have a better method that would be greatly appreciated.
Here is an example of getting the user IDs, looping through each, grabbing a meta\_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys. ``` $user_query = new WP_User_Query( array( 'fields' => 'ID' )); $user_ids = $user_query->get_results(); echo "<ul>"; foreach ( $user_ids as $user_id ) { // all meta for user $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) ); echo "<pre>"; print_r ( $all_meta_for_user ); // see all the values echo "</pre>"; $key = '__TEST_KEY'; $value_set = array(); if( isset( $all_meta_for_user [ $key ] )) { $value_set = get_user_meta ( $user_id, $key, true ); if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array } // add to existing values $value_set[] = timer_stop(4); // remove old items if( count ($value_set) > 4 ) array_shift ($value_set); // set the meta update_user_meta($user_id, $key, $value_set ); // LATEST VALUES $value_set = get_user_meta ( $user_id, $key, true ); echo "<pre>"; print_r ( $value_set ); // the value set currently in our meta echo "</pre>"; foreach ( $value_set as $inx => $value ){ echo "<li>{$user_id} - {$key} - {$inx} - {$value}</li>"; } echo "</ul>"; } echo "</ul>"; ```
212,202
<p>We have a custom plugin we have created for a customer, it simply configures a custom post type.</p> <p>They upgraded to wp 4.4 today. Now that custom post type is the only one that you cannot add a new post for.I can edit a custom post with out issue and I can add the standard posts and other custom post types created with a third party plugin.</p> <p>I have uploaded the plugin to a clean install of 4.4 with a default theme and it still has the issue. </p> <p>My custom post has the capabilities of 'post'. All I get once logged in is "Submit for Review". If you fill out the form and click the "submit for review" button then you get the message "You are not allowed to edit this post."</p> <p>Here is the custom post declaration:</p> <pre><code>$args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_icon' =&gt; plugins_url( 'images/image.png', __FILE__ ), 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array('') ); register_post_type( 'new_post_type' , $args ); </code></pre> <p>I have double checked the DB has the right primary keys and auto increment too.</p> <p>I have even tried creating new users and I have installed plugins to check the role capabilities which all look fine.</p> <p>Any thoughts on how to diagnose?</p> <p><strong>Update</strong> I believe that the capabilities are correct. After changing core WordPress file to retrieve the post type via query string rather than the blank new post object it passes around the correct info appeared.</p> <p>The problem seems to be when you click the add new button in the main navigation WordPress creates a blank post in the DB, this does not persist for some reason. As a result I get a post id of 0 returned rather than the next incremented id I should have. </p> <p>This means that when it tries to pull out the meta info for id 0 it does not have the post type it is returned as '', therefore when it tries to get the capabilities for '' it fails and puts the form into the simplest view "submit for review".</p>
[ { "answer_id": 212201, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Here is an example of getting the user IDs, looping through each, grabbing a meta_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys.</p>\n\n<pre><code>$user_query = new WP_User_Query( array( 'fields' =&gt; 'ID' ));\n$user_ids = $user_query-&gt;get_results();\n\necho \"&lt;ul&gt;\";\n\nforeach ( $user_ids as $user_id ) {\n\n // all meta for user\n $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) );\n\n echo \"&lt;pre&gt;\";\n print_r ( $all_meta_for_user ); // see all the values\n echo \"&lt;/pre&gt;\";\n\n $key = '__TEST_KEY';\n $value_set = array();\n if( isset( $all_meta_for_user [ $key ] )) {\n $value_set = get_user_meta ( $user_id, $key, true );\n if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array\n }\n\n // add to existing values\n $value_set[] = timer_stop(4);\n\n // remove old items\n if( count ($value_set) &gt; 4 ) array_shift ($value_set);\n\n // set the meta\n update_user_meta($user_id, $key, $value_set );\n\n // LATEST VALUES\n $value_set = get_user_meta ( $user_id, $key, true );\n\n echo \"&lt;pre&gt;\";\n print_r ( $value_set ); // the value set currently in our meta\n echo \"&lt;/pre&gt;\";\n\n foreach ( $value_set as $inx =&gt; $value ){\n echo \"&lt;li&gt;{$user_id} - {$key} - {$inx} - {$value}&lt;/li&gt;\";\n }\n echo \"&lt;/ul&gt;\";\n}\n\necho \"&lt;/ul&gt;\";\n</code></pre>\n" }, { "answer_id": 261675, "author": "DiBritto", "author_id": 116109, "author_profile": "https://wordpress.stackexchange.com/users/116109", "pm_score": 0, "selected": false, "text": "<p>I was a long time looking for a solution to this type of query in wp_usermeta and now I can sort the values for each registered user creating a query and making use of a LEFT JOIN using the wpdb class, I know that this post is a bit outdated but I felt compelled to share my script because your post makes me persist until I find a solution, I hope it can help.</p>\n\n<pre><code>&lt;?php\n $sql_query =&lt;&lt;&lt;SQL\n SELECT\n {$wpdb-&gt;users}.user_email,\n {$wpdb-&gt;users}.user_nicename,\n {$wpdb-&gt;usermeta}.meta_value\n FROM\n {$wpdb-&gt;users}\n LEFT JOIN {$wpdb-&gt;usermeta} ON {$wpdb-&gt;users}.ID = {$wpdb-&gt;usermeta}.user_id\n WHERE 1=1\n AND {$wpdb-&gt;users}.user_status = '0'\n AND {$wpdb-&gt;usermeta}.meta_key = 'ma_deposito'\n /* AND {$wpdb-&gt;usermeta}.meta_value = '50'// busca meta_value pelo valor*/ \n SQL;\n $users = $wpdb-&gt;get_results($sql_query);\n //header('Content-type:text/plain');\n // print_r($usersemails);\n foreach ( $users as $indce =&gt; $valor ) :\n echo 'Apelido: '. $valor-&gt;user_nicename . ' - E-mail: '. $valor-&gt;user_email. ' - Valor: '. $valor-&gt;meta_value.'&lt;br /&gt;';\n endforeach;\n ?&gt;\n</code></pre>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212202", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85501/" ]
We have a custom plugin we have created for a customer, it simply configures a custom post type. They upgraded to wp 4.4 today. Now that custom post type is the only one that you cannot add a new post for.I can edit a custom post with out issue and I can add the standard posts and other custom post types created with a third party plugin. I have uploaded the plugin to a clean install of 4.4 with a default theme and it still has the issue. My custom post has the capabilities of 'post'. All I get once logged in is "Submit for Review". If you fill out the form and click the "submit for review" button then you get the message "You are not allowed to edit this post." Here is the custom post declaration: ``` $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'menu_icon' => plugins_url( 'images/image.png', __FILE__ ), 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('') ); register_post_type( 'new_post_type' , $args ); ``` I have double checked the DB has the right primary keys and auto increment too. I have even tried creating new users and I have installed plugins to check the role capabilities which all look fine. Any thoughts on how to diagnose? **Update** I believe that the capabilities are correct. After changing core WordPress file to retrieve the post type via query string rather than the blank new post object it passes around the correct info appeared. The problem seems to be when you click the add new button in the main navigation WordPress creates a blank post in the DB, this does not persist for some reason. As a result I get a post id of 0 returned rather than the next incremented id I should have. This means that when it tries to pull out the meta info for id 0 it does not have the post type it is returned as '', therefore when it tries to get the capabilities for '' it fails and puts the form into the simplest view "submit for review".
Here is an example of getting the user IDs, looping through each, grabbing a meta\_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys. ``` $user_query = new WP_User_Query( array( 'fields' => 'ID' )); $user_ids = $user_query->get_results(); echo "<ul>"; foreach ( $user_ids as $user_id ) { // all meta for user $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) ); echo "<pre>"; print_r ( $all_meta_for_user ); // see all the values echo "</pre>"; $key = '__TEST_KEY'; $value_set = array(); if( isset( $all_meta_for_user [ $key ] )) { $value_set = get_user_meta ( $user_id, $key, true ); if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array } // add to existing values $value_set[] = timer_stop(4); // remove old items if( count ($value_set) > 4 ) array_shift ($value_set); // set the meta update_user_meta($user_id, $key, $value_set ); // LATEST VALUES $value_set = get_user_meta ( $user_id, $key, true ); echo "<pre>"; print_r ( $value_set ); // the value set currently in our meta echo "</pre>"; foreach ( $value_set as $inx => $value ){ echo "<li>{$user_id} - {$key} - {$inx} - {$value}</li>"; } echo "</ul>"; } echo "</ul>"; ```
212,203
<p>I used to have my website hosted through Godaddy and 4 months ago something weird started happening. Every time that I would make changes to my site, it wouldn't show up on the live website. The only exception was the homepage. Every change on the homepage would show up on the live website.</p> <p>I did what everyone then told me to do, which was to flush the caches, tell Godaddy to flush their server's caches etc... The usual protocol. But nothing happened. So I then copied the content from the pages that weren't updating and I created new pages with the same content as the old pages. And these pages showed up on the live website perfectly. So I figured that I had found a solution to this problem.</p> <p>Now, a couple of months later, I wanted to switch to a new server because as everyone knows, Godaddy's shared hosting system can really slow down your website. So I had my website switched to DigitalOcean a few days ago. But now, the same problem has started all over again. </p> <p>The thing is, now the Homepage along with the entire site doesn't even show the new changes anymore, and the live website is showing the exact same website that it was showing 4 months ago. On the backend of my Wordpress site, everything is the way that it's supposed to be. The pages are the way that they are supposed to look, but every time that I click Update Page, it never updates to my new website.</p> <p>This problem can't be on the server side, as my site has been switched to a new server and this problem still persists. I really need help with this and would greatly appreciate it if anyone could help me out.</p> <p>Thank you all so very much in advance!</p>
[ { "answer_id": 212201, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Here is an example of getting the user IDs, looping through each, grabbing a meta_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys.</p>\n\n<pre><code>$user_query = new WP_User_Query( array( 'fields' =&gt; 'ID' ));\n$user_ids = $user_query-&gt;get_results();\n\necho \"&lt;ul&gt;\";\n\nforeach ( $user_ids as $user_id ) {\n\n // all meta for user\n $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) );\n\n echo \"&lt;pre&gt;\";\n print_r ( $all_meta_for_user ); // see all the values\n echo \"&lt;/pre&gt;\";\n\n $key = '__TEST_KEY';\n $value_set = array();\n if( isset( $all_meta_for_user [ $key ] )) {\n $value_set = get_user_meta ( $user_id, $key, true );\n if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array\n }\n\n // add to existing values\n $value_set[] = timer_stop(4);\n\n // remove old items\n if( count ($value_set) &gt; 4 ) array_shift ($value_set);\n\n // set the meta\n update_user_meta($user_id, $key, $value_set );\n\n // LATEST VALUES\n $value_set = get_user_meta ( $user_id, $key, true );\n\n echo \"&lt;pre&gt;\";\n print_r ( $value_set ); // the value set currently in our meta\n echo \"&lt;/pre&gt;\";\n\n foreach ( $value_set as $inx =&gt; $value ){\n echo \"&lt;li&gt;{$user_id} - {$key} - {$inx} - {$value}&lt;/li&gt;\";\n }\n echo \"&lt;/ul&gt;\";\n}\n\necho \"&lt;/ul&gt;\";\n</code></pre>\n" }, { "answer_id": 261675, "author": "DiBritto", "author_id": 116109, "author_profile": "https://wordpress.stackexchange.com/users/116109", "pm_score": 0, "selected": false, "text": "<p>I was a long time looking for a solution to this type of query in wp_usermeta and now I can sort the values for each registered user creating a query and making use of a LEFT JOIN using the wpdb class, I know that this post is a bit outdated but I felt compelled to share my script because your post makes me persist until I find a solution, I hope it can help.</p>\n\n<pre><code>&lt;?php\n $sql_query =&lt;&lt;&lt;SQL\n SELECT\n {$wpdb-&gt;users}.user_email,\n {$wpdb-&gt;users}.user_nicename,\n {$wpdb-&gt;usermeta}.meta_value\n FROM\n {$wpdb-&gt;users}\n LEFT JOIN {$wpdb-&gt;usermeta} ON {$wpdb-&gt;users}.ID = {$wpdb-&gt;usermeta}.user_id\n WHERE 1=1\n AND {$wpdb-&gt;users}.user_status = '0'\n AND {$wpdb-&gt;usermeta}.meta_key = 'ma_deposito'\n /* AND {$wpdb-&gt;usermeta}.meta_value = '50'// busca meta_value pelo valor*/ \n SQL;\n $users = $wpdb-&gt;get_results($sql_query);\n //header('Content-type:text/plain');\n // print_r($usersemails);\n foreach ( $users as $indce =&gt; $valor ) :\n echo 'Apelido: '. $valor-&gt;user_nicename . ' - E-mail: '. $valor-&gt;user_email. ' - Valor: '. $valor-&gt;meta_value.'&lt;br /&gt;';\n endforeach;\n ?&gt;\n</code></pre>\n" } ]
2015/12/17
[ "https://wordpress.stackexchange.com/questions/212203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85502/" ]
I used to have my website hosted through Godaddy and 4 months ago something weird started happening. Every time that I would make changes to my site, it wouldn't show up on the live website. The only exception was the homepage. Every change on the homepage would show up on the live website. I did what everyone then told me to do, which was to flush the caches, tell Godaddy to flush their server's caches etc... The usual protocol. But nothing happened. So I then copied the content from the pages that weren't updating and I created new pages with the same content as the old pages. And these pages showed up on the live website perfectly. So I figured that I had found a solution to this problem. Now, a couple of months later, I wanted to switch to a new server because as everyone knows, Godaddy's shared hosting system can really slow down your website. So I had my website switched to DigitalOcean a few days ago. But now, the same problem has started all over again. The thing is, now the Homepage along with the entire site doesn't even show the new changes anymore, and the live website is showing the exact same website that it was showing 4 months ago. On the backend of my Wordpress site, everything is the way that it's supposed to be. The pages are the way that they are supposed to look, but every time that I click Update Page, it never updates to my new website. This problem can't be on the server side, as my site has been switched to a new server and this problem still persists. I really need help with this and would greatly appreciate it if anyone could help me out. Thank you all so very much in advance!
Here is an example of getting the user IDs, looping through each, grabbing a meta\_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys. ``` $user_query = new WP_User_Query( array( 'fields' => 'ID' )); $user_ids = $user_query->get_results(); echo "<ul>"; foreach ( $user_ids as $user_id ) { // all meta for user $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) ); echo "<pre>"; print_r ( $all_meta_for_user ); // see all the values echo "</pre>"; $key = '__TEST_KEY'; $value_set = array(); if( isset( $all_meta_for_user [ $key ] )) { $value_set = get_user_meta ( $user_id, $key, true ); if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array } // add to existing values $value_set[] = timer_stop(4); // remove old items if( count ($value_set) > 4 ) array_shift ($value_set); // set the meta update_user_meta($user_id, $key, $value_set ); // LATEST VALUES $value_set = get_user_meta ( $user_id, $key, true ); echo "<pre>"; print_r ( $value_set ); // the value set currently in our meta echo "</pre>"; foreach ( $value_set as $inx => $value ){ echo "<li>{$user_id} - {$key} - {$inx} - {$value}</li>"; } echo "</ul>"; } echo "</ul>"; ```
212,239
<p>I'm hosting a WP site on a VPN so I'm doing all of the server management. A while back, I simply renamed my WP folder so that it would be inaccessible. Now I need it to be accessible again and so I renamed it to what it was before. For some reason the site is now extremely slow. As you can see in this screenshot, the server spends about 5 minutes doing who knows what before returning anything. </p> <p><a href="https://i.stack.imgur.com/M1yWo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M1yWo.png" alt="enter image description here"></a></p> <p>Here is the .htaccess file within my /blog/ directory:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I have tried to disable the plugins by renaming the <code>/plugins/</code> directory to <code>/plugins.hold/</code> with no success. Still, though. Any idea why the theme could be causing this issue? It would be nice to have the theme working again!</p> <p>I have tried to look at the apache error logs and nothing suspect seems to show up at the warning level. I also looked at my .htaccess files and didn't find anything out of the ordinary (as far as I know, the WP files have not been modified at all). The site does use HTTPS so I wonder if it has to do with changes that may have been made while the WP site was not being used. I'm thinking this is more of an Apache config problem, but any insight as to how I can debug this would be much appreciated. If you need me to post more info I will happily do so.</p> <p><strong>UPDATE 1</strong></p> <p>It seems to be a problem with my current theme, Salient. Once I switched to another theme, the site appears to load normally. </p>
[ { "answer_id": 212739, "author": "winters", "author_id": 85752, "author_profile": "https://wordpress.stackexchange.com/users/85752", "pm_score": 0, "selected": false, "text": "<p>This may be a stretch but I've had a similar problem in the past, for me it was connected to caching. I would of just posted this as a comment but I don't have the rep yet.</p>\n\n<p>Make sure if you had/have any old cache, it has been purged. Also depending on your cache plugin it may of inserted code that has been left behind or reinserted a double snippet into your template files.</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 325828, "author": "Arturo Gallegos", "author_id": 130585, "author_profile": "https://wordpress.stackexchange.com/users/130585", "pm_score": 1, "selected": false, "text": "<p>The problem is the amount of processes that your site has to carry out before being able to deliver the content, in this particular case to generate the HTML code and be able to dispatch it.</p>\n\n<p>It is a fairly common problem among predesigned plugins and templates, even if they are paid they have this problem ... together the problems that many drag when using editors as \"visual composer\"</p>\n\n<p>The immediate solution is to install some plugin for cache and to merge CSS and JS files</p>\n\n<p><a href=\"https://es.wordpress.org/plugins/merge-minify-refresh/\" rel=\"nofollow noreferrer\">merge-minify-refresh</a></p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-super-cache/\" rel=\"nofollow noreferrer\">wp-super-cache</a></p>\n\n<p>In the long run it would be convenient to replace the template</p>\n" } ]
2015/12/18
[ "https://wordpress.stackexchange.com/questions/212239", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85514/" ]
I'm hosting a WP site on a VPN so I'm doing all of the server management. A while back, I simply renamed my WP folder so that it would be inaccessible. Now I need it to be accessible again and so I renamed it to what it was before. For some reason the site is now extremely slow. As you can see in this screenshot, the server spends about 5 minutes doing who knows what before returning anything. [![enter image description here](https://i.stack.imgur.com/M1yWo.png)](https://i.stack.imgur.com/M1yWo.png) Here is the .htaccess file within my /blog/ directory: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule> # END WordPress ``` I have tried to disable the plugins by renaming the `/plugins/` directory to `/plugins.hold/` with no success. Still, though. Any idea why the theme could be causing this issue? It would be nice to have the theme working again! I have tried to look at the apache error logs and nothing suspect seems to show up at the warning level. I also looked at my .htaccess files and didn't find anything out of the ordinary (as far as I know, the WP files have not been modified at all). The site does use HTTPS so I wonder if it has to do with changes that may have been made while the WP site was not being used. I'm thinking this is more of an Apache config problem, but any insight as to how I can debug this would be much appreciated. If you need me to post more info I will happily do so. **UPDATE 1** It seems to be a problem with my current theme, Salient. Once I switched to another theme, the site appears to load normally.
The problem is the amount of processes that your site has to carry out before being able to deliver the content, in this particular case to generate the HTML code and be able to dispatch it. It is a fairly common problem among predesigned plugins and templates, even if they are paid they have this problem ... together the problems that many drag when using editors as "visual composer" The immediate solution is to install some plugin for cache and to merge CSS and JS files [merge-minify-refresh](https://es.wordpress.org/plugins/merge-minify-refresh/) [wp-super-cache](https://wordpress.org/plugins/wp-super-cache/) In the long run it would be convenient to replace the template