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
261,307
<p>I'm going to be setting up a custom post type on a site (for job vacancies) and I'm going to create a separate menu item on the site's main nav using categories, and i'll use a 'jobs' category to effectively have the jobs menu item running as a second blog.</p> <p>What i would like is to have it so when the client adds a job in the back end, the created post under this custom-post-type automatically has the category 'jobs' applied to it, regardless of any additional categories they use – so the posted jobs automatically get added to this menu item in the front end. </p> <p>Is there a way of automatically adding a category to a custom-post-type? And also having it so any post with the category 'jobs' doesn't then show on the main blog page (which is going to be a news and market info page).</p> <p>Any help would be awesome.</p> <p>Emily</p>
[ { "answer_id": 261308, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 2, "selected": false, "text": "<p>To answer the first question (pre-populate a CPT with a Cat) you could add following function to functions.php .<em>(make backup first svp)</em></p>\n\n<p>In the code below <em>movies</em> is the Custom Post Type and <em>horror</em> is the Category.<br />\nPlease change to own preferences.</p>\n\n<pre><code>/**\n * Set a Category on Custom Post Type\n * \n * Read more: {@link https://developer.wordpress.org/reference/functions/get_post_type/}\n * {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug}\n * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms}\n * \n */\nadd_action( 'save_post', 'wpse261307_set_cat_on_cpt' );\nfunction wpse261307_set_cat_on_cpt( $post_id )\n{\n global $wpdb;\n\n // Check for correct post type\n if ( get_post_type() == 'movies' ) // Set post or custom-post type name here\n { \n // Find the Category by slug\n $idObj = get_category_by_slug( 'horror' ); // Set your Category here\n // Get the Category ID\n $id = $idObj-&gt;term_id;\n\n // Set now the Category for this CPT\n wp_set_object_terms( $post_id, $id, 'category', true );\n }\n\n}// end function\n</code></pre>\n\n<p>--</p>\n\n<p><em>I would then make a function which hides the meta-box in the back-end for this specific CPT. (so no one can add/change the category, but that is only useful when you use only 1 category pro posting)</em></p>\n\n<p>--</p>\n\n<p>Then you will need to make a function which hide this specific CPT to be shown on the main blog page. <em>(by using a query to exclude the category ' jobs' on the main blog page)</em> .<br /></p>\n\n<pre><code>/**\n * Exclude CPT with Cat jobs on Landing page\n *\n * Read more: {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug}\n * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms}\n * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_categories_on_your_main_page}\n * {@link https://codex.wordpress.org/Function_Reference/is_main_query#Examples}\n */\nadd_action( 'pre_get_posts', 'wpse261307_exclude_cat_main_blog' );\nfunction wpse261307_exclude_cat_main_blog( $query )\n{ \n global $wpdb;\n\n // Find the Category by slug\n $idObj = get_category_by_slug( 'horror' );\n // Get the Category ID\n $id = $idObj-&gt;term_id;\n\n if ( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n\n $query-&gt;set( 'cat', -$id );\n }\n\n} // end function\n</code></pre>\n\n<p>Hope this helps you on your way.</p>\n\n<blockquote>\n <p>Note:<br />\n • Add this to a home brew plugin or in a <code>myfunctions.php</code> in the <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">wp-content/mu-plugins</a> folder <em>(which you have to create yourself)</em><br />\n • Imho the most solid solution to be sure nothing get lost <em>(meaning out of sight because it still is in your database)</em> when changing to another theme. <em>(changes made directly in a <code>template</code> file are not anymore visible when you change to another theme)</em><br />\n • Btw, the same <em>(adding them into a myfunctions.php file in the <code>wp-content/mu-plugins</code> folder)</em> I would do for creating Custom Post Types.</p>\n</blockquote>\n\n<p><em>Ps, to clarify why I am not a fan of using <code>id</code> numbers directly:</em><br /></p>\n\n<ul>\n<li>It happens that a category is deleted for whatever reason and afterwards it seems a mistake and the same category needs to be created again.</li>\n<li>When a new category is created <em>(even with the same name)</em> it will get another <code>id</code> number and then <em>(when you use the number itself directly in any code)</em> your functions are not working anymore because of the wrong <code>id</code> number.</li>\n</ul>\n" }, { "answer_id": 261310, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>Auto adding a category to a custom post type was already asked and answered <a href=\"https://wordpress.stackexchange.com/questions/208433/automatic-category-for-a-custom-post-type\">here</a>.</p>\n\n<p>As for excluding it, then you need to write a custom <code>WP_Query</code>:</p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'post',\n 'cat' =&gt; -1,\n);\n\n$fp_query = new WP_Query( $args )\n// The Loop\nif ( $fp_query-&gt;have_posts() ) {\n // Loop Code for Posts\n wp_reset_postdata();\n} else {\n // No Posts Found Code\n}\n</code></pre>\n\n<p>You would change the <code>1</code> to whatever number the Category ID for <code>jobs</code> is but keep it negative as this triggers an exclusion.</p>\n" } ]
2017/03/25
[ "https://wordpress.stackexchange.com/questions/261307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I'm going to be setting up a custom post type on a site (for job vacancies) and I'm going to create a separate menu item on the site's main nav using categories, and i'll use a 'jobs' category to effectively have the jobs menu item running as a second blog. What i would like is to have it so when the client adds a job in the back end, the created post under this custom-post-type automatically has the category 'jobs' applied to it, regardless of any additional categories they use – so the posted jobs automatically get added to this menu item in the front end. Is there a way of automatically adding a category to a custom-post-type? And also having it so any post with the category 'jobs' doesn't then show on the main blog page (which is going to be a news and market info page). Any help would be awesome. Emily
To answer the first question (pre-populate a CPT with a Cat) you could add following function to functions.php .*(make backup first svp)* In the code below *movies* is the Custom Post Type and *horror* is the Category. Please change to own preferences. ``` /** * Set a Category on Custom Post Type * * Read more: {@link https://developer.wordpress.org/reference/functions/get_post_type/} * {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug} * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms} * */ add_action( 'save_post', 'wpse261307_set_cat_on_cpt' ); function wpse261307_set_cat_on_cpt( $post_id ) { global $wpdb; // Check for correct post type if ( get_post_type() == 'movies' ) // Set post or custom-post type name here { // Find the Category by slug $idObj = get_category_by_slug( 'horror' ); // Set your Category here // Get the Category ID $id = $idObj->term_id; // Set now the Category for this CPT wp_set_object_terms( $post_id, $id, 'category', true ); } }// end function ``` -- *I would then make a function which hides the meta-box in the back-end for this specific CPT. (so no one can add/change the category, but that is only useful when you use only 1 category pro posting)* -- Then you will need to make a function which hide this specific CPT to be shown on the main blog page. *(by using a query to exclude the category ' jobs' on the main blog page)* . ``` /** * Exclude CPT with Cat jobs on Landing page * * Read more: {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug} * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms} * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_categories_on_your_main_page} * {@link https://codex.wordpress.org/Function_Reference/is_main_query#Examples} */ add_action( 'pre_get_posts', 'wpse261307_exclude_cat_main_blog' ); function wpse261307_exclude_cat_main_blog( $query ) { global $wpdb; // Find the Category by slug $idObj = get_category_by_slug( 'horror' ); // Get the Category ID $id = $idObj->term_id; if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', -$id ); } } // end function ``` Hope this helps you on your way. > > Note: > > • Add this to a home brew plugin or in a `myfunctions.php` in the [wp-content/mu-plugins](https://codex.wordpress.org/Must_Use_Plugins) folder *(which you have to create yourself)* > > • Imho the most solid solution to be sure nothing get lost *(meaning out of sight because it still is in your database)* when changing to another theme. *(changes made directly in a `template` file are not anymore visible when you change to another theme)* > > • Btw, the same *(adding them into a myfunctions.php file in the `wp-content/mu-plugins` folder)* I would do for creating Custom Post Types. > > > *Ps, to clarify why I am not a fan of using `id` numbers directly:* * It happens that a category is deleted for whatever reason and afterwards it seems a mistake and the same category needs to be created again. * When a new category is created *(even with the same name)* it will get another `id` number and then *(when you use the number itself directly in any code)* your functions are not working anymore because of the wrong `id` number.
261,313
<p>I have installed wordpress in the sub-directory /www/html/wordpress/ (and not at /www/html/) and the solution given here <a href="https://wordpress.stackexchange.com/questions/261080/how-to-get-rid-of-index-php/261089#261089">How to get rid of index.php</a> didn't work on this server.</p> <p>The solution suggests adding the following to .htaccess:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>and changing to 'AllowOverride ALL' in apache configuration.</p> <p>The solution worked for my other server where wordpress is installed at /www/html/ but not this one. Do you know why is that and how I can possibly fix it? (Apparently I should change the above code in .htaccess but I don't know how)</p>
[ { "answer_id": 261308, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 2, "selected": false, "text": "<p>To answer the first question (pre-populate a CPT with a Cat) you could add following function to functions.php .<em>(make backup first svp)</em></p>\n\n<p>In the code below <em>movies</em> is the Custom Post Type and <em>horror</em> is the Category.<br />\nPlease change to own preferences.</p>\n\n<pre><code>/**\n * Set a Category on Custom Post Type\n * \n * Read more: {@link https://developer.wordpress.org/reference/functions/get_post_type/}\n * {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug}\n * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms}\n * \n */\nadd_action( 'save_post', 'wpse261307_set_cat_on_cpt' );\nfunction wpse261307_set_cat_on_cpt( $post_id )\n{\n global $wpdb;\n\n // Check for correct post type\n if ( get_post_type() == 'movies' ) // Set post or custom-post type name here\n { \n // Find the Category by slug\n $idObj = get_category_by_slug( 'horror' ); // Set your Category here\n // Get the Category ID\n $id = $idObj-&gt;term_id;\n\n // Set now the Category for this CPT\n wp_set_object_terms( $post_id, $id, 'category', true );\n }\n\n}// end function\n</code></pre>\n\n<p>--</p>\n\n<p><em>I would then make a function which hides the meta-box in the back-end for this specific CPT. (so no one can add/change the category, but that is only useful when you use only 1 category pro posting)</em></p>\n\n<p>--</p>\n\n<p>Then you will need to make a function which hide this specific CPT to be shown on the main blog page. <em>(by using a query to exclude the category ' jobs' on the main blog page)</em> .<br /></p>\n\n<pre><code>/**\n * Exclude CPT with Cat jobs on Landing page\n *\n * Read more: {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug}\n * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms}\n * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_categories_on_your_main_page}\n * {@link https://codex.wordpress.org/Function_Reference/is_main_query#Examples}\n */\nadd_action( 'pre_get_posts', 'wpse261307_exclude_cat_main_blog' );\nfunction wpse261307_exclude_cat_main_blog( $query )\n{ \n global $wpdb;\n\n // Find the Category by slug\n $idObj = get_category_by_slug( 'horror' );\n // Get the Category ID\n $id = $idObj-&gt;term_id;\n\n if ( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n\n $query-&gt;set( 'cat', -$id );\n }\n\n} // end function\n</code></pre>\n\n<p>Hope this helps you on your way.</p>\n\n<blockquote>\n <p>Note:<br />\n • Add this to a home brew plugin or in a <code>myfunctions.php</code> in the <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">wp-content/mu-plugins</a> folder <em>(which you have to create yourself)</em><br />\n • Imho the most solid solution to be sure nothing get lost <em>(meaning out of sight because it still is in your database)</em> when changing to another theme. <em>(changes made directly in a <code>template</code> file are not anymore visible when you change to another theme)</em><br />\n • Btw, the same <em>(adding them into a myfunctions.php file in the <code>wp-content/mu-plugins</code> folder)</em> I would do for creating Custom Post Types.</p>\n</blockquote>\n\n<p><em>Ps, to clarify why I am not a fan of using <code>id</code> numbers directly:</em><br /></p>\n\n<ul>\n<li>It happens that a category is deleted for whatever reason and afterwards it seems a mistake and the same category needs to be created again.</li>\n<li>When a new category is created <em>(even with the same name)</em> it will get another <code>id</code> number and then <em>(when you use the number itself directly in any code)</em> your functions are not working anymore because of the wrong <code>id</code> number.</li>\n</ul>\n" }, { "answer_id": 261310, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>Auto adding a category to a custom post type was already asked and answered <a href=\"https://wordpress.stackexchange.com/questions/208433/automatic-category-for-a-custom-post-type\">here</a>.</p>\n\n<p>As for excluding it, then you need to write a custom <code>WP_Query</code>:</p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'post',\n 'cat' =&gt; -1,\n);\n\n$fp_query = new WP_Query( $args )\n// The Loop\nif ( $fp_query-&gt;have_posts() ) {\n // Loop Code for Posts\n wp_reset_postdata();\n} else {\n // No Posts Found Code\n}\n</code></pre>\n\n<p>You would change the <code>1</code> to whatever number the Category ID for <code>jobs</code> is but keep it negative as this triggers an exclusion.</p>\n" } ]
2017/03/25
[ "https://wordpress.stackexchange.com/questions/261313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116068/" ]
I have installed wordpress in the sub-directory /www/html/wordpress/ (and not at /www/html/) and the solution given here [How to get rid of index.php](https://wordpress.stackexchange.com/questions/261080/how-to-get-rid-of-index-php/261089#261089) didn't work on this server. The solution suggests adding the following to .htaccess: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` and changing to 'AllowOverride ALL' in apache configuration. The solution worked for my other server where wordpress is installed at /www/html/ but not this one. Do you know why is that and how I can possibly fix it? (Apparently I should change the above code in .htaccess but I don't know how)
To answer the first question (pre-populate a CPT with a Cat) you could add following function to functions.php .*(make backup first svp)* In the code below *movies* is the Custom Post Type and *horror* is the Category. Please change to own preferences. ``` /** * Set a Category on Custom Post Type * * Read more: {@link https://developer.wordpress.org/reference/functions/get_post_type/} * {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug} * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms} * */ add_action( 'save_post', 'wpse261307_set_cat_on_cpt' ); function wpse261307_set_cat_on_cpt( $post_id ) { global $wpdb; // Check for correct post type if ( get_post_type() == 'movies' ) // Set post or custom-post type name here { // Find the Category by slug $idObj = get_category_by_slug( 'horror' ); // Set your Category here // Get the Category ID $id = $idObj->term_id; // Set now the Category for this CPT wp_set_object_terms( $post_id, $id, 'category', true ); } }// end function ``` -- *I would then make a function which hides the meta-box in the back-end for this specific CPT. (so no one can add/change the category, but that is only useful when you use only 1 category pro posting)* -- Then you will need to make a function which hide this specific CPT to be shown on the main blog page. *(by using a query to exclude the category ' jobs' on the main blog page)* . ``` /** * Exclude CPT with Cat jobs on Landing page * * Read more: {@link https://codex.wordpress.org/Function_Reference/get_category_by_slug} * {@link https://codex.wordpress.org/Function_Reference/wp_set_object_terms} * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_categories_on_your_main_page} * {@link https://codex.wordpress.org/Function_Reference/is_main_query#Examples} */ add_action( 'pre_get_posts', 'wpse261307_exclude_cat_main_blog' ); function wpse261307_exclude_cat_main_blog( $query ) { global $wpdb; // Find the Category by slug $idObj = get_category_by_slug( 'horror' ); // Get the Category ID $id = $idObj->term_id; if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', -$id ); } } // end function ``` Hope this helps you on your way. > > Note: > > • Add this to a home brew plugin or in a `myfunctions.php` in the [wp-content/mu-plugins](https://codex.wordpress.org/Must_Use_Plugins) folder *(which you have to create yourself)* > > • Imho the most solid solution to be sure nothing get lost *(meaning out of sight because it still is in your database)* when changing to another theme. *(changes made directly in a `template` file are not anymore visible when you change to another theme)* > > • Btw, the same *(adding them into a myfunctions.php file in the `wp-content/mu-plugins` folder)* I would do for creating Custom Post Types. > > > *Ps, to clarify why I am not a fan of using `id` numbers directly:* * It happens that a category is deleted for whatever reason and afterwards it seems a mistake and the same category needs to be created again. * When a new category is created *(even with the same name)* it will get another `id` number and then *(when you use the number itself directly in any code)* your functions are not working anymore because of the wrong `id` number.
261,319
<p>I want to display the list of posts from my wordpress blog on someother site along with the author name, title, date and description. Hence, I decided to use WP REST API V2. As per WP REST API Documentation I retrived the data in JSON format by following example URL <code>http://example.com/wp-json/wp/v2/posts?_embed</code>. I get all the information except author name. Here is the partial JSON</p> <pre><code> ......... ........ "_embedded": { "author": [ { "code": "rest_user_invalid_id", "message": "Invalid user ID.", "data": { "status": 404 } } ], ........ ........ </code></pre> <p>I also get same error if I try to visit the following link <code>http://example.com/wp-json/wp/v2/users/1</code>. I don't understand why this error occur even though the user exist. Does it deal with authentication?</p> <p><strong>Note:</strong> I had earlier modified a field in the WP database so that the actual user name is not displayed in urls and posts. However, I think this must not affect the JSON output because an another alias for user name is already present and displayed in my blog. Also, the same entries of my blog is displayed on another wordpress blog by a wordpress plugin which also shows the author name.</p> <p>Please help me I am stuck and unable to find solution. </p>
[ { "answer_id": 263326, "author": "erwstout", "author_id": 73064, "author_profile": "https://wordpress.stackexchange.com/users/73064", "pm_score": 4, "selected": true, "text": "<p>Wordfence blocks the User endpoint from the public. In settings there is a checkbox you can unselect to make it visible in the WP Rest API again. </p>\n" }, { "answer_id": 341794, "author": "rtpHarry", "author_id": 60500, "author_profile": "https://wordpress.stackexchange.com/users/60500", "pm_score": 2, "selected": false, "text": "<p>I know this is solved for op but for other users that come along from Google this is what I had to do:</p>\n\n<ol>\n<li>Go to WordFence \"all options\" page</li>\n<li>Search \"rest\" in the filter</li>\n<li>Uncheck the option \"Prevent discovery of usernames through '/?author=N' scans, the oEmbed API, and the WordPress REST API\"</li>\n<li>Go to LiteSpeed Cache and choose Purge All</li>\n</ol>\n\n<p>You might be using different plugins for security and caching but the general idea remains:</p>\n\n<ol>\n<li>Make sure your security plugin isn't blocking access</li>\n<li>Clear your cache</li>\n</ol>\n" }, { "answer_id": 357974, "author": "TheRealMikeD", "author_id": 131296, "author_profile": "https://wordpress.stackexchange.com/users/131296", "pm_score": 0, "selected": false, "text": "<p>If the user data is indeed being blocked by Wordfence (or another security plugin), and you want to continue to utilize that security feature, you can modify the REST API's response, and add in just the fields that you want to use (which would presumably reveal less data than what is exposed by the standard API call). This documentation explains about modifying API responses: <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/</a>. Gives you an additional option.</p>\n" } ]
2017/03/25
[ "https://wordpress.stackexchange.com/questions/261319", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91491/" ]
I want to display the list of posts from my wordpress blog on someother site along with the author name, title, date and description. Hence, I decided to use WP REST API V2. As per WP REST API Documentation I retrived the data in JSON format by following example URL `http://example.com/wp-json/wp/v2/posts?_embed`. I get all the information except author name. Here is the partial JSON ``` ......... ........ "_embedded": { "author": [ { "code": "rest_user_invalid_id", "message": "Invalid user ID.", "data": { "status": 404 } } ], ........ ........ ``` I also get same error if I try to visit the following link `http://example.com/wp-json/wp/v2/users/1`. I don't understand why this error occur even though the user exist. Does it deal with authentication? **Note:** I had earlier modified a field in the WP database so that the actual user name is not displayed in urls and posts. However, I think this must not affect the JSON output because an another alias for user name is already present and displayed in my blog. Also, the same entries of my blog is displayed on another wordpress blog by a wordpress plugin which also shows the author name. Please help me I am stuck and unable to find solution.
Wordfence blocks the User endpoint from the public. In settings there is a checkbox you can unselect to make it visible in the WP Rest API again.
261,340
<p>I'm trying to "POST" data from my Form through ajax to a mysql database. This code is hooked to the "after_setup_theme" action:</p> <pre><code>add_action("wp_ajax_ajax_anmeldung", "ajax_anmeldung"); add_action("wp_ajax_nopriv_ajax_anmeldung", "ajax_anmeldung"); function ajax_anmeldung() { echo "&lt;script&gt; alert('hey'); &lt;/script&gt;"; die(); } </code></pre> <p>And this is the JS code that calls it:</p> <pre><code>$('#teilnahme_form').submit(function(e){ e.preventDefault(); var name = document.getElementById("name").value; jQuery.ajax({ type:"POST", url: window.ajaxurl, data: { action: "ajax_anmeldung", name : name }, success:function(data){ alert(data); } }); }); </code></pre> <p>When I run this I get returned a "0", nothing more.</p> <p>When I tried: <a href="http://my-domain.com/wp-admin/admin-ajax.php?action=ajax_anmeldung" rel="nofollow noreferrer">http://my-domain.com/wp-admin/admin-ajax.php?action=ajax_anmeldung</a> I also get a "0".</p> <p>I read all the others post on here surrounding this topic, but nothing seemed to help me, or I overlooked something really important.</p> <p>Cheers</p>
[ { "answer_id": 261362, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 1, "selected": false, "text": "<p>Please try this:</p>\n\n<p>Add the following in your theme's functions.php</p>\n\n<pre><code>add_action( 'init', 'tnc_aj_scripts' );\n\nfunction tnc_aj_scripts() {\n wp_register_script( \"ajax_anmeldung_script\", get_template_directory_uri(). '/my-ajax.js', array('jquery'), '1.0', true);\n wp_localize_script( 'ajax_anmeldung_script', 'mYAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); \n\n wp_enqueue_script( 'jquery' );\n wp_enqueue_script( 'ajax_anmeldung_script' );\n}\n\nadd_action(\"wp_ajax_ajax_anmeldung\", \"ajax_anmeldung\");\nadd_action(\"wp_ajax_nopriv_ajax_anmeldung\", \"ajax_anmeldung\");\n\nfunction ajax_anmeldung() {\n $result['one'] = 'Hey';\n $result = json_encode($result);\n echo $result;\n die();\n}\n</code></pre>\n\n<p>Create a .js file in your theme directory called my-ajax.js and put the following inside that file:</p>\n\n<pre><code>jQuery('#teilnahme_form').submit(function(e){\n e.preventDefault();\n\n var name = document.getElementById(\"name\").value;\n\n jQuery.ajax({\n type:\"post\",\n dataType : \"json\",\n url : mYAjax.ajaxurl,\n data: {\n action: \"ajax_anmeldung\",\n name : name\n },\n success:function(data){\n alert(data.one);\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 261366, "author": "Irene Mitchell", "author_id": 108769, "author_profile": "https://wordpress.stackexchange.com/users/108769", "pm_score": 0, "selected": false, "text": "<p>When using \"POST\" as request type, exclude \"action\" in data param and append it to the url.</p>\n\n<pre><code>$('#teilnahme_form').submit(function(e){\n e.preventDefault();\n\n var name = document.getElementById(\"name\").value;\n\n jQuery.ajax({\n type:\"POST\",\n url: window.ajaxurl + '?action=ajax_anmeldung',\n data: {\n name : name\n },\n success:function(data){\n alert(data);\n }\n });\n});\n</code></pre>\n" } ]
2017/03/25
[ "https://wordpress.stackexchange.com/questions/261340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116001/" ]
I'm trying to "POST" data from my Form through ajax to a mysql database. This code is hooked to the "after\_setup\_theme" action: ``` add_action("wp_ajax_ajax_anmeldung", "ajax_anmeldung"); add_action("wp_ajax_nopriv_ajax_anmeldung", "ajax_anmeldung"); function ajax_anmeldung() { echo "<script> alert('hey'); </script>"; die(); } ``` And this is the JS code that calls it: ``` $('#teilnahme_form').submit(function(e){ e.preventDefault(); var name = document.getElementById("name").value; jQuery.ajax({ type:"POST", url: window.ajaxurl, data: { action: "ajax_anmeldung", name : name }, success:function(data){ alert(data); } }); }); ``` When I run this I get returned a "0", nothing more. When I tried: <http://my-domain.com/wp-admin/admin-ajax.php?action=ajax_anmeldung> I also get a "0". I read all the others post on here surrounding this topic, but nothing seemed to help me, or I overlooked something really important. Cheers
Please try this: Add the following in your theme's functions.php ``` add_action( 'init', 'tnc_aj_scripts' ); function tnc_aj_scripts() { wp_register_script( "ajax_anmeldung_script", get_template_directory_uri(). '/my-ajax.js', array('jquery'), '1.0', true); wp_localize_script( 'ajax_anmeldung_script', 'mYAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'ajax_anmeldung_script' ); } add_action("wp_ajax_ajax_anmeldung", "ajax_anmeldung"); add_action("wp_ajax_nopriv_ajax_anmeldung", "ajax_anmeldung"); function ajax_anmeldung() { $result['one'] = 'Hey'; $result = json_encode($result); echo $result; die(); } ``` Create a .js file in your theme directory called my-ajax.js and put the following inside that file: ``` jQuery('#teilnahme_form').submit(function(e){ e.preventDefault(); var name = document.getElementById("name").value; jQuery.ajax({ type:"post", dataType : "json", url : mYAjax.ajaxurl, data: { action: "ajax_anmeldung", name : name }, success:function(data){ alert(data.one); } }); }); ```
261,359
<p>I made a custom theme named <code>testTheme</code> having these files:</p> <p><a href="https://i.stack.imgur.com/YJ2x9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YJ2x9.png" alt="The files of my theme" /></a></p> <p>And I wanted to put some translation on it therefore I created the required .po and .mo files for greek language via poedit as seen in the following image:</p> <p><a href="https://i.stack.imgur.com/7aULp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7aULp.png" alt="Theme files" /></a></p> <p>But I cannot make it load the custom translations I created via poedit. Do you have any idea how I will load them?</p> <h1>Edit 1</h1> <p>The <code>functions.php</code> as asked:</p> <pre><code>&lt;?php if(!function_exists('loadThemerequirements')): function loadThemerequirements() { load_theme_textdomain( 'testTheme', get_template_directory() . '/languages' ); } endif; add_action( 'after_setup_theme', 'loadThemerequirements' ); </code></pre> <h2>Update1</h2> <p>The translations files were moved and renamed like that:</p> <p><a href="https://i.stack.imgur.com/3iXlO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3iXlO.png" alt="New translation files" /></a></p> <p>Still Same result.</p> <h1>Edit 2:</h1> <p>This is not a child theme but a from-scratch made one.</p> <h1>Edit 3:</h1> <p>I tried renaming the .po and .mo files as <code>el_GR.po</code> and <code>el_GR.mo</code> still same result. I also tried to rename them in to <code>testTheme/el_GR.po</code> and <code>testTheme/el_GR.mo</code> without any success.</p> <h2>Update 2</h2> <p>The theme is in this git repository: <a href="https://github.com/pc-magas/testTheme" rel="nofollow noreferrer">https://github.com/pc-magas/testTheme</a></p> <h2>Edit 1</h2> <p>I changed my 404 page (that has some text to be translated into greek) like that:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class=&quot;fullpage_center&quot;&gt; &lt;div&gt; &lt;h1&gt;404&lt;/h1&gt; &lt;p&gt;&lt;?php _e('The requested page does not exist.','testTheme');?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php wp_reset_query(); //resetting the page query get_footer(); ?&gt; </code></pre> <p>A sample of my page and the translated text is:</p> <p><a href="https://i.stack.imgur.com/Ap6Yg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ap6Yg.png" alt="404 page with text that needs to be translated" /></a></p> <p>As you can see still no result.</p>
[ { "answer_id": 261392, "author": "jardindeden", "author_id": 116160, "author_profile": "https://wordpress.stackexchange.com/users/116160", "pm_score": 2, "selected": false, "text": "<p>If you have a child theme, in your function.php you have to change <code>get_template_directory()</code> by <code>get_stylesheet_directory()</code></p>\n" }, { "answer_id": 261395, "author": "MahdiY", "author_id": 105285, "author_profile": "https://wordpress.stackexchange.com/users/105285", "pm_score": 2, "selected": true, "text": "<ol>\n<li><p>Change your translate file name to <code>el_GR.po</code> and <code>el_GR.mo</code>:</p>\n\n<pre><code>el_GR.po in: testTheme\\languages\\el.po\nel_GR.mo in: testTheme\\languages\\el.mo\n</code></pre></li>\n<li><p>In 404.php file for print text you should write code like this (add textdomain):</p>\n\n<pre><code>&lt;?php _e('The requested page does not exist.', 'testTheme'); ?&gt;\n</code></pre></li>\n</ol>\n\n<p>Second parameter is textdomain.</p>\n" } ]
2017/03/25
[ "https://wordpress.stackexchange.com/questions/261359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116178/" ]
I made a custom theme named `testTheme` having these files: [![The files of my theme](https://i.stack.imgur.com/YJ2x9.png)](https://i.stack.imgur.com/YJ2x9.png) And I wanted to put some translation on it therefore I created the required .po and .mo files for greek language via poedit as seen in the following image: [![Theme files](https://i.stack.imgur.com/7aULp.png)](https://i.stack.imgur.com/7aULp.png) But I cannot make it load the custom translations I created via poedit. Do you have any idea how I will load them? Edit 1 ====== The `functions.php` as asked: ``` <?php if(!function_exists('loadThemerequirements')): function loadThemerequirements() { load_theme_textdomain( 'testTheme', get_template_directory() . '/languages' ); } endif; add_action( 'after_setup_theme', 'loadThemerequirements' ); ``` Update1 ------- The translations files were moved and renamed like that: [![New translation files](https://i.stack.imgur.com/3iXlO.png)](https://i.stack.imgur.com/3iXlO.png) Still Same result. Edit 2: ======= This is not a child theme but a from-scratch made one. Edit 3: ======= I tried renaming the .po and .mo files as `el_GR.po` and `el_GR.mo` still same result. I also tried to rename them in to `testTheme/el_GR.po` and `testTheme/el_GR.mo` without any success. Update 2 -------- The theme is in this git repository: <https://github.com/pc-magas/testTheme> Edit 1 ------ I changed my 404 page (that has some text to be translated into greek) like that: ``` <?php get_header(); ?> <div class="fullpage_center"> <div> <h1>404</h1> <p><?php _e('The requested page does not exist.','testTheme');?></p> </div> </div> <?php wp_reset_query(); //resetting the page query get_footer(); ?> ``` A sample of my page and the translated text is: [![404 page with text that needs to be translated](https://i.stack.imgur.com/Ap6Yg.png)](https://i.stack.imgur.com/Ap6Yg.png) As you can see still no result.
1. Change your translate file name to `el_GR.po` and `el_GR.mo`: ``` el_GR.po in: testTheme\languages\el.po el_GR.mo in: testTheme\languages\el.mo ``` 2. In 404.php file for print text you should write code like this (add textdomain): ``` <?php _e('The requested page does not exist.', 'testTheme'); ?> ``` Second parameter is textdomain.
261,379
<p>Im working on a plugin. I placed like button under each post so users can like the post. When user click the button it updates 'likes_count' post_meta field which i created. Now here is my question. I created an admin page and i want to list all the tags order by 'likes_count' post_meta field. Is it possible? Thanks.</p>
[ { "answer_id": 261422, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 3, "selected": true, "text": "<pre><code>$querystr = \"\n SELECT DISTINCT\n -- post_meta.meta_value,\n key2.name as tag_name,key2.slug as tag_slug FROM $wpdb-&gt;posts key1\n LEFT JOIN $wpdb-&gt;term_relationships ON (key1.ID = $wpdb-&gt;term_relationships.object_id)\n LEFT JOIN $wpdb-&gt;postmeta post_meta ON (key1.ID = post_meta.post_id)\nLEFT JOIN $wpdb-&gt;terms key2 ON ($wpdb-&gt;term_relationships.term_taxonomy_id = key2.term_id)\nLEFT JOIN $wpdb-&gt;term_taxonomy key3 ON ($wpdb-&gt;term_relationships.term_taxonomy_id = key3.term_id)\n WHERE 1=1\n AND post_meta.meta_key = 'likes_count'\n AND post_meta.meta_value &gt; 0\n AND (key1.post_status = 'publish')\n AND key3.taxonomy = 'post_tag'\n \";\n\n $pageposts = $wpdb-&gt;get_results($querystr, OBJECT);\nprint_r($pageposts);\n</code></pre>\n\n<p>This is the exact query for tags. I tested this and worked fine.\nin below given you sample output</p>\n\n<pre><code>Array\n(\n [0] =&gt; stdClass Object\n (\n [tag_name] =&gt; Tag1\n [tag_slug] =&gt; tag1\n )\n\n [1] =&gt; stdClass Object\n (\n [tag_name] =&gt; Tag2\n [tag_slug] =&gt; tag2\n )\n\n)\n</code></pre>\n" }, { "answer_id": 261434, "author": "Danny van Holten", "author_id": 58001, "author_profile": "https://wordpress.stackexchange.com/users/58001", "pm_score": 0, "selected": false, "text": "<p>You can add a meta query which filters by post meta and then put the wordpress orderby variable to meta_key</p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114388/" ]
Im working on a plugin. I placed like button under each post so users can like the post. When user click the button it updates 'likes\_count' post\_meta field which i created. Now here is my question. I created an admin page and i want to list all the tags order by 'likes\_count' post\_meta field. Is it possible? Thanks.
``` $querystr = " SELECT DISTINCT -- post_meta.meta_value, key2.name as tag_name,key2.slug as tag_slug FROM $wpdb->posts key1 LEFT JOIN $wpdb->term_relationships ON (key1.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->postmeta post_meta ON (key1.ID = post_meta.post_id) LEFT JOIN $wpdb->terms key2 ON ($wpdb->term_relationships.term_taxonomy_id = key2.term_id) LEFT JOIN $wpdb->term_taxonomy key3 ON ($wpdb->term_relationships.term_taxonomy_id = key3.term_id) WHERE 1=1 AND post_meta.meta_key = 'likes_count' AND post_meta.meta_value > 0 AND (key1.post_status = 'publish') AND key3.taxonomy = 'post_tag' "; $pageposts = $wpdb->get_results($querystr, OBJECT); print_r($pageposts); ``` This is the exact query for tags. I tested this and worked fine. in below given you sample output ``` Array ( [0] => stdClass Object ( [tag_name] => Tag1 [tag_slug] => tag1 ) [1] => stdClass Object ( [tag_name] => Tag2 [tag_slug] => tag2 ) ) ```
261,387
<p>is it possible to add first name &amp; last name to the default registration form of wordpress?</p>
[ { "answer_id": 261389, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 4, "selected": true, "text": "<p>Add this code in functions.php</p>\n<pre><code>add_action( 'register_form', 'myplugin_register_form' );\nfunction myplugin_register_form() {\n\n $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : '';\n $last_name = ( ! empty( $_POST['last_name'] ) ) ? trim( $_POST['last_name'] ) : '';\n\n ?&gt;\n &lt;p&gt;\n &lt;label for=&quot;first_name&quot;&gt;&lt;?php _e( 'First Name', 'mydomain' ) ?&gt;&lt;br /&gt;\n &lt;input type=&quot;text&quot; name=&quot;first_name&quot; id=&quot;first_name&quot; class=&quot;input&quot; value=&quot;&lt;?php echo esc_attr( wp_unslash( $first_name ) ); ?&gt;&quot; size=&quot;25&quot; /&gt;&lt;/label&gt;\n &lt;/p&gt;\n\n &lt;p&gt;\n &lt;label for=&quot;last_name&quot;&gt;&lt;?php _e( 'Last Name', 'mydomain' ) ?&gt;&lt;br /&gt;\n &lt;input type=&quot;text&quot; name=&quot;last_name&quot; id=&quot;last_name&quot; class=&quot;input&quot; value=&quot;&lt;?php echo esc_attr( wp_unslash( $last_name ) ); ?&gt;&quot; size=&quot;25&quot; /&gt;&lt;/label&gt;\n &lt;/p&gt;\n\n &lt;?php\n }\n\n //2. Add validation. In this case, we make sure first_name and last_name is required.\n add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\n function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {\n\n if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) &amp;&amp; trim( $_POST['first_name'] ) == '' ) {\n $errors-&gt;add( 'first_name_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: You must include a first name.', 'mydomain' ) );\n }\n if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) &amp;&amp; trim( $_POST['last_name'] ) == '' ) {\n $errors-&gt;add( 'last_name_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: You must include a last name.', 'mydomain' ) );\n }\n return $errors;\n }\n\n //3. Finally, save our extra registration user meta.\n add_action( 'user_register', 'myplugin_user_register' );\n function myplugin_user_register( $user_id ) {\n if ( ! empty( $_POST['first_name'] ) ) {\n update_user_meta( $user_id, 'first_name', trim( $_POST['first_name'] ) );\n update_user_meta( $user_id, 'last_name', trim( $_POST['last_name'] ) );\n }\n }\n</code></pre>\n<p>For more info see <a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow noreferrer\">codex</a></p>\n<p>You can also use some plugins</p>\n<p><a href=\"https://wordpress.org/plugins/cimy-user-extra-fields/\" rel=\"nofollow noreferrer\">cimy-user-extra-fields</a></p>\n<p><a href=\"https://wordpress.org/plugins/fma-additional-registration-attributes/\" rel=\"nofollow noreferrer\">Custom Registration Form</a></p>\n<p><a href=\"https://wordpress.org/plugins/user-registration-aide\" rel=\"nofollow noreferrer\">User Registration Aide</a></p>\n" }, { "answer_id": 292224, "author": "Ignasi Calvo", "author_id": 135596, "author_profile": "https://wordpress.stackexchange.com/users/135596", "pm_score": 0, "selected": false, "text": "<p>The code works, but I've spotted a small bug. On the validation of the last_name, the last var in the if condition hast \"first_name\", and must have \"last_name\". So that piece of code, correctly, would be:</p>\n\n<pre><code>if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) &amp;&amp; trim( $_POST['last_name'] ) == '' ) {\n $errors-&gt;add( 'last_name_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: You must include a first name.', 'mydomain' ) );\n}\n</code></pre>\n" }, { "answer_id": 306194, "author": "Ethan Root", "author_id": 145378, "author_profile": "https://wordpress.stackexchange.com/users/145378", "pm_score": 0, "selected": false, "text": "<pre><code>$form['account']['lname'] = array('#type' =&gt; 'textfield',\n'#title' =&gt; t('LastName'),\n'#default_value' =&gt; $edit['LastName'],\n'#maxlength' =&gt; LASTNAME_MAX_LENGTH,\n'#description' =&gt; t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),\n'#required' =&gt; TRUE,\n);\n</code></pre>\n\n<p>you can do it in the UI only</p>\n\n<p>Navigate to the <code>sitedomain/admin/config/people/accounts/fields</code> and add the first name, lastname as the fields it will display First name and last name the default registration form</p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261387", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110405/" ]
is it possible to add first name & last name to the default registration form of wordpress?
Add this code in functions.php ``` add_action( 'register_form', 'myplugin_register_form' ); function myplugin_register_form() { $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; $last_name = ( ! empty( $_POST['last_name'] ) ) ? trim( $_POST['last_name'] ) : ''; ?> <p> <label for="first_name"><?php _e( 'First Name', 'mydomain' ) ?><br /> <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /></label> </p> <p> <label for="last_name"><?php _e( 'Last Name', 'mydomain' ) ?><br /> <input type="text" name="last_name" id="last_name" class="input" value="<?php echo esc_attr( wp_unslash( $last_name ) ); ?>" size="25" /></label> </p> <?php } //2. Add validation. In this case, we make sure first_name and last_name is required. add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 ); function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) { if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) { $errors->add( 'first_name_error', __( '<strong>ERROR</strong>: You must include a first name.', 'mydomain' ) ); } if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) && trim( $_POST['last_name'] ) == '' ) { $errors->add( 'last_name_error', __( '<strong>ERROR</strong>: You must include a last name.', 'mydomain' ) ); } return $errors; } //3. Finally, save our extra registration user meta. add_action( 'user_register', 'myplugin_user_register' ); function myplugin_user_register( $user_id ) { if ( ! empty( $_POST['first_name'] ) ) { update_user_meta( $user_id, 'first_name', trim( $_POST['first_name'] ) ); update_user_meta( $user_id, 'last_name', trim( $_POST['last_name'] ) ); } } ``` For more info see [codex](https://codex.wordpress.org/Customizing_the_Registration_Form) You can also use some plugins [cimy-user-extra-fields](https://wordpress.org/plugins/cimy-user-extra-fields/) [Custom Registration Form](https://wordpress.org/plugins/fma-additional-registration-attributes/) [User Registration Aide](https://wordpress.org/plugins/user-registration-aide)
261,409
<p>I'm using ajax in a plugin for a front-end form. But it only works if I place the <code>add_action("wp_ajax_..."</code> in the plugin loader. I would like to register the call in another file. </p> <p>I have tried: </p> <pre><code>function my_plugin_init() { if ( ! is_admin() ) { require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' ); } } //add_action( 'wp_loaded', 'my_plugin_init' ); add_action( 'init', 'my_plugin_init' ); </code></pre> <p>But neither <code>add_action</code> hook seems to work. Ajax fails because it cannot find the ajax function in <code>inc/my-plugin-functions.php</code>. </p> <p>If I place the ajax function in the plugin loader, everything works as expected:</p> <pre><code>function my_plugin_etc() { $title = sanitize_text_field( $_POST['title'] ); $meta = update_post_meta(1234, 'test_key', $title); if ( $meta != false ) echo json_encode(array('status' =&gt; 'success', 'message' =&gt; 'Title added as postmeta.') ); else echo json_encode(array('status' =&gt; 'error', 'message' =&gt; 'There was a problem.' ) ); wp_die(); } add_action("wp_ajax_my_plugin_etc", "my_plugin_etc"); </code></pre> <p>I'd rather not put the ajax function in the plugin loader. </p> <p>What is the proper hook to use to include a file so that the ajax function in that file is registered?</p>
[ { "answer_id": 261413, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>Have you enqueued your script and then added wp_localize_script in the file you wish to use ajax?</p>\n\n<pre><code>// your javascript with ajax calls must be enqueued before wp_localize_script. \nwp_enqueue_script( 'ajax-script', plugins_url( 'file_location.js', __FILE__ ), array('jquery') );\n // Wordpress localize script\n wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ), 'we_value' =&gt; 1234 ) );\n</code></pre>\n" }, { "answer_id": 261433, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": true, "text": "<p><em>Any</em> action that fires before the AJAX call is made will work. Generally speaking, <code>init</code> is good choice.</p>\n\n<p>You mention that the ajax call is made from a \"front-end form\". If that form is available to end-users who are <strong>not</strong> logged in, then you need to use:</p>\n\n<pre><code>add_action ('wp_ajax_nopriv_my_plugin_etc', 'my_plugin_etc') ;\n</code></pre>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/\" rel=\"nofollow noreferrer\">wp_ajax_nopriv_{$_REQUEST[‘action’]}</a>.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Must be my lack of sleep, because I should have seen this earlier. </p>\n\n<p><code>is_admin()</code> returns <code>false</code> during an invocation of <code>admin-ajax.php</code>. Thus, change your <code>my_plugin_init()</code> to be:</p>\n\n<pre><code>function my_plugin_init() {\n\n if ( ! is_admin() || wp_doing_ajax ()) {\n\n require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' );\n\n }\n\n}\nadd_action( 'init', 'my_plugin_init' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_doing_ajax/\" rel=\"nofollow noreferrer\">wp_doing_ajax()</a> was introduced in WP 4.7.</p>\n\n<p>If your plugin needs to work in version of WP before that, then change it to:</p>\n\n<pre><code>function my_plugin_init() {\n\n if ( ! is_admin() || (defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX)) {\n\n require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' );\n\n }\n\n}\nadd_action( 'init', 'my_plugin_init' );\n</code></pre>\n\n<p>The advantage of <code>wp_doing_ajax()</code> over the pre-4.7 test (if you can get away with only supporting 4.7+) is that applies the <a href=\"https://developer.wordpress.org/reference/hooks/wp_doing_ajax/\" rel=\"nofollow noreferrer\">wp_doing_ajax</a> filter to the value of <code>defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX</code> which can give you finer control over whether you want to consider yourself within an ajax context. However, this extra control is probably not necessary in your case.</p>\n\n<p>Finally, if <code>inc/my-plugin-functions.php</code> <strong>only</strong> contains code related to AJAX, then you remove <code>! is_admin() ||</code> from the <code>if</code> condition.</p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261409", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16575/" ]
I'm using ajax in a plugin for a front-end form. But it only works if I place the `add_action("wp_ajax_..."` in the plugin loader. I would like to register the call in another file. I have tried: ``` function my_plugin_init() { if ( ! is_admin() ) { require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' ); } } //add_action( 'wp_loaded', 'my_plugin_init' ); add_action( 'init', 'my_plugin_init' ); ``` But neither `add_action` hook seems to work. Ajax fails because it cannot find the ajax function in `inc/my-plugin-functions.php`. If I place the ajax function in the plugin loader, everything works as expected: ``` function my_plugin_etc() { $title = sanitize_text_field( $_POST['title'] ); $meta = update_post_meta(1234, 'test_key', $title); if ( $meta != false ) echo json_encode(array('status' => 'success', 'message' => 'Title added as postmeta.') ); else echo json_encode(array('status' => 'error', 'message' => 'There was a problem.' ) ); wp_die(); } add_action("wp_ajax_my_plugin_etc", "my_plugin_etc"); ``` I'd rather not put the ajax function in the plugin loader. What is the proper hook to use to include a file so that the ajax function in that file is registered?
*Any* action that fires before the AJAX call is made will work. Generally speaking, `init` is good choice. You mention that the ajax call is made from a "front-end form". If that form is available to end-users who are **not** logged in, then you need to use: ``` add_action ('wp_ajax_nopriv_my_plugin_etc', 'my_plugin_etc') ; ``` See [wp\_ajax\_nopriv\_{$\_REQUEST[‘action’]}](https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/). **Edit** Must be my lack of sleep, because I should have seen this earlier. `is_admin()` returns `false` during an invocation of `admin-ajax.php`. Thus, change your `my_plugin_init()` to be: ``` function my_plugin_init() { if ( ! is_admin() || wp_doing_ajax ()) { require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' ); } } add_action( 'init', 'my_plugin_init' ); ``` [wp\_doing\_ajax()](https://developer.wordpress.org/reference/functions/wp_doing_ajax/) was introduced in WP 4.7. If your plugin needs to work in version of WP before that, then change it to: ``` function my_plugin_init() { if ( ! is_admin() || (defined( 'DOING_AJAX' ) && DOING_AJAX)) { require( dirname( __FILE__ ) . '/inc/my-plugin-functions.php' ); } } add_action( 'init', 'my_plugin_init' ); ``` The advantage of `wp_doing_ajax()` over the pre-4.7 test (if you can get away with only supporting 4.7+) is that applies the [wp\_doing\_ajax](https://developer.wordpress.org/reference/hooks/wp_doing_ajax/) filter to the value of `defined( 'DOING_AJAX' ) && DOING_AJAX` which can give you finer control over whether you want to consider yourself within an ajax context. However, this extra control is probably not necessary in your case. Finally, if `inc/my-plugin-functions.php` **only** contains code related to AJAX, then you remove `! is_admin() ||` from the `if` condition.
261,410
<p>I am using the WP-CLI to manage my sites. I can run the following command</p> <pre><code>wp post list --fields=ID,mycustomfield ID | mycustomfield ----------------------- 1 | active 2 | active 3 | disabled 4 | active </code></pre> <p>I am trying to narrow this list down by only returning those which has <strong>mycustomfield</strong> as active</p> <p>Any ideas how I can do this?</p>
[ { "answer_id": 261420, "author": "fightstarr20", "author_id": 10247, "author_profile": "https://wordpress.stackexchange.com/users/10247", "pm_score": 2, "selected": false, "text": "<p>Managed to figure this out, you can pass <strong>--meta_key</strong> and <strong>--meta_compare</strong> arguments like this...</p>\n\n<pre><code>wp post list --fields=ID,mycustomfield --meta_key=mycustomfield '--meta_compare=active'\n\nID | mycustomfield\n-----------------------\n 1 | active\n 2 | active\n 4 | active\n</code></pre>\n" }, { "answer_id": 392007, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 0, "selected": false, "text": "<p>You may pass any standard <code>WP_Query</code> arguments as flags to the <code>wp post list</code> command.</p>\n<p><code>--&lt;field&gt;=&lt;value&gt;</code></p>\n<p>In your example you would use the meta query arguments.</p>\n<p><code>wp post list --fields=ID,mycustomfield --meta_key=mycustomfield --meta_value=active</code></p>\n<p><a href=\"https://developer.wordpress.org/cli/commands/post/list/#options\" rel=\"nofollow noreferrer\">Vague documentation is here.</a></p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261410", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10247/" ]
I am using the WP-CLI to manage my sites. I can run the following command ``` wp post list --fields=ID,mycustomfield ID | mycustomfield ----------------------- 1 | active 2 | active 3 | disabled 4 | active ``` I am trying to narrow this list down by only returning those which has **mycustomfield** as active Any ideas how I can do this?
Managed to figure this out, you can pass **--meta\_key** and **--meta\_compare** arguments like this... ``` wp post list --fields=ID,mycustomfield --meta_key=mycustomfield '--meta_compare=active' ID | mycustomfield ----------------------- 1 | active 2 | active 4 | active ```
261,414
<p>I'm trying to update a custom field by hooking into the <code>save-post</code> action, but for reasons I can't figure out, it's not working.</p> <p>The following function is placed in the theme's <code>functions.php</code>:</p> <pre><code>function save_address_meta() { $meta = get_post_meta( get_the_ID() ); $address = $meta['address']; update_post_meta(get_the_ID(), $address, 'test'); } add_action( 'save_post', 'save_address_meta', 50 ); </code></pre> <p>I've tried using <code>pre_post_update</code> as well, as I understand that <code>save_post</code> won't actually fire unless something, other than a custom field, is updated in the post - but no luck with this one either.</p> <p>I've spent a few hours searching for solutions on stackexchange and various other sources online, but just not coming right. This is a dumbed-down version of the original code, but even in this basic state it doesn't appear to be working.</p> <p>Basically, I'm trying to get the custom field in question, then update it with a string value.</p> <p>If I <code>print_r</code> the <code>$meta</code> array, the custom field value appears in an array as follows: </p> <pre><code> [address] =&gt; Array ( [0] =&gt; 50 Call Lane Leeds LS1 6DT United Kingdom ) </code></pre> <p>I've also tried accessing this custom field in the function above using <code>$address = $meta['address'][0]</code>.<br> I can echo out the value of the key this way, but if I'm not mistaken, it's the key I'll need to reference in order for the string, in the 3rd argument, to update the value as intended. </p>
[ { "answer_id": 261416, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 3, "selected": true, "text": "<p>Try changing <code>update_post_meta(get_the_ID(), $address, 'test');</code> to <code>update_post_meta(get_the_ID(), 'address', 'test');</code></p>\n" }, { "answer_id": 261417, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>The <code>save_post</code> hook will fire whenever WordPress saves a post to the database. This includes saving WP revisions which will have a different post ID than the actual post. It's more than likely you are getting and saving the post meta to a revision instead of to the actual post.</p>\n\n<p>Also, the <code>save_post</code> hook passes a few variables when it fires, including the post ID, so you don't have to use the <code>get_the_ID()</code> function.</p>\n\n<pre><code>function wpse_261414_save_post( $post_id, $post, $update ) {\n //* Make sure this isn't a post revision\n if( wp_is_post_revision( $post_id ) ) {\n return;\n }\n $meta = get_post_meta( $post_id );\n $address = $meta[ 'address' ];\n update_post_meta( $post_id, $address, 'test' );\n}\nadd_action( 'save_post', 'wpse_261414_save_post', 10, 3 );\n</code></pre>\n" }, { "answer_id": 261431, "author": "K. Felix", "author_id": 116266, "author_profile": "https://wordpress.stackexchange.com/users/116266", "pm_score": 0, "selected": false, "text": "<p>Why don't you try something like this;</p>\n\n<pre><code>function save_address_meta() {\n global $post;\n if($post-&gt;post_type == 'your-custom-post-type'){\n $address_field = 'test'; //Get your address field here \n update_post_meta($post-&gt;ID, 'address', 'test');\n }\n}\nadd_action( 'save_post', 'save_address_meta' );\n</code></pre>\n\n<p>And you can get your field value elsewhere may be for example inside the loop as;</p>\n\n<pre><code>$address = get_post_meta($post-&gt;ID, 'address', true);\n</code></pre>\n" }, { "answer_id": 412156, "author": "Adam O'Dwyer", "author_id": 80373, "author_profile": "https://wordpress.stackexchange.com/users/80373", "pm_score": 0, "selected": false, "text": "<p>I had these symptoms, but it turned out to be a validation check behaving unexpectedly, namely:</p>\n<pre><code>if( !current_user_can( 'edit_post') ) return;\n</code></pre>\n<p>This had been working (for several years), but a Wordpress update caused it to fail.</p>\n<p>I amended it to also take the $post_id (as per the <a href=\"https://developer.wordpress.org/reference/functions/current_user_can/\" rel=\"nofollow noreferrer\">documentation example here</a>):</p>\n<pre><code>if( !current_user_can( 'edit_post', $post_id) ) return;\n</code></pre>\n<p>and all was well. So in case this helps anyone else...</p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108005/" ]
I'm trying to update a custom field by hooking into the `save-post` action, but for reasons I can't figure out, it's not working. The following function is placed in the theme's `functions.php`: ``` function save_address_meta() { $meta = get_post_meta( get_the_ID() ); $address = $meta['address']; update_post_meta(get_the_ID(), $address, 'test'); } add_action( 'save_post', 'save_address_meta', 50 ); ``` I've tried using `pre_post_update` as well, as I understand that `save_post` won't actually fire unless something, other than a custom field, is updated in the post - but no luck with this one either. I've spent a few hours searching for solutions on stackexchange and various other sources online, but just not coming right. This is a dumbed-down version of the original code, but even in this basic state it doesn't appear to be working. Basically, I'm trying to get the custom field in question, then update it with a string value. If I `print_r` the `$meta` array, the custom field value appears in an array as follows: ``` [address] => Array ( [0] => 50 Call Lane Leeds LS1 6DT United Kingdom ) ``` I've also tried accessing this custom field in the function above using `$address = $meta['address'][0]`. I can echo out the value of the key this way, but if I'm not mistaken, it's the key I'll need to reference in order for the string, in the 3rd argument, to update the value as intended.
Try changing `update_post_meta(get_the_ID(), $address, 'test');` to `update_post_meta(get_the_ID(), 'address', 'test');`
261,425
<p>I just create a site on my Multisite domain (example.com), for instance site1.example.com</p> <p>After this, I try to enter on <a href="https://site1.example.com/wp-admin" rel="nofollow noreferrer">https://site1.example.com/wp-admin</a>, but I'm redirected to <a href="https://www.example.com/wp-signup.php?new=example.com" rel="nofollow noreferrer">https://www.example.com/wp-signup.php?new=example.com</a></p> <p>My .htaccess containt this lines:</p> <pre><code>RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </code></pre> <p>I have installed, among others, this plugins</p> <ul> <li>wordfence Security</li> <li>Loginizer</li> <li>WP Maintenance Mode (with Status Activated)</li> </ul> <p>Why wordpress multisite redirect me to wp-signup if the site already exists?</p> <p>The problem is because de SSL certificate, because I tried enter by HTTP and It's ok</p> <p>How can solve it? Can I change something on .htaccess file?</p>
[ { "answer_id": 262093, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>This .htaccess file looks like it is for a network that uses sub-folders but the URL address that you say you are trying is for a network that uses sub-domains. Which type are you using? Have you followed the steps in the /wp-admin/network/setup.php page correctly?</p>\n\n<p>Another idea is that you have added SSL but the site is maybe still using the old http URL addresses. Click edit on one of the sites to see the Site Address (URL) field. Does it have https there or just http?</p>\n" }, { "answer_id": 262188, "author": "Justin", "author_id": 114945, "author_profile": "https://wordpress.stackexchange.com/users/114945", "pm_score": -1, "selected": false, "text": "<p>The redirect is to the main WordPress site and this is the way WordPress Multisite works. The sign up is always on the main site of the Network/Multisite.</p>\n\n<p>if you want to allow registration on a subsite only try <a href=\"https://wordpress.org/plugins/network-subsite-user-registration/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/network-subsite-user-registration/</a></p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261425", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116259/" ]
I just create a site on my Multisite domain (example.com), for instance site1.example.com After this, I try to enter on <https://site1.example.com/wp-admin>, but I'm redirected to <https://www.example.com/wp-signup.php?new=example.com> My .htaccess containt this lines: ``` RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] ``` I have installed, among others, this plugins * wordfence Security * Loginizer * WP Maintenance Mode (with Status Activated) Why wordpress multisite redirect me to wp-signup if the site already exists? The problem is because de SSL certificate, because I tried enter by HTTP and It's ok How can solve it? Can I change something on .htaccess file?
This .htaccess file looks like it is for a network that uses sub-folders but the URL address that you say you are trying is for a network that uses sub-domains. Which type are you using? Have you followed the steps in the /wp-admin/network/setup.php page correctly? Another idea is that you have added SSL but the site is maybe still using the old http URL addresses. Click edit on one of the sites to see the Site Address (URL) field. Does it have https there or just http?
261,436
<p>This is similar to, but more specific than, the <a href="https://wordpress.stackexchange.com/questions/30970/using-get-posts-with-arguments-found-in-meta-keys">question found here</a>. That question suggests the Wordpress <a href="https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters" rel="nofollow noreferrer">WP_Query example</a>, which are helpful, but they're not working for me. </p> <p>My code is as follows: </p> <pre><code> $posts = get_posts(array( 'post_type' =&gt; 'events', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'from_datetime', 'meta_value' =&gt; date( "F d, Y g:i a" ), 'meta_compare' =&gt; '&gt;', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'ASC' )); </code></pre> <p>The custom fields are made using ACF in our blog. The <code>from_datetime</code> field shows like this: </p> <pre><code>April 18, 2017 2:30 pm </code></pre> <p>So I've translated this to the date nomenclature: </p> <pre><code>date( "F d, Y g:i a" ) </code></pre> <p>Events are a custom post type. Basically I want to show the upcoming 2 events that are NOT passed. So this is quite close to the example on the WP_Query page, but still the above doesn't work. The query returns nothing. I do know that if I remove the <code>meta_value</code> stuff above, there are four events to show that are beyond "now". </p> <p>Any thoughts on what I may be doing wrongly? The query seems correct according to the documentation at WP. Thank you!</p>
[ { "answer_id": 262093, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>This .htaccess file looks like it is for a network that uses sub-folders but the URL address that you say you are trying is for a network that uses sub-domains. Which type are you using? Have you followed the steps in the /wp-admin/network/setup.php page correctly?</p>\n\n<p>Another idea is that you have added SSL but the site is maybe still using the old http URL addresses. Click edit on one of the sites to see the Site Address (URL) field. Does it have https there or just http?</p>\n" }, { "answer_id": 262188, "author": "Justin", "author_id": 114945, "author_profile": "https://wordpress.stackexchange.com/users/114945", "pm_score": -1, "selected": false, "text": "<p>The redirect is to the main WordPress site and this is the way WordPress Multisite works. The sign up is always on the main site of the Network/Multisite.</p>\n\n<p>if you want to allow registration on a subsite only try <a href=\"https://wordpress.org/plugins/network-subsite-user-registration/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/network-subsite-user-registration/</a></p>\n" } ]
2017/03/26
[ "https://wordpress.stackexchange.com/questions/261436", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16142/" ]
This is similar to, but more specific than, the [question found here](https://wordpress.stackexchange.com/questions/30970/using-get-posts-with-arguments-found-in-meta-keys). That question suggests the Wordpress [WP\_Query example](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters), which are helpful, but they're not working for me. My code is as follows: ``` $posts = get_posts(array( 'post_type' => 'events', 'posts_per_page' => -1, 'meta_key' => 'from_datetime', 'meta_value' => date( "F d, Y g:i a" ), 'meta_compare' => '>', 'orderby' => 'meta_value', 'order' => 'ASC' )); ``` The custom fields are made using ACF in our blog. The `from_datetime` field shows like this: ``` April 18, 2017 2:30 pm ``` So I've translated this to the date nomenclature: ``` date( "F d, Y g:i a" ) ``` Events are a custom post type. Basically I want to show the upcoming 2 events that are NOT passed. So this is quite close to the example on the WP\_Query page, but still the above doesn't work. The query returns nothing. I do know that if I remove the `meta_value` stuff above, there are four events to show that are beyond "now". Any thoughts on what I may be doing wrongly? The query seems correct according to the documentation at WP. Thank you!
This .htaccess file looks like it is for a network that uses sub-folders but the URL address that you say you are trying is for a network that uses sub-domains. Which type are you using? Have you followed the steps in the /wp-admin/network/setup.php page correctly? Another idea is that you have added SSL but the site is maybe still using the old http URL addresses. Click edit on one of the sites to see the Site Address (URL) field. Does it have https there or just http?
261,440
<p>I'm am currently trialling the new (as of 2017) core API built into Wordpress. My setup is reasonably simple:</p> <pre><code> +---------+ +------+ +---------+ |Wordpress|&lt;--&gt;|Guzzle|&lt;--&gt;| App | |(API) | +------+ |(PHPSlim)| +---------+ +---------+ </code></pre> <p>Guzzle will be operating through a local loopback (/etc/hosts set up to see the api as a local resource). </p> <p>The major players in the WP space for cacheing (WP Super Cache, W3, etc) don't appear to do anything around the API. My understanding is that they essentially create snapshots of a rendered page and skip over any php (including db calls) for future requests. </p> <p>So...</p> <p>The question is, is it possible to apply a level of cache to the API calls in WP? The site is reasonably static, so ideally I don't want to ping the DB for every request. </p> <p>I have examined the headers returned by WP and no cacheing indicators are present. I have also considered using wp_cache functions or wp_transient functions, but both seem to be a misuse of their functionality. </p> <p>Headers: <a href="https://i.stack.imgur.com/ITxqX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ITxqX.png" alt="enter image description here"></a></p>
[ { "answer_id": 261673, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 1, "selected": false, "text": "<p>There is a cache plugin for WP Rest API with the name... <a href=\"https://wordpress.org/plugins/wp-rest-api-cache/\" rel=\"nofollow noreferrer\">WP Rest API Cache</a>:</p>\n\n<p>I've used it for small projects and helped me a lot.</p>\n" }, { "answer_id": 261717, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>It is an API.... would you like to get stale cached results when doing $i++? I guess not.</p>\n\n<p>Caching should be done on the user side of the API as only it can know what is the level of staleness that can be tolerated.</p>\n\n<p>It is not like you should avoid any type of caching on the wordpress side, but keep in mind that to do cache invalidation is a bitch. The safest way to go is with object caching which you should have in any case on any serious wordpress deployment.</p>\n" }, { "answer_id": 340584, "author": "samjco", "author_id": 29133, "author_profile": "https://wordpress.stackexchange.com/users/29133", "pm_score": 0, "selected": false, "text": "<p>This one below is actually better I believe:</p>\n\n<p><a href=\"https://github.com/airesvsg/wp-rest-api-cache\" rel=\"nofollow noreferrer\">https://github.com/airesvsg/wp-rest-api-cache</a></p>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261440", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82167/" ]
I'm am currently trialling the new (as of 2017) core API built into Wordpress. My setup is reasonably simple: ``` +---------+ +------+ +---------+ |Wordpress|<-->|Guzzle|<-->| App | |(API) | +------+ |(PHPSlim)| +---------+ +---------+ ``` Guzzle will be operating through a local loopback (/etc/hosts set up to see the api as a local resource). The major players in the WP space for cacheing (WP Super Cache, W3, etc) don't appear to do anything around the API. My understanding is that they essentially create snapshots of a rendered page and skip over any php (including db calls) for future requests. So... The question is, is it possible to apply a level of cache to the API calls in WP? The site is reasonably static, so ideally I don't want to ping the DB for every request. I have examined the headers returned by WP and no cacheing indicators are present. I have also considered using wp\_cache functions or wp\_transient functions, but both seem to be a misuse of their functionality. Headers: [![enter image description here](https://i.stack.imgur.com/ITxqX.png)](https://i.stack.imgur.com/ITxqX.png)
There is a cache plugin for WP Rest API with the name... [WP Rest API Cache](https://wordpress.org/plugins/wp-rest-api-cache/): I've used it for small projects and helped me a lot.
261,443
<p>I created a shortcode for visual composer to get terms of a custom taxonomy. But when I get them (for a category dropdown on visual composer's backend editor) it's not working.<br><br> <a href="https://i.stack.imgur.com/IO1P8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IO1P8.jpg" alt="enter image description here"></a> My code:<br></p> <pre><code>$args1= array( ‘taxonomy’ =&gt; ‘danh_muc’, **// my custom taxonomy** ‘hide_empty’ =&gt; 0, ); $inra=array(); $danhmucs= get_terms($args1); foreach ($danhmucs as $danhmuc) { $tendm=$danhmuc-&gt; name; $iddm=$danhmuc-&gt; term_id; $inra[$tendm]=$iddm; } vc_map( array( “name” =&gt; __(“News”, ‘understrap’), “base” =&gt; “tintuc”, “class” =&gt; “”, “category” =&gt; ‘Content’, “icon” =&gt; “icon-wpb-application-icon-large”, “params” =&gt; array( array( “type” =&gt; “dropdown”, “holder” =&gt; “div”, “class” =&gt; “”, “heading” =&gt; “Danh mục”, “param_name” =&gt; “cat”, “value” =&gt; $inra, //**array taxonomy by name=&gt; id** “description” =&gt; ‘Chọn danh mục BĐS cần hiện bài đăng’, ), ) )); </code></pre> <p>But when I change ‘taxonomy’ => ‘danh_muc’ to ‘taxonomy’ => ‘category’ it's working fine!<br><br> I var_dump $inra with 2 cases: ‘taxonomy’ => ‘danh_muc’ and ‘taxonomy’ => ‘category’, The results are the same.<br><br> Thanks all!<br></p>
[ { "answer_id": 261673, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 1, "selected": false, "text": "<p>There is a cache plugin for WP Rest API with the name... <a href=\"https://wordpress.org/plugins/wp-rest-api-cache/\" rel=\"nofollow noreferrer\">WP Rest API Cache</a>:</p>\n\n<p>I've used it for small projects and helped me a lot.</p>\n" }, { "answer_id": 261717, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>It is an API.... would you like to get stale cached results when doing $i++? I guess not.</p>\n\n<p>Caching should be done on the user side of the API as only it can know what is the level of staleness that can be tolerated.</p>\n\n<p>It is not like you should avoid any type of caching on the wordpress side, but keep in mind that to do cache invalidation is a bitch. The safest way to go is with object caching which you should have in any case on any serious wordpress deployment.</p>\n" }, { "answer_id": 340584, "author": "samjco", "author_id": 29133, "author_profile": "https://wordpress.stackexchange.com/users/29133", "pm_score": 0, "selected": false, "text": "<p>This one below is actually better I believe:</p>\n\n<p><a href=\"https://github.com/airesvsg/wp-rest-api-cache\" rel=\"nofollow noreferrer\">https://github.com/airesvsg/wp-rest-api-cache</a></p>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261443", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116280/" ]
I created a shortcode for visual composer to get terms of a custom taxonomy. But when I get them (for a category dropdown on visual composer's backend editor) it's not working. [![enter image description here](https://i.stack.imgur.com/IO1P8.jpg)](https://i.stack.imgur.com/IO1P8.jpg) My code: ``` $args1= array( ‘taxonomy’ => ‘danh_muc’, **// my custom taxonomy** ‘hide_empty’ => 0, ); $inra=array(); $danhmucs= get_terms($args1); foreach ($danhmucs as $danhmuc) { $tendm=$danhmuc-> name; $iddm=$danhmuc-> term_id; $inra[$tendm]=$iddm; } vc_map( array( “name” => __(“News”, ‘understrap’), “base” => “tintuc”, “class” => “”, “category” => ‘Content’, “icon” => “icon-wpb-application-icon-large”, “params” => array( array( “type” => “dropdown”, “holder” => “div”, “class” => “”, “heading” => “Danh mục”, “param_name” => “cat”, “value” => $inra, //**array taxonomy by name=> id** “description” => ‘Chọn danh mục BĐS cần hiện bài đăng’, ), ) )); ``` But when I change ‘taxonomy’ => ‘danh\_muc’ to ‘taxonomy’ => ‘category’ it's working fine! I var\_dump $inra with 2 cases: ‘taxonomy’ => ‘danh\_muc’ and ‘taxonomy’ => ‘category’, The results are the same. Thanks all!
There is a cache plugin for WP Rest API with the name... [WP Rest API Cache](https://wordpress.org/plugins/wp-rest-api-cache/): I've used it for small projects and helped me a lot.
261,449
<p>i want to change the output of a method inside the class of a plugin from the child function.php without changing the plugin's file. The output i want to change is that instead of a common a href, it uses the template button array. The thing is that the output of the method you get is a shortcode (this shortcode below that you can insert to any template you want). I don't know how to change this method from the child function.php. I modded this plugin file, it works, but it means i don't get to update the plugin without loosing the new button.</p> <pre><code>echo do_shortcode( '[bewpi-download-invoice title="Download (PDF) Invoice {formatted_invoice_number}" order_id="' . $order-&gt;id . '"]' ); </code></pre> <p>Here is the method inside the be-woocommerce-pdf-invoices.php class</p> <pre><code>public function download_invoice_shortcode( $atts ) { if ( ! isset( $atts['order_id'] ) || 0 === intval( $atts['order_id'] ) ) { return; } // by default order status should be Processing or Completed. $order = wc_get_order( $atts['order_id'] ); if ( ! $order-&gt;is_paid() ) { return; } if ( ! BEWPI_Invoice::exists( $order-&gt;id ) ) { return; } $url = add_query_arg( array( 'bewpi_action' =&gt; 'view', 'post' =&gt; $order-&gt;id, 'nonce' =&gt; wp_create_nonce( 'view' ), ) ); $invoice = new BEWPI_Invoice( $order-&gt;id ); $tags = array( '{formatted_invoice_number}' =&gt; $invoice-&gt;get_formatted_number(), '{order_number}' =&gt; $order-&gt;id, '{formatted_invoice_date}' =&gt; $invoice-&gt;get_formatted_invoice_date(), '{formatted_order_date}' =&gt; $invoice-&gt;get_formatted_order_date(), ); // find and replace placeholders. $title = str_replace( array_keys( $tags ), array_values( $tags ), $atts['title'] ); // MOD OF THE PLUGIN thegem_button(array( 'tag' =&gt; 'a', 'href' =&gt; esc_attr( $url ), 'text' =&gt; esc_html__($title, 'thegem' ), 'style' =&gt; 'outline', 'size' =&gt; 'medium', 'extra_class' =&gt; 'checkout-exit', 'attributes' =&gt; array( 'value' =&gt; esc_attr__( $title, 'thegem' ), ) ), true); // ORIGINAL OUTPUT // printf( '&lt;a href="%1$s"&gt;%2$s&lt;/a&gt;', esc_attr( $url ), esc_html( $title ) ); } </code></pre> <p>MOD OF THE PLUGIN is the new code i added. The original output i put it to comment. Any suggestion is welcome of course. Thanks in advance</p>
[ { "answer_id": 261460, "author": "ferdouswp", "author_id": 114362, "author_profile": "https://wordpress.stackexchange.com/users/114362", "pm_score": 0, "selected": false, "text": "<p>You can use in your child theme directory plugin name and plugin file overwrite. Example child-theme-name/plugin-name/example.php</p>\n" }, { "answer_id": 261472, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 2, "selected": true, "text": "<p>In you case i am considering this is direct function attached to shortcode. You can create your own shortcode and use it to display what you want. You can try this hack hope it will help you,</p>\n\n<pre><code>add_shortcode( 'custom-bewpi-download-invoice', 'print_invoice_func');\n\nfunction print_invoice_func( $atts ) {\nif ( ! isset( $atts['order_id'] ) || 0 === intval( $atts['order_id'] ) ) {\nreturn;\n }\n\n // by default order status should be Processing or Completed.\n $order = wc_get_order( $atts['order_id'] );\n if ( ! $order-&gt;is_paid() ) {\n return;\n }\n\n if ( ! BEWPI_Invoice::exists( $order-&gt;id ) ) {\n return;\n }\n\n $url = add_query_arg( array(\n 'bewpi_action' =&gt; 'view',\n 'post' =&gt; $order-&gt;id,\n 'nonce' =&gt; wp_create_nonce( 'view' ),\n ) );\n\n $invoice = new BEWPI_Invoice( $order-&gt;id );\n $tags = array(\n '{formatted_invoice_number}' =&gt; $invoice-&gt;get_formatted_number(),\n '{order_number}' =&gt; $order-&gt;id,\n '{formatted_invoice_date}' =&gt; $invoice-&gt;get_formatted_invoice_date(),\n '{formatted_order_date}' =&gt; $invoice-&gt;get_formatted_order_date(),\n );\n // find and replace placeholders.\n $title = str_replace( array_keys( $tags ), array_values( $tags ), $atts['title'] );\n // MOD OF THE PLUGIN\n thegem_button(array(\n 'tag' =&gt; 'a',\n 'href' =&gt; esc_attr( $url ),\n 'text' =&gt; esc_html__($title, 'thegem' ),\n 'style' =&gt; 'outline',\n 'size' =&gt; 'medium',\n 'extra_class' =&gt; 'checkout-exit',\n 'attributes' =&gt; array(\n 'value' =&gt; esc_attr__( $title, 'thegem' ),\n )\n ), true);\n // ORIGINAL OUTPUT\n// printf( '&lt;a href=\"%1$s\"&gt;%2$s&lt;/a&gt;', esc_attr( $url ), esc_html( $title ) );\n }\n</code></pre>\n\n<p>paste above code in your functions.php and now use this custom shortcode </p>\n\n<pre><code>echo do_shortcode( '[custom-bewpi-download-invoice title=\"Download (PDF) Invoice {formatted_invoice_number}\" order_id=\"' . $order-&gt;id . '\"]' );\n</code></pre>\n\n<p>Let me know what output it gives to you. </p>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261449", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116284/" ]
i want to change the output of a method inside the class of a plugin from the child function.php without changing the plugin's file. The output i want to change is that instead of a common a href, it uses the template button array. The thing is that the output of the method you get is a shortcode (this shortcode below that you can insert to any template you want). I don't know how to change this method from the child function.php. I modded this plugin file, it works, but it means i don't get to update the plugin without loosing the new button. ``` echo do_shortcode( '[bewpi-download-invoice title="Download (PDF) Invoice {formatted_invoice_number}" order_id="' . $order->id . '"]' ); ``` Here is the method inside the be-woocommerce-pdf-invoices.php class ``` public function download_invoice_shortcode( $atts ) { if ( ! isset( $atts['order_id'] ) || 0 === intval( $atts['order_id'] ) ) { return; } // by default order status should be Processing or Completed. $order = wc_get_order( $atts['order_id'] ); if ( ! $order->is_paid() ) { return; } if ( ! BEWPI_Invoice::exists( $order->id ) ) { return; } $url = add_query_arg( array( 'bewpi_action' => 'view', 'post' => $order->id, 'nonce' => wp_create_nonce( 'view' ), ) ); $invoice = new BEWPI_Invoice( $order->id ); $tags = array( '{formatted_invoice_number}' => $invoice->get_formatted_number(), '{order_number}' => $order->id, '{formatted_invoice_date}' => $invoice->get_formatted_invoice_date(), '{formatted_order_date}' => $invoice->get_formatted_order_date(), ); // find and replace placeholders. $title = str_replace( array_keys( $tags ), array_values( $tags ), $atts['title'] ); // MOD OF THE PLUGIN thegem_button(array( 'tag' => 'a', 'href' => esc_attr( $url ), 'text' => esc_html__($title, 'thegem' ), 'style' => 'outline', 'size' => 'medium', 'extra_class' => 'checkout-exit', 'attributes' => array( 'value' => esc_attr__( $title, 'thegem' ), ) ), true); // ORIGINAL OUTPUT // printf( '<a href="%1$s">%2$s</a>', esc_attr( $url ), esc_html( $title ) ); } ``` MOD OF THE PLUGIN is the new code i added. The original output i put it to comment. Any suggestion is welcome of course. Thanks in advance
In you case i am considering this is direct function attached to shortcode. You can create your own shortcode and use it to display what you want. You can try this hack hope it will help you, ``` add_shortcode( 'custom-bewpi-download-invoice', 'print_invoice_func'); function print_invoice_func( $atts ) { if ( ! isset( $atts['order_id'] ) || 0 === intval( $atts['order_id'] ) ) { return; } // by default order status should be Processing or Completed. $order = wc_get_order( $atts['order_id'] ); if ( ! $order->is_paid() ) { return; } if ( ! BEWPI_Invoice::exists( $order->id ) ) { return; } $url = add_query_arg( array( 'bewpi_action' => 'view', 'post' => $order->id, 'nonce' => wp_create_nonce( 'view' ), ) ); $invoice = new BEWPI_Invoice( $order->id ); $tags = array( '{formatted_invoice_number}' => $invoice->get_formatted_number(), '{order_number}' => $order->id, '{formatted_invoice_date}' => $invoice->get_formatted_invoice_date(), '{formatted_order_date}' => $invoice->get_formatted_order_date(), ); // find and replace placeholders. $title = str_replace( array_keys( $tags ), array_values( $tags ), $atts['title'] ); // MOD OF THE PLUGIN thegem_button(array( 'tag' => 'a', 'href' => esc_attr( $url ), 'text' => esc_html__($title, 'thegem' ), 'style' => 'outline', 'size' => 'medium', 'extra_class' => 'checkout-exit', 'attributes' => array( 'value' => esc_attr__( $title, 'thegem' ), ) ), true); // ORIGINAL OUTPUT // printf( '<a href="%1$s">%2$s</a>', esc_attr( $url ), esc_html( $title ) ); } ``` paste above code in your functions.php and now use this custom shortcode ``` echo do_shortcode( '[custom-bewpi-download-invoice title="Download (PDF) Invoice {formatted_invoice_number}" order_id="' . $order->id . '"]' ); ``` Let me know what output it gives to you.
261,459
<p>I have to change a few things in a page that I have not created. I have to insert some text inside a contact form. When I go to edit that page all I see is some shortcode. It's a custom shortcode that looks like [companyName_apply_form]. I have no idea where it comes from. It's not coming from the contact form plugin that created the other contact forms in the page and I also can't find anything in the template files. Any idea where a custom shortcode like that may come from?</p>
[ { "answer_id": 261464, "author": "jardindeden", "author_id": 116160, "author_profile": "https://wordpress.stackexchange.com/users/116160", "pm_score": 2, "selected": true, "text": "<p>Just use the Windows search bar in <code>wp-content</code> directory and search for <code>companyName_apply_form</code>. You should find the file where the shortcode is created.</p>\n\n<p>To add a shortcode in Wordpress you normally use this syntax:</p>\n\n<pre><code>'add_shortcode(\"shortcode_name\", \"function_name\")'\n</code></pre>\n" }, { "answer_id": 343065, "author": "Kev Sturman", "author_id": 172008, "author_profile": "https://wordpress.stackexchange.com/users/172008", "pm_score": 0, "selected": false, "text": "<p>If you only have FTP access and you don't want to download the entire wp-content directory. </p>\n\n<p>Try logging in via ssh and using grep in your wp-content directory:</p>\n\n<pre><code>grep -iRl \"shortcode_name\" ./\n</code></pre>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115742/" ]
I have to change a few things in a page that I have not created. I have to insert some text inside a contact form. When I go to edit that page all I see is some shortcode. It's a custom shortcode that looks like [companyName\_apply\_form]. I have no idea where it comes from. It's not coming from the contact form plugin that created the other contact forms in the page and I also can't find anything in the template files. Any idea where a custom shortcode like that may come from?
Just use the Windows search bar in `wp-content` directory and search for `companyName_apply_form`. You should find the file where the shortcode is created. To add a shortcode in Wordpress you normally use this syntax: ``` 'add_shortcode("shortcode_name", "function_name")' ```
261,477
<p>I need to change a text content inside a contact form using jQuery, I know that the custom.js file that I'm using is connected as when I do a console.log I can see what I write. </p> <p>When I select the paragraph that I need and change it's html content nothing happens, is it possible for the content to be overwritten by something later? Is there a way to prioritize my code?</p> <pre><code>jQuery("p.help-block.small").html("&lt;p&gt; ... &lt;/p&gt;"); </code></pre>
[ { "answer_id": 261487, "author": "Fabrizio Mele", "author_id": 40463, "author_profile": "https://wordpress.stackexchange.com/users/40463", "pm_score": 1, "selected": false, "text": "<p>Have you tried to wrap it into the <code>jQuery()</code> function?</p>\n\n<pre><code>jQuery(function(){\n jQuery(\"p.help-block.small\").html(\"&lt;p&gt; ... &lt;/p&gt;\");\n})\n</code></pre>\n\n<p>This will cause the code to run one the page is loaded, so that every script has already been parsed&amp;run.</p>\n" }, { "answer_id": 261492, "author": "Self Designs", "author_id": 75780, "author_profile": "https://wordpress.stackexchange.com/users/75780", "pm_score": 0, "selected": false, "text": "<p>You could try calling the \"custom.js\" file at the bottom of your page. This means the HTML and CSS should load first then will get overwritten by the script. You could also do a window.alert() to test that your code inside of JQuery is running correctly.</p>\n" }, { "answer_id": 261494, "author": "AuRise", "author_id": 110134, "author_profile": "https://wordpress.stackexchange.com/users/110134", "pm_score": 3, "selected": true, "text": "<p>In some instances, I'll run a <em>delayed init</em> function in a setTimeout like this:</p>\n\n<pre><code>var delay = setTimeout(function() {\n jQuery(\"p.help-block.small\").html(\"&lt;p&gt; ... &lt;/p&gt;\");\n}, 100);\n</code></pre>\n\n<p>In the event that something is overwriting the html of that paragraph block on page load, this function will run 100 milliseconds after that, making yours the last change to the paragraph. 100 milliseconds is rather quick, so with other elements on the page loading, users may or may not notice the change.</p>\n\n<p>I generally use this type of load with the elements hidden via CSS, and then fading them in when they've been \"loaded\" if there are a lot of elements that will will change in shape or size, e.g. going from three words to three paragraphs would make the page jump, so I may fade it in nicely instead.</p>\n\n<p>Also, since you're calling <strong>.html()</strong> on the paragraph element, you don't need to include the paragraph tags within since the html you would be setting is already wrapped by paragraph tags. If you're just changing text, you could use <strong>.text()</strong> instead. However, if you're including line breaks or span elements within the paragraph, then <strong>.html()</strong> would be appropriate.</p>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261477", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115742/" ]
I need to change a text content inside a contact form using jQuery, I know that the custom.js file that I'm using is connected as when I do a console.log I can see what I write. When I select the paragraph that I need and change it's html content nothing happens, is it possible for the content to be overwritten by something later? Is there a way to prioritize my code? ``` jQuery("p.help-block.small").html("<p> ... </p>"); ```
In some instances, I'll run a *delayed init* function in a setTimeout like this: ``` var delay = setTimeout(function() { jQuery("p.help-block.small").html("<p> ... </p>"); }, 100); ``` In the event that something is overwriting the html of that paragraph block on page load, this function will run 100 milliseconds after that, making yours the last change to the paragraph. 100 milliseconds is rather quick, so with other elements on the page loading, users may or may not notice the change. I generally use this type of load with the elements hidden via CSS, and then fading them in when they've been "loaded" if there are a lot of elements that will will change in shape or size, e.g. going from three words to three paragraphs would make the page jump, so I may fade it in nicely instead. Also, since you're calling **.html()** on the paragraph element, you don't need to include the paragraph tags within since the html you would be setting is already wrapped by paragraph tags. If you're just changing text, you could use **.text()** instead. However, if you're including line breaks or span elements within the paragraph, then **.html()** would be appropriate.
261,478
<p>From <a href="https://wordpress.stackexchange.com/a/261087/3206">this answer</a>, a MU site has the following in <code>wp-config.php</code>:</p> <pre><code>define('WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', true); define('DOMAIN_CURRENT_SITE', 'www.example.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); define('COOKIE_DOMAIN', ''); define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); </code></pre> <p>If I try to login to a child site @ <a href="http://example2.net/wp-login.php" rel="nofollow noreferrer">http://example2.net/wp-login.php</a>, I receive the error:</p> <blockquote> <p>The constant "COOKIE_DOMAIN" is defined (probably in wp-config.php). Please remove or comment out that define() line.</p> </blockquote> <p>If I comment out:</p> <pre><code>define('COOKIE_DOMAIN', ''); </code></pre> <p>I receive the error:</p> <blockquote> <p>ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress</p> </blockquote> <p>The site the answer above refers to is working with the definitions above.</p> <p>Any ideas why the same definitions are not working on this earlier installed Wordpress? (perhaps from around <code>v4.3</code>?)</p>
[ { "answer_id": 262475, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>the first error come from additionnal code which would probably not be usefull with the actual WordPress version (4.7.3 today)</p>\n\n<p>try to comment the line <code>define(\"SUNRISE\"...</code> in <code>wp-config.php</code></p>\n" }, { "answer_id": 262576, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Ensure sunrise.php is in the wp-content directory and that you have defined the following in wp-config.php:</p>\n\n<pre><code>define( 'SUNRISE', 'on' );\n</code></pre>\n\n<p>With sunrise on, you should not define COOKIE_DOMAIN anywhere else as it handles that dynamically on all mapped domains.</p>\n\n<p>My guess is that either you don't have <code>define( 'SUNRISE', 'on' );</code> or you don't have <code>sunrise.php</code> installed correctly. Another thing to check would be that the domain is correctly configured in wp-admin.</p>\n" }, { "answer_id": 262625, "author": "Steve", "author_id": 3206, "author_profile": "https://wordpress.stackexchange.com/users/3206", "pm_score": -1, "selected": false, "text": "<p>I bypassed the inbuilt Wordpress domain mapping, and instead used the <a href=\"https://wordpress.org/plugins/wordpress-mu-domain-mapping/\" rel=\"nofollow noreferrer\">Wordpress MU Domain Mapping</a> plugin, which proved to be much easier to maintain and troubleshoot.</p>\n" }, { "answer_id": 311921, "author": "Martin from WP-Stars.com", "author_id": 85008, "author_profile": "https://wordpress.stackexchange.com/users/85008", "pm_score": 3, "selected": true, "text": "<p>Strangely it worked for me (on more than one multisites) to set SUBDOMAIN_INSTALL to false. To be honest, I hadn't had time to investigate further why ...</p>\n\n<p><code>define('SUBDOMAIN_INSTALL', false);</code></p>\n" }, { "answer_id": 352033, "author": "Will Mosley", "author_id": 177951, "author_profile": "https://wordpress.stackexchange.com/users/177951", "pm_score": 1, "selected": false, "text": "<p>For anyone still struggling with this. It turned out it was the sunrise code that was causing the conflict:</p>\n\n<pre><code>&lt;?php\nif ( !defined( 'SUNRISE_LOADED' ) )\n define( 'SUNRISE_LOADED', 1 );\n\nif ( defined( 'COOKIE_DOMAIN' ) ) {\n die( 'The constant \"COOKIE_DOMAIN\" is defined (probably in wp-config.php). Please remove or comment out that define() line.' );\n}\n</code></pre>\n\n<p>...</p>\n\n<p>I commented out the sunrise in wp-config.php</p>\n\n<p><code>//define( 'SUNRISE', 'on' );</code></p>\n\n<p>And added </p>\n\n<p><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code></p>\n\n<p>before the <code>/*</code> That's all, stop editing! Happy blogging. */ comment.</p>\n\n<p>That made me login to my multisite again and all sub sites, but worked like a charm!!!</p>\n\n<p>Really hope this helps someone else struggling with this very very frustrating issue. :)</p>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261478", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
From [this answer](https://wordpress.stackexchange.com/a/261087/3206), a MU site has the following in `wp-config.php`: ``` define('WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', true); define('DOMAIN_CURRENT_SITE', 'www.example.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); define('COOKIE_DOMAIN', ''); define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); ``` If I try to login to a child site @ <http://example2.net/wp-login.php>, I receive the error: > > The constant "COOKIE\_DOMAIN" is defined (probably in wp-config.php). > Please remove or comment out that define() line. > > > If I comment out: ``` define('COOKIE_DOMAIN', ''); ``` I receive the error: > > ERROR: Cookies are blocked or not supported by your browser. You must > enable cookies to use WordPress > > > The site the answer above refers to is working with the definitions above. Any ideas why the same definitions are not working on this earlier installed Wordpress? (perhaps from around `v4.3`?)
Strangely it worked for me (on more than one multisites) to set SUBDOMAIN\_INSTALL to false. To be honest, I hadn't had time to investigate further why ... `define('SUBDOMAIN_INSTALL', false);`
261,482
<p>I want to show posts using WP_Query functions. Also I want to add random order.</p> <p>So I try</p> <pre><code>&lt;?php $temp = $wp_query; $wp_query= null; $args = array( 'orderby' =&gt; 'rand', ); $wp_query = new WP_Query($args); $wp_query-&gt;query('showposts=8' . '&amp;paged='.$paged ); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; </code></pre> <p>I can see 8 posts but it seems 'orderby' => 'rand' doesn't work. </p>
[ { "answer_id": 261483, "author": "Svartbaard", "author_id": 112928, "author_profile": "https://wordpress.stackexchange.com/users/112928", "pm_score": 1, "selected": false, "text": "<p>Take a look at the WP_Query class reference and work yourself up from there. Try the basic examples, play around with the parameters until you get a feel for how WP_Query and the loop works.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>The reason your query isn't working is that you are not passing the parameters correctly (use the args array for all) and using deprecated params.</p>\n" }, { "answer_id": 261825, "author": "MrValueType", "author_id": 12473, "author_profile": "https://wordpress.stackexchange.com/users/12473", "pm_score": 3, "selected": true, "text": "<p>It's quite some time since I worked with WordPress, but it seems to me that:</p>\n\n<h1>You're executing the query twice.</h1>\n\n<ul>\n<li><p>First when you pass <code>$args</code> to the constructor during instantiation.</p></li>\n<li><p>Second when you call <code>query()</code>.</p></li>\n</ul>\n\n<p><strong>With this, you're essentially overwriting the first query (the one that contains the orderby=rand).</strong></p>\n\n<p>The <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">documentation of WP_Query</a> mentions that <code>get_posts()</code> is called if you use a parameter in the constructor, and it shouldn't be called twice:</p>\n\n<blockquote>\n <p><strong>&amp;get_posts()</strong> – Fetch and return the requested posts from the database.\n Also populate $posts and $post_count. Note: <strong>This is called during\n construction if WP_Query is constructed with arguments.</strong> It is not\n idempotent and <strong>should not be called more than once on the same query\n object.</strong> Doing so may result in a broken query.</p>\n</blockquote>\n\n<p>And the <code>query()</code> method's documentation states that it calls <code>get_posts()</code>, therefore it's called twice:</p>\n\n<blockquote>\n <p><strong>&amp;query( $query )</strong> – <strong>Call</strong> parse_query() and <strong>get_posts()</strong>. Return the\n results of get_posts().</p>\n</blockquote>\n\n<h1>The solution:</h1>\n\n<ul>\n<li>You should either put everything in <code>$args</code>, or</li>\n<li>add the <code>orderby</code> parameter too to the <code>$wp_query-&gt;query(..)</code> call.</li>\n</ul>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261482", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116307/" ]
I want to show posts using WP\_Query functions. Also I want to add random order. So I try ``` <?php $temp = $wp_query; $wp_query= null; $args = array( 'orderby' => 'rand', ); $wp_query = new WP_Query($args); $wp_query->query('showposts=8' . '&paged='.$paged ); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> ``` I can see 8 posts but it seems 'orderby' => 'rand' doesn't work.
It's quite some time since I worked with WordPress, but it seems to me that: You're executing the query twice. ================================= * First when you pass `$args` to the constructor during instantiation. * Second when you call `query()`. **With this, you're essentially overwriting the first query (the one that contains the orderby=rand).** The [documentation of WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) mentions that `get_posts()` is called if you use a parameter in the constructor, and it shouldn't be called twice: > > **&get\_posts()** – Fetch and return the requested posts from the database. > Also populate $posts and $post\_count. Note: **This is called during > construction if WP\_Query is constructed with arguments.** It is not > idempotent and **should not be called more than once on the same query > object.** Doing so may result in a broken query. > > > And the `query()` method's documentation states that it calls `get_posts()`, therefore it's called twice: > > **&query( $query )** – **Call** parse\_query() and **get\_posts()**. Return the > results of get\_posts(). > > > The solution: ============= * You should either put everything in `$args`, or * add the `orderby` parameter too to the `$wp_query->query(..)` call.
261,516
<p>Can anybody help me with a function to delete posts older than one year with postmeta, attachements and files?</p> <p>Tnx</p>
[ { "answer_id": 289692, "author": "Md. Mrinal Haque", "author_id": 111354, "author_profile": "https://wordpress.stackexchange.com/users/111354", "pm_score": -1, "selected": false, "text": "<p>I find-out an way, when working on a <code>cron</code> related project.<br/>\n1. Install and active <code>[WP Crontol plugin][1]</code>\n2. Go to Tools->Cron Events.\n3. Create new cron job at `Add PHP Cron Event tab. Here, I use PHP code <br/></p>\n\n<pre><code>global $wpdb;\n$posts_table = $wpdb-&gt;prefix . 'posts';\n$term_relationships_table = $wpdb-&gt;prefix . 'term_relationships';\n$postmeta_table = $wpdb-&gt;prefix . 'postmeta';\n\n$sql = \"DELETE a, b, c\nFROM $posts_table a\nLEFT JOIN $term_relationships_table b ON (a.ID = b.object_id)\nLEFT JOIN $postmeta_table c ON (a.ID = c.post_id)\nWHERE a.post_type = 'post'\nAND DATEDIFF( NOW(), a.post_date) &gt; 365\n\";\n\n$wpdb-&gt;query( $wpdb-&gt;prepare($sql) );\n</code></pre>\n\n<p><br/>\n<code>now</code> and <code>12:00:00</code> in <code>Next Run</code> <br/>\n<code>Once Hourly</code> in <code>Recurrence</code><br/></p>\n\n<ol start=\"4\">\n<li>Save this cron event and click on run now.</li>\n</ol>\n" }, { "answer_id": 390438, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 0, "selected": false, "text": "<p>I've already answered that type of question <a href=\"https://wordpress.stackexchange.com/questions/289103/automatically-delete-attachments-and-posts/289243#289243\">here</a> but you want to delete <code>post_meta</code> too. Here is your code. Please test this on <code>localhost</code> first.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\n// Please use this function carefully.\n// Changes can't undone. Best regards from Serkan Algur :)\n// Let the function begin\nfunction delete_oldest_posts_salgur()\n{\n // We will collect posts from two years ago :)\n $args = array(\n 'date_query' =&gt; array(\n array(\n 'column' =&gt; 'post_date_gmt',\n 'before' =&gt; '2 years ago', // change this definition for your needs\n ),\n ),\n 'posts_per_page' =&gt; -1,\n );\n // Get posts via WP_Query\n $query = new WP_Query($args);\n //We are doing this for 'foreach'\n $posts = $query-&gt;get_posts();\n\n foreach ($posts as $post) {\n echo $post-&gt;ID;\n $args = array(\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'ASC',\n 'post_mime_type' =&gt; 'image', // only for images. Look at https://codex.wordpress.org/Function_Reference/get_children\n 'post_parent' =&gt; $post-&gt;ID,\n 'post_type' =&gt; 'attachment',\n );\n\n $attachments = get_children($args);\n $post_metas = get_post_meta($post-&gt;ID); // Get all post metas\n\n if ($post_metas) {\n foreach ($post_metas as $key =&gt; $pmeta) { //delte all of them\n delete_post_meta($post-&gt;ID, $key);\n }\n }\n\n if ($attachments) {\n foreach ($attachments as $attachment) {\n wp_delete_attachment($attachment-&gt;ID, true); //If You Want to trash post set true to false\n }\n }\n wp_delete_post($post-&gt;ID, true); //If You Want to trash post set true to false\n }\n}\n\n// Problem Solver Cron Job definition\nfunction cron_delete_oldest_posts_salgur()\n{\n if (! wp_next_scheduled('delete_oldest_posts_salgur')) {\n wp_schedule_event(current_time('timestamp'), 'daily', 'delete_oldest_posts_salgur');\n }\n}\nadd_action('wp', 'cron_delete_oldest_posts_salgur');\n</code></pre>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261516", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90139/" ]
Can anybody help me with a function to delete posts older than one year with postmeta, attachements and files? Tnx
I've already answered that type of question [here](https://wordpress.stackexchange.com/questions/289103/automatically-delete-attachments-and-posts/289243#289243) but you want to delete `post_meta` too. Here is your code. Please test this on `localhost` first. ```php <?php // Please use this function carefully. // Changes can't undone. Best regards from Serkan Algur :) // Let the function begin function delete_oldest_posts_salgur() { // We will collect posts from two years ago :) $args = array( 'date_query' => array( array( 'column' => 'post_date_gmt', 'before' => '2 years ago', // change this definition for your needs ), ), 'posts_per_page' => -1, ); // Get posts via WP_Query $query = new WP_Query($args); //We are doing this for 'foreach' $posts = $query->get_posts(); foreach ($posts as $post) { echo $post->ID; $args = array( 'posts_per_page' => -1, 'order' => 'ASC', 'post_mime_type' => 'image', // only for images. Look at https://codex.wordpress.org/Function_Reference/get_children 'post_parent' => $post->ID, 'post_type' => 'attachment', ); $attachments = get_children($args); $post_metas = get_post_meta($post->ID); // Get all post metas if ($post_metas) { foreach ($post_metas as $key => $pmeta) { //delte all of them delete_post_meta($post->ID, $key); } } if ($attachments) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); //If You Want to trash post set true to false } } wp_delete_post($post->ID, true); //If You Want to trash post set true to false } } // Problem Solver Cron Job definition function cron_delete_oldest_posts_salgur() { if (! wp_next_scheduled('delete_oldest_posts_salgur')) { wp_schedule_event(current_time('timestamp'), 'daily', 'delete_oldest_posts_salgur'); } } add_action('wp', 'cron_delete_oldest_posts_salgur'); ```
261,527
<p>I inherited a site with a custom php file for a custom sidebar. The sidebar is pulled in to action on pages using the "About" template. The sidebar is supposed to be displaying the image of the person whose profile it is on the top of the sidebar. Only one of the 4 profiles is pulling the correct image (the other 3 are trying to pull images from an old dev site that no longer exists). So, I need to update the 3 pages to pull images from the current site. But, I can't for the life of me figure out where to do that because I can't figure out where the photo is being pulled from. The profile pages are just regular pages whose parent is the "meet the team" page and they are using the About Page template.</p> <p>The code in question is this: </p> <p><code>&lt;img src="&lt;?php $image = get_post_meta(get_the_ID(),'image',true); $profile = get_post_meta(get_the_ID(),'profile',true); print $image; ?&gt;" /&gt;</code></p> <p>Any help or insight into what photo this is pulling would be greatly appreciated.</p>
[ { "answer_id": 289692, "author": "Md. Mrinal Haque", "author_id": 111354, "author_profile": "https://wordpress.stackexchange.com/users/111354", "pm_score": -1, "selected": false, "text": "<p>I find-out an way, when working on a <code>cron</code> related project.<br/>\n1. Install and active <code>[WP Crontol plugin][1]</code>\n2. Go to Tools->Cron Events.\n3. Create new cron job at `Add PHP Cron Event tab. Here, I use PHP code <br/></p>\n\n<pre><code>global $wpdb;\n$posts_table = $wpdb-&gt;prefix . 'posts';\n$term_relationships_table = $wpdb-&gt;prefix . 'term_relationships';\n$postmeta_table = $wpdb-&gt;prefix . 'postmeta';\n\n$sql = \"DELETE a, b, c\nFROM $posts_table a\nLEFT JOIN $term_relationships_table b ON (a.ID = b.object_id)\nLEFT JOIN $postmeta_table c ON (a.ID = c.post_id)\nWHERE a.post_type = 'post'\nAND DATEDIFF( NOW(), a.post_date) &gt; 365\n\";\n\n$wpdb-&gt;query( $wpdb-&gt;prepare($sql) );\n</code></pre>\n\n<p><br/>\n<code>now</code> and <code>12:00:00</code> in <code>Next Run</code> <br/>\n<code>Once Hourly</code> in <code>Recurrence</code><br/></p>\n\n<ol start=\"4\">\n<li>Save this cron event and click on run now.</li>\n</ol>\n" }, { "answer_id": 390438, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 0, "selected": false, "text": "<p>I've already answered that type of question <a href=\"https://wordpress.stackexchange.com/questions/289103/automatically-delete-attachments-and-posts/289243#289243\">here</a> but you want to delete <code>post_meta</code> too. Here is your code. Please test this on <code>localhost</code> first.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\n// Please use this function carefully.\n// Changes can't undone. Best regards from Serkan Algur :)\n// Let the function begin\nfunction delete_oldest_posts_salgur()\n{\n // We will collect posts from two years ago :)\n $args = array(\n 'date_query' =&gt; array(\n array(\n 'column' =&gt; 'post_date_gmt',\n 'before' =&gt; '2 years ago', // change this definition for your needs\n ),\n ),\n 'posts_per_page' =&gt; -1,\n );\n // Get posts via WP_Query\n $query = new WP_Query($args);\n //We are doing this for 'foreach'\n $posts = $query-&gt;get_posts();\n\n foreach ($posts as $post) {\n echo $post-&gt;ID;\n $args = array(\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'ASC',\n 'post_mime_type' =&gt; 'image', // only for images. Look at https://codex.wordpress.org/Function_Reference/get_children\n 'post_parent' =&gt; $post-&gt;ID,\n 'post_type' =&gt; 'attachment',\n );\n\n $attachments = get_children($args);\n $post_metas = get_post_meta($post-&gt;ID); // Get all post metas\n\n if ($post_metas) {\n foreach ($post_metas as $key =&gt; $pmeta) { //delte all of them\n delete_post_meta($post-&gt;ID, $key);\n }\n }\n\n if ($attachments) {\n foreach ($attachments as $attachment) {\n wp_delete_attachment($attachment-&gt;ID, true); //If You Want to trash post set true to false\n }\n }\n wp_delete_post($post-&gt;ID, true); //If You Want to trash post set true to false\n }\n}\n\n// Problem Solver Cron Job definition\nfunction cron_delete_oldest_posts_salgur()\n{\n if (! wp_next_scheduled('delete_oldest_posts_salgur')) {\n wp_schedule_event(current_time('timestamp'), 'daily', 'delete_oldest_posts_salgur');\n }\n}\nadd_action('wp', 'cron_delete_oldest_posts_salgur');\n</code></pre>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116340/" ]
I inherited a site with a custom php file for a custom sidebar. The sidebar is pulled in to action on pages using the "About" template. The sidebar is supposed to be displaying the image of the person whose profile it is on the top of the sidebar. Only one of the 4 profiles is pulling the correct image (the other 3 are trying to pull images from an old dev site that no longer exists). So, I need to update the 3 pages to pull images from the current site. But, I can't for the life of me figure out where to do that because I can't figure out where the photo is being pulled from. The profile pages are just regular pages whose parent is the "meet the team" page and they are using the About Page template. The code in question is this: `<img src="<?php $image = get_post_meta(get_the_ID(),'image',true); $profile = get_post_meta(get_the_ID(),'profile',true); print $image; ?>" />` Any help or insight into what photo this is pulling would be greatly appreciated.
I've already answered that type of question [here](https://wordpress.stackexchange.com/questions/289103/automatically-delete-attachments-and-posts/289243#289243) but you want to delete `post_meta` too. Here is your code. Please test this on `localhost` first. ```php <?php // Please use this function carefully. // Changes can't undone. Best regards from Serkan Algur :) // Let the function begin function delete_oldest_posts_salgur() { // We will collect posts from two years ago :) $args = array( 'date_query' => array( array( 'column' => 'post_date_gmt', 'before' => '2 years ago', // change this definition for your needs ), ), 'posts_per_page' => -1, ); // Get posts via WP_Query $query = new WP_Query($args); //We are doing this for 'foreach' $posts = $query->get_posts(); foreach ($posts as $post) { echo $post->ID; $args = array( 'posts_per_page' => -1, 'order' => 'ASC', 'post_mime_type' => 'image', // only for images. Look at https://codex.wordpress.org/Function_Reference/get_children 'post_parent' => $post->ID, 'post_type' => 'attachment', ); $attachments = get_children($args); $post_metas = get_post_meta($post->ID); // Get all post metas if ($post_metas) { foreach ($post_metas as $key => $pmeta) { //delte all of them delete_post_meta($post->ID, $key); } } if ($attachments) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); //If You Want to trash post set true to false } } wp_delete_post($post->ID, true); //If You Want to trash post set true to false } } // Problem Solver Cron Job definition function cron_delete_oldest_posts_salgur() { if (! wp_next_scheduled('delete_oldest_posts_salgur')) { wp_schedule_event(current_time('timestamp'), 'daily', 'delete_oldest_posts_salgur'); } } add_action('wp', 'cron_delete_oldest_posts_salgur'); ```
261,560
<p>I am creating a plugin settings page using the register_settings() api. </p> <p>How can i create a html editor (wordpress default editor would be splendid) instead of just a text area.</p> <p>This is an example of the code I am using:</p> <pre><code>add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings' ); ?&gt; &lt;textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'&gt; &lt;?php echo $options['pw_textarea_intro']; ?&gt; &lt;/textarea&gt; &lt;?php } </code></pre> <p>I've stripped the code down to just the one field, but there are more fields.</p> <p>This is rendering the text area for me but I can't format text and it keeps adding extra tabs before and after any text I enter into the settings page.</p> <pre><code>add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); add_settings_field( 'pw_intro', __( 'Intro', 'pw' ), 'pw_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings' ); ?&gt; &lt;textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'&gt; &lt;?php echo $options['pw_textarea_intro']; ?&gt; &lt;/textarea&gt; &lt;?php } function pw_intro_render() { $options = get_option( 'pw_settings' ); echo wp_editor( $options['pw_intro'], 'pw_intro', array('textarea_name' =&gt; 'pw_intro', 'media_buttons' =&gt; false) ); } </code></pre> <p>I added the new code as Dave suggested (thanks!) and now it loads the wp editor, but when I click save to commit changes it doesn't save the wp_editor content. Any ideas? </p>
[ { "answer_id": 261585, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>always always always escape output (ok, some rare cases you should not, but the rule of thumb is to escape). For <code>textarea</code> you need to html escape the content</p>\n\n<p><code>&lt;textarea&gt;&lt;?php echo esc_html(get_option('my option')?&gt;&lt;/textarea&gt;</code></p>\n\n<p>having the space between the start and end <code>textarea</code> tags and the actual output also do not help and probably add some spaces around your actual \"\"content\"</p>\n" }, { "answer_id": 261659, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Here's an updated version of your original code, which solves the saving issue.</p>\n\n<p>The reason that the content inside of the WP Editor was not saving was due to the value of the <code>textarea_name</code> parameter passed to <code>wp_editor()</code>.</p>\n\n<p>This is wrong:</p>\n\n<pre><code> 'textarea_name' =&gt; 'pw_intro',\n</code></pre>\n\n<p>It should look like this:</p>\n\n<pre><code> 'textarea_name' =&gt; 'pw_settings[pw_intro]',\n</code></pre>\n\n<p>I also removed the echo from <code>wp_editor()</code>, fixed up the extra spaces around the text area, etc.</p>\n\n<p>Full code example:</p>\n\n<pre><code>add_action( 'admin_menu', 'pw_add_admin_menu' );\nadd_action( 'admin_init', 'pw_settings_init' );\nfunction pw_add_admin_menu( ) { \n add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' );\n}\n\nfunction pw_settings_init( ) { \n register_setting( 'pluginPage', 'pw_settings' );\n\n add_settings_section(\n 'pw_pluginPage_section', \n __( 'Live Credentials', 'pw' ), \n 'pw_settings_section_callback', \n 'pluginPage'\n );\n\n add_settings_field( \n 'pw_textarea_intro', \n __( 'Header Intro Text', 'pw' ), \n 'pw_textarea_intro_render', \n 'pluginPage', \n 'pw_pluginPage_section' \n );\n\n add_settings_field( \n 'pw_intro', \n __( 'Intro', 'pw' ), \n 'pw_intro_render', \n 'pluginPage', \n 'pw_pluginPage_section' \n );\n}\n\nfunction pw_textarea_intro_render( ) { \n $options = get_option( 'pw_settings', array() );\n\n?&gt;&lt;textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'&gt;&lt;?php echo isset( $options['pw_textarea_intro'] ) ? $options['pw_textarea_intro'] : false; ?&gt;&lt;/textarea&gt;&lt;?php\n}\n\nfunction pw_intro_render() {\n $options = get_option( 'pw_settings', array() );\n $content = isset( $options['pw_intro'] ) ? $options['pw_intro'] : false;\n wp_editor( $content, 'pw_intro', array( \n 'textarea_name' =&gt; 'pw_settings[pw_intro]',\n 'media_buttons' =&gt; false,\n ) );\n}\n\n// section content cb\nfunction pw_settings_section_callback() {\n echo '&lt;p&gt;Section Introduction.&lt;/p&gt;';\n}\n</code></pre>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I am creating a plugin settings page using the register\_settings() api. How can i create a html editor (wordpress default editor would be splendid) instead of just a text area. This is an example of the code I am using: ``` add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings' ); ?> <textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'> <?php echo $options['pw_textarea_intro']; ?> </textarea> <?php } ``` I've stripped the code down to just the one field, but there are more fields. This is rendering the text area for me but I can't format text and it keeps adding extra tabs before and after any text I enter into the settings page. ``` add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); add_settings_field( 'pw_intro', __( 'Intro', 'pw' ), 'pw_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings' ); ?> <textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'> <?php echo $options['pw_textarea_intro']; ?> </textarea> <?php } function pw_intro_render() { $options = get_option( 'pw_settings' ); echo wp_editor( $options['pw_intro'], 'pw_intro', array('textarea_name' => 'pw_intro', 'media_buttons' => false) ); } ``` I added the new code as Dave suggested (thanks!) and now it loads the wp editor, but when I click save to commit changes it doesn't save the wp\_editor content. Any ideas?
Here's an updated version of your original code, which solves the saving issue. The reason that the content inside of the WP Editor was not saving was due to the value of the `textarea_name` parameter passed to `wp_editor()`. This is wrong: ``` 'textarea_name' => 'pw_intro', ``` It should look like this: ``` 'textarea_name' => 'pw_settings[pw_intro]', ``` I also removed the echo from `wp_editor()`, fixed up the extra spaces around the text area, etc. Full code example: ``` add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); add_settings_field( 'pw_intro', __( 'Intro', 'pw' ), 'pw_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings', array() ); ?><textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'><?php echo isset( $options['pw_textarea_intro'] ) ? $options['pw_textarea_intro'] : false; ?></textarea><?php } function pw_intro_render() { $options = get_option( 'pw_settings', array() ); $content = isset( $options['pw_intro'] ) ? $options['pw_intro'] : false; wp_editor( $content, 'pw_intro', array( 'textarea_name' => 'pw_settings[pw_intro]', 'media_buttons' => false, ) ); } // section content cb function pw_settings_section_callback() { echo '<p>Section Introduction.</p>'; } ```
261,562
<p>I want to remove the home page header image from all other pages. When you click an individual article, the feature image and header image blend into each other in an unflattering way.There needs to be separation between the images or have the header image remain on the home page only.</p> <p>www.mybesthelperblog.wordpress.com</p>
[ { "answer_id": 261585, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>always always always escape output (ok, some rare cases you should not, but the rule of thumb is to escape). For <code>textarea</code> you need to html escape the content</p>\n\n<p><code>&lt;textarea&gt;&lt;?php echo esc_html(get_option('my option')?&gt;&lt;/textarea&gt;</code></p>\n\n<p>having the space between the start and end <code>textarea</code> tags and the actual output also do not help and probably add some spaces around your actual \"\"content\"</p>\n" }, { "answer_id": 261659, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Here's an updated version of your original code, which solves the saving issue.</p>\n\n<p>The reason that the content inside of the WP Editor was not saving was due to the value of the <code>textarea_name</code> parameter passed to <code>wp_editor()</code>.</p>\n\n<p>This is wrong:</p>\n\n<pre><code> 'textarea_name' =&gt; 'pw_intro',\n</code></pre>\n\n<p>It should look like this:</p>\n\n<pre><code> 'textarea_name' =&gt; 'pw_settings[pw_intro]',\n</code></pre>\n\n<p>I also removed the echo from <code>wp_editor()</code>, fixed up the extra spaces around the text area, etc.</p>\n\n<p>Full code example:</p>\n\n<pre><code>add_action( 'admin_menu', 'pw_add_admin_menu' );\nadd_action( 'admin_init', 'pw_settings_init' );\nfunction pw_add_admin_menu( ) { \n add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' );\n}\n\nfunction pw_settings_init( ) { \n register_setting( 'pluginPage', 'pw_settings' );\n\n add_settings_section(\n 'pw_pluginPage_section', \n __( 'Live Credentials', 'pw' ), \n 'pw_settings_section_callback', \n 'pluginPage'\n );\n\n add_settings_field( \n 'pw_textarea_intro', \n __( 'Header Intro Text', 'pw' ), \n 'pw_textarea_intro_render', \n 'pluginPage', \n 'pw_pluginPage_section' \n );\n\n add_settings_field( \n 'pw_intro', \n __( 'Intro', 'pw' ), \n 'pw_intro_render', \n 'pluginPage', \n 'pw_pluginPage_section' \n );\n}\n\nfunction pw_textarea_intro_render( ) { \n $options = get_option( 'pw_settings', array() );\n\n?&gt;&lt;textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'&gt;&lt;?php echo isset( $options['pw_textarea_intro'] ) ? $options['pw_textarea_intro'] : false; ?&gt;&lt;/textarea&gt;&lt;?php\n}\n\nfunction pw_intro_render() {\n $options = get_option( 'pw_settings', array() );\n $content = isset( $options['pw_intro'] ) ? $options['pw_intro'] : false;\n wp_editor( $content, 'pw_intro', array( \n 'textarea_name' =&gt; 'pw_settings[pw_intro]',\n 'media_buttons' =&gt; false,\n ) );\n}\n\n// section content cb\nfunction pw_settings_section_callback() {\n echo '&lt;p&gt;Section Introduction.&lt;/p&gt;';\n}\n</code></pre>\n" } ]
2017/03/27
[ "https://wordpress.stackexchange.com/questions/261562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116359/" ]
I want to remove the home page header image from all other pages. When you click an individual article, the feature image and header image blend into each other in an unflattering way.There needs to be separation between the images or have the header image remain on the home page only. www.mybesthelperblog.wordpress.com
Here's an updated version of your original code, which solves the saving issue. The reason that the content inside of the WP Editor was not saving was due to the value of the `textarea_name` parameter passed to `wp_editor()`. This is wrong: ``` 'textarea_name' => 'pw_intro', ``` It should look like this: ``` 'textarea_name' => 'pw_settings[pw_intro]', ``` I also removed the echo from `wp_editor()`, fixed up the extra spaces around the text area, etc. Full code example: ``` add_action( 'admin_menu', 'pw_add_admin_menu' ); add_action( 'admin_init', 'pw_settings_init' ); function pw_add_admin_menu( ) { add_menu_page( 'wpset', 'wpset', 'manage_options', 'pset', 'pw_options_page' ); } function pw_settings_init( ) { register_setting( 'pluginPage', 'pw_settings' ); add_settings_section( 'pw_pluginPage_section', __( 'Live Credentials', 'pw' ), 'pw_settings_section_callback', 'pluginPage' ); add_settings_field( 'pw_textarea_intro', __( 'Header Intro Text', 'pw' ), 'pw_textarea_intro_render', 'pluginPage', 'pw_pluginPage_section' ); add_settings_field( 'pw_intro', __( 'Intro', 'pw' ), 'pw_intro_render', 'pluginPage', 'pw_pluginPage_section' ); } function pw_textarea_intro_render( ) { $options = get_option( 'pw_settings', array() ); ?><textarea cols='40' rows='5' name='pw_settings[pw_textarea_intro]'><?php echo isset( $options['pw_textarea_intro'] ) ? $options['pw_textarea_intro'] : false; ?></textarea><?php } function pw_intro_render() { $options = get_option( 'pw_settings', array() ); $content = isset( $options['pw_intro'] ) ? $options['pw_intro'] : false; wp_editor( $content, 'pw_intro', array( 'textarea_name' => 'pw_settings[pw_intro]', 'media_buttons' => false, ) ); } // section content cb function pw_settings_section_callback() { echo '<p>Section Introduction.</p>'; } ```
261,603
<p>I have a sample:</p> <p><strong>CODE PHP:</strong></p> <pre><code> &lt;ul class="categories-list"&gt; &lt;?php wp_list_categories('title_li='); ?&gt; &lt;/ul&gt; </code></pre> <p>This code displays the category list sorted by name.</p> <p>What I want to do is to have a custom order ... not by name not by id.</p> <p>For example, this order:</p> <pre><code> 1. Category with ID 5: 2. Category with ID 3: 3. Category with ID 9: </code></pre> <p>How can I do this using the function above?</p>
[ { "answer_id": 261609, "author": "Nehal Shah", "author_id": 114177, "author_profile": "https://wordpress.stackexchange.com/users/114177", "pm_score": 1, "selected": false, "text": "<p>You can use the shuffle() function to get the categories in random order.\nLike this, </p>\n\n<pre><code>$categories = get_categories();\nshuffle( $categories );\n</code></pre>\n\n<p>Hope this works for you!</p>\n" }, { "answer_id": 261610, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"> wp_list_categories();</a> give you formatted output,</p>\n\n<p>To display elements for custom layout you can use get_categories() or get_terms() function.</p>\n" }, { "answer_id": 261612, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>You will need to <a href=\"https://developer.wordpress.org/reference/functions/add_term_meta/\" rel=\"nofollow noreferrer\">add term meta</a> to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order (<a href=\"http://themehybrid.com/weblog/introduction-to-wordpress-term-meta\" rel=\"nofollow noreferrer\">tutorial</a>). Let's say you have generated a meta field called <code>my_cat_meta</code> which holds integers that say in which order you want them to be displayed.</p>\n\n<p>Now you can pass this metakey to <code>wp_list_categories</code>. This function ultimately relies on <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms</code></a>, which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'meta_key' -&gt; 'my_cat_meta',\n 'orderby'-&gt; 'meta_key');\nwp_list_categories ($args);\n</code></pre>\n\n<p>A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'orderby'-&gt; 'description');\nwp_list_categories ($args);\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261603", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116384/" ]
I have a sample: **CODE PHP:** ``` <ul class="categories-list"> <?php wp_list_categories('title_li='); ?> </ul> ``` This code displays the category list sorted by name. What I want to do is to have a custom order ... not by name not by id. For example, this order: ``` 1. Category with ID 5: 2. Category with ID 3: 3. Category with ID 9: ``` How can I do this using the function above?
You will need to [add term meta](https://developer.wordpress.org/reference/functions/add_term_meta/) to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order ([tutorial](http://themehybrid.com/weblog/introduction-to-wordpress-term-meta)). Let's say you have generated a meta field called `my_cat_meta` which holds integers that say in which order you want them to be displayed. Now you can pass this metakey to `wp_list_categories`. This function ultimately relies on [`get_terms`](https://developer.wordpress.org/reference/functions/get_terms/), which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to: ``` $args = array ( 'title_li' -> '', 'meta_key' -> 'my_cat_meta', 'orderby'-> 'meta_key'); wp_list_categories ($args); ``` A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use: ``` $args = array ( 'title_li' -> '', 'orderby'-> 'description'); wp_list_categories ($args); ```
261,628
<p>I have a WordPress.org site. I am planning to use a new theme for the site. I have Installed the template and it is currently under the Themes folder. </p> <p>The old theme is currently active. I would like to work on the new template and keep the old template active.</p> <p>Once I finish working on the new theme, I would then like to make that active.</p> <p>How can I achieve this?</p>
[ { "answer_id": 261609, "author": "Nehal Shah", "author_id": 114177, "author_profile": "https://wordpress.stackexchange.com/users/114177", "pm_score": 1, "selected": false, "text": "<p>You can use the shuffle() function to get the categories in random order.\nLike this, </p>\n\n<pre><code>$categories = get_categories();\nshuffle( $categories );\n</code></pre>\n\n<p>Hope this works for you!</p>\n" }, { "answer_id": 261610, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"> wp_list_categories();</a> give you formatted output,</p>\n\n<p>To display elements for custom layout you can use get_categories() or get_terms() function.</p>\n" }, { "answer_id": 261612, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>You will need to <a href=\"https://developer.wordpress.org/reference/functions/add_term_meta/\" rel=\"nofollow noreferrer\">add term meta</a> to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order (<a href=\"http://themehybrid.com/weblog/introduction-to-wordpress-term-meta\" rel=\"nofollow noreferrer\">tutorial</a>). Let's say you have generated a meta field called <code>my_cat_meta</code> which holds integers that say in which order you want them to be displayed.</p>\n\n<p>Now you can pass this metakey to <code>wp_list_categories</code>. This function ultimately relies on <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms</code></a>, which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'meta_key' -&gt; 'my_cat_meta',\n 'orderby'-&gt; 'meta_key');\nwp_list_categories ($args);\n</code></pre>\n\n<p>A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'orderby'-&gt; 'description');\nwp_list_categories ($args);\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92500/" ]
I have a WordPress.org site. I am planning to use a new theme for the site. I have Installed the template and it is currently under the Themes folder. The old theme is currently active. I would like to work on the new template and keep the old template active. Once I finish working on the new theme, I would then like to make that active. How can I achieve this?
You will need to [add term meta](https://developer.wordpress.org/reference/functions/add_term_meta/) to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order ([tutorial](http://themehybrid.com/weblog/introduction-to-wordpress-term-meta)). Let's say you have generated a meta field called `my_cat_meta` which holds integers that say in which order you want them to be displayed. Now you can pass this metakey to `wp_list_categories`. This function ultimately relies on [`get_terms`](https://developer.wordpress.org/reference/functions/get_terms/), which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to: ``` $args = array ( 'title_li' -> '', 'meta_key' -> 'my_cat_meta', 'orderby'-> 'meta_key'); wp_list_categories ($args); ``` A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use: ``` $args = array ( 'title_li' -> '', 'orderby'-> 'description'); wp_list_categories ($args); ```
261,633
<p>I know this is normally an obvious question with a lot of answers (like <a href="https://wordpress.stackexchange.com/questions/120759/show-post-titles-only-on-the-homepage">here</a>), but I'd like to show only the beginning of the posts with a "read more" button. I don't use excerpts, so I'd like Wordpress to automaticly grab the first 55 words or the first phrase to display it.</p> <p>I use the theme Toivo Lite. The index.php is:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php do_action( 'toivo_before_loop' ); // Action hook before loop. ?&gt; &lt;?php /* Start the Loop */ ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'content', ( post_type_supports( get_post_type(), 'post-formats' ) ? get_post_format() : get_post_type() ) ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php the_posts_pagination( array( 'prev_text' =&gt; __( 'Previous page', 'toivo-lite' ), 'next_text' =&gt; __( 'Next page', 'toivo-lite' ), 'before_page_number' =&gt; '&lt;span class="meta-nav screen-reader-text"&gt;' . __( 'Page', 'toivo-lite' ) . ' &lt;/span&gt;', ) ); ?&gt; &lt;?php else : ?&gt; &lt;?php get_template_part( 'content', 'none' ); ?&gt; &lt;?php endif; ?&gt; &lt;?php do_action( 'toivo_after_loop' ); // Action hook after loop. ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I've tried to replace the two <code>content</code> by <code>excerpt</code>, but then the page is empty (only header and foot).</p>
[ { "answer_id": 261609, "author": "Nehal Shah", "author_id": 114177, "author_profile": "https://wordpress.stackexchange.com/users/114177", "pm_score": 1, "selected": false, "text": "<p>You can use the shuffle() function to get the categories in random order.\nLike this, </p>\n\n<pre><code>$categories = get_categories();\nshuffle( $categories );\n</code></pre>\n\n<p>Hope this works for you!</p>\n" }, { "answer_id": 261610, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"> wp_list_categories();</a> give you formatted output,</p>\n\n<p>To display elements for custom layout you can use get_categories() or get_terms() function.</p>\n" }, { "answer_id": 261612, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>You will need to <a href=\"https://developer.wordpress.org/reference/functions/add_term_meta/\" rel=\"nofollow noreferrer\">add term meta</a> to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order (<a href=\"http://themehybrid.com/weblog/introduction-to-wordpress-term-meta\" rel=\"nofollow noreferrer\">tutorial</a>). Let's say you have generated a meta field called <code>my_cat_meta</code> which holds integers that say in which order you want them to be displayed.</p>\n\n<p>Now you can pass this metakey to <code>wp_list_categories</code>. This function ultimately relies on <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms</code></a>, which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'meta_key' -&gt; 'my_cat_meta',\n 'orderby'-&gt; 'meta_key');\nwp_list_categories ($args);\n</code></pre>\n\n<p>A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'orderby'-&gt; 'description');\nwp_list_categories ($args);\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261633", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116402/" ]
I know this is normally an obvious question with a lot of answers (like [here](https://wordpress.stackexchange.com/questions/120759/show-post-titles-only-on-the-homepage)), but I'd like to show only the beginning of the posts with a "read more" button. I don't use excerpts, so I'd like Wordpress to automaticly grab the first 55 words or the first phrase to display it. I use the theme Toivo Lite. The index.php is: ``` <?php get_header(); ?> <?php if ( have_posts() ) : ?> <?php do_action( 'toivo_before_loop' ); // Action hook before loop. ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'content', ( post_type_supports( get_post_type(), 'post-formats' ) ? get_post_format() : get_post_type() ) ); ?> <?php endwhile; ?> <?php the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'toivo-lite' ), 'next_text' => __( 'Next page', 'toivo-lite' ), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'toivo-lite' ) . ' </span>', ) ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> <?php do_action( 'toivo_after_loop' ); // Action hook after loop. ?> <?php get_footer(); ?> ``` I've tried to replace the two `content` by `excerpt`, but then the page is empty (only header and foot).
You will need to [add term meta](https://developer.wordpress.org/reference/functions/add_term_meta/) to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order ([tutorial](http://themehybrid.com/weblog/introduction-to-wordpress-term-meta)). Let's say you have generated a meta field called `my_cat_meta` which holds integers that say in which order you want them to be displayed. Now you can pass this metakey to `wp_list_categories`. This function ultimately relies on [`get_terms`](https://developer.wordpress.org/reference/functions/get_terms/), which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to: ``` $args = array ( 'title_li' -> '', 'meta_key' -> 'my_cat_meta', 'orderby'-> 'meta_key'); wp_list_categories ($args); ``` A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use: ``` $args = array ( 'title_li' -> '', 'orderby'-> 'description'); wp_list_categories ($args); ```
261,641
<p>I am having an issue with my WordPress load times. Site loads very slowly, and trying to pin this to the correct issue whether it be the template/code or server related.</p> <pre><code>http://03e4976.netsolhost.com/site2016/ </code></pre> <p><strong>First Issue -</strong> I am wondering why my wordpress site is looking for a parallax-slider css file that is not on the system? Site seems to work fine but is killing the load times, so how do I remove this? I am unable to see what is calling it.</p> <blockquote> <p>Request URL:<a href="http://03e4976.netsolhost.com/site2016/wp-content/themes/theme54644/parallax-slider/less/parallax-slider.less" rel="nofollow noreferrer">http://03e4976.netsolhost.com/site2016/wp-content/themes/theme54644/parallax-slider/less/parallax-slider.less</a> Request Method:GET Status Code:404 Not Found Remote Address:206.188.192.214:80\</p> </blockquote> <p>I believe there are other issues as well causing this load time.</p> <p>Any help appreciated - Thanks Ryan</p>
[ { "answer_id": 261609, "author": "Nehal Shah", "author_id": 114177, "author_profile": "https://wordpress.stackexchange.com/users/114177", "pm_score": 1, "selected": false, "text": "<p>You can use the shuffle() function to get the categories in random order.\nLike this, </p>\n\n<pre><code>$categories = get_categories();\nshuffle( $categories );\n</code></pre>\n\n<p>Hope this works for you!</p>\n" }, { "answer_id": 261610, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"> wp_list_categories();</a> give you formatted output,</p>\n\n<p>To display elements for custom layout you can use get_categories() or get_terms() function.</p>\n" }, { "answer_id": 261612, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>You will need to <a href=\"https://developer.wordpress.org/reference/functions/add_term_meta/\" rel=\"nofollow noreferrer\">add term meta</a> to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order (<a href=\"http://themehybrid.com/weblog/introduction-to-wordpress-term-meta\" rel=\"nofollow noreferrer\">tutorial</a>). Let's say you have generated a meta field called <code>my_cat_meta</code> which holds integers that say in which order you want them to be displayed.</p>\n\n<p>Now you can pass this metakey to <code>wp_list_categories</code>. This function ultimately relies on <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms</code></a>, which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'meta_key' -&gt; 'my_cat_meta',\n 'orderby'-&gt; 'meta_key');\nwp_list_categories ($args);\n</code></pre>\n\n<p>A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use:</p>\n\n<pre><code>$args = array (\n 'title_li' -&gt; '',\n 'orderby'-&gt; 'description');\nwp_list_categories ($args);\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116407/" ]
I am having an issue with my WordPress load times. Site loads very slowly, and trying to pin this to the correct issue whether it be the template/code or server related. ``` http://03e4976.netsolhost.com/site2016/ ``` **First Issue -** I am wondering why my wordpress site is looking for a parallax-slider css file that is not on the system? Site seems to work fine but is killing the load times, so how do I remove this? I am unable to see what is calling it. > > Request > URL:<http://03e4976.netsolhost.com/site2016/wp-content/themes/theme54644/parallax-slider/less/parallax-slider.less> > Request Method:GET Status Code:404 Not Found Remote > Address:206.188.192.214:80\ > > > I believe there are other issues as well causing this load time. Any help appreciated - Thanks Ryan
You will need to [add term meta](https://developer.wordpress.org/reference/functions/add_term_meta/) to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order ([tutorial](http://themehybrid.com/weblog/introduction-to-wordpress-term-meta)). Let's say you have generated a meta field called `my_cat_meta` which holds integers that say in which order you want them to be displayed. Now you can pass this metakey to `wp_list_categories`. This function ultimately relies on [`get_terms`](https://developer.wordpress.org/reference/functions/get_terms/), which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to: ``` $args = array ( 'title_li' -> '', 'meta_key' -> 'my_cat_meta', 'orderby'-> 'meta_key'); wp_list_categories ($args); ``` A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use: ``` $args = array ( 'title_li' -> '', 'orderby'-> 'description'); wp_list_categories ($args); ```
261,645
<p>I'm struggling to see if this is natively supported, or if it's not the best place to implement this functionality - in my app (Laravel) or the same side as the API (WordPress).</p> <p>Retrieving a single page (/about-us) via the slug is easy:</p> <pre><code>/wp-json/wp/v2/pages?slug=about-us </code></pre> <p>But the issue comes with retrieving a sub/child page. Consider /about-us/child-page - this works perfectly fine in WordPress but retrieving the page via the Rest API seems impossible?</p> <pre><code>/wp-json/wp/v2/pages?slug=about-us/child-page /wp-json/wp/v2/pages?slug=%2Fabout-us%2Fchild-page%2F </code></pre> <p>No Results.</p> <p>I can search for that individual page and get results, however if another page then shares that slug there's the potential for collisions.</p> <pre><code>/wp-json/wp/v2/pages?slug=child-page </code></pre> <p>There's <code>get_page_by_path()</code> which allows you to search for pages via path which is exactly what I'm after - I can implement this using a custom REST API endpoint (<a href="https://www.coditty.com/code/wordpress-rest-api-how-to-get-content-by-slug" rel="noreferrer">https://www.coditty.com/code/wordpress-rest-api-how-to-get-content-by-slug</a>) but the returned result is not standard and not comparable to the WP-REST equivalent (See below) </p> <pre> { "id": 22, "date": "2017-03-28T13:15:53", "date_gmt": "2017-03-28T12:15:53", "guid": { "rendered": "http://127.0.0.1:8000/?page_id=22" }, "modified": "2017-03-28T13:15:53", "modified_gmt": "2017-03-28T12:15:53", "slug": "test-sub-page", "status": "publish", "type": "page", "link": "http://127.0.0.1:8000/test/test-sub-page/", "title": { "rendered": "Test Sub page" }, "content": { "rendered": "...", "protected": false }, "excerpt": { "rendered": "....", "protected": false }, "author": 1, "featured_media": 0, "parent": 7, "menu_order": 0, "comment_status": "closed", "ping_status": "closed", "template": "", "meta": [], "_links": { "self": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/22" } ], "collection": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages" } ], "about": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/types/page" } ], "author": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/users/1" } ], "replies": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/comments?post=22" } ], "version-history": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/22/revisions" } ], "up": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/7" } ], "wp:attachment": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/media?parent=22" } ], "curies": [ { "name": "wp", "href": "https://api.w.org/{rel}", "templated": true } ] } } </pre> <p>VS</p> <pre> { "ID": 22, "post_author": "1", "post_date": "2017-03-28 13:15:53", "post_date_gmt": "2017-03-28 12:15:53", "post_content": "...", "post_title": "Test Sub page", "post_excerpt": "", "post_status": "publish", "comment_status": "closed", "ping_status": "closed", "post_password": "", "post_name": "test-sub-page", "to_ping": "", "pinged": "", "post_modified": "2017-03-28 13:15:53", "post_modified_gmt": "2017-03-28 12:15:53", "post_content_filtered": "", "post_parent": 7, "guid": "http://127.0.0.1:8000/?page_id=22", "menu_order": 0, "post_type": "page", "post_mime_type": "", "comment_count": "0", "filter": "raw" } </pre> <p>Alternatively I can poll the API for each segment/page from my app to verify that each page exists and build up the data that way...</p>
[ { "answer_id": 390444, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, this functionality is not natively supported out of the box. In detail, the problem is that most post types including <code>page</code> use the base <code>WP_REST_Posts_Controller</code> which maps the <code>slug</code> parameter to the <code>post_name__in</code> <code>WP_Query</code> argument, which does not facilitate resolving hierarchical slugs. The <code>pagename</code> query variable does, however - but only one per query, which might be why it's not already leveraged for REST requests for hierarchical post types.</p>\n<p>There are a number of solutions and work-arounds. Please note that the code below has not been thoroughly tested, and the JavaScript in particular neglects important authentication and error-handling practices - it is intended for illustrative purposes only.</p>\n<hr />\n<h1>Make Multiple Requests</h1>\n<p>Your client can simply work through each path part and use the <code>_fields</code> parameter to minimize server load by only requesting ancestor posts' ID, then using that post ID as the <code>parent</code> argument for the subsequent request:</p>\n<pre class=\"lang-js prettyprint-override\"><code>async function wpse261645_fetchPage( path ) {\n const parts = path.split( '/' );\n const uri = '/wp-json/wp/v2/pages';\n let parent_id;\n\n for( let i = 0; i &lt; parts.length; i++ ) {\n const params = new URLSearchParams( { slug: parts[i] } );\n\n if( i &lt; parts.length - 1 )\n params.append( '_fields', 'id' );\n\n if( parent_id )\n params.append( 'parent', parent_id );\n \n const res = await fetch(\n `${uri}?${params}`,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n }\n ).then( res =&gt; res.json() );\n\n if( i === parts.length - 1 )\n return res;\n\n parent_id = res[0].id;\n }\n}\n</code></pre>\n<hr />\n<h1>Modify <code>slug</code> REST Param/QV Mapping</h1>\n<p>This is probably the most appealing solution as it can effectively address the original issue directly without requiring special handling client-side. But it's a bit convoluted and experimental due to the number of moving parts involved and my own lack of familiarity with the REST API - I'm totally open to suggestions and improvements!</p>\n<p>Before the <code>WP_REST_Posts_Controller</code> executes a query to retrieve the items corresponding to the request, it runs the query args and the request object through <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"nofollow noreferrer\">the <code>rest_{$this-&gt;post_type}_query</code> filter</a>. We can leverage this filter to selectively re-map <code>slug</code> as necessary for chosen post-types or controllers.</p>\n<p>It's also necessary to adjust the <code>slug</code> parameter's schema, parsing and sanitization routine for the relevant controllers such that it doesn't strip out <code>/</code>s or <code>%2F</code>s from the slug value or trip validation errors. I don't <em>think</em> that this should create any compatibility issues as the only parts of the schema and parameter registration that are touched are swapping out their sanitization callbacks - the changes should be near invisible to clients and discovery, and wholly backwards-compatible with the original functionality (unless someone's been relying on the REST API to transform <code>/</code>s in slugs into <code>-</code>s) - but I haven't tested it thoroughly.</p>\n<h2>Parsing, Schema, and Sanitization Adjustments (to keep the <code>/</code>s)</h2>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse261645_sanitize_nested_slug( $slug ) {\n // Exploding slugs, as one does.\n $slug_parts = array_map( 'sanitize_title', explode( '/', $slug ) );\n\n return implode( '/', $slug_parts );\n}\n\nfunction wpse261645_parse_nested_slug_list( $slugs ) {\n $slugs = wp_parse_list( $slugs );\n\n return array_unique( array_map( 'wpse261645_sanitize_nested_slug', $slugs ) );\n}\n\nfunction wpse261645_nested_slug_schema( $schema ) {\n $schema['slug']['arg_options']['sanitize_callback'] = 'wpse261645_sanitize_nested_slug';\n\n return $schema;\n}\nadd_filter( 'rest_page_item_schema', 'wpse261645_nested_slug_schema' );\n\nfunction wpse261645_nested_slug_collection_params( $params ) {\n $params['slug']['sanitize_callback'] = 'wpse261645_parse_nested_slug_list';\n\n return $params;\n}\nadd_filter( 'rest_page_collection_params', 'wpse261645_nested_slug_collection_params' );\n</code></pre>\n<h2>Remapping the <code>slug</code> REST Param to Query Variables</h2>\n<p>Now that <code>/</code>s are persisted in the <code>slug</code> parameter, we can map the values into a variety of different queries:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse261645_remap_slug_param_qv( $args, $request ) {\n $slugs = $request-&gt;get_param( 'slug' );\n\n // If the `slug` param was not even set, skip further processing.\n if( empty( $slugs ) )\n return $args;\n\n // Pull out hierarchical slugs into their own list.\n $nested_slugs = [];\n foreach( $slugs as $index =&gt; $slug ) {\n if( strpos( $slug, '/' ) !== false ) {\n $nested_slugs[] = $slug;\n unset( $slugs[ $index ] );\n }\n }\n\n if( count( $slugs ) ) {\n $args['post_name__in'] = $slugs;\n\n if( count( $nested_slugs ) ) {\n $args['wpse261645_compound_query'] = true;\n $args['post__in'] = array_map( 'url_to_postid', $nested_slugs );\n\n add_filter( 'posts_where', 'wpse261645_compound_query_where', 10, 2 );\n }\n }\n else {\n unset( $args['post_name__in'] );\n\n if( count( $nested_slugs ) === 1 )\n $args['pagename'] = $nested_slugs[0];\n elseif( count( $nested_slugs &gt; 1 ) )\n $args['post__in'] = array_map( 'url_to_postid', $nested_slugs );\n }\n\n return $args;\n}\nadd_filter( 'rest_page_query', 'wpse261645_remap_slug_param_qv', 10, 2 );\n\nfunction wpse261645_compound_query_where( $where, $query ) {\n global $wpdb;\n\n if( ! isset( $query-&gt;query['wpse261645_compound_query'] ) )\n return $where;\n\n return preg_replace(\n &quot;/ AND ({$wpdb-&gt;posts}.post_name IN \\([^)]*\\)) AND ({$wpdb-&gt;posts}.ID IN \\([^)]*\\))/&quot;,\n ' AND ($1 OR $2)',\n $where\n );\n}\n</code></pre>\n<p>The logic above handles a number of different situations depending on the value of <code>slug</code>:</p>\n<ul>\n<li>Any number of flat slugs are mapped into the <code>post_name__in</code> QV as per normal.</li>\n<li>A single hierarchical slug will be mapped into the <code>pagename</code> QV, letting <code>WP_Query</code> natively handle the path resolution.</li>\n<li>A list of hierarchical slugs will be resolved via <code>url_to_postid()</code> and mapped into the <code>post__in</code> QV. The lookups add additional overhead.</li>\n<li>A list of intermixed hierarchical and flat slugs will be mapped into the <code>post__in</code> and <code>post_name__in</code> QVs respectively and the WHERE clause modified to OR these conditions instead of ANDing them. Hierarchical slugs will be resolved to IDs, adding additional overhead.</li>\n</ul>\n<p>In summary, the most efficient queries are the product of passing <code>slug</code> as a single hierarchical slug, or any number of flat slugs in a list. Lists of hierarchical or intermixed slugs will result in additional overhead.</p>\n<p>As an added benefit, this implementation also inherently facilitates explicitly requesting a top-level slug by including a <code>/</code>. E.g. <code>?slug=foobar</code> would return all posts with the slug <code>foobar</code> as per usual, but <code>?slug=/foobar</code> will return just the post with the slug <code>foobar</code> which has no parent.</p>\n<hr />\n<h1>Use a HEAD Request to the Web Path</h1>\n<p><strong>This is a horrible dirty hack</strong> that relies on conventions outside of the REST API - ones which may incur a substantial overhead and which <a href=\"https://wordpress.stackexchange.com/questions/211817/how-to-remove-rest-api-link-in-http-headers\">some sites may be prone to disabling</a> to boot - <strong>I strongly recommend against doing this</strong>. Doubly so in any code intended for distribution; you will end up with a lot of unhappy users.</p>\n<p>By default, WordPress returns a number of <code>Link</code> HTTP headers in responses to content requests, one of which being the REST route to the resource or collection corresponding to the content. As such it's possible to resolve any nested slug path to a REST resource within 2 requests by leveraging WordPress's frontend permalink routing:</p>\n<pre class=\"lang-js prettyprint-override\"><code>async function wpse261645_fetchPage( path ) {\n let uri = `/wp-json/wp/v2/pages/?slug=${path}`;\n\n if( path.includes( '/' ) ) {\n const web_res = await fetch( `/${path}`, { method: 'HEAD' } );\n const link_header = web_res.headers.get( 'Link' ).split( ', ' )\n .find( val =&gt; val.includes( ' rel=&quot;alternate&quot;; type=&quot;application/json&quot;' ) );\n\n uri = link_header.substring( 1, link_header.indexOf( '&gt;' ) );\n }\n\n return fetch(\n uri,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n }\n ).then( res =&gt; res.json() );\n}\n</code></pre>\n" }, { "answer_id": 395420, "author": "Jonas Sandstedt", "author_id": 212282, "author_profile": "https://wordpress.stackexchange.com/users/212282", "pm_score": 0, "selected": false, "text": "<p>We just ended up with fetching the page using the child-page slug:</p>\n<pre class=\"lang-js prettyprint-override\"><code>fetch(/wp-json/wp/v2/pages?slug=child-page)\n</code></pre>\n<p>If there is a page and a child page with the same array, we could now loop through that array response and find any post that didn't have any parents:</p>\n<pre><code>.then(page =&gt; page.find(p =&gt; p.parent === 0) )\n</code></pre>\n<p>This is our parent page. In our case, that´s what we wanted. Else you could use that parent.id, to loop through the fetch response array to find the parents child.</p>\n<p>Not the prettiest maybe, but no need for any custom API changes in WordPress.</p>\n" }, { "answer_id": 406229, "author": "whjelm", "author_id": 222649, "author_profile": "https://wordpress.stackexchange.com/users/222649", "pm_score": 1, "selected": false, "text": "<p>This adds a path parameter and adjusts the query being made on the request accordingly. The get_page_by_path function helps us retrieve the correct page in WP and we can then adjust the arguments sent to the query that runs on the /pages path in wp-json.</p>\n<pre><code>add_filter('rest_page_query', function ($args, $request){\n $path = $request-&gt;get_param('path');\n\n if (!empty($path)) {\n $pageByPath = get_page_by_path($path, OBJECT, 'page');\n\n // overwrite the page id with the page id by path\n $args['p'] = $pageByPath-&gt;ID;\n }\n\n return $args;\n}, 10, 2);\n</code></pre>\n<p>Allowing you to request a specific sub page like this:</p>\n<pre><code>.../wp-json/wp/v2/pages?path=/pageslug/subpageslug/\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1062/" ]
I'm struggling to see if this is natively supported, or if it's not the best place to implement this functionality - in my app (Laravel) or the same side as the API (WordPress). Retrieving a single page (/about-us) via the slug is easy: ``` /wp-json/wp/v2/pages?slug=about-us ``` But the issue comes with retrieving a sub/child page. Consider /about-us/child-page - this works perfectly fine in WordPress but retrieving the page via the Rest API seems impossible? ``` /wp-json/wp/v2/pages?slug=about-us/child-page /wp-json/wp/v2/pages?slug=%2Fabout-us%2Fchild-page%2F ``` No Results. I can search for that individual page and get results, however if another page then shares that slug there's the potential for collisions. ``` /wp-json/wp/v2/pages?slug=child-page ``` There's `get_page_by_path()` which allows you to search for pages via path which is exactly what I'm after - I can implement this using a custom REST API endpoint (<https://www.coditty.com/code/wordpress-rest-api-how-to-get-content-by-slug>) but the returned result is not standard and not comparable to the WP-REST equivalent (See below) ``` { "id": 22, "date": "2017-03-28T13:15:53", "date_gmt": "2017-03-28T12:15:53", "guid": { "rendered": "http://127.0.0.1:8000/?page_id=22" }, "modified": "2017-03-28T13:15:53", "modified_gmt": "2017-03-28T12:15:53", "slug": "test-sub-page", "status": "publish", "type": "page", "link": "http://127.0.0.1:8000/test/test-sub-page/", "title": { "rendered": "Test Sub page" }, "content": { "rendered": "...", "protected": false }, "excerpt": { "rendered": "....", "protected": false }, "author": 1, "featured_media": 0, "parent": 7, "menu_order": 0, "comment_status": "closed", "ping_status": "closed", "template": "", "meta": [], "_links": { "self": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/22" } ], "collection": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages" } ], "about": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/types/page" } ], "author": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/users/1" } ], "replies": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/comments?post=22" } ], "version-history": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/22/revisions" } ], "up": [ { "embeddable": true, "href": "http://127.0.0.1:8000/wp-json/wp/v2/pages/7" } ], "wp:attachment": [ { "href": "http://127.0.0.1:8000/wp-json/wp/v2/media?parent=22" } ], "curies": [ { "name": "wp", "href": "https://api.w.org/{rel}", "templated": true } ] } } ``` VS ``` { "ID": 22, "post_author": "1", "post_date": "2017-03-28 13:15:53", "post_date_gmt": "2017-03-28 12:15:53", "post_content": "...", "post_title": "Test Sub page", "post_excerpt": "", "post_status": "publish", "comment_status": "closed", "ping_status": "closed", "post_password": "", "post_name": "test-sub-page", "to_ping": "", "pinged": "", "post_modified": "2017-03-28 13:15:53", "post_modified_gmt": "2017-03-28 12:15:53", "post_content_filtered": "", "post_parent": 7, "guid": "http://127.0.0.1:8000/?page_id=22", "menu_order": 0, "post_type": "page", "post_mime_type": "", "comment_count": "0", "filter": "raw" } ``` Alternatively I can poll the API for each segment/page from my app to verify that each page exists and build up the data that way...
Unfortunately, this functionality is not natively supported out of the box. In detail, the problem is that most post types including `page` use the base `WP_REST_Posts_Controller` which maps the `slug` parameter to the `post_name__in` `WP_Query` argument, which does not facilitate resolving hierarchical slugs. The `pagename` query variable does, however - but only one per query, which might be why it's not already leveraged for REST requests for hierarchical post types. There are a number of solutions and work-arounds. Please note that the code below has not been thoroughly tested, and the JavaScript in particular neglects important authentication and error-handling practices - it is intended for illustrative purposes only. --- Make Multiple Requests ====================== Your client can simply work through each path part and use the `_fields` parameter to minimize server load by only requesting ancestor posts' ID, then using that post ID as the `parent` argument for the subsequent request: ```js async function wpse261645_fetchPage( path ) { const parts = path.split( '/' ); const uri = '/wp-json/wp/v2/pages'; let parent_id; for( let i = 0; i < parts.length; i++ ) { const params = new URLSearchParams( { slug: parts[i] } ); if( i < parts.length - 1 ) params.append( '_fields', 'id' ); if( parent_id ) params.append( 'parent', parent_id ); const res = await fetch( `${uri}?${params}`, { method: 'GET', headers: { 'Content-Type': 'application/json' } } ).then( res => res.json() ); if( i === parts.length - 1 ) return res; parent_id = res[0].id; } } ``` --- Modify `slug` REST Param/QV Mapping =================================== This is probably the most appealing solution as it can effectively address the original issue directly without requiring special handling client-side. But it's a bit convoluted and experimental due to the number of moving parts involved and my own lack of familiarity with the REST API - I'm totally open to suggestions and improvements! Before the `WP_REST_Posts_Controller` executes a query to retrieve the items corresponding to the request, it runs the query args and the request object through [the `rest_{$this->post_type}_query` filter](https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/). We can leverage this filter to selectively re-map `slug` as necessary for chosen post-types or controllers. It's also necessary to adjust the `slug` parameter's schema, parsing and sanitization routine for the relevant controllers such that it doesn't strip out `/`s or `%2F`s from the slug value or trip validation errors. I don't *think* that this should create any compatibility issues as the only parts of the schema and parameter registration that are touched are swapping out their sanitization callbacks - the changes should be near invisible to clients and discovery, and wholly backwards-compatible with the original functionality (unless someone's been relying on the REST API to transform `/`s in slugs into `-`s) - but I haven't tested it thoroughly. Parsing, Schema, and Sanitization Adjustments (to keep the `/`s) ---------------------------------------------------------------- ```php function wpse261645_sanitize_nested_slug( $slug ) { // Exploding slugs, as one does. $slug_parts = array_map( 'sanitize_title', explode( '/', $slug ) ); return implode( '/', $slug_parts ); } function wpse261645_parse_nested_slug_list( $slugs ) { $slugs = wp_parse_list( $slugs ); return array_unique( array_map( 'wpse261645_sanitize_nested_slug', $slugs ) ); } function wpse261645_nested_slug_schema( $schema ) { $schema['slug']['arg_options']['sanitize_callback'] = 'wpse261645_sanitize_nested_slug'; return $schema; } add_filter( 'rest_page_item_schema', 'wpse261645_nested_slug_schema' ); function wpse261645_nested_slug_collection_params( $params ) { $params['slug']['sanitize_callback'] = 'wpse261645_parse_nested_slug_list'; return $params; } add_filter( 'rest_page_collection_params', 'wpse261645_nested_slug_collection_params' ); ``` Remapping the `slug` REST Param to Query Variables -------------------------------------------------- Now that `/`s are persisted in the `slug` parameter, we can map the values into a variety of different queries: ```php function wpse261645_remap_slug_param_qv( $args, $request ) { $slugs = $request->get_param( 'slug' ); // If the `slug` param was not even set, skip further processing. if( empty( $slugs ) ) return $args; // Pull out hierarchical slugs into their own list. $nested_slugs = []; foreach( $slugs as $index => $slug ) { if( strpos( $slug, '/' ) !== false ) { $nested_slugs[] = $slug; unset( $slugs[ $index ] ); } } if( count( $slugs ) ) { $args['post_name__in'] = $slugs; if( count( $nested_slugs ) ) { $args['wpse261645_compound_query'] = true; $args['post__in'] = array_map( 'url_to_postid', $nested_slugs ); add_filter( 'posts_where', 'wpse261645_compound_query_where', 10, 2 ); } } else { unset( $args['post_name__in'] ); if( count( $nested_slugs ) === 1 ) $args['pagename'] = $nested_slugs[0]; elseif( count( $nested_slugs > 1 ) ) $args['post__in'] = array_map( 'url_to_postid', $nested_slugs ); } return $args; } add_filter( 'rest_page_query', 'wpse261645_remap_slug_param_qv', 10, 2 ); function wpse261645_compound_query_where( $where, $query ) { global $wpdb; if( ! isset( $query->query['wpse261645_compound_query'] ) ) return $where; return preg_replace( "/ AND ({$wpdb->posts}.post_name IN \([^)]*\)) AND ({$wpdb->posts}.ID IN \([^)]*\))/", ' AND ($1 OR $2)', $where ); } ``` The logic above handles a number of different situations depending on the value of `slug`: * Any number of flat slugs are mapped into the `post_name__in` QV as per normal. * A single hierarchical slug will be mapped into the `pagename` QV, letting `WP_Query` natively handle the path resolution. * A list of hierarchical slugs will be resolved via `url_to_postid()` and mapped into the `post__in` QV. The lookups add additional overhead. * A list of intermixed hierarchical and flat slugs will be mapped into the `post__in` and `post_name__in` QVs respectively and the WHERE clause modified to OR these conditions instead of ANDing them. Hierarchical slugs will be resolved to IDs, adding additional overhead. In summary, the most efficient queries are the product of passing `slug` as a single hierarchical slug, or any number of flat slugs in a list. Lists of hierarchical or intermixed slugs will result in additional overhead. As an added benefit, this implementation also inherently facilitates explicitly requesting a top-level slug by including a `/`. E.g. `?slug=foobar` would return all posts with the slug `foobar` as per usual, but `?slug=/foobar` will return just the post with the slug `foobar` which has no parent. --- Use a HEAD Request to the Web Path ================================== **This is a horrible dirty hack** that relies on conventions outside of the REST API - ones which may incur a substantial overhead and which [some sites may be prone to disabling](https://wordpress.stackexchange.com/questions/211817/how-to-remove-rest-api-link-in-http-headers) to boot - **I strongly recommend against doing this**. Doubly so in any code intended for distribution; you will end up with a lot of unhappy users. By default, WordPress returns a number of `Link` HTTP headers in responses to content requests, one of which being the REST route to the resource or collection corresponding to the content. As such it's possible to resolve any nested slug path to a REST resource within 2 requests by leveraging WordPress's frontend permalink routing: ```js async function wpse261645_fetchPage( path ) { let uri = `/wp-json/wp/v2/pages/?slug=${path}`; if( path.includes( '/' ) ) { const web_res = await fetch( `/${path}`, { method: 'HEAD' } ); const link_header = web_res.headers.get( 'Link' ).split( ', ' ) .find( val => val.includes( ' rel="alternate"; type="application/json"' ) ); uri = link_header.substring( 1, link_header.indexOf( '>' ) ); } return fetch( uri, { method: 'GET', headers: { 'Content-Type': 'application/json' } } ).then( res => res.json() ); } ```
261,686
<p>Server upgrading Friday, which will kill my existing WP 3.1 blog. So I’m installing 4.7.3 fresh in new subdirectory of existing WP 3.1 domain/site AND using the same database. Domain is a subweb. Server is running PHP 5.3. (New one will run 5.6) Once working, I’ll point the domain at the new directory. (Not sure whether subweb/shared db might affect this?)</p> <p>I did mod the wp-config file with db info and memory use limits. Other than that, the entire install is fresh out of the box. No theme files here other than those included with 4.7.3 (although the old blog is running Thesis 1.8). No plugins other than stock akismet.</p> <p>Got the following errors:</p> <blockquote> <p>Warning: require_once(/users/domain.com/htdocs/directory/new subdirectory/wp-load.php) [function.require-once]: failed to open stream: No such file or directory in /users/domain.com/htdocs/directory/new subdirectory/wp-admin/install.php on line 36</p> <p>Fatal error: require_once() [function.require]: Failed opening required ‘/users/domain.com/htdocs/directory/new subdirectory/wp-load.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /users/domain.com/htdocs/directory/new subdirectory/wp-admin/install.php on line 36</p> </blockquote> <p>Looking at the newly installed subdirectory, I saw ONLY folders:</p> <pre><code>wp-admin wp-content wp-includes </code></pre> <p>Next I tried uploading all files again. Same thing. So I selected the following files (without also selecting the above-named directories) and uploaded:</p> <pre><code>index.php license.txt readme.html wp-activate.php wp-blog-header.php wp-comments-post.php wp-config.php wp-cron.php wp-links-opml.php wp-load.php wp-login.php wp-mail.php wp-settings.php wp-signup.php wp-trackback.php xmlrpc.php </code></pre> <p>And I get a nearly identical error msg:</p> <blockquote> <p>Warning: require(/users/domain.com/htdocs/directory/subdirectory/wp-includes/load.php) [function.require]: failed to open stream: No such file or directory in /users/domain.com/htdocs/directory/subdirectory/wp-settings.php on line 19</p> <p>Fatal error: require() [function.require]: Failed opening required ‘/users/domain.com/htdocs/directory/subdirectory/wp-includes/load.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /users/domain.com/htdocs/directory/subdirectory/wp-settings.php on line 19</p> </blockquote> <p>No idea what's going on here, hoping to learn how to fix it.</p> <p>Any help appreciated!</p>
[ { "answer_id": 261687, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>It could be 2 things</p>\n\n<p>Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. </p>\n\n<p>The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.</p>\n" }, { "answer_id": 364380, "author": "Paolo", "author_id": 38261, "author_profile": "https://wordpress.stackexchange.com/users/38261", "pm_score": 0, "selected": false, "text": "<p>I had the same problem. Apparently the filename referenced in the \"require\" code is in the wrong case. I just had to use the right case and it worked.</p>\n\n<p>So instead of:</p>\n\n<pre><code>require_once \"myFile.php\";\n</code></pre>\n\n<p>I used:</p>\n\n<pre><code>require_once \"myfile.php\";\n</code></pre>\n" } ]
2017/03/28
[ "https://wordpress.stackexchange.com/questions/261686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116436/" ]
Server upgrading Friday, which will kill my existing WP 3.1 blog. So I’m installing 4.7.3 fresh in new subdirectory of existing WP 3.1 domain/site AND using the same database. Domain is a subweb. Server is running PHP 5.3. (New one will run 5.6) Once working, I’ll point the domain at the new directory. (Not sure whether subweb/shared db might affect this?) I did mod the wp-config file with db info and memory use limits. Other than that, the entire install is fresh out of the box. No theme files here other than those included with 4.7.3 (although the old blog is running Thesis 1.8). No plugins other than stock akismet. Got the following errors: > > Warning: require\_once(/users/domain.com/htdocs/directory/new > subdirectory/wp-load.php) [function.require-once]: failed to open > stream: No such file or directory in > /users/domain.com/htdocs/directory/new > subdirectory/wp-admin/install.php on line 36 > > > Fatal error: require\_once() [function.require]: Failed opening > required ‘/users/domain.com/htdocs/directory/new > subdirectory/wp-load.php’ > (include\_path=’.:/usr/share/php:/usr/share/pear’) in > /users/domain.com/htdocs/directory/new > subdirectory/wp-admin/install.php on line 36 > > > Looking at the newly installed subdirectory, I saw ONLY folders: ``` wp-admin wp-content wp-includes ``` Next I tried uploading all files again. Same thing. So I selected the following files (without also selecting the above-named directories) and uploaded: ``` index.php license.txt readme.html wp-activate.php wp-blog-header.php wp-comments-post.php wp-config.php wp-cron.php wp-links-opml.php wp-load.php wp-login.php wp-mail.php wp-settings.php wp-signup.php wp-trackback.php xmlrpc.php ``` And I get a nearly identical error msg: > > Warning: > require(/users/domain.com/htdocs/directory/subdirectory/wp-includes/load.php) > [function.require]: failed to open stream: No such file or directory > in /users/domain.com/htdocs/directory/subdirectory/wp-settings.php on > line 19 > > > Fatal error: require() [function.require]: Failed opening required > ‘/users/domain.com/htdocs/directory/subdirectory/wp-includes/load.php’ > (include\_path=’.:/usr/share/php:/usr/share/pear’) in > /users/domain.com/htdocs/directory/subdirectory/wp-settings.php on > line 19 > > > No idea what's going on here, hoping to learn how to fix it. Any help appreciated!
It could be 2 things Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.
261,712
<p>Lest say i have Category 1 Category 2 Category 3</p> <p>Inside a post which is located in category 1, I would like to show list of posts which are in category 2 and 3. If it is only in category 2 or only in category 3 it shouldn't be shown.</p> <p>I was that there are </p> <p><a href="https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters" rel="nofollow noreferrer">Multiple Taxonomy Handling:</a></p> <p>Can it be done this way?</p> <pre><code> 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category 1', 'field' =&gt; 'slug', 'terms' =&gt; 'category1', ), array( 'taxonomy' =&gt; 'category 2', 'field' =&gt; 'slug', 'terms' =&gt; 'category2', ), ), </code></pre> <p>If yes where does this code needs to be implemented in?</p>
[ { "answer_id": 261687, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>It could be 2 things</p>\n\n<p>Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. </p>\n\n<p>The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.</p>\n" }, { "answer_id": 364380, "author": "Paolo", "author_id": 38261, "author_profile": "https://wordpress.stackexchange.com/users/38261", "pm_score": 0, "selected": false, "text": "<p>I had the same problem. Apparently the filename referenced in the \"require\" code is in the wrong case. I just had to use the right case and it worked.</p>\n\n<p>So instead of:</p>\n\n<pre><code>require_once \"myFile.php\";\n</code></pre>\n\n<p>I used:</p>\n\n<pre><code>require_once \"myfile.php\";\n</code></pre>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100468/" ]
Lest say i have Category 1 Category 2 Category 3 Inside a post which is located in category 1, I would like to show list of posts which are in category 2 and 3. If it is only in category 2 or only in category 3 it shouldn't be shown. I was that there are [Multiple Taxonomy Handling:](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) Can it be done this way? ``` 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category 1', 'field' => 'slug', 'terms' => 'category1', ), array( 'taxonomy' => 'category 2', 'field' => 'slug', 'terms' => 'category2', ), ), ``` If yes where does this code needs to be implemented in?
It could be 2 things Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.
261,756
<p>I've set up a subfolder multisite. Main site: <a href="https://cs-amx.org/" rel="nofollow noreferrer">https://cs-amx.org/</a> Subdomain site: <a href="https://cs-amx.org/chypre" rel="nofollow noreferrer">https://cs-amx.org/chypre</a></p> <p>You see the maintenance screen is well displayed on the main site, but not on the subdomain site.</p> <p>All the themes and plugin files lead to a 404.</p> <p>For example, cs-amx.org/chypre/wp-content/plugins/maintenance/load/style.css doesn't load.</p> <p>But cs-amx.org/wp-content/plugins/maintenance/load/style.css works well.</p> <p>The admin panel at cs-amx.org/chypre/wp-admin/ works, though.</p> <p>Here's the content of the .htaccess file:</p> <pre><code># BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] # END WordPress </code></pre> <p>Any idea?</p>
[ { "answer_id": 261687, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>It could be 2 things</p>\n\n<p>Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. </p>\n\n<p>The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.</p>\n" }, { "answer_id": 364380, "author": "Paolo", "author_id": 38261, "author_profile": "https://wordpress.stackexchange.com/users/38261", "pm_score": 0, "selected": false, "text": "<p>I had the same problem. Apparently the filename referenced in the \"require\" code is in the wrong case. I just had to use the right case and it worked.</p>\n\n<p>So instead of:</p>\n\n<pre><code>require_once \"myFile.php\";\n</code></pre>\n\n<p>I used:</p>\n\n<pre><code>require_once \"myfile.php\";\n</code></pre>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261756", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63073/" ]
I've set up a subfolder multisite. Main site: <https://cs-amx.org/> Subdomain site: <https://cs-amx.org/chypre> You see the maintenance screen is well displayed on the main site, but not on the subdomain site. All the themes and plugin files lead to a 404. For example, cs-amx.org/chypre/wp-content/plugins/maintenance/load/style.css doesn't load. But cs-amx.org/wp-content/plugins/maintenance/load/style.css works well. The admin panel at cs-amx.org/chypre/wp-admin/ works, though. Here's the content of the .htaccess file: ``` # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] # END WordPress ``` Any idea?
It could be 2 things Most like it's your file permissions. It is probably that your apache isn't able to open the files set files to 0644 and directories 0755. The other problem could be your php version. Since you are upgrading to a new server, why not get the php in version 7? php 5.6 hit end of life 2 months ago.
261,764
<p><a href="https://i.stack.imgur.com/8AKxq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8AKxq.jpg" alt="enter image description here"></a> I have added custom menu just as in image above . But i am unable to open the pages. They are showing 404 page not found. </p>
[ { "answer_id": 261765, "author": "Dean Jansen", "author_id": 114897, "author_profile": "https://wordpress.stackexchange.com/users/114897", "pm_score": 2, "selected": false, "text": "<p>You can use the following to create a sub menu under woocommerce.\nPlease use the following for reference.\n<a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_submenu_page/</a></p>\n\n<pre><code> add_action('admin_menu', 'testing_submenu_page');\n\nfunction testing_submenu_page() {\n add_submenu_page( 'woocommerce', 'sub menu', 'sub menu', 'manage_options', 'woo-subpage-test', 'test_callback' );\n}\n\nfunction test_callback() {\n\n echo '&lt;div class=\"wrap\"&gt;&lt;div id=\"icon-tools\" class=\"icon32\"&gt;&lt;/div&gt;';\n echo '&lt;h2&gt; Sub menu test page&lt;/h2&gt;';\n echo '&lt;/div&gt;';\n\n}\n</code></pre>\n\n<p>Example what the results will look like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/hmkLU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hmkLU.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 261851, "author": "osvin websolutns", "author_id": 116488, "author_profile": "https://wordpress.stackexchange.com/users/116488", "pm_score": 0, "selected": false, "text": "<p>Ok. I found the page. It is wc-account-functions.php. We can add custom menus from here. But still i am unable to open that pages. link is showing 404.</p>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116488/" ]
[![enter image description here](https://i.stack.imgur.com/8AKxq.jpg)](https://i.stack.imgur.com/8AKxq.jpg) I have added custom menu just as in image above . But i am unable to open the pages. They are showing 404 page not found.
You can use the following to create a sub menu under woocommerce. Please use the following for reference. <https://developer.wordpress.org/reference/functions/add_submenu_page/> ``` add_action('admin_menu', 'testing_submenu_page'); function testing_submenu_page() { add_submenu_page( 'woocommerce', 'sub menu', 'sub menu', 'manage_options', 'woo-subpage-test', 'test_callback' ); } function test_callback() { echo '<div class="wrap"><div id="icon-tools" class="icon32"></div>'; echo '<h2> Sub menu test page</h2>'; echo '</div>'; } ``` Example what the results will look like: [![enter image description here](https://i.stack.imgur.com/hmkLU.png)](https://i.stack.imgur.com/hmkLU.png)
261,777
<p>Can <code>wp_script_is</code> used in <code>pluginA</code> check if a script is being enqueued/registered from <code>pluginB</code>? </p> <p>I have two plugins both of which use Angular. One plugin (pluginA) has <code>angular.min.js</code> being loaded across all pages. The other (pluginB) has <code>angular.min.js</code> being loaded on only one. I would like to check if <code>pluginA</code> has already enqueued Angular but I want to do it from <code>pluginB</code>.</p> <p>For instance, I tried</p> <pre><code>$handle = 'myAppScript.min.js' // this is a concatenated/minified version of the entire pluginA angular app. $list = 'enqueued' // I also tried all the other $list options. // if 'myAppScript.min.js' is present, don't register Angular again, otherwise register it. if (wp_script_is($handle, $list)) { return; } else { wp_register_script( $this-&gt;plugin_name . '-ajs', plugin_dir_url(__FILE__) . 'js/angular/angular.min.js', array(), $this-&gt;version, false ); } </code></pre> <p>However <code>wp_script_is</code> returns false no matter what I try (I double checked with a <code>var_dump</code>) and therefore adds Angular again.</p> <p>Thanks for any help you can give!</p> <p>Update - I have a working solution to my particular problem using <code>is_plugin_active</code>, but I'm still curious if there's an answer to the question. Thanks!</p> <pre><code> $plugin = 'pluginA/pluginA.php'; include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); if (!is_plugin_active($plugin)) { wp_register_script( $this-&gt;plugin_name . '-ajs', plugin_dir_url(__FILE__) . 'js/angular/angular.min.js', array(), $this-&gt;version, false ); } </code></pre>
[ { "answer_id": 261845, "author": "Jigar Patel", "author_id": 116524, "author_profile": "https://wordpress.stackexchange.com/users/116524", "pm_score": 0, "selected": false, "text": "<p>You are on the right path. There is no better way to determine script is enqueued or not. This is efficient way <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">wp_script_is( $handle, $list )</a></p>\n<p>Just wondering if your $handle name is correct. Make sure <strong>$handle</strong> while checking wp_script_is is the same as when you enqueue script in pluginB. The first parameter is $handle. Refer to this <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">WP Codex</a>.</p>\n<p>It says:</p>\n<h1>Parameters</h1>\n<p><strong>$handle</strong></p>\n<p>(string) (Required) Name of the script. <strong>Should be unique.</strong></p>\n<p>I believe you are using plugin name as a handle in else part.</p>\n<p><strong>Try using same name &quot;AngularJS&quot; or something but must be the same as $handle</strong></p>\n" }, { "answer_id": 261917, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 2, "selected": true, "text": "<p>Now that I see you were hooking into <code>plugins_loaded</code>, this makes sense because it is fired much earlier than <code>wp_enqueue_scripts</code>. It is expected that your function would return 0 at this point.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence\">here</a> for the order in which actions are generally fired.</p>\n\n<p>Try to <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add an action</a> at <code>wp_enqueue_scripts</code> with a late priority to make sure it runs after other enqueued scripts. Then you can <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">deregister</a> the script and register again with new parameters.</p>\n\n<blockquote>\n <p>If you try to register or enqueue an already registered handle with\n different parameters, the new parameters will be ignored. Instead,\n use wp_deregister_script() and register the script again with the new\n parameters.</p>\n</blockquote>\n\n<p>Edit: Sorry, I misread that. <code>is_plugin_active</code> is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function <code>wp_script_is</code> at <code>wp_enqueue_scripts</code> or later.</p>\n" }, { "answer_id": 262161, "author": "dameer dj", "author_id": 107873, "author_profile": "https://wordpress.stackexchange.com/users/107873", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm wrong but according to WP codex:</p>\n\n<pre><code>wp_script_is( string $handle, string $list = 'enqueued' )\n</code></pre>\n\n<p><code>$handle</code> - unique name of the script</p>\n\n<p>As far as I can see you are using FILE NAME instead which is wrong. By me it has nothing to do with when actions/hooks are being fired coz both of your plugins are fired on <code>plugins_loaded</code>.</p>\n\n<p>So, if you check it out this way</p>\n\n<pre><code>$handle = 'MY_SCRIPT_NAME'; /* can't really be $this-&gt;plugin_name . '-ajs' because it gives 2 different strings */\n</code></pre>\n\n<p>in both of your plugins, only one instance of required JS file will be loaded.</p>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261777", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110157/" ]
Can `wp_script_is` used in `pluginA` check if a script is being enqueued/registered from `pluginB`? I have two plugins both of which use Angular. One plugin (pluginA) has `angular.min.js` being loaded across all pages. The other (pluginB) has `angular.min.js` being loaded on only one. I would like to check if `pluginA` has already enqueued Angular but I want to do it from `pluginB`. For instance, I tried ``` $handle = 'myAppScript.min.js' // this is a concatenated/minified version of the entire pluginA angular app. $list = 'enqueued' // I also tried all the other $list options. // if 'myAppScript.min.js' is present, don't register Angular again, otherwise register it. if (wp_script_is($handle, $list)) { return; } else { wp_register_script( $this->plugin_name . '-ajs', plugin_dir_url(__FILE__) . 'js/angular/angular.min.js', array(), $this->version, false ); } ``` However `wp_script_is` returns false no matter what I try (I double checked with a `var_dump`) and therefore adds Angular again. Thanks for any help you can give! Update - I have a working solution to my particular problem using `is_plugin_active`, but I'm still curious if there's an answer to the question. Thanks! ``` $plugin = 'pluginA/pluginA.php'; include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); if (!is_plugin_active($plugin)) { wp_register_script( $this->plugin_name . '-ajs', plugin_dir_url(__FILE__) . 'js/angular/angular.min.js', array(), $this->version, false ); } ```
Now that I see you were hooking into `plugins_loaded`, this makes sense because it is fired much earlier than `wp_enqueue_scripts`. It is expected that your function would return 0 at this point. See [here](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) and [here](https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence) for the order in which actions are generally fired. Try to [add an action](https://developer.wordpress.org/reference/functions/add_action/) at `wp_enqueue_scripts` with a late priority to make sure it runs after other enqueued scripts. Then you can [deregister](https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes) the script and register again with new parameters. > > If you try to register or enqueue an already registered handle with > different parameters, the new parameters will be ignored. Instead, > use wp\_deregister\_script() and register the script again with the new > parameters. > > > Edit: Sorry, I misread that. `is_plugin_active` is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function `wp_script_is` at `wp_enqueue_scripts` or later.
261,785
<p>So I am trying to display just the notes and the audio which are showing up with "AUDIO" and "TRANSCRIPT" as the output with a link to download them. </p> <p>The issue I am having is that this also out put the featured image and the names of the uploaded PDF and MP3 show like this:</p> <p>newyear2 (name of the featured image)<br> honest-wage (name of the audio file)<br> 16-10-30_mh_the-day-after-the-election (name of PDF)<br> AUDIO (the files I want to show)<br> TRANSCRIPT (the file I want to show)</p> <p>Here is the PHP code:</p> <pre><code>function wpfc_sermon_attachments() { global $post; $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; - 1, 'post_status' =&gt; null, 'post_parent' =&gt; $post-&gt;ID, 'exclude' =&gt; get_post_thumbnail_id() ); $attachments = get_posts( $args ); $html = ''; $html .= '&lt;div id="wpfc-attachments" class="cf"&gt;'; if ( $attachments ) { foreach ( $attachments as $attachment ) { $html .= '&lt;br/&gt;&lt;a target="_blank" href="' . wp_get_attachment_url( $attachment-&gt;ID ) . '"&gt;'; $html .= $attachment-&gt;post_title; } } if ( get_wpfc_sermon_meta( 'sermon_audio' ) ) { $html .= '&lt;a href="' . get_wpfc_sermon_meta( 'sermon_audio' ) . '" class="sermon-attachments"&gt;&lt;i class="fa fa-download" aria-hidden="true"&gt;&lt;/i&gt;' . __( 'AUDIO', 'sermon-manager' ) . '&lt;/a&gt;'; } if ( get_wpfc_sermon_meta( 'sermon_notes' ) ) { $html .= '&lt;a href="' . get_wpfc_sermon_meta( 'sermon_notes' ) . '" class="sermon-attachments"&gt;&lt;i class="fa fa-download" aria-hidden="true"&gt;&lt;/i&gt;' . __( 'TRANSCRIPT', 'sermon-manager' ) . '&lt;/a&gt;'; } if ( get_wpfc_sermon_meta( 'sermon_bulletin' ) ) { $html .= '&lt;a href="' . get_wpfc_sermon_meta( 'sermon_bulletin' ) . '" class="sermon-attachments"&gt;&lt;i class="fa fa-download" aria-hidden="true"&gt;&lt;/i&gt;&lt;/span&gt;' . __( 'Bulletin', 'sermon-manager' ) . '&lt;/a&gt;'; } $html .= '&lt;/a&gt;'; $html .= '&lt;/p&gt;'; $html .= '&lt;/div&gt;'; return $html; </code></pre> <p>Any help would be appreciated! Thanks!</p>
[ { "answer_id": 261845, "author": "Jigar Patel", "author_id": 116524, "author_profile": "https://wordpress.stackexchange.com/users/116524", "pm_score": 0, "selected": false, "text": "<p>You are on the right path. There is no better way to determine script is enqueued or not. This is efficient way <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">wp_script_is( $handle, $list )</a></p>\n<p>Just wondering if your $handle name is correct. Make sure <strong>$handle</strong> while checking wp_script_is is the same as when you enqueue script in pluginB. The first parameter is $handle. Refer to this <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">WP Codex</a>.</p>\n<p>It says:</p>\n<h1>Parameters</h1>\n<p><strong>$handle</strong></p>\n<p>(string) (Required) Name of the script. <strong>Should be unique.</strong></p>\n<p>I believe you are using plugin name as a handle in else part.</p>\n<p><strong>Try using same name &quot;AngularJS&quot; or something but must be the same as $handle</strong></p>\n" }, { "answer_id": 261917, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 2, "selected": true, "text": "<p>Now that I see you were hooking into <code>plugins_loaded</code>, this makes sense because it is fired much earlier than <code>wp_enqueue_scripts</code>. It is expected that your function would return 0 at this point.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence\">here</a> for the order in which actions are generally fired.</p>\n\n<p>Try to <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add an action</a> at <code>wp_enqueue_scripts</code> with a late priority to make sure it runs after other enqueued scripts. Then you can <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">deregister</a> the script and register again with new parameters.</p>\n\n<blockquote>\n <p>If you try to register or enqueue an already registered handle with\n different parameters, the new parameters will be ignored. Instead,\n use wp_deregister_script() and register the script again with the new\n parameters.</p>\n</blockquote>\n\n<p>Edit: Sorry, I misread that. <code>is_plugin_active</code> is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function <code>wp_script_is</code> at <code>wp_enqueue_scripts</code> or later.</p>\n" }, { "answer_id": 262161, "author": "dameer dj", "author_id": 107873, "author_profile": "https://wordpress.stackexchange.com/users/107873", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm wrong but according to WP codex:</p>\n\n<pre><code>wp_script_is( string $handle, string $list = 'enqueued' )\n</code></pre>\n\n<p><code>$handle</code> - unique name of the script</p>\n\n<p>As far as I can see you are using FILE NAME instead which is wrong. By me it has nothing to do with when actions/hooks are being fired coz both of your plugins are fired on <code>plugins_loaded</code>.</p>\n\n<p>So, if you check it out this way</p>\n\n<pre><code>$handle = 'MY_SCRIPT_NAME'; /* can't really be $this-&gt;plugin_name . '-ajs' because it gives 2 different strings */\n</code></pre>\n\n<p>in both of your plugins, only one instance of required JS file will be loaded.</p>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116501/" ]
So I am trying to display just the notes and the audio which are showing up with "AUDIO" and "TRANSCRIPT" as the output with a link to download them. The issue I am having is that this also out put the featured image and the names of the uploaded PDF and MP3 show like this: newyear2 (name of the featured image) honest-wage (name of the audio file) 16-10-30\_mh\_the-day-after-the-election (name of PDF) AUDIO (the files I want to show) TRANSCRIPT (the file I want to show) Here is the PHP code: ``` function wpfc_sermon_attachments() { global $post; $args = array( 'post_type' => 'attachment', 'numberposts' => - 1, 'post_status' => null, 'post_parent' => $post->ID, 'exclude' => get_post_thumbnail_id() ); $attachments = get_posts( $args ); $html = ''; $html .= '<div id="wpfc-attachments" class="cf">'; if ( $attachments ) { foreach ( $attachments as $attachment ) { $html .= '<br/><a target="_blank" href="' . wp_get_attachment_url( $attachment->ID ) . '">'; $html .= $attachment->post_title; } } if ( get_wpfc_sermon_meta( 'sermon_audio' ) ) { $html .= '<a href="' . get_wpfc_sermon_meta( 'sermon_audio' ) . '" class="sermon-attachments"><i class="fa fa-download" aria-hidden="true"></i>' . __( 'AUDIO', 'sermon-manager' ) . '</a>'; } if ( get_wpfc_sermon_meta( 'sermon_notes' ) ) { $html .= '<a href="' . get_wpfc_sermon_meta( 'sermon_notes' ) . '" class="sermon-attachments"><i class="fa fa-download" aria-hidden="true"></i>' . __( 'TRANSCRIPT', 'sermon-manager' ) . '</a>'; } if ( get_wpfc_sermon_meta( 'sermon_bulletin' ) ) { $html .= '<a href="' . get_wpfc_sermon_meta( 'sermon_bulletin' ) . '" class="sermon-attachments"><i class="fa fa-download" aria-hidden="true"></i></span>' . __( 'Bulletin', 'sermon-manager' ) . '</a>'; } $html .= '</a>'; $html .= '</p>'; $html .= '</div>'; return $html; ``` Any help would be appreciated! Thanks!
Now that I see you were hooking into `plugins_loaded`, this makes sense because it is fired much earlier than `wp_enqueue_scripts`. It is expected that your function would return 0 at this point. See [here](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) and [here](https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence) for the order in which actions are generally fired. Try to [add an action](https://developer.wordpress.org/reference/functions/add_action/) at `wp_enqueue_scripts` with a late priority to make sure it runs after other enqueued scripts. Then you can [deregister](https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes) the script and register again with new parameters. > > If you try to register or enqueue an already registered handle with > different parameters, the new parameters will be ignored. Instead, > use wp\_deregister\_script() and register the script again with the new > parameters. > > > Edit: Sorry, I misread that. `is_plugin_active` is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function `wp_script_is` at `wp_enqueue_scripts` or later.
261,789
<p>I am trying to build a function, which gives out different image-urls, according to the last digit of <code>bbp_get_topic_id()</code>.<br> This is, what i've got so far: </p> <pre><code>function bg_image_topic_titlearea() { $letztezifferimgs = substr("'.bbp_get_topic_id().'", -1); switch ($letztezifferimgs) { case "0": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/10/Blockaden-lösen-2.jpg"; break; case "1": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/09/Das-Leben-ist-ein-Spiel-2.jpg"; break; case "2": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/02/Bedürfnisse-erkennen-3.jpg"; break; case "3": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/08/Selbsterkenntnis-sich-selbst-finden2-1.jpg"; break; case "4": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/11/Reinkarnation-Wiedergeburt-2.jpg"; break; case "5": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/10/Intuition3.jpg"; break; case "6": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/07/Manchmal-muss-man-loslassen-3.jpg"; break; case "7": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/07/Manchmal-muss-man-loslassen-3.jpg"; break; case "8": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/02/Pfad.jpg"; break; case "9": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/01/Zirbeldrüse-aktivieren-2.jpg"; break; } } </code></pre> <p>Yet it does not react, if i use <code>.bg_image_topic_titlearea().</code> to get the image url.<br> I am trying to get it done for some time now and i would be glad, if someone could help me. </p> <p>Kind regards<br> Dominik</p>
[ { "answer_id": 261845, "author": "Jigar Patel", "author_id": 116524, "author_profile": "https://wordpress.stackexchange.com/users/116524", "pm_score": 0, "selected": false, "text": "<p>You are on the right path. There is no better way to determine script is enqueued or not. This is efficient way <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">wp_script_is( $handle, $list )</a></p>\n<p>Just wondering if your $handle name is correct. Make sure <strong>$handle</strong> while checking wp_script_is is the same as when you enqueue script in pluginB. The first parameter is $handle. Refer to this <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">WP Codex</a>.</p>\n<p>It says:</p>\n<h1>Parameters</h1>\n<p><strong>$handle</strong></p>\n<p>(string) (Required) Name of the script. <strong>Should be unique.</strong></p>\n<p>I believe you are using plugin name as a handle in else part.</p>\n<p><strong>Try using same name &quot;AngularJS&quot; or something but must be the same as $handle</strong></p>\n" }, { "answer_id": 261917, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 2, "selected": true, "text": "<p>Now that I see you were hooking into <code>plugins_loaded</code>, this makes sense because it is fired much earlier than <code>wp_enqueue_scripts</code>. It is expected that your function would return 0 at this point.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence\">here</a> for the order in which actions are generally fired.</p>\n\n<p>Try to <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add an action</a> at <code>wp_enqueue_scripts</code> with a late priority to make sure it runs after other enqueued scripts. Then you can <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes\" rel=\"nofollow noreferrer\">deregister</a> the script and register again with new parameters.</p>\n\n<blockquote>\n <p>If you try to register or enqueue an already registered handle with\n different parameters, the new parameters will be ignored. Instead,\n use wp_deregister_script() and register the script again with the new\n parameters.</p>\n</blockquote>\n\n<p>Edit: Sorry, I misread that. <code>is_plugin_active</code> is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function <code>wp_script_is</code> at <code>wp_enqueue_scripts</code> or later.</p>\n" }, { "answer_id": 262161, "author": "dameer dj", "author_id": 107873, "author_profile": "https://wordpress.stackexchange.com/users/107873", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm wrong but according to WP codex:</p>\n\n<pre><code>wp_script_is( string $handle, string $list = 'enqueued' )\n</code></pre>\n\n<p><code>$handle</code> - unique name of the script</p>\n\n<p>As far as I can see you are using FILE NAME instead which is wrong. By me it has nothing to do with when actions/hooks are being fired coz both of your plugins are fired on <code>plugins_loaded</code>.</p>\n\n<p>So, if you check it out this way</p>\n\n<pre><code>$handle = 'MY_SCRIPT_NAME'; /* can't really be $this-&gt;plugin_name . '-ajs' because it gives 2 different strings */\n</code></pre>\n\n<p>in both of your plugins, only one instance of required JS file will be loaded.</p>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261789", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116503/" ]
I am trying to build a function, which gives out different image-urls, according to the last digit of `bbp_get_topic_id()`. This is, what i've got so far: ``` function bg_image_topic_titlearea() { $letztezifferimgs = substr("'.bbp_get_topic_id().'", -1); switch ($letztezifferimgs) { case "0": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/10/Blockaden-lösen-2.jpg"; break; case "1": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/09/Das-Leben-ist-ein-Spiel-2.jpg"; break; case "2": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/02/Bedürfnisse-erkennen-3.jpg"; break; case "3": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/08/Selbsterkenntnis-sich-selbst-finden2-1.jpg"; break; case "4": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/11/Reinkarnation-Wiedergeburt-2.jpg"; break; case "5": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/10/Intuition3.jpg"; break; case "6": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/07/Manchmal-muss-man-loslassen-3.jpg"; break; case "7": echo "https://test.bewusstewelt.de/wp-content/uploads/2016/07/Manchmal-muss-man-loslassen-3.jpg"; break; case "8": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/02/Pfad.jpg"; break; case "9": echo "https://test.bewusstewelt.de/wp-content/uploads/2017/01/Zirbeldrüse-aktivieren-2.jpg"; break; } } ``` Yet it does not react, if i use `.bg_image_topic_titlearea().` to get the image url. I am trying to get it done for some time now and i would be glad, if someone could help me. Kind regards Dominik
Now that I see you were hooking into `plugins_loaded`, this makes sense because it is fired much earlier than `wp_enqueue_scripts`. It is expected that your function would return 0 at this point. See [here](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request) and [here](https://wordpress.stackexchange.com/questions/162862/how-to-get-wordpress-hook-run-sequence) for the order in which actions are generally fired. Try to [add an action](https://developer.wordpress.org/reference/functions/add_action/) at `wp_enqueue_scripts` with a late priority to make sure it runs after other enqueued scripts. Then you can [deregister](https://developer.wordpress.org/reference/functions/wp_enqueue_script/#notes) the script and register again with new parameters. > > If you try to register or enqueue an already registered handle with > different parameters, the new parameters will be ignored. Instead, > use wp\_deregister\_script() and register the script again with the new > parameters. > > > Edit: Sorry, I misread that. `is_plugin_active` is not an action hook and will immediately return true without telling you whether the script is enqueued. It still stands that you must hook the function `wp_script_is` at `wp_enqueue_scripts` or later.
261,829
<p>I am setting the featured image as a background for the top part of the page. The images are quite large and I'd like to be able to set smaller image sizes for smaller screen sizes. Since the images are added inline, I don't think I can use the external styles.css file to set different images.</p> <p>Here's an example of what I have:</p> <pre><code>&lt;?php $bannerImg = ''; if(has_post_thumbnail()) { $bannerImg = get_the_post_thumbnail_url(); } ?&gt; &lt;section class="page-banner" style="background-image: url(&lt;?php echo $bannerImg; ?&gt;);"&gt; &lt;h1 class="banner-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;/section&gt; </code></pre> <p>I'd like to do something like <code>srcset</code> but I couldn't find an equivalent for background images.</p>
[ { "answer_id": 261847, "author": "ferdouswp", "author_id": 114362, "author_profile": "https://wordpress.stackexchange.com/users/114362", "pm_score": -1, "selected": false, "text": "<pre>\n\n<b>You can simply use CSS media query for different device one example </b>\n\n@media only screen and (max-width: 320px) {\n /* styles for narrow screens */\n .page-banner{\n background-size:100% auto;\n background-repeat:no-repeat;\n background-position:center;\n display: block;\n width: 100%;\n height: 500px;\n }\n\n}\n\nYou can use different page different class id \npage-id-34 logged-in wpb-js-composer js-comp-ver-4.12 vc_responsive\">\n</pre>\n" }, { "answer_id": 262029, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>If you use Adaptive Images plugin for WordPress, you would just make one inline css for all viewport widths using the biggest image and then it does all the work on the server. You do nothing to your markup but in the Adaptive Images plugin settings you enter your breakpoints, so it will serve small images to small devices and so forth.</p>\n\n<p>If you use Adaptive Images it would be:</p>\n\n<pre><code>/** \n *\n * Background Image from Post Image using Adaptive Images Plugin for WordPress\n * @since 1.0.0\n * Credits: TwentyFifteen WordPress theme adjacent pagination\n *\n */\nfunction the_other_idea_good_heavens_change_this_function_name() {\n\n global $post;\n\n if ( ! has_post_thumbnail( $post-&gt;ID ) ) return; //exit if there is no featured image\n\n $theme_handle = 'visionary'; //the theme handle used for the main style.css file\n\n //image\n $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'super-huge-image' );\n\n //css\n $css = '.banner-image { background-image: url(' . esc_url( $image[0] ) . '); } ';\n\n //minify \n $css = str_replace( array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\", ' ', ' ', ' '), '', $css );\n\n //add it\n wp_add_inline_style( $theme_handle, $css );\n\n}\nadd_action( 'wp_enqueue_scripts', 'the_other_idea_good_heavens_change_this_function_name', 99 );\n</code></pre>\n\n<p>This is what I do (before I started using Adapative Images ).</p>\n\n<pre><code>add_image_size();\n</code></pre>\n\n<p>I use three sizes small, medium, large in this example and then I regenerate my thumbnails.</p>\n\n<pre><code>/** \n *\n * Background Image from Post Image\n * @since 1.0.0\n * Credits: TwentyFifteen WordPress theme adjacent pagination\n *\n */\nfunction yourprefix_responsive_mobile_first_background_images() {\n\n global $post;\n\n if ( ! has_post_thumbnail( $post-&gt;ID ) ) return; //exit if there is no featured image\n\n\n $theme_handle = 'visionary'; //the theme handle used for the main style.css file\n $property = '.banner-image'; //the property\n $css = '';\n\n //small image\n $small_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-small-image-size' );\n $small_style = '\n ' . $property . ' { background-image: url(' . esc_url( $small_img[0] ) . '); }\n ';\n $css .= $small_style;\n\n\n //medium image\n $medium_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-medium-image-size' );\n $medium_style = '\n ' . $property . ' { background-image: url(' . esc_url( $medium_img[0] ) . '); }\n ';\n $css .= '@media (min-width: 1000px) { '. $medium_style . ' }';\n\n\n //large image\n $large_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-large-image-size' );\n $large_style = '\n ' . $property . ' { background-image: url(' . esc_url( $large_img[0] ) . '); }\n ';\n $css .= '@media (min-width: 1700px) { '. $large_style . ' }';\n\n //minify \n $css = str_replace( array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\", ' ', ' ', ' '), '', $css );\n\n //add it\n wp_add_inline_style( $theme_handle, $css );\n\n}\nadd_action( 'wp_enqueue_scripts', 'yourprefix_responsive_mobile_first_background_images', 99 );\n</code></pre>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38890/" ]
I am setting the featured image as a background for the top part of the page. The images are quite large and I'd like to be able to set smaller image sizes for smaller screen sizes. Since the images are added inline, I don't think I can use the external styles.css file to set different images. Here's an example of what I have: ``` <?php $bannerImg = ''; if(has_post_thumbnail()) { $bannerImg = get_the_post_thumbnail_url(); } ?> <section class="page-banner" style="background-image: url(<?php echo $bannerImg; ?>);"> <h1 class="banner-title"><?php the_title(); ?></h1> </section> ``` I'd like to do something like `srcset` but I couldn't find an equivalent for background images.
If you use Adaptive Images plugin for WordPress, you would just make one inline css for all viewport widths using the biggest image and then it does all the work on the server. You do nothing to your markup but in the Adaptive Images plugin settings you enter your breakpoints, so it will serve small images to small devices and so forth. If you use Adaptive Images it would be: ``` /** * * Background Image from Post Image using Adaptive Images Plugin for WordPress * @since 1.0.0 * Credits: TwentyFifteen WordPress theme adjacent pagination * */ function the_other_idea_good_heavens_change_this_function_name() { global $post; if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image $theme_handle = 'visionary'; //the theme handle used for the main style.css file //image $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'super-huge-image' ); //css $css = '.banner-image { background-image: url(' . esc_url( $image[0] ) . '); } '; //minify $css = str_replace( array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css ); //add it wp_add_inline_style( $theme_handle, $css ); } add_action( 'wp_enqueue_scripts', 'the_other_idea_good_heavens_change_this_function_name', 99 ); ``` This is what I do (before I started using Adapative Images ). ``` add_image_size(); ``` I use three sizes small, medium, large in this example and then I regenerate my thumbnails. ``` /** * * Background Image from Post Image * @since 1.0.0 * Credits: TwentyFifteen WordPress theme adjacent pagination * */ function yourprefix_responsive_mobile_first_background_images() { global $post; if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image $theme_handle = 'visionary'; //the theme handle used for the main style.css file $property = '.banner-image'; //the property $css = ''; //small image $small_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-small-image-size' ); $small_style = ' ' . $property . ' { background-image: url(' . esc_url( $small_img[0] ) . '); } '; $css .= $small_style; //medium image $medium_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-medium-image-size' ); $medium_style = ' ' . $property . ' { background-image: url(' . esc_url( $medium_img[0] ) . '); } '; $css .= '@media (min-width: 1000px) { '. $medium_style . ' }'; //large image $large_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-large-image-size' ); $large_style = ' ' . $property . ' { background-image: url(' . esc_url( $large_img[0] ) . '); } '; $css .= '@media (min-width: 1700px) { '. $large_style . ' }'; //minify $css = str_replace( array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css ); //add it wp_add_inline_style( $theme_handle, $css ); } add_action( 'wp_enqueue_scripts', 'yourprefix_responsive_mobile_first_background_images', 99 ); ```
261,832
<p>I've been using shortcodes for cutting down on the amount of html I have in my visual editor.</p> <p>I have a shortcode [person] with features name, age, location, phone, and description. I want to list my 50 friends on a page. Each feature of the person needs to be styled in html and the same on all. Each person returns the same info with about 10 different tags, etc.</p> <p>Is it super inefficient (processing) to have a page with 50 people:</p> <p>[person name="Doug Vander" age="60" location="United States" phone="1119992929"]Doug has been my friend for a long time.......[/person]</p> <p>.... [person name="Lastperson"].......[/person]</p> <p>Is there a better way to list info I re-use all the time?</p>
[ { "answer_id": 261847, "author": "ferdouswp", "author_id": 114362, "author_profile": "https://wordpress.stackexchange.com/users/114362", "pm_score": -1, "selected": false, "text": "<pre>\n\n<b>You can simply use CSS media query for different device one example </b>\n\n@media only screen and (max-width: 320px) {\n /* styles for narrow screens */\n .page-banner{\n background-size:100% auto;\n background-repeat:no-repeat;\n background-position:center;\n display: block;\n width: 100%;\n height: 500px;\n }\n\n}\n\nYou can use different page different class id \npage-id-34 logged-in wpb-js-composer js-comp-ver-4.12 vc_responsive\">\n</pre>\n" }, { "answer_id": 262029, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>If you use Adaptive Images plugin for WordPress, you would just make one inline css for all viewport widths using the biggest image and then it does all the work on the server. You do nothing to your markup but in the Adaptive Images plugin settings you enter your breakpoints, so it will serve small images to small devices and so forth.</p>\n\n<p>If you use Adaptive Images it would be:</p>\n\n<pre><code>/** \n *\n * Background Image from Post Image using Adaptive Images Plugin for WordPress\n * @since 1.0.0\n * Credits: TwentyFifteen WordPress theme adjacent pagination\n *\n */\nfunction the_other_idea_good_heavens_change_this_function_name() {\n\n global $post;\n\n if ( ! has_post_thumbnail( $post-&gt;ID ) ) return; //exit if there is no featured image\n\n $theme_handle = 'visionary'; //the theme handle used for the main style.css file\n\n //image\n $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'super-huge-image' );\n\n //css\n $css = '.banner-image { background-image: url(' . esc_url( $image[0] ) . '); } ';\n\n //minify \n $css = str_replace( array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\", ' ', ' ', ' '), '', $css );\n\n //add it\n wp_add_inline_style( $theme_handle, $css );\n\n}\nadd_action( 'wp_enqueue_scripts', 'the_other_idea_good_heavens_change_this_function_name', 99 );\n</code></pre>\n\n<p>This is what I do (before I started using Adapative Images ).</p>\n\n<pre><code>add_image_size();\n</code></pre>\n\n<p>I use three sizes small, medium, large in this example and then I regenerate my thumbnails.</p>\n\n<pre><code>/** \n *\n * Background Image from Post Image\n * @since 1.0.0\n * Credits: TwentyFifteen WordPress theme adjacent pagination\n *\n */\nfunction yourprefix_responsive_mobile_first_background_images() {\n\n global $post;\n\n if ( ! has_post_thumbnail( $post-&gt;ID ) ) return; //exit if there is no featured image\n\n\n $theme_handle = 'visionary'; //the theme handle used for the main style.css file\n $property = '.banner-image'; //the property\n $css = '';\n\n //small image\n $small_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-small-image-size' );\n $small_style = '\n ' . $property . ' { background-image: url(' . esc_url( $small_img[0] ) . '); }\n ';\n $css .= $small_style;\n\n\n //medium image\n $medium_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-medium-image-size' );\n $medium_style = '\n ' . $property . ' { background-image: url(' . esc_url( $medium_img[0] ) . '); }\n ';\n $css .= '@media (min-width: 1000px) { '. $medium_style . ' }';\n\n\n //large image\n $large_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'my-large-image-size' );\n $large_style = '\n ' . $property . ' { background-image: url(' . esc_url( $large_img[0] ) . '); }\n ';\n $css .= '@media (min-width: 1700px) { '. $large_style . ' }';\n\n //minify \n $css = str_replace( array(\"\\r\\n\", \"\\r\", \"\\n\", \"\\t\", ' ', ' ', ' '), '', $css );\n\n //add it\n wp_add_inline_style( $theme_handle, $css );\n\n}\nadd_action( 'wp_enqueue_scripts', 'yourprefix_responsive_mobile_first_background_images', 99 );\n</code></pre>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104376/" ]
I've been using shortcodes for cutting down on the amount of html I have in my visual editor. I have a shortcode [person] with features name, age, location, phone, and description. I want to list my 50 friends on a page. Each feature of the person needs to be styled in html and the same on all. Each person returns the same info with about 10 different tags, etc. Is it super inefficient (processing) to have a page with 50 people: [person name="Doug Vander" age="60" location="United States" phone="1119992929"]Doug has been my friend for a long time.......[/person] .... [person name="Lastperson"].......[/person] Is there a better way to list info I re-use all the time?
If you use Adaptive Images plugin for WordPress, you would just make one inline css for all viewport widths using the biggest image and then it does all the work on the server. You do nothing to your markup but in the Adaptive Images plugin settings you enter your breakpoints, so it will serve small images to small devices and so forth. If you use Adaptive Images it would be: ``` /** * * Background Image from Post Image using Adaptive Images Plugin for WordPress * @since 1.0.0 * Credits: TwentyFifteen WordPress theme adjacent pagination * */ function the_other_idea_good_heavens_change_this_function_name() { global $post; if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image $theme_handle = 'visionary'; //the theme handle used for the main style.css file //image $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'super-huge-image' ); //css $css = '.banner-image { background-image: url(' . esc_url( $image[0] ) . '); } '; //minify $css = str_replace( array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css ); //add it wp_add_inline_style( $theme_handle, $css ); } add_action( 'wp_enqueue_scripts', 'the_other_idea_good_heavens_change_this_function_name', 99 ); ``` This is what I do (before I started using Adapative Images ). ``` add_image_size(); ``` I use three sizes small, medium, large in this example and then I regenerate my thumbnails. ``` /** * * Background Image from Post Image * @since 1.0.0 * Credits: TwentyFifteen WordPress theme adjacent pagination * */ function yourprefix_responsive_mobile_first_background_images() { global $post; if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image $theme_handle = 'visionary'; //the theme handle used for the main style.css file $property = '.banner-image'; //the property $css = ''; //small image $small_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-small-image-size' ); $small_style = ' ' . $property . ' { background-image: url(' . esc_url( $small_img[0] ) . '); } '; $css .= $small_style; //medium image $medium_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-medium-image-size' ); $medium_style = ' ' . $property . ' { background-image: url(' . esc_url( $medium_img[0] ) . '); } '; $css .= '@media (min-width: 1000px) { '. $medium_style . ' }'; //large image $large_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'my-large-image-size' ); $large_style = ' ' . $property . ' { background-image: url(' . esc_url( $large_img[0] ) . '); } '; $css .= '@media (min-width: 1700px) { '. $large_style . ' }'; //minify $css = str_replace( array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css ); //add it wp_add_inline_style( $theme_handle, $css ); } add_action( 'wp_enqueue_scripts', 'yourprefix_responsive_mobile_first_background_images', 99 ); ```
261,833
<p>I am trying to output some calendar events from a custom table which are also tied to a custom post type. I have this working except that in my foreach loop, the last date is repeated in each row. I need some help using the right method of getting the $eventDate correctly. Here is my code:</p> <pre><code>&lt;?php $today = date('Y-m-d'); global $wpdb; $events = $wpdb-&gt;get_results("SELECT * FROM ".$wpdb-&gt;prefix."calp_events WHERE start &gt;= '$today' ORDER BY start ASC LIMIT 5"); foreach ($events as $event) : $eventID = $event-&gt;post_id; $eventDate = $event-&gt;start; endforeach; global $post; $args = array ( 'post_type' =&gt; 'calp_event', 'ID' =&gt; $eventID, ); $myposts = get_posts($args); foreach ($myposts as $post) : setup_postdata($post); echo $eventDate.' '.the_title().'&lt;br&gt;'; endforeach; ?&gt; </code></pre> <p>Somehow I need to be able to get the $eventDate in the last loop.</p>
[ { "answer_id": 261843, "author": "Jigar Patel", "author_id": 116524, "author_profile": "https://wordpress.stackexchange.com/users/116524", "pm_score": 0, "selected": false, "text": "<p>You need to go for the <strong>nested loop</strong>. Try this</p>\n\n<pre><code>&lt;?php\n $today = date('Y-m-d');\n global $wpdb;\n $events = $wpdb-&gt;get_results(\"SELECT * FROM \".$wpdb-&gt;prefix.\"calp_events WHERE start &gt;= '$today' ORDER BY start ASC LIMIT 5\");\n\n global $post;\n\n foreach ($events as $event) :\n $eventID = $event-&gt;post_id;\n $eventDate = $event-&gt;start;\n $args = array (\n 'post_type' =&gt; 'calp_event',\n 'ID' =&gt; $eventID,\n );\n $myposts = get_posts($args);\n foreach ($myposts as $post) : setup_postdata($post);\n echo $eventDate.' '.the_title().'&lt;br&gt;';\n endforeach;\n\n // wp_reset_postdata();\n endforeach;\n\n?&gt;\n</code></pre>\n\n<p>I moved your second foreach block inside the first one, so you will have everytime different $eventID and $eventDate. If it give you same data everytime try removing wp_reset_postdata(); comment block.</p>\n" }, { "answer_id": 261960, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": true, "text": "<p>As discussed in the comments, instead of using the <code>ID</code> query argument to get each <code>'calp_event'</code>-type post individually, you can pass an array of IDs to <code>post__in</code> in order to grab them all at once, thus reducing the number of database transactions in your code to 2.</p>\n\n<p>By creating an array mapping post IDs to event start dates from the results of your 3rd-party table query, you can easily obtain the value to pass to <code>post__in</code> by using <code>array_keys()</code> to get an array of just post IDs. Then later in the loop, you can look up the start date using the same post-ID-to-start-date map.</p>\n\n<p>Since you're looping through query results and using template tags in a manner similar to WordPress's \"Loop\", you might also consider using a new <code>WP_Query</code> object instead of <code>get_posts()</code> to allow you to use a more conventional \"Loop\" logic to display your results.</p>\n\n<pre><code>global $wpdb;\n\n$today = date('Y-m-d');\n$events = $wpdb-&gt;get_results( \"SELECT * FROM \" . $wpdb-&gt;prefix . \"calp_events WHERE start &gt;= '$today' ORDER BY start ASC LIMIT 5\" );\n\n// Create an array using event post IDs as keys and start dates as values\n$eventDates = array();\nforeach( $events as $event ) {\n $eventDates[ $event-&gt;post_id ] = $event-&gt;start;\n}\n\n// Query for the 'calp_event' posts indicated by the earlier query.\n// Since the keys of $eventDates are the post IDs returned by the previous query, \n// array_keys( $eventDates ) will return an array consisting of those IDs\n$eventQuery = new WP_Query( array(\n 'post_type' =&gt; 'calp_event',\n 'post__in' =&gt; array_keys( $eventDates )\n) );\n\n// Use conventional Loop logic to display your results\nif( $eventQuery-&gt;have_posts() ) {\n while( $eventQuery-&gt;have_posts() ) {\n $eventQuery-&gt;the_post();\n\n // Accessing the $eventDates array with the current post ID as a key will produce\n // the event start date which that ID is mapped to.\n echo $eventDates[ get_the_ID() ] . ' ' . the_title() . '&lt;br&gt;';\n }\n\n // Reset global post data so we don't muck up the main query\n wp_reset_postdata();\n}\nelse {\n echo 'No upcoming events!';\n}\n</code></pre>\n\n<p>You could reduce this to a single query by using more advanced SQL to grab all of the necessary posts and event start-dates in one go.</p>\n" } ]
2017/03/29
[ "https://wordpress.stackexchange.com/questions/261833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40891/" ]
I am trying to output some calendar events from a custom table which are also tied to a custom post type. I have this working except that in my foreach loop, the last date is repeated in each row. I need some help using the right method of getting the $eventDate correctly. Here is my code: ``` <?php $today = date('Y-m-d'); global $wpdb; $events = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."calp_events WHERE start >= '$today' ORDER BY start ASC LIMIT 5"); foreach ($events as $event) : $eventID = $event->post_id; $eventDate = $event->start; endforeach; global $post; $args = array ( 'post_type' => 'calp_event', 'ID' => $eventID, ); $myposts = get_posts($args); foreach ($myposts as $post) : setup_postdata($post); echo $eventDate.' '.the_title().'<br>'; endforeach; ?> ``` Somehow I need to be able to get the $eventDate in the last loop.
As discussed in the comments, instead of using the `ID` query argument to get each `'calp_event'`-type post individually, you can pass an array of IDs to `post__in` in order to grab them all at once, thus reducing the number of database transactions in your code to 2. By creating an array mapping post IDs to event start dates from the results of your 3rd-party table query, you can easily obtain the value to pass to `post__in` by using `array_keys()` to get an array of just post IDs. Then later in the loop, you can look up the start date using the same post-ID-to-start-date map. Since you're looping through query results and using template tags in a manner similar to WordPress's "Loop", you might also consider using a new `WP_Query` object instead of `get_posts()` to allow you to use a more conventional "Loop" logic to display your results. ``` global $wpdb; $today = date('Y-m-d'); $events = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "calp_events WHERE start >= '$today' ORDER BY start ASC LIMIT 5" ); // Create an array using event post IDs as keys and start dates as values $eventDates = array(); foreach( $events as $event ) { $eventDates[ $event->post_id ] = $event->start; } // Query for the 'calp_event' posts indicated by the earlier query. // Since the keys of $eventDates are the post IDs returned by the previous query, // array_keys( $eventDates ) will return an array consisting of those IDs $eventQuery = new WP_Query( array( 'post_type' => 'calp_event', 'post__in' => array_keys( $eventDates ) ) ); // Use conventional Loop logic to display your results if( $eventQuery->have_posts() ) { while( $eventQuery->have_posts() ) { $eventQuery->the_post(); // Accessing the $eventDates array with the current post ID as a key will produce // the event start date which that ID is mapped to. echo $eventDates[ get_the_ID() ] . ' ' . the_title() . '<br>'; } // Reset global post data so we don't muck up the main query wp_reset_postdata(); } else { echo 'No upcoming events!'; } ``` You could reduce this to a single query by using more advanced SQL to grab all of the necessary posts and event start-dates in one go.
261,838
<p>I need to add a div before the first paragraph.</p> <p>Example:</p> <pre><code>&lt;div class="ads-site"&gt;ADS &lt;/div&gt; &lt;p&gt;First Paragraph&lt;/p&gt; &lt;p&gt;Second Paragraph&lt;/p&gt; </code></pre> <p>My Function:</p> <pre><code>global $post; function my_content_div( $content ) { $content = '&lt;div&gt;My div&lt;/div&gt;' . $content; return $content; } add_filter('the_content', 'my_content_div'); </code></pre>
[ { "answer_id": 261840, "author": "Yogensia", "author_id": 97143, "author_profile": "https://wordpress.stackexchange.com/users/97143", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code> filter</a> if that helps:</p>\n\n<pre><code>function my_content_div( $content ) {\n $content = '&lt;div&gt;My div&lt;/div&gt;' . $content;\n return $content;\n}\nadd_filter('the_content', 'my_content_div');\n</code></pre>\n\n<p>You can also add <code>global $post;</code> inside the function to get info on the post and have more control when you show the div.</p>\n" }, { "answer_id": 261841, "author": "ricotheque", "author_id": 34238, "author_profile": "https://wordpress.stackexchange.com/users/34238", "pm_score": 2, "selected": true, "text": "<p>Yogenisia's is right that you should use <code>the_content</code> filter.</p>\n\n<p>If you want to insert something before the first paragraph, locate the first <code>&lt;p&gt;</code> in <code>$content</code>, then insert your <code>div</code> with <code>substr_replace</code>.</p>\n\n<pre><code>add_filter( 'the_content', 'namespace_insert_before_first_paragraph' );\n\nfunction namespace_insert_before_first_paragraph( $content ) { \n $my_div = '&lt;div&gt; ... &lt;/div&gt;';\n $first_para_pos = strpos( $content, '&lt;p' );\n $new_content = substr_replace( $content, $my_div, $first_para_pos, 0 );\n\n return $new_content;\n}\n</code></pre>\n\n<p>Keep in mind however that many embeds, such as Twitter's, wrap their content in a <code>&lt;p&gt;...&lt;/p&gt;</code>.</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I need to add a div before the first paragraph. Example: ``` <div class="ads-site">ADS </div> <p>First Paragraph</p> <p>Second Paragraph</p> ``` My Function: ``` global $post; function my_content_div( $content ) { $content = '<div>My div</div>' . $content; return $content; } add_filter('the_content', 'my_content_div'); ```
Yogenisia's is right that you should use `the_content` filter. If you want to insert something before the first paragraph, locate the first `<p>` in `$content`, then insert your `div` with `substr_replace`. ``` add_filter( 'the_content', 'namespace_insert_before_first_paragraph' ); function namespace_insert_before_first_paragraph( $content ) { $my_div = '<div> ... </div>'; $first_para_pos = strpos( $content, '<p' ); $new_content = substr_replace( $content, $my_div, $first_para_pos, 0 ); return $new_content; } ``` Keep in mind however that many embeds, such as Twitter's, wrap their content in a `<p>...</p>`.
261,855
<p>I have a custom post type, named 'products', it has a custom taxonomy that is called 'collections'.<br> This is how I have registered the taxonomy.</p> <pre><code>$productTaxonomyArgs = [ 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_admin_column' =&gt; true, 'description' =&gt; __('Product category', 'byronposttypes'), 'hierarchical' =&gt; true, 'rewrite' =&gt; [ 'slug' =&gt; __('collections', 'byronposttypes'), 'with_front' =&gt; true, 'hierarchical' =&gt; true, 'ep_mask' =&gt; EP_CATEGORIES ], ]; register_taxonomy('collections', 'products', $productTaxonomyArgs); register_taxonomy_for_object_type('collections', 'products'); </code></pre> <p>I have created a taxonomy template by the name taxonomy-collections.php. </p> <pre><code>&lt;?php get_header(); $post = null; echo '&lt;h1&gt;taxonomy-collections.php&lt;/h1&gt;'; //Echo this to make sure the template works. if (have_posts()) { while (have_posts()) { //rest of the code </code></pre> <p>When I navigate to <code>/collections/lifestyle</code> (lifestyle is one of the taxonomy terms), the <code>&lt;title&gt;</code> is 'Lifestyle Archives - [sitename]', so Wordpress does recognise the url as a taxonomy term archive. The problem is, that it doesn't even echo <code>&lt;h1&gt;taxonomy-collections.php&lt;/h1&gt;</code> to the page. That makes me assume that the <code>taxonomy-collections.php</code> is not recognised by Wordpress.<br> Any idea as to what I am doing wrong? Thanks a lot for reading and helping!<br> I found out that Wordpress is falling back to index.php. But <code>is_tax();</code> returns <code>true</code>. Not a single one of the taxonomy-specific templates seem to work (<code>taxonomy.php</code>, <code>taxonomy-collection.php</code> and <code>taxonomy-collection-lifestyle.php</code>), not even <code>archive.php</code> will work.</p>
[ { "answer_id": 261864, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": -1, "selected": false, "text": "<p>Try this code, its working for me ..</p>\n\n<pre><code> function add_collection_taxonomies() {\n $productTaxonomyArgs = array(\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'show_admin_column' =&gt; true,\n 'description' =&gt; __('Product category', 'byronposttypes'),\n 'hierarchical' =&gt; true,\n 'rewrite' =&gt; array(\n 'slug' =&gt; __('collections', 'byronposttypes'),\n 'with_front' =&gt; true,\n 'hierarchical' =&gt; true,\n 'ep_mask' =&gt; EP_CATEGORIES\n ),\n );\n register_taxonomy_for_object_type('collections', 'products');\n register_taxonomy('collections', 'product', $productTaxonomyArgs);\n</code></pre>\n" }, { "answer_id": 261888, "author": "Connor", "author_id": 106941, "author_profile": "https://wordpress.stackexchange.com/users/106941", "pm_score": 2, "selected": true, "text": "<p>I just found out what I was doing wrong. Apparently you have to place archive pages in the root folder of your theme.<br>\nI placed them in a subfolder called templates. This works for page templates with a template name, but not for <code>taxonomy.php</code>, <code>archive.php</code>, <code>single.php</code> etc.</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106941/" ]
I have a custom post type, named 'products', it has a custom taxonomy that is called 'collections'. This is how I have registered the taxonomy. ``` $productTaxonomyArgs = [ 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_admin_column' => true, 'description' => __('Product category', 'byronposttypes'), 'hierarchical' => true, 'rewrite' => [ 'slug' => __('collections', 'byronposttypes'), 'with_front' => true, 'hierarchical' => true, 'ep_mask' => EP_CATEGORIES ], ]; register_taxonomy('collections', 'products', $productTaxonomyArgs); register_taxonomy_for_object_type('collections', 'products'); ``` I have created a taxonomy template by the name taxonomy-collections.php. ``` <?php get_header(); $post = null; echo '<h1>taxonomy-collections.php</h1>'; //Echo this to make sure the template works. if (have_posts()) { while (have_posts()) { //rest of the code ``` When I navigate to `/collections/lifestyle` (lifestyle is one of the taxonomy terms), the `<title>` is 'Lifestyle Archives - [sitename]', so Wordpress does recognise the url as a taxonomy term archive. The problem is, that it doesn't even echo `<h1>taxonomy-collections.php</h1>` to the page. That makes me assume that the `taxonomy-collections.php` is not recognised by Wordpress. Any idea as to what I am doing wrong? Thanks a lot for reading and helping! I found out that Wordpress is falling back to index.php. But `is_tax();` returns `true`. Not a single one of the taxonomy-specific templates seem to work (`taxonomy.php`, `taxonomy-collection.php` and `taxonomy-collection-lifestyle.php`), not even `archive.php` will work.
I just found out what I was doing wrong. Apparently you have to place archive pages in the root folder of your theme. I placed them in a subfolder called templates. This works for page templates with a template name, but not for `taxonomy.php`, `archive.php`, `single.php` etc.
261,868
<p>Im using a charts plugin an i need to force some array elements to be strings.</p> <pre><code>$values_x = array(); for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) { $values_x[] = $series[0]['data'][$i][0]; } $values_y = array(); for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) { $values_y[] = $series[0]['data'][$i][1]; } $categories = array( "label" =&gt; $label_x, "values" =&gt; $values_x, "colors" =&gt; $eco_chart_colors, ); $series = array("label" =&gt; null, "values" =&gt; array( array("data" =&gt; $values_y))); } else { $categories = array( "label" =&gt; $label_x, "values" =&gt; $values_x, "colors" =&gt; "", ); $series = array("label" =&gt; $label_y, "values" =&gt; $series); } </code></pre> <p>i need $values_x to become strings. it outputs the years in the graph but in the json it comes as integers and i need it to be strings. eg: not 2010 but '2010'. ive tried with strval and some other options but cant seem to get it right, it outputs "values":null when i try it. can someone help? thanks in advance.</p>
[ { "answer_id": 261910, "author": "xvilo", "author_id": 104427, "author_profile": "https://wordpress.stackexchange.com/users/104427", "pm_score": 0, "selected": false, "text": "<p>I am not sure how your code works. \nBut if <code>$series[0]['data'][$i][0]</code> generates <code>2010</code> for example you could do this:</p>\n\n<pre><code>$values_x = array();\n for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) {\n $values_x[] = (string)$series[0]['data'][$i][0];\n }\n\n $values_y = array();\n for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) {\n $values_y[] = $series[0]['data'][$i][1];\n }\n\n $categories = array(\n \"label\" =&gt; $label_x,\n \"values\" =&gt; $values_x,\n \"colors\" =&gt; $eco_chart_colors,\n );\n\n $series = array(\"label\" =&gt; null, \"values\" =&gt; array( array(\"data\" =&gt; $values_y)));\n\n } else {\n\n $categories = array(\n \"label\" =&gt; $label_x,\n \"values\" =&gt; $values_x,\n \"colors\" =&gt; \"\",\n );\n\n $series = array(\"label\" =&gt; $label_y, \"values\" =&gt; $series);\n\n }\n</code></pre>\n\n<p>You can force a specifice type with <code>(int)</code>, <code>(bool)</code>, <code>(string)</code> etc. \nAn example for string would be:</p>\n\n<pre><code>$AlwaysAnInt = (int)$CouldBeAnInt\n</code></pre>\n" }, { "answer_id": 261911, "author": "Clint Stegman", "author_id": 115494, "author_profile": "https://wordpress.stackexchange.com/users/115494", "pm_score": 2, "selected": false, "text": "<p>There are a few ways you can make an integer a string. Here are 2 main ways to make that happen</p>\n\n<ol>\n<li><p><strong>Type Cast</strong> - <code>$values_x[] = (string) $series[0]['data'][$i][0]</code></p></li>\n<li><p><strong>Double Quote</strong> - <code>$values_x[] \"{$series[0]['data'][$i][0]}\"</code></p></li>\n</ol>\n\n<p>Also, you might want to check for null first and assign a default</p>\n\n<pre><code>$values_x = !empty($values_x) ? $values_x : array('2010');\n</code></pre>\n\n<p>If you want to make the whole array a string, use <code>implode</code></p>\n\n<pre><code>\"values\" =&gt; implode(', ', $values_x)\n</code></pre>\n\n<p>If you have multiple integers, this will output '2010, 2011'. Replace the comma and space with what you want placed between the pieces.</p>\n\n<p><a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.implode.php</a></p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116556/" ]
Im using a charts plugin an i need to force some array elements to be strings. ``` $values_x = array(); for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) { $values_x[] = $series[0]['data'][$i][0]; } $values_y = array(); for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) { $values_y[] = $series[0]['data'][$i][1]; } $categories = array( "label" => $label_x, "values" => $values_x, "colors" => $eco_chart_colors, ); $series = array("label" => null, "values" => array( array("data" => $values_y))); } else { $categories = array( "label" => $label_x, "values" => $values_x, "colors" => "", ); $series = array("label" => $label_y, "values" => $series); } ``` i need $values\_x to become strings. it outputs the years in the graph but in the json it comes as integers and i need it to be strings. eg: not 2010 but '2010'. ive tried with strval and some other options but cant seem to get it right, it outputs "values":null when i try it. can someone help? thanks in advance.
There are a few ways you can make an integer a string. Here are 2 main ways to make that happen 1. **Type Cast** - `$values_x[] = (string) $series[0]['data'][$i][0]` 2. **Double Quote** - `$values_x[] "{$series[0]['data'][$i][0]}"` Also, you might want to check for null first and assign a default ``` $values_x = !empty($values_x) ? $values_x : array('2010'); ``` If you want to make the whole array a string, use `implode` ``` "values" => implode(', ', $values_x) ``` If you have multiple integers, this will output '2010, 2011'. Replace the comma and space with what you want placed between the pieces. <http://php.net/manual/en/function.implode.php>
261,870
<p>I want to add a third column consisting of an input textfield using the Settings API. Is this possible?</p> <pre><code>function print_custom_field() { $value = get_option( 'my_first_field', '' ); $value_second = get_option( 'my_second_field', '' ); echo '&lt;input type="text" id="my_first_field" name="my_first_field" value="' . $value . '" /&gt;'; echo '&lt;input type="text" id="my_second_field" name="my_second_field" value="' . $value_second . '" /&gt;'; } add_filter('admin_init', 'register_fields'); </code></pre> <p>EDIT: I tried this code and Wordpress doesn't save the values of the second input field. Only the value of the first input field gets saved. How can I show another text input in the same row?</p>
[ { "answer_id": 261910, "author": "xvilo", "author_id": 104427, "author_profile": "https://wordpress.stackexchange.com/users/104427", "pm_score": 0, "selected": false, "text": "<p>I am not sure how your code works. \nBut if <code>$series[0]['data'][$i][0]</code> generates <code>2010</code> for example you could do this:</p>\n\n<pre><code>$values_x = array();\n for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) {\n $values_x[] = (string)$series[0]['data'][$i][0];\n }\n\n $values_y = array();\n for ($i = 0; $i &lt; count( $series[0]['data'] ); $i++ ) {\n $values_y[] = $series[0]['data'][$i][1];\n }\n\n $categories = array(\n \"label\" =&gt; $label_x,\n \"values\" =&gt; $values_x,\n \"colors\" =&gt; $eco_chart_colors,\n );\n\n $series = array(\"label\" =&gt; null, \"values\" =&gt; array( array(\"data\" =&gt; $values_y)));\n\n } else {\n\n $categories = array(\n \"label\" =&gt; $label_x,\n \"values\" =&gt; $values_x,\n \"colors\" =&gt; \"\",\n );\n\n $series = array(\"label\" =&gt; $label_y, \"values\" =&gt; $series);\n\n }\n</code></pre>\n\n<p>You can force a specifice type with <code>(int)</code>, <code>(bool)</code>, <code>(string)</code> etc. \nAn example for string would be:</p>\n\n<pre><code>$AlwaysAnInt = (int)$CouldBeAnInt\n</code></pre>\n" }, { "answer_id": 261911, "author": "Clint Stegman", "author_id": 115494, "author_profile": "https://wordpress.stackexchange.com/users/115494", "pm_score": 2, "selected": false, "text": "<p>There are a few ways you can make an integer a string. Here are 2 main ways to make that happen</p>\n\n<ol>\n<li><p><strong>Type Cast</strong> - <code>$values_x[] = (string) $series[0]['data'][$i][0]</code></p></li>\n<li><p><strong>Double Quote</strong> - <code>$values_x[] \"{$series[0]['data'][$i][0]}\"</code></p></li>\n</ol>\n\n<p>Also, you might want to check for null first and assign a default</p>\n\n<pre><code>$values_x = !empty($values_x) ? $values_x : array('2010');\n</code></pre>\n\n<p>If you want to make the whole array a string, use <code>implode</code></p>\n\n<pre><code>\"values\" =&gt; implode(', ', $values_x)\n</code></pre>\n\n<p>If you have multiple integers, this will output '2010, 2011'. Replace the comma and space with what you want placed between the pieces.</p>\n\n<p><a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.implode.php</a></p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/447/" ]
I want to add a third column consisting of an input textfield using the Settings API. Is this possible? ``` function print_custom_field() { $value = get_option( 'my_first_field', '' ); $value_second = get_option( 'my_second_field', '' ); echo '<input type="text" id="my_first_field" name="my_first_field" value="' . $value . '" />'; echo '<input type="text" id="my_second_field" name="my_second_field" value="' . $value_second . '" />'; } add_filter('admin_init', 'register_fields'); ``` EDIT: I tried this code and Wordpress doesn't save the values of the second input field. Only the value of the first input field gets saved. How can I show another text input in the same row?
There are a few ways you can make an integer a string. Here are 2 main ways to make that happen 1. **Type Cast** - `$values_x[] = (string) $series[0]['data'][$i][0]` 2. **Double Quote** - `$values_x[] "{$series[0]['data'][$i][0]}"` Also, you might want to check for null first and assign a default ``` $values_x = !empty($values_x) ? $values_x : array('2010'); ``` If you want to make the whole array a string, use `implode` ``` "values" => implode(', ', $values_x) ``` If you have multiple integers, this will output '2010, 2011'. Replace the comma and space with what you want placed between the pieces. <http://php.net/manual/en/function.implode.php>
261,872
<p>Custom post type created with this arg</p> <pre><code>'labels' =&gt; $labels, 'hierarchical' =&gt; false, 'description' =&gt; 'Custom post type for question and answer', 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail' ), 'public' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; false, 'menu_position' =&gt; 24, 'menu_icon' =&gt; 'dashicons-editor-help', 'show_in_nav_menus' =&gt; false, 'publicly_queryable' =&gt; false, 'exclude_from_search' =&gt; true, 'has_archive' =&gt; false, 'query_var' =&gt; false, 'can_export' =&gt; true, 'rewrite' =&gt; false, 'capability_type' =&gt; 'post' </code></pre> <p>The loop inside the page template to show this custom post type contant PS/1: in the wordpress reading setting POSTS to show 100 in page PS/2: this permalink been used archive page for this custom post type</p> <pre><code>'post_type' =&gt; 'question', 'posts_per_page' =&gt; -1 </code></pre> <p>I have 24 posts.</p> <p>The problem is when visiting <code>%link/thispage/page/2/</code>, <code>%link/thispage/page/3/</code>, <code>%link/thispage/page/4/</code>, <code>%link/thispage/page/5/</code>, <code>%link/thispage/page/6/</code>, <code>%link/thispage/page/7/</code>, <code>%link/thispage/page/8/</code> even <code>%link/thispage/page/100/</code></p> <p>How i can avoid subpages for custom post type if there is no more posts to show and also how to avoid subpages for pages that include loop for custom post type that show all -1 posts </p>
[ { "answer_id": 261885, "author": "dipen patel", "author_id": 116371, "author_profile": "https://wordpress.stackexchange.com/users/116371", "pm_score": 1, "selected": false, "text": "<p>I think this issue is connected to has_archive set to false in your code. So you need to set ‘has_archive’ to true in register_post_type()\n'has_archive' => true,\nAnd then Please flush permalinks after you update that property.\nI believe it should help.\nAlso, you might need to create a custom template for archive of this CPT, check this section of the <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Type_Templates\" rel=\"nofollow noreferrer\">codex</a>.</p>\n" }, { "answer_id": 261977, "author": "Husam Alfas", "author_id": 116559, "author_profile": "https://wordpress.stackexchange.com/users/116559", "pm_score": 1, "selected": true, "text": "<p>will as i had answerd dipen under here this a wordpress Super mega SEO bug ... try any page created in wordpress and add link /page/3/ to /page/100000000/ it will have the same content which my own Competitors sent to index and really harm my serp resluts. </p>\n\n<p><a href=\"https://perishablepress.com/wordpress-infinite-duplicate-content/\" rel=\"nofollow noreferrer\">Wordpress Infinity loop</a>\nThanks for Jeff Starr - <a href=\"https://perishablepress.com\" rel=\"nofollow noreferrer\">https://perishablepress.com</a></p>\n\n<pre><code>global $posts, $numpages;\n\n$request_uri = $_SERVER['REQUEST_URI'];\n\n$result = preg_match('%\\/(\\d)+(\\/)?$%', $request_uri, $matches);\n\n$ordinal = $result ? intval($matches[1]) : FALSE;\n\nif(is_numeric($ordinal)) {\n\n // a numbered page was requested: validate it\n // look-ahead: initialises the global $numpages\n\n setup_postdata($posts[0]); // yes, hack\n\n $redirect_to = ($ordinal &lt; 2) ? '/': (($ordinal &gt; $numpages) ? \"/$numpages/\" : FALSE);\n\n if(is_string($redirect_to)) {\n\n // we got us a phantom\n $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);\n\n // if page = 0 or 1, redirect permanently\n if($ordinal &lt; 2) {\n header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');\n } else {\n header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');\n }\n\n header(\"Location: $redirect_url\");\n exit();\n\n }\n}\n</code></pre>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116559/" ]
Custom post type created with this arg ``` 'labels' => $labels, 'hierarchical' => false, 'description' => 'Custom post type for question and answer', 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), 'public' => false, 'show_ui' => true, 'show_in_menu' => false, 'menu_position' => 24, 'menu_icon' => 'dashicons-editor-help', 'show_in_nav_menus' => false, 'publicly_queryable' => false, 'exclude_from_search' => true, 'has_archive' => false, 'query_var' => false, 'can_export' => true, 'rewrite' => false, 'capability_type' => 'post' ``` The loop inside the page template to show this custom post type contant PS/1: in the wordpress reading setting POSTS to show 100 in page PS/2: this permalink been used archive page for this custom post type ``` 'post_type' => 'question', 'posts_per_page' => -1 ``` I have 24 posts. The problem is when visiting `%link/thispage/page/2/`, `%link/thispage/page/3/`, `%link/thispage/page/4/`, `%link/thispage/page/5/`, `%link/thispage/page/6/`, `%link/thispage/page/7/`, `%link/thispage/page/8/` even `%link/thispage/page/100/` How i can avoid subpages for custom post type if there is no more posts to show and also how to avoid subpages for pages that include loop for custom post type that show all -1 posts
will as i had answerd dipen under here this a wordpress Super mega SEO bug ... try any page created in wordpress and add link /page/3/ to /page/100000000/ it will have the same content which my own Competitors sent to index and really harm my serp resluts. [Wordpress Infinity loop](https://perishablepress.com/wordpress-infinite-duplicate-content/) Thanks for Jeff Starr - <https://perishablepress.com> ``` global $posts, $numpages; $request_uri = $_SERVER['REQUEST_URI']; $result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches); $ordinal = $result ? intval($matches[1]) : FALSE; if(is_numeric($ordinal)) { // a numbered page was requested: validate it // look-ahead: initialises the global $numpages setup_postdata($posts[0]); // yes, hack $redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE); if(is_string($redirect_to)) { // we got us a phantom $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri); // if page = 0 or 1, redirect permanently if($ordinal < 2) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); } else { header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found'); } header("Location: $redirect_url"); exit(); } } ```
261,889
<p>I have a simple "favorite post" button that works with AJAX. I understand that using a WordPress nonce improves security, but am not quite sure why or how it does this. This also makes me unable to check if I've implemented the nonce correctly and securely.</p> <p><strong>jQuery Script</strong></p> <pre><code>function favorites_javascript() { $ajax_nonce = wp_create_nonce( "ajax-nonce-favorites" ); ?&gt; &lt;script&gt; ( function( $ ) { var ajaxurl = "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;"; // ... // Data to be sent to function var data = { 'action': 'favorites_callback', 'security': '&lt;?php echo $ajax_nonce; ?&gt;', 'post_id': post_id, 'button_action' : button_action }; // Send Data jQuery.post(ajaxurl, data, function(response) { // ... }); // ... } )( jQuery ); &lt;/script&gt; &lt;?php } add_action( 'wp_footer', 'favorites_javascript' ); </code></pre> <p><strong>PHP Callback</strong></p> <pre><code>function favorites_callback() { check_ajax_referer( 'ajax-nonce-favorites', 'security' ); if ( !is_user_logged_in() ) { wp_send_json_error( 'Error!' ); } // Process Data wp_die(); } add_action( 'wp_ajax_favorites_callback', 'favorites_callback' ); </code></pre> <p>Is this the correct implementation of WordPress nonce for AJAX? And how do I "test" this code to see if the nonce works and is secure?</p>
[ { "answer_id": 261885, "author": "dipen patel", "author_id": 116371, "author_profile": "https://wordpress.stackexchange.com/users/116371", "pm_score": 1, "selected": false, "text": "<p>I think this issue is connected to has_archive set to false in your code. So you need to set ‘has_archive’ to true in register_post_type()\n'has_archive' => true,\nAnd then Please flush permalinks after you update that property.\nI believe it should help.\nAlso, you might need to create a custom template for archive of this CPT, check this section of the <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Type_Templates\" rel=\"nofollow noreferrer\">codex</a>.</p>\n" }, { "answer_id": 261977, "author": "Husam Alfas", "author_id": 116559, "author_profile": "https://wordpress.stackexchange.com/users/116559", "pm_score": 1, "selected": true, "text": "<p>will as i had answerd dipen under here this a wordpress Super mega SEO bug ... try any page created in wordpress and add link /page/3/ to /page/100000000/ it will have the same content which my own Competitors sent to index and really harm my serp resluts. </p>\n\n<p><a href=\"https://perishablepress.com/wordpress-infinite-duplicate-content/\" rel=\"nofollow noreferrer\">Wordpress Infinity loop</a>\nThanks for Jeff Starr - <a href=\"https://perishablepress.com\" rel=\"nofollow noreferrer\">https://perishablepress.com</a></p>\n\n<pre><code>global $posts, $numpages;\n\n$request_uri = $_SERVER['REQUEST_URI'];\n\n$result = preg_match('%\\/(\\d)+(\\/)?$%', $request_uri, $matches);\n\n$ordinal = $result ? intval($matches[1]) : FALSE;\n\nif(is_numeric($ordinal)) {\n\n // a numbered page was requested: validate it\n // look-ahead: initialises the global $numpages\n\n setup_postdata($posts[0]); // yes, hack\n\n $redirect_to = ($ordinal &lt; 2) ? '/': (($ordinal &gt; $numpages) ? \"/$numpages/\" : FALSE);\n\n if(is_string($redirect_to)) {\n\n // we got us a phantom\n $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);\n\n // if page = 0 or 1, redirect permanently\n if($ordinal &lt; 2) {\n header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');\n } else {\n header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');\n }\n\n header(\"Location: $redirect_url\");\n exit();\n\n }\n}\n</code></pre>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
I have a simple "favorite post" button that works with AJAX. I understand that using a WordPress nonce improves security, but am not quite sure why or how it does this. This also makes me unable to check if I've implemented the nonce correctly and securely. **jQuery Script** ``` function favorites_javascript() { $ajax_nonce = wp_create_nonce( "ajax-nonce-favorites" ); ?> <script> ( function( $ ) { var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; // ... // Data to be sent to function var data = { 'action': 'favorites_callback', 'security': '<?php echo $ajax_nonce; ?>', 'post_id': post_id, 'button_action' : button_action }; // Send Data jQuery.post(ajaxurl, data, function(response) { // ... }); // ... } )( jQuery ); </script> <?php } add_action( 'wp_footer', 'favorites_javascript' ); ``` **PHP Callback** ``` function favorites_callback() { check_ajax_referer( 'ajax-nonce-favorites', 'security' ); if ( !is_user_logged_in() ) { wp_send_json_error( 'Error!' ); } // Process Data wp_die(); } add_action( 'wp_ajax_favorites_callback', 'favorites_callback' ); ``` Is this the correct implementation of WordPress nonce for AJAX? And how do I "test" this code to see if the nonce works and is secure?
will as i had answerd dipen under here this a wordpress Super mega SEO bug ... try any page created in wordpress and add link /page/3/ to /page/100000000/ it will have the same content which my own Competitors sent to index and really harm my serp resluts. [Wordpress Infinity loop](https://perishablepress.com/wordpress-infinite-duplicate-content/) Thanks for Jeff Starr - <https://perishablepress.com> ``` global $posts, $numpages; $request_uri = $_SERVER['REQUEST_URI']; $result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches); $ordinal = $result ? intval($matches[1]) : FALSE; if(is_numeric($ordinal)) { // a numbered page was requested: validate it // look-ahead: initialises the global $numpages setup_postdata($posts[0]); // yes, hack $redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE); if(is_string($redirect_to)) { // we got us a phantom $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri); // if page = 0 or 1, redirect permanently if($ordinal < 2) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); } else { header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found'); } header("Location: $redirect_url"); exit(); } } ```
261,932
<p>I was trying to dig into this deeper, but I couldn't find any useful ways/hooks to add a little disclaimer above the Additional CSS code editor in the Wordpress Customizer. If anyone has a starting point of how i can add something simple like that, it would be greatly appreciated. </p> <p>The section I am talking about is <code>wp-admin &gt; Appearance &gt; Customize &gt; Additonal CSS</code></p> <p>We basically want to add a disclaimer to our clients about using that section, and I wanted to do it the Wordpress way, and not hack anything using jQuery (to add it) or in core.</p>
[ { "answer_id": 261939, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>You will need the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_section\" rel=\"nofollow noreferrer\"><code>get_section</code></a> method of the <code>$wp_customizer class</code>. Like this:</p>\n\n<pre><code>add_action( 'customize_register', 'wpse261932_change_css_title', 15 );\n\nfunction wpse261932_change_css_title () {\n global $wp_customize;\n $wp_customize-&gt;get_section('custom_css')-&gt;title = __('Additional CSS. Be careful!', 'textdomain');\n }\n</code></pre>\n\n<p>For some reason the description has <code>display:none</code> on it in this panel, even though that would be a more logical place to show your disclaimer.</p>\n" }, { "answer_id": 262063, "author": "Aaron Olin", "author_id": 38146, "author_profile": "https://wordpress.stackexchange.com/users/38146", "pm_score": 1, "selected": false, "text": "<p>Yep. I was able to show it by default using:</p>\n\n<pre><code>&lt;?php\nadd_action('customize_controls_print_styles', function() {\n?&gt;\n &lt;style id=\"custom-css\"&gt;\n #sub-accordion-section-custom_css .description {\n display: block !important;\n }\n &lt;/style&gt;\n&lt;?php\n});\n</code></pre>\n\n<p>Thanks for your help!</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38146/" ]
I was trying to dig into this deeper, but I couldn't find any useful ways/hooks to add a little disclaimer above the Additional CSS code editor in the Wordpress Customizer. If anyone has a starting point of how i can add something simple like that, it would be greatly appreciated. The section I am talking about is `wp-admin > Appearance > Customize > Additonal CSS` We basically want to add a disclaimer to our clients about using that section, and I wanted to do it the Wordpress way, and not hack anything using jQuery (to add it) or in core.
Yep. I was able to show it by default using: ``` <?php add_action('customize_controls_print_styles', function() { ?> <style id="custom-css"> #sub-accordion-section-custom_css .description { display: block !important; } </style> <?php }); ``` Thanks for your help!
261,935
<p>I am developing a simple ranking plugin. Every post has it's own like count, and these counts are saved as custom-fields. </p> <p>The problem is, no matter how much i research, i still couldn't find the proper way to manipulate theme's design in order to display post meta as i like. I've found some methods about changing theme's content.php file but it doesn't make sense because i want this plugin to work on every theme. Also in wordpress codex, it's told that i can do this by using template tags in the loop however index.php page which i can customize loop in, is not also included to my plugins directory.</p> <p>What should i do in order to display post's ranking meta properly for all themes ? </p>
[ { "answer_id": 261939, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>You will need the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_section\" rel=\"nofollow noreferrer\"><code>get_section</code></a> method of the <code>$wp_customizer class</code>. Like this:</p>\n\n<pre><code>add_action( 'customize_register', 'wpse261932_change_css_title', 15 );\n\nfunction wpse261932_change_css_title () {\n global $wp_customize;\n $wp_customize-&gt;get_section('custom_css')-&gt;title = __('Additional CSS. Be careful!', 'textdomain');\n }\n</code></pre>\n\n<p>For some reason the description has <code>display:none</code> on it in this panel, even though that would be a more logical place to show your disclaimer.</p>\n" }, { "answer_id": 262063, "author": "Aaron Olin", "author_id": 38146, "author_profile": "https://wordpress.stackexchange.com/users/38146", "pm_score": 1, "selected": false, "text": "<p>Yep. I was able to show it by default using:</p>\n\n<pre><code>&lt;?php\nadd_action('customize_controls_print_styles', function() {\n?&gt;\n &lt;style id=\"custom-css\"&gt;\n #sub-accordion-section-custom_css .description {\n display: block !important;\n }\n &lt;/style&gt;\n&lt;?php\n});\n</code></pre>\n\n<p>Thanks for your help!</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261935", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116595/" ]
I am developing a simple ranking plugin. Every post has it's own like count, and these counts are saved as custom-fields. The problem is, no matter how much i research, i still couldn't find the proper way to manipulate theme's design in order to display post meta as i like. I've found some methods about changing theme's content.php file but it doesn't make sense because i want this plugin to work on every theme. Also in wordpress codex, it's told that i can do this by using template tags in the loop however index.php page which i can customize loop in, is not also included to my plugins directory. What should i do in order to display post's ranking meta properly for all themes ?
Yep. I was able to show it by default using: ``` <?php add_action('customize_controls_print_styles', function() { ?> <style id="custom-css"> #sub-accordion-section-custom_css .description { display: block !important; } </style> <?php }); ``` Thanks for your help!
261,940
<p>I am trying to show 5 posts from a category in my home footer. I have placed this code</p> <pre><code>&lt;?php query_posts( 'category_name=entertainment&amp;posts_per_page=5' ); ?&gt; </code></pre> <p>right in my <code>home.php</code> file and everything works fine except more than 5 posts are showing. In fact it is showing all the posts from that category. I have also tried <code>showposts=5</code> but still it is not working.</p> <p>this is the full code in my <code>home.php</code></p> <pre><code> &lt;?php query_posts( 'category_name=entertainment&amp;posts_per_page=5' ); ?&gt; &lt;?php if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); } if (CFCT_DEBUG) { cfct_banner(__FILE__); } if (have_posts()) { echo '&lt;ul class="disclosure table group"&gt;'; while (have_posts()) { the_post(); ?&gt; &lt;li&gt; &lt;?php if(has_post_thumbnail()) { the_post_thumbnail();} cfct_excerpt(); ?&gt; &lt;/li&gt; &lt;?php } echo '&lt;li class="pagination"&gt;', cfct_misc('nav-list'),'&lt;/li&gt;'; echo '&lt;/ul&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 261941, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>First: <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">don't use <code>query_posts</code></a>. Second: use <a href=\"https://codex.wordpress.org/Function_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>$wp_query</code></a> instead:</p>\n\n<pre><code>$args = array (\n 'category_name' =&gt; 'entertainment',\n 'posts_per_page'=&gt; 5\n );\n$the_query = new WP_Query( $args );\n\nif ( $the_query-&gt;have_posts() ) {\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n /* Restore original Post Data */\n wp_reset_postdata();\n }\nelse {\n // no posts found\n }\n</code></pre>\n" }, { "answer_id": 261942, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>I would suggest you to use <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> function. With below code you'll get 5 post object-</p>\n\n<pre><code>$args = array (\n 'category_name' =&gt; 'entertainment',\n 'posts_per_page'=&gt; 5\n);\n\n$posts = get_posts($args);\n</code></pre>\n\n<p>Here at <code>$posts</code> variable you'll get the 5 posts. </p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261940", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115764/" ]
I am trying to show 5 posts from a category in my home footer. I have placed this code ``` <?php query_posts( 'category_name=entertainment&posts_per_page=5' ); ?> ``` right in my `home.php` file and everything works fine except more than 5 posts are showing. In fact it is showing all the posts from that category. I have also tried `showposts=5` but still it is not working. this is the full code in my `home.php` ``` <?php query_posts( 'category_name=entertainment&posts_per_page=5' ); ?> <?php if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); } if (CFCT_DEBUG) { cfct_banner(__FILE__); } if (have_posts()) { echo '<ul class="disclosure table group">'; while (have_posts()) { the_post(); ?> <li> <?php if(has_post_thumbnail()) { the_post_thumbnail();} cfct_excerpt(); ?> </li> <?php } echo '<li class="pagination">', cfct_misc('nav-list'),'</li>'; echo '</ul>'; } ?> ```
First: [don't use `query_posts`](https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts). Second: use [`$wp_query`](https://codex.wordpress.org/Function_Reference/WP_Query) instead: ``` $args = array ( 'category_name' => 'entertainment', 'posts_per_page'=> 5 ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found } ```
261,944
<p>I'm developing a theme which will grab and upload an image when a post is published, using the following function:</p> <pre><code>media_sideload_img( $url, $id, $description, 'src' ); </code></pre> <p>The problem is, I often update my posts and this ends up with dozens of copies of the same image, which was uploaded several times with every post update. </p> <p>Is there a way to check whether an attachment exists before uploading it to the server? </p> <p><strong>P.S:</strong> At the moment i'm using this function to get the ID of uploaded attachment:</p> <pre><code>function get_attachment_id_from_src ($image_src) { global $wpdb; $query = "SELECT ID FROM {$wpdb-&gt;posts} WHERE guid='$image_src'"; $id = $wpdb-&gt;get_var($query); return $id; } </code></pre> <p>Since i have access to the filename that I'm grabbing (from the URL) and they are all unique ( filenames are in hash ), i could check for it's existence in database but I'm not good enough with SQL queries. If this is an option too, any help is appreciated.</p> <p><strong>UPDATE</strong></p> <p>I'm using this query to see if the file exists or not. Is it safe to use this? will it always return the right value?</p> <pre><code>$wpdb-&gt;get_var("SELECT post_id FROM {$wpdb-&gt;postmeta} WHERE meta_value = '$img_name'"); </code></pre>
[ { "answer_id": 262125, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I wonder if you're looking for the core <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\"><code>attachment_url_to_postid()</code></a> function that uses:</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare(\n \"SELECT post_id FROM $wpdb-&gt;postmeta \n WHERE meta_key = '_wp_attached_file' AND meta_value = %s\",\n $path\n);\n$post_id = $wpdb-&gt;get_var( $sql );\n</code></pre>\n\n<p>Note the extra meta key <code>_wp_attached_file</code> check compared to your current snippet.</p>\n\n<p>If you need to check if an image url is an existing thumbnail, then you can check my recent answer <a href=\"https://wordpress.stackexchange.com/a/260635/26350\">here</a>.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Now I understand it better what you mean. The problem is that <code>_wp_attached_file</code> stores values like <code>2015/04/test.jpg</code>, if you use year/month uploads, so you could try to search for the <code>test.jpg</code> file with </p>\n\n<pre><code>... WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '%/test.jpg' \n</code></pre>\n\n<p>in your custom snippet (watch out for possible SQL injections in your code). </p>\n\n<p>Not sure what your setup is, but another approach might be to store successfully fetched and uploaded images in a more suitable way in the db that suits your needs.</p>\n" }, { "answer_id": 262130, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>I accepted @birgire's answer, however i solved it by approaching the problem this way:</p>\n\n<pre><code>function upload_image_as_attachment ($image_url, $post_id, $title) {\n $img_name = basename ($image_url);\n $local_url = wp_get_upload_dir()['path'].'/'.$img_name;\n if(file_exists($local_url)){\n $id = attachment_url_to_postid($local_url);\n return $id;\n } else {\n $attachment_src = media_sideload_image( $image_url, $post_id, $title,'src' );\n $id = attachment_url_to_postid($attachment_src);\n return $id;\n }\n}\n</code></pre>\n\n<p>This function takes an image URL and checks if the media is already uploaded. If not, uses <code>media_sideload_image()</code> to upload it and returns the ID of the uploaded attachment.</p>\n\n<p>I have to mention that i needed to disable year/month organization of uploaded medias to achieve this.</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261944", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
I'm developing a theme which will grab and upload an image when a post is published, using the following function: ``` media_sideload_img( $url, $id, $description, 'src' ); ``` The problem is, I often update my posts and this ends up with dozens of copies of the same image, which was uploaded several times with every post update. Is there a way to check whether an attachment exists before uploading it to the server? **P.S:** At the moment i'm using this function to get the ID of uploaded attachment: ``` function get_attachment_id_from_src ($image_src) { global $wpdb; $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'"; $id = $wpdb->get_var($query); return $id; } ``` Since i have access to the filename that I'm grabbing (from the URL) and they are all unique ( filenames are in hash ), i could check for it's existence in database but I'm not good enough with SQL queries. If this is an option too, any help is appreciated. **UPDATE** I'm using this query to see if the file exists or not. Is it safe to use this? will it always return the right value? ``` $wpdb->get_var("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value = '$img_name'"); ```
I wonder if you're looking for the core [`attachment_url_to_postid()`](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/) function that uses: ``` $sql = $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", $path ); $post_id = $wpdb->get_var( $sql ); ``` Note the extra meta key `_wp_attached_file` check compared to your current snippet. If you need to check if an image url is an existing thumbnail, then you can check my recent answer [here](https://wordpress.stackexchange.com/a/260635/26350). **Update:** Now I understand it better what you mean. The problem is that `_wp_attached_file` stores values like `2015/04/test.jpg`, if you use year/month uploads, so you could try to search for the `test.jpg` file with ``` ... WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '%/test.jpg' ``` in your custom snippet (watch out for possible SQL injections in your code). Not sure what your setup is, but another approach might be to store successfully fetched and uploaded images in a more suitable way in the db that suits your needs.
261,951
<p>I'm a beginner plugin developer. I need my plugin to save and edit multiple indexed sets of key/value pairs on my custom settings page and retrieve later them by their index on the Appearance>>Widgets page.</p> <p>Is it best to create a custom table in the database for this or does the Settings API have dimensional accommodation for this? If so can someone please get me pointed in the right direction?</p> <p>TIA</p>
[ { "answer_id": 262125, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I wonder if you're looking for the core <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\"><code>attachment_url_to_postid()</code></a> function that uses:</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare(\n \"SELECT post_id FROM $wpdb-&gt;postmeta \n WHERE meta_key = '_wp_attached_file' AND meta_value = %s\",\n $path\n);\n$post_id = $wpdb-&gt;get_var( $sql );\n</code></pre>\n\n<p>Note the extra meta key <code>_wp_attached_file</code> check compared to your current snippet.</p>\n\n<p>If you need to check if an image url is an existing thumbnail, then you can check my recent answer <a href=\"https://wordpress.stackexchange.com/a/260635/26350\">here</a>.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Now I understand it better what you mean. The problem is that <code>_wp_attached_file</code> stores values like <code>2015/04/test.jpg</code>, if you use year/month uploads, so you could try to search for the <code>test.jpg</code> file with </p>\n\n<pre><code>... WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '%/test.jpg' \n</code></pre>\n\n<p>in your custom snippet (watch out for possible SQL injections in your code). </p>\n\n<p>Not sure what your setup is, but another approach might be to store successfully fetched and uploaded images in a more suitable way in the db that suits your needs.</p>\n" }, { "answer_id": 262130, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>I accepted @birgire's answer, however i solved it by approaching the problem this way:</p>\n\n<pre><code>function upload_image_as_attachment ($image_url, $post_id, $title) {\n $img_name = basename ($image_url);\n $local_url = wp_get_upload_dir()['path'].'/'.$img_name;\n if(file_exists($local_url)){\n $id = attachment_url_to_postid($local_url);\n return $id;\n } else {\n $attachment_src = media_sideload_image( $image_url, $post_id, $title,'src' );\n $id = attachment_url_to_postid($attachment_src);\n return $id;\n }\n}\n</code></pre>\n\n<p>This function takes an image URL and checks if the media is already uploaded. If not, uses <code>media_sideload_image()</code> to upload it and returns the ID of the uploaded attachment.</p>\n\n<p>I have to mention that i needed to disable year/month organization of uploaded medias to achieve this.</p>\n" } ]
2017/03/30
[ "https://wordpress.stackexchange.com/questions/261951", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116579/" ]
I'm a beginner plugin developer. I need my plugin to save and edit multiple indexed sets of key/value pairs on my custom settings page and retrieve later them by their index on the Appearance>>Widgets page. Is it best to create a custom table in the database for this or does the Settings API have dimensional accommodation for this? If so can someone please get me pointed in the right direction? TIA
I wonder if you're looking for the core [`attachment_url_to_postid()`](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/) function that uses: ``` $sql = $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", $path ); $post_id = $wpdb->get_var( $sql ); ``` Note the extra meta key `_wp_attached_file` check compared to your current snippet. If you need to check if an image url is an existing thumbnail, then you can check my recent answer [here](https://wordpress.stackexchange.com/a/260635/26350). **Update:** Now I understand it better what you mean. The problem is that `_wp_attached_file` stores values like `2015/04/test.jpg`, if you use year/month uploads, so you could try to search for the `test.jpg` file with ``` ... WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '%/test.jpg' ``` in your custom snippet (watch out for possible SQL injections in your code). Not sure what your setup is, but another approach might be to store successfully fetched and uploaded images in a more suitable way in the db that suits your needs.
261,968
<p>Is there a possibility to disable the email field on WooCommerce customer account details? Or Is there a hook or action available to do such thing? I'm just using a pre-made themes and not that much into PHP. Have tried this plugin called "Prevent Email Change" by Happy Plugins, but it didn't worked. </p> <p>Would really appreciate any help from this.</p> <p>Thanks,</p>
[ { "answer_id": 262044, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 3, "selected": true, "text": "<p>You can do it by adding this code to <code>functions.php</code>:</p>\n\n<pre><code>function custom_override_checkout_fields( $fields ) {\n unset($fields['billing']['billing_email']); \n return $fields;\n}\nadd_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields', 1000, 1 );\n</code></pre>\n\n<p>But it is wrong approach, since WooCommerce uses email to notify user about status of the order.</p>\n" }, { "answer_id": 363408, "author": "Antoine Henrich", "author_id": 179899, "author_profile": "https://wordpress.stackexchange.com/users/179899", "pm_score": 1, "selected": false, "text": "<p>This is what I use. I was also troubleshooting with wrong emails on registered accounts. So I simply disabled the field and set it to <code>'required' =&gt; false</code> if the user is logged in.</p>\n\n<pre><code>if ( is_user_logged_in() ) {\n $fields['billing']['billing_email'] = [\n 'label' =&gt; 'E-Mail-Adresse',\n 'required' =&gt; false,\n 'custom_attributes' =&gt; [\n 'disabled' =&gt; 'disabled',\n ]\n ];\n} else {\n $fields['billing']['billing_email'] = [\n 'label' =&gt; 'E-Mail-Adresse',\n 'required' =&gt; true,\n\n ];\n}\n</code></pre>\n\n<p>Hope this helps someone out there!</p>\n" }, { "answer_id": 370934, "author": "Manuel Ruiz", "author_id": 191511, "author_profile": "https://wordpress.stackexchange.com/users/191511", "pm_score": 0, "selected": false, "text": "<p>I found in this file:\n<strong>wp-content\\plugins\\woocommerce\\includes\\class-wc-countries.php</strong>:</p>\n<p>public function <strong>get_address_fields</strong>( $country = '', $type = 'billing_' )</p>\n<p>Set required to false and the email would be optional.</p>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/261968", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104391/" ]
Is there a possibility to disable the email field on WooCommerce customer account details? Or Is there a hook or action available to do such thing? I'm just using a pre-made themes and not that much into PHP. Have tried this plugin called "Prevent Email Change" by Happy Plugins, but it didn't worked. Would really appreciate any help from this. Thanks,
You can do it by adding this code to `functions.php`: ``` function custom_override_checkout_fields( $fields ) { unset($fields['billing']['billing_email']); return $fields; } add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields', 1000, 1 ); ``` But it is wrong approach, since WooCommerce uses email to notify user about status of the order.
261,969
<p>I'm trying to rename and rearange the <strong>Widgets</strong> panel in WP Customizer area (apperance > customizer). So far I've only tried to rename the section, I would also like to move it to the bottom.</p> <p>I'm using this code:</p> <pre><code> $wp_customize-&gt;get_section('widgets')-&gt;title = __( 'Sidebar &amp; Footer widgets' ); </code></pre> <p>Here's the complete code:</p> <pre><code>function my_customize_register() { global $wp_customize; //Remove various sections $wp_customize-&gt;remove_section( 'fl-js-code-section' ); // JavaScript code box $wp_customize-&gt;remove_section( 'fl-head-code-section' ); // Head code box $wp_customize-&gt;remove_section( 'fl-header-code-section' ); // Header code box $wp_customize-&gt;remove_section( 'fl-footer-code-section' ); // Footer code box $wp_customize-&gt;remove_section( 'custom_css' ); // Additonal css box // Rename various sections $wp_customize-&gt;get_section('widgets')-&gt;title = __( 'Sidebar Footer widgets' ); } add_action( 'customize_register', 'my_customize_register', 11); </code></pre> <p>But when I save and reload customizer I keep getting the following warning</p> <blockquote> <p>Warning: Creating default object from empty value in /home/siteid4/public_html/_test4/wp-content/themes/bb-theme-child/functions.php on line 51</p> </blockquote> <p>Line 51 is the code renaming the widgets section.</p> <p>The weird thing is that there are various section NOT from wordpress, they are added by other plugins. Those I have no problem renaming, it's only the WP sections I am having trouble with.</p> <p>Any idea on how to rename and move this section?</p>
[ { "answer_id": 261984, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 2, "selected": false, "text": "<p>Rename and Re-arrange the Widgets panel in WP customizer area in \nappearance > customizer.</p>\n\n<p><a href=\"http://natko.com/changing-default-wordpress-theme-customization-api-sections/\" rel=\"nofollow noreferrer\">http://natko.com/changing-default-wordpress-theme-customization-api-sections/</a></p>\n\n<pre><code>function customize_register_init( $wp_customize ){\n $wp_customize-&gt;get_section('colors')-&gt;title = __( 'Theme Colors' );\n $wp_customize-&gt;get_section('colors')-&gt;priority = 500;\n}\nadd_action( 'customize_register', 'customize_register_init' );\n</code></pre>\n\n<p><strong>For this</strong> : <code>Warning: Creating default object from empty value in /home/siteid4/public_html/_test4/wp-content/themes/bb-theme-child/functions.php</code></p>\n\n<p>you can wrong section name enter in remove_section or get_section.</p>\n\n<p>I hope is useful.</p>\n" }, { "answer_id": 262006, "author": "Treb", "author_id": 101618, "author_profile": "https://wordpress.stackexchange.com/users/101618", "pm_score": 3, "selected": true, "text": "<p>Figured it out. Use \"get_panel\" not \"get_section\"</p>\n\n<pre><code> $wp_customize-&gt;get_panel('widgets')-&gt;title = __( 'Sidebar &amp; Footer widgets' );\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/261969", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101618/" ]
I'm trying to rename and rearange the **Widgets** panel in WP Customizer area (apperance > customizer). So far I've only tried to rename the section, I would also like to move it to the bottom. I'm using this code: ``` $wp_customize->get_section('widgets')->title = __( 'Sidebar & Footer widgets' ); ``` Here's the complete code: ``` function my_customize_register() { global $wp_customize; //Remove various sections $wp_customize->remove_section( 'fl-js-code-section' ); // JavaScript code box $wp_customize->remove_section( 'fl-head-code-section' ); // Head code box $wp_customize->remove_section( 'fl-header-code-section' ); // Header code box $wp_customize->remove_section( 'fl-footer-code-section' ); // Footer code box $wp_customize->remove_section( 'custom_css' ); // Additonal css box // Rename various sections $wp_customize->get_section('widgets')->title = __( 'Sidebar Footer widgets' ); } add_action( 'customize_register', 'my_customize_register', 11); ``` But when I save and reload customizer I keep getting the following warning > > Warning: Creating default object from empty value in /home/siteid4/public\_html/\_test4/wp-content/themes/bb-theme-child/functions.php on line 51 > > > Line 51 is the code renaming the widgets section. The weird thing is that there are various section NOT from wordpress, they are added by other plugins. Those I have no problem renaming, it's only the WP sections I am having trouble with. Any idea on how to rename and move this section?
Figured it out. Use "get\_panel" not "get\_section" ``` $wp_customize->get_panel('widgets')->title = __( 'Sidebar & Footer widgets' ); ```
261,972
<p>Here's my code in the functions.php file:</p> <pre><code>&lt;?php // Excerpt Length Control function set_excerpt_length(){ return 85; } // Theme stream_support function wpb_theme_setup(){ add_theme_support( 'post-thumbnails' ); } add_filter('excerpt_length', 'set_excerpt_length'); </code></pre> <p>Any idea what I am doing wrong here?</p> <p>Thanks!</p> <p>ALSO! I notice that the functions.php never has a closing ?> - how come?</p>
[ { "answer_id": 261984, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 2, "selected": false, "text": "<p>Rename and Re-arrange the Widgets panel in WP customizer area in \nappearance > customizer.</p>\n\n<p><a href=\"http://natko.com/changing-default-wordpress-theme-customization-api-sections/\" rel=\"nofollow noreferrer\">http://natko.com/changing-default-wordpress-theme-customization-api-sections/</a></p>\n\n<pre><code>function customize_register_init( $wp_customize ){\n $wp_customize-&gt;get_section('colors')-&gt;title = __( 'Theme Colors' );\n $wp_customize-&gt;get_section('colors')-&gt;priority = 500;\n}\nadd_action( 'customize_register', 'customize_register_init' );\n</code></pre>\n\n<p><strong>For this</strong> : <code>Warning: Creating default object from empty value in /home/siteid4/public_html/_test4/wp-content/themes/bb-theme-child/functions.php</code></p>\n\n<p>you can wrong section name enter in remove_section or get_section.</p>\n\n<p>I hope is useful.</p>\n" }, { "answer_id": 262006, "author": "Treb", "author_id": 101618, "author_profile": "https://wordpress.stackexchange.com/users/101618", "pm_score": 3, "selected": true, "text": "<p>Figured it out. Use \"get_panel\" not \"get_section\"</p>\n\n<pre><code> $wp_customize-&gt;get_panel('widgets')-&gt;title = __( 'Sidebar &amp; Footer widgets' );\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/261972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
Here's my code in the functions.php file: ``` <?php // Excerpt Length Control function set_excerpt_length(){ return 85; } // Theme stream_support function wpb_theme_setup(){ add_theme_support( 'post-thumbnails' ); } add_filter('excerpt_length', 'set_excerpt_length'); ``` Any idea what I am doing wrong here? Thanks! ALSO! I notice that the functions.php never has a closing ?> - how come?
Figured it out. Use "get\_panel" not "get\_section" ``` $wp_customize->get_panel('widgets')->title = __( 'Sidebar & Footer widgets' ); ```
261,986
<p>I'm new to developing a custom template in Wordpress but I fail to see how I can style a menu item seperately.</p> <p>With <code>posts</code> I can loop through them and place them in custom html elements. With <code>wp_page_menu()</code> I can only output the whole list. How can I loop through each item and place them in my custom template?</p> <p><strong>Html Template:</strong></p> <pre><code>&lt;ul class="nav navbar-nav navbar-right is-hidden"&gt; &lt;li&gt; &lt;a class="page-link" href=""&gt; ... &lt;/a&gt; &lt;/li&gt; ... ... &lt;/ul&gt; </code></pre>
[ { "answer_id": 261995, "author": "Philipp Zedler", "author_id": 44375, "author_profile": "https://wordpress.stackexchange.com/users/44375", "pm_score": 1, "selected": false, "text": "<p>Following the code of the <code>wp_page_menu</code> directs me to the function <a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\"><code>get_pages</code></a>. This is probably what you are looking for.</p>\n\n<p>Looking at the function calls in <a href=\"https://developer.wordpress.org/reference/functions/wp_page_menu/\" rel=\"nofollow noreferrer\"><code>wp_page_menu</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\"><code>wp_list_pages</code></a>, you'll get an idea about what arguments you should pass to the <code>get_pages</code> function.</p>\n" }, { "answer_id": 261998, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 3, "selected": true, "text": "<p>Please find below the function for showing navigation menu. \nHere, <code>$menu</code> is equivalent to <strong><em>Menu name, ID, or slug</em></strong></p>\n\n<pre><code>&lt;?php \nfunction showMyMenu($menu)\n{\n $navData = wp_get_nav_menu_items($menu); \n?&gt;\n&lt;ul class=\"nav navbar-nav navbar-right is-hidden\"&gt;\n &lt;?php\n foreach($navData as $k =&gt; $v)\n { \n echo '&lt;li&gt;&lt;a class=\"page-link\" href=\"' . $v-&gt;url . '\"&gt; ' . $v-&gt;title . ' &lt;/a&gt;&lt;/li&gt;';\n }\n ?&gt;\n&lt;/ul&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/261986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116634/" ]
I'm new to developing a custom template in Wordpress but I fail to see how I can style a menu item seperately. With `posts` I can loop through them and place them in custom html elements. With `wp_page_menu()` I can only output the whole list. How can I loop through each item and place them in my custom template? **Html Template:** ``` <ul class="nav navbar-nav navbar-right is-hidden"> <li> <a class="page-link" href=""> ... </a> </li> ... ... </ul> ```
Please find below the function for showing navigation menu. Here, `$menu` is equivalent to ***Menu name, ID, or slug*** ``` <?php function showMyMenu($menu) { $navData = wp_get_nav_menu_items($menu); ?> <ul class="nav navbar-nav navbar-right is-hidden"> <?php foreach($navData as $k => $v) { echo '<li><a class="page-link" href="' . $v->url . '"> ' . $v->title . ' </a></li>'; } ?> </ul> <?php } ?> ```
261,996
<p>Have a CPT with custom field "size" valued "big" or "small" and Author with custom radio field "gender". Author can be "Man" or "Woman". Need query posts if, for example, author is "man" and filed "size" is "big". Try something like this:</p> <pre><code>$args = array( 'post_type' =&gt; 'custom_post_type', 'meta_query' =&gt; array( array( 'key' =&gt; 'size', 'value' =&gt; 'big', 'compare' =&gt; 'LIKE', ) ) ); $query = new WP_Query( $args ); </code></pre> <p>This show posts with key value "big" from all authors, but how add author with key "gender" valued "man" to this query?</p>
[ { "answer_id": 262381, "author": "BillyHoyle", "author_id": 116633, "author_profile": "https://wordpress.stackexchange.com/users/116633", "pm_score": 2, "selected": true, "text": "<p>In case this helps anyone in the future:</p>\n\n<p>The problem was not a WordPress issue, it was a server configuration issue.</p>\n\n<p>Useful explanation on checking which stream wrappers are enabled on your server (used this to make sure https was enabled on my server) <a href=\"https://stackoverflow.com/questions/2305954/how-to-enable-https-stream-wrappers\">Enable Stream Wrappers</a></p>\n\n<p>Someone with the same issue found that their certificate failed to verify:\n<a href=\"https://stackoverflow.com/questions/32621929/error-when-loading-external-xml-file-with-php-via-https-ssl3-get-server-certif\">Certificate Verification Fails</a></p>\n\n<p>The issue was fixed by our hosting provider, with the following explanation:</p>\n\n<blockquote>\n <p>The problem is caused by the the self signed certificate on the\n server. We could either allow the self signed certificate in the php\n setup or load a valid SSL certificate.</p>\n \n <p>The issue was fixed by creating a self signed certificate which\n matches the Openssl common name. This fixed all libxml errors</p>\n</blockquote>\n" }, { "answer_id": 262386, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 0, "selected": false, "text": "<p>You've loaded the <code>xml</code> file using an URL of your own web server. While your solution fixes the problem, it wasn't necessary to load the <code>xml</code> using URL (HTTP or HTTPS) in the first place. Since it's on the same server, you could've loaded the <code>xml</code> file using file PATH instead.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> <code>get_template_directory_uri()</code> function returns URL, whereas, <code>get_template_directory()</code> function returns local file PATH.</p>\n</blockquote>\n\n<p>So instead of:</p>\n\n<pre><code>simplexml_load_file( get_template_directory_uri() . '/myxml.xml' );\n</code></pre>\n\n<p>CODE, you can use:</p>\n\n<pre><code>simplexml_load_file( get_template_directory() . '/myxml.xml' );\n</code></pre>\n\n<p>This way, there will be no local URL issue at all &amp; it's much faster.</p>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/261996", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64530/" ]
Have a CPT with custom field "size" valued "big" or "small" and Author with custom radio field "gender". Author can be "Man" or "Woman". Need query posts if, for example, author is "man" and filed "size" is "big". Try something like this: ``` $args = array( 'post_type' => 'custom_post_type', 'meta_query' => array( array( 'key' => 'size', 'value' => 'big', 'compare' => 'LIKE', ) ) ); $query = new WP_Query( $args ); ``` This show posts with key value "big" from all authors, but how add author with key "gender" valued "man" to this query?
In case this helps anyone in the future: The problem was not a WordPress issue, it was a server configuration issue. Useful explanation on checking which stream wrappers are enabled on your server (used this to make sure https was enabled on my server) [Enable Stream Wrappers](https://stackoverflow.com/questions/2305954/how-to-enable-https-stream-wrappers) Someone with the same issue found that their certificate failed to verify: [Certificate Verification Fails](https://stackoverflow.com/questions/32621929/error-when-loading-external-xml-file-with-php-via-https-ssl3-get-server-certif) The issue was fixed by our hosting provider, with the following explanation: > > The problem is caused by the the self signed certificate on the > server. We could either allow the self signed certificate in the php > setup or load a valid SSL certificate. > > > The issue was fixed by creating a self signed certificate which > matches the Openssl common name. This fixed all libxml errors > > >
262,005
<p>I already have found <a href="https://wordpress.stackexchange.com/a/59957/25187">a working solution</a> for my question, but <strong>the problem is that it neutralizes</strong> <a href="https://wordpress.stackexchange.com/a/94820/25187">another function</a> that adds the category base into the custom post type permalinks, and I need boths, so <strong>I must to merge them somehow</strong>. How to do that?</p> <p>This is the code that adds the .html extention to the custom post types:</p> <pre><code>//Create the rewrite rules like post-type/post-name.html add_action( 'rewrite_rules_array', 'rewrite_rules' ); function rewrite_rules( $rules ) { $new_rules = array(); foreach ( get_post_types() as $t ) $new_rules[ $t . '/([^/]+)\.html$' ] = 'index.php?post_type=' . $t . '&amp;name=$matches[1]'; return $new_rules + $rules; } //Format the new permalink structure for these post types. add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link) function custom_post_permalink ( $post_link ) { global $post; $type = get_post_type( $post-&gt;ID ); return home_url( $type . '/' . $post-&gt;post_name . '.html' ); } //And then stop redirecting the canonical URLs to remove the trailing slash. add_filter( 'redirect_canonical', '__return_false' ); </code></pre> <p>And this is the code that adds the category base to a <em>cources</em> custom post type (see <a href="https://wordpress.stackexchange.com/a/108647/25187">a similar solution</a>, and <a href="https://stackoverflow.com/a/23702560/1354580">another</a>):</p> <pre><code>//Change your rewrite to add the course query var: 'rewrite' =&gt; array('slug' =&gt; 'courses/%course%') //Then filter post_type_link to insert the selected course into the permalink: function wpa_course_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post-&gt;ID, 'course' ); if( $terms ){ return str_replace( '%course%' , $terms[0]-&gt;slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 ); </code></pre>
[ { "answer_id": 262023, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Lets take these functions and paraphrase them into english, then put them in the order they're ran. I'm going to deliberately avoid using PHP in this answer, but a basic understanding of PHP will be necessary:</p>\n\n<pre><code>When the `post_type_link` filter runs: // the add_action calls\n run: `wpa_course_post_link` as it has priority 3 // function wpa_course_post_link(....\n if the object is a post\n and that post has a course term\n search for %course% in the URL string and replace it\n Then, run `custom_post_permalink` as it has priority 10: // function custom_post_permalink(...\n Ignore the URL we got given and construct a brand new one by returning the post_type + \"/\" + posts name + \".html\"\n</code></pre>\n\n<p>So <code>custom_post_permalink</code> doesn't add <code>.html</code> to the end of your URLs as you thought it did, it creates a whole new URL. If you changed the priority from 3 to 11, your .html URLs will work, but your course URLs will not as <code>%course%</code> was replaced.</p>\n\n<p>Luckily the <code>wpa_course_post_link</code> function provides a much better template for how to do this. Insted of grabbing the course terms and doing a string replace, just add .html to the end of the <code>$post_link</code> string and return it</p>\n\n<p>So instead if we write it out as pseudocode in plain english, we might get this:</p>\n\n<pre><code>When the `post_type_link` filter runs:\n run: `wpa_course_post_link` as it has priority 3\n if the object is a post, then:\n if that post has a course term then:\n search for %course% in the URL string and replace it\n then add \".html\" to the end\n</code></pre>\n\n<p>I leave conversion to PHP as a task for the reader, all the needed PHP is already available in the question.</p>\n" }, { "answer_id": 262185, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 2, "selected": false, "text": "<p>With the help of <a href=\"https://wordpress.stackexchange.com/a/262023/25187\">@tom-j-nowell</a> I have a working solution. I suppose it is not yet perfect, but it works.</p>\n\n<pre><code>//When your create a custom post type change your rewrite to:\n'rewrite' =&gt; array('slug' =&gt; 'courses/%course_category%')\n\n//Then filter post_type_link to insert the category of selected course into the permalink:\nfunction wpa_course_post_link( $post_link, $id = 0 ){\n $post = get_post($id);\n if ( is_object( $post ) ){\n $terms = wp_get_object_terms( $post-&gt;ID, 'course_category' );\n if( $terms ){\n $post_link = str_replace( '%course_category%' , $terms[0]-&gt;slug , $post_link );\n //and add the .html extension to the returned post link:\n return $post_link . '.html';\n }\n }\n return $post_link; \n}\nadd_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 );\n\n//Then create the rewrite rules for the post-type/post-category/post-name.html permalink structure:\nadd_action( 'rewrite_rules_array', 'rewrite_rules' );\nfunction rewrite_rules( $rules ) {\n $new_rules = array();\n $new_rules[ 'courses/([^/]+)/(.+)\\.html$' ] = 'index.php?courses=$matches[2]';\n return $new_rules + $rules;\n}\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/262005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I already have found [a working solution](https://wordpress.stackexchange.com/a/59957/25187) for my question, but **the problem is that it neutralizes** [another function](https://wordpress.stackexchange.com/a/94820/25187) that adds the category base into the custom post type permalinks, and I need boths, so **I must to merge them somehow**. How to do that? This is the code that adds the .html extention to the custom post types: ``` //Create the rewrite rules like post-type/post-name.html add_action( 'rewrite_rules_array', 'rewrite_rules' ); function rewrite_rules( $rules ) { $new_rules = array(); foreach ( get_post_types() as $t ) $new_rules[ $t . '/([^/]+)\.html$' ] = 'index.php?post_type=' . $t . '&name=$matches[1]'; return $new_rules + $rules; } //Format the new permalink structure for these post types. add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link) function custom_post_permalink ( $post_link ) { global $post; $type = get_post_type( $post->ID ); return home_url( $type . '/' . $post->post_name . '.html' ); } //And then stop redirecting the canonical URLs to remove the trailing slash. add_filter( 'redirect_canonical', '__return_false' ); ``` And this is the code that adds the category base to a *cources* custom post type (see [a similar solution](https://wordpress.stackexchange.com/a/108647/25187), and [another](https://stackoverflow.com/a/23702560/1354580)): ``` //Change your rewrite to add the course query var: 'rewrite' => array('slug' => 'courses/%course%') //Then filter post_type_link to insert the selected course into the permalink: function wpa_course_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'course' ); if( $terms ){ return str_replace( '%course%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 ); ```
Lets take these functions and paraphrase them into english, then put them in the order they're ran. I'm going to deliberately avoid using PHP in this answer, but a basic understanding of PHP will be necessary: ``` When the `post_type_link` filter runs: // the add_action calls run: `wpa_course_post_link` as it has priority 3 // function wpa_course_post_link(.... if the object is a post and that post has a course term search for %course% in the URL string and replace it Then, run `custom_post_permalink` as it has priority 10: // function custom_post_permalink(... Ignore the URL we got given and construct a brand new one by returning the post_type + "/" + posts name + ".html" ``` So `custom_post_permalink` doesn't add `.html` to the end of your URLs as you thought it did, it creates a whole new URL. If you changed the priority from 3 to 11, your .html URLs will work, but your course URLs will not as `%course%` was replaced. Luckily the `wpa_course_post_link` function provides a much better template for how to do this. Insted of grabbing the course terms and doing a string replace, just add .html to the end of the `$post_link` string and return it So instead if we write it out as pseudocode in plain english, we might get this: ``` When the `post_type_link` filter runs: run: `wpa_course_post_link` as it has priority 3 if the object is a post, then: if that post has a course term then: search for %course% in the URL string and replace it then add ".html" to the end ``` I leave conversion to PHP as a task for the reader, all the needed PHP is already available in the question.
262,026
<p>I have a Wordpress menu that are both being used as a normal menu with page name that links to the page. I want to echo the same registered menu, but without the page name. To be clear, I still want the anchorlink, but I do not want any text contained within the anchorlink.</p> <pre><code>&lt;li&gt;&lt;a href="the-page-link"&gt;&lt;/a&gt;&lt;/li&gt; </code></pre> <p>The reason I want this is because I style the anchorlinks as small circles. </p> <p>Is this possible? I tried to clear the content in css, but that does not affect the anchorlink when the page name is echoed in the HTML.</p>
[ { "answer_id": 262023, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Lets take these functions and paraphrase them into english, then put them in the order they're ran. I'm going to deliberately avoid using PHP in this answer, but a basic understanding of PHP will be necessary:</p>\n\n<pre><code>When the `post_type_link` filter runs: // the add_action calls\n run: `wpa_course_post_link` as it has priority 3 // function wpa_course_post_link(....\n if the object is a post\n and that post has a course term\n search for %course% in the URL string and replace it\n Then, run `custom_post_permalink` as it has priority 10: // function custom_post_permalink(...\n Ignore the URL we got given and construct a brand new one by returning the post_type + \"/\" + posts name + \".html\"\n</code></pre>\n\n<p>So <code>custom_post_permalink</code> doesn't add <code>.html</code> to the end of your URLs as you thought it did, it creates a whole new URL. If you changed the priority from 3 to 11, your .html URLs will work, but your course URLs will not as <code>%course%</code> was replaced.</p>\n\n<p>Luckily the <code>wpa_course_post_link</code> function provides a much better template for how to do this. Insted of grabbing the course terms and doing a string replace, just add .html to the end of the <code>$post_link</code> string and return it</p>\n\n<p>So instead if we write it out as pseudocode in plain english, we might get this:</p>\n\n<pre><code>When the `post_type_link` filter runs:\n run: `wpa_course_post_link` as it has priority 3\n if the object is a post, then:\n if that post has a course term then:\n search for %course% in the URL string and replace it\n then add \".html\" to the end\n</code></pre>\n\n<p>I leave conversion to PHP as a task for the reader, all the needed PHP is already available in the question.</p>\n" }, { "answer_id": 262185, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 2, "selected": false, "text": "<p>With the help of <a href=\"https://wordpress.stackexchange.com/a/262023/25187\">@tom-j-nowell</a> I have a working solution. I suppose it is not yet perfect, but it works.</p>\n\n<pre><code>//When your create a custom post type change your rewrite to:\n'rewrite' =&gt; array('slug' =&gt; 'courses/%course_category%')\n\n//Then filter post_type_link to insert the category of selected course into the permalink:\nfunction wpa_course_post_link( $post_link, $id = 0 ){\n $post = get_post($id);\n if ( is_object( $post ) ){\n $terms = wp_get_object_terms( $post-&gt;ID, 'course_category' );\n if( $terms ){\n $post_link = str_replace( '%course_category%' , $terms[0]-&gt;slug , $post_link );\n //and add the .html extension to the returned post link:\n return $post_link . '.html';\n }\n }\n return $post_link; \n}\nadd_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 );\n\n//Then create the rewrite rules for the post-type/post-category/post-name.html permalink structure:\nadd_action( 'rewrite_rules_array', 'rewrite_rules' );\nfunction rewrite_rules( $rules ) {\n $new_rules = array();\n $new_rules[ 'courses/([^/]+)/(.+)\\.html$' ] = 'index.php?courses=$matches[2]';\n return $new_rules + $rules;\n}\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/262026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92908/" ]
I have a Wordpress menu that are both being used as a normal menu with page name that links to the page. I want to echo the same registered menu, but without the page name. To be clear, I still want the anchorlink, but I do not want any text contained within the anchorlink. ``` <li><a href="the-page-link"></a></li> ``` The reason I want this is because I style the anchorlinks as small circles. Is this possible? I tried to clear the content in css, but that does not affect the anchorlink when the page name is echoed in the HTML.
Lets take these functions and paraphrase them into english, then put them in the order they're ran. I'm going to deliberately avoid using PHP in this answer, but a basic understanding of PHP will be necessary: ``` When the `post_type_link` filter runs: // the add_action calls run: `wpa_course_post_link` as it has priority 3 // function wpa_course_post_link(.... if the object is a post and that post has a course term search for %course% in the URL string and replace it Then, run `custom_post_permalink` as it has priority 10: // function custom_post_permalink(... Ignore the URL we got given and construct a brand new one by returning the post_type + "/" + posts name + ".html" ``` So `custom_post_permalink` doesn't add `.html` to the end of your URLs as you thought it did, it creates a whole new URL. If you changed the priority from 3 to 11, your .html URLs will work, but your course URLs will not as `%course%` was replaced. Luckily the `wpa_course_post_link` function provides a much better template for how to do this. Insted of grabbing the course terms and doing a string replace, just add .html to the end of the `$post_link` string and return it So instead if we write it out as pseudocode in plain english, we might get this: ``` When the `post_type_link` filter runs: run: `wpa_course_post_link` as it has priority 3 if the object is a post, then: if that post has a course term then: search for %course% in the URL string and replace it then add ".html" to the end ``` I leave conversion to PHP as a task for the reader, all the needed PHP is already available in the question.
262,042
<p>I have a plugin, which creates a panel on following page:</p> <pre><code>mysite.com/wp-content/plugins/myplugin/includes/mypanel.php </code></pre> <p>I want to use this panel on following page </p> <pre><code>mysite.com/mypanel </code></pre> <p>Solution that I tried was to using <code>mypanel.php</code> as page template as below:</p> <pre><code>add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'mypanel' ) ) { $page_template = dirname( __FILE__ ) . '/includes/mypanel.php'; } return $page_template; } </code></pre> <p>This way the page displays but none of the javascript works. So I have tried to import plugin's javascript in functions php. </p> <pre><code>add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855'); function Load_Template_Scripts_wpa83855(){ if ( strpos(get_page_template(), 'mypanel.php') !== false ) { wp_enqueue_script('wtd', $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/myplugin/js/wtd.js'); } } </code></pre> <p>Which resulted 403 forbidden error. I added tried adding an .htaccess folder into plugin's page but it continued to give error. </p> <p>Please tell me what is the correct way to solve this problem. </p> <p><strong>EDIT:</strong> After some answers below (thanks everyone). I moved my codes to my plugin's page, and no more 403 forbidden error. But my buttons are not working, and I feel like my js file not run over the page.</p> <p>My js file starts with: <code>jQuery(document).ready(function()</code></p> <p>Here final code on plugin's page: </p> <pre><code>/* Make tisort-tasarla page as template */ add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'tisort-tasarla' ) ) { $page_template = dirname( __FILE__ ) . '/includes/tshirt-designer-design-template.php'; } return $page_template; } /* Add Javascript to T-Shirt Design Page */ add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855'); function Load_Template_Scripts_wpa83855(){ if ( is_page( 'tisort-tasarla' ) ) { wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ), array( 'jquery' )); } } </code></pre>
[ { "answer_id": 262190, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>If you already have, or are planning to have, a page called 'mypanel', then you can use the <code>page_template</code> filter to filter the template used on that page. I'm assuming that's what you're doing.</p>\n\n<p>We can use the <code>page_template</code> filter to use a custom template for this page. While using this filter, we can add an action to enqueue scripts specific for this page.</p>\n\n<pre><code>add_filter( 'page_template', 'wpse_262042_page_template', 10, 1 );\nfunction wpse_262042_page_template( $page_template ) {\n if( is_page( 'mypanel' ) ) {\n add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' );\n $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php';\n }\n return $page_template;\n}\nfunction wpse_262042_enqueue_scripts() {\n wp_enqueue_script( 'wpse-262042', plugins_url( '/js/wpse-262042.js', __FILE__ ) );\n}\n</code></pre>\n\n<p>In the <code>/includes/mypanel.php</code> template file, make sure to call <code>wp_head()</code> and <code>wp_footer()</code> otherwise the enqueued scripts won't be printed.</p>\n" }, { "answer_id": 262191, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>Your CODE is fine, the reason you are getting 403 error is because <code>$_SERVER['DOCUMENT_ROOT']</code> returns absolute PATH to your web root, not URL.</p>\n<p>JavaScript needs to be added as URL. So, you may use <code>Load_Template_Scripts_wpa83855</code> function in your plugin and then use:</p>\n<pre><code>wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ) );\n</code></pre>\n<p>CODE to add JavaScript.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> obviously you can make the CODE even better using logic like what <a href=\"https://wordpress.stackexchange.com/a/262190/110572\">@nathan used in his answer</a>, i.e. adding:</p>\n<p><code>add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');</code></p>\n<p>within the <code>wpa3396_page_template()</code> function in <code>if ( is_page( 'mypanel' ) ) {}</code> condition block; but that's not the reason of the error. Server PATH cannot be accessed by browser, that's why the server returns <code>Access Forbidden</code> error.</p>\n</blockquote>\n<h2>Full CODE (Updated):</h2>\n<p>Here is the full CODE for your convenience (add it in your main plugin file):</p>\n<pre><code>add_filter( 'page_template', 'wpse_262042_page_template' );\nfunction wpse_262042_page_template( $page_template ) {\n if( is_page( 'mypanel' ) ) {\n add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' );\n $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php';\n }\n return $page_template;\n}\n\nfunction wpse_262042_enqueue_scripts() {\n wp_enqueue_script( 'wtd', plugins_url( 'js/wtd.js' , __FILE__ ), array( 'jquery' ) );\n}\n</code></pre>\n" } ]
2017/03/31
[ "https://wordpress.stackexchange.com/questions/262042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112778/" ]
I have a plugin, which creates a panel on following page: ``` mysite.com/wp-content/plugins/myplugin/includes/mypanel.php ``` I want to use this panel on following page ``` mysite.com/mypanel ``` Solution that I tried was to using `mypanel.php` as page template as below: ``` add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'mypanel' ) ) { $page_template = dirname( __FILE__ ) . '/includes/mypanel.php'; } return $page_template; } ``` This way the page displays but none of the javascript works. So I have tried to import plugin's javascript in functions php. ``` add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855'); function Load_Template_Scripts_wpa83855(){ if ( strpos(get_page_template(), 'mypanel.php') !== false ) { wp_enqueue_script('wtd', $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/myplugin/js/wtd.js'); } } ``` Which resulted 403 forbidden error. I added tried adding an .htaccess folder into plugin's page but it continued to give error. Please tell me what is the correct way to solve this problem. **EDIT:** After some answers below (thanks everyone). I moved my codes to my plugin's page, and no more 403 forbidden error. But my buttons are not working, and I feel like my js file not run over the page. My js file starts with: `jQuery(document).ready(function()` Here final code on plugin's page: ``` /* Make tisort-tasarla page as template */ add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'tisort-tasarla' ) ) { $page_template = dirname( __FILE__ ) . '/includes/tshirt-designer-design-template.php'; } return $page_template; } /* Add Javascript to T-Shirt Design Page */ add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855'); function Load_Template_Scripts_wpa83855(){ if ( is_page( 'tisort-tasarla' ) ) { wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ), array( 'jquery' )); } } ```
Your CODE is fine, the reason you are getting 403 error is because `$_SERVER['DOCUMENT_ROOT']` returns absolute PATH to your web root, not URL. JavaScript needs to be added as URL. So, you may use `Load_Template_Scripts_wpa83855` function in your plugin and then use: ``` wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ) ); ``` CODE to add JavaScript. > > ***Note:*** obviously you can make the CODE even better using logic like what [@nathan used in his answer](https://wordpress.stackexchange.com/a/262190/110572), i.e. adding: > > > `add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');` > > > within the `wpa3396_page_template()` function in `if ( is_page( 'mypanel' ) ) {}` condition block; but that's not the reason of the error. Server PATH cannot be accessed by browser, that's why the server returns `Access Forbidden` error. > > > Full CODE (Updated): -------------------- Here is the full CODE for your convenience (add it in your main plugin file): ``` add_filter( 'page_template', 'wpse_262042_page_template' ); function wpse_262042_page_template( $page_template ) { if( is_page( 'mypanel' ) ) { add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' ); $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php'; } return $page_template; } function wpse_262042_enqueue_scripts() { wp_enqueue_script( 'wtd', plugins_url( 'js/wtd.js' , __FILE__ ), array( 'jquery' ) ); } ```
262,079
<p>Users to the site can register and log in and access a special page <code>members.php</code>, which is the home page of their account.</p> <p>But if they leave the site and come back (provided they are still logged in) they need to be landing on <code>members.php</code> and not my regular home page.</p> <p>Now everyone, logged in as well as logged out, folks land on the <code>index.php</code> page of my site.</p> <p>How to make the above possible?</p>
[ { "answer_id": 262190, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>If you already have, or are planning to have, a page called 'mypanel', then you can use the <code>page_template</code> filter to filter the template used on that page. I'm assuming that's what you're doing.</p>\n\n<p>We can use the <code>page_template</code> filter to use a custom template for this page. While using this filter, we can add an action to enqueue scripts specific for this page.</p>\n\n<pre><code>add_filter( 'page_template', 'wpse_262042_page_template', 10, 1 );\nfunction wpse_262042_page_template( $page_template ) {\n if( is_page( 'mypanel' ) ) {\n add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' );\n $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php';\n }\n return $page_template;\n}\nfunction wpse_262042_enqueue_scripts() {\n wp_enqueue_script( 'wpse-262042', plugins_url( '/js/wpse-262042.js', __FILE__ ) );\n}\n</code></pre>\n\n<p>In the <code>/includes/mypanel.php</code> template file, make sure to call <code>wp_head()</code> and <code>wp_footer()</code> otherwise the enqueued scripts won't be printed.</p>\n" }, { "answer_id": 262191, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>Your CODE is fine, the reason you are getting 403 error is because <code>$_SERVER['DOCUMENT_ROOT']</code> returns absolute PATH to your web root, not URL.</p>\n<p>JavaScript needs to be added as URL. So, you may use <code>Load_Template_Scripts_wpa83855</code> function in your plugin and then use:</p>\n<pre><code>wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ) );\n</code></pre>\n<p>CODE to add JavaScript.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> obviously you can make the CODE even better using logic like what <a href=\"https://wordpress.stackexchange.com/a/262190/110572\">@nathan used in his answer</a>, i.e. adding:</p>\n<p><code>add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');</code></p>\n<p>within the <code>wpa3396_page_template()</code> function in <code>if ( is_page( 'mypanel' ) ) {}</code> condition block; but that's not the reason of the error. Server PATH cannot be accessed by browser, that's why the server returns <code>Access Forbidden</code> error.</p>\n</blockquote>\n<h2>Full CODE (Updated):</h2>\n<p>Here is the full CODE for your convenience (add it in your main plugin file):</p>\n<pre><code>add_filter( 'page_template', 'wpse_262042_page_template' );\nfunction wpse_262042_page_template( $page_template ) {\n if( is_page( 'mypanel' ) ) {\n add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' );\n $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php';\n }\n return $page_template;\n}\n\nfunction wpse_262042_enqueue_scripts() {\n wp_enqueue_script( 'wtd', plugins_url( 'js/wtd.js' , __FILE__ ), array( 'jquery' ) );\n}\n</code></pre>\n" } ]
2017/04/01
[ "https://wordpress.stackexchange.com/questions/262079", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78121/" ]
Users to the site can register and log in and access a special page `members.php`, which is the home page of their account. But if they leave the site and come back (provided they are still logged in) they need to be landing on `members.php` and not my regular home page. Now everyone, logged in as well as logged out, folks land on the `index.php` page of my site. How to make the above possible?
Your CODE is fine, the reason you are getting 403 error is because `$_SERVER['DOCUMENT_ROOT']` returns absolute PATH to your web root, not URL. JavaScript needs to be added as URL. So, you may use `Load_Template_Scripts_wpa83855` function in your plugin and then use: ``` wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ) ); ``` CODE to add JavaScript. > > ***Note:*** obviously you can make the CODE even better using logic like what [@nathan used in his answer](https://wordpress.stackexchange.com/a/262190/110572), i.e. adding: > > > `add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');` > > > within the `wpa3396_page_template()` function in `if ( is_page( 'mypanel' ) ) {}` condition block; but that's not the reason of the error. Server PATH cannot be accessed by browser, that's why the server returns `Access Forbidden` error. > > > Full CODE (Updated): -------------------- Here is the full CODE for your convenience (add it in your main plugin file): ``` add_filter( 'page_template', 'wpse_262042_page_template' ); function wpse_262042_page_template( $page_template ) { if( is_page( 'mypanel' ) ) { add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' ); $page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php'; } return $page_template; } function wpse_262042_enqueue_scripts() { wp_enqueue_script( 'wtd', plugins_url( 'js/wtd.js' , __FILE__ ), array( 'jquery' ) ); } ```
262,100
<p>I have 10 thousand of users about 98% of these users never published a post (i mean post not comments). </p> <p>I need a way to mass delete users with 0 posts.</p> <p>The method must count all posts included custom post types and has to use proper WordPress function to delete a user as if they were manually deleted in the dashboard and not just drop a table/row on mysql, since that might cause unexpected results.</p> <p>There's <a href="https://wordpress.org/plugins/no-posts-user-delete/" rel="noreferrer">an old plugin</a> that does this but doesn't consider all post types so can't really be used.</p> <p>Any help appreciated.</p>
[ { "answer_id": 262105, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>If you have a large number of users to delete, you might consder using the <a href=\"https://wp-cli.org/commands/user/delete/\" rel=\"nofollow noreferrer\">wp user delete</a> <strong>wp-cli</strong> command to avoid script timeouts.</p>\n\n<p><a href=\"https://stackoverflow.com/a/8155865/2078474\">Here's</a> an example of a SQL query to delete all users <strong>without posts of any type and status</strong>.</p>\n\n<p>You can therefore try this <s>untested</s> one-liner:</p>\n\n<pre><code>wp user delete $(wp db query \"SELECT ID FROM wp_users WHERE ID NOT IN (SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)\" | tail -n +2 ) --reassign=1\n</code></pre>\n\n<p>or in expanded form:</p>\n\n<pre><code>wp user delete $(wp db query\n \"SELECT ID \n FROM wp_users \n WHERE ID NOT IN ( \n SELECT DISTINCT post_author FROM wp_posts \n ) AND ID NOT IN (1,2,3)\" | tail -n +2 \n ) --reassign=1\n</code></pre>\n\n<p>Note that we added an extra <code>AND ID NOT IN (1,2,3)</code> restriction to make sure these users are not deleted (e.g. admin users). You will have to adjust it to your needs and also the table prefix <code>wp_</code>. </p>\n\n<p>When I briefly tested this for couple of users, I noticed I had to add the <code>tail -n +2</code> part to avoid the top 3 lines in the header and the table border of the <code>wp db query</code> output.</p>\n\n<p>Here we reassign all posts to user 1, to avoid the notice:</p>\n\n<pre><code>--reassign parameter not passed. All associated posts will be deleted. Proceed? [y/n] \n</code></pre>\n\n<p>Hope you can adjust it further to your needs, like relaxing the user delete conditions by adding <code>WHERE post_status = 'publish'</code>.</p>\n\n<p><strong>Note:</strong> Remember to backup before testing!</p>\n" }, { "answer_id": 262107, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 1, "selected": false, "text": "<p>Judging by the source code of the old plugin you mentioned, the post types that it does not consider are <a href=\"https://codex.wordpress.org/Post_Type#Attachment\" rel=\"nofollow noreferrer\">attachment</a> and <a href=\"https://codex.wordpress.org/Post_Type#Revision\" rel=\"nofollow noreferrer\">revision</a>. I think you can easily fix this by removing this from the source code of the plugin file no-posts-user-delete.php</p>\n\n<pre><code> AND NOT WP.post_type in ('attachment', 'revision')\n</code></pre>\n" }, { "answer_id": 262120, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>Here's a way to do it in PHP. It might be slow and/or timeout, but since it's a one-time thing, it shouldn't matter too much. Temporarily place inside your functions.php or upload as a new plugin.</p>\n\n<pre><code>//* You don't want to run this on admin_init. Run it once and deactivate\nadd_action( 'admin_init', 'wpse_262100_admin_init' );\nfunction wpse_262100_admin_init() {\n $reserved_post_types = [\n 'attachment',\n 'revision',\n 'nav_menu_item',\n 'custom_css',\n 'customize_changeset',\n ];\n\n //* Get the non-reserved post types\n $post_types = array_diff( array_keys( get_post_types() ), $reserved_post_types );\n foreach( get_users() as $user ) {\n if( 0 == count_user_posts( $user-&gt;ID, $post_types ) ) {\n wp_delete_user( $user-&gt;ID );\n }\n }\n}\n</code></pre>\n" } ]
2017/04/01
[ "https://wordpress.stackexchange.com/questions/262100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
I have 10 thousand of users about 98% of these users never published a post (i mean post not comments). I need a way to mass delete users with 0 posts. The method must count all posts included custom post types and has to use proper WordPress function to delete a user as if they were manually deleted in the dashboard and not just drop a table/row on mysql, since that might cause unexpected results. There's [an old plugin](https://wordpress.org/plugins/no-posts-user-delete/) that does this but doesn't consider all post types so can't really be used. Any help appreciated.
If you have a large number of users to delete, you might consder using the [wp user delete](https://wp-cli.org/commands/user/delete/) **wp-cli** command to avoid script timeouts. [Here's](https://stackoverflow.com/a/8155865/2078474) an example of a SQL query to delete all users **without posts of any type and status**. You can therefore try this ~~untested~~ one-liner: ``` wp user delete $(wp db query "SELECT ID FROM wp_users WHERE ID NOT IN (SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)" | tail -n +2 ) --reassign=1 ``` or in expanded form: ``` wp user delete $(wp db query "SELECT ID FROM wp_users WHERE ID NOT IN ( SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)" | tail -n +2 ) --reassign=1 ``` Note that we added an extra `AND ID NOT IN (1,2,3)` restriction to make sure these users are not deleted (e.g. admin users). You will have to adjust it to your needs and also the table prefix `wp_`. When I briefly tested this for couple of users, I noticed I had to add the `tail -n +2` part to avoid the top 3 lines in the header and the table border of the `wp db query` output. Here we reassign all posts to user 1, to avoid the notice: ``` --reassign parameter not passed. All associated posts will be deleted. Proceed? [y/n] ``` Hope you can adjust it further to your needs, like relaxing the user delete conditions by adding `WHERE post_status = 'publish'`. **Note:** Remember to backup before testing!
262,109
<p>I'm new to WP and I am not quite sure how to approach my goal - I'd like to make featured images in blog posts 1920px wide x 350px high that will become full width banner images at the top of the page.</p> <p>How do I go about that?</p> <p>Currently I am using pretty simple .css rules that simply position a background image at the top of the page below the navigation with text written over it - but I'd like that to be applied to all blog posts...</p> <p>How would you tackle this? </p> <p>Thanks for all direction...</p>
[ { "answer_id": 262105, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>If you have a large number of users to delete, you might consder using the <a href=\"https://wp-cli.org/commands/user/delete/\" rel=\"nofollow noreferrer\">wp user delete</a> <strong>wp-cli</strong> command to avoid script timeouts.</p>\n\n<p><a href=\"https://stackoverflow.com/a/8155865/2078474\">Here's</a> an example of a SQL query to delete all users <strong>without posts of any type and status</strong>.</p>\n\n<p>You can therefore try this <s>untested</s> one-liner:</p>\n\n<pre><code>wp user delete $(wp db query \"SELECT ID FROM wp_users WHERE ID NOT IN (SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)\" | tail -n +2 ) --reassign=1\n</code></pre>\n\n<p>or in expanded form:</p>\n\n<pre><code>wp user delete $(wp db query\n \"SELECT ID \n FROM wp_users \n WHERE ID NOT IN ( \n SELECT DISTINCT post_author FROM wp_posts \n ) AND ID NOT IN (1,2,3)\" | tail -n +2 \n ) --reassign=1\n</code></pre>\n\n<p>Note that we added an extra <code>AND ID NOT IN (1,2,3)</code> restriction to make sure these users are not deleted (e.g. admin users). You will have to adjust it to your needs and also the table prefix <code>wp_</code>. </p>\n\n<p>When I briefly tested this for couple of users, I noticed I had to add the <code>tail -n +2</code> part to avoid the top 3 lines in the header and the table border of the <code>wp db query</code> output.</p>\n\n<p>Here we reassign all posts to user 1, to avoid the notice:</p>\n\n<pre><code>--reassign parameter not passed. All associated posts will be deleted. Proceed? [y/n] \n</code></pre>\n\n<p>Hope you can adjust it further to your needs, like relaxing the user delete conditions by adding <code>WHERE post_status = 'publish'</code>.</p>\n\n<p><strong>Note:</strong> Remember to backup before testing!</p>\n" }, { "answer_id": 262107, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 1, "selected": false, "text": "<p>Judging by the source code of the old plugin you mentioned, the post types that it does not consider are <a href=\"https://codex.wordpress.org/Post_Type#Attachment\" rel=\"nofollow noreferrer\">attachment</a> and <a href=\"https://codex.wordpress.org/Post_Type#Revision\" rel=\"nofollow noreferrer\">revision</a>. I think you can easily fix this by removing this from the source code of the plugin file no-posts-user-delete.php</p>\n\n<pre><code> AND NOT WP.post_type in ('attachment', 'revision')\n</code></pre>\n" }, { "answer_id": 262120, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>Here's a way to do it in PHP. It might be slow and/or timeout, but since it's a one-time thing, it shouldn't matter too much. Temporarily place inside your functions.php or upload as a new plugin.</p>\n\n<pre><code>//* You don't want to run this on admin_init. Run it once and deactivate\nadd_action( 'admin_init', 'wpse_262100_admin_init' );\nfunction wpse_262100_admin_init() {\n $reserved_post_types = [\n 'attachment',\n 'revision',\n 'nav_menu_item',\n 'custom_css',\n 'customize_changeset',\n ];\n\n //* Get the non-reserved post types\n $post_types = array_diff( array_keys( get_post_types() ), $reserved_post_types );\n foreach( get_users() as $user ) {\n if( 0 == count_user_posts( $user-&gt;ID, $post_types ) ) {\n wp_delete_user( $user-&gt;ID );\n }\n }\n}\n</code></pre>\n" } ]
2017/04/01
[ "https://wordpress.stackexchange.com/questions/262109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I'm new to WP and I am not quite sure how to approach my goal - I'd like to make featured images in blog posts 1920px wide x 350px high that will become full width banner images at the top of the page. How do I go about that? Currently I am using pretty simple .css rules that simply position a background image at the top of the page below the navigation with text written over it - but I'd like that to be applied to all blog posts... How would you tackle this? Thanks for all direction...
If you have a large number of users to delete, you might consder using the [wp user delete](https://wp-cli.org/commands/user/delete/) **wp-cli** command to avoid script timeouts. [Here's](https://stackoverflow.com/a/8155865/2078474) an example of a SQL query to delete all users **without posts of any type and status**. You can therefore try this ~~untested~~ one-liner: ``` wp user delete $(wp db query "SELECT ID FROM wp_users WHERE ID NOT IN (SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)" | tail -n +2 ) --reassign=1 ``` or in expanded form: ``` wp user delete $(wp db query "SELECT ID FROM wp_users WHERE ID NOT IN ( SELECT DISTINCT post_author FROM wp_posts ) AND ID NOT IN (1,2,3)" | tail -n +2 ) --reassign=1 ``` Note that we added an extra `AND ID NOT IN (1,2,3)` restriction to make sure these users are not deleted (e.g. admin users). You will have to adjust it to your needs and also the table prefix `wp_`. When I briefly tested this for couple of users, I noticed I had to add the `tail -n +2` part to avoid the top 3 lines in the header and the table border of the `wp db query` output. Here we reassign all posts to user 1, to avoid the notice: ``` --reassign parameter not passed. All associated posts will be deleted. Proceed? [y/n] ``` Hope you can adjust it further to your needs, like relaxing the user delete conditions by adding `WHERE post_status = 'publish'`. **Note:** Remember to backup before testing!
262,116
<p>I have a code, i used to call a particular category in my post page footer and i have specified the number of posts to display but its showing all the posts from that category.</p> <p>here are the codes</p> <pre><code>&lt;?php query_posts('category_name=tech&amp;order=dsc&amp;showposts=12'); ?&gt; </code></pre> <p>and <code>&lt;?php query_posts('cat=438'.'&amp;showposts=7'); ?&gt;</code></p> <p>any help please, i really need the post to be five. As for loop, am using my default loop to get my preferred design.</p> <p>thanks</p>
[ { "answer_id": 262131, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>It says <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters\" rel=\"nofollow noreferrer\">here</a> that <em>showposts</em> was replaced by <em>posts_per_page</em>. Try using it instead.</p>\n" }, { "answer_id": 262187, "author": "IAmDhar", "author_id": 116777, "author_profile": "https://wordpress.stackexchange.com/users/116777", "pm_score": 1, "selected": false, "text": "<p>If you need the number of posts in the query args then use posts_per_page, since posts_per_page has a default value of 10, it will always display 10 posts, if you wish to see all the posts, as in, there should not be any limit then choose its value to be -1 and use it like this</p>\n\n<pre><code>$args=array( \n 'post_type'=&gt;'page',\n 'posts_per_page'=&gt; '-1', \n); \n</code></pre>\n" } ]
2017/04/01
[ "https://wordpress.stackexchange.com/questions/262116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115764/" ]
I have a code, i used to call a particular category in my post page footer and i have specified the number of posts to display but its showing all the posts from that category. here are the codes ``` <?php query_posts('category_name=tech&order=dsc&showposts=12'); ?> ``` and `<?php query_posts('cat=438'.'&showposts=7'); ?>` any help please, i really need the post to be five. As for loop, am using my default loop to get my preferred design. thanks
If you need the number of posts in the query args then use posts\_per\_page, since posts\_per\_page has a default value of 10, it will always display 10 posts, if you wish to see all the posts, as in, there should not be any limit then choose its value to be -1 and use it like this ``` $args=array( 'post_type'=>'page', 'posts_per_page'=> '-1', ); ```
262,153
<p>I have a subdomain </p> <blockquote> <p><code>http://blog.example.com</code></p> </blockquote> <p>I would like to redirect it to subdirectory as </p> <blockquote> <p><code>https://www.example.com/blog</code></p> </blockquote> <p>But not admin(<strong>/wp-admin</strong>). Admin area should be as it is </p> <blockquote> <p><code>http://blog.example.com/wp-admin</code></p> </blockquote> <p>currently I have this in my htaccess</p> <pre><code>&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] RewriteCond %{HTTP:X-Forwarded-Host}i ^example\.com RewriteCond %{HTTP_HOST} ^blog\.example\.com$ RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] &lt;/IfModule&gt; </code></pre> <p>and my site URL and WordPress URL is:</p> <pre><code>WordPress Address (URL) = /blog Site Address (URL) = https://www.example.com/blog </code></pre> <p>but this setup redirects every URLs in my website and creating many issues in the backend.</p> <p>What is the best ways to do this?</p>
[ { "answer_id": 262214, "author": "Greeso", "author_id": 34253, "author_profile": "https://wordpress.stackexchange.com/users/34253", "pm_score": 0, "selected": false, "text": "<p>Have you tried the following?</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"refresh\" content=\"0; url=https://www.example.com/blog\" /&gt;\n &lt;/head&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This would be your <code>index.php</code> file, and you would place it in <code>http://blog.example.com</code></p>\n\n<p><strong>Note</strong> \nThe <code>0</code> in the refresh statement is the number of seconds your page waits before redirecting to a new site, and <code>0</code> means redirect immediately.</p>\n\n<p><strong>Note 2</strong> You can make a new theme, that only contains this <code>index.php</code> file above (and the <code>style.css</code> file for theme definition), and switch to this theme, and you will be set. Alternatively, update your existing theme, and add the meta tag above to your header. Either way should work.</p>\n" }, { "answer_id": 263333, "author": "Abhishek Gurjar", "author_id": 114650, "author_profile": "https://wordpress.stackexchange.com/users/114650", "pm_score": 2, "selected": false, "text": "<p>Use below rule,</p>\n\n<pre><code>RewriteEngine On\n\n# excluding www\nRewriteCond %{HTTP_HOST} !^www\nRewriteCond %{HTTP_HOST} ^blog\n\n# excluding wp-admin\nRewriteCond %{REQUEST_URI} !^wp-admin\nRewriteRule ^ https://www.example.com/%1\n</code></pre>\n" } ]
2017/04/02
[ "https://wordpress.stackexchange.com/questions/262153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63027/" ]
I have a subdomain > > `http://blog.example.com` > > > I would like to redirect it to subdirectory as > > `https://www.example.com/blog` > > > But not admin(**/wp-admin**). Admin area should be as it is > > `http://blog.example.com/wp-admin` > > > currently I have this in my htaccess ``` <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] RewriteCond %{HTTP:X-Forwarded-Host}i ^example\.com RewriteCond %{HTTP_HOST} ^blog\.example\.com$ RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] </IfModule> ``` and my site URL and WordPress URL is: ``` WordPress Address (URL) = /blog Site Address (URL) = https://www.example.com/blog ``` but this setup redirects every URLs in my website and creating many issues in the backend. What is the best ways to do this?
Use below rule, ``` RewriteEngine On # excluding www RewriteCond %{HTTP_HOST} !^www RewriteCond %{HTTP_HOST} ^blog # excluding wp-admin RewriteCond %{REQUEST_URI} !^wp-admin RewriteRule ^ https://www.example.com/%1 ```
262,155
<p>I have following code, which is generating the the text on the website. code resides in front-page.php file in the theme folder.</p> <pre><code>&lt;p class="excerpt"&gt; &lt;?php $theExcerpt = get_the_excerpt(); $tags = array("&lt;p&gt;", "&lt;/p&gt;"); $theExcerpt = str_replace($tags, "", $theExcerpt); echo $theExcerpt; ?&gt; &lt;/p&gt; </code></pre> <p>Let me know if you want more information. Thank you.</p> <p><a href="https://i.stack.imgur.com/BlGg6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BlGg6.png" alt="enter image description here"></a></p>
[ { "answer_id": 262164, "author": "Bob", "author_id": 116319, "author_profile": "https://wordpress.stackexchange.com/users/116319", "pm_score": 3, "selected": true, "text": "<p>One thing you can try is going into the page's Edit mode, by pressing \"Edit\" on that page, and then checking whether that text is by any chance the actual excerpt. If you can't see an \"excerpt\" section on that page you can go to the top of that page, click \"Screen Options\" on the top right, and tick the option \"Excerpt\" (see image). <br><br>\nIf you find that the excerpt of the page is actually empty, meaning that your theme is probably generating a predefined excerpt when no excerpt is present, you can download your theme to your pc and do an in-file search using the text it is generating (in your case \"Lorem ipsum ...\"). This way you can find out where it is in your theme's code that the text has been hard-coded.<br>\nYou can use some software like AstroGrep in order to perform the search. <br>\n<a href=\"https://i.stack.imgur.com/pQGbH.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pQGbH.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 262166, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>Your code only output the_excerpt without the p tags, excerpt is part of the written post but can also be automatically generated, theme can have the support of excerpt and then the ox is viewable. </p>\n\n<p>There's filters to change the excerpt lengh and other behaviour, you can learn more <a href=\"https://developer.wordpress.org/reference/functions/the_excerpt/\" rel=\"nofollow noreferrer\">here</a> (read the example).</p>\n\n<p>Note that there's also the filter wpautop to disable p tags in a function.</p>\n\n<p>Hope it helps</p>\n" } ]
2017/04/02
[ "https://wordpress.stackexchange.com/questions/262155", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116754/" ]
I have following code, which is generating the the text on the website. code resides in front-page.php file in the theme folder. ``` <p class="excerpt"> <?php $theExcerpt = get_the_excerpt(); $tags = array("<p>", "</p>"); $theExcerpt = str_replace($tags, "", $theExcerpt); echo $theExcerpt; ?> </p> ``` Let me know if you want more information. Thank you. [![enter image description here](https://i.stack.imgur.com/BlGg6.png)](https://i.stack.imgur.com/BlGg6.png)
One thing you can try is going into the page's Edit mode, by pressing "Edit" on that page, and then checking whether that text is by any chance the actual excerpt. If you can't see an "excerpt" section on that page you can go to the top of that page, click "Screen Options" on the top right, and tick the option "Excerpt" (see image). If you find that the excerpt of the page is actually empty, meaning that your theme is probably generating a predefined excerpt when no excerpt is present, you can download your theme to your pc and do an in-file search using the text it is generating (in your case "Lorem ipsum ..."). This way you can find out where it is in your theme's code that the text has been hard-coded. You can use some software like AstroGrep in order to perform the search. [![enter image description here](https://i.stack.imgur.com/pQGbH.jpg)](https://i.stack.imgur.com/pQGbH.jpg)
262,160
<p>I'm using <strong>woocommerce multi vendor plugin</strong>, this is my current URL </p> <pre><code>http://localhost/cloudstock4/vendor/vender-two/ </code></pre> <p>I want to get this last couple of word. i think this page use the WP archive.php </p>
[ { "answer_id": 262163, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> to get what you want in the query made with the request.</p>\n\n<pre><code>$vendor = get_query_var('vendor');\n</code></pre>\n\n<p>If the vendor var is set, $vendor will be 'vender-two'.</p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 262169, "author": "J. Doe", "author_id": 116757, "author_profile": "https://wordpress.stackexchange.com/users/116757", "pm_score": 0, "selected": false, "text": "<pre><code>function hitcount(){\n\nglobal $wpdb;\nglobal $wp_query;\n\n$vendor_slug = $wp_query-&gt;query['wcpv_product_vendors'];\n\n$wpdb-&gt;insert( \n 'wp_profile_hits', \n array( \n **---&gt;&gt;&gt;** 'vendor_name' =&gt; $vendor_slug ,\n 'user_ip' =&gt; get_client_ip()\n )\n );\n}\n</code></pre>\n\n<p>This is my function. I just want to add before URL last couple of word and save to custom table in data base.</p>\n\n<p>The Bold line is to be correct. the get the vendor username slug. </p>\n" } ]
2017/04/02
[ "https://wordpress.stackexchange.com/questions/262160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116757/" ]
I'm using **woocommerce multi vendor plugin**, this is my current URL ``` http://localhost/cloudstock4/vendor/vender-two/ ``` I want to get this last couple of word. i think this page use the WP archive.php
You can use [`get_query_var()`](https://codex.wordpress.org/Function_Reference/get_query_var) to get what you want in the query made with the request. ``` $vendor = get_query_var('vendor'); ``` If the vendor var is set, $vendor will be 'vender-two'. Hope it helps
262,178
<p>I have a super simple requirement here. I have added a meta field to all posts that will allow a url to be used to redirect the post (i have reasons for doing it this way). I am trying to trigger this on the action "the_post", but for some reason it doesnt seem to fire. Here is what ive added </p> <pre><code>function nb_checkredirect($post) { if(get_post_meta( $post-&gt;ID, 'nb_postredirect', true ) != "") { header('Location: '.get_post_meta( $post-&gt;ID, 'nb_postredirect', true )); wp_die(); die(); } } add_action( 'the_post', 'nb_checkredirect' ); </code></pre> <p>I have checked what gets output to the PHP error log and there doesnt appear to be anything going wrong. </p>
[ { "answer_id": 262175, "author": "Kevin Mamaqi", "author_id": 60103, "author_profile": "https://wordpress.stackexchange.com/users/60103", "pm_score": 2, "selected": false, "text": "<p>You need to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">wp_script_is</a> in order to check if the library you are willing to use has already been included by another plugin. As you can see the handle is important, if you change it to whatEverIWant.js, it will not recognize the library.</p>\n" }, { "answer_id": 262176, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>There's no real way that developers would be able to achieve this. This is mostly because:</p>\n\n<ul>\n<li>Different plugins may depend on different version of a library, not being able to work with another.</li>\n<li>Not every developer works clean enough to think of conflicts while creating something. A low quality coded theme/plugin can always cause issue.</li>\n<li>The same library can be included under different names ( due to carelessness, mistake, etc. ) and if you are publishing a theme/plugin, you won't always be there for the customer to check for these problems.</li>\n</ul>\n\n<p>However, if you are using a well-known and popular library which is included in WordPress too, you can check if it is loaded already by using the following function:</p>\n\n<pre><code>wp_script_is( $name, $list = 'enqueued' );\n</code></pre>\n\n<p>This will return <code>true</code> if the script is already printed/enqueued/registered so you can use it with conjunction of an <code>if()</code> to decide whether you should print it again or not.</p>\n\n<p>But as i mentioned above, if the names are not the same, this won't work.</p>\n" } ]
2017/04/02
[ "https://wordpress.stackexchange.com/questions/262178", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have a super simple requirement here. I have added a meta field to all posts that will allow a url to be used to redirect the post (i have reasons for doing it this way). I am trying to trigger this on the action "the\_post", but for some reason it doesnt seem to fire. Here is what ive added ``` function nb_checkredirect($post) { if(get_post_meta( $post->ID, 'nb_postredirect', true ) != "") { header('Location: '.get_post_meta( $post->ID, 'nb_postredirect', true )); wp_die(); die(); } } add_action( 'the_post', 'nb_checkredirect' ); ``` I have checked what gets output to the PHP error log and there doesnt appear to be anything going wrong.
You need to use [wp\_script\_is](https://codex.wordpress.org/Function_Reference/wp_script_is) in order to check if the library you are willing to use has already been included by another plugin. As you can see the handle is important, if you change it to whatEverIWant.js, it will not recognize the library.
262,196
<p>I'm using WP 4.7.3 and a custom template set (mh-magazine).</p> <p>By default, WP sets a title tag like "Page title" - "Blog title".</p> <p>Now all I want to achieve is to replace "-" into a pipe symbol for layout reasons. So the processed HTMl should look like:</p> <p>My page title | My blog title</p> <p>I thought that this is easy to achieve, but I see I need some help since I'm not an expert in PHP or WP.</p>
[ { "answer_id": 262197, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 3, "selected": true, "text": "<p>It all depends on how your theme's <code>header.php</code> is structured, but the most likely way is via the <a href=\"https://developer.wordpress.org/reference/hooks/document_title_separator/\" rel=\"nofollow noreferrer\">document_title_separator</a> filter, as in</p>\n\n<pre><code>add_filter ('document_title_separator', 'wpse_set_document_title_separator') ;\n\nfunction\nwpse_set_document_title_separator ($sep)\n{\n return ('|') ;\n}\n</code></pre>\n" }, { "answer_id": 262208, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<h2>Possibility-1:</h2>\n\n<p>If your theme has:</p>\n\n<ol>\n<li><p><code>add_theme_support( 'title-tag' );</code> somewhere in your <code>functions.php</code> file, and</p></li>\n<li><p><code>wp_head()</code> function call in <code>header.php</code> file</p></li>\n</ol>\n\n<p>then using <code>document_title_separator</code> filter will work as <a href=\"https://wordpress.stackexchange.com/a/262197/110572\">@Paul's answer</a> suggested.</p>\n\n<p>If the filter doesn't work even after meeting those conditions above, then perhaps a plugin is overriding it. Try increasing the priority of the filter so that it runs last, like so:</p>\n\n<pre><code>function wpse262196_document_title_separator( $sep ) {\n return '|';\n}\nadd_filter( 'document_title_separator', 'wpse262196_document_title_separator', PHP_INT_MAX );\n</code></pre>\n\n<p>or if the <code>document_title_separator</code> filter already exists in your theme's <code>functions.php</code> file, then change it there.</p>\n\n<hr>\n\n<h2>Possibility-2:</h2>\n\n<p>May be your theme doesn't include <code>add_theme_support( 'title-tag' );</code> and instead uses the old <a href=\"https://developer.wordpress.org/reference/functions/wp_title/\" rel=\"nofollow noreferrer\"><code>&lt;title&gt;&lt;?php wp_title(); ?&gt;&lt;/title&gt;</code></a> in <code>header.php</code> file.</p>\n\n<p>In this case, you may change it like: <code>&lt;title&gt;&lt;?php wp_title( '|' ); ?&gt;&lt;/title&gt;</code> to change the separator.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> it's strongly advised to change it back to <code>add_theme_support( 'title-tag' );</code>, as <code>wp_title()</code> is likely to be deprecated.</p>\n</blockquote>\n\n<p>Also, if it doesn't work, then may be your a plugin is replacing it using <code>wp_title</code> filter. In that case, use the filter below in your themes <code>functions.php</code> file to change the behaviour:</p>\n\n<pre><code>function wpse262196_wp_title( $title, $sep, $seplocation ) {\n return str_replace( \" $sep \", \" | \", $title );\n}\nadd_filter( 'wp_title', 'wpse262196_wp_title', PHP_INT_MAX );\n</code></pre>\n\n<p>or if the <code>wp_title</code> filter already exists in your theme's <code>functions.php</code> file, then change it there.</p>\n\n<p>Hopefully one the solutions will work for you.</p>\n" }, { "answer_id": 262209, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 1, "selected": false, "text": "<p>If you would like to go a plugin route, you can use the <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a> plugin which is a free and powerful SEO tool.</p>\n\n<p><strong>Note: Yoast SEO is a full featured SEO plugin. So if you're not going to make use of the other SEO features of Yoast and changing the title separator is all you need, then this plugin will be overkill and the other answers given would be both much lighter weight and more appropriate for your needs.</strong></p>\n\n<ol>\n<li>Install it from the WordPress repo (within your WordPress installation is easiest) as you would any other plugin. Then activate it.</li>\n<li>Head to Yoast > Dashboard > Features and make sure to turn on the \"Advanced Settings Pages\" and hit save. <a href=\"https://i.stack.imgur.com/PV9nR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PV9nR.png\" alt=\"Yoast - turn on Advanced Settings\"></a></li>\n<li>Click the \"Titles &amp; Metas\" option page. The very first tab (\"General\") will give you the ability to globally specify your title separators. <a href=\"https://i.stack.imgur.com/wuFDr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wuFDr.png\" alt=\"Title Separators\"></a></li>\n</ol>\n" } ]
2017/04/02
[ "https://wordpress.stackexchange.com/questions/262196", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116780/" ]
I'm using WP 4.7.3 and a custom template set (mh-magazine). By default, WP sets a title tag like "Page title" - "Blog title". Now all I want to achieve is to replace "-" into a pipe symbol for layout reasons. So the processed HTMl should look like: My page title | My blog title I thought that this is easy to achieve, but I see I need some help since I'm not an expert in PHP or WP.
It all depends on how your theme's `header.php` is structured, but the most likely way is via the [document\_title\_separator](https://developer.wordpress.org/reference/hooks/document_title_separator/) filter, as in ``` add_filter ('document_title_separator', 'wpse_set_document_title_separator') ; function wpse_set_document_title_separator ($sep) { return ('|') ; } ```
262,220
<p>I wanted to display ads on in post in a particular category. I also want to display ads in another category not only one but every time I insert the code again and change the category id, it causes a "white screen" error. Can you tell me how can I extend that function, that I will be able to display different ads in different post in a particular category?</p> <p>Below is the function that i use to display the ad:</p> <pre><code>add_filter('the_content', 'wpse_ad_content'); function wpse_ad_content($content) { if (!is_single()) return $content; if(!in_category('7')) return $content; $paragraphAfter = 2; //Enter number of paragraphs to display ad after. $content = explode("&lt;/p&gt;", $content); $new_content = ''; for ($i = 0; $i &lt; count($content); $i++) { if ($i == $paragraphAfter) { $new_content.= '&lt;div style="width: 300px; height: 250px; padding: 6px 6px 6px 0; float: left; margin-left: 0; margin-right: 18px;"&gt;'; $new_content.= '//Enter your ad code here....'; $new_content.= '&lt;/div&gt;'; } $new_content.= $content[$i] . "&lt;/p&gt;"; } return $new_content; } </code></pre>
[ { "answer_id": 262197, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 3, "selected": true, "text": "<p>It all depends on how your theme's <code>header.php</code> is structured, but the most likely way is via the <a href=\"https://developer.wordpress.org/reference/hooks/document_title_separator/\" rel=\"nofollow noreferrer\">document_title_separator</a> filter, as in</p>\n\n<pre><code>add_filter ('document_title_separator', 'wpse_set_document_title_separator') ;\n\nfunction\nwpse_set_document_title_separator ($sep)\n{\n return ('|') ;\n}\n</code></pre>\n" }, { "answer_id": 262208, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<h2>Possibility-1:</h2>\n\n<p>If your theme has:</p>\n\n<ol>\n<li><p><code>add_theme_support( 'title-tag' );</code> somewhere in your <code>functions.php</code> file, and</p></li>\n<li><p><code>wp_head()</code> function call in <code>header.php</code> file</p></li>\n</ol>\n\n<p>then using <code>document_title_separator</code> filter will work as <a href=\"https://wordpress.stackexchange.com/a/262197/110572\">@Paul's answer</a> suggested.</p>\n\n<p>If the filter doesn't work even after meeting those conditions above, then perhaps a plugin is overriding it. Try increasing the priority of the filter so that it runs last, like so:</p>\n\n<pre><code>function wpse262196_document_title_separator( $sep ) {\n return '|';\n}\nadd_filter( 'document_title_separator', 'wpse262196_document_title_separator', PHP_INT_MAX );\n</code></pre>\n\n<p>or if the <code>document_title_separator</code> filter already exists in your theme's <code>functions.php</code> file, then change it there.</p>\n\n<hr>\n\n<h2>Possibility-2:</h2>\n\n<p>May be your theme doesn't include <code>add_theme_support( 'title-tag' );</code> and instead uses the old <a href=\"https://developer.wordpress.org/reference/functions/wp_title/\" rel=\"nofollow noreferrer\"><code>&lt;title&gt;&lt;?php wp_title(); ?&gt;&lt;/title&gt;</code></a> in <code>header.php</code> file.</p>\n\n<p>In this case, you may change it like: <code>&lt;title&gt;&lt;?php wp_title( '|' ); ?&gt;&lt;/title&gt;</code> to change the separator.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> it's strongly advised to change it back to <code>add_theme_support( 'title-tag' );</code>, as <code>wp_title()</code> is likely to be deprecated.</p>\n</blockquote>\n\n<p>Also, if it doesn't work, then may be your a plugin is replacing it using <code>wp_title</code> filter. In that case, use the filter below in your themes <code>functions.php</code> file to change the behaviour:</p>\n\n<pre><code>function wpse262196_wp_title( $title, $sep, $seplocation ) {\n return str_replace( \" $sep \", \" | \", $title );\n}\nadd_filter( 'wp_title', 'wpse262196_wp_title', PHP_INT_MAX );\n</code></pre>\n\n<p>or if the <code>wp_title</code> filter already exists in your theme's <code>functions.php</code> file, then change it there.</p>\n\n<p>Hopefully one the solutions will work for you.</p>\n" }, { "answer_id": 262209, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 1, "selected": false, "text": "<p>If you would like to go a plugin route, you can use the <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a> plugin which is a free and powerful SEO tool.</p>\n\n<p><strong>Note: Yoast SEO is a full featured SEO plugin. So if you're not going to make use of the other SEO features of Yoast and changing the title separator is all you need, then this plugin will be overkill and the other answers given would be both much lighter weight and more appropriate for your needs.</strong></p>\n\n<ol>\n<li>Install it from the WordPress repo (within your WordPress installation is easiest) as you would any other plugin. Then activate it.</li>\n<li>Head to Yoast > Dashboard > Features and make sure to turn on the \"Advanced Settings Pages\" and hit save. <a href=\"https://i.stack.imgur.com/PV9nR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PV9nR.png\" alt=\"Yoast - turn on Advanced Settings\"></a></li>\n<li>Click the \"Titles &amp; Metas\" option page. The very first tab (\"General\") will give you the ability to globally specify your title separators. <a href=\"https://i.stack.imgur.com/wuFDr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wuFDr.png\" alt=\"Title Separators\"></a></li>\n</ol>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115069/" ]
I wanted to display ads on in post in a particular category. I also want to display ads in another category not only one but every time I insert the code again and change the category id, it causes a "white screen" error. Can you tell me how can I extend that function, that I will be able to display different ads in different post in a particular category? Below is the function that i use to display the ad: ``` add_filter('the_content', 'wpse_ad_content'); function wpse_ad_content($content) { if (!is_single()) return $content; if(!in_category('7')) return $content; $paragraphAfter = 2; //Enter number of paragraphs to display ad after. $content = explode("</p>", $content); $new_content = ''; for ($i = 0; $i < count($content); $i++) { if ($i == $paragraphAfter) { $new_content.= '<div style="width: 300px; height: 250px; padding: 6px 6px 6px 0; float: left; margin-left: 0; margin-right: 18px;">'; $new_content.= '//Enter your ad code here....'; $new_content.= '</div>'; } $new_content.= $content[$i] . "</p>"; } return $new_content; } ```
It all depends on how your theme's `header.php` is structured, but the most likely way is via the [document\_title\_separator](https://developer.wordpress.org/reference/hooks/document_title_separator/) filter, as in ``` add_filter ('document_title_separator', 'wpse_set_document_title_separator') ; function wpse_set_document_title_separator ($sep) { return ('|') ; } ```
262,225
<p>I want to change the size of the featued image for one custom post type only. This is what I currently have:</p> <pre><code>function custom_admin_thumb_size($thumb_size){ global $post_type; if( 'slider' == $post_type ){ return array(1000,400); }else{ return array(266,266); } } add_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size'); </code></pre> <p>This function does what I expected but I was wondering if there is any better method to call the custom post type "slider" without touching the others.</p> <p>Thanks in advance</p>
[ { "answer_id": 262228, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 1, "selected": false, "text": "<p>There is no filter to do this for just a certain post_type but you can use <code>get_post_type( esc_attr( $_GET['post'] ) )</code> to save 1 line of code basically.</p>\n\n<p>You can also take out the else statement since your if statement has a return it won't reach after the if anyway. Other than that this is basically what you do.</p>\n\n<pre><code>function custom_admin_thumb_size( $thumb_size ){\n\n if( 'slider' == get_post_type( esc_attr( $_GET['post'] ) ) ) {\n\n return array( 1000, 400 );\n\n }\n\n return array( 266, 266);\n\n}\nadd_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size' );\n</code></pre>\n" }, { "answer_id": 262233, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_size/\" rel=\"nofollow noreferrer\"><code>admin_post_thumbnail_size</code></a> takes three parameters:</p>\n\n<ol>\n<li><p>$thumb_size: selected Thumb Size if you do nothing in the filter.</p></li>\n<li><p>$thumbnail_id: Thumbnail attachment ID.</p></li>\n<li><p>$post: associated WP_Post instance</p></li>\n</ol>\n\n<p>So you may make use of these parameters to have a better control in your CODE. Use the CODE like below:</p>\n\n<pre><code>function custom_admin_thumb_size( $thumb_size, $thumbnail_id, $post ) {\n if( 'slider' === $post-&gt;post_type ) {\n return array( 1000, 400 );\n }\n\n return $thumb_size;\n}\nadd_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size', 10, 3);\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262225", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102737/" ]
I want to change the size of the featued image for one custom post type only. This is what I currently have: ``` function custom_admin_thumb_size($thumb_size){ global $post_type; if( 'slider' == $post_type ){ return array(1000,400); }else{ return array(266,266); } } add_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size'); ``` This function does what I expected but I was wondering if there is any better method to call the custom post type "slider" without touching the others. Thanks in advance
[`admin_post_thumbnail_size`](https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_size/) takes three parameters: 1. $thumb\_size: selected Thumb Size if you do nothing in the filter. 2. $thumbnail\_id: Thumbnail attachment ID. 3. $post: associated WP\_Post instance So you may make use of these parameters to have a better control in your CODE. Use the CODE like below: ``` function custom_admin_thumb_size( $thumb_size, $thumbnail_id, $post ) { if( 'slider' === $post->post_type ) { return array( 1000, 400 ); } return $thumb_size; } add_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size', 10, 3); ```
262,227
<p>I am trying to retrieve all the post associated with my custom taxonomy term. My custom taxonomy is "Stores". I am using the following code.</p> <pre><code>$posts = get_posts(array( 'post_type' =&gt; 'coupon', 'numberposts' =&gt; -1, 'post_status' =&gt; array('publish', 'unreliable', 'draft'), 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'stores', 'field' =&gt; 'name', 'terms' =&gt; 'New Store', 'include_children' =&gt; false ) ) )); </code></pre> <p>My taxonomy term name is "New Store". Just because it has a space in the title I couldn't get any posts associated with it. I tried the same code on a taxonomy term without a space in the title and it worked.</p> <p>Any help will be appreciated. Thanks.</p>
[ { "answer_id": 262228, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 1, "selected": false, "text": "<p>There is no filter to do this for just a certain post_type but you can use <code>get_post_type( esc_attr( $_GET['post'] ) )</code> to save 1 line of code basically.</p>\n\n<p>You can also take out the else statement since your if statement has a return it won't reach after the if anyway. Other than that this is basically what you do.</p>\n\n<pre><code>function custom_admin_thumb_size( $thumb_size ){\n\n if( 'slider' == get_post_type( esc_attr( $_GET['post'] ) ) ) {\n\n return array( 1000, 400 );\n\n }\n\n return array( 266, 266);\n\n}\nadd_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size' );\n</code></pre>\n" }, { "answer_id": 262233, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_size/\" rel=\"nofollow noreferrer\"><code>admin_post_thumbnail_size</code></a> takes three parameters:</p>\n\n<ol>\n<li><p>$thumb_size: selected Thumb Size if you do nothing in the filter.</p></li>\n<li><p>$thumbnail_id: Thumbnail attachment ID.</p></li>\n<li><p>$post: associated WP_Post instance</p></li>\n</ol>\n\n<p>So you may make use of these parameters to have a better control in your CODE. Use the CODE like below:</p>\n\n<pre><code>function custom_admin_thumb_size( $thumb_size, $thumbnail_id, $post ) {\n if( 'slider' === $post-&gt;post_type ) {\n return array( 1000, 400 );\n }\n\n return $thumb_size;\n}\nadd_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size', 10, 3);\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110516/" ]
I am trying to retrieve all the post associated with my custom taxonomy term. My custom taxonomy is "Stores". I am using the following code. ``` $posts = get_posts(array( 'post_type' => 'coupon', 'numberposts' => -1, 'post_status' => array('publish', 'unreliable', 'draft'), 'tax_query' => array( array( 'taxonomy' => 'stores', 'field' => 'name', 'terms' => 'New Store', 'include_children' => false ) ) )); ``` My taxonomy term name is "New Store". Just because it has a space in the title I couldn't get any posts associated with it. I tried the same code on a taxonomy term without a space in the title and it worked. Any help will be appreciated. Thanks.
[`admin_post_thumbnail_size`](https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_size/) takes three parameters: 1. $thumb\_size: selected Thumb Size if you do nothing in the filter. 2. $thumbnail\_id: Thumbnail attachment ID. 3. $post: associated WP\_Post instance So you may make use of these parameters to have a better control in your CODE. Use the CODE like below: ``` function custom_admin_thumb_size( $thumb_size, $thumbnail_id, $post ) { if( 'slider' === $post->post_type ) { return array( 1000, 400 ); } return $thumb_size; } add_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size', 10, 3); ```
262,275
<p>I want to conditionally add a body class depending on what template is being used.</p> <p>I can't figure out why the following code is not working...</p> <pre><code>function damsonhomes_body_classes( $classes ) { if (is_page_template('single.php')) { $classes[] = 'sans-hero'; } return $classes; } add_filter( 'body_class', 'damsonhomes_body_classes'); </code></pre> <p>Thanks all</p>
[ { "answer_id": 262278, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/is_page_template/\" rel=\"nofollow noreferrer\"><code>is_page_template()</code></a> function is the incorrect function to use in this case as it checks against <a href=\"https://codex.wordpress.org/Pages#Page_Templates\" rel=\"nofollow noreferrer\">Page Templates</a> and <code>single.php</code> is just a normal template, not a page specific one, usually meant for posts.</p>\n\n<p>The function you're probably looking to use instead is <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\"><code>is_single( $optional_posttype )</code></a> which will look for singular view of a post type, <code>post</code> by default.</p>\n\n<pre><code>if( is_single() ) {\n /** ... **/\n}\n</code></pre>\n\n<p>You could also check against the basename if you <em>really</em> wanted to:</p>\n\n<pre><code>global $template;\n$template_slug = basename( $template );\n\nif( 'single.php' === $template_slug ) {\n /** ... **/\n}\n</code></pre>\n" }, { "answer_id": 262282, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Note that <code>single.php</code> is a template file for a single post, that you would not normally use for pages.</p>\n\n<p>Also note that <a href=\"https://developer.wordpress.org/reference/functions/get_body_class/\" rel=\"nofollow noreferrer\"><code>get_body_class()</code></a> is already adding some info regarding the current page template:</p>\n\n<pre><code>if ( is_page_template() ) {\n $classes[] = \"{$post_type}-template\";\n\n $template_slug = get_page_template_slug( $post_id );\n $template_parts = explode( '/', $template_slug );\n\n foreach ( $template_parts as $part ) {\n $classes[] = \"{$post_type}-template-\" . sanitize_html_class(\n str_replace( array( '.', '/' ), '-', basename( $part, '.php' ) ) );\n }\n $classes[] = \"{$post_type}-template-\" . sanitize_html_class(\n str_replace( '.', '-', $template_slug ) );\n} else {\n $classes[] = \"{$post_type}-template-default\";\n}\n</code></pre>\n\n<p>If you meant to target <code>single.php</code> then in many cases we don't need to add a custom body class for that, because <a href=\"https://developer.wordpress.org/reference/functions/get_body_class/\" rel=\"nofollow noreferrer\"><code>get_body_class()</code></a> already adds the following classes in that case:</p>\n\n<pre><code>if ( is_single() ) {\n $classes[] = 'single';\n if ( isset( $post-&gt;post_type ) ) {\n $classes[] = 'single-' . sanitize_html_class( $post-&gt;post_type, $post_id );\n $classes[] = 'postid-' . $post_id;\n\n // Post Format\n if ( post_type_supports( $post-&gt;post_type, 'post-formats' ) ) {\n $post_format = get_post_format( $post-&gt;ID );\n\n if ( $post_format &amp;&amp; !is_wp_error($post_format) )\n $classes[] = 'single-format-' . sanitize_html_class( $post_format );\n else\n $classes[] = 'single-format-standard';\n }\n }\n}\n</code></pre>\n\n<p>So I would say that in most cases the default body classes are sufficient.</p>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262275", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57057/" ]
I want to conditionally add a body class depending on what template is being used. I can't figure out why the following code is not working... ``` function damsonhomes_body_classes( $classes ) { if (is_page_template('single.php')) { $classes[] = 'sans-hero'; } return $classes; } add_filter( 'body_class', 'damsonhomes_body_classes'); ``` Thanks all
The [`is_page_template()`](https://developer.wordpress.org/reference/functions/is_page_template/) function is the incorrect function to use in this case as it checks against [Page Templates](https://codex.wordpress.org/Pages#Page_Templates) and `single.php` is just a normal template, not a page specific one, usually meant for posts. The function you're probably looking to use instead is [`is_single( $optional_posttype )`](https://developer.wordpress.org/reference/functions/is_single/) which will look for singular view of a post type, `post` by default. ``` if( is_single() ) { /** ... **/ } ``` You could also check against the basename if you *really* wanted to: ``` global $template; $template_slug = basename( $template ); if( 'single.php' === $template_slug ) { /** ... **/ } ```
262,286
<p>I'm trying to load the 3 latests posts on my homepage. I'm an utter novice but I <em>seem</em> to be making progress.</p> <p>This is my code (below). At the minute each post has a title of "Home", I understand that is because the homepage is the main query?</p> <pre><code>&lt;?php $latest_blog_posts = new WP_Query( array( 'posts_per_page' =&gt; 3 ) ); if ( $latest_blog_posts-&gt;have_posts() ) : while ( $latest_blog_posts-&gt;have_posts() ) : $latest_blog_posts-&gt;the_post(); get_template_part('loop'); endwhile; endif; ?&gt; </code></pre> <p>So how would I amend this code so it pulls in the 3 latest posts from the blog using loop.php?</p> <p>I also having a Custom Post Type which uses a different page/loop. But I assume once this is working it would just be a matter of swapping the 'loop' for 'loop-2' to get that working using the same code?</p> <p>Hope someone can help with this. It's one step forward, two steps back at the minute for me!</p> <p><strong>EDIT</strong></p> <p>Contents of <code>loop.php</code> as requested in reply :)</p> <pre><code>&lt;?php if (have_posts()): while (have_posts()) : the_post(); ?&gt; &lt;!-- article --&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;!-- post thumbnail --&gt; &lt;?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;" class="h-entry__image-link"&gt; &lt;?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;!-- /post thumbnail --&gt; &lt;!-- post title --&gt; &lt;h2 class="p-name"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h2&gt; &lt;!-- /post title --&gt; &lt;!-- post details --&gt; &lt;time datetime="&lt;?php the_time('Y-m-j'); ?&gt;" class="dt-published"&gt;&lt;?php the_time('jS F Y'); ?&gt;&lt;/time&gt; &lt;!-- /post details --&gt; &lt;?php html5wp_summary('html5wp_index'); // Build your custom callback length in functions.php ?&gt; &lt;p&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;" class="arrow-link"&gt;Read the full article&lt;/a&gt;&lt;/p&gt; &lt;?php edit_post_link(); ?&gt; &lt;/article&gt; &lt;!-- /article --&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;!-- article --&gt; &lt;article&gt; &lt;h2&gt;&lt;?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?&gt;&lt;/h2&gt; &lt;/article&gt; &lt;!-- /article --&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 262287, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>This is how you would do it. You're loop is based on being in an archive or index page. (or home)</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 3,\n 'post_type' =&gt; 'post', //choose post type here\n 'order' =&gt; 'DESC',\n);\n// query\n$the_query = new WP_Query( $args );\n\n\nif( $the_query-&gt;have_posts() ):\n while( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n get_template_part('loop');\n endwhile; \nelse :\n\nendif; \n</code></pre>\n\n<p>revised code running full query without the content-part.php</p>\n\n<pre><code>// WP_Query arguments\n$args = array(\n 'posts_per_page' =&gt; 3,\n 'post_type' =&gt; 'post', //choose post type here\n 'order' =&gt; 'DESC',\n);\n\n// The Query\n$query = new WP_Query( $args );\n\n// The Loop\nif ( $query-&gt;have_posts() ) {\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n?&gt;\n &lt;!-- article --&gt;\n&lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n\n &lt;!-- post thumbnail --&gt;\n &lt;?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\" class=\"h-entry__image-link\"&gt;\n &lt;?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?&gt;\n &lt;/a&gt;\n &lt;?php endif; ?&gt;\n &lt;!-- /post thumbnail --&gt;\n\n &lt;!-- post title --&gt;\n &lt;h2 class=\"p-name\"&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;/h2&gt;\n &lt;!-- /post title --&gt;\n\n &lt;!-- post details --&gt;\n &lt;time datetime=\"&lt;?php the_time('Y-m-j'); ?&gt;\" class=\"dt-published\"&gt;&lt;?php the_time('jS F Y'); ?&gt;&lt;/time&gt;\n &lt;!-- /post details --&gt;\n\n &lt;?php html5wp_summary('html5wp_index'); // Build your custom callback length in functions.php ?&gt;\n\n &lt;p&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\" class=\"arrow-link\"&gt;Read the full article&lt;/a&gt;&lt;/p&gt;\n\n &lt;?php edit_post_link(); ?&gt;\n\n&lt;/article&gt;\n&lt;!-- /article --&gt;\n&lt;?php\n }\n} else {\n // no posts found\n}\n\n// Restore original Post Data\nwp_reset_postdata();\n</code></pre>\n\n<p>i can't fully test it because of the functions being called by your theme, but try it out.</p>\n\n<p>If this does work you you can pull out the article content. Replace all the content in your current loop.php with the content above but only from</p>\n\n<pre><code>&lt;!-- article --&gt;\n</code></pre>\n\n<p>to </p>\n\n<pre><code>&lt;!-- /article --&gt;\n</code></pre>\n\n<p>Since that would be in your new loop.php, you'll take it out of the main page.</p>\n" }, { "answer_id": 262500, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>&lt;?php\n $latest_blog_posts = new WP_Query( array( 'posts_per_page' =&gt; 3, 'offset' =&gt; 3 ) );\n if ( $latest_blog_posts-&gt;have_posts() ) : while ( $latest_blog_posts-&gt;have_posts() ) : $latest_blog_posts-&gt;the_post();\n get_template_part('loop');\n endwhile; endif;\n?&gt;\n</code></pre>\n\n<p>For more information about WP Query with custom parameters check this <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">link</a></p>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116827/" ]
I'm trying to load the 3 latests posts on my homepage. I'm an utter novice but I *seem* to be making progress. This is my code (below). At the minute each post has a title of "Home", I understand that is because the homepage is the main query? ``` <?php $latest_blog_posts = new WP_Query( array( 'posts_per_page' => 3 ) ); if ( $latest_blog_posts->have_posts() ) : while ( $latest_blog_posts->have_posts() ) : $latest_blog_posts->the_post(); get_template_part('loop'); endwhile; endif; ?> ``` So how would I amend this code so it pulls in the 3 latest posts from the blog using loop.php? I also having a Custom Post Type which uses a different page/loop. But I assume once this is working it would just be a matter of swapping the 'loop' for 'loop-2' to get that working using the same code? Hope someone can help with this. It's one step forward, two steps back at the minute for me! **EDIT** Contents of `loop.php` as requested in reply :) ``` <?php if (have_posts()): while (have_posts()) : the_post(); ?> <!-- article --> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- post thumbnail --> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="h-entry__image-link"> <?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <!-- /post thumbnail --> <!-- post title --> <h2 class="p-name"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <!-- /post title --> <!-- post details --> <time datetime="<?php the_time('Y-m-j'); ?>" class="dt-published"><?php the_time('jS F Y'); ?></time> <!-- /post details --> <?php html5wp_summary('html5wp_index'); // Build your custom callback length in functions.php ?> <p><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="arrow-link">Read the full article</a></p> <?php edit_post_link(); ?> </article> <!-- /article --> <?php endwhile; ?> <?php else: ?> <!-- article --> <article> <h2><?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?></h2> </article> <!-- /article --> <?php endif; ?> ```
This is how you would do it. You're loop is based on being in an archive or index page. (or home) ``` $args = array( 'posts_per_page' => 3, 'post_type' => 'post', //choose post type here 'order' => 'DESC', ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); get_template_part('loop'); endwhile; else : endif; ``` revised code running full query without the content-part.php ``` // WP_Query arguments $args = array( 'posts_per_page' => 3, 'post_type' => 'post', //choose post type here 'order' => 'DESC', ); // The Query $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> <!-- article --> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- post thumbnail --> <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="h-entry__image-link"> <?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?> </a> <?php endif; ?> <!-- /post thumbnail --> <!-- post title --> <h2 class="p-name"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> </h2> <!-- /post title --> <!-- post details --> <time datetime="<?php the_time('Y-m-j'); ?>" class="dt-published"><?php the_time('jS F Y'); ?></time> <!-- /post details --> <?php html5wp_summary('html5wp_index'); // Build your custom callback length in functions.php ?> <p><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="arrow-link">Read the full article</a></p> <?php edit_post_link(); ?> </article> <!-- /article --> <?php } } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ``` i can't fully test it because of the functions being called by your theme, but try it out. If this does work you you can pull out the article content. Replace all the content in your current loop.php with the content above but only from ``` <!-- article --> ``` to ``` <!-- /article --> ``` Since that would be in your new loop.php, you'll take it out of the main page.
262,299
<p>Is there anyway to load a custom style in specific taxonomy pages? for example these two pages: </p> <pre><code>wp-admin/edit-tags.php?taxonomy=news-category&amp;post_type=news wp-admin/term.php?taxonomy=news-category&amp;.. </code></pre> <p>I added a style to admin but other pager got edited too, how can we load the style when in these two pages of custom post type taxonomy?</p>
[ { "answer_id": 262302, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 4, "selected": true, "text": "<p>You can do it like this:</p>\n\n<pre><code>add_action ('admin_enqueue_scripts', 'wpse_style_tax') ;\n\nfunction\nwpse_style_tax ()\n{\n // these 3 globals are set during execution of {edit-tags,term}.php\n global $pagenow, $typenow, $taxnow ;\n\n if (!in_array ($pagenow, array ('edit-tags.php', 'term.php')) {\n return ;\n }\n if ('news' != $typenow) {\n return ;\n }\n if ('news-category' != $taxnow) {\n return ;\n }\n\n wp_enqueue_style ('wpse_my_handle', 'path_to_css_file', ...) ;\n\n return ;\n}\n</code></pre>\n" }, { "answer_id": 262312, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>I know there's already an accepted answer, but here's another way to accomplish the same thing using hooks.</p>\n\n<pre><code>//* Make sure we're on the load edit tags admin page\nadd_action( 'load-edit-tags.php', 'wpse_262299_edit_tags' );\nadd_action( 'load-term.php', 'wpse_262299_edit_tags' );\n\nfunction wpse_262299_edit_tags() {\n\n //* Return early if not the news post type\n if( 'news' !== get_current_screen()-&gt;post_type ) {\n return;\n }\n\n $taxonomies = [ 'news-category', 'other-taxonomy' ];\n //* Add actions to $taxonomy_pre_add_form and $taxonomy_pre_edit_form\n array_filter( $taxonomies, function( $taxonomy ) {\n add_action( \"{$taxonomy}_pre_add_form\", 'wpse_262299_enqueue_style' );\n add_action( \"{$taxonomy}_pre_edit_form\", 'wpse_262299_enqueue_style' );\n });\n}\n\nfunction wpse_262299_enqueue_style( $taxonomy ) {\n //* All the logic has already been done, do enqueue the style\n wp_enqueue_style( 'wpse-262299', plugins_url( 'style.css', __FILE__ ) );\n}\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262299", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116836/" ]
Is there anyway to load a custom style in specific taxonomy pages? for example these two pages: ``` wp-admin/edit-tags.php?taxonomy=news-category&post_type=news wp-admin/term.php?taxonomy=news-category&.. ``` I added a style to admin but other pager got edited too, how can we load the style when in these two pages of custom post type taxonomy?
You can do it like this: ``` add_action ('admin_enqueue_scripts', 'wpse_style_tax') ; function wpse_style_tax () { // these 3 globals are set during execution of {edit-tags,term}.php global $pagenow, $typenow, $taxnow ; if (!in_array ($pagenow, array ('edit-tags.php', 'term.php')) { return ; } if ('news' != $typenow) { return ; } if ('news-category' != $taxnow) { return ; } wp_enqueue_style ('wpse_my_handle', 'path_to_css_file', ...) ; return ; } ```
262,300
<p>I'm saving my CPT in <a href="https://github.com/nanodesigns/nanosupport/blob/v0.3.3/includes/ns-set-environment.php#L355-L377" rel="nofollow noreferrer"><code>private</code> status</a>. So the transition would be from <code>pending</code> to <code>private</code>. Thing is, when the post was first submitted and is pending there's a date of that submission on the <code>post_date</code> field in db. But when the post got published, the date updated with the current date.</p> <p>I want to keep the original date of the submission of the post even the post privately published later.</p> <p>So I did something like below:</p> <pre><code>function mycpt_keep_pending_date_on_publishing( $new_status, $old_status, $post ) { if( 'mycpt' === $post-&gt;post_type &amp;&amp; 'pending' === $old_status &amp;&amp; 'private' === $new_status ) : $pending_datetime = get_post_field( 'post_date', $post-&gt;ID, 'raw' ); // Update the post $modified_post = array( 'ID' =&gt; $post-&gt;ID, 'post_date' =&gt; $pending_datetime, 'post_date_gmt' =&gt; get_gmt_from_date( $pending_datetime ) ); // Update the post into the database wp_update_post( $modified_post ); endif; } add_action( 'transition_post_status', 'mycpt_keep_pending_date_on_publishing' ); </code></pre> <p>But it's not working. What can be the reason?</p>
[ { "answer_id": 262306, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 3, "selected": true, "text": "<p>@Howdy_McGee is on the right track in his comment: by the time <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status\" rel=\"nofollow noreferrer\">transition_post_status</a> is fired, the post has already been updated (i.e., written to the db).</p>\n\n<p>What you need to do is hook into <a href=\"https://developer.wordpress.org/reference/hooks/wp_insert_post_data/\" rel=\"nofollow noreferrer\">wp_insert_post_data</a>, <strong>instead of</strong> <code>transition_post_status</code>, as follows:</p>\n\n<pre><code>add_filter ('wp_insert_post_data', 'mycpt_keep_pending_date_on_publishing', 10, 2) ;\n\nfunction\nmycpt_keep_pending_date_on_publishing ($data, $postarr)\n{\n if ($data['post_type'] != 'mycpt') {\n return ($data) ;\n }\n\n // this check amounts to the same thing as transition_post_status(private, pending)\n if ('private' != $data['post_status'] || 'pending' != $postarr['original_post_status']) {\n return ($data) ;\n }\n\n $pending_datetime = get_post_field ('post_date', $data['ID'], 'raw') ;\n\n $data['post_date'] = $pending_datetime ;\n $data['post_date_gmt'] = get_gmt_from_date ($pending_datetime) ;\n\n return ($data) ;\n}\n</code></pre>\n\n<p><strong>Note:</strong> I used the same function name as you did, but the body of that function is different.</p>\n" }, { "answer_id": 262328, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 1, "selected": false, "text": "<p>In addition to the other answers, here's a small plugin that makes sure the code is only executed once. In case the data is reset by a plugin running later, try using <code>PHP_INT_MAX -1</code> as priority (not for publicly distributed plugins). In this case, you will have to set the same value for <code>remove_filter()</code>, else the callback will not get removed.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: (WPSE) Static post date\n * Description: Keep the post date as the original date for posts published as private\n */\nnamespace WPSE;\n\nadd_filter( 'wp_insert_post_data', '\\WPSE\\save', 10, 2 );\nfunction save( $post, $raw ) {\n if ( ! in_array( $post['post_status'], [ 'private', 'pending', ] ) ) {\n return $post;\n }\n if ( 'your_post_type' !== $post['post_type'] ) {\n return $post;\n }\n\n $date = get_post_field( 'post_date', $post['ID'], 'raw' );\n $post['post_date'] = $date;\n $post['post_date_gmt'] = get_gmt_from_date( $date );\n\n return $post;\n}\n\nadd_action( 'transition_post_status', function() {\n # Make sure above callback is only triggered once\n remove_filter( 'wp_insert_post_data', '\\WPSE\\save' );\n} );\n</code></pre>\n\n<p>IIRC your main problem with above code is, that the <code>private_to_published</code> filter was deprecated, so there is nothing specific enough <strong>aside from a post type status filter</strong>. Try the following plugin and see if it works (if your post type really is named <code>mycpt</code>):</p>\n\n<pre><code>&lt;?php\n/* Plugin Name: (WPSE) Test post type status actions */\nadd_action( 'private_mycpt', function( $ID, \\WP_Post $post ) {\n var_dump( current_filter() );\n exit;\n}, 10, 2 );\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262300", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm saving my CPT in [`private` status](https://github.com/nanodesigns/nanosupport/blob/v0.3.3/includes/ns-set-environment.php#L355-L377). So the transition would be from `pending` to `private`. Thing is, when the post was first submitted and is pending there's a date of that submission on the `post_date` field in db. But when the post got published, the date updated with the current date. I want to keep the original date of the submission of the post even the post privately published later. So I did something like below: ``` function mycpt_keep_pending_date_on_publishing( $new_status, $old_status, $post ) { if( 'mycpt' === $post->post_type && 'pending' === $old_status && 'private' === $new_status ) : $pending_datetime = get_post_field( 'post_date', $post->ID, 'raw' ); // Update the post $modified_post = array( 'ID' => $post->ID, 'post_date' => $pending_datetime, 'post_date_gmt' => get_gmt_from_date( $pending_datetime ) ); // Update the post into the database wp_update_post( $modified_post ); endif; } add_action( 'transition_post_status', 'mycpt_keep_pending_date_on_publishing' ); ``` But it's not working. What can be the reason?
@Howdy\_McGee is on the right track in his comment: by the time [transition\_post\_status](https://developer.wordpress.org/reference/hooks/transition_post_status) is fired, the post has already been updated (i.e., written to the db). What you need to do is hook into [wp\_insert\_post\_data](https://developer.wordpress.org/reference/hooks/wp_insert_post_data/), **instead of** `transition_post_status`, as follows: ``` add_filter ('wp_insert_post_data', 'mycpt_keep_pending_date_on_publishing', 10, 2) ; function mycpt_keep_pending_date_on_publishing ($data, $postarr) { if ($data['post_type'] != 'mycpt') { return ($data) ; } // this check amounts to the same thing as transition_post_status(private, pending) if ('private' != $data['post_status'] || 'pending' != $postarr['original_post_status']) { return ($data) ; } $pending_datetime = get_post_field ('post_date', $data['ID'], 'raw') ; $data['post_date'] = $pending_datetime ; $data['post_date_gmt'] = get_gmt_from_date ($pending_datetime) ; return ($data) ; } ``` **Note:** I used the same function name as you did, but the body of that function is different.
262,301
<p>I am trying to get rig of the <code>Disqus</code> script on my front page, but unfortunately I cannot manage how to do this.</p> <p>Here is a little story of the steps I've done.</p> <ol> <li><p>Find the script name in the source code files of the plugin</p> <p>wp_register_script( 'dsq_count_script', plugins_url( '/media/js/count.js', <strong>FILE</strong> ) ); wp_localize_script( 'dsq_count_script', 'countVars', $count_vars ); wp_enqueue_script( 'dsq_count_script', plugins_url( '/media/js/count.js', <strong>FILE</strong> ) ); </p></li> <li><p>Add an action for the <code>wp_print_scripts</code> hook</p> <pre><code>add_action('wp_print_scripts', array($this, 'deregister_unused_scripts'), 100); </code></pre></li> <li><p>Implement <code>deregister_unused_scripts</code> function</p> <pre><code>public function deregister_unused_scripts() { wp_dequeue_script('dsq_count_script'); wp_deregister_script('dsq_count_script'); } </code></pre></li> </ol> <p>Still doesn't work. </p> <p>I also tried another hook</p> <pre><code> add_action('wp_footer', array($this, 'deregister_unused_scripts'), 100); </code></pre> <p>But this didn't help as well, I still get an output in the footer.</p> <pre><code>&lt;script type='text/javascript'&gt; /* &lt;![CDATA[ */ var countVars = {"disqusShortname":"myname"}; /* ]]&gt; */ &lt;/script&gt; &lt;script type='text/javascript' src='http://myurl.net/wp-content/plugins/disqus-comment-system/media/js/count.js?ver=4.7.3'&gt;&lt;/script&gt; </code></pre> <p>What can be wrong ? </p> <p><strong>EDIT</strong></p> <p>Here is the action used to register the plugin script. </p> <pre><code>add_action('wp_footer', 'dsq_output_footer_comment_js'); </code></pre>
[ { "answer_id": 262305, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 5, "selected": true, "text": "<p>When attempting to dequeue a script, we need to hook in after the script is enqueued, but before it's printed. In this case, the Disqus plugin is using the <code>wp_footer</code> hook at a priority of 10 to enqueue the scripts. The footer scripts get printed during <code>wp_footer</code> at a priority of 20. So we should be able to hook into <code>wp_footer</code> at a priority of 11 and dequeue the script.</p>\n\n<pre><code>add_action( 'wp_footer', 'wpse_262301_wp_footer', 11 );\nfunction wpse_262301_wp_footer() { \n wp_dequeue_script( 'dsq_count_script' ); \n}\n</code></pre>\n" }, { "answer_id": 372782, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 1, "selected": false, "text": "<p>add_action('wp_footer') didn't work for me, but it did 'wp_enqueue_scripts':</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_deregister_scripts', 1000 );\n function my_deregister_scripts() {\n wp_deregister_script( 'wdm_script' );\n wp_dequeue_script('wdm_script');\n wp_deregister_script( 'enjoyHint_script' );\n wp_dequeue_script('enjoyHint_script');\n}\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93387/" ]
I am trying to get rig of the `Disqus` script on my front page, but unfortunately I cannot manage how to do this. Here is a little story of the steps I've done. 1. Find the script name in the source code files of the plugin wp\_register\_script( 'dsq\_count\_script', plugins\_url( '/media/js/count.js', **FILE** ) ); wp\_localize\_script( 'dsq\_count\_script', 'countVars', $count\_vars ); wp\_enqueue\_script( 'dsq\_count\_script', plugins\_url( '/media/js/count.js', **FILE** ) ); 2. Add an action for the `wp_print_scripts` hook ``` add_action('wp_print_scripts', array($this, 'deregister_unused_scripts'), 100); ``` 3. Implement `deregister_unused_scripts` function ``` public function deregister_unused_scripts() { wp_dequeue_script('dsq_count_script'); wp_deregister_script('dsq_count_script'); } ``` Still doesn't work. I also tried another hook ``` add_action('wp_footer', array($this, 'deregister_unused_scripts'), 100); ``` But this didn't help as well, I still get an output in the footer. ``` <script type='text/javascript'> /* <![CDATA[ */ var countVars = {"disqusShortname":"myname"}; /* ]]> */ </script> <script type='text/javascript' src='http://myurl.net/wp-content/plugins/disqus-comment-system/media/js/count.js?ver=4.7.3'></script> ``` What can be wrong ? **EDIT** Here is the action used to register the plugin script. ``` add_action('wp_footer', 'dsq_output_footer_comment_js'); ```
When attempting to dequeue a script, we need to hook in after the script is enqueued, but before it's printed. In this case, the Disqus plugin is using the `wp_footer` hook at a priority of 10 to enqueue the scripts. The footer scripts get printed during `wp_footer` at a priority of 20. So we should be able to hook into `wp_footer` at a priority of 11 and dequeue the script. ``` add_action( 'wp_footer', 'wpse_262301_wp_footer', 11 ); function wpse_262301_wp_footer() { wp_dequeue_script( 'dsq_count_script' ); } ```
262,310
<p>One of the pages on my company's website, the hero is displaying incorrectly. It seems that the news page is missing an "h3". Where is the document where i can edit this. an example of the difference is below.</p> <p>So the careers page has it set up like so:</p> <pre><code>&lt;div class="hero__content"&gt; &lt;div class="hero__content-wrap content"&gt; &lt;div class="hero__description" style="opacity: 1;"&gt; &lt;h3 class="hero__title" style="color: black; font-size: 16px; opacity: 1; transform: matrix(1, 0, 0, 1, 0, 0);"&gt; &lt;div class="hero-page-title"&gt;CAREERS&lt;/div&gt; &lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and news is like this:</p> <pre><code>&lt;div class="hero__content"&gt; &lt;div class="hero__content-wrap content"&gt; &lt;div class="hero__description" style="transform: matrix(1, 0, 0, 1, 0, 0); opacity: 1;"&gt; &lt;div class="hero-page-title"&gt;NEWS&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 262311, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>It depends on your theme. To find out exactly which file to edit, add the following code to your <code>header.php</code> file inside <code>/wp-content/themes/nameofyourtheme</code>:</p>\n\n<pre><code>&lt;!-- &lt;?php global $template; print_r($template); ?&gt; --&gt;\n</code></pre>\n\n<p>You can then view the page in question's source and see a comment that tells you the name of the file, which will also be somewhere inside your theme's folder structure.</p>\n\n<p>Once you open that file, it is possible that it's calling another file - WordPress themes sometimes use template parts - if this is the case, the PHP code in the area you're troubleshooting will have a call to <code>get_template_part</code> and you'll need to find that separate PHP file. It sounds like this may not be the case though since it differs from page to page.</p>\n" }, { "answer_id": 262323, "author": "Ray", "author_id": 101989, "author_profile": "https://wordpress.stackexchange.com/users/101989", "pm_score": 1, "selected": false, "text": "<p>Another alternative would be to install the <code>What The File</code> plugin.</p>\n\n<p>I've used it many times to narrow down where a particular template issue is.</p>\n\n<p>Great plugin IMO</p>\n" }, { "answer_id": 263055, "author": "Jess Mann", "author_id": 117278, "author_profile": "https://wordpress.stackexchange.com/users/117278", "pm_score": 0, "selected": false, "text": "<p>This is probably more complicated than you're prepared for. </p>\n\n<p>I'm going to guess this is coming from a plugin. The trouble is, even if you identify the exact part of the plugin's code in question, editing the plugin directly would not be advisable, because the next update would break anything you changed. </p>\n\n<p>There's probably a reason the h3 is being shown on one page and not the other. Can you investigate the plugin settings to see why that might be? Is there a checkbox that says \"show title\" or something like that? </p>\n\n<p>If you really need to find the part of the code, another option is to \"grep\" for it. This will only work if you have ssh access, or access to a unix command line (like cygwin). </p>\n\n<p>Issue this command in your wp-content folder:</p>\n\n<pre><code>grep -R \"class=\\\"hero__title\" *\n</code></pre>\n\n<p>If you can share details about the plugins you're using, we might be able to help more. Good luck!</p>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116845/" ]
One of the pages on my company's website, the hero is displaying incorrectly. It seems that the news page is missing an "h3". Where is the document where i can edit this. an example of the difference is below. So the careers page has it set up like so: ``` <div class="hero__content"> <div class="hero__content-wrap content"> <div class="hero__description" style="opacity: 1;"> <h3 class="hero__title" style="color: black; font-size: 16px; opacity: 1; transform: matrix(1, 0, 0, 1, 0, 0);"> <div class="hero-page-title">CAREERS</div> </h3> </div> </div> </div> ``` and news is like this: ``` <div class="hero__content"> <div class="hero__content-wrap content"> <div class="hero__description" style="transform: matrix(1, 0, 0, 1, 0, 0); opacity: 1;"> <div class="hero-page-title">NEWS</div> </div> </div> </div> ```
It depends on your theme. To find out exactly which file to edit, add the following code to your `header.php` file inside `/wp-content/themes/nameofyourtheme`: ``` <!-- <?php global $template; print_r($template); ?> --> ``` You can then view the page in question's source and see a comment that tells you the name of the file, which will also be somewhere inside your theme's folder structure. Once you open that file, it is possible that it's calling another file - WordPress themes sometimes use template parts - if this is the case, the PHP code in the area you're troubleshooting will have a call to `get_template_part` and you'll need to find that separate PHP file. It sounds like this may not be the case though since it differs from page to page.
262,319
<p>I am trying to add a style to the header, using this method the style only loads on single posts but if I use a shortcode to load the post content that style does not load in the header: </p> <pre><code>add_action( 'wp_head', 'output_styles') function output_styles($base_ID){ $global post; echo '&lt;style type="text/css"&gt;'. get_post_meta($post-&gt;ID, 'append_css') .'&lt;/style&gt;'; } </code></pre> <p>in my shortcode I am passing the ID of the post, if I call the <code>ouput_styles</code> functions from shortcode function : </p> <pre><code>output_styles($pass_id); </code></pre> <p>then the content of <code>output_style</code> is printed but it is not in the header. It is right before the shortcode output.</p> <p>How can I output the style in the header when using shortcodes?</p>
[ { "answer_id": 262324, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 1, "selected": false, "text": "<p>In this case, <a href=\"https://developer.wordpress.org/reference/functions/has_shortcode/\" rel=\"nofollow noreferrer\">has_shortcode()</a> is your friend.</p>\n\n<p>First, we hook into <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_styles/\" rel=\"nofollow noreferrer\">wp_print_styles</a>, instead of <code>wp_head</code>. In the func we hook\nwe check if the post contains our shortcode. If it does, we get the CSS we want and output\nit as an inlined <code>&lt;style&gt;</code>.</p>\n\n<pre><code>add_action ('wp_print_styles', 'wpse_enqueue_shortcode_css') ;\n\nfunction\nwpse_enqueue_shortcode_css ()\n{\n global $post ;\n\n if (is_single () &amp;&amp; has_shortcode ($post-&gt;post_content, 'my_shortcode')) {\n $append_css = get_post_meta ($post-&gt;ID, 'append_css', true) ;\n\n echo &lt;&lt;&lt;EOF\n &lt;style type='text/css'&gt;\n $append_css\n &lt;/style&gt;\nEOF;\n }\n\n return ;\n}\n</code></pre>\n" }, { "answer_id": 262338, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 0, "selected": false, "text": "<p>@bosco, thanx for the comment...I misunderstood what @Alen was trying to accomplish (the <code>global $post</code> in the code included in the question threw me off).</p>\n\n<p>If my understanding is now correct, the following should do the trick (altho, it's a bit ugly). It works by hooking into <code>wp_print_styles</code> <strong>within</strong> the function that processes the shortcode.</p>\n\n<pre><code>add_shortcode ('my_shortcode', 'my_shortcode') ;\n\nfunction\nmy_shortcode ($atts)\n{\n $defaults = array (\n 'id' =&gt; '',\n // other atts for the shortcode\n ) ;\n $atts = shortcode_atts ($defaults, $atts) ;\n\n if (!empty ($atts['id'])) {\n global $my_shortcode_css ;\n\n // grab the CSS from the post whose ID was passed in the 'id' attribute of\n // my_shortcode, e.g., [my_shortcode id='123']\n // and store it in a global\n $my_shortcode_css = get_post_meta ($atts['id'], 'append_css', true) ;\n\n // no need to hook into wp_print_styles IF we don't have any CSS to output\n if (!empty ($my_shortcode_css)) {\n // hook into wp_print_styles with an anonymous func\n add_action ('wp_print_styles', function () {\n global $my_shortcode_css ;\n\n if (empty ($my_shortcode_css)) {\n return ;\n }\n\n echo &lt;&lt;&lt;EOF\n &lt;style type='text/css'&gt;\n $my_shortcode_css\n &lt;/style&gt;\nEOF;\n\n // clean up, since we no longer need this global\n unset ($my_shortcode_css) ;\n }) ;\n }\n }\n\n // insert code to produce the output of the shortcode\n $output = ... ;\n\n return ($output) ;\n}\n</code></pre>\n\n<p><strong>Note:</strong> If you can conceive of <code>[my_shortcode]</code> being used more than once within a given post, it would probably be a good idea to add logic to the above to check whether CSS has already been output for a given post ID. I'll leave that as an \"exercise for the reader\" :-)</p>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262319", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116836/" ]
I am trying to add a style to the header, using this method the style only loads on single posts but if I use a shortcode to load the post content that style does not load in the header: ``` add_action( 'wp_head', 'output_styles') function output_styles($base_ID){ $global post; echo '<style type="text/css">'. get_post_meta($post->ID, 'append_css') .'</style>'; } ``` in my shortcode I am passing the ID of the post, if I call the `ouput_styles` functions from shortcode function : ``` output_styles($pass_id); ``` then the content of `output_style` is printed but it is not in the header. It is right before the shortcode output. How can I output the style in the header when using shortcodes?
In this case, [has\_shortcode()](https://developer.wordpress.org/reference/functions/has_shortcode/) is your friend. First, we hook into [wp\_print\_styles](https://developer.wordpress.org/reference/hooks/wp_print_styles/), instead of `wp_head`. In the func we hook we check if the post contains our shortcode. If it does, we get the CSS we want and output it as an inlined `<style>`. ``` add_action ('wp_print_styles', 'wpse_enqueue_shortcode_css') ; function wpse_enqueue_shortcode_css () { global $post ; if (is_single () && has_shortcode ($post->post_content, 'my_shortcode')) { $append_css = get_post_meta ($post->ID, 'append_css', true) ; echo <<<EOF <style type='text/css'> $append_css </style> EOF; } return ; } ```
262,326
<p>I have a "utility navigation" on the top of my website that currently has two links - one to our blog and the other to the weekly newsletter. We also do a radio show everyday at 5pm, as well as a rerun on Saturday at 7am and 7pm. During this time, I would like a third menu item to appear with a link to the podcast to listen live.</p> <p>Anyone have a clue on how to do this, without installing a plugin? I figured I would be able to edit the function but I have no idea how to program timers.. :(</p> <p>Any help is appreciated!</p>
[ { "answer_id": 262440, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": true, "text": "<p>Since you need to edit theme files, you'll first want to determine whether you're using a custom-built theme or something that was downloaded from somewhere. If it was downloaded from somewhere, you'll need to create a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> (basically, you just create a new <code>style.css</code> file which only needs to contain comments at the top, which let WordPress recognize it as a theme you can activate - and then you copy whichever file you're editing, probably <code>header.php</code>, into your theme and make edits there). This way whenever your main theme is updated your child theme will still apply your changes.</p>\n\n<p>Then, in header.php, you'll change code that should look something like this (it may be longer but will contain <code>wp_nav_menu</code>):</p>\n\n<pre><code>wp_nav_menu(array('theme_location' =&gt; 'header'));\n</code></pre>\n\n<p>to a conditional:</p>\n\n<pre><code>$weekdayShowStart = '17';\n$weekdayShowEnd = '18';\n$satFirstShowStart = '07';\n$satFirstShowEnd = '08';\n$satSecondShowStart = '19';\n$satSecondShowEnd = '20';\n$dayAndTime = current_time(\"N G\");\n$timestamp = explode(' ', $dayAndTime);\n$day = $timestamp[0];\n$hour = $timestamp[1];\nif(\n ($day &lt; 6 &amp;&amp; $hour &gt;= $weekdayShowStart &amp;&amp; $hour &lt; $weekdayShowEnd) ||\n ($day == 6 &amp;&amp; $hour &gt;= $satFirstShowStart &amp;&amp; $hour &lt; $satFirstShowEnd) ||\n ($day == 7 &amp;&amp; $hour &gt;= $satSecondShowStart &amp;&amp; $hour &lt; $satSecondShowEnd)\n) {\n // paste your old code here, but change 'menu' value to 'radio_show_live_menu'\n wp_nav_menu(array('menu' =&gt; 'radio_show_live_menu'));\n} else {\n // paste your old code here, with no changes\n wp_nav_menu(array('menu' =&gt; 'header'));\n}\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>Using WordPress's <code>current_time(\"N G\")</code> gives you N, which is a day of the week, with Monday=1 through Sunday=7, as well as G, which is the hour of the day, with midnight=00 through 11 PM=23.</p>\n\n<p>If your show is more than one hour you'll want to edit the show start and end values above.</p>\n\n<p>You'll need to make sure WordPress is set to use your local time zone to ensure that things happen at the time you expect. You can do that in Settings > General.</p>\n\n<p>Finally, this new code looks for 2 separate menus. If your show is on, it will pull from a <em>new</em> menu which you need to create. If your show isn't on, it will pull from the old/existing menu.</p>\n\n<p>To create the new menu: in your (child) theme's <code>functions.php</code> file, add</p>\n\n<p>function radio_show_live_menu() {\n register_nav_menu('radio_show_live_menu', __('Radio Live Menu'));\n}\nadd_action('init', 'radio_show_live_menu');</p>\n\n<p>You can then copy the existing menu into the new one and add the extra link.</p>\n" }, { "answer_id": 262457, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 2, "selected": false, "text": "<p>A bit late to the show, but I'd put the whole function in the functions.php. No need to edit the header.php:\nYou'll want to make sure you're in the right timezone too and IMHO Stringtotime is a bit easier to understand.</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'my_nav_menu_profile_link');\nfunction my_nav_menu_profile_link($menu) {\n $livesite = '#'; //link to add to show\n $linkdescription = 'Live broadcast'; //what the link will say on frontend\n $currdate = date('now'); //may need to set your timezone if it is different than server time.\n\n //saturday morning show\n if ($currdate &gt;= strtotime ('Saturday 7am') &amp;&amp; $currdate &lt;= strtotime ('saturday 8am') ) {\n $livelink = '&lt;li&gt;&lt;a href=\"'.$livesite.'\" &gt;'.$linkdescription.'&lt;/a&gt;&lt;/li&gt;';\n $menu = $menu . $livelink;\n return $menu;\n\n //Saturday evening show\n } elseif ($currdate &gt;= strtotime ('Saturday 7pm') &amp;&amp; $currdate &lt;= strtotime ('saturday 8pm')) {\n $livelink = '&lt;li&gt;&lt;a href=\"'.$livesite.'\" &gt;'.$linkdescription.'&lt;/a&gt;&lt;/li&gt;';\n $menu = $menu . $livelink;\n return $menu;\n\n //evening shows everyday\n } elseif ($currdate &gt;= strtotime ('5pm') &amp;&amp; $currdate &lt;= strtotime ('6pm')) {\n $livelink = '&lt;li&gt;&lt;a href=\"'.$livesite.'\" &gt;'.$linkdescription.'&lt;/a&gt;&lt;/li&gt;';\n $menu = $menu . $livelink;\n return $menu;\n\n //other times no live show \n } else {\n return $menu;\n }\n}\n</code></pre>\n" } ]
2017/04/03
[ "https://wordpress.stackexchange.com/questions/262326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116850/" ]
I have a "utility navigation" on the top of my website that currently has two links - one to our blog and the other to the weekly newsletter. We also do a radio show everyday at 5pm, as well as a rerun on Saturday at 7am and 7pm. During this time, I would like a third menu item to appear with a link to the podcast to listen live. Anyone have a clue on how to do this, without installing a plugin? I figured I would be able to edit the function but I have no idea how to program timers.. :( Any help is appreciated!
Since you need to edit theme files, you'll first want to determine whether you're using a custom-built theme or something that was downloaded from somewhere. If it was downloaded from somewhere, you'll need to create a [child theme](https://codex.wordpress.org/Child_Themes) (basically, you just create a new `style.css` file which only needs to contain comments at the top, which let WordPress recognize it as a theme you can activate - and then you copy whichever file you're editing, probably `header.php`, into your theme and make edits there). This way whenever your main theme is updated your child theme will still apply your changes. Then, in header.php, you'll change code that should look something like this (it may be longer but will contain `wp_nav_menu`): ``` wp_nav_menu(array('theme_location' => 'header')); ``` to a conditional: ``` $weekdayShowStart = '17'; $weekdayShowEnd = '18'; $satFirstShowStart = '07'; $satFirstShowEnd = '08'; $satSecondShowStart = '19'; $satSecondShowEnd = '20'; $dayAndTime = current_time("N G"); $timestamp = explode(' ', $dayAndTime); $day = $timestamp[0]; $hour = $timestamp[1]; if( ($day < 6 && $hour >= $weekdayShowStart && $hour < $weekdayShowEnd) || ($day == 6 && $hour >= $satFirstShowStart && $hour < $satFirstShowEnd) || ($day == 7 && $hour >= $satSecondShowStart && $hour < $satSecondShowEnd) ) { // paste your old code here, but change 'menu' value to 'radio_show_live_menu' wp_nav_menu(array('menu' => 'radio_show_live_menu')); } else { // paste your old code here, with no changes wp_nav_menu(array('menu' => 'header')); } ``` Explanation: Using WordPress's `current_time("N G")` gives you N, which is a day of the week, with Monday=1 through Sunday=7, as well as G, which is the hour of the day, with midnight=00 through 11 PM=23. If your show is more than one hour you'll want to edit the show start and end values above. You'll need to make sure WordPress is set to use your local time zone to ensure that things happen at the time you expect. You can do that in Settings > General. Finally, this new code looks for 2 separate menus. If your show is on, it will pull from a *new* menu which you need to create. If your show isn't on, it will pull from the old/existing menu. To create the new menu: in your (child) theme's `functions.php` file, add function radio\_show\_live\_menu() { register\_nav\_menu('radio\_show\_live\_menu', \_\_('Radio Live Menu')); } add\_action('init', 'radio\_show\_live\_menu'); You can then copy the existing menu into the new one and add the extra link.
262,339
<p>I'm using Advanced Custom Fields and Genesis and trying to modify a template to reflect a relationship between two custom post types (using their associated custom fields.) In this case, I have custom post types for "Staff" and "Reports", and for staff, I have the custom fields "first_name" and "last_name"; and associated with the "Reports" CPT, I also have two custom fields "primary_contact" and "associated_contact"— and in the "single-staff.php" template, I'd like to render a list of any associated reports in the sidebar that would include entries (post titles) for which <strong>that staff member</strong> is defined as <em>either</em> a "primary_contact" or an "associated_contact."</p> <p>Thus, for example, if I've created "Tom Jones" as a staff member (an instance of the "Staff" post type), is it possible for me to define a query that outputs a list of reports for which "Tom Jones" is defined as a "primary_contact" and/or "associated_contact" in any instances of the "Reports" custom post type? I'm including a (very) rough concept for this query below:</p> <pre><code>$args = array( 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'post_type' =&gt; 'reports', 'meta_key' =&gt; 'primary_contact', 'meta_value' =&gt; '$this.full_name', ), array( 'post_type' =&gt; 'reports', 'meta_key' =&gt; 'associated_contact', 'meta_value' =&gt; '$this.full_name', ) ) ); $query = new WP_Query( $args ); </code></pre> <p>Please let me know if the question is not sufficiently clear-- and thank you for any insight!</p>
[ { "answer_id": 262345, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>I haven't tested this but it SHOULD work. You'll want to put it in the single-staff.php. You'll have to add the details (actual query, post types, etc).</p>\n\n<pre><code>$reports = get_posts(array(\n 'post_type' =&gt; 'reports', //use actual post type\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'or',\n array(\n 'key' =&gt; 'primary_contact', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n array(\n 'key' =&gt; 'associated_contact', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n )\n ));\n\n ?&gt;\n &lt;?php if( $reports ): ?&gt;\n &lt;ul&gt;\n &lt;?php foreach( $reports as $report ): ?&gt;\n &lt;li&gt;\n &lt;?php echo get_the_title( $doctor-&gt;ID ); ?&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 262429, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>Another option: there's an ACF add-on called <a href=\"https://www.advancedcustomfields.com/resources/bidirectional-relationships/\" rel=\"nofollow noreferrer\">Bidirectional Relationships</a> that may simplify this for you. You define relationships in ACF, and then when you're editing either post type, you'll see a box that lets you search or select from a list the related content. You can then use that info in your templates however you like.</p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262339", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89753/" ]
I'm using Advanced Custom Fields and Genesis and trying to modify a template to reflect a relationship between two custom post types (using their associated custom fields.) In this case, I have custom post types for "Staff" and "Reports", and for staff, I have the custom fields "first\_name" and "last\_name"; and associated with the "Reports" CPT, I also have two custom fields "primary\_contact" and "associated\_contact"— and in the "single-staff.php" template, I'd like to render a list of any associated reports in the sidebar that would include entries (post titles) for which **that staff member** is defined as *either* a "primary\_contact" or an "associated\_contact." Thus, for example, if I've created "Tom Jones" as a staff member (an instance of the "Staff" post type), is it possible for me to define a query that outputs a list of reports for which "Tom Jones" is defined as a "primary\_contact" and/or "associated\_contact" in any instances of the "Reports" custom post type? I'm including a (very) rough concept for this query below: ``` $args = array( 'meta_query' => array( 'relation' => 'OR', array( 'post_type' => 'reports', 'meta_key' => 'primary_contact', 'meta_value' => '$this.full_name', ), array( 'post_type' => 'reports', 'meta_key' => 'associated_contact', 'meta_value' => '$this.full_name', ) ) ); $query = new WP_Query( $args ); ``` Please let me know if the question is not sufficiently clear-- and thank you for any insight!
I haven't tested this but it SHOULD work. You'll want to put it in the single-staff.php. You'll have to add the details (actual query, post types, etc). ``` $reports = get_posts(array( 'post_type' => 'reports', //use actual post type 'meta_query' => array( 'relation' => 'or', array( 'key' => 'primary_contact', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) array( 'key' => 'associated_contact', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) ) )); ?> <?php if( $reports ): ?> <ul> <?php foreach( $reports as $report ): ?> <li> <?php echo get_the_title( $doctor->ID ); ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> ```
262,340
<p>I'm developing a single page application (SAP) based theme, where I've <strong>Portfolio</strong> CPT to show portfolio items in loop other than blog posts.</p> <p>I've built 2 separate posts load more function which triggers on click. SO the blog posts are working fine, but on click on load more button on <strong>Portfolio</strong> section it appends posts for Blog instead of Portfolio.</p> <p>Following I've Code Functions for Blog.</p> <p><strong>blog-functions.php</strong></p> <pre><code>// Enqueing Scripts for loading blogs posts via Ajax wp_enqueue_script('ajax_blog_scripts', get_template_directory_uri() . '/assets/js/blog-scripts.js', array(), false, true ); wp_localize_script('ajax_blog_scripts', 'ajaxurl', admin_url('admin-ajax.php') ); // Initiating Ajax Load More Posts Function function loadmore_blog_posts() { $count = $_POST["count"]; $cpt = 1; $args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'post', // change the post type if you use a custom post type 'post_status' =&gt; 'publish', ); $blog_posts = new WP_Query( $args ); if( $blog_posts-&gt;have_posts() ) { while( $blog_posts-&gt;have_posts() ) { $blog_posts-&gt;the_post(); if( $cpt &gt; $count &amp;&amp; $cpt &lt; $count+3 ) { &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('post-item'); ?&gt;&gt; Post Content... &lt;/article&gt; &lt;?php } $cpt++; } } die(); } add_action( 'wp_ajax_load_more_posts', 'loadmore_blog_posts' ); add_action( 'wp_ajax_nopriv_load_more_posts', 'loadmore_blog_posts' ); </code></pre> <p><strong>blog-scripts.js</strong></p> <pre><code>// Load Next Posts via AJAX Request $('#blog-section .load-more-btn').click(function() { // Adding Loading Posts spinner on click var $btn = $(this).button('loading'); // Sending Ajax Request for getting more Posts $.post(ajaxurl, { 'action': 'load_more_posts', 'count': $('article.post-item').length }, function(response) { $('#blog-section .blog-posts').append(response); $btn.button('reset'); }); }); </code></pre> <p><strong>Loop Markup</strong></p> <pre><code>&lt;div class="blog-posts"&gt; &lt;?php $args = array( 'order' =&gt; $blog_post_order, 'posts_per_page' =&gt; $blog_post_count ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('post-item col-sm-6'); ?&gt;&gt; Post Content... &lt;/article&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endwhile; else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, there is no post added so far. Please go to Dashboard and add one.', 'theme-slug' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre> <p><br></p> <p>Following I've Code Functions for Portfolio.</p> <p><strong>portfolio-scripts.php</strong></p> <pre><code>// Enqueing Scripts for loading portfolio posts via Ajax wp_enqueue_script('ajax_portfolio_scripts', get_template_directory_uri() . '/assets/js/portfolio-scripts.js', array(), false, true ); wp_localize_script('ajax_portfolio_scripts', 'ajaxurl', admin_url('admin-ajax.php') ); // Initiating Ajax Load More Posts Function function loadmore_portfolio_posts() { $count = $_POST["count"]; $cpt = 1; $args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'portfolio', // change the post type if you use a custom post type 'post_status' =&gt; 'publish', ); $portfolio_posts = new WP_Query( $args ); if( $portfolio_posts-&gt;have_posts() ) { while( $portfolio_posts-&gt;have_posts() ) { $portfolio_posts-&gt;the_post(); if( $cpt &gt; $count &amp;&amp; $cpt &lt; $count+5 ) { ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('col-xl-2 col-lg-3 col-md-3 col-sm-4 col-xs-6 portfolio-item'); ?&gt;&gt; Loop Content &lt;/div&gt; &lt;?php } $cpt++; } } die(); } add_action( 'wp_ajax_load_more_posts', 'loadmore_portfolio_posts' ); add_action( 'wp_ajax_nopriv_load_more_posts', 'loadmore_portfolio_posts' ); </code></pre> <p><strong>portfolio-scripts.js</strong></p> <pre><code>// Load Next Posts via AJAX Request $('#portfolio-section .load-more-btn').click(function() { // Adding Loading Posts spinner on click var $btn = $(this).button('loading'); // Sending Ajax Request for getting more Posts $.post(ajaxurl, { 'action': 'load_more_posts', 'count': $('div.portfolio-item').length }, function(response) { $('#portfolio-section .portfolio-items').append(response); $btn.button('reset'); }); }); </code></pre> <p><strong>Loop Markup</strong></p> <pre><code>&lt;div class="portfolio-items"&gt; &lt;?php $args = array( 'post_type' =&gt; 'portfolio', 'order' =&gt; $portfolio_post_order, 'posts_per_page' =&gt; $portfolio_post_count ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('col-xl-2 col-lg-3 col-md-3 col-sm-4 col-xs-6 portfolio-item'); ?&gt;&gt; Loop Content &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endwhile; else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, there is no post added so far. Please go to Dashboard and add one.', 'theme-slug' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 262345, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>I haven't tested this but it SHOULD work. You'll want to put it in the single-staff.php. You'll have to add the details (actual query, post types, etc).</p>\n\n<pre><code>$reports = get_posts(array(\n 'post_type' =&gt; 'reports', //use actual post type\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'or',\n array(\n 'key' =&gt; 'primary_contact', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n array(\n 'key' =&gt; 'associated_contact', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n )\n ));\n\n ?&gt;\n &lt;?php if( $reports ): ?&gt;\n &lt;ul&gt;\n &lt;?php foreach( $reports as $report ): ?&gt;\n &lt;li&gt;\n &lt;?php echo get_the_title( $doctor-&gt;ID ); ?&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 262429, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>Another option: there's an ACF add-on called <a href=\"https://www.advancedcustomfields.com/resources/bidirectional-relationships/\" rel=\"nofollow noreferrer\">Bidirectional Relationships</a> that may simplify this for you. You define relationships in ACF, and then when you're editing either post type, you'll see a box that lets you search or select from a list the related content. You can then use that info in your templates however you like.</p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78274/" ]
I'm developing a single page application (SAP) based theme, where I've **Portfolio** CPT to show portfolio items in loop other than blog posts. I've built 2 separate posts load more function which triggers on click. SO the blog posts are working fine, but on click on load more button on **Portfolio** section it appends posts for Blog instead of Portfolio. Following I've Code Functions for Blog. **blog-functions.php** ``` // Enqueing Scripts for loading blogs posts via Ajax wp_enqueue_script('ajax_blog_scripts', get_template_directory_uri() . '/assets/js/blog-scripts.js', array(), false, true ); wp_localize_script('ajax_blog_scripts', 'ajaxurl', admin_url('admin-ajax.php') ); // Initiating Ajax Load More Posts Function function loadmore_blog_posts() { $count = $_POST["count"]; $cpt = 1; $args = array( 'posts_per_page' => -1, 'post_type' => 'post', // change the post type if you use a custom post type 'post_status' => 'publish', ); $blog_posts = new WP_Query( $args ); if( $blog_posts->have_posts() ) { while( $blog_posts->have_posts() ) { $blog_posts->the_post(); if( $cpt > $count && $cpt < $count+3 ) { <article id="post-<?php the_ID(); ?>" <?php post_class('post-item'); ?>> Post Content... </article> <?php } $cpt++; } } die(); } add_action( 'wp_ajax_load_more_posts', 'loadmore_blog_posts' ); add_action( 'wp_ajax_nopriv_load_more_posts', 'loadmore_blog_posts' ); ``` **blog-scripts.js** ``` // Load Next Posts via AJAX Request $('#blog-section .load-more-btn').click(function() { // Adding Loading Posts spinner on click var $btn = $(this).button('loading'); // Sending Ajax Request for getting more Posts $.post(ajaxurl, { 'action': 'load_more_posts', 'count': $('article.post-item').length }, function(response) { $('#blog-section .blog-posts').append(response); $btn.button('reset'); }); }); ``` **Loop Markup** ``` <div class="blog-posts"> <?php $args = array( 'order' => $blog_post_order, 'posts_per_page' => $blog_post_count ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('post-item col-sm-6'); ?>> Post Content... </article> <?php wp_reset_postdata(); ?> <?php endwhile; else : ?> <p><?php _e( 'Sorry, there is no post added so far. Please go to Dashboard and add one.', 'theme-slug' ); ?></p> <?php endif; ?> </div> ``` Following I've Code Functions for Portfolio. **portfolio-scripts.php** ``` // Enqueing Scripts for loading portfolio posts via Ajax wp_enqueue_script('ajax_portfolio_scripts', get_template_directory_uri() . '/assets/js/portfolio-scripts.js', array(), false, true ); wp_localize_script('ajax_portfolio_scripts', 'ajaxurl', admin_url('admin-ajax.php') ); // Initiating Ajax Load More Posts Function function loadmore_portfolio_posts() { $count = $_POST["count"]; $cpt = 1; $args = array( 'posts_per_page' => -1, 'post_type' => 'portfolio', // change the post type if you use a custom post type 'post_status' => 'publish', ); $portfolio_posts = new WP_Query( $args ); if( $portfolio_posts->have_posts() ) { while( $portfolio_posts->have_posts() ) { $portfolio_posts->the_post(); if( $cpt > $count && $cpt < $count+5 ) { ?> <div id="post-<?php the_ID(); ?>" <?php post_class('col-xl-2 col-lg-3 col-md-3 col-sm-4 col-xs-6 portfolio-item'); ?>> Loop Content </div> <?php } $cpt++; } } die(); } add_action( 'wp_ajax_load_more_posts', 'loadmore_portfolio_posts' ); add_action( 'wp_ajax_nopriv_load_more_posts', 'loadmore_portfolio_posts' ); ``` **portfolio-scripts.js** ``` // Load Next Posts via AJAX Request $('#portfolio-section .load-more-btn').click(function() { // Adding Loading Posts spinner on click var $btn = $(this).button('loading'); // Sending Ajax Request for getting more Posts $.post(ajaxurl, { 'action': 'load_more_posts', 'count': $('div.portfolio-item').length }, function(response) { $('#portfolio-section .portfolio-items').append(response); $btn.button('reset'); }); }); ``` **Loop Markup** ``` <div class="portfolio-items"> <?php $args = array( 'post_type' => 'portfolio', 'order' => $portfolio_post_order, 'posts_per_page' => $portfolio_post_count ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class('col-xl-2 col-lg-3 col-md-3 col-sm-4 col-xs-6 portfolio-item'); ?>> Loop Content </div> <?php wp_reset_postdata(); ?> <?php endwhile; else : ?> <p><?php _e( 'Sorry, there is no post added so far. Please go to Dashboard and add one.', 'theme-slug' ); ?></p> <?php endif; ?> </div> ```
I haven't tested this but it SHOULD work. You'll want to put it in the single-staff.php. You'll have to add the details (actual query, post types, etc). ``` $reports = get_posts(array( 'post_type' => 'reports', //use actual post type 'meta_query' => array( 'relation' => 'or', array( 'key' => 'primary_contact', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) array( 'key' => 'associated_contact', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) ) )); ?> <?php if( $reports ): ?> <ul> <?php foreach( $reports as $report ): ?> <li> <?php echo get_the_title( $doctor->ID ); ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> ```
262,371
<p>How i can add custom text to menu? I want such structure in output:</p> <pre><code>&lt;ul&gt; &lt;li&gt;home&lt;/li&gt; &lt;li&gt;services &lt;ul&gt; &lt;p&gt;services&lt;/p&gt; &lt;li&gt;&lt;a href="#"&gt;service1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;service2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;service3&lt;/a&gt; &lt;ul&gt; &lt;p&gt;service3&lt;p&gt; &lt;li&gt;&lt;a href="#"&gt;service 3.1&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Thanks!</p>
[ { "answer_id": 262379, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": -1, "selected": false, "text": "<p>You can add it by back end appearance > menu and create menu and > sub menu by dragging page or posts to your menu and call it where you want to call.</p>\n\n<p>For More Detail See this link <a href=\"https://premium.wpmudev.org/blog/add-menus-to-wordpress/?utm_expid=3606929-101.yRvM9BqCTnWwtfcczEfOmg.0&amp;utm_referrer=https%3A%2F%2Fwww.google.co.in%2F\" rel=\"nofollow noreferrer\">How to Add More Navigation Menus to your WordPress </a></p>\n\n<p>OR\nYou can use the fallowing code for adding specific element to the menu</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );\nfunction your_custom_menu_item ( $items, $args ) {\n if (is_single() &amp;&amp; $args-&gt;theme_location == 'primary') {\n $items .= '&lt;li&gt;&lt;p&gt;Show whatever&lt;/p&gt;&lt;li&gt;';\n }\n return $items;\n}\n</code></pre>\n" }, { "answer_id": 293455, "author": "Ray", "author_id": 101989, "author_profile": "https://wordpress.stackexchange.com/users/101989", "pm_score": 2, "selected": false, "text": "<p>There is another alt way to do this with CSS3. You would add a link to the WP Menu as normal but make the Location either <code>javascript:void(0);</code> or <code>#</code> so it doesn't go anywhere (I would say the <code>javascript...</code> is the better way to prevent anchor link from firing).</p>\n\n<p>Then in your style.css or CSS doc you can get target those links via the <code>href</code> like</p>\n\n<pre><code>header .nav li a[href=\"#\"], header .nav li a[href=\"#\"]:hover,\nheader .nav li a[href=\"javascript:void(0);\"],\nheader .nav li a[href=\"javascript:void(0);\"]:hover {\n text-decoration:none !important;\n cursor: text !important\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://css-tricks.com/almanac/selectors/a/attribute/\" rel=\"nofollow noreferrer\">https://css-tricks.com/almanac/selectors/a/attribute/</a></p>\n\n<p><em>Your selectors may be different</em></p>\n" }, { "answer_id": 300452, "author": "LJJ", "author_id": 65422, "author_profile": "https://wordpress.stackexchange.com/users/65422", "pm_score": -1, "selected": false, "text": "<p>For this, you have to add a walker class to your WordPress menu,</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a></p>\n\n<p>and all the walker class inside your wp_nav_menu function</p>\n\n<pre><code>&lt;?php\n wp_nav_menu(array(\n 'menu' =&gt; 2, //menu id\n 'walker' =&gt; new Walker_Quickstart_Menu() //use our custom walker\n ));\n ?&gt;\n</code></pre>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262371", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116880/" ]
How i can add custom text to menu? I want such structure in output: ``` <ul> <li>home</li> <li>services <ul> <p>services</p> <li><a href="#">service1</a></li> <li><a href="#">service2</a></li> <li><a href="#">service3</a> <ul> <p>service3<p> <li><a href="#">service 3.1</a></li> <ul> </li> </ul> </li> </ul> ``` Thanks!
There is another alt way to do this with CSS3. You would add a link to the WP Menu as normal but make the Location either `javascript:void(0);` or `#` so it doesn't go anywhere (I would say the `javascript...` is the better way to prevent anchor link from firing). Then in your style.css or CSS doc you can get target those links via the `href` like ``` header .nav li a[href="#"], header .nav li a[href="#"]:hover, header .nav li a[href="javascript:void(0);"], header .nav li a[href="javascript:void(0);"]:hover { text-decoration:none !important; cursor: text !important } ``` Reference: <https://css-tricks.com/almanac/selectors/a/attribute/> *Your selectors may be different*
262,393
<p>Is is possible to remove all the categories from a product in WooCommerce?</p> <p>I have written a script which is run every time when a product is added/updated via WP-All-Import, but there are some wrong categories on the products, which I want to clean, deleting all the categories or products is not an option, so I want clear the categories on the products and let my script decide which categories to add to this product.</p>
[ { "answer_id": 262402, "author": "NVO", "author_id": 116406, "author_profile": "https://wordpress.stackexchange.com/users/116406", "pm_score": 2, "selected": true, "text": "<p>I have found the solution, actually it is very simple:</p>\n\n<pre><code>$terms = get_the_terms($product_id, 'product_cat');\nforeach($terms as $term){\n wp_remove_object_terms($product_id, $term-&gt;term_id, 'product_cat');\n}\n</code></pre>\n\n<p>This code get all the therms with the 'product_cat' taxonomy, with a foreach loop I remove all the items. </p>\n" }, { "answer_id": 411391, "author": "Jelle Wielsma", "author_id": 101549, "author_profile": "https://wordpress.stackexchange.com/users/101549", "pm_score": 0, "selected": false, "text": "<p>You could wipe all terms from a product using the <code>wp_set_post_terms</code> function. Setting the <code>append</code> argument to <code>false</code> ensures that all terms are overwritten.</p>\n<p>For example:</p>\n<pre><code>wp_set_post_terms( $product_id, array(), 'product_cat', false );\n</code></pre>\n<p>More information on the <code>wp_set_post_terms</code> function:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_set_post_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_post_terms/</a></p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116406/" ]
Is is possible to remove all the categories from a product in WooCommerce? I have written a script which is run every time when a product is added/updated via WP-All-Import, but there are some wrong categories on the products, which I want to clean, deleting all the categories or products is not an option, so I want clear the categories on the products and let my script decide which categories to add to this product.
I have found the solution, actually it is very simple: ``` $terms = get_the_terms($product_id, 'product_cat'); foreach($terms as $term){ wp_remove_object_terms($product_id, $term->term_id, 'product_cat'); } ``` This code get all the therms with the 'product\_cat' taxonomy, with a foreach loop I remove all the items.
262,423
<p>When adding a new user role with <a href="https://developer.wordpress.org/reference/functions/add_role/" rel="nofollow noreferrer"><code>add_role()</code></a>, are there any capabilities attributed to the role (or allowed by the role) by default?</p> <p>It is possible to create a role without defining any capabilities. There will simply be no capabilities set for this role in the database. However, you can explicitly deny capabilities by setting them to false upon creating the role. </p> <blockquote> <p><strong>$capabilities</strong><br> (array) (Optional) List of capabilities, e.g. array( 'edit_posts' => true, 'delete_posts' => false );</p> </blockquote> <p>I have seen examples of this, but I am left wondering why this would ever be necessary unless WordPress assumes that a newly created role has certain capabilities until otherwise excluded.</p> <p>For example, are all roles assumed to have the <code>read</code> capability unless the capability is explicitly excluded? I can use <code>get_role( $new_role )-&gt;capabilities;</code> to get a list of capabilities which are explicitly set, but this does not answer my question about how WordPress handles new roles. If no capabilities are explicitly set for a new role then this will return empty.</p> <p>Must I exclude all capabilities I don't not want a role to have or does WordPress presume all capabilities to be false until they are set as true?</p> <p>Edit: This question was inspired by <a href="https://developer.wordpress.org/reference/functions/add_role/#comment-941" rel="nofollow noreferrer">an example</a> on the developer site which sets a capability to false when a role is created. I can't see why this would be necessary.</p> <pre><code>$result = add_role( 'guest_author', __( 'Guest Author', 'testdomain' ), array( 'read' =&gt; true, // true allows this capability 'edit_posts' =&gt; true, 'delete_posts' =&gt; false, // Use false to explicitly deny ) ); </code></pre>
[ { "answer_id": 262461, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 1, "selected": false, "text": "<p>With the default value (empty array), there is no capabilities added to the role (not even <code>read</code>) and they cannot acces the dashboard</p>\n\n<p>then, you can just create the role with this code : </p>\n\n<pre><code>add_role(\"on_the_door\", \"User with no access\");\n</code></pre>\n\n<p>you can use this plugin to see the capabilities of the roles :<br>\n<a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/user-role-editor/</a></p>\n" }, { "answer_id": 262477, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 3, "selected": true, "text": "<p>I've found that the WordPress <code>has_cap()</code> function, which is relied on by functions like <code>user_can()</code> and <code>current_user_can</code>, explicitly returns false for empty capabilities.</p>\n\n<p>Example: If a capability is passed as an argument using <a href=\"https://developer.wordpress.org/reference/functions/current_user_can/#source\" rel=\"nofollow noreferrer\"><code>current_user_can()</code></a>, this function will pass the capability to <code>has_cap()</code> and return the results:</p>\n\n<pre><code> return call_user_func_array( array( $current_user, 'has_cap' ), $args\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_user/has_cap/#source\" rel=\"nofollow noreferrer\"><code>has_cap()</code></a> will return false if the requested capability does not exist or the value is false:</p>\n\n<pre><code>foreach ( (array) $caps as $cap ) {\n if ( empty( $capabilities[ $cap ] ) )\n return false;\n}\n</code></pre>\n\n<p>This is because the <a href=\"http://php.net/manual/en/function.empty.php\" rel=\"nofollow noreferrer\"><code>empty()</code></a> function returns true in either case.</p>\n\n<blockquote>\n <p>A variable is considered empty if it does not exist or if its value\n equals FALSE.</p>\n</blockquote>\n\n<p>Unless I am mistaken about how these functions work, then it appears safe to say that <strong>no default capabilities are attributed to a new role unless explicitly set to true</strong>. It is not necessary to <a href=\"https://developer.wordpress.org/reference/functions/add_role/#comment-941\" rel=\"nofollow noreferrer\">explicitly deny</a> a capability when creating a new role with <code>add_role()</code> and I can't see any reason to do so. If a capability is not listed, the user will not have it.</p>\n" }, { "answer_id": 262494, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>This is a misleading way to look at how wordpress capabilities work. In essence there is no structure that contains all the capabilities, and it all boils down to the developer implementing filters for the <code>has_cap</code> function. There is a core structure for core related capabilities, but this is truly a subset of what can be done.</p>\n\n<p>There is one default to the capabilities system - Admins has all the capabilities and there is no other assumption about any other user.</p>\n\n<p>So the discussion should be about specific capabilities, and not about some general capabilities concepts. </p>\n\n<p>Now when focusing on core capabilities, the tradition is that whatever value in the capabilities storage evaluates to <code>false</code> means that the user do not have the capability, so empty storage should mean that a user has no core capability (no other as well, but those capabilities might not rely on the core capabilities structure). </p>\n\n<p>But it is important to remember that capability is just an API, and code do not have to use the API, therefor when you ask specifically \"will user with empty capabilities will have a read capability\", it is very much depends on how the developer of the feature regard such capability. For example I can see how access to the dashboard might be unconditional, and being able to access your own profile being \"on\" by default. More extreme - almost no theme I know of implements a capability check before granting access to the content on the front end, therefor it is just meaningless to fiddle with a \"read\" style capability.</p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33393/" ]
When adding a new user role with [`add_role()`](https://developer.wordpress.org/reference/functions/add_role/), are there any capabilities attributed to the role (or allowed by the role) by default? It is possible to create a role without defining any capabilities. There will simply be no capabilities set for this role in the database. However, you can explicitly deny capabilities by setting them to false upon creating the role. > > **$capabilities** > > (array) (Optional) List of capabilities, e.g. array( 'edit\_posts' => true, 'delete\_posts' => false ); > > > I have seen examples of this, but I am left wondering why this would ever be necessary unless WordPress assumes that a newly created role has certain capabilities until otherwise excluded. For example, are all roles assumed to have the `read` capability unless the capability is explicitly excluded? I can use `get_role( $new_role )->capabilities;` to get a list of capabilities which are explicitly set, but this does not answer my question about how WordPress handles new roles. If no capabilities are explicitly set for a new role then this will return empty. Must I exclude all capabilities I don't not want a role to have or does WordPress presume all capabilities to be false until they are set as true? Edit: This question was inspired by [an example](https://developer.wordpress.org/reference/functions/add_role/#comment-941) on the developer site which sets a capability to false when a role is created. I can't see why this would be necessary. ``` $result = add_role( 'guest_author', __( 'Guest Author', 'testdomain' ), array( 'read' => true, // true allows this capability 'edit_posts' => true, 'delete_posts' => false, // Use false to explicitly deny ) ); ```
I've found that the WordPress `has_cap()` function, which is relied on by functions like `user_can()` and `current_user_can`, explicitly returns false for empty capabilities. Example: If a capability is passed as an argument using [`current_user_can()`](https://developer.wordpress.org/reference/functions/current_user_can/#source), this function will pass the capability to `has_cap()` and return the results: ``` return call_user_func_array( array( $current_user, 'has_cap' ), $args ``` [`has_cap()`](https://developer.wordpress.org/reference/classes/wp_user/has_cap/#source) will return false if the requested capability does not exist or the value is false: ``` foreach ( (array) $caps as $cap ) { if ( empty( $capabilities[ $cap ] ) ) return false; } ``` This is because the [`empty()`](http://php.net/manual/en/function.empty.php) function returns true in either case. > > A variable is considered empty if it does not exist or if its value > equals FALSE. > > > Unless I am mistaken about how these functions work, then it appears safe to say that **no default capabilities are attributed to a new role unless explicitly set to true**. It is not necessary to [explicitly deny](https://developer.wordpress.org/reference/functions/add_role/#comment-941) a capability when creating a new role with `add_role()` and I can't see any reason to do so. If a capability is not listed, the user will not have it.
262,427
<p>I'm looking to pull all of the metadata (e.g. alt, width, height) from the theme logo, which is uploaded through Appearance -> Customization into my theme template file. This is what I currently have, but it's not working:</p> <pre><code>$custom_logo_id = get_theme_mod('custom_logo'); if ($custom_logo_id) { $image = wp_get_attachment_image_src($custom_logo_id, 'full'); $meta = wp_get_attachment_metadata($custom_logo_id); echo '&lt;img src="' . $image[0] . '" alt="' . $meta['alt'] . ' width="' . $meta['width'] . '" height="' . $meta['height'] . '"&gt;'; } else { echo bloginfo('name'); } </code></pre>
[ { "answer_id": 262445, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 1, "selected": false, "text": "<p>Ends up that \"alt\" is not stored in wp_get_attachment_metadata so I pulled it from the post meta:</p>\n\n<pre><code>$custom_logo_id = get_theme_mod('custom_logo');\nif ($custom_logo_id) {\n $image = wp_get_attachment_image_src($custom_logo_id, 'full');\n $meta = wp_get_attachment_metadata($custom_logo_id);\n **$alt_text = get_post_meta($custom_logo_id, '_wp_attachment_image_alt', true);**\n echo '&lt;img src=\"' . $image[0] . '\" alt=\"' . $alt_text . '\" width=\"' . $meta['width'] . '\" height=\"' . $meta['height'] . '\"&gt;';\n} else {\n echo bloginfo('name');\n}\n</code></pre>\n" }, { "answer_id": 262447, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>As you can see from the description of <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_metadata</code></a> there's no alt field stored in that location. The easiest way out would be to just use the title-field for the alt.</p>\n\n<p>Otherwise you can retrieve the alt-field using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta</code></a>. More explanation <a href=\"https://wordpress.stackexchange.com/questions/1051/how-to-retrieve-an-image-attachments-alt-text\">here</a>.</p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262427", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I'm looking to pull all of the metadata (e.g. alt, width, height) from the theme logo, which is uploaded through Appearance -> Customization into my theme template file. This is what I currently have, but it's not working: ``` $custom_logo_id = get_theme_mod('custom_logo'); if ($custom_logo_id) { $image = wp_get_attachment_image_src($custom_logo_id, 'full'); $meta = wp_get_attachment_metadata($custom_logo_id); echo '<img src="' . $image[0] . '" alt="' . $meta['alt'] . ' width="' . $meta['width'] . '" height="' . $meta['height'] . '">'; } else { echo bloginfo('name'); } ```
Ends up that "alt" is not stored in wp\_get\_attachment\_metadata so I pulled it from the post meta: ``` $custom_logo_id = get_theme_mod('custom_logo'); if ($custom_logo_id) { $image = wp_get_attachment_image_src($custom_logo_id, 'full'); $meta = wp_get_attachment_metadata($custom_logo_id); **$alt_text = get_post_meta($custom_logo_id, '_wp_attachment_image_alt', true);** echo '<img src="' . $image[0] . '" alt="' . $alt_text . '" width="' . $meta['width'] . '" height="' . $meta['height'] . '">'; } else { echo bloginfo('name'); } ```
262,438
<p>I have the code below to list the recent posts on my site. It's working fine.</p> <p>I need to style differently the first post (bigger image and bigger title).</p> <p>Any idea how ?</p> <pre><code>&lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 10, 'paged' =&gt; $paged ); $wp_query = new WP_Query($args); while ( have_posts() ) : the_post(); ?&gt; &lt;div class="main-content span12"&gt; &lt;div class="main-content span4"&gt; &lt;!--Image article--&gt; &lt;img src="&lt;?php the_post_thumbnail_url( 'medium' ); ?&gt;"&gt; &lt;/div&gt; &lt;div class="main-content span8"&gt; &lt;!--Titre article--&gt; &lt;h4&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt; &lt;!--Extrait article--&gt; &lt;?php the_excerpt(__('(more…)')); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 262439, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You will have to need to redirect all your traffics from HTTP to HTTPS. A rewrite rule can do this for you. Use this code instead of WordPress's original rewrite rule (if you are not using cache) in your <code>.htaccess</code> file:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{ENV:HTTPS} !=on\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n\n# BEGIN WordPress\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>There are plugins that can do this for you too, such as <a href=\"https://wordpress.org/plugins/https-redirection/\" rel=\"nofollow noreferrer\">Easy HTTPS Rediction</a>.</p>\n" }, { "answer_id": 262441, "author": "Andy", "author_id": 116912, "author_profile": "https://wordpress.stackexchange.com/users/116912", "pm_score": -1, "selected": false, "text": "<p>Install this plugin: <a href=\"https://wordpress.org/plugins/http-https-remover/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/http-https-remover/</a></p>\n\n<p>Despite the name - HTTP / HTTPS Remover - the latest version will force all http to https, and your mixed content warnings will be gone.</p>\n" }, { "answer_id": 262442, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 3, "selected": false, "text": "<p>This is happening because WordPress saves URLs in content absolutely by default (meaning that it's actually got your urls saved as <a href=\"http://example.com\" rel=\"noreferrer\">http://example.com</a> in the database). So to fix this you'll want to run a search and replace in your database to fix those errors.</p>\n\n<p>I like to use the plugin <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"noreferrer\">Better Search Replace</a> because it has a nice feature to let you try out your search/replace as a dry run to test. There are lots of other search/replace methods, and you could also make the changes in PhpMyAdmin, but I'll just put instructions for using the Better Search Replace plugin.</p>\n\n<p>Assuming you are using Better Search Replace:</p>\n\n<ol>\n<li><strong>BACK UP YOUR DATABASE! Always always always. Use whatever tool you want to do this (UpdraftPlus, or dump (NOT DROP) it from PhpMyAdmin or straight from MySQL are all options).</strong></li>\n<li>Head to tools > Better Search Replace</li>\n<li>Add the non SSL version of your website to the search field http (eg. <code>http://example.com</code>) and the SSL version of your website to the replace field <a href=\"https://i.stack.imgur.com/AfKfX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AfKfX.png\" alt=\"Search Replace Example 1\"></a></li>\n<li>Select the tables you want to update. Most likely all you'll need is the <code>wp_posts</code> and <code>wp_postmeta</code> table but you can add them all if you like. Just know that it could take longer and time out depending on your server specs.<a href=\"https://i.stack.imgur.com/n64MF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/n64MF.png\" alt=\"Select your tables\"></a></li>\n<li>Do a dry run to make sure that it works <a href=\"https://i.stack.imgur.com/VYEoU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VYEoU.png\" alt=\"Dry run\"></a></li>\n<li>If it works, then uncheck the dry run option and run it for real.</li>\n<li>Check your website to verify the errors have been fixed. If they have, awesome!</li>\n</ol>\n\n<p><strong>Note: Any time you search/replace there's a chance you could cause massive problems to your website. Hence step one, back up your website. If something goes wrong, you have a way to restore your data.</strong></p>\n" }, { "answer_id": 262444, "author": "fwho", "author_id": 82807, "author_profile": "https://wordpress.stackexchange.com/users/82807", "pm_score": -1, "selected": false, "text": "<p>I just moved my company site to the secure only version last Friday. I used the <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow noreferrer\">Really Simple SSL Plugin</a> and then added a 301 redirect into my .htaccess file.</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>Don't forget to also verify the HTTPS version of your site in <a href=\"https://www.google.com/webmasters/\" rel=\"nofollow noreferrer\">Search Console / Webmaster Tools</a></p>\n" }, { "answer_id": 325630, "author": "Francesco Mantovani", "author_id": 157101, "author_profile": "https://wordpress.stackexchange.com/users/157101", "pm_score": 1, "selected": false, "text": "<p>I used <strong>Better Search Replace</strong> and <strong>Really Simple SSL</strong> and the winner is:</p>\n\n<p><a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow noreferrer\">Really Simple SSL</a></p>\n\n<p>Just do this:</p>\n\n<ol>\n<li>Install it</li>\n<li>Activate it</li>\n<li>Allow SSL</li>\n</ol>\n\n<p>Done</p>\n\n<p>It also fixed all the problems with image redirection</p>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92431/" ]
I have the code below to list the recent posts on my site. It's working fine. I need to style differently the first post (bigger image and bigger title). Any idea how ? ``` <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => $paged ); $wp_query = new WP_Query($args); while ( have_posts() ) : the_post(); ?> <div class="main-content span12"> <div class="main-content span4"> <!--Image article--> <img src="<?php the_post_thumbnail_url( 'medium' ); ?>"> </div> <div class="main-content span8"> <!--Titre article--> <h4><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h4> <!--Extrait article--> <?php the_excerpt(__('(more…)')); ?> </div> </div> <?php endwhile; ?> ```
This is happening because WordPress saves URLs in content absolutely by default (meaning that it's actually got your urls saved as <http://example.com> in the database). So to fix this you'll want to run a search and replace in your database to fix those errors. I like to use the plugin [Better Search Replace](https://wordpress.org/plugins/better-search-replace/) because it has a nice feature to let you try out your search/replace as a dry run to test. There are lots of other search/replace methods, and you could also make the changes in PhpMyAdmin, but I'll just put instructions for using the Better Search Replace plugin. Assuming you are using Better Search Replace: 1. **BACK UP YOUR DATABASE! Always always always. Use whatever tool you want to do this (UpdraftPlus, or dump (NOT DROP) it from PhpMyAdmin or straight from MySQL are all options).** 2. Head to tools > Better Search Replace 3. Add the non SSL version of your website to the search field http (eg. `http://example.com`) and the SSL version of your website to the replace field [![Search Replace Example 1](https://i.stack.imgur.com/AfKfX.png)](https://i.stack.imgur.com/AfKfX.png) 4. Select the tables you want to update. Most likely all you'll need is the `wp_posts` and `wp_postmeta` table but you can add them all if you like. Just know that it could take longer and time out depending on your server specs.[![Select your tables](https://i.stack.imgur.com/n64MF.png)](https://i.stack.imgur.com/n64MF.png) 5. Do a dry run to make sure that it works [![Dry run](https://i.stack.imgur.com/VYEoU.png)](https://i.stack.imgur.com/VYEoU.png) 6. If it works, then uncheck the dry run option and run it for real. 7. Check your website to verify the errors have been fixed. If they have, awesome! **Note: Any time you search/replace there's a chance you could cause massive problems to your website. Hence step one, back up your website. If something goes wrong, you have a way to restore your data.**
262,478
<p>So I have followed the tutorial below to reset my own passwords when I get forget my password for WordPress Admin login</p> <p><a href="https://crybit.com/reset-wordpress-users-password/" rel="nofollow noreferrer">https://crybit.com/reset-wordpress-users-password/</a></p> <p>but it does not seem to work for this other site I am working on. I am not sure why. I have heard colleagues talk about the PHP Portable password hashing framework. Could someone explain to me, if this indeed is the issue, do I simply use a tool like this one:</p> <p><a href="http://tools.k2an.com/?page=wordpress" rel="nofollow noreferrer">http://tools.k2an.com/?page=wordpress</a></p> <p>because I have tried it and it has not worked either and I am out of ammo for a solutions. Please help.</p> <p>Does anybody know if any of these plugins or this error message could be the problem:</p> <pre><code>[email protected] [~/public_html]# wp plugin list Notice: Undefined index: HTTP_HOST in /home/medthursday/public_html/wp-content/plugins/simple-301-redirects/wp-simple-301-redirects.php on line 271 +--------------------------------------------+----------+-----------+------------+ | name | status | update | version | +--------------------------------------------+----------+-----------+------------+ | advanced-custom-fields-pro | active | available | 5.5.0 | | akismet | inactive | available | 3.2 | | custom-post-type-ui | active | available | 1.4.3 | | hc-custom-wp-admin-url | active | none | 1.3.2 | | hello | inactive | none | 1.6 | | wd-instagram-feed | active | available | 1.1.16 | | post-types-order | active | available | 1.9 | | regenerate-thumbnails | active | none | 2.2.6 | | remove-query-strings-from-static-resources | active | available | 1.3.1 | | simple-301-redirects | active | none | 1.07 | | sucuri-scanner | active | none | 1.8.3 | | sumome | active | available | 1.22 | | theme-check | inactive | none | 20160523.1 | | updraftplus | active | available | 1.12.29 | | user-role-editor | active | available | 4.31 | | wordfence | active | available | 6.2.6 | | wordpress-importer | active | none | 0.6.3 | | wp-pagenavi | active | none | 2.91 | | wordpress-seo | active | available | 3.8 | +--------------------------------------------+----------+-----------+------------+ </code></pre>
[ { "answer_id": 262485, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 1, "selected": false, "text": "<p>Maybe this is not the answer you look for but giving one of below a try could maybe help you out?!<br /></p>\n\n<p>Ofcourse you have FTP or SSL access.<br />\n<em>If you don't have one of them, don't bother to read any further!</em><br /></p>\n\n<blockquote>\n <p>The good old <strong>make a backup from</strong> in this case <code>functions.php</code> before you start adding/editing is wishdom and could be important.<br /></p>\n</blockquote>\n\n<p>Start by activating <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">debug</a> in <code>wp-config.php</code> to see(hopefully) possible errors when some seems to bother WordPress.<br /></p>\n\n<p><strong>Option 1:</strong><br />\nAdd in <code>functions.php</code> the following code snippet when your admin user has ID number 1(ONE):</p>\n\n<pre><code>/**\n * Read more {@link https://codex.wordpress.org/Function_Reference/wp_set_password}\n*/\n$user_id = 1;\n$password = 'newpasswd';\nwp_set_password( $password, $user_id );\n</code></pre>\n\n<p><strong>Please note: This code should be deleted after ONE page load, otherwise the password will be reset on every subsequent load, sending the user back to the login screen each time.</strong><br />\nChange both to your preference! When the Administrator is not having <code>user_id</code> 1 and you have no idea which <code>user_id</code> number it should be, please forget this option. <em>(no need to tryout!)</em></p>\n\n<p>When you have add the snippet try to login your site. <em>(be sure browser cache is empty)</em><br />\nTry now to login with your admin name and your new created password.<br />\nSuccessful? If yes, delete the snippet from <code>functions.php</code> and all should be fine now.<br />\nNot successful? Delete the snippet and try option 2.<br /></p>\n\n<p><strong>Option 2:</strong><br />\nAdd in <code>functions.php</code> the following function, which will*(should)* create a new administrator user for you. Change <code>$username \\ $email \\ $password</code> to your preference. <em>(a correct working email address would be logical)</em></p>\n\n<pre><code>/**\n * Create a new user with admin caps\n *\n * Read more {@link https://codex.wordpress.org/Function_Reference/wp_create_user}\n *\n * @version WP 4.7.3\n */\nadd_action( 'init', 'wpse262478_add_new_adminuser' );\nfunction wpse262478_add_new_adminuser()\n{\n $username = 'aname'; \n $email = '[email protected]';\n $password = 'LZTf$f$FR)Y@xye';\n $user_id = username_exists( $username );\n\n if ( !$user_id &amp;&amp; email_exists( $email ) == false )\n {\n $user_id = wp_create_user( $username, $password, $email );\n\n if( !is_wp_error( $user_id ) )\n {\n $user = get_user_by( 'id', $user_id );\n $user-&gt;set_role( 'administrator' );\n }\n }\n} // end function\n</code></pre>\n\n<p><em>(make sure the browser cache is empty, which can always be helpful in these situations)</em><br /></p>\n\n<p>If you are successful you can login with the new created admin account <em>(if not directly working press F5 on the keyboard to refresh a few times)</em> and can delete the function from your <code>functions.php</code>. If you are not having success you still have to delete the function because this option seems also fruitless.<br /></p>\n\n<p>Hopefully one of the above did help, if so, stop reading and take a deep breath. If not, maybe followng could be helpful.<br /></p>\n\n<p>As you already tried accessing through phpMyAdmin <em>(seen the chat discussion)</em> which was also fruitless, you can still try another option which is not always helping but at least you did a -try and error-.<br /></p>\n\n<p><strong>Option 3:</strong><br />\nRename your <code>plugins</code> folder to something else and retry option 1 or 2.<br />\nIf successful, login, rename the plugin folder back to <code>plugins</code>. Now you have to enable 1 by 1 each plugin and check if all still is working. <br /> When all seems okay then at least you found a solution but still have no answer about the 'why was it not working' but it would be too far to digg into that issue but at least now you can take some time to find out what it maybe could be.</p>\n\n<p><em>ps, did you check your <code>functions.php</code> also, maybe there is code which could be the culprit for this dilemma?!</em></p>\n" }, { "answer_id": 262496, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": 0, "selected": false, "text": "<p>You can change your password through db user table . Go to databases and open user table and find admin and change your password with md5 selection and save the table.</p>\n\n<p>I think you can get help through this link <a href=\"https://codex.wordpress.org/Resetting_Your_Password\" rel=\"nofollow noreferrer\">Reset Wordpress Password</a></p>\n" }, { "answer_id": 262541, "author": "Daniel", "author_id": 109760, "author_profile": "https://wordpress.stackexchange.com/users/109760", "pm_score": -1, "selected": true, "text": "<p>you all have been wonderful resources. Now for the answer. It was a plugin called Wordfence that refused to recognize any user I created via wp_users table. If the person with admin privileges did not create my user, there was no way I was going to get in. The users I created it says Existing User No, but when a colleague with admin rights created daniel user, yes Wordfence recognized it as an Existing User. Sooo, I do not know if to be angry that we use that plugin or happy that the plugin works so well.</p>\n\n<pre><code>Top 5 Failed Logins\nUsername Login Attempts Existing User\nmedia_dev 21 No\nadmin 9 No\nearthquake2018 7 No\nJosiahSchaefer 7 Yes\ndaniel 5 Yes\n</code></pre>\n" } ]
2017/04/04
[ "https://wordpress.stackexchange.com/questions/262478", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109760/" ]
So I have followed the tutorial below to reset my own passwords when I get forget my password for WordPress Admin login <https://crybit.com/reset-wordpress-users-password/> but it does not seem to work for this other site I am working on. I am not sure why. I have heard colleagues talk about the PHP Portable password hashing framework. Could someone explain to me, if this indeed is the issue, do I simply use a tool like this one: <http://tools.k2an.com/?page=wordpress> because I have tried it and it has not worked either and I am out of ammo for a solutions. Please help. Does anybody know if any of these plugins or this error message could be the problem: ``` [email protected] [~/public_html]# wp plugin list Notice: Undefined index: HTTP_HOST in /home/medthursday/public_html/wp-content/plugins/simple-301-redirects/wp-simple-301-redirects.php on line 271 +--------------------------------------------+----------+-----------+------------+ | name | status | update | version | +--------------------------------------------+----------+-----------+------------+ | advanced-custom-fields-pro | active | available | 5.5.0 | | akismet | inactive | available | 3.2 | | custom-post-type-ui | active | available | 1.4.3 | | hc-custom-wp-admin-url | active | none | 1.3.2 | | hello | inactive | none | 1.6 | | wd-instagram-feed | active | available | 1.1.16 | | post-types-order | active | available | 1.9 | | regenerate-thumbnails | active | none | 2.2.6 | | remove-query-strings-from-static-resources | active | available | 1.3.1 | | simple-301-redirects | active | none | 1.07 | | sucuri-scanner | active | none | 1.8.3 | | sumome | active | available | 1.22 | | theme-check | inactive | none | 20160523.1 | | updraftplus | active | available | 1.12.29 | | user-role-editor | active | available | 4.31 | | wordfence | active | available | 6.2.6 | | wordpress-importer | active | none | 0.6.3 | | wp-pagenavi | active | none | 2.91 | | wordpress-seo | active | available | 3.8 | +--------------------------------------------+----------+-----------+------------+ ```
you all have been wonderful resources. Now for the answer. It was a plugin called Wordfence that refused to recognize any user I created via wp\_users table. If the person with admin privileges did not create my user, there was no way I was going to get in. The users I created it says Existing User No, but when a colleague with admin rights created daniel user, yes Wordfence recognized it as an Existing User. Sooo, I do not know if to be angry that we use that plugin or happy that the plugin works so well. ``` Top 5 Failed Logins Username Login Attempts Existing User media_dev 21 No admin 9 No earthquake2018 7 No JosiahSchaefer 7 Yes daniel 5 Yes ```
262,484
<p>I added some shortcode after the content using filter, like this:</p> <pre><code>add_filter( 'the_content', 'image_posts' ); </code></pre> <p>but now that I run <code>has_shortcode</code> in another function, this returns false even though the shortcode is there (which was added using the above filter. </p> <pre><code>add_action( 'wp_head', 'gallery_style'); function gallery_style(){ if ( has_shortcode( $content, 'gallery' ) ) { // enqueue style // it fails for posts which add gallery using the_content } </code></pre> <p>how can I test the <code>has_shortcode</code> for contents added using add_filter? </p>
[ { "answer_id": 262487, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 1, "selected": false, "text": "<p>For this, you'll actually want to utilize the <code>wp_enqueue_scripts</code> action instead of <code>wp_head</code>.</p>\n\n<p><code>wp_enqueue_scripts</code> is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because <code>wp_head</code> runs before <code>the_content</code> which means that you won't be able to modify the head once your code gets to <code>the_content</code>.</p>\n\n<p>First let's register our style using the <code>wp_enqueue_scripts</code> action.</p>\n\n<pre><code>/**\n * Register the gallery stylesheet for later use if our content contains the gallery shortcode.\n */\nfunction enqueue_gallery_style(){\n wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css');\n}\nadd_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action\n</code></pre>\n\n<p>We register the script using the <code>wp_register_style</code> function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it \"gallery_style\". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">wp_register_style</a></p>\n\n<p>Now we can add another <code>the_content</code> filter in addition to your <code>image_posts</code> filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the <code>wp_enqueue_style</code> function to enqueue our gallery style and add it to that specific page.</p>\n\n<pre><code>/**\n * This function is used to check the_content to see if it contains any shortcodes\n *\n * @param $content\n *\n * @return string\n */\n\nfunction shortcode_check( $content ) {\n\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it.\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\nadd_filter( 'the_content', 'shortcode_check' );\n</code></pre>\n\n<p>More info on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a></p>\n\n<p><strong>Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.</strong></p>\n\n<p>If you need to output styles that are generated via the admin (ie, colors) you can utilize the <code>wp_add_inline_style</code> function.</p>\n\n<p>This function will allow you to add on styles to a registered stylesheet.\nSo in the case of our already registered gallery.css file above, we can add\n<code>wp_add_inline_style( 'gallery_style', $user_css );</code> and it will add that as an inline style immediately after registered stylesheet.</p>\n\n<p>Here <code>$user_css</code> would be the styles as a string <strong>without</strong> the <code>&lt;style&gt;</code> wrapper.</p>\n\n<p>So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles.</p>\n\n<pre><code>function shortcode_check( $content ) {\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style('gallery_style');\n wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!!\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\n</code></pre>\n\n<p>More on <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style\" rel=\"nofollow noreferrer\">wp_add_inline_style</a></p>\n" }, { "answer_id": 262489, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>You can actually enqueue styles and scripts from any hook. If <code>wp_head()</code> had already fired, then the styles and/or scripts will be enqueued into the footer.</p>\n\n<pre><code>//* Add filter to the_content\nadd_filter( 'the_content', 'wpse_262484_the_content' );\nfunction wpse_262484_the_content( $content ) {\n\n //* Maybe do something useful with $content\n\n //* Enqueue style if the content has gallery shortcode\n //* Since wp_head() has already fired, this will be output in the footer\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'wpse-262484', PATH_TO . 'style.css' );\n }\n return $content;\n}\n</code></pre>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262484", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116939/" ]
I added some shortcode after the content using filter, like this: ``` add_filter( 'the_content', 'image_posts' ); ``` but now that I run `has_shortcode` in another function, this returns false even though the shortcode is there (which was added using the above filter. ``` add_action( 'wp_head', 'gallery_style'); function gallery_style(){ if ( has_shortcode( $content, 'gallery' ) ) { // enqueue style // it fails for posts which add gallery using the_content } ``` how can I test the `has_shortcode` for contents added using add\_filter?
For this, you'll actually want to utilize the `wp_enqueue_scripts` action instead of `wp_head`. `wp_enqueue_scripts` is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because `wp_head` runs before `the_content` which means that you won't be able to modify the head once your code gets to `the_content`. First let's register our style using the `wp_enqueue_scripts` action. ``` /** * Register the gallery stylesheet for later use if our content contains the gallery shortcode. */ function enqueue_gallery_style(){ wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css'); } add_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action ``` We register the script using the `wp_register_style` function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it "gallery\_style". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on [wp\_register\_style](https://codex.wordpress.org/Function_Reference/wp_register_style) Now we can add another `the_content` filter in addition to your `image_posts` filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the `wp_enqueue_style` function to enqueue our gallery style and add it to that specific page. ``` /** * This function is used to check the_content to see if it contains any shortcodes * * @param $content * * @return string */ function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it. } return $content; // Make sure you still return your content or else nothing will display. } add_filter( 'the_content', 'shortcode_check' ); ``` More info on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) **Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.** If you need to output styles that are generated via the admin (ie, colors) you can utilize the `wp_add_inline_style` function. This function will allow you to add on styles to a registered stylesheet. So in the case of our already registered gallery.css file above, we can add `wp_add_inline_style( 'gallery_style', $user_css );` and it will add that as an inline style immediately after registered stylesheet. Here `$user_css` would be the styles as a string **without** the `<style>` wrapper. So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles. ``` function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style('gallery_style'); wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!! } return $content; // Make sure you still return your content or else nothing will display. } ``` More on [wp\_add\_inline\_style](https://codex.wordpress.org/Function_Reference/wp_add_inline_style)
262,491
<p>I am making a theme that will be updateable via github. <a href="https://github.com/pallazzio/skeleton" rel="nofollow noreferrer">https://github.com/pallazzio/skeleton</a></p> <p>I am trying to use the plugin updater tutorial from smashing magazine, modified for updating a theme instead. <a href="https://www.smashingmagazine.com/2015/08/deploy-wordpress-plugins-with-github-using-transients/" rel="nofollow noreferrer">https://www.smashingmagazine.com/2015/08/deploy-wordpress-plugins-with-github-using-transients/</a></p> <p>I got it almost working. The update gets downloaded and installed to the correct folder. However, instead of leaving the same theme active, it is activating a new theme whose name is pallazzio-skeleton-b203a7f.</p> <p>The weird part is that there is no folder created with that name. The files get installed to the correct place. The update is fully functional once I switch the active theme back to the original theme name.</p> <p>The only thing I need to finish is how to make sure the current active theme doesn't change to a random name. I'm stuck.</p> <p>Any help would be greatly appreciated.</p> <p>Here is the relevant part in functions.php</p> <pre><code>// Init theme updater if( ! class_exists( 'Pallazzio_Theme_Updater' ) ){ include_once( 'updater.php' ); } $updater = new Pallazzio_Theme_Updater( 'skeleton' ); $updater-&gt;set_username( 'pallazzio' ); $updater-&gt;set_repository( 'skeleton' ); //$updater-&gt;authorize( 'abcdefghijk1234567890' ); // auth code for private repos $updater-&gt;initialize(); </code></pre> <p>Here is the contents of updater.php</p> <pre><code>&lt;?php class Pallazzio_Theme_Updater { private $theme; private $username; private $repository; private $authorize_token; private $github_response; public function __construct( $theme ) { $this-&gt;theme = wp_get_theme( $theme ); return $this; } public function set_username( $username ) { $this-&gt;username = $username; } public function set_repository( $repository ) { $this-&gt;repository = $repository; } public function authorize( $token ) { $this-&gt;authorize_token = $token; } public function initialize() { add_filter( 'pre_set_site_transient_update_themes', array( $this, 'modify_transient' ), 10, 1 ); add_filter( 'upgrader_post_install', array( $this, 'after_install' ), 10, 3 ); } public function modify_transient( $transient ) { if( property_exists( $transient, 'checked') ) { // Check if transient has a checked property if( $checked = $transient-&gt;checked ) { // Did Wordpress check for updates? $this-&gt;get_repository_info(); // Get the repo info $out_of_date = version_compare( $this-&gt;github_response['tag_name'], $checked[ $this-&gt;theme-&gt;template ], 'gt' ); // Check if we're out of date if( $out_of_date ) { $new_files = $this-&gt;github_response['zipball_url']; // Get the ZIP $theme = array( // setup our theme info 'theme' =&gt; $this-&gt;theme-&gt;template, 'url' =&gt; $this-&gt;theme-&gt;get( 'ThemeURI' ), 'package' =&gt; $new_files, 'new_version' =&gt; $this-&gt;github_response['tag_name'] ); $transient-&gt;response[$this-&gt;theme-&gt;template] = $theme; // Return it in response } } } return $transient; // Return filtered transient } public function after_install( $response, $hook_extra, $result ) { global $wp_filesystem; // Get global FS object $install_directory = get_template_directory(); // Our theme directory $result['destination_name'] = $this-&gt;theme-&gt;template; // Set the destination name for the rest of the stack $result['remote_destination'] = $install_directory; // Set the remote destination for the rest of the stack $wp_filesystem-&gt;move( $result['destination'], $install_directory ); // Move files to the theme dir $result['destination'] = $install_directory; // Set the destination for the rest of the stack //switch_theme( $this-&gt;theme-&gt;template ); return $result; } private function get_repository_info() { if ( is_null( $this-&gt;github_response ) ) { // Do we have a response? $request_uri = sprintf( 'https://api.github.com/repos/%s/%s/releases', $this-&gt;username, $this-&gt;repository ); // Build URI if( $this-&gt;authorize_token ) { // Is there an access token? $request_uri = add_query_arg( 'access_token', $this-&gt;authorize_token, $request_uri ); // Append it } $response = json_decode( wp_remote_retrieve_body( wp_remote_get( $request_uri ) ), true ); // Get JSON and parse it if( is_array( $response ) ) { // If it is an array $response = current( $response ); // Get the first item } if( $this-&gt;authorize_token ) { // Is there an access token? $response['zipball_url'] = add_query_arg( 'access_token', $this-&gt;authorize_token, $response['zipball_url'] ); // Update our zip url with token } $this-&gt;github_response = $response; } } } ?&gt; </code></pre>
[ { "answer_id": 262487, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 1, "selected": false, "text": "<p>For this, you'll actually want to utilize the <code>wp_enqueue_scripts</code> action instead of <code>wp_head</code>.</p>\n\n<p><code>wp_enqueue_scripts</code> is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because <code>wp_head</code> runs before <code>the_content</code> which means that you won't be able to modify the head once your code gets to <code>the_content</code>.</p>\n\n<p>First let's register our style using the <code>wp_enqueue_scripts</code> action.</p>\n\n<pre><code>/**\n * Register the gallery stylesheet for later use if our content contains the gallery shortcode.\n */\nfunction enqueue_gallery_style(){\n wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css');\n}\nadd_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action\n</code></pre>\n\n<p>We register the script using the <code>wp_register_style</code> function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it \"gallery_style\". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">wp_register_style</a></p>\n\n<p>Now we can add another <code>the_content</code> filter in addition to your <code>image_posts</code> filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the <code>wp_enqueue_style</code> function to enqueue our gallery style and add it to that specific page.</p>\n\n<pre><code>/**\n * This function is used to check the_content to see if it contains any shortcodes\n *\n * @param $content\n *\n * @return string\n */\n\nfunction shortcode_check( $content ) {\n\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it.\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\nadd_filter( 'the_content', 'shortcode_check' );\n</code></pre>\n\n<p>More info on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a></p>\n\n<p><strong>Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.</strong></p>\n\n<p>If you need to output styles that are generated via the admin (ie, colors) you can utilize the <code>wp_add_inline_style</code> function.</p>\n\n<p>This function will allow you to add on styles to a registered stylesheet.\nSo in the case of our already registered gallery.css file above, we can add\n<code>wp_add_inline_style( 'gallery_style', $user_css );</code> and it will add that as an inline style immediately after registered stylesheet.</p>\n\n<p>Here <code>$user_css</code> would be the styles as a string <strong>without</strong> the <code>&lt;style&gt;</code> wrapper.</p>\n\n<p>So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles.</p>\n\n<pre><code>function shortcode_check( $content ) {\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style('gallery_style');\n wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!!\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\n</code></pre>\n\n<p>More on <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style\" rel=\"nofollow noreferrer\">wp_add_inline_style</a></p>\n" }, { "answer_id": 262489, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>You can actually enqueue styles and scripts from any hook. If <code>wp_head()</code> had already fired, then the styles and/or scripts will be enqueued into the footer.</p>\n\n<pre><code>//* Add filter to the_content\nadd_filter( 'the_content', 'wpse_262484_the_content' );\nfunction wpse_262484_the_content( $content ) {\n\n //* Maybe do something useful with $content\n\n //* Enqueue style if the content has gallery shortcode\n //* Since wp_head() has already fired, this will be output in the footer\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'wpse-262484', PATH_TO . 'style.css' );\n }\n return $content;\n}\n</code></pre>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115138/" ]
I am making a theme that will be updateable via github. <https://github.com/pallazzio/skeleton> I am trying to use the plugin updater tutorial from smashing magazine, modified for updating a theme instead. <https://www.smashingmagazine.com/2015/08/deploy-wordpress-plugins-with-github-using-transients/> I got it almost working. The update gets downloaded and installed to the correct folder. However, instead of leaving the same theme active, it is activating a new theme whose name is pallazzio-skeleton-b203a7f. The weird part is that there is no folder created with that name. The files get installed to the correct place. The update is fully functional once I switch the active theme back to the original theme name. The only thing I need to finish is how to make sure the current active theme doesn't change to a random name. I'm stuck. Any help would be greatly appreciated. Here is the relevant part in functions.php ``` // Init theme updater if( ! class_exists( 'Pallazzio_Theme_Updater' ) ){ include_once( 'updater.php' ); } $updater = new Pallazzio_Theme_Updater( 'skeleton' ); $updater->set_username( 'pallazzio' ); $updater->set_repository( 'skeleton' ); //$updater->authorize( 'abcdefghijk1234567890' ); // auth code for private repos $updater->initialize(); ``` Here is the contents of updater.php ``` <?php class Pallazzio_Theme_Updater { private $theme; private $username; private $repository; private $authorize_token; private $github_response; public function __construct( $theme ) { $this->theme = wp_get_theme( $theme ); return $this; } public function set_username( $username ) { $this->username = $username; } public function set_repository( $repository ) { $this->repository = $repository; } public function authorize( $token ) { $this->authorize_token = $token; } public function initialize() { add_filter( 'pre_set_site_transient_update_themes', array( $this, 'modify_transient' ), 10, 1 ); add_filter( 'upgrader_post_install', array( $this, 'after_install' ), 10, 3 ); } public function modify_transient( $transient ) { if( property_exists( $transient, 'checked') ) { // Check if transient has a checked property if( $checked = $transient->checked ) { // Did Wordpress check for updates? $this->get_repository_info(); // Get the repo info $out_of_date = version_compare( $this->github_response['tag_name'], $checked[ $this->theme->template ], 'gt' ); // Check if we're out of date if( $out_of_date ) { $new_files = $this->github_response['zipball_url']; // Get the ZIP $theme = array( // setup our theme info 'theme' => $this->theme->template, 'url' => $this->theme->get( 'ThemeURI' ), 'package' => $new_files, 'new_version' => $this->github_response['tag_name'] ); $transient->response[$this->theme->template] = $theme; // Return it in response } } } return $transient; // Return filtered transient } public function after_install( $response, $hook_extra, $result ) { global $wp_filesystem; // Get global FS object $install_directory = get_template_directory(); // Our theme directory $result['destination_name'] = $this->theme->template; // Set the destination name for the rest of the stack $result['remote_destination'] = $install_directory; // Set the remote destination for the rest of the stack $wp_filesystem->move( $result['destination'], $install_directory ); // Move files to the theme dir $result['destination'] = $install_directory; // Set the destination for the rest of the stack //switch_theme( $this->theme->template ); return $result; } private function get_repository_info() { if ( is_null( $this->github_response ) ) { // Do we have a response? $request_uri = sprintf( 'https://api.github.com/repos/%s/%s/releases', $this->username, $this->repository ); // Build URI if( $this->authorize_token ) { // Is there an access token? $request_uri = add_query_arg( 'access_token', $this->authorize_token, $request_uri ); // Append it } $response = json_decode( wp_remote_retrieve_body( wp_remote_get( $request_uri ) ), true ); // Get JSON and parse it if( is_array( $response ) ) { // If it is an array $response = current( $response ); // Get the first item } if( $this->authorize_token ) { // Is there an access token? $response['zipball_url'] = add_query_arg( 'access_token', $this->authorize_token, $response['zipball_url'] ); // Update our zip url with token } $this->github_response = $response; } } } ?> ```
For this, you'll actually want to utilize the `wp_enqueue_scripts` action instead of `wp_head`. `wp_enqueue_scripts` is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because `wp_head` runs before `the_content` which means that you won't be able to modify the head once your code gets to `the_content`. First let's register our style using the `wp_enqueue_scripts` action. ``` /** * Register the gallery stylesheet for later use if our content contains the gallery shortcode. */ function enqueue_gallery_style(){ wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css'); } add_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action ``` We register the script using the `wp_register_style` function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it "gallery\_style". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on [wp\_register\_style](https://codex.wordpress.org/Function_Reference/wp_register_style) Now we can add another `the_content` filter in addition to your `image_posts` filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the `wp_enqueue_style` function to enqueue our gallery style and add it to that specific page. ``` /** * This function is used to check the_content to see if it contains any shortcodes * * @param $content * * @return string */ function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it. } return $content; // Make sure you still return your content or else nothing will display. } add_filter( 'the_content', 'shortcode_check' ); ``` More info on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) **Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.** If you need to output styles that are generated via the admin (ie, colors) you can utilize the `wp_add_inline_style` function. This function will allow you to add on styles to a registered stylesheet. So in the case of our already registered gallery.css file above, we can add `wp_add_inline_style( 'gallery_style', $user_css );` and it will add that as an inline style immediately after registered stylesheet. Here `$user_css` would be the styles as a string **without** the `<style>` wrapper. So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles. ``` function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style('gallery_style'); wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!! } return $content; // Make sure you still return your content or else nothing will display. } ``` More on [wp\_add\_inline\_style](https://codex.wordpress.org/Function_Reference/wp_add_inline_style)
262,506
<p>I would like to show comment count IN the post (not in post meta), is there a snippet how to do this or a wordpress internal shortcode? </p>
[ { "answer_id": 262487, "author": "Ian", "author_id": 11583, "author_profile": "https://wordpress.stackexchange.com/users/11583", "pm_score": 1, "selected": false, "text": "<p>For this, you'll actually want to utilize the <code>wp_enqueue_scripts</code> action instead of <code>wp_head</code>.</p>\n\n<p><code>wp_enqueue_scripts</code> is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because <code>wp_head</code> runs before <code>the_content</code> which means that you won't be able to modify the head once your code gets to <code>the_content</code>.</p>\n\n<p>First let's register our style using the <code>wp_enqueue_scripts</code> action.</p>\n\n<pre><code>/**\n * Register the gallery stylesheet for later use if our content contains the gallery shortcode.\n */\nfunction enqueue_gallery_style(){\n wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css');\n}\nadd_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action\n</code></pre>\n\n<p>We register the script using the <code>wp_register_style</code> function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it \"gallery_style\". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">wp_register_style</a></p>\n\n<p>Now we can add another <code>the_content</code> filter in addition to your <code>image_posts</code> filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the <code>wp_enqueue_style</code> function to enqueue our gallery style and add it to that specific page.</p>\n\n<pre><code>/**\n * This function is used to check the_content to see if it contains any shortcodes\n *\n * @param $content\n *\n * @return string\n */\n\nfunction shortcode_check( $content ) {\n\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it.\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\nadd_filter( 'the_content', 'shortcode_check' );\n</code></pre>\n\n<p>More info on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a></p>\n\n<p><strong>Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.</strong></p>\n\n<p>If you need to output styles that are generated via the admin (ie, colors) you can utilize the <code>wp_add_inline_style</code> function.</p>\n\n<p>This function will allow you to add on styles to a registered stylesheet.\nSo in the case of our already registered gallery.css file above, we can add\n<code>wp_add_inline_style( 'gallery_style', $user_css );</code> and it will add that as an inline style immediately after registered stylesheet.</p>\n\n<p>Here <code>$user_css</code> would be the styles as a string <strong>without</strong> the <code>&lt;style&gt;</code> wrapper.</p>\n\n<p>So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles.</p>\n\n<pre><code>function shortcode_check( $content ) {\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style('gallery_style');\n wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!!\n }\n\n return $content; // Make sure you still return your content or else nothing will display.\n}\n</code></pre>\n\n<p>More on <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style\" rel=\"nofollow noreferrer\">wp_add_inline_style</a></p>\n" }, { "answer_id": 262489, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>You can actually enqueue styles and scripts from any hook. If <code>wp_head()</code> had already fired, then the styles and/or scripts will be enqueued into the footer.</p>\n\n<pre><code>//* Add filter to the_content\nadd_filter( 'the_content', 'wpse_262484_the_content' );\nfunction wpse_262484_the_content( $content ) {\n\n //* Maybe do something useful with $content\n\n //* Enqueue style if the content has gallery shortcode\n //* Since wp_head() has already fired, this will be output in the footer\n if ( has_shortcode( $content, 'gallery' ) ) {\n wp_enqueue_style( 'wpse-262484', PATH_TO . 'style.css' );\n }\n return $content;\n}\n</code></pre>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262506", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102691/" ]
I would like to show comment count IN the post (not in post meta), is there a snippet how to do this or a wordpress internal shortcode?
For this, you'll actually want to utilize the `wp_enqueue_scripts` action instead of `wp_head`. `wp_enqueue_scripts` is technically the proper way to add scripts and styles to your site. This action allows us to both register scripts and styles for later use (which is what we want here) and allows us to output scripts and styles to our page without hard coding. Also this matters because `wp_head` runs before `the_content` which means that you won't be able to modify the head once your code gets to `the_content`. First let's register our style using the `wp_enqueue_scripts` action. ``` /** * Register the gallery stylesheet for later use if our content contains the gallery shortcode. */ function enqueue_gallery_style(){ wp_register_style('gallery_style', get_stylesheet_directory_uri() . '/assets/css/gallery.css'); } add_action('wp_enqueue_scripts', 'enqueue_gallery_style'); // register with the wp_enqueue_scripts action ``` We register the script using the `wp_register_style` function. In this case we'll make use of the first two parameters. The first is the name we want to give to the style so we can use it later. You can name it whatever you want. Here I've named it "gallery\_style". The second parameter is the url path to the stylesheet in your theme or plugin (make sure to update based on your specific path). Here are more details on [wp\_register\_style](https://codex.wordpress.org/Function_Reference/wp_register_style) Now we can add another `the_content` filter in addition to your `image_posts` filter to perform the shortcode conditional check. Inside the check, if we find it, then we run the `wp_enqueue_style` function to enqueue our gallery style and add it to that specific page. ``` /** * This function is used to check the_content to see if it contains any shortcodes * * @param $content * * @return string */ function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style( 'gallery_style' ); // this is the same name we gave our gallery style when we registered it. } return $content; // Make sure you still return your content or else nothing will display. } add_filter( 'the_content', 'shortcode_check' ); ``` More info on [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) **Method if you are trying to add admin-generated styles (eg. from customizer or other settings) that won't have a physical file.** If you need to output styles that are generated via the admin (ie, colors) you can utilize the `wp_add_inline_style` function. This function will allow you to add on styles to a registered stylesheet. So in the case of our already registered gallery.css file above, we can add `wp_add_inline_style( 'gallery_style', $user_css );` and it will add that as an inline style immediately after registered stylesheet. Here `$user_css` would be the styles as a string **without** the `<style>` wrapper. So in your case, you could register a stylesheet for gallery with some base styles and then use this function to add styles that would override those base styles. ``` function shortcode_check( $content ) { if ( has_shortcode( $content, 'gallery' ) ) { wp_enqueue_style('gallery_style'); wp_add_inline_style( 'gallery_style', $user_css ); // this will add our inline styles. Make sure to sanitize!!! } return $content; // Make sure you still return your content or else nothing will display. } ``` More on [wp\_add\_inline\_style](https://codex.wordpress.org/Function_Reference/wp_add_inline_style)
262,527
<p>On one particular site, when I do a search, not all relevant results are returned.</p> <p>Example:</p> <p>Post Title: This is xxx</p> <p>Post Content: Hello World, this is xxx.</p> <p>When searching for 'xxx', the post isn't returned in the search results.</p> <p>Is this expected behaviour, and how do I fix this?</p> <p>This is the code for the search template:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="vw-page-wrapper clearfix"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="vw-page-content col-md-8" role="main"&gt; &lt;?php do_action( 'vw_action_before_archive_posts' ); ?&gt; &lt;?php get_template_part( 'templates/post-box/post-layout-'.vw_get_archive_blog_layout() ); ?&gt; &lt;?php do_action( 'vw_action_after_archive_posts' ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 262524, "author": "Shivanand Sharma", "author_id": 116231, "author_profile": "https://wordpress.stackexchange.com/users/116231", "pm_score": 0, "selected": false, "text": "<p>The function <code>wp_send_new_user_notifications</code> automatically sends the registration info of new users to admin. Just try this line of code and it should do the needful.</p>\n\n<pre><code>add_action('register_new_user','wp_send_new_user_notifications');\n</code></pre>\n" }, { "answer_id": 262525, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": 1, "selected": false, "text": "<p>You can get the last inserted id at the time of registration and with this id get the user meta by meta keys you assign and send mail with details.</p>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50432/" ]
On one particular site, when I do a search, not all relevant results are returned. Example: Post Title: This is xxx Post Content: Hello World, this is xxx. When searching for 'xxx', the post isn't returned in the search results. Is this expected behaviour, and how do I fix this? This is the code for the search template: ``` <?php get_header(); ?> <div class="vw-page-wrapper clearfix"> <div class="container"> <div class="row"> <div class="vw-page-content col-md-8" role="main"> <?php do_action( 'vw_action_before_archive_posts' ); ?> <?php get_template_part( 'templates/post-box/post-layout-'.vw_get_archive_blog_layout() ); ?> <?php do_action( 'vw_action_after_archive_posts' ); ?> </div> </div> </div> </div> <?php get_footer(); ?> ```
You can get the last inserted id at the time of registration and with this id get the user meta by meta keys you assign and send mail with details.
262,534
<pre><code> register_setting('Y-sidebar-options','picture'); </code></pre> <p>where do the option group name stored in database . </p>
[ { "answer_id": 262524, "author": "Shivanand Sharma", "author_id": 116231, "author_profile": "https://wordpress.stackexchange.com/users/116231", "pm_score": 0, "selected": false, "text": "<p>The function <code>wp_send_new_user_notifications</code> automatically sends the registration info of new users to admin. Just try this line of code and it should do the needful.</p>\n\n<pre><code>add_action('register_new_user','wp_send_new_user_notifications');\n</code></pre>\n" }, { "answer_id": 262525, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": 1, "selected": false, "text": "<p>You can get the last inserted id at the time of registration and with this id get the user meta by meta keys you assign and send mail with details.</p>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262534", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116882/" ]
``` register_setting('Y-sidebar-options','picture'); ``` where do the option group name stored in database .
You can get the last inserted id at the time of registration and with this id get the user meta by meta keys you assign and send mail with details.
262,569
<p>Any reason this code does not work in the admin section (specifically when ajaxing but the issue persists on other pages) of WordPress but works just fine</p> <pre><code>ob_start(); dynamic_sidebar('frontpage_widgets'); $content = ob_get_clean(); print_r($content); // nothing </code></pre> <p>the sidebars are set from what I see (because I have called my code which registered the sidebars)</p> <p><code>print_r($GLOBALS['wp_registered_sidebars'])</code></p> <pre><code> Array ( [frontpage_widgets] =&gt; Array ( [name] =&gt; Frontpage Widgets [id] =&gt; frontpage_widgets [description] =&gt; Widgets for the Frontpage Widgetspage [class] =&gt; [before_widget] =&gt; ... </code></pre> <p>Is there something preventing the widgets from displaying in the admin section?</p> <p>Edit - I seems that the widgets are not being set globally: $wp_registered_widgets is empty</p>
[ { "answer_id": 262990, "author": "Atul Jindal", "author_id": 58957, "author_profile": "https://wordpress.stackexchange.com/users/58957", "pm_score": -1, "selected": false, "text": "<p>Try to logout the admin, and then see the code behavior. Sometimes, due to login session this behavior is seen. If you provide more details to your question, it might be helpful to give better answer.</p>\n" }, { "answer_id": 263044, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 3, "selected": true, "text": "<p>Yes, you have to make sure to hook this function at some point after the sidebars are registered. It's not quite explained, but implied in the codex that this function <a href=\"https://codex.wordpress.org/Function_Reference/dynamic_sidebar\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar( $index )</code></a> expects them to be registered and loaded as registered by the time it runs. Otherwise, it won't have anything to match the <code>$index</code> argument, which in your case is <code>'frontpage_widgets'</code>. </p>\n\n<blockquote>\n <p>If your sidebars were registered by number, they should be retrieved\n by number. If they had names when you registered them, use their names\n to retrieve them.</p>\n</blockquote>\n\n<p>If I had to guess off hand, I'd say <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded()</code></a> is the earliest action you can safely hook it to. Or if you need to, you can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_register_sidebar_widget\" rel=\"nofollow noreferrer\"><code>wp_register_sidebar_widget</code></a> to hook into the specific widget you are testing for.</p>\n\n<p>I assume you were just using the object buffering for debugging purposes. You can almost always find an appropriate action to hook or area of your template to edit. I'm finding that understanding the order in which actions are fired is invaluable. Take a look at this <a href=\"https://wordpress.stackexchange.com/a/162869/33393\">answer by birgire</a> as a good reference for when different actions are fired. This will make debugging a lot easier. Usually, finding the proper place to hook will be fairly intuitive depending on what you're working with. </p>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19536/" ]
Any reason this code does not work in the admin section (specifically when ajaxing but the issue persists on other pages) of WordPress but works just fine ``` ob_start(); dynamic_sidebar('frontpage_widgets'); $content = ob_get_clean(); print_r($content); // nothing ``` the sidebars are set from what I see (because I have called my code which registered the sidebars) `print_r($GLOBALS['wp_registered_sidebars'])` ``` Array ( [frontpage_widgets] => Array ( [name] => Frontpage Widgets [id] => frontpage_widgets [description] => Widgets for the Frontpage Widgetspage [class] => [before_widget] => ... ``` Is there something preventing the widgets from displaying in the admin section? Edit - I seems that the widgets are not being set globally: $wp\_registered\_widgets is empty
Yes, you have to make sure to hook this function at some point after the sidebars are registered. It's not quite explained, but implied in the codex that this function [`dynamic_sidebar( $index )`](https://codex.wordpress.org/Function_Reference/dynamic_sidebar) expects them to be registered and loaded as registered by the time it runs. Otherwise, it won't have anything to match the `$index` argument, which in your case is `'frontpage_widgets'`. > > If your sidebars were registered by number, they should be retrieved > by number. If they had names when you registered them, use their names > to retrieve them. > > > If I had to guess off hand, I'd say [`wp_loaded()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded) is the earliest action you can safely hook it to. Or if you need to, you can hook into [`wp_register_sidebar_widget`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_register_sidebar_widget) to hook into the specific widget you are testing for. I assume you were just using the object buffering for debugging purposes. You can almost always find an appropriate action to hook or area of your template to edit. I'm finding that understanding the order in which actions are fired is invaluable. Take a look at this [answer by birgire](https://wordpress.stackexchange.com/a/162869/33393) as a good reference for when different actions are fired. This will make debugging a lot easier. Usually, finding the proper place to hook will be fairly intuitive depending on what you're working with.
262,579
<p>I'm trying to create a code that will show the a photo if there is featured image otherwise it will just show the page title. This code is in my header as it's near the logo.</p> <p>When I use this code on a page without a featured image:</p> <pre><code>&lt;?php if ( get_post_thumbnail_id() =='' ) { echo 'no picture'; echo 'its id is '.get_post_thumbnail_id(); } else { echo 'there is a thumbnail'; echo 'its id is '.get_post_thumbnail_id(); } ?&gt; </code></pre> <p>It returns "there is a thumbnail it's id is -3."</p> <p>When I run this code on a page without a featured image:</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) :?&gt; &lt;img class="img-responsive logo-main scale-with-grid" src="&lt;?php the_post_thumbnail_url('full'); ?&gt;"/&gt; &lt;div class='text-box'&gt; &lt;p class='dataNumber title'&gt;&lt;?php the_title();?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;div class="logo-main scale-with-grid"&gt;no postthumb&lt;/div&gt; &lt;div class='text-box'&gt; &lt;p class='dataNumber title'&gt;&lt;?php the_title();?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>IT returns this:</p> <pre><code>&lt;div class="containerBox"&gt; &lt;img class="img-responsive logo-main scale-with-grid" src=""&gt; &lt;div class="text-box"&gt; &lt;p class="dataNumber title"&gt;Careers &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If i set a featured image both codes run fine.</p> <p>Per Jack I tried this with the same result:</p> <pre><code>if ( has_post_thumbnail(get_the_id()) ) { echo 'there is a thumbnail for post '.get_the_id().' its id is '.get_post_thumbnail_id(); } else { echo 'no picture for post '.get_the_id(); } </code></pre> <p>it does display the right page id though.</p>
[ { "answer_id": 262990, "author": "Atul Jindal", "author_id": 58957, "author_profile": "https://wordpress.stackexchange.com/users/58957", "pm_score": -1, "selected": false, "text": "<p>Try to logout the admin, and then see the code behavior. Sometimes, due to login session this behavior is seen. If you provide more details to your question, it might be helpful to give better answer.</p>\n" }, { "answer_id": 263044, "author": "iyrin", "author_id": 33393, "author_profile": "https://wordpress.stackexchange.com/users/33393", "pm_score": 3, "selected": true, "text": "<p>Yes, you have to make sure to hook this function at some point after the sidebars are registered. It's not quite explained, but implied in the codex that this function <a href=\"https://codex.wordpress.org/Function_Reference/dynamic_sidebar\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar( $index )</code></a> expects them to be registered and loaded as registered by the time it runs. Otherwise, it won't have anything to match the <code>$index</code> argument, which in your case is <code>'frontpage_widgets'</code>. </p>\n\n<blockquote>\n <p>If your sidebars were registered by number, they should be retrieved\n by number. If they had names when you registered them, use their names\n to retrieve them.</p>\n</blockquote>\n\n<p>If I had to guess off hand, I'd say <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded\" rel=\"nofollow noreferrer\"><code>wp_loaded()</code></a> is the earliest action you can safely hook it to. Or if you need to, you can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_register_sidebar_widget\" rel=\"nofollow noreferrer\"><code>wp_register_sidebar_widget</code></a> to hook into the specific widget you are testing for.</p>\n\n<p>I assume you were just using the object buffering for debugging purposes. You can almost always find an appropriate action to hook or area of your template to edit. I'm finding that understanding the order in which actions are fired is invaluable. Take a look at this <a href=\"https://wordpress.stackexchange.com/a/162869/33393\">answer by birgire</a> as a good reference for when different actions are fired. This will make debugging a lot easier. Usually, finding the proper place to hook will be fairly intuitive depending on what you're working with. </p>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I'm trying to create a code that will show the a photo if there is featured image otherwise it will just show the page title. This code is in my header as it's near the logo. When I use this code on a page without a featured image: ``` <?php if ( get_post_thumbnail_id() =='' ) { echo 'no picture'; echo 'its id is '.get_post_thumbnail_id(); } else { echo 'there is a thumbnail'; echo 'its id is '.get_post_thumbnail_id(); } ?> ``` It returns "there is a thumbnail it's id is -3." When I run this code on a page without a featured image: ``` <?php if ( has_post_thumbnail() ) :?> <img class="img-responsive logo-main scale-with-grid" src="<?php the_post_thumbnail_url('full'); ?>"/> <div class='text-box'> <p class='dataNumber title'><?php the_title();?> </p> </div> </div> <?php else: ?> <div class="logo-main scale-with-grid">no postthumb</div> <div class='text-box'> <p class='dataNumber title'><?php the_title();?> </p> </div> </div> <?php endif; ?> ``` IT returns this: ``` <div class="containerBox"> <img class="img-responsive logo-main scale-with-grid" src=""> <div class="text-box"> <p class="dataNumber title">Careers </p> </div> </div> ``` If i set a featured image both codes run fine. Per Jack I tried this with the same result: ``` if ( has_post_thumbnail(get_the_id()) ) { echo 'there is a thumbnail for post '.get_the_id().' its id is '.get_post_thumbnail_id(); } else { echo 'no picture for post '.get_the_id(); } ``` it does display the right page id though.
Yes, you have to make sure to hook this function at some point after the sidebars are registered. It's not quite explained, but implied in the codex that this function [`dynamic_sidebar( $index )`](https://codex.wordpress.org/Function_Reference/dynamic_sidebar) expects them to be registered and loaded as registered by the time it runs. Otherwise, it won't have anything to match the `$index` argument, which in your case is `'frontpage_widgets'`. > > If your sidebars were registered by number, they should be retrieved > by number. If they had names when you registered them, use their names > to retrieve them. > > > If I had to guess off hand, I'd say [`wp_loaded()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_loaded) is the earliest action you can safely hook it to. Or if you need to, you can hook into [`wp_register_sidebar_widget`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_register_sidebar_widget) to hook into the specific widget you are testing for. I assume you were just using the object buffering for debugging purposes. You can almost always find an appropriate action to hook or area of your template to edit. I'm finding that understanding the order in which actions are fired is invaluable. Take a look at this [answer by birgire](https://wordpress.stackexchange.com/a/162869/33393) as a good reference for when different actions are fired. This will make debugging a lot easier. Usually, finding the proper place to hook will be fairly intuitive depending on what you're working with.
262,582
<p>I want to add a custom image size to my child theme.</p> <p>The base is the Penscratch theme, and it has it own image sizes defined:</p> <pre><code>function penscratch_setup() { /* ... */ add_theme_support( 'post-thumbnails' ); add_image_size( 'penscratch-featured', '400', '200', true ); /* ... */ } </code></pre> <p>And if I made some changes here (base functions.php), everything work as it should, But the point is to make it done in child-Theme, I'm writing it the same way but for some reason it's not working:</p> <pre><code>add_action( 'after_setup_teme', 'add_custom_img_sizes'); function add_custom_img_sizes() { add_theme_support( 'post-thumbnails' ); add_image_size( 'category-thumbnail', '300', '200', true ); } </code></pre> <p>if I use then the 'category-thumbnail' in my template, it is displaying the full-sized image, not the cropped one, what is going wrong here?</p>
[ { "answer_id": 262583, "author": "Shivanand Sharma", "author_id": 116231, "author_profile": "https://wordpress.stackexchange.com/users/116231", "pm_score": 3, "selected": true, "text": "<p>After you add a new image size, you have to regenerate the images for that size. The <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">Regenerate Thumbnails</a> plugin comes in handy for this purpose.</p>\n" }, { "answer_id": 262584, "author": "ahmad araj", "author_id": 94726, "author_profile": "https://wordpress.stackexchange.com/users/94726", "pm_score": 0, "selected": false, "text": "<p>You have to add the handle name in your the post thumbnail </p>\n\n<pre><code> the_post_thumbnail( 'category-thumbnail' );\n</code></pre>\n" }, { "answer_id": 313416, "author": "pjehan", "author_id": 150037, "author_profile": "https://wordpress.stackexchange.com/users/150037", "pm_score": 1, "selected": false, "text": "<p>Now you can use the Command Line Interface (CLI) to regenerate the thumbnails using the <a href=\"https://developer.wordpress.org/cli/commands/media/regenerate/\" rel=\"nofollow noreferrer\">wp media regenerate</a> command:</p>\n\n<pre><code>wp media regenerate\n</code></pre>\n\n<p>Have a look at <a href=\"https://make.wordpress.org/cli/handbook/installing/\" rel=\"nofollow noreferrer\">this page</a> and follow the steps to install the <strong>wp</strong> command.</p>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116999/" ]
I want to add a custom image size to my child theme. The base is the Penscratch theme, and it has it own image sizes defined: ``` function penscratch_setup() { /* ... */ add_theme_support( 'post-thumbnails' ); add_image_size( 'penscratch-featured', '400', '200', true ); /* ... */ } ``` And if I made some changes here (base functions.php), everything work as it should, But the point is to make it done in child-Theme, I'm writing it the same way but for some reason it's not working: ``` add_action( 'after_setup_teme', 'add_custom_img_sizes'); function add_custom_img_sizes() { add_theme_support( 'post-thumbnails' ); add_image_size( 'category-thumbnail', '300', '200', true ); } ``` if I use then the 'category-thumbnail' in my template, it is displaying the full-sized image, not the cropped one, what is going wrong here?
After you add a new image size, you have to regenerate the images for that size. The [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) plugin comes in handy for this purpose.
262,593
<p>I'm working on a WordPress website and I'd like to modify the password reset screen <code>/wp-login.php?action=rp</code>. Currently, the password reset screen generates a new password for the user and I want to add a <code>Confirm Password</code> field and make it a required field.</p> <p>I think I've found the relevant code in the <code>wp-login.php</code> file and it looks like there is a confirm password option but I don't know how to get it to appear.</p> <pre><code>&lt;form name="resetpassform" id="resetpassform" action="&lt;?php echo esc_url( network_site_url( 'wp-login.php?action=resetpass', 'login_post' ) ); ?&gt;" method="post" autocomplete="off"&gt; &lt;input type="hidden" id="user_login" value="&lt;?php echo esc_attr( $rp_login ); ?&gt;" autocomplete="off" /&gt; &lt;div class="user-pass1-wrap"&gt; &lt;p&gt; &lt;label for="pass1"&gt;&lt;?php _e( 'New password' ) ?&gt;&lt;/label&gt; &lt;/p&gt; &lt;div class="wp-pwd"&gt; &lt;span class="password-input-wrapper"&gt; &lt;input type="password" data-reveal="1" data-pw="&lt;?php echo esc_attr( wp_generate_password( 16 ) ); ?&gt;" name="pass1" id="pass1" class="input" size="20" value="" autocomplete="off" aria-describedby="pass-strength-result" /&gt; &lt;/span&gt; &lt;div id="pass-strength-result" class="hide-if-no-js" aria-live="polite"&gt;&lt;?php _e( 'Strength indicator' ); ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p class="user-pass2-wrap"&gt; &lt;label for="pass2"&gt;&lt;?php _e( 'Confirm new password' ) ?&gt;&lt;/label&gt;&lt;br /&gt; &lt;input type="password" name="pass2" id="pass2" class="input" size="20" value="" autocomplete="off" /&gt; &lt;/p&gt; &lt;p class="description indicator-hint"&gt;&lt;?php echo wp_get_password_hint(); ?&gt;&lt;/p&gt; &lt;br class="clear" /&gt; &lt;?php /** * Fires following the 'Strength indicator' meter in the user password reset form. * * @since 3.9.0 * * @param WP_User $user User object of the user whose password is being reset. */ do_action( 'resetpass_form', $user ); ?&gt; &lt;input type="hidden" name="rp_key" value="&lt;?php echo esc_attr( $rp_key ); ?&gt;" /&gt; &lt;p class="submit"&gt;&lt;input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="&lt;?php esc_attr_e('Reset Password'); ?&gt;" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 262607, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>It's tempting to unhide the <code>pass2</code> input but that's not enough. </p>\n\n<p>In the file <code>/wp-admin/js/user-profile.js</code> the <code>bindPass1()</code> binds it to <code>pass1</code> that makes writing to it not possible. The <code>pass2</code> input is then hidden in <code>bindPasswordForm()</code> with <code>$('.user-pass2-wrap').hide();</code></p>\n\n<p>We can instead add our own input field to validate the password.</p>\n\n<p>First we add it via the <code>resetpass_form</code> action:</p>\n\n<pre><code>add_action( 'resetpass_form', function( $user )\n{ ?&gt; &lt;p class=\"user-wpse-pass2-wrap\"&gt;\n &lt;label for=\"wpse-pass2\"&gt;&lt;?php _e( 'Confirm new password' ) ?&gt;&lt;/label&gt;&lt;br /&gt;\n &lt;input type=\"password\" name=\"wpse-pass2\" id=\"wpse-pass2\" class=\"input\" \n size=\"20\" value=\"\" autocomplete=\"off\" /&gt;\n &lt;/p&gt; &lt;?php\n} );\n</code></pre>\n\n<p>Then we use the <code>validate_password_reset</code> hook to validate it:</p>\n\n<pre><code>add_action( 'validate_password_reset', function( $errors )\n{\n if ( isset( $_POST['pass1'] ) &amp;&amp; $_POST['pass1'] != $_POST['wpse-pass2'] )\n $errors-&gt;add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );\n} );\n</code></pre>\n\n<p>This is just using similar code as we have in the <code>wp-login.php</code> file.</p>\n\n<p>This is how it looks in Icelandic, when there's a mismatch:</p>\n\n<p><a href=\"https://i.stack.imgur.com/krCkh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/krCkh.jpg\" alt=\"reset\"></a></p>\n\n<p><strong>Plugin</strong></p>\n\n<p>Create the plugin under:</p>\n\n<pre><code>/wp-content/plugins/wpse-confirm-password/wpse-confirm-password.php\n</code></pre>\n\n<p>and add the following code into that file:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Confirm New Login Password\n * Plugin URI: http://wordpress.stackexchange.com/a/262607/26350\n */\n\nadd_action( 'resetpass_form', function( $user )\n{ ?&gt; &lt;p class=\"user-wpse-pass2-wrap\"&gt;\n &lt;label for=\"wpse-pass2\"&gt;&lt;?php _e( 'Confirm new password' ) ?&gt;&lt;/label&gt;&lt;br /&gt;\n &lt;input type=\"password\" name=\"wpse-pass2\" id=\"wpse-pass2\" class=\"input\" \n size=\"20\" value=\"\" autocomplete=\"off\" /&gt;\n &lt;/p&gt; &lt;?php\n} );\n\nadd_action( 'validate_password_reset', function( $errors )\n{\n if ( isset( $_POST['pass1'] ) &amp;&amp; $_POST['pass1'] != $_POST['wpse-pass2'] )\n $errors-&gt;add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );\n} );\n</code></pre>\n\n<p>Then activate the plugin from the backend as usual.</p>\n" }, { "answer_id": 262851, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<p>In addition to the very useful <a href=\"https://wordpress.stackexchange.com/a/262607/110572\">Plugin CODE @birgire added in his answer</a>, it may also be useful to hide the Password Text (as you type in the password field) on the password reset page. Since with this CODE we will have Confirm Password field anyway, it doesn't make sense to show the password as you type.</p>\n\n<p>The reason WordPress core doesn't add a Confirm Password field is mainly because WordPress already shows the password text as you type it. Confirm Password field is the replacement for that feature and can be very useful (more secure) when the user is typing in front of someone else.</p>\n\n<p>So, I suggest you add the following CODE in addition to birgire's Plugin CODE:</p>\n\n<pre><code>add_action( 'login_enqueue_scripts', function ()\n{\n if ( ! wp_script_is( 'jquery', 'done' ) ) {\n wp_enqueue_script( 'jquery' );\n }\n // this line basically hides the password text\n wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){ jQuery( \"#pass1\" ).data( \"reveal\", 0 ); });' );\n}, 1 );\n</code></pre>\n\n<p>Of course, in this case WordPress will not auto generate the password for you, because obviously auto generating password &amp; then hiding the password text doesn't make sense, as users will not be able to see it &amp; type it in the Confirm Password field.</p>\n\n<p>Anyways, if you want to use this, then the final Plugin CODE will become:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Confirm New Login Password\n * Plugin URI: https://wordpress.stackexchange.com/a/262851/110572\n */\n\nadd_action( 'resetpass_form', function( $user )\n{ ?&gt; &lt;p class=\"user-wpse-pass2-wrap\"&gt;\n &lt;label for=\"wpse-pass2\"&gt;&lt;?php _e( 'Confirm new password' ) ?&gt;&lt;/label&gt;&lt;br /&gt;\n &lt;input type=\"password\" name=\"wpse-pass2\" id=\"wpse-pass2\" class=\"input\" \n size=\"20\" value=\"\" autocomplete=\"off\" /&gt;\n &lt;/p&gt; &lt;?php\n} );\n\nadd_action( 'validate_password_reset', function( $errors )\n{\n if ( isset( $_POST['pass1'] ) &amp;&amp; $_POST['pass1'] != $_POST['wpse-pass2'] )\n $errors-&gt;add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );\n} );\n\nadd_action( 'login_enqueue_scripts', function ()\n{\n if ( ! wp_script_is( 'jquery', 'done' ) ) {\n wp_enqueue_script( 'jquery' );\n }\n wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){ jQuery( \"#pass1\" ).data( \"reveal\", 0 ); });' );\n}, 1 );\n</code></pre>\n" } ]
2017/04/05
[ "https://wordpress.stackexchange.com/questions/262593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114722/" ]
I'm working on a WordPress website and I'd like to modify the password reset screen `/wp-login.php?action=rp`. Currently, the password reset screen generates a new password for the user and I want to add a `Confirm Password` field and make it a required field. I think I've found the relevant code in the `wp-login.php` file and it looks like there is a confirm password option but I don't know how to get it to appear. ``` <form name="resetpassform" id="resetpassform" action="<?php echo esc_url( network_site_url( 'wp-login.php?action=resetpass', 'login_post' ) ); ?>" method="post" autocomplete="off"> <input type="hidden" id="user_login" value="<?php echo esc_attr( $rp_login ); ?>" autocomplete="off" /> <div class="user-pass1-wrap"> <p> <label for="pass1"><?php _e( 'New password' ) ?></label> </p> <div class="wp-pwd"> <span class="password-input-wrapper"> <input type="password" data-reveal="1" data-pw="<?php echo esc_attr( wp_generate_password( 16 ) ); ?>" name="pass1" id="pass1" class="input" size="20" value="" autocomplete="off" aria-describedby="pass-strength-result" /> </span> <div id="pass-strength-result" class="hide-if-no-js" aria-live="polite"><?php _e( 'Strength indicator' ); ?></div> </div> </div> <p class="user-pass2-wrap"> <label for="pass2"><?php _e( 'Confirm new password' ) ?></label><br /> <input type="password" name="pass2" id="pass2" class="input" size="20" value="" autocomplete="off" /> </p> <p class="description indicator-hint"><?php echo wp_get_password_hint(); ?></p> <br class="clear" /> <?php /** * Fires following the 'Strength indicator' meter in the user password reset form. * * @since 3.9.0 * * @param WP_User $user User object of the user whose password is being reset. */ do_action( 'resetpass_form', $user ); ?> <input type="hidden" name="rp_key" value="<?php echo esc_attr( $rp_key ); ?>" /> <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Reset Password'); ?>" /></p> </form> ```
It's tempting to unhide the `pass2` input but that's not enough. In the file `/wp-admin/js/user-profile.js` the `bindPass1()` binds it to `pass1` that makes writing to it not possible. The `pass2` input is then hidden in `bindPasswordForm()` with `$('.user-pass2-wrap').hide();` We can instead add our own input field to validate the password. First we add it via the `resetpass_form` action: ``` add_action( 'resetpass_form', function( $user ) { ?> <p class="user-wpse-pass2-wrap"> <label for="wpse-pass2"><?php _e( 'Confirm new password' ) ?></label><br /> <input type="password" name="wpse-pass2" id="wpse-pass2" class="input" size="20" value="" autocomplete="off" /> </p> <?php } ); ``` Then we use the `validate_password_reset` hook to validate it: ``` add_action( 'validate_password_reset', function( $errors ) { if ( isset( $_POST['pass1'] ) && $_POST['pass1'] != $_POST['wpse-pass2'] ) $errors->add( 'password_reset_mismatch', __( 'The passwords do not match.' ) ); } ); ``` This is just using similar code as we have in the `wp-login.php` file. This is how it looks in Icelandic, when there's a mismatch: [![reset](https://i.stack.imgur.com/krCkh.jpg)](https://i.stack.imgur.com/krCkh.jpg) **Plugin** Create the plugin under: ``` /wp-content/plugins/wpse-confirm-password/wpse-confirm-password.php ``` and add the following code into that file: ``` <?php /** * Plugin Name: Confirm New Login Password * Plugin URI: http://wordpress.stackexchange.com/a/262607/26350 */ add_action( 'resetpass_form', function( $user ) { ?> <p class="user-wpse-pass2-wrap"> <label for="wpse-pass2"><?php _e( 'Confirm new password' ) ?></label><br /> <input type="password" name="wpse-pass2" id="wpse-pass2" class="input" size="20" value="" autocomplete="off" /> </p> <?php } ); add_action( 'validate_password_reset', function( $errors ) { if ( isset( $_POST['pass1'] ) && $_POST['pass1'] != $_POST['wpse-pass2'] ) $errors->add( 'password_reset_mismatch', __( 'The passwords do not match.' ) ); } ); ``` Then activate the plugin from the backend as usual.
262,634
<p>I am trying to cleanup unnecessary code in a wordpress site. I see, in html source code of the website, there is a javascript. it is adroll script, check below...</p> <pre><code>&lt;script type="text/javascript"&gt; adroll_adv_id = "4XJPGN2DSVEYBBDED4DKXK"; adroll_pix_id = "SEEYI5KV2BA53OK5YIG7IP"; (function () { var oldonload = window.onload; window.onload = function(){ __adroll_loaded=true; var scr = document.createElement("script"); var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com"); scr.setAttribute('async', 'true'); scr.type = "text/javascript"; scr.src = host + "/j/roundtrip.js"; ((document.getElementsByTagName('head') || [null])[0] || document.getElementsByTagName('script')[0].parentNode).appendChild(scr); if(oldonload){oldonload()}}; }()); &lt;/script&gt; </code></pre> <p>I tried to locate the above code in all possible ways.</p> <blockquote> <blockquote> <p>checked all the plugins</p> <p>Deactivated Google Analytics plugin</p> <p>Checked functions.php</p> <p>Checked header.php and foother.php</p> <p>downloaded wntire wordpress from server and then used MX dreamweaver to find adroll in source code.</p> </blockquote> </blockquote> <p>But location of the javascript is still not found.</p>
[ { "answer_id": 262665, "author": "Barry Kooij", "author_id": 16655, "author_profile": "https://wordpress.stackexchange.com/users/16655", "pm_score": 3, "selected": true, "text": "<p>I would download all files via FTP and search in the folder for <code>adroll_adv_id</code>. If there's no result then it's either in the database or obfuscated.</p>\n" }, { "answer_id": 262695, "author": "semibur", "author_id": 55153, "author_profile": "https://wordpress.stackexchange.com/users/55153", "pm_score": 0, "selected": false, "text": "<p>Do you use some template and is there a chance that is includes anywhere in it something that starts with <code>eval</code> or has adroll IDs fields in settings panel?\nOr maybe you use a free hosting provider that is adding their ads on you site?\nCan you share the link to the website?</p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102538/" ]
I am trying to cleanup unnecessary code in a wordpress site. I see, in html source code of the website, there is a javascript. it is adroll script, check below... ``` <script type="text/javascript"> adroll_adv_id = "4XJPGN2DSVEYBBDED4DKXK"; adroll_pix_id = "SEEYI5KV2BA53OK5YIG7IP"; (function () { var oldonload = window.onload; window.onload = function(){ __adroll_loaded=true; var scr = document.createElement("script"); var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com"); scr.setAttribute('async', 'true'); scr.type = "text/javascript"; scr.src = host + "/j/roundtrip.js"; ((document.getElementsByTagName('head') || [null])[0] || document.getElementsByTagName('script')[0].parentNode).appendChild(scr); if(oldonload){oldonload()}}; }()); </script> ``` I tried to locate the above code in all possible ways. > > > > > > checked all the plugins > > > > > > Deactivated Google Analytics plugin > > > > > > Checked functions.php > > > > > > Checked header.php and foother.php > > > > > > downloaded wntire wordpress from server and then used MX dreamweaver to find adroll in source code. > > > > > > > > > But location of the javascript is still not found.
I would download all files via FTP and search in the folder for `adroll_adv_id`. If there's no result then it's either in the database or obfuscated.
262,644
<p>For our WordPress-website, I wanted to create a test instance - to test WordPress-updates/plugin updates and new developments on the theme and so on ...</p> <p>so i wrote a script to copy the database and the files:</p> <pre><code>sourcedir="/srv/www/htdocs/www.example.de" testdir="/srv/www/htdocs/test.example.de" workdir="/data/example.de_test-system" sqldumpfile="$workdir/mysql_dump_example_wp2017.sql" echo "delete webroot test.example.de" rm -rf $testdir echo "www.example.de nach test.example.de kopieren" cp -R $sourcedir $testdir echo "cache-verzeichnisse leeren" rm -rf $testdir/wp-content/cache/minify rm -rf $testdir/wp-content/cache/db rm -rf $testdir/wp-content/cache/object rm -rf $testdir/wp-content/cache/page_enhanced rm -rf $testdir/wp-content/cache/tmp echo "alten dump loeschen" rm -f $sqldumpfile echo "aktuellen Dump aus DB ziehen" mysqldump -u root --password=xxx example_wp_2017 &gt; $sqldumpfile echo "dump bearbeiten - www.example.de gegen test.example.de ersetzen" sed -i s/www.example.de/test.example.de/g $sqldumpfile echo "bearbeiteten dump in test-DB einspielen" mysql -u root --password=xxx example_wp_2017_test &lt; $sqldumpfile echo "test-config einspielen" cp /data/example.de_test-system/wp-config.php $testdir echo "www-nutzer-rechte auf test.example.de setzen" chown -R wwwrun $testdir chgrp -R www $testdir </code></pre> <p>the script will copy the WordPress-folder, empty cache folders, dump the database and find/replace entries of the productive system with test-system and import the dump to the database - finally, copy the test-config to the test folder</p> <p>this works, but I got some strange errors - like a logo image, where it displays a placeholder image instead</p> <p>the meta-navigation is missing</p> <p>and in the backend, some points in the left navigation are missing - like the custom post types</p> <p>am I missing some things in my script?</p>
[ { "answer_id": 262646, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>In general test enviroments better use the same domain name as the live site. Since it doesn't seem like you follow such pattern (and yes, it is harder to follow), you need to make sure you convert all the URLs in the DB properly, and the way you do it will fail with any data which is serialized. Use wp-cli to change URLs instead of re-inventing your own solution.</p>\n\n<p>In addition you will probably will want to change the option or add some code to make sure that google do not try to index the test site.</p>\n" }, { "answer_id": 262717, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I've found the best cloning plugin for my use is WP Clone here: <a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a></p>\n\n<p>Quite easy to use, just install on the source and target WP sites. Then export from the source site, and import to the target (log into the target). All your settings (including users) and content including media will be in the target site; you will have to log in using an account that was on the source system.</p>\n\n<p>Great plugin.</p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117033/" ]
For our WordPress-website, I wanted to create a test instance - to test WordPress-updates/plugin updates and new developments on the theme and so on ... so i wrote a script to copy the database and the files: ``` sourcedir="/srv/www/htdocs/www.example.de" testdir="/srv/www/htdocs/test.example.de" workdir="/data/example.de_test-system" sqldumpfile="$workdir/mysql_dump_example_wp2017.sql" echo "delete webroot test.example.de" rm -rf $testdir echo "www.example.de nach test.example.de kopieren" cp -R $sourcedir $testdir echo "cache-verzeichnisse leeren" rm -rf $testdir/wp-content/cache/minify rm -rf $testdir/wp-content/cache/db rm -rf $testdir/wp-content/cache/object rm -rf $testdir/wp-content/cache/page_enhanced rm -rf $testdir/wp-content/cache/tmp echo "alten dump loeschen" rm -f $sqldumpfile echo "aktuellen Dump aus DB ziehen" mysqldump -u root --password=xxx example_wp_2017 > $sqldumpfile echo "dump bearbeiten - www.example.de gegen test.example.de ersetzen" sed -i s/www.example.de/test.example.de/g $sqldumpfile echo "bearbeiteten dump in test-DB einspielen" mysql -u root --password=xxx example_wp_2017_test < $sqldumpfile echo "test-config einspielen" cp /data/example.de_test-system/wp-config.php $testdir echo "www-nutzer-rechte auf test.example.de setzen" chown -R wwwrun $testdir chgrp -R www $testdir ``` the script will copy the WordPress-folder, empty cache folders, dump the database and find/replace entries of the productive system with test-system and import the dump to the database - finally, copy the test-config to the test folder this works, but I got some strange errors - like a logo image, where it displays a placeholder image instead the meta-navigation is missing and in the backend, some points in the left navigation are missing - like the custom post types am I missing some things in my script?
In general test enviroments better use the same domain name as the live site. Since it doesn't seem like you follow such pattern (and yes, it is harder to follow), you need to make sure you convert all the URLs in the DB properly, and the way you do it will fail with any data which is serialized. Use wp-cli to change URLs instead of re-inventing your own solution. In addition you will probably will want to change the option or add some code to make sure that google do not try to index the test site.
262,654
<p>I managed to make my code working via codepen as you can see if you visit the link <a href="http://codepen.io/Sidney-Dev/pen/gmyoWM?editors=1111" rel="nofollow noreferrer">here</a></p> <p>Now trying to implement on a WordPress test site it looks like my javascript is not working as well as the fontawesome is not being loaded properly. <a href="http://wordpressdev.burnnotice.co.za/" rel="nofollow noreferrer">Here is the link for the test site</a></p> <p>Here it is my js:</p> <pre><code>$(document).ready(function() { var txtFromDate, txtToDate; $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function(selected) { txtFromDate = selected; var dt = new Date(selected); dt.setDate(dt.getDate() + 1); $("#txtTo").datepicker("option", "minDate", dt); } }); $("#txtTo").datepicker({ numberOfMonths: 1, onSelect: function(selected) { txtToDate = selected; var dt = new Date(selected); dt.setDate(dt.getDate() - 1); $("#txtFrom").datepicker("option", "maxDate", dt); } }); $('.submit-here').click(function() { // var link = day_1+month_1+year; var date1 = $("#txtFrom").datepicker('getDate'), day_1 = date1.getDate(), month_1 = date1.getMonth() + 1, year_1 = date1.getFullYear(); var date2 = $("#txtTo").datepicker('getDate'), day_2 = date2.getDate(), month_2 = date2.getMonth() + 1, year_2 = date2.getFullYear(); var where = $('#selection :selected').text(); var people = $('#people :selected').text(); console.log('www.lekkeslaap.co.za/akkommodasie-in/'+where+'?q='+where+'&amp;start='+day_1+'+'+month_1+'+'+year_1+'&amp;end='+day_2+'+'+month_2+'+'+year_2+'&amp;pax='+people); }); }); </code></pre> <p>And here it is for my functions.php:</p> <pre><code>function testsite_scripts() { wp_enqueue_style( 'testsite-style', get_stylesheet_uri() ); wp_enqueue_style( 'fontawesome', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), '1.0.0', 'all' ); wp_enqueue_script( 'testsite-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'testsite-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'testsite_scripts' ); function testsite_load_scripts(){ wp_enqueue_style( 'font_extra', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/start/jquery-ui.css', array(), '1.0.0', 'all' ); wp_enqueue_script( 'plugin_script', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'calendario', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'calendario', get_template_directory_uri() . '/js/calendario.js', array('jquery'), '20151215', true ); } add_action( 'wp_enqueue_scripts', 'testsite_load_scripts' ); </code></pre>
[ { "answer_id": 262646, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>In general test enviroments better use the same domain name as the live site. Since it doesn't seem like you follow such pattern (and yes, it is harder to follow), you need to make sure you convert all the URLs in the DB properly, and the way you do it will fail with any data which is serialized. Use wp-cli to change URLs instead of re-inventing your own solution.</p>\n\n<p>In addition you will probably will want to change the option or add some code to make sure that google do not try to index the test site.</p>\n" }, { "answer_id": 262717, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I've found the best cloning plugin for my use is WP Clone here: <a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a></p>\n\n<p>Quite easy to use, just install on the source and target WP sites. Then export from the source site, and import to the target (log into the target). All your settings (including users) and content including media will be in the target site; you will have to log in using an account that was on the source system.</p>\n\n<p>Great plugin.</p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99178/" ]
I managed to make my code working via codepen as you can see if you visit the link [here](http://codepen.io/Sidney-Dev/pen/gmyoWM?editors=1111) Now trying to implement on a WordPress test site it looks like my javascript is not working as well as the fontawesome is not being loaded properly. [Here is the link for the test site](http://wordpressdev.burnnotice.co.za/) Here it is my js: ``` $(document).ready(function() { var txtFromDate, txtToDate; $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function(selected) { txtFromDate = selected; var dt = new Date(selected); dt.setDate(dt.getDate() + 1); $("#txtTo").datepicker("option", "minDate", dt); } }); $("#txtTo").datepicker({ numberOfMonths: 1, onSelect: function(selected) { txtToDate = selected; var dt = new Date(selected); dt.setDate(dt.getDate() - 1); $("#txtFrom").datepicker("option", "maxDate", dt); } }); $('.submit-here').click(function() { // var link = day_1+month_1+year; var date1 = $("#txtFrom").datepicker('getDate'), day_1 = date1.getDate(), month_1 = date1.getMonth() + 1, year_1 = date1.getFullYear(); var date2 = $("#txtTo").datepicker('getDate'), day_2 = date2.getDate(), month_2 = date2.getMonth() + 1, year_2 = date2.getFullYear(); var where = $('#selection :selected').text(); var people = $('#people :selected').text(); console.log('www.lekkeslaap.co.za/akkommodasie-in/'+where+'?q='+where+'&start='+day_1+'+'+month_1+'+'+year_1+'&end='+day_2+'+'+month_2+'+'+year_2+'&pax='+people); }); }); ``` And here it is for my functions.php: ``` function testsite_scripts() { wp_enqueue_style( 'testsite-style', get_stylesheet_uri() ); wp_enqueue_style( 'fontawesome', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), '1.0.0', 'all' ); wp_enqueue_script( 'testsite-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'testsite-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'testsite_scripts' ); function testsite_load_scripts(){ wp_enqueue_style( 'font_extra', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/start/jquery-ui.css', array(), '1.0.0', 'all' ); wp_enqueue_script( 'plugin_script', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'calendario', get_template_directory_uri() . 'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js', array('jquery'), '20151215', true ); wp_enqueue_script( 'calendario', get_template_directory_uri() . '/js/calendario.js', array('jquery'), '20151215', true ); } add_action( 'wp_enqueue_scripts', 'testsite_load_scripts' ); ```
In general test enviroments better use the same domain name as the live site. Since it doesn't seem like you follow such pattern (and yes, it is harder to follow), you need to make sure you convert all the URLs in the DB properly, and the way you do it will fail with any data which is serialized. Use wp-cli to change URLs instead of re-inventing your own solution. In addition you will probably will want to change the option or add some code to make sure that google do not try to index the test site.
262,677
<p>I have defined the following custom post type + taxonomy </p> <pre><code>$productTaxonomyLabels = [ 'name' =&gt; __('Product Categories', 'byronposttypes'), 'singular_name' =&gt; __('Product Category', 'byronposttypes'), ]; $productTaxonomyArgs = [ 'labels' =&gt; $productTaxonomyLabels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_admin_column' =&gt; true, 'description' =&gt; __('Product category', 'byronposttypes'), 'hierarchical' =&gt; true, 'rewrite' =&gt; [ 'slug' =&gt; __('collections', 'byronposttypes'), 'with_front' =&gt; false, 'hierarchical' =&gt; true, 'ep_mask' =&gt; EP_CATEGORIES ], ]; register_taxonomy('collections', 'products', $productTaxonomyArgs); register_taxonomy_for_object_type('collections', 'products'); $productLabels = [ 'name' =&gt; _x('Products', 'post type plural name', 'byronposttypes'), 'singular_name' =&gt; _x('Product', 'post type singular name', 'byronposttypes'), 'menu_name' =&gt; _x('Collection', 'name in admin menu', 'byronposttypes'), 'add_new' =&gt; _x('Add new', 'product', 'byronposttypes'), 'add_new_item' =&gt; __('Add new product', 'byronposttypes'), 'new_item' =&gt; __('New product', 'byronposttypes'), 'edit_item' =&gt; __('Edit product', 'byronposttypes'), 'view_item' =&gt; __('View product', 'byronposttypes'), 'not_found' =&gt; __('No products found', 'byronposttypes'), 'not_found_in_trash' =&gt; __('No products found in trash', 'byronposttypes'), 'all_items' =&gt; __('All products', 'byronposttypes'), 'archives' =&gt; __('Product archives', 'byronposttypes'), 'attributes' =&gt; __('Product attributes', 'byronposttypes'), ]; $productSupports = ['title', 'editor', 'thumbnail']; $productArgs = [ 'labels' =&gt; $productLabels, 'description' =&gt; __('Products', 'byronposttypes'), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'menu_position' =&gt; 57, 'menu_icon' =&gt; 'dashicons-screenoptions', 'capability_type' =&gt; ['product', 'products'], 'hierarchical' =&gt; false, 'supports' =&gt; $productSupports, 'taxonomies' =&gt; ['banaan'], 'rewrite' =&gt; [ 'slug' =&gt; 'banaan', 'with_front' =&gt; false, ], 'has_archive' =&gt; 'banaan', ]; register_post_type('products', $productArgs); </code></pre> <p>As you can see, I have defined the post type slug to be 'banaan'. The problem is, that the link wordpress generates (for instance, when clicking 'view' in wp-admin, the uri is <code>collection/$product_name</code>. I used to have /collection as base of the url, but I changed that to banaan for testing purposes, but it won't change. I have re-saved the permalinks. Am I missing something here?<br> *Manually navigating to /banaan/$product_name redirects to /collection/$product_name and gives a 404</p>
[ { "answer_id": 262661, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 3, "selected": true, "text": "<p>File name should be <code>admin-ajax.php</code></p>\n\n<p>This file handles all the ajax requests. So, you should never remove this file.</p>\n\n<p>Many features will stop working like autosave and many other that uses ajax if you remove this file.</p>\n" }, { "answer_id": 262664, "author": "Barry Kooij", "author_id": 16655, "author_profile": "https://wordpress.stackexchange.com/users/16655", "pm_score": 0, "selected": false, "text": "<p>Removing your admin-ajax.php file will break your WordPress website. Look into what plugins are slowing your website down (via AJAX) and disable them &amp; look for better alternatives.</p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106941/" ]
I have defined the following custom post type + taxonomy ``` $productTaxonomyLabels = [ 'name' => __('Product Categories', 'byronposttypes'), 'singular_name' => __('Product Category', 'byronposttypes'), ]; $productTaxonomyArgs = [ 'labels' => $productTaxonomyLabels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_admin_column' => true, 'description' => __('Product category', 'byronposttypes'), 'hierarchical' => true, 'rewrite' => [ 'slug' => __('collections', 'byronposttypes'), 'with_front' => false, 'hierarchical' => true, 'ep_mask' => EP_CATEGORIES ], ]; register_taxonomy('collections', 'products', $productTaxonomyArgs); register_taxonomy_for_object_type('collections', 'products'); $productLabels = [ 'name' => _x('Products', 'post type plural name', 'byronposttypes'), 'singular_name' => _x('Product', 'post type singular name', 'byronposttypes'), 'menu_name' => _x('Collection', 'name in admin menu', 'byronposttypes'), 'add_new' => _x('Add new', 'product', 'byronposttypes'), 'add_new_item' => __('Add new product', 'byronposttypes'), 'new_item' => __('New product', 'byronposttypes'), 'edit_item' => __('Edit product', 'byronposttypes'), 'view_item' => __('View product', 'byronposttypes'), 'not_found' => __('No products found', 'byronposttypes'), 'not_found_in_trash' => __('No products found in trash', 'byronposttypes'), 'all_items' => __('All products', 'byronposttypes'), 'archives' => __('Product archives', 'byronposttypes'), 'attributes' => __('Product attributes', 'byronposttypes'), ]; $productSupports = ['title', 'editor', 'thumbnail']; $productArgs = [ 'labels' => $productLabels, 'description' => __('Products', 'byronposttypes'), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'menu_position' => 57, 'menu_icon' => 'dashicons-screenoptions', 'capability_type' => ['product', 'products'], 'hierarchical' => false, 'supports' => $productSupports, 'taxonomies' => ['banaan'], 'rewrite' => [ 'slug' => 'banaan', 'with_front' => false, ], 'has_archive' => 'banaan', ]; register_post_type('products', $productArgs); ``` As you can see, I have defined the post type slug to be 'banaan'. The problem is, that the link wordpress generates (for instance, when clicking 'view' in wp-admin, the uri is `collection/$product_name`. I used to have /collection as base of the url, but I changed that to banaan for testing purposes, but it won't change. I have re-saved the permalinks. Am I missing something here? \*Manually navigating to /banaan/$product\_name redirects to /collection/$product\_name and gives a 404
File name should be `admin-ajax.php` This file handles all the ajax requests. So, you should never remove this file. Many features will stop working like autosave and many other that uses ajax if you remove this file.
262,712
<p>I am using <a href="http://underscores.me/" rel="nofollow noreferrer">Underscores</a> starter theme and I've created a custom post type <code>video</code>.</p> <pre><code>$args = array( 'label' =&gt; __( 'Video', 'text_domain' ), 'description' =&gt; __( 'Videos', 'text_domain' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'custom-fields', ), 'taxonomies' =&gt; array( 'category', 'post_tag' ), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-video-alt2', 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'capability_type' =&gt; 'post', ); register_post_type( 'video', $args ); </code></pre> <p>I am able to display the latest posts from <code>video</code> on the homepage (which is a custom page template) but when I visit the video link, I get <code>Oops! That page can’t be found!</code></p> <p>I've created a new file <code>single-video.php</code> and inside I'm getting the video template</p> <pre><code>get_template_part( 'template-parts/content', 'video' ); </code></pre> <p>I've also created another file <code>content-video.php</code> which lives inside <code>template-parts</code> folder and is the copy of the original <code>content.php</code> file</p> <p>But it's not working, I'm still getting <code>Page Not Found</code> when I visit the video url.</p>
[ { "answer_id": 262714, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 4, "selected": true, "text": "<p>In your dashboard go to settings/permalinks. Hit save. You should be able to see your cpts now.</p>\n" }, { "answer_id": 262715, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 2, "selected": false, "text": "<p>you should create <code>content-video.php</code> inside <code>template-parts</code> folder.</p>\n\n<p>And try resetting permalinks. That means:</p>\n\n<p>Go to Settings > Permalinks</p>\n\n<p>Change Permalink setting to plain and save</p>\n\n<p>Change permalink settings to your desired one again and save</p>\n\n<p>It should fix the issue.</p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50147/" ]
I am using [Underscores](http://underscores.me/) starter theme and I've created a custom post type `video`. ``` $args = array( 'label' => __( 'Video', 'text_domain' ), 'description' => __( 'Videos', 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields', ), 'taxonomies' => array( 'category', 'post_tag' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-video-alt2', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'post', ); register_post_type( 'video', $args ); ``` I am able to display the latest posts from `video` on the homepage (which is a custom page template) but when I visit the video link, I get `Oops! That page can’t be found!` I've created a new file `single-video.php` and inside I'm getting the video template ``` get_template_part( 'template-parts/content', 'video' ); ``` I've also created another file `content-video.php` which lives inside `template-parts` folder and is the copy of the original `content.php` file But it's not working, I'm still getting `Page Not Found` when I visit the video url.
In your dashboard go to settings/permalinks. Hit save. You should be able to see your cpts now.
262,725
<p>I made a mistake and changed the URL under settings -> General. After this Wordpress locked me out. I first added in the wp-congif.php file: </p> <pre><code>define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com'); </code></pre> <p>This appeared to have fixed the issue but only if I was logged into Wordpress. Users could not enter to the website and they have a forbidden message. My URL to visit my test site would redirect me always to my homepage, etc. </p> <p>I also resetted the htcaccess file but nothing seems to do the trick. I finally uploaded a full backup of my site and the problem is still there, nothing works and the site is completely broken. Any ideas?</p> <p>My current htaccess file looks like this:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /guiacentros/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /guiacentros/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 262728, "author": "Jonny Perl", "author_id": 40765, "author_profile": "https://wordpress.stackexchange.com/users/40765", "pm_score": 0, "selected": false, "text": "<p>Take a look in the wp_options table and check the values for <code>siteurl</code> and <code>home</code> - these are the values that would have been changed when you submitted the form, so you could change them back directly there. This may not be it but it's worth trying.</p>\n" }, { "answer_id": 262778, "author": "Sergi", "author_id": 115742, "author_profile": "https://wordpress.stackexchange.com/users/115742", "pm_score": 1, "selected": false, "text": "<p>Fixed by adding a htaccess file to the root directory with this information:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine on\nRewriteCond %{HTTP_HOST} ^(www.)?example.com$\nRewriteCond %{REQUEST_URI} !^/my_subdir/\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ /my_subdir/$1\nRewriteCond %{HTTP_HOST} ^(www.)?example.com$\nRewriteRule ^(/)?$ my_subdir/index.php [L] \n&lt;/IfModule&gt;\n</code></pre>\n\n<p>The main issues was Wordpress being installed in a subdirectory, so the root URL was \"example.com/subdirectory\" instead of \"example.com\". This htaccess comfiguration does redirect users properly.</p>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory</a></p>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262725", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115742/" ]
I made a mistake and changed the URL under settings -> General. After this Wordpress locked me out. I first added in the wp-congif.php file: ``` define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com'); ``` This appeared to have fixed the issue but only if I was logged into Wordpress. Users could not enter to the website and they have a forbidden message. My URL to visit my test site would redirect me always to my homepage, etc. I also resetted the htcaccess file but nothing seems to do the trick. I finally uploaded a full backup of my site and the problem is still there, nothing works and the site is completely broken. Any ideas? My current htaccess file looks like this: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /guiacentros/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /guiacentros/index.php [L] </IfModule> # END WordPress ```
Fixed by adding a htaccess file to the root directory with this information: ``` <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteCond %{REQUEST_URI} !^/my_subdir/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /my_subdir/$1 RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteRule ^(/)?$ my_subdir/index.php [L] </IfModule> ``` The main issues was Wordpress being installed in a subdirectory, so the root URL was "example.com/subdirectory" instead of "example.com". This htaccess comfiguration does redirect users properly. Source: <https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory>