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
181,541
<p>I have been researching on Google and WPSE and the only thing I see repeatedly is to use <code>showposts</code>, that is deprecated.</p> <p>I am familiar with <code>WP_Query</code>, and I thought that if I set <code>posts_per_page</code> to my limit (ie. 5), and <code>nopaging</code> to <code>true</code>, it would become to something like "<em>Ok, I'll give you only 5 posts</em>". But this doesn't work.</p> <p><img src="https://i.stack.imgur.com/WNuwc.png" alt="enter image description here"></p> <p>How can I do this?</p>
[ { "answer_id": 181543, "author": "shuvroMithun", "author_id": 65928, "author_profile": "https://wordpress.stackexchange.com/users/65928", "pm_score": 3, "selected": false, "text": "<p>Ok , lets you have post type called 'blog_posts' , and you want to fetch 5 posts of that post type . Here is what you need to do </p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'blog_posts',\n 'posts_per_page' =&gt; '5',\n);\n\n\n$query = new WP_Query($args);\n</code></pre>\n\n<p>The above query will return 5 posts of type 'blog_posts' , if it is not a custom post type , then just replace like this <code>'post_type' =&gt; 'posts',</code> if you want to fetch all posts then replace like this <code>'posts_per_page' =&gt; '-1',</code> , for more details <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\">WP Query</a></p>\n" }, { "answer_id": 181549, "author": "Shreyo Gi", "author_id": 65741, "author_profile": "https://wordpress.stackexchange.com/users/65741", "pm_score": 2, "selected": false, "text": "<p>I know that @user1750063 has mentioned the code but try this</p>\n\n<pre><code>$args = array (\n 'post_type' =&gt; 'custom_post',\n 'nopaging' =&gt; false,\n 'posts_per_page' =&gt; '5',\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'ID',\n);\n\n$query = new WP_Query( $args );\n\nif ( $query-&gt;have_posts() ) {\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // display content\n }\n} else {\n // display when no posts found\n}\n\nwp_reset_postdata(); // Restore original Post Data\n</code></pre>\n" }, { "answer_id": 181552, "author": "EliasNS", "author_id": 40743, "author_profile": "https://wordpress.stackexchange.com/users/40743", "pm_score": 2, "selected": false, "text": "<p>After the conversation with @Pieter Goosen on the comments of the question, I think I can answer the question and explain my mistake.</p>\n\n<p>The key is that <code>found_posts</code> was confussing me. I thougth that, that number is the posts retrieved but is not. <strong>It is the number of posts that match the criteria</strong>. It's like the <code>WP_Query</code> had 2 parts: one for finding (all) the posts, and other for fetching the content, when it checks for the <code>pagination</code> parameters. So we have the <code>$post_count</code> property that is the number of posts fetched (Codex says <code>The number of posts being displayed</code>), that of course is equal to the number on <code>posts_per_page</code> parameter, and the number of items on the <code>$posts</code> array property.</p>\n\n<p>So <code>WP_Query</code> is not doing any useless work, as I thought ^^</p>\n\n<p>Hope this helps others!</p>\n" }, { "answer_id": 181553, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 7, "selected": true, "text": "<p>I think that now I understand what you are trying to do. When you run a custom query with <code>WP_Query</code> and set the limit to get only 5 posts per page, only 5 posts will be retrieved by the query and that query will only hold 5 posts, <strong>BUT</strong> for the sake of pagination, <code>WP_Query</code> still runs through the whole database and counts all the posts that matches the criteria of the query.</p>\n\n<p>That can be seen when you look at the <code>$found_posts</code> and <code>$max_num_pages</code> properties of the query. Lets take an example:</p>\n\n<p>You have 20 posts belonging to the default post type <code>post</code>. You <strong>only</strong> need the latest 5 posts without pagination. Your query looks like this</p>\n\n<pre><code>$q = new WP_Query( 'posts_per_page=5' );\n</code></pre>\n\n<ul>\n<li><code>var_dump( $q-&gt;posts )</code> will give you the latest 5 posts as expected</li>\n<li><code>echo $q-&gt;found_posts</code> will give you <code>20</code></li>\n<li><code>echo $q-&gt;max_num_pages</code> will give you <code>4</code></li>\n</ul>\n\n<p>The impact of this extra work is minimal on sites with only a few posts, but this can gt expensive if you are running a site with hundreds or thousands of posts. This is a waste of resources if you are only ever going to need the 5 latest posts</p>\n\n<p>There is an undocumented parameter called <code>no_found_rows</code> which uses boolean values which you can use to make your query bail after it found the 5 posts you need. This will force <code>WP_Query</code> not to look for any more posts mathing the criteria after it has retrieved the amount of posts queried. This parameter is already build into <code>get_posts</code>, that is why <code>get_posts</code> is a bit faster than <code>WP_Query</code> although <code>get_posts</code> uses <code>WP_Query</code></p>\n\n<h1>Conclusion</h1>\n\n<p>In conclusion, if you are not going to use pagination on a query, it is always wise to <strong><code>'no_found_rows=true'</code></strong> in your query to speed things up and to save on wasting resources. </p>\n" }, { "answer_id": 369320, "author": "Hasan Gad", "author_id": 38835, "author_profile": "https://wordpress.stackexchange.com/users/38835", "pm_score": -1, "selected": false, "text": "<p>I would limit it with custom fields, check this query sample below:</p>\n<pre><code>$wp_query = new WP_Query(&quot;orderby=DESC&amp;post_type=portfolio&amp;meta_key=FeaturedProject&amp;meta_value=1&amp;posts_per_page=6&quot;);\n</code></pre>\n<p>It will return 6 Featured projects.</p>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40743/" ]
I have been researching on Google and WPSE and the only thing I see repeatedly is to use `showposts`, that is deprecated. I am familiar with `WP_Query`, and I thought that if I set `posts_per_page` to my limit (ie. 5), and `nopaging` to `true`, it would become to something like "*Ok, I'll give you only 5 posts*". But this doesn't work. ![enter image description here](https://i.stack.imgur.com/WNuwc.png) How can I do this?
I think that now I understand what you are trying to do. When you run a custom query with `WP_Query` and set the limit to get only 5 posts per page, only 5 posts will be retrieved by the query and that query will only hold 5 posts, **BUT** for the sake of pagination, `WP_Query` still runs through the whole database and counts all the posts that matches the criteria of the query. That can be seen when you look at the `$found_posts` and `$max_num_pages` properties of the query. Lets take an example: You have 20 posts belonging to the default post type `post`. You **only** need the latest 5 posts without pagination. Your query looks like this ``` $q = new WP_Query( 'posts_per_page=5' ); ``` * `var_dump( $q->posts )` will give you the latest 5 posts as expected * `echo $q->found_posts` will give you `20` * `echo $q->max_num_pages` will give you `4` The impact of this extra work is minimal on sites with only a few posts, but this can gt expensive if you are running a site with hundreds or thousands of posts. This is a waste of resources if you are only ever going to need the 5 latest posts There is an undocumented parameter called `no_found_rows` which uses boolean values which you can use to make your query bail after it found the 5 posts you need. This will force `WP_Query` not to look for any more posts mathing the criteria after it has retrieved the amount of posts queried. This parameter is already build into `get_posts`, that is why `get_posts` is a bit faster than `WP_Query` although `get_posts` uses `WP_Query` Conclusion ========== In conclusion, if you are not going to use pagination on a query, it is always wise to **`'no_found_rows=true'`** in your query to speed things up and to save on wasting resources.
181,545
<p>Is it possible to change the value of a custom field after X number of seconds has passed since it was modified?</p> <p>For example, I have a checkbox that a user can check to say whether or not they are available. By default the box is unchecked and what I want to do is, 7200 seconds (2 hours) after a user has checked the box, revert it back to unchecked.</p> <p>Is this possible?</p>
[ { "answer_id": 181555, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>Is this like an option you have saved to the database?\nIf so you could use <a href=\"http://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow\">wp_schedule_event</a>.</p>\n\n<p>At the same time you save the option that the user is available, push a scheduled event in two hours to revert the option back.</p>\n\n<p>edit: Also when reverting the option back, remember to unschedule the event.</p>\n\n<p>Alternatively, you could save a timestamp when saving the availability and when you check if the person is available, if the timestamp is over 2 hours old, change them not to be.</p>\n" }, { "answer_id": 181557, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You'll need two meta fields: the 'available' field, and a 'lastchecked' field that contains a Unix timestamp for when the box was checked.</p>\n\n<p>Then, you can use wp_cron (assuming your site has enough traffic; but most sites will get at least one visit an hour; if not, you can always set up a regular cron to visit your site every hour) to run your reset.</p>\n\n<p>Assuming the meta fields are named as above, and 'available' is 1 for yes, 0 for no:</p>\n\n<pre><code>function reset_available_meta() {\n $args = array(\n 'post_type' =&gt; 'post',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'lastchecked',\n 'value' =&gt; time() - ( 60 * 60 * 2 ), // 2 hours ago\n 'compare' =&gt; '&lt;='\n )\n ),\n 'posts_per_page' =&gt; -1\n );\n\n $resetQ = new WP_Query( $args );\n\n while ( $resetQ-&gt;have_posts() ) {\n $resetQ-&gt;the_post();\n update_post_meta( get_the_ID(), 'available', '0' );\n\n //optional: update lastchecked so it's not included for the next call\n update_post_meta( get_the_ID(), 'lastchecked', time() );\n }\n}\n\nwp_schedule_event(time(), 'hourly', 'reset_available_meta' ); \n</code></pre>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19319/" ]
Is it possible to change the value of a custom field after X number of seconds has passed since it was modified? For example, I have a checkbox that a user can check to say whether or not they are available. By default the box is unchecked and what I want to do is, 7200 seconds (2 hours) after a user has checked the box, revert it back to unchecked. Is this possible?
You'll need two meta fields: the 'available' field, and a 'lastchecked' field that contains a Unix timestamp for when the box was checked. Then, you can use wp\_cron (assuming your site has enough traffic; but most sites will get at least one visit an hour; if not, you can always set up a regular cron to visit your site every hour) to run your reset. Assuming the meta fields are named as above, and 'available' is 1 for yes, 0 for no: ``` function reset_available_meta() { $args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'lastchecked', 'value' => time() - ( 60 * 60 * 2 ), // 2 hours ago 'compare' => '<=' ) ), 'posts_per_page' => -1 ); $resetQ = new WP_Query( $args ); while ( $resetQ->have_posts() ) { $resetQ->the_post(); update_post_meta( get_the_ID(), 'available', '0' ); //optional: update lastchecked so it's not included for the next call update_post_meta( get_the_ID(), 'lastchecked', time() ); } } wp_schedule_event(time(), 'hourly', 'reset_available_meta' ); ```
181,580
<p>Is this enough to change the user ID? I'm doing this for security purposes, where the administrator has user ID=1 and I want to keep all posts, pages and content.</p> <pre><code>UPDATE wp_posts SET post_author='1000' WHERE post_author='1'; UPDATE wp_users SET ID = '1000' WHERE ID = '1'; UPDATE wp_usermeta SET user_id = '1000' WHERE user_id = '1'; ALTER TABLE wp_users AUTO_INCREMENT = 1001; </code></pre> <p>Is there a WordPress function to do it globally?</p>
[ { "answer_id": 181586, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>It should work but it doesn't add even the tiniest security to the site (if the bad guy has enough permissions to alter the password of the admin he can probably create an admin user for himself). Don't forget to backup before running the queries.</p>\n" }, { "answer_id": 181942, "author": "Earle Davies", "author_id": 33380, "author_profile": "https://wordpress.stackexchange.com/users/33380", "pm_score": 2, "selected": true, "text": "<p>Why not make a new account for this user which will generate a new database ID. Then delete the user with the ID of 1 and attribute all posts / content to the new user you created for them? Then you don't have to worry about queries or messing up your database. Also, as said before this makes absolutely no sense from a security standpoint as it's pointless. If your client doesn't trust you enough and wants to micromanage the site security they clearly know nothing about, might be time to dump that client.</p>\n" }, { "answer_id": 243726, "author": "theyuv", "author_id": 102281, "author_profile": "https://wordpress.stackexchange.com/users/102281", "pm_score": 2, "selected": false, "text": "<p>If you would like to also keep comments:</p>\n\n<pre><code>UPDATE wp_comments SET user_id = 1000 WHERE user_id = 1;\n</code></pre>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7349/" ]
Is this enough to change the user ID? I'm doing this for security purposes, where the administrator has user ID=1 and I want to keep all posts, pages and content. ``` UPDATE wp_posts SET post_author='1000' WHERE post_author='1'; UPDATE wp_users SET ID = '1000' WHERE ID = '1'; UPDATE wp_usermeta SET user_id = '1000' WHERE user_id = '1'; ALTER TABLE wp_users AUTO_INCREMENT = 1001; ``` Is there a WordPress function to do it globally?
Why not make a new account for this user which will generate a new database ID. Then delete the user with the ID of 1 and attribute all posts / content to the new user you created for them? Then you don't have to worry about queries or messing up your database. Also, as said before this makes absolutely no sense from a security standpoint as it's pointless. If your client doesn't trust you enough and wants to micromanage the site security they clearly know nothing about, might be time to dump that client.
181,606
<p>I've created my template and installed extensions everything worked fine. I work on localhost and then upload to my server and use searchreplacedb2.php to change the root url as usually.</p> <p>But now, I can login and then access wp-admin in localhost, but on my server I can login (correctly and have the admin bar on top of the website pages), but I have a blank page a wp-admin/</p> <p>I desactivated all security (extensions desactivated and files modifications removed in :function.php, wp-config.php, .htaccess updated on server) used on localhost, and uploaded the SQL database again, but no change, I still have a blank page.</p> <p>define('WP_DEBUG', true); → wp-admin still blank page</p> <p>Where should I search for a solution ? Thanks for help !</p>
[ { "answer_id": 181646, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>WP 4.1.1 seems to need a lot more memory than previous versions. Just add </p>\n\n<p><code>define('WP_MEMORY_LIMIT', '256M');</code></p>\n\n<p>in your <code>wp-config.php</code> file just before the <code>/* Stop editing */</code> comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48.</p>\n\n<p>EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: </p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com');\nUPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');\n</code></pre>\n\n<p>Without any logs I'm afraid I can't be of any further help.</p>\n" }, { "answer_id": 181652, "author": "CodeX", "author_id": 55186, "author_profile": "https://wordpress.stackexchange.com/users/55186", "pm_score": -1, "selected": false, "text": "<p>When exporting a DB from localhost, you are much better off opening the sql file in a program like notepad++ and doing a \"find replace\" on the URL before importing to your server.</p>\n\n<p>I find that these type of plugins do more harm then good.</p>\n\n<p>Exporting from localhost goes like this for me:</p>\n\n<pre><code>Export DB\nOpen `sql` file in notepad++\nFind Replace the URL with the one on your domain\nImport DB (.sql file)\nedit and upload wp-config.php\n</code></pre>\n\n<p>Works Everytime without problem</p>\n" }, { "answer_id": 212734, "author": "Liton Arefin", "author_id": 85724, "author_profile": "https://wordpress.stackexchange.com/users/85724", "pm_score": -1, "selected": false, "text": "<p>I've faced this kind of problems few times. The problem may occurs for:\nMemory Limit\nCache Plugin Problem</p>\n\n<p>Uninstall all Plugins. If it's not solved the problem then the way I'd solved was, rename \"wp-admin\" folder and upload a Fresh Downloaded \"wp-admin\" folder. \nHope it helps you. </p>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67808/" ]
I've created my template and installed extensions everything worked fine. I work on localhost and then upload to my server and use searchreplacedb2.php to change the root url as usually. But now, I can login and then access wp-admin in localhost, but on my server I can login (correctly and have the admin bar on top of the website pages), but I have a blank page a wp-admin/ I desactivated all security (extensions desactivated and files modifications removed in :function.php, wp-config.php, .htaccess updated on server) used on localhost, and uploaded the SQL database again, but no change, I still have a blank page. define('WP\_DEBUG', true); → wp-admin still blank page Where should I search for a solution ? Thanks for help !
WP 4.1.1 seems to need a lot more memory than previous versions. Just add `define('WP_MEMORY_LIMIT', '256M');` in your `wp-config.php` file just before the `/* Stop editing */` comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48. EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com'); ``` Without any logs I'm afraid I can't be of any further help.
181,619
<p>I'm calling images with a wordpress loop to display in a flexslider on the home page.</p> <p>However, the active class for the thumbnails of the slider aren't working in tandem with the slideshow -- I can't click on thumbnails to view the corresponding larger slideshow image. Instead when I click on the thumbnails all the images in the slider disappear.</p> <p>I believe it has something to do with setting the active class on the thumbnails - and since it isn't hard coded, I'm trying to modify the flexslider jquery to add the active class to the thumbnails </p> <p><a href="http://www.ccbcreative.com/three-river/" rel="nofollow">test site</a></p> <pre><code>jQuery(document).ready(function() { // Default FlexSlider parameters if (typeof fs_params == 'undefined') { fs_params = {animation: 'fade', controlNav: true, directionNav: true, slideshow: false, pauseOnAction: true, pauseOnHover: false, animationSpeed: 600, slideshowSpeed: 7000}; } // Homepage FlexSlider parameters if (typeof fs_params_homepage == 'undefined') { fs_params_homepage = {animation: 'fade', controlNav: true, directionNav: true, slideshow: true, pauseOnAction: false, pauseOnHover: true, animationSpeed: 600, slideshowSpeed: 7000}; } // Note: fs_params / fs_params_homepage can be overwritten by setting its value in an html file // *** FLEXSLIDER INITIALIZATION $('.flexslider').each(function() { var $this = $(this); if ($this.is('#home-slider')) { // Callback function: fires asynchronously with each slider animation fs_params_homepage.before = function(slider){ var next_index = slider.animatingTo + 1, current_index = slider.currentSlide + 1, $next_caption = $('.slider-caption div[id=caption'+next_index+']'), $current_caption = $('.slider-caption div[id=caption'+current_index+']'); $('.slider-menu li').removeClass('active').siblings().find('a') .filter(function () { return $(this).attr('href') == '#slide'+next_index; }).parent().addClass('active'); if ($('html').hasClass('ie8')) { // IE8 hack $current_caption.hide(); } $current_caption.fadeOut(400, 'swing', function() { if ($('html').hasClass('ie8')) { // IE8 hack $next_caption.show(); } else { $next_caption.fadeIn(300, 'swing'); } setCaptionHeight($next_caption); }); }; // Callback function: fires after each slider animation completes fs_params_homepage.after = function(slider){ }; // Init homepage slider: // full-width slider with center-aligned image if ($this.parent().parent().parent().parent().hasClass('full-width-image')) { if ($this.attr('data-slideshow') == 'yes') { fs_params_homepage.slideshow = true; } if ($this.attr('data-slideshow') == 'no') { fs_params_homepage.slideshow = false; } if ($this.attr('data-animation') == 'fade') { fs_params_homepage.animation = 'fade'; } if ($this.attr('data-animation') == 'slide') { fs_params_homepage.animation = 'slide'; } if ($this.attr('data-control-nav') == 'yes') { fs_params_homepage.controlNav = true; } if ($this.attr('data-control-nav') == 'no') { fs_params_homepage.controlNav = false; } if ($this.attr('data-direction-nav') == 'yes') { fs_params_homepage.directionNav = true; } if ($this.attr('data-direction-nav') == 'no') { fs_params_homepage.directionNav = false; } if ($this.attr('data-pause-on-action') == 'yes') { fs_params_homepage.pauseOnAction = true; } if ($this.attr('data-pause-on-action') == 'no') { fs_params_homepage.pauseOnAction = false; } } // slider with right-aligned image else { fs_params_homepage.animation = 'fade'; } if ($this.attr('data-slideshow-speed') &gt; 0) { fs_params_homepage.slideshowSpeed = $this.attr('data-slideshow-speed'); } $this.flexslider(fs_params_homepage); } else { // Init default slider var params = $.extend({}, fs_params); if ($this.attr('data-slideshow') == 'yes') { params.slideshow = true; } if ($this.attr('data-slideshow') == 'no') { params.slideshow = false; } if ($this.attr('data-slideshow-speed') &gt; 0) { params.slideshowSpeed = $this.attr('data-slideshow-speed'); } if ($this.attr('data-animation') == 'fade') { params.animation = 'fade'; } if ($this.attr('data-animation') == 'slide') { params.animation = 'slide'; } if ($this.attr('data-control-nav') == 'yes') { params.controlNav = true; } if ($this.attr('data-control-nav') == 'no') { params.controlNav = false; } if ($this.attr('data-direction-nav') == 'yes') { params.directionNav = true; } if ($this.attr('data-direction-nav') == 'no') { params.directionNav = false; } if ($this.attr('data-pause-on-action') == 'yes') { params.pauseOnAction = true; } if ($this.attr('data-pause-on-action') == 'no') { params.pauseOnAction = false; } $this.flexslider(params); } }); // *** HOMEPAGE SLIDER $homeSlider = $('#home-slider').data('flexslider'); // Slider menu $('.slider-menu li').on('click', function(e) { e.preventDefault(); var slide_index = $('a', this).attr('href').substr(6) - 1; $homeSlider.flexslider(slide_index); return false; // IE9 hack }); // Position the right side navigation ("right-side-nav" class) function positionRightSideNav() { if ($(window).width() &gt;= 768) { var homeHero_x = 0.5 * ($(window).width() - $('#home-hero').width()), heroImage_marginLeft = parseInt($('#home-hero .hero-image').css('margin-left')), col_marginLeft = parseInt($('#home-hero-content .columns').css('margin-left')), rightSideNav_width = $('#home-slider.right-side-nav .flex-direction-nav a').width(), navLeft = $(window).width() - (homeHero_x + col_marginLeft + heroImage_marginLeft) - rightSideNav_width; $('#home-slider.right-side-nav .flex-direction-nav a').css('left', navLeft + 'px'); } else { $('#home-slider.right-side-nav .flex-direction-nav a').css('left', ''); } } </code></pre> <p><strong>wp-query for large slideshow images:</strong></p> <pre><code>&lt;div class="hero-image"&gt; &lt;div id="home-slider" class="flexslider right-side-nav"&gt; &lt;ul class="slides"&gt; &lt;?php $attachments = get_children(array('post_parent' =&gt; 107, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'post_status' =&gt; 'inherit', 'posts_per_page' =&gt; 7, 'order' =&gt; 'DESC' )); if ($attachments) { foreach ( $attachments as $attachment_id =&gt; $attachment ) { echo '&lt;li id="slide'.$attachment_id.'" &gt;'; echo wp_get_attachment_image($attachment_id, 'home-slider'); echo '&lt;/li&gt;'; } } // end see if images wp_reset_postdata(); ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>and then wp-query for thumbs:</strong></p> <pre><code>&lt;?php $thumbs = get_children(array('post_parent' =&gt; 107, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'post_status' =&gt; 'inherit', 'posts_per_page' =&gt; 7, 'order' =&gt; 'DESC' )); if ($thumbs) { // if there are images attached to posting, start the flexslider markup foreach ( $thumbs as $attachment_id =&gt; $thumb ) { // create the list items for images with captions echo '&lt;li&gt;'; echo '&lt;a href="#slide'.$attachment_id.'" &gt;'; echo wp_get_attachment_image($attachment_id, 'home-slider-thumb'); echo '&lt;/a&gt;'; echo '&lt;/li&gt;'; } } // end see if images wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 181646, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>WP 4.1.1 seems to need a lot more memory than previous versions. Just add </p>\n\n<p><code>define('WP_MEMORY_LIMIT', '256M');</code></p>\n\n<p>in your <code>wp-config.php</code> file just before the <code>/* Stop editing */</code> comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48.</p>\n\n<p>EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: </p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com');\nUPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');\n</code></pre>\n\n<p>Without any logs I'm afraid I can't be of any further help.</p>\n" }, { "answer_id": 181652, "author": "CodeX", "author_id": 55186, "author_profile": "https://wordpress.stackexchange.com/users/55186", "pm_score": -1, "selected": false, "text": "<p>When exporting a DB from localhost, you are much better off opening the sql file in a program like notepad++ and doing a \"find replace\" on the URL before importing to your server.</p>\n\n<p>I find that these type of plugins do more harm then good.</p>\n\n<p>Exporting from localhost goes like this for me:</p>\n\n<pre><code>Export DB\nOpen `sql` file in notepad++\nFind Replace the URL with the one on your domain\nImport DB (.sql file)\nedit and upload wp-config.php\n</code></pre>\n\n<p>Works Everytime without problem</p>\n" }, { "answer_id": 212734, "author": "Liton Arefin", "author_id": 85724, "author_profile": "https://wordpress.stackexchange.com/users/85724", "pm_score": -1, "selected": false, "text": "<p>I've faced this kind of problems few times. The problem may occurs for:\nMemory Limit\nCache Plugin Problem</p>\n\n<p>Uninstall all Plugins. If it's not solved the problem then the way I'd solved was, rename \"wp-admin\" folder and upload a Fresh Downloaded \"wp-admin\" folder. \nHope it helps you. </p>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54520/" ]
I'm calling images with a wordpress loop to display in a flexslider on the home page. However, the active class for the thumbnails of the slider aren't working in tandem with the slideshow -- I can't click on thumbnails to view the corresponding larger slideshow image. Instead when I click on the thumbnails all the images in the slider disappear. I believe it has something to do with setting the active class on the thumbnails - and since it isn't hard coded, I'm trying to modify the flexslider jquery to add the active class to the thumbnails [test site](http://www.ccbcreative.com/three-river/) ``` jQuery(document).ready(function() { // Default FlexSlider parameters if (typeof fs_params == 'undefined') { fs_params = {animation: 'fade', controlNav: true, directionNav: true, slideshow: false, pauseOnAction: true, pauseOnHover: false, animationSpeed: 600, slideshowSpeed: 7000}; } // Homepage FlexSlider parameters if (typeof fs_params_homepage == 'undefined') { fs_params_homepage = {animation: 'fade', controlNav: true, directionNav: true, slideshow: true, pauseOnAction: false, pauseOnHover: true, animationSpeed: 600, slideshowSpeed: 7000}; } // Note: fs_params / fs_params_homepage can be overwritten by setting its value in an html file // *** FLEXSLIDER INITIALIZATION $('.flexslider').each(function() { var $this = $(this); if ($this.is('#home-slider')) { // Callback function: fires asynchronously with each slider animation fs_params_homepage.before = function(slider){ var next_index = slider.animatingTo + 1, current_index = slider.currentSlide + 1, $next_caption = $('.slider-caption div[id=caption'+next_index+']'), $current_caption = $('.slider-caption div[id=caption'+current_index+']'); $('.slider-menu li').removeClass('active').siblings().find('a') .filter(function () { return $(this).attr('href') == '#slide'+next_index; }).parent().addClass('active'); if ($('html').hasClass('ie8')) { // IE8 hack $current_caption.hide(); } $current_caption.fadeOut(400, 'swing', function() { if ($('html').hasClass('ie8')) { // IE8 hack $next_caption.show(); } else { $next_caption.fadeIn(300, 'swing'); } setCaptionHeight($next_caption); }); }; // Callback function: fires after each slider animation completes fs_params_homepage.after = function(slider){ }; // Init homepage slider: // full-width slider with center-aligned image if ($this.parent().parent().parent().parent().hasClass('full-width-image')) { if ($this.attr('data-slideshow') == 'yes') { fs_params_homepage.slideshow = true; } if ($this.attr('data-slideshow') == 'no') { fs_params_homepage.slideshow = false; } if ($this.attr('data-animation') == 'fade') { fs_params_homepage.animation = 'fade'; } if ($this.attr('data-animation') == 'slide') { fs_params_homepage.animation = 'slide'; } if ($this.attr('data-control-nav') == 'yes') { fs_params_homepage.controlNav = true; } if ($this.attr('data-control-nav') == 'no') { fs_params_homepage.controlNav = false; } if ($this.attr('data-direction-nav') == 'yes') { fs_params_homepage.directionNav = true; } if ($this.attr('data-direction-nav') == 'no') { fs_params_homepage.directionNav = false; } if ($this.attr('data-pause-on-action') == 'yes') { fs_params_homepage.pauseOnAction = true; } if ($this.attr('data-pause-on-action') == 'no') { fs_params_homepage.pauseOnAction = false; } } // slider with right-aligned image else { fs_params_homepage.animation = 'fade'; } if ($this.attr('data-slideshow-speed') > 0) { fs_params_homepage.slideshowSpeed = $this.attr('data-slideshow-speed'); } $this.flexslider(fs_params_homepage); } else { // Init default slider var params = $.extend({}, fs_params); if ($this.attr('data-slideshow') == 'yes') { params.slideshow = true; } if ($this.attr('data-slideshow') == 'no') { params.slideshow = false; } if ($this.attr('data-slideshow-speed') > 0) { params.slideshowSpeed = $this.attr('data-slideshow-speed'); } if ($this.attr('data-animation') == 'fade') { params.animation = 'fade'; } if ($this.attr('data-animation') == 'slide') { params.animation = 'slide'; } if ($this.attr('data-control-nav') == 'yes') { params.controlNav = true; } if ($this.attr('data-control-nav') == 'no') { params.controlNav = false; } if ($this.attr('data-direction-nav') == 'yes') { params.directionNav = true; } if ($this.attr('data-direction-nav') == 'no') { params.directionNav = false; } if ($this.attr('data-pause-on-action') == 'yes') { params.pauseOnAction = true; } if ($this.attr('data-pause-on-action') == 'no') { params.pauseOnAction = false; } $this.flexslider(params); } }); // *** HOMEPAGE SLIDER $homeSlider = $('#home-slider').data('flexslider'); // Slider menu $('.slider-menu li').on('click', function(e) { e.preventDefault(); var slide_index = $('a', this).attr('href').substr(6) - 1; $homeSlider.flexslider(slide_index); return false; // IE9 hack }); // Position the right side navigation ("right-side-nav" class) function positionRightSideNav() { if ($(window).width() >= 768) { var homeHero_x = 0.5 * ($(window).width() - $('#home-hero').width()), heroImage_marginLeft = parseInt($('#home-hero .hero-image').css('margin-left')), col_marginLeft = parseInt($('#home-hero-content .columns').css('margin-left')), rightSideNav_width = $('#home-slider.right-side-nav .flex-direction-nav a').width(), navLeft = $(window).width() - (homeHero_x + col_marginLeft + heroImage_marginLeft) - rightSideNav_width; $('#home-slider.right-side-nav .flex-direction-nav a').css('left', navLeft + 'px'); } else { $('#home-slider.right-side-nav .flex-direction-nav a').css('left', ''); } } ``` **wp-query for large slideshow images:** ``` <div class="hero-image"> <div id="home-slider" class="flexslider right-side-nav"> <ul class="slides"> <?php $attachments = get_children(array('post_parent' => 107, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => 7, 'order' => 'DESC' )); if ($attachments) { foreach ( $attachments as $attachment_id => $attachment ) { echo '<li id="slide'.$attachment_id.'" >'; echo wp_get_attachment_image($attachment_id, 'home-slider'); echo '</li>'; } } // end see if images wp_reset_postdata(); ?> </ul> </div> </div> ``` **and then wp-query for thumbs:** ``` <?php $thumbs = get_children(array('post_parent' => 107, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => 7, 'order' => 'DESC' )); if ($thumbs) { // if there are images attached to posting, start the flexslider markup foreach ( $thumbs as $attachment_id => $thumb ) { // create the list items for images with captions echo '<li>'; echo '<a href="#slide'.$attachment_id.'" >'; echo wp_get_attachment_image($attachment_id, 'home-slider-thumb'); echo '</a>'; echo '</li>'; } } // end see if images wp_reset_postdata(); ?> ```
WP 4.1.1 seems to need a lot more memory than previous versions. Just add `define('WP_MEMORY_LIMIT', '256M');` in your `wp-config.php` file just before the `/* Stop editing */` comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48. EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com'); ``` Without any logs I'm afraid I can't be of any further help.
181,620
<p>I have one meta key "game" containing this meta value "game 1, game 2".</p> <p>I would like to display this meta value on my site like this:</p> <pre><code>&lt;a href="http://www.url.com/game-1"&gt;game 1&lt;/a&gt; &lt;a href="http://www.url.com/game-2"&gt;game 2&lt;/a&gt; </code></pre> <p>Thanks for your help.</p>
[ { "answer_id": 181646, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>WP 4.1.1 seems to need a lot more memory than previous versions. Just add </p>\n\n<p><code>define('WP_MEMORY_LIMIT', '256M');</code></p>\n\n<p>in your <code>wp-config.php</code> file just before the <code>/* Stop editing */</code> comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48.</p>\n\n<p>EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: </p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com');\nUPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');\n</code></pre>\n\n<p>Without any logs I'm afraid I can't be of any further help.</p>\n" }, { "answer_id": 181652, "author": "CodeX", "author_id": 55186, "author_profile": "https://wordpress.stackexchange.com/users/55186", "pm_score": -1, "selected": false, "text": "<p>When exporting a DB from localhost, you are much better off opening the sql file in a program like notepad++ and doing a \"find replace\" on the URL before importing to your server.</p>\n\n<p>I find that these type of plugins do more harm then good.</p>\n\n<p>Exporting from localhost goes like this for me:</p>\n\n<pre><code>Export DB\nOpen `sql` file in notepad++\nFind Replace the URL with the one on your domain\nImport DB (.sql file)\nedit and upload wp-config.php\n</code></pre>\n\n<p>Works Everytime without problem</p>\n" }, { "answer_id": 212734, "author": "Liton Arefin", "author_id": 85724, "author_profile": "https://wordpress.stackexchange.com/users/85724", "pm_score": -1, "selected": false, "text": "<p>I've faced this kind of problems few times. The problem may occurs for:\nMemory Limit\nCache Plugin Problem</p>\n\n<p>Uninstall all Plugins. If it's not solved the problem then the way I'd solved was, rename \"wp-admin\" folder and upload a Fresh Downloaded \"wp-admin\" folder. \nHope it helps you. </p>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181620", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66753/" ]
I have one meta key "game" containing this meta value "game 1, game 2". I would like to display this meta value on my site like this: ``` <a href="http://www.url.com/game-1">game 1</a> <a href="http://www.url.com/game-2">game 2</a> ``` Thanks for your help.
WP 4.1.1 seems to need a lot more memory than previous versions. Just add `define('WP_MEMORY_LIMIT', '256M');` in your `wp-config.php` file just before the `/* Stop editing */` comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48. EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com'); ``` Without any logs I'm afraid I can't be of any further help.
181,624
<p>Is it a good idea to harden your web server by disabling outbound connectivity on them?</p> <p>I am using RHEL 7 for a WordPress Multisite installation.</p> <p>After disabling outbound connectivity, the dashboard has become extremely slow, and the plugins page does not list the latest available ones.</p> <p>Could I still live with this? What are the biggest disadvantages?</p>
[ { "answer_id": 181646, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>WP 4.1.1 seems to need a lot more memory than previous versions. Just add </p>\n\n<p><code>define('WP_MEMORY_LIMIT', '256M');</code></p>\n\n<p>in your <code>wp-config.php</code> file just before the <code>/* Stop editing */</code> comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48.</p>\n\n<p>EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: </p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com');\nUPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');\n</code></pre>\n\n<p>Without any logs I'm afraid I can't be of any further help.</p>\n" }, { "answer_id": 181652, "author": "CodeX", "author_id": 55186, "author_profile": "https://wordpress.stackexchange.com/users/55186", "pm_score": -1, "selected": false, "text": "<p>When exporting a DB from localhost, you are much better off opening the sql file in a program like notepad++ and doing a \"find replace\" on the URL before importing to your server.</p>\n\n<p>I find that these type of plugins do more harm then good.</p>\n\n<p>Exporting from localhost goes like this for me:</p>\n\n<pre><code>Export DB\nOpen `sql` file in notepad++\nFind Replace the URL with the one on your domain\nImport DB (.sql file)\nedit and upload wp-config.php\n</code></pre>\n\n<p>Works Everytime without problem</p>\n" }, { "answer_id": 212734, "author": "Liton Arefin", "author_id": 85724, "author_profile": "https://wordpress.stackexchange.com/users/85724", "pm_score": -1, "selected": false, "text": "<p>I've faced this kind of problems few times. The problem may occurs for:\nMemory Limit\nCache Plugin Problem</p>\n\n<p>Uninstall all Plugins. If it's not solved the problem then the way I'd solved was, rename \"wp-admin\" folder and upload a Fresh Downloaded \"wp-admin\" folder. \nHope it helps you. </p>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5852/" ]
Is it a good idea to harden your web server by disabling outbound connectivity on them? I am using RHEL 7 for a WordPress Multisite installation. After disabling outbound connectivity, the dashboard has become extremely slow, and the plugins page does not list the latest available ones. Could I still live with this? What are the biggest disadvantages?
WP 4.1.1 seems to need a lot more memory than previous versions. Just add `define('WP_MEMORY_LIMIT', '256M');` in your `wp-config.php` file just before the `/* Stop editing */` comment line and you should get rid of the blank screens. If you can't access that much memory, go for less, but from my tests the minimum required is 96M. This is probably a bug and will prolly get fixed a.s.a.p. by WP devs. WP is supposed to run fine on 64M, or even 48. EDIT: I wrongly assumed you have the memory leak bug that seems to be quite big at the moment related to updating existing WP installations to the latest patch. Your issue has to do with wrong options set in your DB. Here are the SQL queries I run when moving WP installations to a new address: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-domain.com', 'http://www.new-domain.com') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com', 'http://www.new-domain.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com'); ``` Without any logs I'm afraid I can't be of any further help.
181,630
<p>So I have the following code:</p> <pre><code> &lt;h3&gt; &lt;div class="sellertitle"&gt;&lt;a class="allseller" href="#"&gt;Something&lt;/a&gt; &lt;/div&gt; &lt;?php if ( is_user_logged_in() ) { ?&gt; &lt;div class="otherseller"&gt; &lt;a class="allotherseller" href="#"&gt;Else&lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/h3&gt; </code></pre> <p>Then, for the "sellertitle," I have the following CSS:</p> <pre><code>&lt;--logged in--&gt; .sellertitle { float: left; width: 49%; } </code></pre> <p>As you can see, "Something" is always visible and "Else" is only visible when the user is logged in.</p> <p>However when the user is logged out, I want the "sellertitle" CSS to be "float:none"</p> <pre><code>&lt;--logged out--&gt; .sellertitle { float: none; width: 49%; } </code></pre> <p>What would be the best way to achieve this?</p>
[ { "answer_id": 181632, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 2, "selected": false, "text": "<p>you could try something like this... this will add css on the head</p>\n\n<pre><code>add_action('wp_head', 'add_css_head');\nfunction add_css_head() {\n if ( is_user_logged_in() ) {\n ?&gt;\n &lt;style&gt;\n .sellertitle {\n float: left;\n width: 49%; \n }\n &lt;/style&gt;\n &lt;?php\n } else {\n ?&gt;\n &lt;style&gt;\n .sellertitle {\n float: none;\n width: 49%; \n }\n &lt;/style&gt;\n &lt;?php\n }\n}\n</code></pre>\n\n<hr>\n\n<p>another is to change class if logged in...</p>\n\n<p>so you will have two css</p>\n\n<pre><code>.sellertitle {\n float: none;\n width: 49%; \n}\n.sellertitle.logged {\n float: left; \n}\n</code></pre>\n\n<p>then on your div something like this...</p>\n\n<pre><code>&lt;div class=\"sellertitle &lt;?php if ( is_user_logged_in() ) {echo 'logged';}\"&gt;\n</code></pre>\n" }, { "answer_id": 181657, "author": "Rafael", "author_id": 69288, "author_profile": "https://wordpress.stackexchange.com/users/69288", "pm_score": 5, "selected": true, "text": "<p>Here is another CSS-only approach, without any inline-PHP and needless CSS-spam in the head.\nIf your theme is correctly using <a href=\"http://codex.wordpress.org/Function_Reference/body_class\" rel=\"noreferrer\">body_class()</a> and a user is logged in, Wordpress adds a class \"logged-in\" to the body-element, so we can use this in our stylesheet:</p>\n\n<pre><code>&lt;--logged out--&gt;\n.sellertitle {\n float: none;\n width: 49%; \n}\n\n.otherseller {\n display: none;\n}\n\n&lt;--logged in--&gt;\n.logged-in .sellertitle {\n float: left; \n}\n\n.logged-in .otherseller {\n display: inline;\n}\n</code></pre>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So I have the following code: ``` <h3> <div class="sellertitle"><a class="allseller" href="#">Something</a> </div> <?php if ( is_user_logged_in() ) { ?> <div class="otherseller"> <a class="allotherseller" href="#">Else</a> </div> <?php } ?> </h3> ``` Then, for the "sellertitle," I have the following CSS: ``` <--logged in--> .sellertitle { float: left; width: 49%; } ``` As you can see, "Something" is always visible and "Else" is only visible when the user is logged in. However when the user is logged out, I want the "sellertitle" CSS to be "float:none" ``` <--logged out--> .sellertitle { float: none; width: 49%; } ``` What would be the best way to achieve this?
Here is another CSS-only approach, without any inline-PHP and needless CSS-spam in the head. If your theme is correctly using [body\_class()](http://codex.wordpress.org/Function_Reference/body_class) and a user is logged in, Wordpress adds a class "logged-in" to the body-element, so we can use this in our stylesheet: ``` <--logged out--> .sellertitle { float: none; width: 49%; } .otherseller { display: none; } <--logged in--> .logged-in .sellertitle { float: left; } .logged-in .otherseller { display: inline; } ```
181,653
<p>So, I have the following shortcode which is included in two different pages.</p> <pre><code>&lt;?php echo do_shortcode('[shortcode]'); ?&gt; </code></pre> <p>Since two pages are using one identical shortocode, I am thinking of adding a class to the first page so that I can customize the first page shortcode only.</p> <p>So here is my question.</p> <ol> <li><p>Do you think that adding a class to the shortcode in the first page would allow me to customize it?</p></li> <li><p>If so, what is the proper way of adding a class to the above code?</p></li> <li><p>If not, what would be an option to add customization to a shortcode for only specific page?</p></li> </ol> <p>Thank</p>
[ { "answer_id": 181632, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 2, "selected": false, "text": "<p>you could try something like this... this will add css on the head</p>\n\n<pre><code>add_action('wp_head', 'add_css_head');\nfunction add_css_head() {\n if ( is_user_logged_in() ) {\n ?&gt;\n &lt;style&gt;\n .sellertitle {\n float: left;\n width: 49%; \n }\n &lt;/style&gt;\n &lt;?php\n } else {\n ?&gt;\n &lt;style&gt;\n .sellertitle {\n float: none;\n width: 49%; \n }\n &lt;/style&gt;\n &lt;?php\n }\n}\n</code></pre>\n\n<hr>\n\n<p>another is to change class if logged in...</p>\n\n<p>so you will have two css</p>\n\n<pre><code>.sellertitle {\n float: none;\n width: 49%; \n}\n.sellertitle.logged {\n float: left; \n}\n</code></pre>\n\n<p>then on your div something like this...</p>\n\n<pre><code>&lt;div class=\"sellertitle &lt;?php if ( is_user_logged_in() ) {echo 'logged';}\"&gt;\n</code></pre>\n" }, { "answer_id": 181657, "author": "Rafael", "author_id": 69288, "author_profile": "https://wordpress.stackexchange.com/users/69288", "pm_score": 5, "selected": true, "text": "<p>Here is another CSS-only approach, without any inline-PHP and needless CSS-spam in the head.\nIf your theme is correctly using <a href=\"http://codex.wordpress.org/Function_Reference/body_class\" rel=\"noreferrer\">body_class()</a> and a user is logged in, Wordpress adds a class \"logged-in\" to the body-element, so we can use this in our stylesheet:</p>\n\n<pre><code>&lt;--logged out--&gt;\n.sellertitle {\n float: none;\n width: 49%; \n}\n\n.otherseller {\n display: none;\n}\n\n&lt;--logged in--&gt;\n.logged-in .sellertitle {\n float: left; \n}\n\n.logged-in .otherseller {\n display: inline;\n}\n</code></pre>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, I have the following shortcode which is included in two different pages. ``` <?php echo do_shortcode('[shortcode]'); ?> ``` Since two pages are using one identical shortocode, I am thinking of adding a class to the first page so that I can customize the first page shortcode only. So here is my question. 1. Do you think that adding a class to the shortcode in the first page would allow me to customize it? 2. If so, what is the proper way of adding a class to the above code? 3. If not, what would be an option to add customization to a shortcode for only specific page? Thank
Here is another CSS-only approach, without any inline-PHP and needless CSS-spam in the head. If your theme is correctly using [body\_class()](http://codex.wordpress.org/Function_Reference/body_class) and a user is logged in, Wordpress adds a class "logged-in" to the body-element, so we can use this in our stylesheet: ``` <--logged out--> .sellertitle { float: none; width: 49%; } .otherseller { display: none; } <--logged in--> .logged-in .sellertitle { float: left; } .logged-in .otherseller { display: inline; } ```
181,688
<p>I'm creating a custom plugin. One of the fields in the plugin let's the user add data.<br> If I add a <code>textarea</code> the user has no control over the text. So I would like to add a editor.<br> I know WordPress offers the <code>wp_editor();</code> function.<br>After some Google-ing I found that it is very easy to implement the editor.:</p> <pre><code>$content = ''; $editor_id = 'mycustomeditor'; wp_editor( $content, $editor_id ); </code></pre> <p>This shows a nice editor. The problem is that the content isn't getting saved. <br>The editor is a part of a form so I thought I add the save function to the form save function like this:<br> <code>if( isset( $_POST[ 'mycustomeditor' ] ) ) {update_post_meta( $post_id, 'mycustomeditor', array_map('sanitize_text_field', $_POST[ 'mycustomeditor' ]) );} </code> However WordPress thinks different about this. It does create the <code>meta_key</code> in the database but no value.</p> <p>I hope anyone can see what I'm doing wrong!</p>
[ { "answer_id": 181753, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 4, "selected": true, "text": "<p>Solved it!</p>\n\n<p>Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why.</p>\n\n<pre><code>$editor_id = 'custom_editor_box';\n$uploaded_csv = get_post_meta( $post-&gt;ID, 'custom_editor_box', true);\nwp_editor( $uploaded_csv, $editor_id );\n</code></pre>\n\n<p>To save the data:</p>\n\n<pre><code>function save_wp_editor_fields(){\n global $post;\n update_post_meta($post-&gt;ID, 'custom_editor_box', $_POST['custom_editor_box']);\n}\nadd_action( 'save_post', 'save_wp_editor_fields' );\n</code></pre>\n\n<p>And that's all there is to it!</p>\n" }, { "answer_id": 244065, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>This is how I have it in one of my plugins:</p>\n\n<pre><code>&lt;?php\nwp_nonce_field('nonce_action', 'nonce_field');\n$content = get_option('my_content');\nwp_editor( $content, 'settings_wpeditor' );\n?&gt;\n\nfunction settings_save_wpeditor(){\n// check the nonce, update the option etc...\n\nif(isset($_POST['settings_wpeditor']) &amp;&amp; isset($_POST['nonce_field']) &amp;&amp; wp_verify_nonce($_POST['nonce_field'], 'nonce_action') ){\nupdate_option('my_content', wp_kses_post($_POST['settings_wpeditor']));\n}\n}\n\nadd_action('admin_init', 'settings_save_wpeditor', 10);\n</code></pre>\n\n<p>Be sure to add prefixes to your variables and option names and also look up wp_none and wp_verify_nonce from the WordPress codex.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_nonce_field</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_verify_nonce\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_verify_nonce</a></p>\n" }, { "answer_id": 261332, "author": "Dharmin", "author_id": 116208, "author_profile": "https://wordpress.stackexchange.com/users/116208", "pm_score": 0, "selected": false, "text": "<pre><code>$editor_id = 'product_summary';\n\n$summary = get_post_meta( $post-&gt;ID,'product_summary', true );\nwp_editor( $summary, $editor_id );\nif( isset( $_REQUEST['product_summary'] ) ){\n update_post_meta( $post_id, 'product_summary',wp_kses_post( $_POST['product_summary'] ) );\n }\n</code></pre>\n\n<p>value update in <code>wp_editor</code> but not update the value in database, please check and solve it?</p>\n" }, { "answer_id": 277493, "author": "Jaswinder Singh", "author_id": 126201, "author_profile": "https://wordpress.stackexchange.com/users/126201", "pm_score": 0, "selected": false, "text": "<p>Hi that is the solution of your problem, Just copy and paste and see.....</p>\n\n<pre><code> function dhansikhi_hukamnama_post_page(){\n ?&gt;\n &lt;div class='wrap'&gt;\n &lt;h2&gt;My Super Admin Page&lt;/h2&gt;\n &lt;form method='post'&gt;\n &lt;?php\n wp_nonce_field('nates_nonce_action', 'nates_nonce_field');\n $content = get_option('special_content');\n wp_editor( $content, 'special_content' );\n submit_button('Save', 'primary');\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;&lt;!-- .wrap --&gt;\n &lt;?php\n }\n add_action( 'admin_menu', 'dhansikhi_hukamnama_page' );\n</code></pre>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52240/" ]
I'm creating a custom plugin. One of the fields in the plugin let's the user add data. If I add a `textarea` the user has no control over the text. So I would like to add a editor. I know WordPress offers the `wp_editor();` function. After some Google-ing I found that it is very easy to implement the editor.: ``` $content = ''; $editor_id = 'mycustomeditor'; wp_editor( $content, $editor_id ); ``` This shows a nice editor. The problem is that the content isn't getting saved. The editor is a part of a form so I thought I add the save function to the form save function like this: `if( isset( $_POST[ 'mycustomeditor' ] ) ) {update_post_meta( $post_id, 'mycustomeditor', array_map('sanitize_text_field', $_POST[ 'mycustomeditor' ]) );}` However WordPress thinks different about this. It does create the `meta_key` in the database but no value. I hope anyone can see what I'm doing wrong!
Solved it! Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why. ``` $editor_id = 'custom_editor_box'; $uploaded_csv = get_post_meta( $post->ID, 'custom_editor_box', true); wp_editor( $uploaded_csv, $editor_id ); ``` To save the data: ``` function save_wp_editor_fields(){ global $post; update_post_meta($post->ID, 'custom_editor_box', $_POST['custom_editor_box']); } add_action( 'save_post', 'save_wp_editor_fields' ); ``` And that's all there is to it!
181,706
<p>Is it possible to add a class to links created with the link button in the posts editor of wordpress. If not is there a plugin that allow me to do that? Thanks in advance</p>
[ { "answer_id": 181753, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 4, "selected": true, "text": "<p>Solved it!</p>\n\n<p>Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why.</p>\n\n<pre><code>$editor_id = 'custom_editor_box';\n$uploaded_csv = get_post_meta( $post-&gt;ID, 'custom_editor_box', true);\nwp_editor( $uploaded_csv, $editor_id );\n</code></pre>\n\n<p>To save the data:</p>\n\n<pre><code>function save_wp_editor_fields(){\n global $post;\n update_post_meta($post-&gt;ID, 'custom_editor_box', $_POST['custom_editor_box']);\n}\nadd_action( 'save_post', 'save_wp_editor_fields' );\n</code></pre>\n\n<p>And that's all there is to it!</p>\n" }, { "answer_id": 244065, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>This is how I have it in one of my plugins:</p>\n\n<pre><code>&lt;?php\nwp_nonce_field('nonce_action', 'nonce_field');\n$content = get_option('my_content');\nwp_editor( $content, 'settings_wpeditor' );\n?&gt;\n\nfunction settings_save_wpeditor(){\n// check the nonce, update the option etc...\n\nif(isset($_POST['settings_wpeditor']) &amp;&amp; isset($_POST['nonce_field']) &amp;&amp; wp_verify_nonce($_POST['nonce_field'], 'nonce_action') ){\nupdate_option('my_content', wp_kses_post($_POST['settings_wpeditor']));\n}\n}\n\nadd_action('admin_init', 'settings_save_wpeditor', 10);\n</code></pre>\n\n<p>Be sure to add prefixes to your variables and option names and also look up wp_none and wp_verify_nonce from the WordPress codex.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_nonce_field</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_verify_nonce\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_verify_nonce</a></p>\n" }, { "answer_id": 261332, "author": "Dharmin", "author_id": 116208, "author_profile": "https://wordpress.stackexchange.com/users/116208", "pm_score": 0, "selected": false, "text": "<pre><code>$editor_id = 'product_summary';\n\n$summary = get_post_meta( $post-&gt;ID,'product_summary', true );\nwp_editor( $summary, $editor_id );\nif( isset( $_REQUEST['product_summary'] ) ){\n update_post_meta( $post_id, 'product_summary',wp_kses_post( $_POST['product_summary'] ) );\n }\n</code></pre>\n\n<p>value update in <code>wp_editor</code> but not update the value in database, please check and solve it?</p>\n" }, { "answer_id": 277493, "author": "Jaswinder Singh", "author_id": 126201, "author_profile": "https://wordpress.stackexchange.com/users/126201", "pm_score": 0, "selected": false, "text": "<p>Hi that is the solution of your problem, Just copy and paste and see.....</p>\n\n<pre><code> function dhansikhi_hukamnama_post_page(){\n ?&gt;\n &lt;div class='wrap'&gt;\n &lt;h2&gt;My Super Admin Page&lt;/h2&gt;\n &lt;form method='post'&gt;\n &lt;?php\n wp_nonce_field('nates_nonce_action', 'nates_nonce_field');\n $content = get_option('special_content');\n wp_editor( $content, 'special_content' );\n submit_button('Save', 'primary');\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;&lt;!-- .wrap --&gt;\n &lt;?php\n }\n add_action( 'admin_menu', 'dhansikhi_hukamnama_page' );\n</code></pre>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69318/" ]
Is it possible to add a class to links created with the link button in the posts editor of wordpress. If not is there a plugin that allow me to do that? Thanks in advance
Solved it! Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why. ``` $editor_id = 'custom_editor_box'; $uploaded_csv = get_post_meta( $post->ID, 'custom_editor_box', true); wp_editor( $uploaded_csv, $editor_id ); ``` To save the data: ``` function save_wp_editor_fields(){ global $post; update_post_meta($post->ID, 'custom_editor_box', $_POST['custom_editor_box']); } add_action( 'save_post', 'save_wp_editor_fields' ); ``` And that's all there is to it!
181,715
<p>I'm running into a catch-22 situation running a request filter. I need the request to be correct in order to run the correct filter, but I need the filter to correct the request. GAH!</p> <p>Here is the code:</p> <pre><code>function cpt_parse_taxonomy_string( $request, $cpt, $ctax ){ if( array_key_exists( $ctax , $request ) &amp;&amp; ! get_term_by( 'slug', $request[$ctax], $ctax ) ){ $request[$cpt] = $request[$ctax]; $request['name'] = $request[$ctax]; $request['post_type'] = $cpt; unset( $request[$ctax] ); } return $request; } function cpt_request_filters( $request ) { global $post; if ( 'toys' == get_post_type( $post ) ) { return cpt_parse_taxonomy_string( $request, 'toys', 'toy_series' ); } if ( 'books' == get_post_type( $post ) ) { return cpt_parse_taxonomy_string( $request, 'books', 'book-publishers-series' ); } return $request; } add_filter( 'request', 'cpt_request_filters' ); </code></pre> <p>In an effort to keep my code DRY and not do a redundant filter for every post-type that will be affected, I tried to push the bulk of the code into a reusable function. However, the function is never being run.</p> <p>The second function is where I'm having the difficulty. I am attempting to call in the global $post, but I think I am trying to get it too early. It doesn't exist yet, so it's coming in null which makes the rest of my conditionals flake and the first function never runs for either custom post type I am testing for. Then I thought perhaps I could look at the request itself to get the info I need, but because the filter hasn't run yet, the request is potentially wrong and my conditionals will not run correctly.</p> <p>How can I get the post or what other way can I test for those post types?</p> <p>Thanks!</p>
[ { "answer_id": 181753, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 4, "selected": true, "text": "<p>Solved it!</p>\n\n<p>Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why.</p>\n\n<pre><code>$editor_id = 'custom_editor_box';\n$uploaded_csv = get_post_meta( $post-&gt;ID, 'custom_editor_box', true);\nwp_editor( $uploaded_csv, $editor_id );\n</code></pre>\n\n<p>To save the data:</p>\n\n<pre><code>function save_wp_editor_fields(){\n global $post;\n update_post_meta($post-&gt;ID, 'custom_editor_box', $_POST['custom_editor_box']);\n}\nadd_action( 'save_post', 'save_wp_editor_fields' );\n</code></pre>\n\n<p>And that's all there is to it!</p>\n" }, { "answer_id": 244065, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>This is how I have it in one of my plugins:</p>\n\n<pre><code>&lt;?php\nwp_nonce_field('nonce_action', 'nonce_field');\n$content = get_option('my_content');\nwp_editor( $content, 'settings_wpeditor' );\n?&gt;\n\nfunction settings_save_wpeditor(){\n// check the nonce, update the option etc...\n\nif(isset($_POST['settings_wpeditor']) &amp;&amp; isset($_POST['nonce_field']) &amp;&amp; wp_verify_nonce($_POST['nonce_field'], 'nonce_action') ){\nupdate_option('my_content', wp_kses_post($_POST['settings_wpeditor']));\n}\n}\n\nadd_action('admin_init', 'settings_save_wpeditor', 10);\n</code></pre>\n\n<p>Be sure to add prefixes to your variables and option names and also look up wp_none and wp_verify_nonce from the WordPress codex.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_nonce_field</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_verify_nonce\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_verify_nonce</a></p>\n" }, { "answer_id": 261332, "author": "Dharmin", "author_id": 116208, "author_profile": "https://wordpress.stackexchange.com/users/116208", "pm_score": 0, "selected": false, "text": "<pre><code>$editor_id = 'product_summary';\n\n$summary = get_post_meta( $post-&gt;ID,'product_summary', true );\nwp_editor( $summary, $editor_id );\nif( isset( $_REQUEST['product_summary'] ) ){\n update_post_meta( $post_id, 'product_summary',wp_kses_post( $_POST['product_summary'] ) );\n }\n</code></pre>\n\n<p>value update in <code>wp_editor</code> but not update the value in database, please check and solve it?</p>\n" }, { "answer_id": 277493, "author": "Jaswinder Singh", "author_id": 126201, "author_profile": "https://wordpress.stackexchange.com/users/126201", "pm_score": 0, "selected": false, "text": "<p>Hi that is the solution of your problem, Just copy and paste and see.....</p>\n\n<pre><code> function dhansikhi_hukamnama_post_page(){\n ?&gt;\n &lt;div class='wrap'&gt;\n &lt;h2&gt;My Super Admin Page&lt;/h2&gt;\n &lt;form method='post'&gt;\n &lt;?php\n wp_nonce_field('nates_nonce_action', 'nates_nonce_field');\n $content = get_option('special_content');\n wp_editor( $content, 'special_content' );\n submit_button('Save', 'primary');\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;&lt;!-- .wrap --&gt;\n &lt;?php\n }\n add_action( 'admin_menu', 'dhansikhi_hukamnama_page' );\n</code></pre>\n" } ]
2015/03/19
[ "https://wordpress.stackexchange.com/questions/181715", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68905/" ]
I'm running into a catch-22 situation running a request filter. I need the request to be correct in order to run the correct filter, but I need the filter to correct the request. GAH! Here is the code: ``` function cpt_parse_taxonomy_string( $request, $cpt, $ctax ){ if( array_key_exists( $ctax , $request ) && ! get_term_by( 'slug', $request[$ctax], $ctax ) ){ $request[$cpt] = $request[$ctax]; $request['name'] = $request[$ctax]; $request['post_type'] = $cpt; unset( $request[$ctax] ); } return $request; } function cpt_request_filters( $request ) { global $post; if ( 'toys' == get_post_type( $post ) ) { return cpt_parse_taxonomy_string( $request, 'toys', 'toy_series' ); } if ( 'books' == get_post_type( $post ) ) { return cpt_parse_taxonomy_string( $request, 'books', 'book-publishers-series' ); } return $request; } add_filter( 'request', 'cpt_request_filters' ); ``` In an effort to keep my code DRY and not do a redundant filter for every post-type that will be affected, I tried to push the bulk of the code into a reusable function. However, the function is never being run. The second function is where I'm having the difficulty. I am attempting to call in the global $post, but I think I am trying to get it too early. It doesn't exist yet, so it's coming in null which makes the rest of my conditionals flake and the first function never runs for either custom post type I am testing for. Then I thought perhaps I could look at the request itself to get the info I need, but because the filter hasn't run yet, the request is potentially wrong and my conditionals will not run correctly. How can I get the post or what other way can I test for those post types? Thanks!
Solved it! Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why. ``` $editor_id = 'custom_editor_box'; $uploaded_csv = get_post_meta( $post->ID, 'custom_editor_box', true); wp_editor( $uploaded_csv, $editor_id ); ``` To save the data: ``` function save_wp_editor_fields(){ global $post; update_post_meta($post->ID, 'custom_editor_box', $_POST['custom_editor_box']); } add_action( 'save_post', 'save_wp_editor_fields' ); ``` And that's all there is to it!
181,729
<p>I have strong passwords enforced for all my clients but I got some complaints recently as some users tried to change their password and gave up trying to achieve a strong rating. I was initially dismissive until I tried it out. I spend some time trying to write a strong password using these resources:</p> <p><a href="http://wpengine.com/support/strong-passwords/" rel="nofollow">http://wpengine.com/support/strong-passwords/</a> <a href="https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html" rel="nofollow">https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html</a> <a href="https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" rel="nofollow">https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/</a></p> <p>I understand now that the system allows for easier to remember yet harder to guess passwords however it took me a very long time to come up with a password. I was able to set a very long password quickly, but to get something which is easy to remember it took me dozens of tries, which is fine for me, but my clients are not going to accept that.</p> <p>I understand that WordPress is only making suggestions about the strength of the password but in my case I have strong passwords enforced via a plugin and I would prefer to keep this setting, and of course the idea with this is to increase security, but ironically if I can't figure out a system for creating passwords which works with the checker I will be faced with the prospect of turning off the strong password enforce setting. </p> <p>Are there any guidelines to be able to set a password in a short number of tries, ideally something that I could use to educate my clients. In traditional password checkers, the end user knew how to achieve a strong password by following a set of rules ( eg > 8 chars, one capital, one number, one symbol, not username, etc ) </p> <p><strong>Edit:</strong> It was pointed out in the comments that the zxcvbn system is used outside of WordPress, eg Drupal; so this question could be asked eg on StackOverflow, but I tested the ratings from the official zxcvbn tester demo and I couldn't find any correlation between the results and the messages "weak", "medium", "strong" etc. <a href="https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html" rel="nofollow">https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html</a></p> <p><strong>How does WordPress interpret and use the rankings from zxcvbn?</strong></p> <p><strong>Edit 2:</strong> I discovered what the relationship is between the zxcvbn software and the WordPress messages, which effectively answers the question, to some degree anyway, so I've added this as an answer.</p>
[ { "answer_id": 181753, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 4, "selected": true, "text": "<p>Solved it!</p>\n\n<p>Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why.</p>\n\n<pre><code>$editor_id = 'custom_editor_box';\n$uploaded_csv = get_post_meta( $post-&gt;ID, 'custom_editor_box', true);\nwp_editor( $uploaded_csv, $editor_id );\n</code></pre>\n\n<p>To save the data:</p>\n\n<pre><code>function save_wp_editor_fields(){\n global $post;\n update_post_meta($post-&gt;ID, 'custom_editor_box', $_POST['custom_editor_box']);\n}\nadd_action( 'save_post', 'save_wp_editor_fields' );\n</code></pre>\n\n<p>And that's all there is to it!</p>\n" }, { "answer_id": 244065, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 1, "selected": false, "text": "<p>This is how I have it in one of my plugins:</p>\n\n<pre><code>&lt;?php\nwp_nonce_field('nonce_action', 'nonce_field');\n$content = get_option('my_content');\nwp_editor( $content, 'settings_wpeditor' );\n?&gt;\n\nfunction settings_save_wpeditor(){\n// check the nonce, update the option etc...\n\nif(isset($_POST['settings_wpeditor']) &amp;&amp; isset($_POST['nonce_field']) &amp;&amp; wp_verify_nonce($_POST['nonce_field'], 'nonce_action') ){\nupdate_option('my_content', wp_kses_post($_POST['settings_wpeditor']));\n}\n}\n\nadd_action('admin_init', 'settings_save_wpeditor', 10);\n</code></pre>\n\n<p>Be sure to add prefixes to your variables and option names and also look up wp_none and wp_verify_nonce from the WordPress codex.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_nonce_field</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_verify_nonce\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_verify_nonce</a></p>\n" }, { "answer_id": 261332, "author": "Dharmin", "author_id": 116208, "author_profile": "https://wordpress.stackexchange.com/users/116208", "pm_score": 0, "selected": false, "text": "<pre><code>$editor_id = 'product_summary';\n\n$summary = get_post_meta( $post-&gt;ID,'product_summary', true );\nwp_editor( $summary, $editor_id );\nif( isset( $_REQUEST['product_summary'] ) ){\n update_post_meta( $post_id, 'product_summary',wp_kses_post( $_POST['product_summary'] ) );\n }\n</code></pre>\n\n<p>value update in <code>wp_editor</code> but not update the value in database, please check and solve it?</p>\n" }, { "answer_id": 277493, "author": "Jaswinder Singh", "author_id": 126201, "author_profile": "https://wordpress.stackexchange.com/users/126201", "pm_score": 0, "selected": false, "text": "<p>Hi that is the solution of your problem, Just copy and paste and see.....</p>\n\n<pre><code> function dhansikhi_hukamnama_post_page(){\n ?&gt;\n &lt;div class='wrap'&gt;\n &lt;h2&gt;My Super Admin Page&lt;/h2&gt;\n &lt;form method='post'&gt;\n &lt;?php\n wp_nonce_field('nates_nonce_action', 'nates_nonce_field');\n $content = get_option('special_content');\n wp_editor( $content, 'special_content' );\n submit_button('Save', 'primary');\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;&lt;!-- .wrap --&gt;\n &lt;?php\n }\n add_action( 'admin_menu', 'dhansikhi_hukamnama_page' );\n</code></pre>\n" } ]
2015/03/20
[ "https://wordpress.stackexchange.com/questions/181729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6169/" ]
I have strong passwords enforced for all my clients but I got some complaints recently as some users tried to change their password and gave up trying to achieve a strong rating. I was initially dismissive until I tried it out. I spend some time trying to write a strong password using these resources: <http://wpengine.com/support/strong-passwords/> <https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html> <https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/> I understand now that the system allows for easier to remember yet harder to guess passwords however it took me a very long time to come up with a password. I was able to set a very long password quickly, but to get something which is easy to remember it took me dozens of tries, which is fine for me, but my clients are not going to accept that. I understand that WordPress is only making suggestions about the strength of the password but in my case I have strong passwords enforced via a plugin and I would prefer to keep this setting, and of course the idea with this is to increase security, but ironically if I can't figure out a system for creating passwords which works with the checker I will be faced with the prospect of turning off the strong password enforce setting. Are there any guidelines to be able to set a password in a short number of tries, ideally something that I could use to educate my clients. In traditional password checkers, the end user knew how to achieve a strong password by following a set of rules ( eg > 8 chars, one capital, one number, one symbol, not username, etc ) **Edit:** It was pointed out in the comments that the zxcvbn system is used outside of WordPress, eg Drupal; so this question could be asked eg on StackOverflow, but I tested the ratings from the official zxcvbn tester demo and I couldn't find any correlation between the results and the messages "weak", "medium", "strong" etc. <https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html> **How does WordPress interpret and use the rankings from zxcvbn?** **Edit 2:** I discovered what the relationship is between the zxcvbn software and the WordPress messages, which effectively answers the question, to some degree anyway, so I've added this as an answer.
Solved it! Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why. ``` $editor_id = 'custom_editor_box'; $uploaded_csv = get_post_meta( $post->ID, 'custom_editor_box', true); wp_editor( $uploaded_csv, $editor_id ); ``` To save the data: ``` function save_wp_editor_fields(){ global $post; update_post_meta($post->ID, 'custom_editor_box', $_POST['custom_editor_box']); } add_action( 'save_post', 'save_wp_editor_fields' ); ``` And that's all there is to it!
181,795
<p>So here is my button shortcode in my widget.</p> <pre><code> [button title="EDIT" href="&lt;?php ech edit_product_url( $post-&gt;ID ); ?&gt;"] </code></pre> <p>As you can guess the href url does not work.</p> <p>What would be the best way to add php in the shortcode?</p> <p>Thanks</p>
[ { "answer_id": 181798, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>To be honest, if you see yourself in the need of adding executable PHP code into a shortcode attribute, or in content editor in general, you are doing something wrong. You should think again about what, why and how do it. There is a high security risk accepting executable PHP code form user inputs.</p>\n\n<p>Instead, you should pass the post ID in shortcode attributes and get the permalink when parsing the shortcode.</p>\n\n<p>For example, the PHP function that parse the shortcode could be something like this:</p>\n\n<pre><code>add_shortcode( 'button' , 'render_button' );\nfunction render_button( $atts, $content = null ) {\n\n $atts = shortcode_atts( array(\n 'postID' =&gt; 0,\n 'href' =&gt; '',\n 'title' =&gt; ''\n ), $atts );\n\n //You may need sanitize title, not sure what your needs are\n //change this if you need\n $atts['title'] = sanitize_text_field( $atts['title'] );\n\n\n if( (int) $atts['postID'] &gt; 0 ) {\n\n //If postID is set and greater thant zero, get post permalink for that ID\n //and override href\n $atts['href'] = edit_product_url( $atts['postID'] );\n //For standard posts uncomment next linke\n //$atts['href'] = get_permalink( $atts['postID'] );\n\n }\n\n //Example output\n $output = '&lt;a class=\"button\" href=\"' . esc_url( $atts['href'] ) . '\"&gt;' . $atts['title'] . '&lt;/a&gt;';\n\n return $output;\n\n}\n</code></pre>\n\n<p>Now you get the functionality without the need of include executable PHP in shortcode attributes. Also, you can use the <code>render_button</code> function directly if you need.</p>\n\n<p>You can use the shortcode in content editor or wherever shortcodes are parsed, for example:</p>\n\n<pre><code>[button title=\"EDIT\" postID=\"1542\"]\n</code></pre>\n\n<p>You can also render buttons by direct call to the function:</p>\n\n<pre><code> $button = render_button( array( 'postID' =&gt; 4578 ) );\n echo $button;\n</code></pre>\n\n<p>And if you need a specific <code>href</code>, you can use this shortcode:</p>\n\n<pre><code> [button title=\"EDIT\" href=\"http://www.example.com\"]\n</code></pre>\n\n<p>Or with direct function call:</p>\n\n<pre><code> $button = render_button( array( 'href' =&gt; 'http://www.example.com' ) );\n echo $button;\n\n //Or shorter\n echo render_button( array( 'href' =&gt; 'http://www.example.com' ) );\n</code></pre>\n" }, { "answer_id": 181799, "author": "Will English IV", "author_id": 29483, "author_profile": "https://wordpress.stackexchange.com/users/29483", "pm_score": -1, "selected": false, "text": "<p>I would change this to the following</p>\n\n<pre><code>do_shortcode('[button title=\"EDIT\" href=\"' . edit_product_url( $post-&gt;ID ) . '\"]');\n</code></pre>\n" } ]
2015/03/20
[ "https://wordpress.stackexchange.com/questions/181795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So here is my button shortcode in my widget. ``` [button title="EDIT" href="<?php ech edit_product_url( $post->ID ); ?>"] ``` As you can guess the href url does not work. What would be the best way to add php in the shortcode? Thanks
To be honest, if you see yourself in the need of adding executable PHP code into a shortcode attribute, or in content editor in general, you are doing something wrong. You should think again about what, why and how do it. There is a high security risk accepting executable PHP code form user inputs. Instead, you should pass the post ID in shortcode attributes and get the permalink when parsing the shortcode. For example, the PHP function that parse the shortcode could be something like this: ``` add_shortcode( 'button' , 'render_button' ); function render_button( $atts, $content = null ) { $atts = shortcode_atts( array( 'postID' => 0, 'href' => '', 'title' => '' ), $atts ); //You may need sanitize title, not sure what your needs are //change this if you need $atts['title'] = sanitize_text_field( $atts['title'] ); if( (int) $atts['postID'] > 0 ) { //If postID is set and greater thant zero, get post permalink for that ID //and override href $atts['href'] = edit_product_url( $atts['postID'] ); //For standard posts uncomment next linke //$atts['href'] = get_permalink( $atts['postID'] ); } //Example output $output = '<a class="button" href="' . esc_url( $atts['href'] ) . '">' . $atts['title'] . '</a>'; return $output; } ``` Now you get the functionality without the need of include executable PHP in shortcode attributes. Also, you can use the `render_button` function directly if you need. You can use the shortcode in content editor or wherever shortcodes are parsed, for example: ``` [button title="EDIT" postID="1542"] ``` You can also render buttons by direct call to the function: ``` $button = render_button( array( 'postID' => 4578 ) ); echo $button; ``` And if you need a specific `href`, you can use this shortcode: ``` [button title="EDIT" href="http://www.example.com"] ``` Or with direct function call: ``` $button = render_button( array( 'href' => 'http://www.example.com' ) ); echo $button; //Or shorter echo render_button( array( 'href' => 'http://www.example.com' ) ); ```
181,806
<p>I've made some custom post types, and some user roles. Each role has access to different custom post types.</p> <p>The thing is that edit_others_customposttypecapability, isn't working. I've tried logging in with the admin account, and it can't edit other's published custom post types.</p> <p>I've installed User Role Editor plugin, checked each user's capabilities, and admin should be able to edit all site's posts.</p> <p>Here are the user roles...</p> <pre><code>&lt;?php /* This page loads all user roles that are necesary to the correct administration of the site. */ add_action('init', 'create_metaroles'); function create_metaroles() { // Defino los roles $roles = array(); $roles['Webmaster'] = array( 'role' =&gt; 'webmaster', 'caps' =&gt; array( array('pb_institucional','pb_institucionales'), array('pb_experto','pb_expertos'), array('pb_comite','pb_comites'), array('pb_reunion','pb_reuniones'), array('pb_progproy','pb_progproys'), array('pb_vacante','pb_vacantes'), array('pb_pais','pb_paises'), array('pb_organizacion','pb_organizaciones'), array('pb_evento','pb_eventos'), array('pb_noticia','pb_noticias'), array('pb_publicacion','pb_publicaciones'), array('pb_sector','pb_sectores'), array('pb_producto','pb_productos'), array('pb_conocimiento','pb_conocimientos') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor Institucional'] = array( 'role' =&gt; 'gestor_institucional', 'caps' =&gt; array( array('pb_institucional','pb_institucionales'), array('pb_experto','pb_expertos'), array('pb_comite','pb_comites'), array('pb_reunion','pb_reuniones') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Programas y Proyectos'] = array( 'role' =&gt; 'gestor_progproy', 'caps' =&gt; array( array('pb_progproy','pb_progproys') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de RRHH'] = array( 'role' =&gt; 'gestor_rrhh', 'caps' =&gt; array( array('pb_vacante','pb_vacantes') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Comunicacion Institucional'] = array( 'role' =&gt; 'gestor_comunicacion', 'caps' =&gt; array( array('pb_pais','pb_paises'), array('pb_organizacion','pb_organizaciones'), array('pb_evento','pb_eventos'), array('pb_noticia','pb_noticias'), array('pb_publicacion','pb_publicaciones') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Sectores'] = array( 'role' =&gt; 'gestor_sectores', 'caps' =&gt; array( array('pb_sector','pb_sectores') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Sectores, Programas y Proyectos'] = array( 'role' =&gt; 'gestor_sectores', 'caps' =&gt; array( array('pb_sector','pb_sectores'), array('pb_sector','pb_sectores') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Productos'] = array( 'role' =&gt; 'gestor_productos', 'caps' =&gt; array( array('pb_producto','pb_productos') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); $roles['Gestor de Biblioteca/Conocimiento'] = array( 'role' =&gt; 'gestor_conocimiento', 'caps' =&gt; array( array('pb_conocimiento','pb_conocimientos') ), 'capabilities' =&gt; array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true ) ); foreach( $roles as $name =&gt; $arr ){ add_role($arr['role'], $name, array( 'read' =&gt; true, 'edit_posts' =&gt; false, 'delete_posts' =&gt; false, 'publish_posts' =&gt; false, 'upload_files' =&gt; true )); $rol = get_role( $arr['role'] ); foreach( $arr['caps'] as $cap ){ $rol-&gt;add_cap( 'read' ); $rol-&gt;add_cap( 'read_' . $cap[0] ); $rol-&gt;add_cap( 'read_private_' . $cap[1] ); $rol-&gt;add_cap( 'edit_' . $cap[1] ); $rol-&gt;add_cap( 'edit_others_' . $cap[1] ); $rol-&gt;add_cap( 'edit_published_' . $cap[1] ); $rol-&gt;add_cap( 'publish_' . $cap[1] ); $rol-&gt;add_cap( 'delete_' . $cap[0] ); $rol-&gt;add_cap( 'delete_others_' . $cap[1] ); $rol-&gt;add_cap( 'delete_private_' . $cap[1] ); $rol-&gt;add_cap( 'delete_published_' . $cap[1] ); } $rol = get_role('webmaster'); $rol-&gt;add_cap( 'add_users' ); $rol-&gt;add_cap( 'create_users' ); $rol-&gt;add_cap( 'delete_users' ); $rol-&gt;add_cap( 'edit_users' ); $rol-&gt;add_cap( 'list_users' ); $rol-&gt;add_cap( 'promote_users' ); $rol-&gt;add_cap( 'remove_users' ); $rol-&gt;add_cap( 'manage_categories' ); $rol-&gt;add_cap( 'edit_plugins' ); $rol-&gt;add_cap( 'edit_theme_options' ); $rol-&gt;add_cap( 'manage_links' ); $rol-&gt;add_cap( 'manage_options' ); $rol = get_role( 'administrator' ); foreach( $arr['caps'] as $cap ){ $rol-&gt;add_cap( 'read' ); $rol-&gt;add_cap( 'read_' . $cap[0] ); $rol-&gt;add_cap( 'read_private_' . $cap[1] ); $rol-&gt;add_cap( 'edit_' . $cap[1] ); $rol-&gt;add_cap( 'edit_others_' . $cap[1] ); $rol-&gt;add_cap( 'edit_others_' . $cap[0] ); $rol-&gt;add_cap( 'edit_published_' . $cap[1] ); $rol-&gt;add_cap( 'publish_' . $cap[1] ); $rol-&gt;add_cap( 'delete_' . $cap[0] ); $rol-&gt;add_cap( 'delete_others_' . $cap[1] ); $rol-&gt;add_cap( 'delete_private_' . $cap[1] ); $rol-&gt;add_cap( 'delete_published_' . $cap[1] ); } } } ?&gt; </code></pre> <p>And i'll just copy one custom post type declaration (I'm using 15, but makes no sense copying all of'em)</p> <pre><code>class PB_Noticias { public function __construct(){ $this-&gt;register_post_type(); } public function register_post_type(){ $labels = array( 'name' =&gt; __( 'Noticias', 'text-domain' ), 'singular_name' =&gt; __( 'Noticia', 'text-domain' ), 'add_new' =&gt; _x( 'Agregar Noticia', 'text-domain', 'text-domain' ), 'add_new_item' =&gt; __( 'Agregar Noticia', 'text-domain' ), 'edit_item' =&gt; __( 'Editar Noticia', 'text-domain' ), 'new_item' =&gt; __( 'Nuevo Noticia', 'text-domain' ), 'view_item' =&gt; __( 'Ver Noticia', 'text-domain' ), 'search_items' =&gt; __( 'Buscar Noticias', 'text-domain' ), 'not_found' =&gt; __( 'No se encontraron Noticias', 'text-domain' ), 'not_found_in_trash' =&gt; __( 'No se encontraron Noticias en la papelera', 'text-domain' ), 'parent_item_colon' =&gt; __( 'Noticia Padre:', 'text-domain' ), 'menu_name' =&gt; __( 'Noticias', 'text-domain' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; false, 'description' =&gt; 'Noticias OLADE', 'taxonomies' =&gt; array('category', 'post_tag'), 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; true, 'menu_position' =&gt; 30, 'menu_icon' =&gt; admin_url() . 'images/project.png', 'show_in_nav_menus' =&gt; true, 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'has_archive' =&gt; true, 'query_var' =&gt; 'noticias', 'can_export' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'noticias' ), 'capability_type' =&gt; array('pb_noticia','pb_noticias'), 'supports' =&gt; array( 'title', 'editor' ) ); register_post_type('pb_noticia', $args ); } // Galeria // Foto grande // Cuerpo de la nota } </code></pre> <p>Any ideas why edit_others_cpt isn't working?</p> <p>Thanks in advance!</p>
[ { "answer_id": 181953, "author": "Laurence Stanley", "author_id": 67816, "author_profile": "https://wordpress.stackexchange.com/users/67816", "pm_score": 0, "selected": false, "text": "<p>Is your problem occurring in a multisite setup? If so, here is a solution:</p>\n\n<p><a href=\"http://thereforei.am/2011/03/15/how-to-allow-administrators-to-edit-users-in-a-wordpress-network/\" rel=\"nofollow\">http://thereforei.am/2011/03/15/how-to-allow-administrators-to-edit-users-in-a-wordpress-network/</a></p>\n\n<p>By default in a multisite setup, only Super Administrators can edit users. </p>\n" }, { "answer_id": 182041, "author": "Pablo", "author_id": 60311, "author_profile": "https://wordpress.stackexchange.com/users/60311", "pm_score": 2, "selected": true, "text": "<p>Found it!\nI was missing one custom capability. To the code above, I added this line:</p>\n\n<pre><code>$rol-&gt;add_cap( 'edit_' . $cap[0] );\n</code></pre>\n\n<p>It gives the capability edit_ctpsinglename. (edit_pb_publicacion).\nAnd now it works just fine.\nHope someone find's this useful.</p>\n" } ]
2015/03/20
[ "https://wordpress.stackexchange.com/questions/181806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60311/" ]
I've made some custom post types, and some user roles. Each role has access to different custom post types. The thing is that edit\_others\_customposttypecapability, isn't working. I've tried logging in with the admin account, and it can't edit other's published custom post types. I've installed User Role Editor plugin, checked each user's capabilities, and admin should be able to edit all site's posts. Here are the user roles... ``` <?php /* This page loads all user roles that are necesary to the correct administration of the site. */ add_action('init', 'create_metaroles'); function create_metaroles() { // Defino los roles $roles = array(); $roles['Webmaster'] = array( 'role' => 'webmaster', 'caps' => array( array('pb_institucional','pb_institucionales'), array('pb_experto','pb_expertos'), array('pb_comite','pb_comites'), array('pb_reunion','pb_reuniones'), array('pb_progproy','pb_progproys'), array('pb_vacante','pb_vacantes'), array('pb_pais','pb_paises'), array('pb_organizacion','pb_organizaciones'), array('pb_evento','pb_eventos'), array('pb_noticia','pb_noticias'), array('pb_publicacion','pb_publicaciones'), array('pb_sector','pb_sectores'), array('pb_producto','pb_productos'), array('pb_conocimiento','pb_conocimientos') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor Institucional'] = array( 'role' => 'gestor_institucional', 'caps' => array( array('pb_institucional','pb_institucionales'), array('pb_experto','pb_expertos'), array('pb_comite','pb_comites'), array('pb_reunion','pb_reuniones') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Programas y Proyectos'] = array( 'role' => 'gestor_progproy', 'caps' => array( array('pb_progproy','pb_progproys') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de RRHH'] = array( 'role' => 'gestor_rrhh', 'caps' => array( array('pb_vacante','pb_vacantes') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Comunicacion Institucional'] = array( 'role' => 'gestor_comunicacion', 'caps' => array( array('pb_pais','pb_paises'), array('pb_organizacion','pb_organizaciones'), array('pb_evento','pb_eventos'), array('pb_noticia','pb_noticias'), array('pb_publicacion','pb_publicaciones') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Sectores'] = array( 'role' => 'gestor_sectores', 'caps' => array( array('pb_sector','pb_sectores') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Sectores, Programas y Proyectos'] = array( 'role' => 'gestor_sectores', 'caps' => array( array('pb_sector','pb_sectores'), array('pb_sector','pb_sectores') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Productos'] = array( 'role' => 'gestor_productos', 'caps' => array( array('pb_producto','pb_productos') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); $roles['Gestor de Biblioteca/Conocimiento'] = array( 'role' => 'gestor_conocimiento', 'caps' => array( array('pb_conocimiento','pb_conocimientos') ), 'capabilities' => array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'upload_files' => true ) ); foreach( $roles as $name => $arr ){ add_role($arr['role'], $name, array( 'read' => true, 'edit_posts' => false, 'delete_posts' => false, 'publish_posts' => false, 'upload_files' => true )); $rol = get_role( $arr['role'] ); foreach( $arr['caps'] as $cap ){ $rol->add_cap( 'read' ); $rol->add_cap( 'read_' . $cap[0] ); $rol->add_cap( 'read_private_' . $cap[1] ); $rol->add_cap( 'edit_' . $cap[1] ); $rol->add_cap( 'edit_others_' . $cap[1] ); $rol->add_cap( 'edit_published_' . $cap[1] ); $rol->add_cap( 'publish_' . $cap[1] ); $rol->add_cap( 'delete_' . $cap[0] ); $rol->add_cap( 'delete_others_' . $cap[1] ); $rol->add_cap( 'delete_private_' . $cap[1] ); $rol->add_cap( 'delete_published_' . $cap[1] ); } $rol = get_role('webmaster'); $rol->add_cap( 'add_users' ); $rol->add_cap( 'create_users' ); $rol->add_cap( 'delete_users' ); $rol->add_cap( 'edit_users' ); $rol->add_cap( 'list_users' ); $rol->add_cap( 'promote_users' ); $rol->add_cap( 'remove_users' ); $rol->add_cap( 'manage_categories' ); $rol->add_cap( 'edit_plugins' ); $rol->add_cap( 'edit_theme_options' ); $rol->add_cap( 'manage_links' ); $rol->add_cap( 'manage_options' ); $rol = get_role( 'administrator' ); foreach( $arr['caps'] as $cap ){ $rol->add_cap( 'read' ); $rol->add_cap( 'read_' . $cap[0] ); $rol->add_cap( 'read_private_' . $cap[1] ); $rol->add_cap( 'edit_' . $cap[1] ); $rol->add_cap( 'edit_others_' . $cap[1] ); $rol->add_cap( 'edit_others_' . $cap[0] ); $rol->add_cap( 'edit_published_' . $cap[1] ); $rol->add_cap( 'publish_' . $cap[1] ); $rol->add_cap( 'delete_' . $cap[0] ); $rol->add_cap( 'delete_others_' . $cap[1] ); $rol->add_cap( 'delete_private_' . $cap[1] ); $rol->add_cap( 'delete_published_' . $cap[1] ); } } } ?> ``` And i'll just copy one custom post type declaration (I'm using 15, but makes no sense copying all of'em) ``` class PB_Noticias { public function __construct(){ $this->register_post_type(); } public function register_post_type(){ $labels = array( 'name' => __( 'Noticias', 'text-domain' ), 'singular_name' => __( 'Noticia', 'text-domain' ), 'add_new' => _x( 'Agregar Noticia', 'text-domain', 'text-domain' ), 'add_new_item' => __( 'Agregar Noticia', 'text-domain' ), 'edit_item' => __( 'Editar Noticia', 'text-domain' ), 'new_item' => __( 'Nuevo Noticia', 'text-domain' ), 'view_item' => __( 'Ver Noticia', 'text-domain' ), 'search_items' => __( 'Buscar Noticias', 'text-domain' ), 'not_found' => __( 'No se encontraron Noticias', 'text-domain' ), 'not_found_in_trash' => __( 'No se encontraron Noticias en la papelera', 'text-domain' ), 'parent_item_colon' => __( 'Noticia Padre:', 'text-domain' ), 'menu_name' => __( 'Noticias', 'text-domain' ), ); $args = array( 'labels' => $labels, 'hierarchical' => false, 'description' => 'Noticias OLADE', 'taxonomies' => array('category', 'post_tag'), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => true, 'menu_position' => 30, 'menu_icon' => admin_url() . 'images/project.png', 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => true, 'query_var' => 'noticias', 'can_export' => true, 'rewrite' => array( 'slug' => 'noticias' ), 'capability_type' => array('pb_noticia','pb_noticias'), 'supports' => array( 'title', 'editor' ) ); register_post_type('pb_noticia', $args ); } // Galeria // Foto grande // Cuerpo de la nota } ``` Any ideas why edit\_others\_cpt isn't working? Thanks in advance!
Found it! I was missing one custom capability. To the code above, I added this line: ``` $rol->add_cap( 'edit_' . $cap[0] ); ``` It gives the capability edit\_ctpsinglename. (edit\_pb\_publicacion). And now it works just fine. Hope someone find's this useful.
181,813
<p>I have this <a href="https://picasaweb.google.com/data/feed/base/user/110981376645512804522/albumid/5638371435917293985?alt=rss&amp;kind=photo&amp;hl=en_US" rel="noreferrer">feed</a> from <a href="https://picasaweb.google.com/110981376645512804522/DropBox" rel="noreferrer">picasa</a> (correct but arbitrary, desired order).</p> <p>The result is <a href="http://jig.openelements.com/?page_id=6" rel="noreferrer">messed up</a></p> <p>Also, with <a href="http://jig.openelements.com/?p=12" rel="noreferrer">this feed</a>, for example.</p> <p>It's fine in regular, sorted by date feeds, but not these. In the object I get from Simplepie it has a messed up order. I don't do anything fancy just loop over the results and display them in the found order using my commercial gallery plugin.</p> <p><code>$rss_items = $rss-&gt;get_items(0, $rss-&gt;get_item_quantity($limit));</code></p> <p>I have tried this (hooked into <code>wp_feed_options</code>) but it doesn't change anything: <code>$rss-&gt;enable_order_by_date(false);</code></p> <p>Also, when I do <code>var_dump($rss_items);</code> I get an array that is represented by <strong>546503</strong> lines of text. I don't believe that's normal, maybe it also hogs the memory, but I can't even look through that data manually to see if the order is inherently bad or just gets mixed up somewhere.</p> <p>Also I can't tell if it's Simplepie's or WordPress' wrapper's fault.</p>
[ { "answer_id": 181954, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>I think you simply have to replace:</p>\n\n<pre><code>$feed-&gt;enable_order_by_date(false);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>$rss-&gt;enable_order_by_date(false);\n</code></pre>\n\n<p>to disable the descending date ordering. </p>\n\n<p>In the case of a feed error, the <code>fetch_feed()</code> function returns an instance of the <code>\\WP_Error</code> class. Otherwise the output is an instance of the <code>\\SimplePie</code> class and this class contains the <code>enable_order_by_date</code>() public method. </p>\n\n<p>So you should use it like this:</p>\n\n<pre><code>// Fetch the feed:\n$rss = fetch_feed( $feed_url );\n\n// Make sure we don't have and WP_Error instance:\nif ( ! is_wp_error( $rss ) ) \n{\n // Disable the date ordering:\n $rss-&gt;enable_order_by_date( false );\n\n // ... etc ...\n}\n</code></pre>\n\n<p>where we (implicitly) make sure we have an instance of the <code>\\SimplePie</code> class.</p>\n" }, { "answer_id": 182043, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 1, "selected": false, "text": "<p>I have no idea what's happening with this feed but with this code</p>\n\n<pre><code>include_once( ABSPATH . WPINC . '/feed.php' );\n$rss = fetch_feed( 'https://picasaweb.google.com/data/feed/base/user/110981376645512804522/albumid/5638371435917293985' );\n\nforeach ($rss-&gt;get_items() as $item) {\n if ($enclosure = $item-&gt;get_enclosure()) {\n echo '&lt;img src=\"'.$enclosure-&gt;get_link().'\"&gt;';\n }\n}\n</code></pre>\n\n<p>I get the same order that I get when opening that feed with my browser. If I leave the <code>?alt=rss&amp;kind=photo&amp;hl=en_US</code> in the url, it gives the problems you described and the items are in the wrong order.</p>\n\n<p>No idea why, but maybe you can work forward from here.</p>\n\n<p>Edit: So in short, maybe the problem was the url of the feed?</p>\n\n<hr>\n\n<p>Here's a hacky way to get the right feed:</p>\n\n<pre><code>$url = 'https://picasaweb.google.com/data/feed/base/user/110981376645512804522/albumid/5638371435917293985?alt=json';\n// or https://picasaweb.google.com/data/feed/base/user/117541338986679044195/albumid/6129832223894216561?alt=json&amp;kind=photo&amp;hl=en_US&amp;imgmax=800\n$json = json_decode(file_get_contents($url));\n$feed = (array)$json-&gt;feed;\nforeach ($feed['entry'] as $entry) {\n $i = 0;\n foreach ($entry-&gt;content as $image) {\n if($i % 2 != 0) { echo '&lt;img src=\"'.$image.'\" /&gt;'; }\n $i++;\n }\n}\n</code></pre>\n\n<p>So I switched to json feed and parse it kinda uglily. But it gets the job done :D\nthe <code>$entry-&gt;content</code> gives both image type and source which is why there's that extra <code>if($i % 2 != 0)</code> to get only every other node.</p>\n\n<p>Still, I have no clue why the RSS does that, but here's alternative way anyway.</p>\n\n<p><strong>edit:</strong> to add again you said you really couldn't parse the rss manually so I'll just say that you can add <code>&amp;prettyprint=true</code> to the url to get a prettier feed if you'd like to read it.</p>\n\n<hr>\n\n<p><strong>edit number thousand:</strong> Alternative way!</p>\n\n<pre><code>include_once( ABSPATH . WPINC . '/feed.php' );\n$rss = fetch_feed( 'https://picasaweb.google.com/data/feed/base/user/117541338986679044195/albumid/6129832223894216561?alt=rss&amp;fields=item(media:group(media:content(@url)))' );\n\nforeach ($rss-&gt;get_items() as $item) {\n if ($enclosure = $item-&gt;get_enclosure()) {\n //echo $enclosure-&gt;get_link().'&lt;br&gt;';\n echo '&lt;img src=\"'.$enclosure-&gt;get_link().'\"&gt;';\n }\n}\n</code></pre>\n\n<p>by adding <code>?alt=rss&amp;fields=item(media:group(media:content(@url)))</code> I got the two feeds you have provided thus far to work correctly! I got all the funny information to try out from <a href=\"https://developers.google.com/picasa-web/docs/2.0/reference#Parameters\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 182551, "author": "Firsh - justifiedgrid.com", "author_id": 28069, "author_profile": "https://wordpress.stackexchange.com/users/28069", "pm_score": 3, "selected": true, "text": "<p>At the end of <code>class-simplepie.php</code> there is this line:</p>\n\n<pre><code>usort($items, array(get_class($urls[0]), 'sort_items'));\n</code></pre>\n\n<p>Which force-sorts feed elements, in case of <strong>multifeed</strong>.</p>\n\n<p>The <code>$feed-&gt;enable_order_by_date(false);</code> is indeed very important and the key to things, BUT it gets disregarded (what I was experiencing) if I use <strong>multifeed</strong>. Source: in <code>get_items()</code> of <code>class-simplepie.php</code> there is this:</p>\n\n<pre><code>// If we want to order it by date, check if all items have a date, and then sort it\nif ($this-&gt;order_by_date &amp;&amp; empty($this-&gt;multifeed_objects))\n</code></pre>\n\n<p>I used <strong>multifeed</strong> accidentally for single URLs too. Remember it's a plugin where I didn't know if it was going to be single or multiple URLs so it seemed convenient to always pass an array to <code>fetch_feed()</code>.</p>\n\n<p>So it now looks something like this:</p>\n\n<pre><code>$rss_url = explode(',',$rss_url); // Accept multiple URLs\n\nif(count($rss_url) == 1){ // New code\n $rss_url = $rss_url[0];\n}\n\nadd_action('wp_feed_options', array($this, 'jig_add_force_rss'), 10,2);\n$rss = fetch_feed($rss_url);\nremove_action('wp_feed_options', array($this, 'jig_add_force_rss'), 10);\n</code></pre>\n\n<p>And the action is:</p>\n\n<pre><code>function jig_add_force_rss($feed,$url){\n $feed-&gt;force_feed(true);\n $feed-&gt;enable_order_by_date(false);\n}\n</code></pre>\n\n<p>Your solutions were working becuase you passed the RSS url as a string and not as a one-element array. I compared them with how I was using the methods and this was the difference. Now it works with and without query string in the Picasa feed URL, always same as how it looks in the browser.</p>\n" }, { "answer_id": 270285, "author": "Marc", "author_id": 71657, "author_profile": "https://wordpress.stackexchange.com/users/71657", "pm_score": 2, "selected": false, "text": "<p>The simplest fix for someone who is experiencing this issue is this:</p>\n\n<pre><code>function my_add_force_rss($feed,$url){\n $feed-&gt;force_feed(true);\n $feed-&gt;enable_order_by_date(false);\n}\nadd_action('wp_feed_options', 'my_add_force_rss', 10,2);\n</code></pre>\n\n<p>Placing this in your <code>functions.php</code> will force any feed to be displayed in the order that it is received.</p>\n" } ]
2015/03/20
[ "https://wordpress.stackexchange.com/questions/181813", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28069/" ]
I have this [feed](https://picasaweb.google.com/data/feed/base/user/110981376645512804522/albumid/5638371435917293985?alt=rss&kind=photo&hl=en_US) from [picasa](https://picasaweb.google.com/110981376645512804522/DropBox) (correct but arbitrary, desired order). The result is [messed up](http://jig.openelements.com/?page_id=6) Also, with [this feed](http://jig.openelements.com/?p=12), for example. It's fine in regular, sorted by date feeds, but not these. In the object I get from Simplepie it has a messed up order. I don't do anything fancy just loop over the results and display them in the found order using my commercial gallery plugin. `$rss_items = $rss->get_items(0, $rss->get_item_quantity($limit));` I have tried this (hooked into `wp_feed_options`) but it doesn't change anything: `$rss->enable_order_by_date(false);` Also, when I do `var_dump($rss_items);` I get an array that is represented by **546503** lines of text. I don't believe that's normal, maybe it also hogs the memory, but I can't even look through that data manually to see if the order is inherently bad or just gets mixed up somewhere. Also I can't tell if it's Simplepie's or WordPress' wrapper's fault.
At the end of `class-simplepie.php` there is this line: ``` usort($items, array(get_class($urls[0]), 'sort_items')); ``` Which force-sorts feed elements, in case of **multifeed**. The `$feed->enable_order_by_date(false);` is indeed very important and the key to things, BUT it gets disregarded (what I was experiencing) if I use **multifeed**. Source: in `get_items()` of `class-simplepie.php` there is this: ``` // If we want to order it by date, check if all items have a date, and then sort it if ($this->order_by_date && empty($this->multifeed_objects)) ``` I used **multifeed** accidentally for single URLs too. Remember it's a plugin where I didn't know if it was going to be single or multiple URLs so it seemed convenient to always pass an array to `fetch_feed()`. So it now looks something like this: ``` $rss_url = explode(',',$rss_url); // Accept multiple URLs if(count($rss_url) == 1){ // New code $rss_url = $rss_url[0]; } add_action('wp_feed_options', array($this, 'jig_add_force_rss'), 10,2); $rss = fetch_feed($rss_url); remove_action('wp_feed_options', array($this, 'jig_add_force_rss'), 10); ``` And the action is: ``` function jig_add_force_rss($feed,$url){ $feed->force_feed(true); $feed->enable_order_by_date(false); } ``` Your solutions were working becuase you passed the RSS url as a string and not as a one-element array. I compared them with how I was using the methods and this was the difference. Now it works with and without query string in the Picasa feed URL, always same as how it looks in the browser.
181,841
<p>Unlike most of the spammer/spambot plugins out there, which stop registrations from a known list of spam IPs and email domains, I need to stop malicious users who may try and register more than one account from the same ip address. Their intentions may be to either harass people in the comments once they've been banned on other accounts, or they may try and play games with one of my submission forms and submit duplicate results to attempt to ruin the integrity of the output. </p> <p>Is there a way that I can limit an ip address from registering accounts per a given time period? Since IP addresses change, I'd like to still allow some innocent who may end up with a previously blocked IP, to register.</p>
[ { "answer_id": 181848, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": true, "text": "<p>Despite that this approach may be flawed by the fact that it can be by-passed using proxies, here is a simplistic (yet untested) approach, which <strong>you would need to improve upon</strong> but would give you the foundation for achieving your desired goal.</p>\n\n<p>The process as I see it:</p>\n\n<ul>\n<li>filter user registerations on the <code>pre_user_login</code> or <code>pre_user_nicename</code> hooks</li>\n<li>check database to see if IP exists in a time-limited blacklist</li>\n<li>if IP exists within range, reject registration with custom error message</li>\n<li>if IP does not exist within range, add the IP to the time-limited blacklist</li>\n<li>rinse and repeat for each registration attempt</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>function filter_user_registration_ip($user_nicename) {\n\n $ip = $_SERVER['REMOTE_ADDR']; //get current IP address\n $time = time(); //get current timestamp\n $blacklist = get_option('user_ip_blacklist') ?: array(); //get IP blacklist\n\n /*\n * If IP is an array key found on the resulting $blacklist array\n * run a differential of the \n * \n */\n if ( array_key_exists($ip, $blacklist) ) {\n\n /*\n * Find the difference between the current timestamp and the timestamp at which\n * the IP was stored in the database converted into hours.\n */\n $diff_in_hours = ($time - $blacklist[$ip]) / 60 / 60;\n\n\n if ( $diff_in_hours &lt; 24 ) {\n\n /*\n * If the difference is less than 24 hours, block the registration attempt\n * and do not reset or overwrite the timestamp already stored against the\n * current IP address.\n */\n wp_die('Your IP is temporarily blocked from registering an account');\n }\n\n } \n\n /*\n * If the IP address does not exist, add it to the array of blacklisted IPs with\n * the current timestamp (now).\n *\n * Or if the IP address exists but is greater than 24 hours in difference between\n * the original stored timestamp and the current timestamp, add it to the array\n * of blacklisted IPs.\n */\n $blacklist[$ip] = $time;\n update_option('user_ip_blacklist', $blacklist); \n\n return $user_nicename;\n\n}\n\nadd_filter('pre_user_nicename', 'filter_user_registration_ip', 10, 1);\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>The above code is <strong>untested</strong> and <strong>may contain errors</strong>.</li>\n<li>The approach to retrieving the current user IP is not fool proof.</li>\n<li>The array of IPs will grow exponentially overtime, you will need to prune the array periodically.</li>\n</ul>\n" }, { "answer_id": 181862, "author": "wordpress", "author_id": 13514, "author_profile": "https://wordpress.stackexchange.com/users/13514", "pm_score": 0, "selected": false, "text": "<p>A better solution would be not to ban their IP from within Wordpress, but if you have root access to WHM then you can ban their IP from your server altogether. This is the real solution to the problem.</p>\n\n<p>Also, usually IP addresses do not change. However, a person may go to another internet connection, a proxy server, or some other manner to use an alternate IP. However, it will still be a pain for them because once you ban their home IP, the only real solution for them is to get their ISP to change their IP, of which many ISPs will be reluctant to do or will flat out deny the request.</p>\n\n<p>If you do not have access to WHM or the root of your server, then you can still ban their IP by adding it to the .htaccess file like so:</p>\n\n<pre><code>order allow,deny\ndeny from 123.45.67.89\nallow from all\n</code></pre>\n" } ]
2015/03/21
[ "https://wordpress.stackexchange.com/questions/181841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65738/" ]
Unlike most of the spammer/spambot plugins out there, which stop registrations from a known list of spam IPs and email domains, I need to stop malicious users who may try and register more than one account from the same ip address. Their intentions may be to either harass people in the comments once they've been banned on other accounts, or they may try and play games with one of my submission forms and submit duplicate results to attempt to ruin the integrity of the output. Is there a way that I can limit an ip address from registering accounts per a given time period? Since IP addresses change, I'd like to still allow some innocent who may end up with a previously blocked IP, to register.
Despite that this approach may be flawed by the fact that it can be by-passed using proxies, here is a simplistic (yet untested) approach, which **you would need to improve upon** but would give you the foundation for achieving your desired goal. The process as I see it: * filter user registerations on the `pre_user_login` or `pre_user_nicename` hooks * check database to see if IP exists in a time-limited blacklist * if IP exists within range, reject registration with custom error message * if IP does not exist within range, add the IP to the time-limited blacklist * rinse and repeat for each registration attempt Example: ``` function filter_user_registration_ip($user_nicename) { $ip = $_SERVER['REMOTE_ADDR']; //get current IP address $time = time(); //get current timestamp $blacklist = get_option('user_ip_blacklist') ?: array(); //get IP blacklist /* * If IP is an array key found on the resulting $blacklist array * run a differential of the * */ if ( array_key_exists($ip, $blacklist) ) { /* * Find the difference between the current timestamp and the timestamp at which * the IP was stored in the database converted into hours. */ $diff_in_hours = ($time - $blacklist[$ip]) / 60 / 60; if ( $diff_in_hours < 24 ) { /* * If the difference is less than 24 hours, block the registration attempt * and do not reset or overwrite the timestamp already stored against the * current IP address. */ wp_die('Your IP is temporarily blocked from registering an account'); } } /* * If the IP address does not exist, add it to the array of blacklisted IPs with * the current timestamp (now). * * Or if the IP address exists but is greater than 24 hours in difference between * the original stored timestamp and the current timestamp, add it to the array * of blacklisted IPs. */ $blacklist[$ip] = $time; update_option('user_ip_blacklist', $blacklist); return $user_nicename; } add_filter('pre_user_nicename', 'filter_user_registration_ip', 10, 1); ``` Notes: * The above code is **untested** and **may contain errors**. * The approach to retrieving the current user IP is not fool proof. * The array of IPs will grow exponentially overtime, you will need to prune the array periodically.
181,868
<p>I got a custom field and I want to toggle a specific custom field. So for example I have 2 custom fields named: Subject and Score. When viewing a single post the custom field 'Score' data is hidden until a user clicks on the button to see the data. How can I do this toggle effect?</p>
[ { "answer_id": 181871, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 3, "selected": true, "text": "<p>You could do this with jquery.</p>\n\n<p>I have a similar code on use which you could probably easily edit to your needs:</p>\n\n<p>load the admin js (I load css too but you can remove that)</p>\n\n<pre><code>function wpse181868_admin_css_js() {\n wp_register_style( 'bones_admin_css', get_template_directory_uri() . '/library/css/admin.css', false );\n wp_enqueue_style( 'bones_admin_css' );\n\n //adding scripts file in the footer\n wp_enqueue_script( 'admin_js', get_stylesheet_directory_uri() . '/library/js/admin.js', array( 'jquery' ), '', true );\n}\nadd_action( 'admin_enqueue_scripts', 'wpse181868_admin_css_js' );\n</code></pre>\n\n<p>and then in the js check and show stuff as needed (I show different boxes for different post formats)</p>\n\n<pre><code>jQuery(document).ready(function($) {\n function checkFormat() {\n $('#attachments-gallery_attachments').hide();\n $('#featured_video').hide();\n if($('input[name=post_format]:checked', '#formatdiv').val() == \"gallery\") { $('#attachments-gallery_attachments').show(); }\n if($('input[name=post_format]:checked', '#formatdiv').val() == \"video\") { $('#featured_video').show(); }\n }\n\n $('#formatdiv input[type=\"radio\"]').live('click', checkFormat);\n checkFormat();\n});\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT:</strong>\nIn you theme's functions.php add this code</p>\n\n<pre><code>function wpse181868_admin_js() { ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(document).ready(function($) {\n var $input = $('&lt;input type=\"button\" id=\"s_s\" value=\"Show score\" /&gt;');\n $('input[name^=\"meta[\"]').each(function(){\n var val = $(this).val();\n if(val == \"score\") {\n var valueTD = $(this).parent().siblings();\n $(valueTD.find('textarea')).hide();\n $input.appendTo($(valueTD));\n $('#s_s').click(function(){ $(valueTD.find('textarea')).show(); $input.remove(); });\n }\n });\n });\n &lt;/script&gt;\n&lt;?php }\nadd_action('admin_footer', 'wpse181868_admin_js');\n</code></pre>\n" }, { "answer_id": 258852, "author": "user114724", "author_id": 114724, "author_profile": "https://wordpress.stackexchange.com/users/114724", "pm_score": 0, "selected": false, "text": "<p>I'm not sure you still have this issue, but recently I have the same struggle...</p>\n\n<p>And this is what I found. </p>\n\n<p>Toggle with CSS only. I try showing you in the most simple way You could do this with JQuery, though.</p>\n\n<p>HTML(single.php or page.php, or something)---------------------</p>\n\n<pre><code>&lt;?php if ( $post-&gt;Scores ): ?&gt;\n &lt;div class=\"menu\"&gt;\n &lt;label for=\"A\"&gt;Scores&lt;/label&gt;\n &lt;input type=\"checkbox\" id=\"A\" class=\"B\" /&gt;\n &lt;div class=\"C\"&gt;\n &lt;?php echo nl2br( $post-&gt;Scores ); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>CSS--------------------</p>\n\n<pre><code>label {\n color: #3f3f3f;\n padding: 0px;\n display: block;\n margin: 0;\n border: 1px solid #fff;\n}\n\ninput[type=\"checkbox\"].B{\n display: none;\n}\n\n.menu .C {\n -webkit-transition: all 0.5s;\n -moz-transition: all 0.5s;\n -ms-transition: all 0.5s;\n -o-transition: all 0.5s;\n transition: all 0.5s;\n margin: 0;\n padding: 5px;\n}\n\ninput[type=\"checkbox\"].B + .C{\n height: 0;\n overflow: hidden;\n}\n\ninput[type=\"checkbox\"].B:checked + .C{\n height: 200px;\n}\n</code></pre>\n\n<hr>\n\n<p>Please customize CSS such as the height, margin, padding, color, etc as you like. </p>\n\n<p>Hope this helps you and works for your site.</p>\n" } ]
2015/03/21
[ "https://wordpress.stackexchange.com/questions/181868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17971/" ]
I got a custom field and I want to toggle a specific custom field. So for example I have 2 custom fields named: Subject and Score. When viewing a single post the custom field 'Score' data is hidden until a user clicks on the button to see the data. How can I do this toggle effect?
You could do this with jquery. I have a similar code on use which you could probably easily edit to your needs: load the admin js (I load css too but you can remove that) ``` function wpse181868_admin_css_js() { wp_register_style( 'bones_admin_css', get_template_directory_uri() . '/library/css/admin.css', false ); wp_enqueue_style( 'bones_admin_css' ); //adding scripts file in the footer wp_enqueue_script( 'admin_js', get_stylesheet_directory_uri() . '/library/js/admin.js', array( 'jquery' ), '', true ); } add_action( 'admin_enqueue_scripts', 'wpse181868_admin_css_js' ); ``` and then in the js check and show stuff as needed (I show different boxes for different post formats) ``` jQuery(document).ready(function($) { function checkFormat() { $('#attachments-gallery_attachments').hide(); $('#featured_video').hide(); if($('input[name=post_format]:checked', '#formatdiv').val() == "gallery") { $('#attachments-gallery_attachments').show(); } if($('input[name=post_format]:checked', '#formatdiv').val() == "video") { $('#featured_video').show(); } } $('#formatdiv input[type="radio"]').live('click', checkFormat); checkFormat(); }); ``` --- **EDIT:** In you theme's functions.php add this code ``` function wpse181868_admin_js() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { var $input = $('<input type="button" id="s_s" value="Show score" />'); $('input[name^="meta["]').each(function(){ var val = $(this).val(); if(val == "score") { var valueTD = $(this).parent().siblings(); $(valueTD.find('textarea')).hide(); $input.appendTo($(valueTD)); $('#s_s').click(function(){ $(valueTD.find('textarea')).show(); $input.remove(); }); } }); }); </script> <?php } add_action('admin_footer', 'wpse181868_admin_js'); ```
181,877
<p>I would like to know if there is a simple way (custom code or plugin) to create thumbnail sizes <strong>only for</strong> images that I intend to use as <strong>featured images</strong> (index.php, archive.php, etc.) , but not for the images used in the posts (single.php). My main goal is reduce server space usage by not creating thumbnails that my theme will never use. </p> <p>My thumbnails would actually only have two sizes, 720px wide and 328px wide, and the 720px wide featured images (homepage only) would also have a 328px wide one (for archive.php and sidebar.php) </p> <p>Currently, the only programmatic way I know is to <a href="https://codex.wordpress.org/Post_Thumbnails" rel="noreferrer">generate thumbnails for every image upload</a>, which is undesirable, since most of my uploads will be post images and I would have to deleted a lot of images from the server manually. </p> <p>I would prefer custom code over plugins, but a plugin would be acceptable. I know there are some image resizing plugins out there, but they haven't been update in a longtime (TimThumb, <a href="http://wordpress.org/plugins/dynamic-image-resizer/" rel="noreferrer">Dynamic Image Resizer</a>). </p> <p>I have also found a <a href="https://wordpress.stackexchange.com/questions/124355/only-create-image-size-when-used-in-featured-image">similar question</a> here on Wordpress SE, but the accepted answer doesn't really solve my problem. </p> <hr> <p>EDIT: I need to delete or prevent thumbnails for images inside the post, not for featured images, i.e.:</p> <p>(1) <strong>Featured image</strong>: additional thumbnails auto-generated by WP are OK.</p> <p>(2) <strong>Images used inside the posts</strong>: Upload the original image and do not generate any additional sizes. I will crop, resize and optimize the image before uploading it and one size will fit my needs.</p>
[ { "answer_id": 181886, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>You can see this <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow\">link</a>. there has some example like</p>\n\n<pre><code>add_action( 'after_setup_theme', 'baw_theme_setup' );\nfunction baw_theme_setup() {\n add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height)\n add_image_size( 'homepage-thumb', 220, 180, true ); // (cropped)\n}\n</code></pre>\n" }, { "answer_id": 184751, "author": "Trang", "author_id": 70868, "author_profile": "https://wordpress.stackexchange.com/users/70868", "pm_score": 0, "selected": false, "text": "<p>1.Go to Dashboard > Settings > Media<br>\n2.Uncheck Crop thumbnail to exact dimensions (normally thumbnails are proportional)<br>\n3.Enter 0 for all input (0 for all size)<br>\n4.Add these to your functions.php</p>\n\n<pre><code>// Enable support for Post Thumbnails, and declare sizes.\nadd_theme_support( 'post-thumbnails' );\nset_post_thumbnail_size( 400, 400, array(\"center\",\"center\") );\nfunction fw_add_image_insert_override($sizes){\n // unset( $sizes['thumbnail']);\n unset( $sizes['small']);\n unset( $sizes['medium']);\n unset( $sizes['large']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'fw_add_image_insert_override' );\n</code></pre>\n\n<p>5. Make sure that there is no code line in your functions.php start with <code>add_imge_size</code> \n<strong>Note:</strong>: I suppose you use size of 400x400 for your thumbnail\nNow when you upload a photo, it will create only 2 versions instead of at least 4 versions photo as previous.</p>\n" }, { "answer_id": 187800, "author": "timholz", "author_id": 71669, "author_profile": "https://wordpress.stackexchange.com/users/71669", "pm_score": 0, "selected": false, "text": "<p>Hi – I had a similar problem. WooCommerce uses catalogue images for catalogue and related product images. That is not ideal, for you loose either image quality or speed. So I tried to add a fourth image category for my related products. Howdy McGee has solved the problem. Please take a look at Howdy McGees answer:</p>\n\n<blockquote>\n <p>Modify Related Product Image Sizes: <a href=\"https://wordpress.stackexchange.com/questions/186366/custom-woocommerce-image-size/186370?noredirect=1#comment273470_186370\">read his code</a>!</p>\n</blockquote>\n\n<p>It has worked out magnificently for my needs. For your problem the same logic could be applied. Hope this helps.</p>\n\n<p>Regards, </p>\n\n<p>Theo</p>\n\n<p>**Addition: **</p>\n\n<p>I found a solution that works.</p>\n\n<p><strong>Step 1:</strong> Assign a new thumbnail size in your functions.php.\nCheck reference: <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow noreferrer\">wp codex</a>!</p>\n\n<pre><code>/*add your custom size*/\nadd_action( 'after_setup_theme', 'your_theme_setup' );\nfunction your_theme_setup() {\nadd_image_size( 'your-thumb', 123, 123, true );//insert your values\n}\n</code></pre>\n\n<p>Note: 'your-thumb', you will use this variable name later</p>\n\n<p><strong>Step 2:</strong> Then add the following code wherever you want to display your featured products:</p>\n\n<pre><code> &lt;h1&gt;featured products&lt;/h1&gt; \n &lt;div class=\"woocommerce\"&gt;\n &lt;ul class= \"products\"&gt;\n\n &lt;?php\n $args = array( 'post_type' =&gt; 'product', 'meta_key' =&gt; '_featured','posts_per_page' =&gt; 4,'columns' =&gt; '4', 'meta_value' =&gt; 'yes' );\n $loop = new WP_Query( $args );\n\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt;\n\n &lt;li class=\"product post-&lt;?php echo get_the_ID(); ?&gt;\"&gt; \n &lt;a href=\"&lt;?php echo get_permalink( $loop-&gt;post-&gt;ID ) ?&gt;\" title=\"&lt;?php echo esc_attr($loop-&gt;post-&gt;post_title ? $loop-&gt;post-&gt;post_title : $loop-&gt;post-&gt;ID); ?&gt;\"&gt;\n\n &lt;?php woocommerce_show_product_sale_flash( $post, $product ); ?&gt;\n &lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;&lt;span class=\"price\"&gt;&lt;?php echo $product-&gt;get_price_html(); ?&gt;&lt;/span&gt;\n\n &lt;/li&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php wp_reset_query(); ?&gt; \n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Reference and info: \n(<a href=\"https://haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/\" rel=\"nofollow noreferrer\">www.haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/</a>)</p>\n\n<p>I placed it in the index.php (my homepage) of wootheme mystyle.\nDon't forget to use 'your-thumb' on line:</p>\n\n<pre><code>&lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n</code></pre>\n\n<p><strong>Step 3:</strong> Regenerate thumbnails, use the plugin <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n\n<p><strong>Step 4:</strong> Refresh the browser and inspect the DOM and compare the values </p>\n\n<p>According to your theme you may change the mark up and class names.\nI tested the above method and it works well.</p>\n\n<p>The only thing I couldn't do so far, is to add the-add-to-cart-button, because I do not know how to write a variable into the add to cart button shortcode.\nThis is the code:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[add_to_cart id=\"variable number?\"]'); ?&gt;\n</code></pre>\n\n<p>I hope this helps.</p>\n\n<p>There is certainly a more elegant way to do this. For instance with a function in the functions.php</p>\n\n<p>Regards,</p>\n\n<p>Theo</p>\n" }, { "answer_id": 190756, "author": "Mathew Tinsley", "author_id": 69793, "author_profile": "https://wordpress.stackexchange.com/users/69793", "pm_score": 2, "selected": false, "text": "<p>This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size.</p>\n\n<pre><code>function lazy_image_size($image_id, $width, $height, $crop) {\n // Temporarily create an image size\n $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop);\n add_image_size($size_id, $width, $height, $crop);\n\n // Get the attachment data\n $meta = wp_get_attachment_metadata($image_id);\n\n // If the size does not exist\n if(!isset($meta['sizes'][$size_id])) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n\n $file = get_attached_file($image_id);\n $new_meta = wp_generate_attachment_metadata($image_id, $file);\n\n // Merge the sizes so we don't lose already generated sizes\n $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']);\n\n // Update the meta data\n wp_update_attachment_metadata($image_id, $new_meta);\n }\n\n // Fetch the sized image\n $sized = wp_get_attachment_image_src($image_id, $size_id);\n\n // Remove the image size so new images won't be created in this size automatically\n remove_image_size($size_id);\n return $sized;\n}\n</code></pre>\n\n<p>It's \"lazy\" because images are not generated until they are needed.</p>\n\n<p>In your use-case, you would call that <code>lazy_image_size</code> with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image.</p>\n\n<p>Gist: <a href=\"https://gist.github.com/mtinsley/be503d90724be73cdda4\" rel=\"nofollow\">https://gist.github.com/mtinsley/be503d90724be73cdda4</a></p>\n" } ]
2015/03/21
[ "https://wordpress.stackexchange.com/questions/181877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69406/" ]
I would like to know if there is a simple way (custom code or plugin) to create thumbnail sizes **only for** images that I intend to use as **featured images** (index.php, archive.php, etc.) , but not for the images used in the posts (single.php). My main goal is reduce server space usage by not creating thumbnails that my theme will never use. My thumbnails would actually only have two sizes, 720px wide and 328px wide, and the 720px wide featured images (homepage only) would also have a 328px wide one (for archive.php and sidebar.php) Currently, the only programmatic way I know is to [generate thumbnails for every image upload](https://codex.wordpress.org/Post_Thumbnails), which is undesirable, since most of my uploads will be post images and I would have to deleted a lot of images from the server manually. I would prefer custom code over plugins, but a plugin would be acceptable. I know there are some image resizing plugins out there, but they haven't been update in a longtime (TimThumb, [Dynamic Image Resizer](http://wordpress.org/plugins/dynamic-image-resizer/)). I have also found a [similar question](https://wordpress.stackexchange.com/questions/124355/only-create-image-size-when-used-in-featured-image) here on Wordpress SE, but the accepted answer doesn't really solve my problem. --- EDIT: I need to delete or prevent thumbnails for images inside the post, not for featured images, i.e.: (1) **Featured image**: additional thumbnails auto-generated by WP are OK. (2) **Images used inside the posts**: Upload the original image and do not generate any additional sizes. I will crop, resize and optimize the image before uploading it and one size will fit my needs.
This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size. ``` function lazy_image_size($image_id, $width, $height, $crop) { // Temporarily create an image size $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop); add_image_size($size_id, $width, $height, $crop); // Get the attachment data $meta = wp_get_attachment_metadata($image_id); // If the size does not exist if(!isset($meta['sizes'][$size_id])) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $file = get_attached_file($image_id); $new_meta = wp_generate_attachment_metadata($image_id, $file); // Merge the sizes so we don't lose already generated sizes $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']); // Update the meta data wp_update_attachment_metadata($image_id, $new_meta); } // Fetch the sized image $sized = wp_get_attachment_image_src($image_id, $size_id); // Remove the image size so new images won't be created in this size automatically remove_image_size($size_id); return $sized; } ``` It's "lazy" because images are not generated until they are needed. In your use-case, you would call that `lazy_image_size` with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image. Gist: <https://gist.github.com/mtinsley/be503d90724be73cdda4>
181,900
<p>I have a custom post type for a group of people (employees). At first, I needed to display 7 random employees. That was easy</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'employees', 'orderby' =&gt; 'rand', 'posts_per_page' =&gt; 7, ); $query = new WP_Query($args); while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); //do stuff &lt;?php endif; } wp_reset_postdata(); ?&gt; </code></pre> <p>But now I've been asked to make sure at least one of the seven is always a woman. The man to woman ratio at the company is 4 to 1.</p> <p>I've set a checkbox that I can test for:</p> <pre><code>&lt;?php if( in_array( 'yes', get_field('is_female') ) ){ // this is a female } </code></pre> <p>I need help putting it all together. I assume I need to keep track if any of the posts are displayed are women. Once I get to the 7th position if a woman isn't listed, I need to keep iterating until I find one.</p> <p>Any suggestions?</p>
[ { "answer_id": 181886, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>You can see this <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow\">link</a>. there has some example like</p>\n\n<pre><code>add_action( 'after_setup_theme', 'baw_theme_setup' );\nfunction baw_theme_setup() {\n add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height)\n add_image_size( 'homepage-thumb', 220, 180, true ); // (cropped)\n}\n</code></pre>\n" }, { "answer_id": 184751, "author": "Trang", "author_id": 70868, "author_profile": "https://wordpress.stackexchange.com/users/70868", "pm_score": 0, "selected": false, "text": "<p>1.Go to Dashboard > Settings > Media<br>\n2.Uncheck Crop thumbnail to exact dimensions (normally thumbnails are proportional)<br>\n3.Enter 0 for all input (0 for all size)<br>\n4.Add these to your functions.php</p>\n\n<pre><code>// Enable support for Post Thumbnails, and declare sizes.\nadd_theme_support( 'post-thumbnails' );\nset_post_thumbnail_size( 400, 400, array(\"center\",\"center\") );\nfunction fw_add_image_insert_override($sizes){\n // unset( $sizes['thumbnail']);\n unset( $sizes['small']);\n unset( $sizes['medium']);\n unset( $sizes['large']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'fw_add_image_insert_override' );\n</code></pre>\n\n<p>5. Make sure that there is no code line in your functions.php start with <code>add_imge_size</code> \n<strong>Note:</strong>: I suppose you use size of 400x400 for your thumbnail\nNow when you upload a photo, it will create only 2 versions instead of at least 4 versions photo as previous.</p>\n" }, { "answer_id": 187800, "author": "timholz", "author_id": 71669, "author_profile": "https://wordpress.stackexchange.com/users/71669", "pm_score": 0, "selected": false, "text": "<p>Hi – I had a similar problem. WooCommerce uses catalogue images for catalogue and related product images. That is not ideal, for you loose either image quality or speed. So I tried to add a fourth image category for my related products. Howdy McGee has solved the problem. Please take a look at Howdy McGees answer:</p>\n\n<blockquote>\n <p>Modify Related Product Image Sizes: <a href=\"https://wordpress.stackexchange.com/questions/186366/custom-woocommerce-image-size/186370?noredirect=1#comment273470_186370\">read his code</a>!</p>\n</blockquote>\n\n<p>It has worked out magnificently for my needs. For your problem the same logic could be applied. Hope this helps.</p>\n\n<p>Regards, </p>\n\n<p>Theo</p>\n\n<p>**Addition: **</p>\n\n<p>I found a solution that works.</p>\n\n<p><strong>Step 1:</strong> Assign a new thumbnail size in your functions.php.\nCheck reference: <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow noreferrer\">wp codex</a>!</p>\n\n<pre><code>/*add your custom size*/\nadd_action( 'after_setup_theme', 'your_theme_setup' );\nfunction your_theme_setup() {\nadd_image_size( 'your-thumb', 123, 123, true );//insert your values\n}\n</code></pre>\n\n<p>Note: 'your-thumb', you will use this variable name later</p>\n\n<p><strong>Step 2:</strong> Then add the following code wherever you want to display your featured products:</p>\n\n<pre><code> &lt;h1&gt;featured products&lt;/h1&gt; \n &lt;div class=\"woocommerce\"&gt;\n &lt;ul class= \"products\"&gt;\n\n &lt;?php\n $args = array( 'post_type' =&gt; 'product', 'meta_key' =&gt; '_featured','posts_per_page' =&gt; 4,'columns' =&gt; '4', 'meta_value' =&gt; 'yes' );\n $loop = new WP_Query( $args );\n\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt;\n\n &lt;li class=\"product post-&lt;?php echo get_the_ID(); ?&gt;\"&gt; \n &lt;a href=\"&lt;?php echo get_permalink( $loop-&gt;post-&gt;ID ) ?&gt;\" title=\"&lt;?php echo esc_attr($loop-&gt;post-&gt;post_title ? $loop-&gt;post-&gt;post_title : $loop-&gt;post-&gt;ID); ?&gt;\"&gt;\n\n &lt;?php woocommerce_show_product_sale_flash( $post, $product ); ?&gt;\n &lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;&lt;span class=\"price\"&gt;&lt;?php echo $product-&gt;get_price_html(); ?&gt;&lt;/span&gt;\n\n &lt;/li&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php wp_reset_query(); ?&gt; \n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Reference and info: \n(<a href=\"https://haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/\" rel=\"nofollow noreferrer\">www.haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/</a>)</p>\n\n<p>I placed it in the index.php (my homepage) of wootheme mystyle.\nDon't forget to use 'your-thumb' on line:</p>\n\n<pre><code>&lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n</code></pre>\n\n<p><strong>Step 3:</strong> Regenerate thumbnails, use the plugin <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n\n<p><strong>Step 4:</strong> Refresh the browser and inspect the DOM and compare the values </p>\n\n<p>According to your theme you may change the mark up and class names.\nI tested the above method and it works well.</p>\n\n<p>The only thing I couldn't do so far, is to add the-add-to-cart-button, because I do not know how to write a variable into the add to cart button shortcode.\nThis is the code:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[add_to_cart id=\"variable number?\"]'); ?&gt;\n</code></pre>\n\n<p>I hope this helps.</p>\n\n<p>There is certainly a more elegant way to do this. For instance with a function in the functions.php</p>\n\n<p>Regards,</p>\n\n<p>Theo</p>\n" }, { "answer_id": 190756, "author": "Mathew Tinsley", "author_id": 69793, "author_profile": "https://wordpress.stackexchange.com/users/69793", "pm_score": 2, "selected": false, "text": "<p>This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size.</p>\n\n<pre><code>function lazy_image_size($image_id, $width, $height, $crop) {\n // Temporarily create an image size\n $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop);\n add_image_size($size_id, $width, $height, $crop);\n\n // Get the attachment data\n $meta = wp_get_attachment_metadata($image_id);\n\n // If the size does not exist\n if(!isset($meta['sizes'][$size_id])) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n\n $file = get_attached_file($image_id);\n $new_meta = wp_generate_attachment_metadata($image_id, $file);\n\n // Merge the sizes so we don't lose already generated sizes\n $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']);\n\n // Update the meta data\n wp_update_attachment_metadata($image_id, $new_meta);\n }\n\n // Fetch the sized image\n $sized = wp_get_attachment_image_src($image_id, $size_id);\n\n // Remove the image size so new images won't be created in this size automatically\n remove_image_size($size_id);\n return $sized;\n}\n</code></pre>\n\n<p>It's \"lazy\" because images are not generated until they are needed.</p>\n\n<p>In your use-case, you would call that <code>lazy_image_size</code> with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image.</p>\n\n<p>Gist: <a href=\"https://gist.github.com/mtinsley/be503d90724be73cdda4\" rel=\"nofollow\">https://gist.github.com/mtinsley/be503d90724be73cdda4</a></p>\n" } ]
2015/03/22
[ "https://wordpress.stackexchange.com/questions/181900", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69417/" ]
I have a custom post type for a group of people (employees). At first, I needed to display 7 random employees. That was easy ``` <?php $args = array( 'post_type' => 'employees', 'orderby' => 'rand', 'posts_per_page' => 7, ); $query = new WP_Query($args); while ( $query->have_posts() ) { $query->the_post(); //do stuff <?php endif; } wp_reset_postdata(); ?> ``` But now I've been asked to make sure at least one of the seven is always a woman. The man to woman ratio at the company is 4 to 1. I've set a checkbox that I can test for: ``` <?php if( in_array( 'yes', get_field('is_female') ) ){ // this is a female } ``` I need help putting it all together. I assume I need to keep track if any of the posts are displayed are women. Once I get to the 7th position if a woman isn't listed, I need to keep iterating until I find one. Any suggestions?
This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size. ``` function lazy_image_size($image_id, $width, $height, $crop) { // Temporarily create an image size $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop); add_image_size($size_id, $width, $height, $crop); // Get the attachment data $meta = wp_get_attachment_metadata($image_id); // If the size does not exist if(!isset($meta['sizes'][$size_id])) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $file = get_attached_file($image_id); $new_meta = wp_generate_attachment_metadata($image_id, $file); // Merge the sizes so we don't lose already generated sizes $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']); // Update the meta data wp_update_attachment_metadata($image_id, $new_meta); } // Fetch the sized image $sized = wp_get_attachment_image_src($image_id, $size_id); // Remove the image size so new images won't be created in this size automatically remove_image_size($size_id); return $sized; } ``` It's "lazy" because images are not generated until they are needed. In your use-case, you would call that `lazy_image_size` with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image. Gist: <https://gist.github.com/mtinsley/be503d90724be73cdda4>
181,907
<p>I want to add a field in my custom meta box, same as below, but not for tags. How can I repeatedly take more inputs in the same field? </p> <p><img src="https://i.stack.imgur.com/CJj3W.png" alt="enter image description here"></p> <p>Here is my code added to functions.php:</p> <pre><code>function dikka_cmb_meoxes( array $meta_boxes ) { $prefix = 'dikka_'; $meta_boxes['details_meox'] = array( 'id' =&gt; 'details_meox', 'title' =&gt; __( 'Porject Details', 'dikka' ), 'pages' =&gt; array( 'portfolio', ), // Post type 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'show_names' =&gt; true, // Show field names on the left 'fields' =&gt; array( array( 'name' =&gt; __( 'Client', 'dikka' ), 'desc' =&gt; __( 'Add client name', 'dikka' ), 'id' =&gt; $prefix . 'add_client', 'type' =&gt; 'text', ), array( 'name' =&gt; __( 'Skills', 'dikka' ), 'desc' =&gt; __( 'Add skills', 'dikka' ), 'id' =&gt; $prefix . 'skills', 'type' =&gt; 'text', ), array( 'name' =&gt; __( 'Release Date', 'dikka' ), 'desc' =&gt; __( 'Add release date of project', 'dikka' ), 'id' =&gt; $prefix . 'add_releasedate', 'type' =&gt; 'text_date', ), ) ); return $meta_boxes; } </code></pre>
[ { "answer_id": 181886, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>You can see this <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow\">link</a>. there has some example like</p>\n\n<pre><code>add_action( 'after_setup_theme', 'baw_theme_setup' );\nfunction baw_theme_setup() {\n add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height)\n add_image_size( 'homepage-thumb', 220, 180, true ); // (cropped)\n}\n</code></pre>\n" }, { "answer_id": 184751, "author": "Trang", "author_id": 70868, "author_profile": "https://wordpress.stackexchange.com/users/70868", "pm_score": 0, "selected": false, "text": "<p>1.Go to Dashboard > Settings > Media<br>\n2.Uncheck Crop thumbnail to exact dimensions (normally thumbnails are proportional)<br>\n3.Enter 0 for all input (0 for all size)<br>\n4.Add these to your functions.php</p>\n\n<pre><code>// Enable support for Post Thumbnails, and declare sizes.\nadd_theme_support( 'post-thumbnails' );\nset_post_thumbnail_size( 400, 400, array(\"center\",\"center\") );\nfunction fw_add_image_insert_override($sizes){\n // unset( $sizes['thumbnail']);\n unset( $sizes['small']);\n unset( $sizes['medium']);\n unset( $sizes['large']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'fw_add_image_insert_override' );\n</code></pre>\n\n<p>5. Make sure that there is no code line in your functions.php start with <code>add_imge_size</code> \n<strong>Note:</strong>: I suppose you use size of 400x400 for your thumbnail\nNow when you upload a photo, it will create only 2 versions instead of at least 4 versions photo as previous.</p>\n" }, { "answer_id": 187800, "author": "timholz", "author_id": 71669, "author_profile": "https://wordpress.stackexchange.com/users/71669", "pm_score": 0, "selected": false, "text": "<p>Hi – I had a similar problem. WooCommerce uses catalogue images for catalogue and related product images. That is not ideal, for you loose either image quality or speed. So I tried to add a fourth image category for my related products. Howdy McGee has solved the problem. Please take a look at Howdy McGees answer:</p>\n\n<blockquote>\n <p>Modify Related Product Image Sizes: <a href=\"https://wordpress.stackexchange.com/questions/186366/custom-woocommerce-image-size/186370?noredirect=1#comment273470_186370\">read his code</a>!</p>\n</blockquote>\n\n<p>It has worked out magnificently for my needs. For your problem the same logic could be applied. Hope this helps.</p>\n\n<p>Regards, </p>\n\n<p>Theo</p>\n\n<p>**Addition: **</p>\n\n<p>I found a solution that works.</p>\n\n<p><strong>Step 1:</strong> Assign a new thumbnail size in your functions.php.\nCheck reference: <a href=\"https://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow noreferrer\">wp codex</a>!</p>\n\n<pre><code>/*add your custom size*/\nadd_action( 'after_setup_theme', 'your_theme_setup' );\nfunction your_theme_setup() {\nadd_image_size( 'your-thumb', 123, 123, true );//insert your values\n}\n</code></pre>\n\n<p>Note: 'your-thumb', you will use this variable name later</p>\n\n<p><strong>Step 2:</strong> Then add the following code wherever you want to display your featured products:</p>\n\n<pre><code> &lt;h1&gt;featured products&lt;/h1&gt; \n &lt;div class=\"woocommerce\"&gt;\n &lt;ul class= \"products\"&gt;\n\n &lt;?php\n $args = array( 'post_type' =&gt; 'product', 'meta_key' =&gt; '_featured','posts_per_page' =&gt; 4,'columns' =&gt; '4', 'meta_value' =&gt; 'yes' );\n $loop = new WP_Query( $args );\n\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt;\n\n &lt;li class=\"product post-&lt;?php echo get_the_ID(); ?&gt;\"&gt; \n &lt;a href=\"&lt;?php echo get_permalink( $loop-&gt;post-&gt;ID ) ?&gt;\" title=\"&lt;?php echo esc_attr($loop-&gt;post-&gt;post_title ? $loop-&gt;post-&gt;post_title : $loop-&gt;post-&gt;ID); ?&gt;\"&gt;\n\n &lt;?php woocommerce_show_product_sale_flash( $post, $product ); ?&gt;\n &lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;&lt;span class=\"price\"&gt;&lt;?php echo $product-&gt;get_price_html(); ?&gt;&lt;/span&gt;\n\n &lt;/li&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php wp_reset_query(); ?&gt; \n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Reference and info: \n(<a href=\"https://haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/\" rel=\"nofollow noreferrer\">www.haloseeker.com/display-woocommerce-featured-products-without-a-shortcode/</a>)</p>\n\n<p>I placed it in the index.php (my homepage) of wootheme mystyle.\nDon't forget to use 'your-thumb' on line:</p>\n\n<pre><code>&lt;?php if (has_post_thumbnail( $loop-&gt;post-&gt;ID )) echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'your-thumb'); else echo '&lt;img src=\"'.woocommerce_placeholder_img_src().'\" alt=\"Placeholder\" width=\"123px\" height=\"123px\" /&gt;'; ?&gt;&lt;/a&gt;\n</code></pre>\n\n<p><strong>Step 3:</strong> Regenerate thumbnails, use the plugin <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n\n<p><strong>Step 4:</strong> Refresh the browser and inspect the DOM and compare the values </p>\n\n<p>According to your theme you may change the mark up and class names.\nI tested the above method and it works well.</p>\n\n<p>The only thing I couldn't do so far, is to add the-add-to-cart-button, because I do not know how to write a variable into the add to cart button shortcode.\nThis is the code:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[add_to_cart id=\"variable number?\"]'); ?&gt;\n</code></pre>\n\n<p>I hope this helps.</p>\n\n<p>There is certainly a more elegant way to do this. For instance with a function in the functions.php</p>\n\n<p>Regards,</p>\n\n<p>Theo</p>\n" }, { "answer_id": 190756, "author": "Mathew Tinsley", "author_id": 69793, "author_profile": "https://wordpress.stackexchange.com/users/69793", "pm_score": 2, "selected": false, "text": "<p>This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size.</p>\n\n<pre><code>function lazy_image_size($image_id, $width, $height, $crop) {\n // Temporarily create an image size\n $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop);\n add_image_size($size_id, $width, $height, $crop);\n\n // Get the attachment data\n $meta = wp_get_attachment_metadata($image_id);\n\n // If the size does not exist\n if(!isset($meta['sizes'][$size_id])) {\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n\n $file = get_attached_file($image_id);\n $new_meta = wp_generate_attachment_metadata($image_id, $file);\n\n // Merge the sizes so we don't lose already generated sizes\n $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']);\n\n // Update the meta data\n wp_update_attachment_metadata($image_id, $new_meta);\n }\n\n // Fetch the sized image\n $sized = wp_get_attachment_image_src($image_id, $size_id);\n\n // Remove the image size so new images won't be created in this size automatically\n remove_image_size($size_id);\n return $sized;\n}\n</code></pre>\n\n<p>It's \"lazy\" because images are not generated until they are needed.</p>\n\n<p>In your use-case, you would call that <code>lazy_image_size</code> with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image.</p>\n\n<p>Gist: <a href=\"https://gist.github.com/mtinsley/be503d90724be73cdda4\" rel=\"nofollow\">https://gist.github.com/mtinsley/be503d90724be73cdda4</a></p>\n" } ]
2015/03/22
[ "https://wordpress.stackexchange.com/questions/181907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69421/" ]
I want to add a field in my custom meta box, same as below, but not for tags. How can I repeatedly take more inputs in the same field? ![enter image description here](https://i.stack.imgur.com/CJj3W.png) Here is my code added to functions.php: ``` function dikka_cmb_meoxes( array $meta_boxes ) { $prefix = 'dikka_'; $meta_boxes['details_meox'] = array( 'id' => 'details_meox', 'title' => __( 'Porject Details', 'dikka' ), 'pages' => array( 'portfolio', ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __( 'Client', 'dikka' ), 'desc' => __( 'Add client name', 'dikka' ), 'id' => $prefix . 'add_client', 'type' => 'text', ), array( 'name' => __( 'Skills', 'dikka' ), 'desc' => __( 'Add skills', 'dikka' ), 'id' => $prefix . 'skills', 'type' => 'text', ), array( 'name' => __( 'Release Date', 'dikka' ), 'desc' => __( 'Add release date of project', 'dikka' ), 'id' => $prefix . 'add_releasedate', 'type' => 'text_date', ), ) ); return $meta_boxes; } ```
This function will generate an image by temporarily registering an image size, generating the image (if necessary) and the removing the size so new images will not be created in that size. ``` function lazy_image_size($image_id, $width, $height, $crop) { // Temporarily create an image size $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop); add_image_size($size_id, $width, $height, $crop); // Get the attachment data $meta = wp_get_attachment_metadata($image_id); // If the size does not exist if(!isset($meta['sizes'][$size_id])) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $file = get_attached_file($image_id); $new_meta = wp_generate_attachment_metadata($image_id, $file); // Merge the sizes so we don't lose already generated sizes $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']); // Update the meta data wp_update_attachment_metadata($image_id, $new_meta); } // Fetch the sized image $sized = wp_get_attachment_image_src($image_id, $size_id); // Remove the image size so new images won't be created in this size automatically remove_image_size($size_id); return $sized; } ``` It's "lazy" because images are not generated until they are needed. In your use-case, you would call that `lazy_image_size` with the post thumbnail ID to get an image of the desired size. An image would be generated on the first call. Subsequent calls would fetch the existing image. Gist: <https://gist.github.com/mtinsley/be503d90724be73cdda4>
181,921
<p>I want to add text but only appear on the homepage only. I have used this if script:</p> <pre><code>&lt;?php if( is_home() ) : ?&gt; &lt;p&gt;Some text&lt;/p&gt; &lt;?php endif;?&gt; </code></pre> <p>but the problem with this is it's appearing on every paginated page. So for example if I view <code>http://www.example.com/page/2/</code> it will show that text. I only want it appear on 1st page. </p> <p>Any fix to this?</p>
[ { "answer_id": 181922, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/is_paged\" rel=\"nofollow\"><code>is_paged()</code></a></p>\n\n<blockquote>\n <p>...checks if page being displayed is \"paged\" and the current page number is greater than one. This is a boolean function, meaning it returns either TRUE or FALSE.</p>\n</blockquote>\n\n<p>You can adjust your code as follows</p>\n\n<pre><code>&lt;?php if( is_home() &amp;&amp; !is_paged() ) : ?&gt;\n &lt;p&gt;Some text&lt;/p&gt;\n&lt;?php endif;?&gt;\n</code></pre>\n" }, { "answer_id": 275164, "author": "WaleedBarakat", "author_id": 124846, "author_profile": "https://wordpress.stackexchange.com/users/124846", "pm_score": 0, "selected": false, "text": "<p>There is another way you can show text block in all pages and categories but hide it on the homepage and vice versa.</p>\n\n<pre><code>&lt;?php if( is_front_page() ==\"\" ) : ?&gt;\n &lt;p&gt;Some text here&lt;/p&gt;\n&lt;?php endif;?&gt;\n</code></pre>\n" } ]
2015/03/22
[ "https://wordpress.stackexchange.com/questions/181921", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17971/" ]
I want to add text but only appear on the homepage only. I have used this if script: ``` <?php if( is_home() ) : ?> <p>Some text</p> <?php endif;?> ``` but the problem with this is it's appearing on every paginated page. So for example if I view `http://www.example.com/page/2/` it will show that text. I only want it appear on 1st page. Any fix to this?
You can use [`is_paged()`](https://codex.wordpress.org/Function_Reference/is_paged) > > ...checks if page being displayed is "paged" and the current page number is greater than one. This is a boolean function, meaning it returns either TRUE or FALSE. > > > You can adjust your code as follows ``` <?php if( is_home() && !is_paged() ) : ?> <p>Some text</p> <?php endif;?> ```
181,930
<p>I have this code. But when i enter in subcategory which has no own sub, it disappears. I want if has no subs return parent's subs.</p> <p>$category->category_parent and $category->parent aren't returning parent cat id.</p> <pre><code>&lt;div style="margin: 0 0 20px 0;"&gt; &lt;?php $thisCat = get_categories(array('child_of'=&gt;$_GET['cat'])); if(empty($thisCat)){ $thisCat = get_categories(array('parent'=&gt;$_GET['cat'])); } foreach($thisCat as $cat) { ?&gt; &lt;div style="margin: 0 25px 0 0; display: inline-block;"&gt; &lt;a style="font-size: 10pt; color: #777; font-weight: normal;" href="/?cat=&lt;?php echo $cat-&gt;cat_ID; ?&gt;"&gt;&lt;?php echo $cat-&gt;name; ?&gt;&lt;/a&gt;&lt;span style="font-size: 7pt; font-weight: bold; background: #f47a6d; padding: 0 4px 0 4px; color: white; border-radius: 1px; margin: -15px 0 0 -5px; position: absolute; text-align: center;"&gt;&lt;?php echo $cat-&gt;count; ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php } ?&gt;&lt;/div&gt; </code></pre> <p>Example:</p> <ul> <li><p>Main category</p> <ul> <li>Sub category 1 (has no sub cats)</li> <li>Sub category 2 (has no sub cats)</li> </ul></li> </ul> <p>When i go to "Sub category 1" and "Sub category 2" url i want to show "Main category's" sub categories ("Sub category 1", "Sub category 2") if "Sub Category 1" and "Sub Category 2" has no its own sub categories.</p>
[ { "answer_id": 181922, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/is_paged\" rel=\"nofollow\"><code>is_paged()</code></a></p>\n\n<blockquote>\n <p>...checks if page being displayed is \"paged\" and the current page number is greater than one. This is a boolean function, meaning it returns either TRUE or FALSE.</p>\n</blockquote>\n\n<p>You can adjust your code as follows</p>\n\n<pre><code>&lt;?php if( is_home() &amp;&amp; !is_paged() ) : ?&gt;\n &lt;p&gt;Some text&lt;/p&gt;\n&lt;?php endif;?&gt;\n</code></pre>\n" }, { "answer_id": 275164, "author": "WaleedBarakat", "author_id": 124846, "author_profile": "https://wordpress.stackexchange.com/users/124846", "pm_score": 0, "selected": false, "text": "<p>There is another way you can show text block in all pages and categories but hide it on the homepage and vice versa.</p>\n\n<pre><code>&lt;?php if( is_front_page() ==\"\" ) : ?&gt;\n &lt;p&gt;Some text here&lt;/p&gt;\n&lt;?php endif;?&gt;\n</code></pre>\n" } ]
2015/03/22
[ "https://wordpress.stackexchange.com/questions/181930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69437/" ]
I have this code. But when i enter in subcategory which has no own sub, it disappears. I want if has no subs return parent's subs. $category->category\_parent and $category->parent aren't returning parent cat id. ``` <div style="margin: 0 0 20px 0;"> <?php $thisCat = get_categories(array('child_of'=>$_GET['cat'])); if(empty($thisCat)){ $thisCat = get_categories(array('parent'=>$_GET['cat'])); } foreach($thisCat as $cat) { ?> <div style="margin: 0 25px 0 0; display: inline-block;"> <a style="font-size: 10pt; color: #777; font-weight: normal;" href="/?cat=<?php echo $cat->cat_ID; ?>"><?php echo $cat->name; ?></a><span style="font-size: 7pt; font-weight: bold; background: #f47a6d; padding: 0 4px 0 4px; color: white; border-radius: 1px; margin: -15px 0 0 -5px; position: absolute; text-align: center;"><?php echo $cat->count; ?></span> </div> <?php } ?></div> ``` Example: * Main category + Sub category 1 (has no sub cats) + Sub category 2 (has no sub cats) When i go to "Sub category 1" and "Sub category 2" url i want to show "Main category's" sub categories ("Sub category 1", "Sub category 2") if "Sub Category 1" and "Sub Category 2" has no its own sub categories.
You can use [`is_paged()`](https://codex.wordpress.org/Function_Reference/is_paged) > > ...checks if page being displayed is "paged" and the current page number is greater than one. This is a boolean function, meaning it returns either TRUE or FALSE. > > > You can adjust your code as follows ``` <?php if( is_home() && !is_paged() ) : ?> <p>Some text</p> <?php endif;?> ```
181,934
<p>I'm building a child theme and it currently has a very simple <code>&lt;head&gt;</code> section in header.php:</p> <pre><code>&lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"&gt; &lt;title&gt;&lt;?php wp_title( '|', true, 'right' ); ?&gt;&lt;/title&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11"&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;"&gt; &lt;!--[if lt IE 9]&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/js/html5shiv.min.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; </code></pre> <p>I'm guessing <code>wp_head()</code> is responsible for the second <code>&lt;title&gt;</code> element (it appears just there in the final HTML), but other things I've read say this is impossible.</p> <p>Should I be removing the <code>&lt;title&gt;</code> from my header.php, or should I be adding something to my functions to remove the title from <code>wp_head()</code> (eg. <code>remove_action('wp_head', 'title'</code>) ?</p> <p>Or should I be doing something else altogether?</p>
[ { "answer_id": 181963, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call <a href=\"https://codex.wordpress.org/Function_Reference/wp_title\"><code>wp_title()</code></a> in the head any more, you can make use of new <code>title_tag</code> theme support tag which automatically adds the <code>wp_title()</code> tag in the header</p>\n\n<p>The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p>As a solution, copy the parent theme <code>header.php</code> to your child theme and simply remove the <code>wp_title()</code> function from the child theme <code>header.php</code></p>\n\n<p>Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (<em>Taken from the codex</em>)</p>\n\n<pre><code> if ( ! function_exists( '_wp_render_title_tag' ) ) {\n function theme_slug_render_title() \n {\n ?&gt;\n &lt;title&gt;\n &lt;?php wp_title( '|', true, 'right' ); ?&gt;\n &lt;/title&gt;\n &lt;?php\n }\n add_action( 'wp_head', 'theme_slug_render_title' );\n}\n</code></pre>\n" }, { "answer_id": 216544, "author": "vunguyen", "author_id": 88022, "author_profile": "https://wordpress.stackexchange.com/users/88022", "pm_score": -1, "selected": false, "text": "<p>At <code>function.php</code> file in your theme comment code</p>\n\n<pre><code>//add_theme_support( 'title-tag' );\n</code></pre>\n" } ]
2015/03/22
[ "https://wordpress.stackexchange.com/questions/181934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
I'm building a child theme and it currently has a very simple `<head>` section in header.php: ``` <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <!--[if lt IE 9]> <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/html5shiv.min.js"></script> <![endif]--> <?php wp_head(); ?> </head> ``` I'm guessing `wp_head()` is responsible for the second `<title>` element (it appears just there in the final HTML), but other things I've read say this is impossible. Should I be removing the `<title>` from my header.php, or should I be adding something to my functions to remove the title from `wp_head()` (eg. `remove_action('wp_head', 'title'`) ? Or should I be doing something else altogether?
The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call [`wp_title()`](https://codex.wordpress.org/Function_Reference/wp_title) in the head any more, you can make use of new `title_tag` theme support tag which automatically adds the `wp_title()` tag in the header The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code ``` add_theme_support( 'title-tag' ); ``` As a solution, copy the parent theme `header.php` to your child theme and simply remove the `wp_title()` function from the child theme `header.php` Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (*Taken from the codex*) ``` if ( ! function_exists( '_wp_render_title_tag' ) ) { function theme_slug_render_title() { ?> <title> <?php wp_title( '|', true, 'right' ); ?> </title> <?php } add_action( 'wp_head', 'theme_slug_render_title' ); } ```
181,966
<p>I am querying for most popular posts by custom view count by using the custom query below,</p> <pre><code>&lt;?php $mostpopular_args=array( 'post_type' =&gt; 'post', 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'view_count', 'posts_per_page' =&gt; 2, ); &lt;?php $mostpopular_pick = new WP_Query($mostpopular_args); ?&gt; ?&gt; </code></pre> <p>However, this is not working. As suggested by an expert, I ran <code>$mostpopular_pick-&gt;request</code>and it seems that wordpress is ordering posts by 'menu_order' instead of meta_value_num. Here is what it returned,</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND (wp_postmeta.meta_key = 'view_count') GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order, wp_postmeta.meta_value DESC LIMIT 0, 2 </code></pre> <p>And also, though I limited post count to 2, it is still returning 4 posts.</p> <p>Whats going on, any Idea?</p>
[ { "answer_id": 181963, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call <a href=\"https://codex.wordpress.org/Function_Reference/wp_title\"><code>wp_title()</code></a> in the head any more, you can make use of new <code>title_tag</code> theme support tag which automatically adds the <code>wp_title()</code> tag in the header</p>\n\n<p>The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p>As a solution, copy the parent theme <code>header.php</code> to your child theme and simply remove the <code>wp_title()</code> function from the child theme <code>header.php</code></p>\n\n<p>Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (<em>Taken from the codex</em>)</p>\n\n<pre><code> if ( ! function_exists( '_wp_render_title_tag' ) ) {\n function theme_slug_render_title() \n {\n ?&gt;\n &lt;title&gt;\n &lt;?php wp_title( '|', true, 'right' ); ?&gt;\n &lt;/title&gt;\n &lt;?php\n }\n add_action( 'wp_head', 'theme_slug_render_title' );\n}\n</code></pre>\n" }, { "answer_id": 216544, "author": "vunguyen", "author_id": 88022, "author_profile": "https://wordpress.stackexchange.com/users/88022", "pm_score": -1, "selected": false, "text": "<p>At <code>function.php</code> file in your theme comment code</p>\n\n<pre><code>//add_theme_support( 'title-tag' );\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/181966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64811/" ]
I am querying for most popular posts by custom view count by using the custom query below, ``` <?php $mostpopular_args=array( 'post_type' => 'post', 'orderby' => 'meta_value_num', 'meta_key' => 'view_count', 'posts_per_page' => 2, ); <?php $mostpopular_pick = new WP_Query($mostpopular_args); ?> ?> ``` However, this is not working. As suggested by an expert, I ran `$mostpopular_pick->request`and it seems that wordpress is ordering posts by 'menu\_order' instead of meta\_value\_num. Here is what it returned, ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND (wp_postmeta.meta_key = 'view_count') GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order, wp_postmeta.meta_value DESC LIMIT 0, 2 ``` And also, though I limited post count to 2, it is still returning 4 posts. Whats going on, any Idea?
The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call [`wp_title()`](https://codex.wordpress.org/Function_Reference/wp_title) in the head any more, you can make use of new `title_tag` theme support tag which automatically adds the `wp_title()` tag in the header The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code ``` add_theme_support( 'title-tag' ); ``` As a solution, copy the parent theme `header.php` to your child theme and simply remove the `wp_title()` function from the child theme `header.php` Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (*Taken from the codex*) ``` if ( ! function_exists( '_wp_render_title_tag' ) ) { function theme_slug_render_title() { ?> <title> <?php wp_title( '|', true, 'right' ); ?> </title> <?php } add_action( 'wp_head', 'theme_slug_render_title' ); } ```
181,977
<p>I have created a custom post type portfolio with custom taxonomy Portfolio Category. I can create portfolio items and assign portfolio categories to them and save these custom posts. But what I need is the permalink to show <code>domain.com/portfolio-category/portfolio-item-name</code>. Portfolio Category is variable depending on the category I pick.</p> <p>Now I only see <code>domain.com/portfolio/item-name</code> The name portfolio should be the name of the custom taxonomy I attach the custom post to, but it does not. Is just a fixed name from the CPT it seems. I would like urls like <code>domain.com/design/client-a</code> and <code>domain.com/dev/client-b</code></p> <p>Here is my code: </p> <pre><code>// Register Custom Taxonomy function portfolio_taxonomy() { $labels = array( 'name' =&gt; _x( 'Portfolio Category', 'Taxonomy General Name', 'imagewize_portfolio_plugin' ), 'singular_name' =&gt; _x( 'Portfolio Category', 'Taxonomy Singular Name', 'imagewize_portfolio_plugin' ), 'menu_name' =&gt; __( 'Category', 'imagewize_portfolio_plugin' ), 'all_items' =&gt; __( 'All Items', 'imagewize_portfolio_plugin' ), 'parent_item' =&gt; __( 'Parent Item', 'imagewize_portfolio_plugin' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'imagewize_portfolio_plugin' ), 'new_item_name' =&gt; __( 'New Item Name', 'imagewize_portfolio_plugin' ), 'add_new_item' =&gt; __( 'Add New Item', 'imagewize_portfolio_plugin' ), 'edit_item' =&gt; __( 'Edit Item', 'imagewize_portfolio_plugin' ), 'update_item' =&gt; __( 'Update Item', 'imagewize_portfolio_plugin' ), 'separate_items_with_commas' =&gt; __( 'Separate items with commas', 'imagewize_portfolio_plugin' ), 'search_items' =&gt; __( 'Search Items', 'imagewize_portfolio_plugin' ), 'add_or_remove_items' =&gt; __( 'Add or remove items', 'imagewize_portfolio_plugin' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used items', 'imagewize_portfolio_plugin' ), 'not_found' =&gt; __( 'Not Found', 'imagewize_portfolio_plugin' ), ); $rewrite = array( 'slug' =&gt; 'Portfolio Category', 'with_front' =&gt; true, 'hierarchical' =&gt; true, ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'rewrite' =&gt; $rewrite, ); register_taxonomy( 'portfolio', array( 'Img_portfolio_cpt' ), $args ); } // Hook into the 'init' action add_action( 'init', 'portfolio_taxonomy', 0 ); if ( ! function_exists('img_portfolio_cpt') ) { // Register Custom Post Type function img_portfolio_cpt() { $labels = array( 'name' =&gt; _x( 'Portfolio Items', 'Post Type General Name', 'imagewize_portfolio_plugin' ), 'singular_name' =&gt; _x( 'Portfolio', 'Post Type Singular Name', 'imagewize_portfolio_plugin' ), 'menu_name' =&gt; __( 'Portfolio', 'imagewize_portfolio_plugin' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'imagewize_portfolio_plugin' ), 'all_items' =&gt; __( 'All Items', 'imagewize_portfolio_plugin' ), 'view_item' =&gt; __( 'View Item', 'imagewize_portfolio_plugin' ), 'add_new_item' =&gt; __( 'Add New Item', 'imagewize_portfolio_plugin' ), 'add_new' =&gt; __( 'Add New', 'imagewize_portfolio_plugin' ), 'edit_item' =&gt; __( 'Edit Item', 'imagewize_portfolio_plugin' ), 'update_item' =&gt; __( 'Update Item', 'imagewize_portfolio_plugin' ), 'search_items' =&gt; __( 'Search Item', 'imagewize_portfolio_plugin' ), 'not_found' =&gt; __( 'Not found', 'imagewize_portfolio_plugin' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'imagewize_portfolio_plugin' ), ); $rewrite = array( 'slug' =&gt; 'portfolio', 'with_front' =&gt; true, 'pages' =&gt; true, 'feeds' =&gt; true, ); $args = array( 'label' =&gt; __( 'Img_portfolio_cpt', 'imagewize_portfolio_plugin' ), 'description' =&gt; __( 'Imagewize Portfolio', 'imagewize_portfolio_plugin' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', ), 'taxonomies' =&gt; array( 'portfolio' ), 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-portfolio', 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'page', ); register_post_type( 'Img_portfolio_cpt', $args ); } // Hook into the 'init' action add_action( 'init', 'img_portfolio_cpt', 0 ); } </code></pre>
[ { "answer_id": 181963, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call <a href=\"https://codex.wordpress.org/Function_Reference/wp_title\"><code>wp_title()</code></a> in the head any more, you can make use of new <code>title_tag</code> theme support tag which automatically adds the <code>wp_title()</code> tag in the header</p>\n\n<p>The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p>As a solution, copy the parent theme <code>header.php</code> to your child theme and simply remove the <code>wp_title()</code> function from the child theme <code>header.php</code></p>\n\n<p>Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (<em>Taken from the codex</em>)</p>\n\n<pre><code> if ( ! function_exists( '_wp_render_title_tag' ) ) {\n function theme_slug_render_title() \n {\n ?&gt;\n &lt;title&gt;\n &lt;?php wp_title( '|', true, 'right' ); ?&gt;\n &lt;/title&gt;\n &lt;?php\n }\n add_action( 'wp_head', 'theme_slug_render_title' );\n}\n</code></pre>\n" }, { "answer_id": 216544, "author": "vunguyen", "author_id": 88022, "author_profile": "https://wordpress.stackexchange.com/users/88022", "pm_score": -1, "selected": false, "text": "<p>At <code>function.php</code> file in your theme comment code</p>\n\n<pre><code>//add_theme_support( 'title-tag' );\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/181977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12260/" ]
I have created a custom post type portfolio with custom taxonomy Portfolio Category. I can create portfolio items and assign portfolio categories to them and save these custom posts. But what I need is the permalink to show `domain.com/portfolio-category/portfolio-item-name`. Portfolio Category is variable depending on the category I pick. Now I only see `domain.com/portfolio/item-name` The name portfolio should be the name of the custom taxonomy I attach the custom post to, but it does not. Is just a fixed name from the CPT it seems. I would like urls like `domain.com/design/client-a` and `domain.com/dev/client-b` Here is my code: ``` // Register Custom Taxonomy function portfolio_taxonomy() { $labels = array( 'name' => _x( 'Portfolio Category', 'Taxonomy General Name', 'imagewize_portfolio_plugin' ), 'singular_name' => _x( 'Portfolio Category', 'Taxonomy Singular Name', 'imagewize_portfolio_plugin' ), 'menu_name' => __( 'Category', 'imagewize_portfolio_plugin' ), 'all_items' => __( 'All Items', 'imagewize_portfolio_plugin' ), 'parent_item' => __( 'Parent Item', 'imagewize_portfolio_plugin' ), 'parent_item_colon' => __( 'Parent Item:', 'imagewize_portfolio_plugin' ), 'new_item_name' => __( 'New Item Name', 'imagewize_portfolio_plugin' ), 'add_new_item' => __( 'Add New Item', 'imagewize_portfolio_plugin' ), 'edit_item' => __( 'Edit Item', 'imagewize_portfolio_plugin' ), 'update_item' => __( 'Update Item', 'imagewize_portfolio_plugin' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'imagewize_portfolio_plugin' ), 'search_items' => __( 'Search Items', 'imagewize_portfolio_plugin' ), 'add_or_remove_items' => __( 'Add or remove items', 'imagewize_portfolio_plugin' ), 'choose_from_most_used' => __( 'Choose from the most used items', 'imagewize_portfolio_plugin' ), 'not_found' => __( 'Not Found', 'imagewize_portfolio_plugin' ), ); $rewrite = array( 'slug' => 'Portfolio Category', 'with_front' => true, 'hierarchical' => true, ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'rewrite' => $rewrite, ); register_taxonomy( 'portfolio', array( 'Img_portfolio_cpt' ), $args ); } // Hook into the 'init' action add_action( 'init', 'portfolio_taxonomy', 0 ); if ( ! function_exists('img_portfolio_cpt') ) { // Register Custom Post Type function img_portfolio_cpt() { $labels = array( 'name' => _x( 'Portfolio Items', 'Post Type General Name', 'imagewize_portfolio_plugin' ), 'singular_name' => _x( 'Portfolio', 'Post Type Singular Name', 'imagewize_portfolio_plugin' ), 'menu_name' => __( 'Portfolio', 'imagewize_portfolio_plugin' ), 'parent_item_colon' => __( 'Parent Item:', 'imagewize_portfolio_plugin' ), 'all_items' => __( 'All Items', 'imagewize_portfolio_plugin' ), 'view_item' => __( 'View Item', 'imagewize_portfolio_plugin' ), 'add_new_item' => __( 'Add New Item', 'imagewize_portfolio_plugin' ), 'add_new' => __( 'Add New', 'imagewize_portfolio_plugin' ), 'edit_item' => __( 'Edit Item', 'imagewize_portfolio_plugin' ), 'update_item' => __( 'Update Item', 'imagewize_portfolio_plugin' ), 'search_items' => __( 'Search Item', 'imagewize_portfolio_plugin' ), 'not_found' => __( 'Not found', 'imagewize_portfolio_plugin' ), 'not_found_in_trash' => __( 'Not found in Trash', 'imagewize_portfolio_plugin' ), ); $rewrite = array( 'slug' => 'portfolio', 'with_front' => true, 'pages' => true, 'feeds' => true, ); $args = array( 'label' => __( 'Img_portfolio_cpt', 'imagewize_portfolio_plugin' ), 'description' => __( 'Imagewize Portfolio', 'imagewize_portfolio_plugin' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', ), 'taxonomies' => array( 'portfolio' ), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-portfolio', 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'rewrite' => $rewrite, 'capability_type' => 'page', ); register_post_type( 'Img_portfolio_cpt', $args ); } // Hook into the 'init' action add_action( 'init', 'img_portfolio_cpt', 0 ); } ```
The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call [`wp_title()`](https://codex.wordpress.org/Function_Reference/wp_title) in the head any more, you can make use of new `title_tag` theme support tag which automatically adds the `wp_title()` tag in the header The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code ``` add_theme_support( 'title-tag' ); ``` As a solution, copy the parent theme `header.php` to your child theme and simply remove the `wp_title()` function from the child theme `header.php` Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (*Taken from the codex*) ``` if ( ! function_exists( '_wp_render_title_tag' ) ) { function theme_slug_render_title() { ?> <title> <?php wp_title( '|', true, 'right' ); ?> </title> <?php } add_action( 'wp_head', 'theme_slug_render_title' ); } ```
182,006
<p>Similar questions have been asked before, but no answer suits well.</p> <p>I have: <code>site.com/parent-page/child-page</code> and would like to have: <code>site.com/child-page</code></p> <p>So I want to exclusively have permalinks with depth 1, without using the custom menu but still "hierarchizing" my pages in the admin all pages view and with parent/order in page attributes. </p> <p>The solution also needs to work automatically, so not changing permalinks on each page with the plugin "Custom Permalinks".</p> <p>This is what I need, and I am sure it is possible with a few lines of code in the <code>functions.php</code>, which I have found elsewhere but only for posts to remove the category, but not working for pages to remove the parent.</p> <p>This is such code, that maybe can be changed to work for <em>pages</em>?</p> <pre><code>add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 ); function remove_parent_cats_from_link( $permalink, $post, $leavename ) { $cats = get_the_category( $post-&gt;ID ); if ( $cats ) { // Make sure we use the same start cat as the permalink generator usort( $cats, '_usort_terms_by_ID' ); // order by ID $category = $cats[0]-&gt;slug; if ( $parent = $cats[0]-&gt;parent ) { // If there are parent categories, collect them and replace them in the link $parentcats = get_category_parents( $parent, false, '/', true ); // str_replace() is not the best solution if you can have duplicates: // example.com/luxemburg/luxemburg/ will be stripped down to example.com/ // But if you don't expect that, it should work $permalink = str_replace( $parentcats, '', $permalink ); } } return $permalink; } </code></pre>
[ { "answer_id": 181963, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call <a href=\"https://codex.wordpress.org/Function_Reference/wp_title\"><code>wp_title()</code></a> in the head any more, you can make use of new <code>title_tag</code> theme support tag which automatically adds the <code>wp_title()</code> tag in the header</p>\n\n<p>The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p>As a solution, copy the parent theme <code>header.php</code> to your child theme and simply remove the <code>wp_title()</code> function from the child theme <code>header.php</code></p>\n\n<p>Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (<em>Taken from the codex</em>)</p>\n\n<pre><code> if ( ! function_exists( '_wp_render_title_tag' ) ) {\n function theme_slug_render_title() \n {\n ?&gt;\n &lt;title&gt;\n &lt;?php wp_title( '|', true, 'right' ); ?&gt;\n &lt;/title&gt;\n &lt;?php\n }\n add_action( 'wp_head', 'theme_slug_render_title' );\n}\n</code></pre>\n" }, { "answer_id": 216544, "author": "vunguyen", "author_id": 88022, "author_profile": "https://wordpress.stackexchange.com/users/88022", "pm_score": -1, "selected": false, "text": "<p>At <code>function.php</code> file in your theme comment code</p>\n\n<pre><code>//add_theme_support( 'title-tag' );\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182006", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56789/" ]
Similar questions have been asked before, but no answer suits well. I have: `site.com/parent-page/child-page` and would like to have: `site.com/child-page` So I want to exclusively have permalinks with depth 1, without using the custom menu but still "hierarchizing" my pages in the admin all pages view and with parent/order in page attributes. The solution also needs to work automatically, so not changing permalinks on each page with the plugin "Custom Permalinks". This is what I need, and I am sure it is possible with a few lines of code in the `functions.php`, which I have found elsewhere but only for posts to remove the category, but not working for pages to remove the parent. This is such code, that maybe can be changed to work for *pages*? ``` add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 ); function remove_parent_cats_from_link( $permalink, $post, $leavename ) { $cats = get_the_category( $post->ID ); if ( $cats ) { // Make sure we use the same start cat as the permalink generator usort( $cats, '_usort_terms_by_ID' ); // order by ID $category = $cats[0]->slug; if ( $parent = $cats[0]->parent ) { // If there are parent categories, collect them and replace them in the link $parentcats = get_category_parents( $parent, false, '/', true ); // str_replace() is not the best solution if you can have duplicates: // example.com/luxemburg/luxemburg/ will be stripped down to example.com/ // But if you don't expect that, it should work $permalink = str_replace( $parentcats, '', $permalink ); } } return $permalink; } ```
The two title tags can be explained as that you are using a theme that is written for Wordpress4.1 and actually is using 4.1. As from 4.1 you don't need to call [`wp_title()`](https://codex.wordpress.org/Function_Reference/wp_title) in the head any more, you can make use of new `title_tag` theme support tag which automatically adds the `wp_title()` tag in the header The parent theme you are using are most probably already doing this. Look in your functions.php for this line of code ``` add_theme_support( 'title-tag' ); ``` As a solution, copy the parent theme `header.php` to your child theme and simply remove the `wp_title()` function from the child theme `header.php` Here is also a great function to keep in mind for backwards compatibility and is useful for parent theme developers: (*Taken from the codex*) ``` if ( ! function_exists( '_wp_render_title_tag' ) ) { function theme_slug_render_title() { ?> <title> <?php wp_title( '|', true, 'right' ); ?> </title> <?php } add_action( 'wp_head', 'theme_slug_render_title' ); } ```
182,015
<p>My goal is to have the slug www.domain.com/resources used by a <strong>Page Template</strong> rather than an <strong>Archive Page</strong>, and have single CPT posts as children of that slug, such as <code>www.domain.com/resources/post</code>.</p> <p>Solution I thought would work:</p> <p>I created a new Page in Wordpress and gave it a custom page template. I'm also registering my custom post type as follows. Pay special attention to <em>has_archive</em> and <em>rewrite</em>:</p> <pre><code>function bb_resources() { register_post_type( 'resources', array( 'labels' =&gt; array( 'name' =&gt; 'Resources', 'singular_name' =&gt; 'Resource', ), 'taxonomies' =&gt; array('resources_cat'), 'public' =&gt; true, 'has_archive' =&gt; false, 'show_ui' =&gt; true, 'supports' =&gt; array( 'title', 'editor' ), 'rewrite' =&gt; array('slug'=&gt;'resources', 'with_front'=&gt;false), ) ); } </code></pre> <p>This, however, creates a 404 on the single post pages.</p> <p>I'm stumped, please advise!</p>
[ { "answer_id": 221099, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 5, "selected": true, "text": "<p>Since WordPress version 4.4 the hook <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow\"><code>'theme_page_templates'</code></a> allows to set arbitrary page templates.</p>\n\n<p>It means that it's possible to show arbitrary values in the \"Page Template\" menu of the page edit screen, and when selected, the value will be stored in the page template meta for the page.</p>\n\n<p>This means that you can \"automagically\" create a page template for any of the CPT's registered.</p>\n\n<h1>Setup page templates</h1>\n\n<p>The code would look something like this:</p>\n\n<pre><code>add_action( 'current_screen', function( \\WP_Screen $screen ) {\n if( 'page' !== $screen-&gt;id || 'post' !== $screen-&gt;base ) {\n return;\n }\n\n // retrieve CPT objects with archive\n $types = get_post_types( ['has_archive' =&gt; true], 'objects' );\n\n // store CPT slug and labels in an array\n $menu = array();\n foreach( $types as $cpt ) {\n $menu[ $cpt-&gt;name ] = 'Archive: ' . $cpt-&gt;label;\n }\n\n // merge with page templates\n $menu and add_filter(\n 'theme_page_templates',\n function( array $templates ) use ( $menu ) {\n $templates = array_merge( $templates, $menu );\n return $templates;\n }\n );\n} );\n</code></pre>\n\n<p>With this code in place, assuming you have registered a post type <code>resources</code> with <code>has_archive</code> set to <code>true</code>, when you create or edit a page, you'll see in the \"Page Template\" dropdown a page template named <code>Archive: Resources</code>.</p>\n\n<p>You can choose that template when creating a page, you want to use to display your <code>resources</code> posts.</p>\n\n<h1>Redirect direct page access</h1>\n\n<p>Since this page is an archive more than a page, you could use some code to redirect users to the actual CPT's archive when the page is accessed:</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n if( is_page_template() ) {\n\n // current page templates\n $template = get_page_template_slug( get_queried_object_id() );\n\n // array of CPT names, filtering the ones with archives\n $types = get_post_types( array( 'has_archive' =&gt; true ), 'names' );\n\n // if the current template is one of the CPT, redirect\n if( in_array( $template, $types, true ) ) {\n wp_safe_redirect( get_post_type_archive_link( $template ) );\n exit();\n }\n }\n} );\n</code></pre>\n\n<h1>Getting page data</h1>\n\n<p>You probably want to use content and title from that page when viewing the article.</p>\n\n<p>So, let's write a function that let's you get the page for a specific post type.</p>\n\n<pre><code>function get_archive_page( $post_type = '' ) {\n\n // if no CPT given, let's use the current main query to get it\n if( ! $post_type ) {\n global $wp_query;\n $query_var = ( array ) $wp_query-&gt;get( 'post_type' );\n $post_type = reset($query_var);\n }\n\n // if we have a valid post type\n if( post_type_exists( $post_type ) ) {\n\n // let's query the first page that has a page template\n // named after the the post type\n $posts = get_posts( array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array( array( \n 'key' =&gt; '_wp_page_template',\n 'value' =&gt; $post_type\n ) )\n ) );\n\n // if we have results, return first (and only) post object\n if( $posts ) {\n return reset($posts);\n }\n }\n}\n</code></pre>\n\n<p>You could use the function above to write two additional functions to get the title and the content of the page:</p>\n\n<pre><code>function get_archive_page_title( $post_type = '' ) {\n $page = get_archive_page( $post_type );\n\n return ( $page ) ? get_the_title( $page ) : '';\n} \n\nfunction get_archive_page_content( $post_type = '' ) {\n $page = get_archive_page( $post_type );\n $content = '';\n\n if( $page ) {\n setup_postdata( $page );\n ob_start();\n the_content();\n $content = ob_get_clean();\n wp_reset_postdata();\n }\n\n return $content;\n}\n\nfunction the_archive_page_title() {\n echo get_archive_page_title();\n}\n\nfunction the_archive_page_content() {\n echo get_archive_page_content();\n}\n</code></pre>\n\n<p>Function names should make clear what they do.</p>\n\n<p>You could also write functions like <code>get_archive_page_meta()</code> if you need custom fields.</p>\n\n<h1>In the archive template</h1>\n\n<p>Now, in the <code>archive.php</code> (or in the <code>archive-resources.php</code>) template, you can make use of the above functions to show title and content of the archive page.</p>\n\n<p>It will look something like:</p>\n\n<pre><code>&lt;h1&gt;&lt;?php the_archive_page_title(); ?&gt;&lt;/h1&gt;\n\n&lt;div&gt;&lt;?php the_archive_page_content(); ?&gt;&lt;/div&gt;\n\n&lt;?php\n while( have_posts() ) : the_post();\n // loop stuff here\n endwhile;\n?&gt;\n</code></pre>\n\n<p>This way your CPT archive url will be <code>example.com/resources/</code> and your single CPT url will be <code>example.com/resources/post-name/</code> just like you want.</p>\n\n<p>At the same time you'll be able to write content and title (and custom fields, if you want) specific for the post type.</p>\n\n<p>Also, consider this method is reusable for any post type, you have or might use in the future.</p>\n" }, { "answer_id": 221106, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/users/35541/gmazzap\">gmazzap</a>'s <a href=\"https://wordpress.stackexchange.com/a/221099/47733\">answer</a> is great! I'd just like to add that since 4.1 there are two new functions that perfectly fit that use case: <a href=\"https://developer.wordpress.org/reference/functions/the_archive_title/\" rel=\"nofollow noreferrer\"><code>the_archive_title</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/the_archive_description/\" rel=\"nofollow noreferrer\"><code>the_archive_description</code></a>. For themes that already use those (like Twenty Fifteen) you can skip the last part where you edit the theme template and do this instead:</p>\n\n<h2>Add data through filters</h2>\n\n<pre><code>add_filter( 'get_the_archive_title', function( $title ) {\n if( is_post_type_archive() ) { \n $page = get_archive_page( $post_type ); // Function Found in @gmazzap's answer\n $title = $page ? get_the_title( $page ) : $title;\n }\n\n return $title;\n} );\n\nadd_filter( 'get_the_archive_description', function( $content ) {\n if( is_post_type_archive() ) {\n $page = get_archive_page( $post_type ); // Function Found in @gmazzap's answer\n $content = '';\n\n if( $page ) {\n setup_postdata( $page );\n ob_start();\n the_content();\n $content = ob_get_clean();\n wp_reset_postdata();\n }\n\n $content = ( $content !== '' ) ? get_the_title( $page ) : $content;\n }\n\n return $content;\n} );\n</code></pre>\n" }, { "answer_id": 221129, "author": "Will", "author_id": 44795, "author_profile": "https://wordpress.stackexchange.com/users/44795", "pm_score": 0, "selected": false, "text": "<p>My own method for this feels decidedly caveman after reading the previous two answers but I'll share it anyway because while it's not nearly as robust, it's incredibly easy to set up. It also makes it dead simple for content authors to know where to edit the 'overview' content for a given archive in a largely page based/CMS style site structure.</p>\n\n<p>For a post_type called <code>region</code> I'd register it along with an actual WP page called <code>regions</code>. </p>\n\n<p>Create a template called <code>page-regions.php</code> (or whatever strategy you want to use to connect it that page) and do a custom loop to pull all of the region post_types. If you use template parts for your templates, it's easy enough to include the page header and main body as well so your code remains DRY. It's also really easy to customize because there's <em>always</em> that one post_type. :)</p>\n\n<p>With this, the URLs will be <em>slightly</em> different than what you asked for: </p>\n\n<p><a href=\"http://example.com/regions\" rel=\"nofollow\">http://example.com/regions</a> for the page with the archive posts and<br>\n<a href=\"http://example.com/region/africa\" rel=\"nofollow\">http://example.com/region/africa</a> or<br>\n<a href=\"http://example.com/region/asia\" rel=\"nofollow\">http://example.com/region/asia</a> for a single CPT view.</p>\n\n<p>But to me, <code>/region/africa</code> actually makes more sense than <code>/regions/africa</code> though that might be driven by working on rails/cakephp sites where it's the norm. <code>/region</code> alone winds up being a post_type=region archive (depending on how you set up the post_type) without the overview content from the page but I simply don't link to it. If URL bar surfers get there, no big deal.</p>\n\n<p>Slight, secondary bonus: you can make the URL for the overview/archive page whatever you want, say <code>/regions-of-the-world</code>.</p>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54137/" ]
My goal is to have the slug www.domain.com/resources used by a **Page Template** rather than an **Archive Page**, and have single CPT posts as children of that slug, such as `www.domain.com/resources/post`. Solution I thought would work: I created a new Page in Wordpress and gave it a custom page template. I'm also registering my custom post type as follows. Pay special attention to *has\_archive* and *rewrite*: ``` function bb_resources() { register_post_type( 'resources', array( 'labels' => array( 'name' => 'Resources', 'singular_name' => 'Resource', ), 'taxonomies' => array('resources_cat'), 'public' => true, 'has_archive' => false, 'show_ui' => true, 'supports' => array( 'title', 'editor' ), 'rewrite' => array('slug'=>'resources', 'with_front'=>false), ) ); } ``` This, however, creates a 404 on the single post pages. I'm stumped, please advise!
Since WordPress version 4.4 the hook [`'theme_page_templates'`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) allows to set arbitrary page templates. It means that it's possible to show arbitrary values in the "Page Template" menu of the page edit screen, and when selected, the value will be stored in the page template meta for the page. This means that you can "automagically" create a page template for any of the CPT's registered. Setup page templates ==================== The code would look something like this: ``` add_action( 'current_screen', function( \WP_Screen $screen ) { if( 'page' !== $screen->id || 'post' !== $screen->base ) { return; } // retrieve CPT objects with archive $types = get_post_types( ['has_archive' => true], 'objects' ); // store CPT slug and labels in an array $menu = array(); foreach( $types as $cpt ) { $menu[ $cpt->name ] = 'Archive: ' . $cpt->label; } // merge with page templates $menu and add_filter( 'theme_page_templates', function( array $templates ) use ( $menu ) { $templates = array_merge( $templates, $menu ); return $templates; } ); } ); ``` With this code in place, assuming you have registered a post type `resources` with `has_archive` set to `true`, when you create or edit a page, you'll see in the "Page Template" dropdown a page template named `Archive: Resources`. You can choose that template when creating a page, you want to use to display your `resources` posts. Redirect direct page access =========================== Since this page is an archive more than a page, you could use some code to redirect users to the actual CPT's archive when the page is accessed: ``` add_action( 'template_redirect', function() { if( is_page_template() ) { // current page templates $template = get_page_template_slug( get_queried_object_id() ); // array of CPT names, filtering the ones with archives $types = get_post_types( array( 'has_archive' => true ), 'names' ); // if the current template is one of the CPT, redirect if( in_array( $template, $types, true ) ) { wp_safe_redirect( get_post_type_archive_link( $template ) ); exit(); } } } ); ``` Getting page data ================= You probably want to use content and title from that page when viewing the article. So, let's write a function that let's you get the page for a specific post type. ``` function get_archive_page( $post_type = '' ) { // if no CPT given, let's use the current main query to get it if( ! $post_type ) { global $wp_query; $query_var = ( array ) $wp_query->get( 'post_type' ); $post_type = reset($query_var); } // if we have a valid post type if( post_type_exists( $post_type ) ) { // let's query the first page that has a page template // named after the the post type $posts = get_posts( array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'menu_order', 'order' => 'ASC', 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => $post_type ) ) ) ); // if we have results, return first (and only) post object if( $posts ) { return reset($posts); } } } ``` You could use the function above to write two additional functions to get the title and the content of the page: ``` function get_archive_page_title( $post_type = '' ) { $page = get_archive_page( $post_type ); return ( $page ) ? get_the_title( $page ) : ''; } function get_archive_page_content( $post_type = '' ) { $page = get_archive_page( $post_type ); $content = ''; if( $page ) { setup_postdata( $page ); ob_start(); the_content(); $content = ob_get_clean(); wp_reset_postdata(); } return $content; } function the_archive_page_title() { echo get_archive_page_title(); } function the_archive_page_content() { echo get_archive_page_content(); } ``` Function names should make clear what they do. You could also write functions like `get_archive_page_meta()` if you need custom fields. In the archive template ======================= Now, in the `archive.php` (or in the `archive-resources.php`) template, you can make use of the above functions to show title and content of the archive page. It will look something like: ``` <h1><?php the_archive_page_title(); ?></h1> <div><?php the_archive_page_content(); ?></div> <?php while( have_posts() ) : the_post(); // loop stuff here endwhile; ?> ``` This way your CPT archive url will be `example.com/resources/` and your single CPT url will be `example.com/resources/post-name/` just like you want. At the same time you'll be able to write content and title (and custom fields, if you want) specific for the post type. Also, consider this method is reusable for any post type, you have or might use in the future.
182,017
<p>I have one default page template that I wish to use for two scenarios. I'd prefer to use only one page template for the sake of simplicity for my client. </p> <p>Here's what I'm trying to accomplish: </p> <pre><code>if parent_page OR if child-page without children { display full-width-layout } if child page with children or if grandchild page { display sidebar-menu-layout } </code></pre> <p>Is this possible? </p> <p>This is what I've tried so far:</p> <pre><code>if( is_page() &amp;&amp; $post-&gt;post_parent &gt; 0 ) { //display sidebar-menu-layout } else { //display full-width-layout } </code></pre> <p>It works so far as on top level pages, it displays full-width-layouts. But, what can I do to make sure that the sidebar-menu-layout is displayed on child-pages with children and on grandchile pages only? And for child-pages with no children, to display the full-width-layout. </p> <p>Thanks in advance. I'm sure it has a simple solution, I'm just relatively new to WP so still trying to figure out what can and cannot be done.</p>
[ { "answer_id": 182036, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 2, "selected": false, "text": "<pre><code>Level-0\n--Level-1\n----Level-2\n------Level-3\n----Levelanother-2\n--Levelanother-1\n</code></pre>\n\n<p>check whether page is top level page (it may have children or not) ?</p>\n\n<p><code>$post-&gt;$post_parent == 0</code> or is empty <code>get_post_ancestors( $post )</code> returns only Level-0 Pages.</p>\n\n<p>Is a child page and is a Level-1 page or Levelanother-1 only ?</p>\n\n<p><code>$post-&gt;$post_parent &gt; 0</code> or is not empty <code>get_post_ancestors( $post )</code> and is empty <code>get_post_ancestors( $post-&gt;post_parent )</code> </p>\n\n<p>Is level-1 page but doesn't have children like Levelanother-1 page ?</p>\n\n<p><code>$post-&gt;$post_parent &gt; 0</code> or is not empty <code>get_post_ancestors( $post )</code> and is empty <code>get_post_ancestors( $post-&gt;post_parent )</code> and <code>count(get_children( $post -&gt;ID, 'ARRAY_A' )) == 0</code> ..</p>\n\n<p>I didn't check this yet..but it should work fine. You can also play with get_page_children() and <a href=\"https://developer.wordpress.org/reference/functions/get_page_children/\" rel=\"noreferrer\">get_posts() </a></p>\n" }, { "answer_id": 182289, "author": "laura.f", "author_id": 51337, "author_profile": "https://wordpress.stackexchange.com/users/51337", "pm_score": 4, "selected": true, "text": "<p>Before reading the solution Bravokeyl provided I had finally, through trial and error, come up with a solution that worked for me. I'm not sure which is the better of the two, or the most correct, I only know that mine worked for me, for the problem I had. </p>\n\n<p>This is the code I used to display full-width layout or sidebar-menu layout:</p>\n\n<pre><code>if( is_page() &amp;&amp; $post-&gt;post_parent &gt; 0 ) { \n // post has parents\n\n $children = get_pages('child_of='.$post-&gt;ID);\n if( count( $children ) != 0 ) {\n // display sidebar-menu layout\n }\n\n $parent = get_post_ancestors($post-&gt;ID);\n if( count( $children ) &lt;= 0 &amp;&amp; empty($parent[1]) ) {\n // display full-width layout\n } elseif ( count( $children ) &lt;= 0 &amp;&amp; !empty($parent[1]) ) {\n // display sidebar-menu layout\n }\n\n} else {\n // post has no parents\n // display full-width layout\n}\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51337/" ]
I have one default page template that I wish to use for two scenarios. I'd prefer to use only one page template for the sake of simplicity for my client. Here's what I'm trying to accomplish: ``` if parent_page OR if child-page without children { display full-width-layout } if child page with children or if grandchild page { display sidebar-menu-layout } ``` Is this possible? This is what I've tried so far: ``` if( is_page() && $post->post_parent > 0 ) { //display sidebar-menu-layout } else { //display full-width-layout } ``` It works so far as on top level pages, it displays full-width-layouts. But, what can I do to make sure that the sidebar-menu-layout is displayed on child-pages with children and on grandchile pages only? And for child-pages with no children, to display the full-width-layout. Thanks in advance. I'm sure it has a simple solution, I'm just relatively new to WP so still trying to figure out what can and cannot be done.
Before reading the solution Bravokeyl provided I had finally, through trial and error, come up with a solution that worked for me. I'm not sure which is the better of the two, or the most correct, I only know that mine worked for me, for the problem I had. This is the code I used to display full-width layout or sidebar-menu layout: ``` if( is_page() && $post->post_parent > 0 ) { // post has parents $children = get_pages('child_of='.$post->ID); if( count( $children ) != 0 ) { // display sidebar-menu layout } $parent = get_post_ancestors($post->ID); if( count( $children ) <= 0 && empty($parent[1]) ) { // display full-width layout } elseif ( count( $children ) <= 0 && !empty($parent[1]) ) { // display sidebar-menu layout } } else { // post has no parents // display full-width layout } ```
182,025
<p>I have a simple PHP script that I want to load whenever someone lands on a homepage. It is fetching data from another service and then I have to display it in a container on the homepage. </p> <p>I was looking at options on how to enable PHP code in an HTML box that is provided by Wordpress. </p> <p>I found several plugins that claim to enable parsing and execution of PHP scripts inside the HTML box/text-box. However, none of them are working for me. I tried <a href="https://wordpress.org/plugins/php-code-widget/" rel="nofollow">PHP Code Widget</a> in the last and I noticed that somehow my PHP code is automatically converted to HTML comments. See example below -- </p> <p>After activating the plugin, I entered this in the text view (I tried visual view as well) of the HTML box. </p> <pre><code>&lt;?php echo "Hello World!"; ?&gt; </code></pre> <p>However, nothing showed up on the page. When I did an inspect element, it showed me something like this -- </p> <pre><code>&lt;div class="htmlbox-content"&gt; &lt;!--?php echo "Hello world!"; ?--&gt; &lt;/div&gt; </code></pre> <p>It had automatically converted the opening bracket of my PHP code to an HTML comment. I tried editing it inline, however whenever I remove the "--", they come back again i.e. it doesn't let me alter them. </p> <p>I am not 100% sure if I am doing it right. However, I could not find anything wrong in the steps I have been performing. How do I fix this?</p> <p>Also, I am aware that enabling PHP code in HTML/textbox is not a great solution. However, I could not find anything that points me to how I can achieve the same goal otherwise. Any tutorial/pointers otherwise would be really appreciated!</p> <p><strong>Some details:</strong></p> <p>I am on a network enabled Wordpress 3.9.2</p> <p>I tried enabling just for the website as well as enabling it across the network. Same result in both scenarios. </p> <p>The plugin is compatible for versions 2.8 and higher and supported uptil 4.0.1, hence should ideally work. I have also tried other plugins with different variations on what they support, however none of them seem to work. </p>
[ { "answer_id": 182026, "author": "Gabriel", "author_id": 54569, "author_profile": "https://wordpress.stackexchange.com/users/54569", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://wordpress.org/plugins/php-code-widget/\" rel=\"nofollow\">PHP Code Widget</a> does not modify the Text or Visual editor box, or the standard \"Text\" widget; it adds a \"PHP Code\" widget, which you'll find under Appearance > Widgets > Available Widgets. </p>\n\n<p>If you want to display your script within the body of the post or page, you should create a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode</a>. The basic example from the API would work for \"Hello World\"; you would add this to your theme's <code>functions.php</code> (or better yet create a plugin):</p>\n\n<pre><code>function foobar_func( $atts ){\n return \"Hello World\";\n}\nadd_shortcode( 'foobar', 'foobar_func' );\n</code></pre>\n\n<p>Then in your post or page, type the <code>[foobar]</code> shortcode to display your script. Add the code for your custom PHP script, and <code>return</code> the final output to be displayed (you don't want to <code>echo</code> from within the shortcode function). </p>\n\n<p>Or, creating the shortcode in a plugin will keep it available even if you switch themes:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: wpse-182025\n * Description: Creates [wpse-182025] shortcode to execute custom PHP script on posts, pages, etc\n * Plugin URI: http://wordpress.stackexchange.com/a/182026/54569\n * Version: 1.0\n */\n\nfunction wpse_182025_func() {\n // Add your custom PHP script\n $output = \"Hello World\";\n return $output;\n}\nadd_shortcode( 'wpse-182025', 'wpse_182025_func' );\n?&gt;\n</code></pre>\n\n<p>Add the above code to <code>/wp-content/plugins/wpse-182025/wpse-182025.php</code>, OR create the <code>/wpse-182025/wpse-182025.php</code> folder and file locally, add to a zip file, and upload using Plugins > Add New > Uploads. Display the shortcode with <code>[wpse-182025]</code>. You can modify any of the example plugin code as needed. </p>\n" }, { "answer_id": 182030, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>As you have already understated, running executable PHP inside a text box is not a good idea. It isn't only just not a good idea, but a terrible idea. This creates a loop hole in your security which can be very easily exploited by a hacker.</p>\n\n<p>I would suggest writing your own custom widget for this functionality. It is really easy adding a custom sidebar to the top of your index.php for that specific purpose into which you can just simply drop your custom widget into. Have a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\"><code>register_sidebar()</code></a>. There are also plenty tutorials out there on this specific subject on how to add a custom sidebar in your theme</p>\n\n<p>As for the widget, look at the <a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">Widget API</a>. I (with some assistance from @birgire ;-)) have also done a <a href=\"https://wordpress.stackexchange.com/a/181350/31545\">recent widget which displays categories</a> which you can use as a base for your widget. You can simply code your custom code from the selected service into the <code>widget</code> method. You can make this very dynamic. </p>\n\n<p>Here is basic skeleton you can use. To make this work, you only need to replace <code>// ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END</code> with your custom php code which is inside the <code>widget()</code> method (<em>NOTE: Requires PHP 5.4+</em>)</p>\n\n<pre><code>class Custom_Services extends WP_Widget \n{\n\n public function __construct() \n {\n parent::__construct(\n 'widget_custom_service', \n _x( 'Custom Service Widget', 'Custom Service Widget' ), \n [ 'description' =&gt; __( 'Displays information from a custom service.' ) ] \n );\n $this-&gt;alt_option_name = 'widget_custom_service';\n\n add_action( 'save_post', [$this, 'flush_widget_cache'] );\n add_action( 'deleted_post', [$this, 'flush_widget_cache'] );\n add_action( 'switch_theme', [$this, 'flush_widget_cache'] );\n }\n\n public function widget( $args, $instance ) \n {\n $cache = [];\n if ( ! $this-&gt;is_preview() ) {\n $cache = wp_cache_get( 'widget_services', 'widget' );\n }\n\n if ( ! is_array( $cache ) ) {\n $cache = [];\n }\n\n if ( ! isset( $args['widget_id'] ) ) {\n $args['widget_id'] = $this-&gt;id;\n }\n\n if ( isset( $cache[ $args['widget_id'] ] ) ) {\n echo $cache[ $args['widget_id'] ];\n return;\n }\n\n ob_start();\n\n $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' );\n /** This filter is documented in wp-includes/default-widgets.php */\n $title = apply_filters( 'widget_title', $title, $instance, $this-&gt;id_base );\n\n // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END\n\n echo $args['after_widget']; \n\n if ( ! $this-&gt;is_preview() ) {\n $cache[ $args['widget_id'] ] = ob_get_flush();\n wp_cache_set( 'widget_services', $cache, 'widget' );\n } else {\n ob_end_flush();\n }\n }\n\n public function update( $new_instance, $old_instance ) \n {\n $instance = $old_instance;\n $instance['title'] = strip_tags( $new_instance['title'] );\n $this-&gt;flush_widget_cache();\n\n $alloptions = wp_cache_get( 'alloptions', 'options' );\n if ( isset($alloptions['widget_custom_service']) )\n delete_option('widget_custom_service');\n\n return $instance;\n }\n\n public function flush_widget_cache() \n {\n wp_cache_delete('widget_services', 'widget');\n }\n\n public function form( $instance ) \n {\n\n $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';\n ?&gt;\n\n &lt;p&gt;\n &lt;label for=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\"&gt;&lt;?php _e( 'Title:' ); ?&gt;&lt;/label&gt;\n &lt;input class=\"widefat\" id=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;\" type=\"text\" value=\"&lt;?php echo $title; ?&gt;\" /&gt;\n &lt;/p&gt;\n\n &lt;?php\n }\n\n}\n\nadd_action( 'widgets_init', function () \n{\n register_widget( 'Custom_Services' );\n});\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69485/" ]
I have a simple PHP script that I want to load whenever someone lands on a homepage. It is fetching data from another service and then I have to display it in a container on the homepage. I was looking at options on how to enable PHP code in an HTML box that is provided by Wordpress. I found several plugins that claim to enable parsing and execution of PHP scripts inside the HTML box/text-box. However, none of them are working for me. I tried [PHP Code Widget](https://wordpress.org/plugins/php-code-widget/) in the last and I noticed that somehow my PHP code is automatically converted to HTML comments. See example below -- After activating the plugin, I entered this in the text view (I tried visual view as well) of the HTML box. ``` <?php echo "Hello World!"; ?> ``` However, nothing showed up on the page. When I did an inspect element, it showed me something like this -- ``` <div class="htmlbox-content"> <!--?php echo "Hello world!"; ?--> </div> ``` It had automatically converted the opening bracket of my PHP code to an HTML comment. I tried editing it inline, however whenever I remove the "--", they come back again i.e. it doesn't let me alter them. I am not 100% sure if I am doing it right. However, I could not find anything wrong in the steps I have been performing. How do I fix this? Also, I am aware that enabling PHP code in HTML/textbox is not a great solution. However, I could not find anything that points me to how I can achieve the same goal otherwise. Any tutorial/pointers otherwise would be really appreciated! **Some details:** I am on a network enabled Wordpress 3.9.2 I tried enabling just for the website as well as enabling it across the network. Same result in both scenarios. The plugin is compatible for versions 2.8 and higher and supported uptil 4.0.1, hence should ideally work. I have also tried other plugins with different variations on what they support, however none of them seem to work.
As you have already understated, running executable PHP inside a text box is not a good idea. It isn't only just not a good idea, but a terrible idea. This creates a loop hole in your security which can be very easily exploited by a hacker. I would suggest writing your own custom widget for this functionality. It is really easy adding a custom sidebar to the top of your index.php for that specific purpose into which you can just simply drop your custom widget into. Have a look at [`register_sidebar()`](https://codex.wordpress.org/Function_Reference/register_sidebar). There are also plenty tutorials out there on this specific subject on how to add a custom sidebar in your theme As for the widget, look at the [Widget API](https://codex.wordpress.org/Widgets_API). I (with some assistance from @birgire ;-)) have also done a [recent widget which displays categories](https://wordpress.stackexchange.com/a/181350/31545) which you can use as a base for your widget. You can simply code your custom code from the selected service into the `widget` method. You can make this very dynamic. Here is basic skeleton you can use. To make this work, you only need to replace `// ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END` with your custom php code which is inside the `widget()` method (*NOTE: Requires PHP 5.4+*) ``` class Custom_Services extends WP_Widget { public function __construct() { parent::__construct( 'widget_custom_service', _x( 'Custom Service Widget', 'Custom Service Widget' ), [ 'description' => __( 'Displays information from a custom service.' ) ] ); $this->alt_option_name = 'widget_custom_service'; add_action( 'save_post', [$this, 'flush_widget_cache'] ); add_action( 'deleted_post', [$this, 'flush_widget_cache'] ); add_action( 'switch_theme', [$this, 'flush_widget_cache'] ); } public function widget( $args, $instance ) { $cache = []; if ( ! $this->is_preview() ) { $cache = wp_cache_get( 'widget_services', 'widget' ); } if ( ! is_array( $cache ) ) { $cache = []; } if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } if ( isset( $cache[ $args['widget_id'] ] ) ) { echo $cache[ $args['widget_id'] ]; return; } ob_start(); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' ); /** This filter is documented in wp-includes/default-widgets.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END echo $args['after_widget']; if ( ! $this->is_preview() ) { $cache[ $args['widget_id'] ] = ob_get_flush(); wp_cache_set( 'widget_services', $cache, 'widget' ); } else { ob_end_flush(); } } public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); $this->flush_widget_cache(); $alloptions = wp_cache_get( 'alloptions', 'options' ); if ( isset($alloptions['widget_custom_service']) ) delete_option('widget_custom_service'); return $instance; } public function flush_widget_cache() { wp_cache_delete('widget_services', 'widget'); } public function form( $instance ) { $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : ''; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /> </p> <?php } } add_action( 'widgets_init', function () { register_widget( 'Custom_Services' ); }); ```
182,040
<p>I have this code fragment in my codebase:</p> <pre><code> foreach($this-&gt;adverisers as $adveriser) { $this-&gt;data[$adveriser-&gt;name]['image'] = bfi_thumb(get_post_meta($adveriser-&gt;ID, 'ss_advertisers_cats_image', true ), $this-&gt;imgDimensions ); $this-&gt;data[$adveriser-&gt;name]['description'] = get_post_meta($adveriser-&gt;ID, 'ss_advertisers_cats_description', true ); $this-&gt;data[$adveriser-&gt;name]['advertiser'] = $wpdb-&gt;get_results( "SELECT DISTINCT * FROM {$wpdb-&gt;posts} WHERE(post_type='brands' OR post_type='boutiques') AND post_author='{$adveriser-&gt;post_author}' ", OBJECT ); $this-&gt;data[$adveriser-&gt;name]['advertiserRedirectionLink'] = get_post_meta($adveriser-&gt;ID, 'ss_advertisers_cats_link', true ); } </code></pre> <p>The loop builds a custom array of data for later display on the site. As you can see, there is a total of four queries to the database executed on each iteration of the loop. This is probably far from optimal performance-wise as, in my view, this is an example of <a href="https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/" rel="nofollow"><em>N+1 Query problem</em></a>. </p> <p>Is there any straightforward solution that would bring siginificant performance increase to this code? Or is my only option crafting a complex, muli-join SQL query with <code>$wpdb</code> to get all the required data in one/two queries, or .. maybe the presented code is not so bad after all and would not hinder performance so considerably</p>
[ { "answer_id": 182026, "author": "Gabriel", "author_id": 54569, "author_profile": "https://wordpress.stackexchange.com/users/54569", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://wordpress.org/plugins/php-code-widget/\" rel=\"nofollow\">PHP Code Widget</a> does not modify the Text or Visual editor box, or the standard \"Text\" widget; it adds a \"PHP Code\" widget, which you'll find under Appearance > Widgets > Available Widgets. </p>\n\n<p>If you want to display your script within the body of the post or page, you should create a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode</a>. The basic example from the API would work for \"Hello World\"; you would add this to your theme's <code>functions.php</code> (or better yet create a plugin):</p>\n\n<pre><code>function foobar_func( $atts ){\n return \"Hello World\";\n}\nadd_shortcode( 'foobar', 'foobar_func' );\n</code></pre>\n\n<p>Then in your post or page, type the <code>[foobar]</code> shortcode to display your script. Add the code for your custom PHP script, and <code>return</code> the final output to be displayed (you don't want to <code>echo</code> from within the shortcode function). </p>\n\n<p>Or, creating the shortcode in a plugin will keep it available even if you switch themes:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: wpse-182025\n * Description: Creates [wpse-182025] shortcode to execute custom PHP script on posts, pages, etc\n * Plugin URI: http://wordpress.stackexchange.com/a/182026/54569\n * Version: 1.0\n */\n\nfunction wpse_182025_func() {\n // Add your custom PHP script\n $output = \"Hello World\";\n return $output;\n}\nadd_shortcode( 'wpse-182025', 'wpse_182025_func' );\n?&gt;\n</code></pre>\n\n<p>Add the above code to <code>/wp-content/plugins/wpse-182025/wpse-182025.php</code>, OR create the <code>/wpse-182025/wpse-182025.php</code> folder and file locally, add to a zip file, and upload using Plugins > Add New > Uploads. Display the shortcode with <code>[wpse-182025]</code>. You can modify any of the example plugin code as needed. </p>\n" }, { "answer_id": 182030, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>As you have already understated, running executable PHP inside a text box is not a good idea. It isn't only just not a good idea, but a terrible idea. This creates a loop hole in your security which can be very easily exploited by a hacker.</p>\n\n<p>I would suggest writing your own custom widget for this functionality. It is really easy adding a custom sidebar to the top of your index.php for that specific purpose into which you can just simply drop your custom widget into. Have a look at <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\"><code>register_sidebar()</code></a>. There are also plenty tutorials out there on this specific subject on how to add a custom sidebar in your theme</p>\n\n<p>As for the widget, look at the <a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">Widget API</a>. I (with some assistance from @birgire ;-)) have also done a <a href=\"https://wordpress.stackexchange.com/a/181350/31545\">recent widget which displays categories</a> which you can use as a base for your widget. You can simply code your custom code from the selected service into the <code>widget</code> method. You can make this very dynamic. </p>\n\n<p>Here is basic skeleton you can use. To make this work, you only need to replace <code>// ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END</code> with your custom php code which is inside the <code>widget()</code> method (<em>NOTE: Requires PHP 5.4+</em>)</p>\n\n<pre><code>class Custom_Services extends WP_Widget \n{\n\n public function __construct() \n {\n parent::__construct(\n 'widget_custom_service', \n _x( 'Custom Service Widget', 'Custom Service Widget' ), \n [ 'description' =&gt; __( 'Displays information from a custom service.' ) ] \n );\n $this-&gt;alt_option_name = 'widget_custom_service';\n\n add_action( 'save_post', [$this, 'flush_widget_cache'] );\n add_action( 'deleted_post', [$this, 'flush_widget_cache'] );\n add_action( 'switch_theme', [$this, 'flush_widget_cache'] );\n }\n\n public function widget( $args, $instance ) \n {\n $cache = [];\n if ( ! $this-&gt;is_preview() ) {\n $cache = wp_cache_get( 'widget_services', 'widget' );\n }\n\n if ( ! is_array( $cache ) ) {\n $cache = [];\n }\n\n if ( ! isset( $args['widget_id'] ) ) {\n $args['widget_id'] = $this-&gt;id;\n }\n\n if ( isset( $cache[ $args['widget_id'] ] ) ) {\n echo $cache[ $args['widget_id'] ];\n return;\n }\n\n ob_start();\n\n $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' );\n /** This filter is documented in wp-includes/default-widgets.php */\n $title = apply_filters( 'widget_title', $title, $instance, $this-&gt;id_base );\n\n // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END\n\n echo $args['after_widget']; \n\n if ( ! $this-&gt;is_preview() ) {\n $cache[ $args['widget_id'] ] = ob_get_flush();\n wp_cache_set( 'widget_services', $cache, 'widget' );\n } else {\n ob_end_flush();\n }\n }\n\n public function update( $new_instance, $old_instance ) \n {\n $instance = $old_instance;\n $instance['title'] = strip_tags( $new_instance['title'] );\n $this-&gt;flush_widget_cache();\n\n $alloptions = wp_cache_get( 'alloptions', 'options' );\n if ( isset($alloptions['widget_custom_service']) )\n delete_option('widget_custom_service');\n\n return $instance;\n }\n\n public function flush_widget_cache() \n {\n wp_cache_delete('widget_services', 'widget');\n }\n\n public function form( $instance ) \n {\n\n $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';\n ?&gt;\n\n &lt;p&gt;\n &lt;label for=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\"&gt;&lt;?php _e( 'Title:' ); ?&gt;&lt;/label&gt;\n &lt;input class=\"widefat\" id=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;\" type=\"text\" value=\"&lt;?php echo $title; ?&gt;\" /&gt;\n &lt;/p&gt;\n\n &lt;?php\n }\n\n}\n\nadd_action( 'widgets_init', function () \n{\n register_widget( 'Custom_Services' );\n});\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182040", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60985/" ]
I have this code fragment in my codebase: ``` foreach($this->adverisers as $adveriser) { $this->data[$adveriser->name]['image'] = bfi_thumb(get_post_meta($adveriser->ID, 'ss_advertisers_cats_image', true ), $this->imgDimensions ); $this->data[$adveriser->name]['description'] = get_post_meta($adveriser->ID, 'ss_advertisers_cats_description', true ); $this->data[$adveriser->name]['advertiser'] = $wpdb->get_results( "SELECT DISTINCT * FROM {$wpdb->posts} WHERE(post_type='brands' OR post_type='boutiques') AND post_author='{$adveriser->post_author}' ", OBJECT ); $this->data[$adveriser->name]['advertiserRedirectionLink'] = get_post_meta($adveriser->ID, 'ss_advertisers_cats_link', true ); } ``` The loop builds a custom array of data for later display on the site. As you can see, there is a total of four queries to the database executed on each iteration of the loop. This is probably far from optimal performance-wise as, in my view, this is an example of [*N+1 Query problem*](https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/). Is there any straightforward solution that would bring siginificant performance increase to this code? Or is my only option crafting a complex, muli-join SQL query with `$wpdb` to get all the required data in one/two queries, or .. maybe the presented code is not so bad after all and would not hinder performance so considerably
As you have already understated, running executable PHP inside a text box is not a good idea. It isn't only just not a good idea, but a terrible idea. This creates a loop hole in your security which can be very easily exploited by a hacker. I would suggest writing your own custom widget for this functionality. It is really easy adding a custom sidebar to the top of your index.php for that specific purpose into which you can just simply drop your custom widget into. Have a look at [`register_sidebar()`](https://codex.wordpress.org/Function_Reference/register_sidebar). There are also plenty tutorials out there on this specific subject on how to add a custom sidebar in your theme As for the widget, look at the [Widget API](https://codex.wordpress.org/Widgets_API). I (with some assistance from @birgire ;-)) have also done a [recent widget which displays categories](https://wordpress.stackexchange.com/a/181350/31545) which you can use as a base for your widget. You can simply code your custom code from the selected service into the `widget` method. You can make this very dynamic. Here is basic skeleton you can use. To make this work, you only need to replace `// ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END` with your custom php code which is inside the `widget()` method (*NOTE: Requires PHP 5.4+*) ``` class Custom_Services extends WP_Widget { public function __construct() { parent::__construct( 'widget_custom_service', _x( 'Custom Service Widget', 'Custom Service Widget' ), [ 'description' => __( 'Displays information from a custom service.' ) ] ); $this->alt_option_name = 'widget_custom_service'; add_action( 'save_post', [$this, 'flush_widget_cache'] ); add_action( 'deleted_post', [$this, 'flush_widget_cache'] ); add_action( 'switch_theme', [$this, 'flush_widget_cache'] ); } public function widget( $args, $instance ) { $cache = []; if ( ! $this->is_preview() ) { $cache = wp_cache_get( 'widget_services', 'widget' ); } if ( ! is_array( $cache ) ) { $cache = []; } if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } if ( isset( $cache[ $args['widget_id'] ] ) ) { echo $cache[ $args['widget_id'] ]; return; } ob_start(); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' ); /** This filter is documented in wp-includes/default-widgets.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END echo $args['after_widget']; if ( ! $this->is_preview() ) { $cache[ $args['widget_id'] ] = ob_get_flush(); wp_cache_set( 'widget_services', $cache, 'widget' ); } else { ob_end_flush(); } } public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); $this->flush_widget_cache(); $alloptions = wp_cache_get( 'alloptions', 'options' ); if ( isset($alloptions['widget_custom_service']) ) delete_option('widget_custom_service'); return $instance; } public function flush_widget_cache() { wp_cache_delete('widget_services', 'widget'); } public function form( $instance ) { $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : ''; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /> </p> <?php } } add_action( 'widgets_init', function () { register_widget( 'Custom_Services' ); }); ```
182,045
<p>I'm on centOS 7 and I have a WordPress site. Due to some problems with the WordPress default wp-cron settings, I have chosen to do the cron tasks with my server instead. I have used this command:</p> <pre class="lang-none prettyprint-override"><code>wget http://www.example.com/wp-cron.php?doing_wp_cron=1 &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>to run every 10 minutes. This works, every ten minutes it try to wget that page but it doesn't generate any outputs and the WordPress cron tasks are not executed. </p> <p>Furthermore, if I try to open the page: <a href="http://www.example.com/wp-cron.php?doing_wp_cron=1" rel="nofollow noreferrer">http://www.example.com/wp-cron.php?doing_wp_cron=1</a> by myself on my browser, I get a blank page... Is this an error? I don't get any message in the Apache error log.</p>
[ { "answer_id": 182046, "author": "Gaia", "author_id": 5090, "author_profile": "https://wordpress.stackexchange.com/users/5090", "pm_score": 3, "selected": true, "text": "<p>Do you have <strong><code>define('DISABLE_WP_CRON', true);</code></strong> set in wp-config? You need it to have the system cron fire up the wp-cron tasks. Go to the bottom of the database settings in wp-config.php, typically around line 37, and <strong>add it</strong>.</p>\n\n<p><strong>Then setup the system cron to fire up the wp-cron tasks</strong>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - \"http://example.com/wp-cron.php?t=`date +\\%s`\" &gt; /dev/null 2&gt;&amp;1\n\n#Sometimes it might be required to run PHP directly:\n*/5 * * * * php /home/$USER/public_html/wp-cron.php\n</code></pre>\n\n<p><code>?doing_wp_cron</code> is appended only automatically when you define <code>ALTERNATE_WP_CRON</code> as <code>true</code> in <code>wp-config.php</code>. Since you are disabling it entirely, you want to use the URL above instead or the 2nd method, which dispenses parameters.</p>\n\n<p>If you're on a development environment and want to output debug information, calling it manually like that will show you your debug output.</p>\n\n<p>Alternatively you can use PHP's built-in <a href=\"http://php.net/manual/en/function.error-log.php\" rel=\"nofollow noreferrer\">error_log</a> function to log message strings to the error log for debugging. You'd need to use this in conjunction with <a href=\"http://codex.wordpress.org/Editing_wp-config.php#Configure_Error_Log\" rel=\"nofollow noreferrer\">WP_DEBUG settings</a>.</p>\n\n<p>If you need further help debugging it, try this <a href=\"https://wordpress.stackexchange.com/questions/13625/how-to-debug-wordpress-cron-wp-schedule-event/13655#13655\">question</a>.</p>\n" }, { "answer_id": 390787, "author": "JesusIniesta", "author_id": 191749, "author_profile": "https://wordpress.stackexchange.com/users/191749", "pm_score": -1, "selected": false, "text": "<p>For people reaching this page because they use FastCGI and they can't find a way to run <code>wp-cron.php</code></p>\n<h3>Issue with FastCGI:</h3>\n<p>When using FastCGI there is an issue that prevents wp-cron.php to be run from the browser.</p>\n<p>To fix it, comment the following lines in your <code>wp-cron.php</code>:</p>\n<blockquote>\n<p>Remember that it is not recommended to modify core WordPress files, so proceed only if you know what you are doing.</p>\n</blockquote>\n<p><strong>Before</strong>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/* Don't make the request block till we finish, if possible. */\nif (function_exists('fastcgi_finish_request') &amp;&amp; version_compare(phpversion(), '7.0.16', '&gt;=')) {\n if (!headers_sent()) {\n header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');\n header('Cache-Control: no-cache, must-revalidate, max-age=0');\n }\n\n fastcgi_finish_request();\n}\n</code></pre>\n<p><strong>After</strong>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/* Don't make the request block till we finish, if possible. */\n//if (function_exists('fastcgi_finish_request') &amp;&amp; version_compare(phpversion(), '7.0.16', '&gt;=')) {\n// if (!headers_sent()) {\n// header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');\n// header('Cache-Control: no-cache, must-revalidate, max-age=0');\n// }\n//\n// fastcgi_finish_request();\n//}\n</code></pre>\n" } ]
2015/03/23
[ "https://wordpress.stackexchange.com/questions/182045", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69539/" ]
I'm on centOS 7 and I have a WordPress site. Due to some problems with the WordPress default wp-cron settings, I have chosen to do the cron tasks with my server instead. I have used this command: ```none wget http://www.example.com/wp-cron.php?doing_wp_cron=1 > /dev/null 2>&1 ``` to run every 10 minutes. This works, every ten minutes it try to wget that page but it doesn't generate any outputs and the WordPress cron tasks are not executed. Furthermore, if I try to open the page: <http://www.example.com/wp-cron.php?doing_wp_cron=1> by myself on my browser, I get a blank page... Is this an error? I don't get any message in the Apache error log.
Do you have **`define('DISABLE_WP_CRON', true);`** set in wp-config? You need it to have the system cron fire up the wp-cron tasks. Go to the bottom of the database settings in wp-config.php, typically around line 37, and **add it**. **Then setup the system cron to fire up the wp-cron tasks**: ``` */5 * * * * wget -q -O - "http://example.com/wp-cron.php?t=`date +\%s`" > /dev/null 2>&1 #Sometimes it might be required to run PHP directly: */5 * * * * php /home/$USER/public_html/wp-cron.php ``` `?doing_wp_cron` is appended only automatically when you define `ALTERNATE_WP_CRON` as `true` in `wp-config.php`. Since you are disabling it entirely, you want to use the URL above instead or the 2nd method, which dispenses parameters. If you're on a development environment and want to output debug information, calling it manually like that will show you your debug output. Alternatively you can use PHP's built-in [error\_log](http://php.net/manual/en/function.error-log.php) function to log message strings to the error log for debugging. You'd need to use this in conjunction with [WP\_DEBUG settings](http://codex.wordpress.org/Editing_wp-config.php#Configure_Error_Log). If you need further help debugging it, try this [question](https://wordpress.stackexchange.com/questions/13625/how-to-debug-wordpress-cron-wp-schedule-event/13655#13655).
182,075
<p>I'm using WP 4.1.1 and trying to create a default value for the 'Alt text' when uploading an image (dropping it straight into post and dialog appears).</p> <p>I've tried doing this with this hook <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_edit" rel="nofollow">https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_edit</a></p> <p>and while I seem to be able to ADD a new field (it appears on the dialog form), I cannot modify the value of the 'Alt Text' field. So the following does NOT work (but should, according to the docs!). I have tried changing the priority from high to very low too, no difference.</p> <pre><code>add_filter('attachment_fields_to_edit', 'dpcontent_attachment_fields_to_edit', 999, 2 ); function dpcontent_attachment_fields_to_edit($form_fields, $post) { if ( substr( $post-&gt;post_mime_type, 0, 5 ) == 'image' ) { _log("DBG: 1 in here ... form_fields=" . arr_to_string($form_fields)); // its empty :-( $form_fields['image_alt'] = array( 'value' =&gt; 'Hello world!', 'label' =&gt; __('Alternative Text'), 'show_in_model' =&gt; true ); } return $form_fields; } </code></pre> <p>Any help with this would be greatly appreciated!</p> <p>gvanto</p>
[ { "answer_id": 241824, "author": "vralle", "author_id": 34691, "author_profile": "https://wordpress.stackexchange.com/users/34691", "pm_score": 2, "selected": false, "text": "<p>Ok, the answer will not be short</p>\n\n<p>At first, You can't change the alt attribute using <a href=\"https://developer.wordpress.org/reference/hooks/attachment_fields_to_edit/\" rel=\"nofollow\">attachment_fields_to_edit</a>, because you can't modify default fields. To see how this works can be in the source code of <a href=\"https://developer.wordpress.org/reference/functions/get_compat_media_markup/\" rel=\"nofollow\">get_compat_media_markup</a>.</p>\n\n<p>With <code>attachment_fields_to_edit</code> you can add only additional input fields.</p>\n\n<p>Example:</p>\n\n<pre><code>/**\n * Add custom field for Images\n *\n * @param array $fields An array of attachment form fields.\n * field arguments:\n * array(\n * 'show_in_edit' =&gt; (bool) Show in Edit Screen. Default true,\n * 'show_in_modal' =&gt; (bool) Show in Modal Screen. Default true,\n * 'label' =&gt; string label text,\n * 'input' =&gt; string input type: text, textarea, etc or 'html' key with custom input html callback. Default 'text'\n * 'required' =&gt; (bool) Input attributte 'required'. Default false,\n * 'html' =&gt; string custom input html or callback name,\n * 'extra_rows' =&gt; array(),\n * 'helps' =&gt; string help text,\n * )\n * @param WP_Post $post The WP_Post attachment object.\n */\nfunction add_attachment_fields($fields, $post)\n{\n if (substr($post-&gt;post_mime_type, 0, 5) == 'image') {\n $meta = wp_get_attachment_metadata($post-&gt;ID);\n $fields['meta_credit'] = array(\n 'label' =&gt; __('Credit'),\n 'input' =&gt; 'text',\n 'value' =&gt; $meta['image_meta']['credit'],\n 'helps' =&gt; __('Only text. Max length 40 characters'),\n 'error_text' =&gt; __('Error credit meta')\n );\n } \n return $fields;\n}\nadd_filter('attachment_fields_to_edit', 'add_attachment_fields', 10, 2);\n</code></pre>\n\n<p>For save value, use <a href=\"https://developer.wordpress.org/reference/hooks/attachment_fields_to_save/\" rel=\"nofollow\">attachment_fields_to_save</a>:</p>\n\n<pre><code>/**\n * Filters the attachment fields to be saved.\n * @param array $post An array of post data.\n * @param array $attachment An array of attachment metadata.\n */\nfunction update_attachment_fields($post, $attachment)\n{\n if (isset($attachment['meta_credit'])) {\n $credit = $attachment['meta_credit'];\n $meta = wp_get_attachment_metadata($post['ID']);\n if ($credit !== $meta['image_meta']['credit']) {\n $meta['image_meta']['credit'] = $credit;\n wp_update_attachment_metadata($post['ID'], $meta);\n }\n }\n return $post;\n}\nadd_filter('attachment_fields_to_save', 'update_attachment_fields', 10, 2);\n</code></pre>\n\n<hr>\n\n<p>What to do with the alt attribute?\nNo good idea, although it is not good to keep trash in database, but work:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/add_attachment/\" rel=\"nofollow\">add_attachment</a> and <a href=\"https://developer.wordpress.org/reference/functions/add_post_meta/\" rel=\"nofollow\">add_post_meta</a> variant fires once when attachment is added:</p>\n\n<pre><code>add_action('add_attachment', 'add_alt_to_attachment');\nfunction add_alt_to_attachment($post_ID)\n{\n add_post_meta($post_ID, '_wp_attachment_image_alt', 'MY TEXT');\n}\n</code></pre>\n\n<p>Fired, when any field change:</p>\n\n<pre><code>function update_alt_field($post, $attachment)\n{\n if (empty($attachment['image_alt'])) {\n $image_alt = wp_unslash('My Alt is good');\n $image_alt = wp_strip_all_tags($image_alt, true);\n // Update_meta expects slashed.\n update_post_meta($attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt));\n }\n return $post;\n}\nadd_filter('attachment_fields_to_save', 'update_alt_field', 10, 2);\n</code></pre>\n\n<p>And other way - add alt text when image inserting in post:</p>\n\n<pre><code>/**\n * Filter the list of attachment image attributes.\n *\n * @param array $attrs Attributes for the image markup.\n * @param WP_Post $attachment Image attachment post.\n * @param string|array $size Requested size. Image size or array of width and height values\n * (in that order). Default 'thumbnail'.\n * @return array $attrs Attributes for the image markup.\n */\nfunction my_images_attr($attrs, $attachment, $size)\n{\n if (empty($attrs['alt'])) {\n $attrs['alt']) = 'MY TEXT';\n }\n return $attrs;\n}\nadd_filter('wp_get_attachment_image_attributes', 'my_images_attr', 10, 3);\n</code></pre>\n" }, { "answer_id": 247821, "author": "bubblez", "author_id": 104091, "author_profile": "https://wordpress.stackexchange.com/users/104091", "pm_score": 1, "selected": false, "text": "<p>I found a solution to add a default caption for all new uploaded attachments:</p>\n\n<pre><code>function add_caption_to_attachment($data, $postarr){\n if(empty(trim($data['post_excerpt']))){\n $data['post_excerpt'] = '«&lt;a href=\"\"&gt;TITEL&lt;/a&gt;» - &lt;a href=\"\"&gt;NAME&lt;/a&gt;, CC &lt;a href=\"\"&gt;XXX&lt;/a&gt;';\n }\n return $data;\n}\nadd_filter('wp_insert_attachment_data', 'add_caption_to_attachment');\n</code></pre>\n\n<p>The solutions proposed by @vralle work well for actual attachment meta data, but caption is not. So I had to find another way, add_attachment hook did not work.</p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51271/" ]
I'm using WP 4.1.1 and trying to create a default value for the 'Alt text' when uploading an image (dropping it straight into post and dialog appears). I've tried doing this with this hook <https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_edit> and while I seem to be able to ADD a new field (it appears on the dialog form), I cannot modify the value of the 'Alt Text' field. So the following does NOT work (but should, according to the docs!). I have tried changing the priority from high to very low too, no difference. ``` add_filter('attachment_fields_to_edit', 'dpcontent_attachment_fields_to_edit', 999, 2 ); function dpcontent_attachment_fields_to_edit($form_fields, $post) { if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) { _log("DBG: 1 in here ... form_fields=" . arr_to_string($form_fields)); // its empty :-( $form_fields['image_alt'] = array( 'value' => 'Hello world!', 'label' => __('Alternative Text'), 'show_in_model' => true ); } return $form_fields; } ``` Any help with this would be greatly appreciated! gvanto
Ok, the answer will not be short At first, You can't change the alt attribute using [attachment\_fields\_to\_edit](https://developer.wordpress.org/reference/hooks/attachment_fields_to_edit/), because you can't modify default fields. To see how this works can be in the source code of [get\_compat\_media\_markup](https://developer.wordpress.org/reference/functions/get_compat_media_markup/). With `attachment_fields_to_edit` you can add only additional input fields. Example: ``` /** * Add custom field for Images * * @param array $fields An array of attachment form fields. * field arguments: * array( * 'show_in_edit' => (bool) Show in Edit Screen. Default true, * 'show_in_modal' => (bool) Show in Modal Screen. Default true, * 'label' => string label text, * 'input' => string input type: text, textarea, etc or 'html' key with custom input html callback. Default 'text' * 'required' => (bool) Input attributte 'required'. Default false, * 'html' => string custom input html or callback name, * 'extra_rows' => array(), * 'helps' => string help text, * ) * @param WP_Post $post The WP_Post attachment object. */ function add_attachment_fields($fields, $post) { if (substr($post->post_mime_type, 0, 5) == 'image') { $meta = wp_get_attachment_metadata($post->ID); $fields['meta_credit'] = array( 'label' => __('Credit'), 'input' => 'text', 'value' => $meta['image_meta']['credit'], 'helps' => __('Only text. Max length 40 characters'), 'error_text' => __('Error credit meta') ); } return $fields; } add_filter('attachment_fields_to_edit', 'add_attachment_fields', 10, 2); ``` For save value, use [attachment\_fields\_to\_save](https://developer.wordpress.org/reference/hooks/attachment_fields_to_save/): ``` /** * Filters the attachment fields to be saved. * @param array $post An array of post data. * @param array $attachment An array of attachment metadata. */ function update_attachment_fields($post, $attachment) { if (isset($attachment['meta_credit'])) { $credit = $attachment['meta_credit']; $meta = wp_get_attachment_metadata($post['ID']); if ($credit !== $meta['image_meta']['credit']) { $meta['image_meta']['credit'] = $credit; wp_update_attachment_metadata($post['ID'], $meta); } } return $post; } add_filter('attachment_fields_to_save', 'update_attachment_fields', 10, 2); ``` --- What to do with the alt attribute? No good idea, although it is not good to keep trash in database, but work: [add\_attachment](https://developer.wordpress.org/reference/hooks/add_attachment/) and [add\_post\_meta](https://developer.wordpress.org/reference/functions/add_post_meta/) variant fires once when attachment is added: ``` add_action('add_attachment', 'add_alt_to_attachment'); function add_alt_to_attachment($post_ID) { add_post_meta($post_ID, '_wp_attachment_image_alt', 'MY TEXT'); } ``` Fired, when any field change: ``` function update_alt_field($post, $attachment) { if (empty($attachment['image_alt'])) { $image_alt = wp_unslash('My Alt is good'); $image_alt = wp_strip_all_tags($image_alt, true); // Update_meta expects slashed. update_post_meta($attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt)); } return $post; } add_filter('attachment_fields_to_save', 'update_alt_field', 10, 2); ``` And other way - add alt text when image inserting in post: ``` /** * Filter the list of attachment image attributes. * * @param array $attrs Attributes for the image markup. * @param WP_Post $attachment Image attachment post. * @param string|array $size Requested size. Image size or array of width and height values * (in that order). Default 'thumbnail'. * @return array $attrs Attributes for the image markup. */ function my_images_attr($attrs, $attachment, $size) { if (empty($attrs['alt'])) { $attrs['alt']) = 'MY TEXT'; } return $attrs; } add_filter('wp_get_attachment_image_attributes', 'my_images_attr', 10, 3); ```
182,106
<p>I would like to insert a custom field into a shortcode and use it in post(s). I want the shortcode to be used with parameters. I tried to solve this problem but it displays the "Array" word instead of the value of the custom field:</p> <pre><code>function get_my_custom_field( $atts ) { global $post; return get_post_meta( $post-&gt;ID, $field, true ); } add_shortcode( 'insert-custom-field', 'get_my_custom_field' ); </code></pre> <p>The shortcode present in the post:</p> <pre><code>[insert-custom-field field="price"] </code></pre>
[ { "answer_id": 182109, "author": "matheuscl", "author_id": 41008, "author_profile": "https://wordpress.stackexchange.com/users/41008", "pm_score": -1, "selected": false, "text": "<p>The <code>$atts</code> don't extract automatic, try this before call <code>global $post</code></p>\n\n<pre><code> extract(shortcode_atts(array(\n 'field' =&gt; '',//#Default value or null\n ), $atts));\n</code></pre>\n\n<p>This code extract <code>$atts</code> to single variables, see more in <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow\">Codex</a>.</p>\n" }, { "answer_id": 182137, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>As I already stated in comments, <code>extract()</code> should never be used. It was removed from core and the codex for very specific reasons and the use there of is strictly not recommended in future applications and functions. Please <a href=\"https://core.trac.wordpress.org/ticket/22400\" rel=\"nofollow\">see trac ticket #22400</a> for complete details.</p>\n\n<p>As stated before, the codex was also updated accordingly, so you can look at the examples given in the <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode API</a> on how to construct a proper shortcode.</p>\n\n<p>With this all in mind, you can create your shortcode as follows:</p>\n\n<pre><code>function get_my_custom_field( $atts ) {\n $attributes = shortcode_atts( array(\n 'field' =&gt; '';\n ), $atts );\n\n global $post;\n\n if ( empty( $attributes['field'] ) )\n return null;\n\n return get_post_meta( $post-&gt;ID, $attributes['field'], true );\n}\nadd_shortcode( 'insert-custom-field', 'get_my_custom_field' );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>You will maybe want to sanitize the input as well according to your input. I will leave that up to you as I'm not exactly sure which data will be passed</p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69533/" ]
I would like to insert a custom field into a shortcode and use it in post(s). I want the shortcode to be used with parameters. I tried to solve this problem but it displays the "Array" word instead of the value of the custom field: ``` function get_my_custom_field( $atts ) { global $post; return get_post_meta( $post->ID, $field, true ); } add_shortcode( 'insert-custom-field', 'get_my_custom_field' ); ``` The shortcode present in the post: ``` [insert-custom-field field="price"] ```
As I already stated in comments, `extract()` should never be used. It was removed from core and the codex for very specific reasons and the use there of is strictly not recommended in future applications and functions. Please [see trac ticket #22400](https://core.trac.wordpress.org/ticket/22400) for complete details. As stated before, the codex was also updated accordingly, so you can look at the examples given in the [Shortcode API](https://codex.wordpress.org/Shortcode_API) on how to construct a proper shortcode. With this all in mind, you can create your shortcode as follows: ``` function get_my_custom_field( $atts ) { $attributes = shortcode_atts( array( 'field' => ''; ), $atts ); global $post; if ( empty( $attributes['field'] ) ) return null; return get_post_meta( $post->ID, $attributes['field'], true ); } add_shortcode( 'insert-custom-field', 'get_my_custom_field' ); ``` EDIT ---- You will maybe want to sanitize the input as well according to your input. I will leave that up to you as I'm not exactly sure which data will be passed
182,112
<p>I have the following rules in my .htaccess file on a WordPress (single installation):</p> <pre><code># REWRITE FORUMS DOMAIN TO FOLDER RewriteCond %{HTTP_HOST} ^forums\.example\.com$ RewriteRule !^forums/? forums%{REQUEST_URI} [NC,L] # REWRITE FORUMS FOLDER TO SUBDOMAIN RewriteCond %{THE_REQUEST} \s/forums/([^\s]*) [NC] RewriteRule ^ http://forums.example.com/%1 [R=301,L] </code></pre> <p>This is so that the forums that exist at <code>http://example.com/forums</code> are accessed at <code>http://forums.example.com/</code></p> <p>However the server just blows up with a 500 server error...</p> <p>Any ideas on how to do this? <strong>These rules work perfectly when used on non-wordpress sites...</strong> The second rewrite rules successfully send /forums to the sub domain but the subdomain doesn't seem to be able to pass the data into WordPress correctly.'</p> <p>The whole htaccess file looks like:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / # REWRITE FORUMS DOMAIN TO FOLDER RewriteCond %{HTTP_HOST} ^forums\.example\.com$ RewriteRule !^forums/? forums%{REQUEST_URI} [NC,L] # REWRITE FORUMS FOLDER TO SUBDOMAIN RewriteCond %{THE_REQUEST} \s/forums/([^\s]*) [NC] RewriteRule ^ http://forums.example.com/%1 [R=301,L] # BEGIN WordPress RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress &lt;/IfModule&gt; </code></pre> <p><strong>The reason that the WordPress rules are after the forums rules are because if I put them after then they are never hit!</strong></p>
[ { "answer_id": 182109, "author": "matheuscl", "author_id": 41008, "author_profile": "https://wordpress.stackexchange.com/users/41008", "pm_score": -1, "selected": false, "text": "<p>The <code>$atts</code> don't extract automatic, try this before call <code>global $post</code></p>\n\n<pre><code> extract(shortcode_atts(array(\n 'field' =&gt; '',//#Default value or null\n ), $atts));\n</code></pre>\n\n<p>This code extract <code>$atts</code> to single variables, see more in <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow\">Codex</a>.</p>\n" }, { "answer_id": 182137, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>As I already stated in comments, <code>extract()</code> should never be used. It was removed from core and the codex for very specific reasons and the use there of is strictly not recommended in future applications and functions. Please <a href=\"https://core.trac.wordpress.org/ticket/22400\" rel=\"nofollow\">see trac ticket #22400</a> for complete details.</p>\n\n<p>As stated before, the codex was also updated accordingly, so you can look at the examples given in the <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode API</a> on how to construct a proper shortcode.</p>\n\n<p>With this all in mind, you can create your shortcode as follows:</p>\n\n<pre><code>function get_my_custom_field( $atts ) {\n $attributes = shortcode_atts( array(\n 'field' =&gt; '';\n ), $atts );\n\n global $post;\n\n if ( empty( $attributes['field'] ) )\n return null;\n\n return get_post_meta( $post-&gt;ID, $attributes['field'], true );\n}\nadd_shortcode( 'insert-custom-field', 'get_my_custom_field' );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>You will maybe want to sanitize the input as well according to your input. I will leave that up to you as I'm not exactly sure which data will be passed</p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/881/" ]
I have the following rules in my .htaccess file on a WordPress (single installation): ``` # REWRITE FORUMS DOMAIN TO FOLDER RewriteCond %{HTTP_HOST} ^forums\.example\.com$ RewriteRule !^forums/? forums%{REQUEST_URI} [NC,L] # REWRITE FORUMS FOLDER TO SUBDOMAIN RewriteCond %{THE_REQUEST} \s/forums/([^\s]*) [NC] RewriteRule ^ http://forums.example.com/%1 [R=301,L] ``` This is so that the forums that exist at `http://example.com/forums` are accessed at `http://forums.example.com/` However the server just blows up with a 500 server error... Any ideas on how to do this? **These rules work perfectly when used on non-wordpress sites...** The second rewrite rules successfully send /forums to the sub domain but the subdomain doesn't seem to be able to pass the data into WordPress correctly.' The whole htaccess file looks like: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # REWRITE FORUMS DOMAIN TO FOLDER RewriteCond %{HTTP_HOST} ^forums\.example\.com$ RewriteRule !^forums/? forums%{REQUEST_URI} [NC,L] # REWRITE FORUMS FOLDER TO SUBDOMAIN RewriteCond %{THE_REQUEST} \s/forums/([^\s]*) [NC] RewriteRule ^ http://forums.example.com/%1 [R=301,L] # BEGIN WordPress RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress </IfModule> ``` **The reason that the WordPress rules are after the forums rules are because if I put them after then they are never hit!**
As I already stated in comments, `extract()` should never be used. It was removed from core and the codex for very specific reasons and the use there of is strictly not recommended in future applications and functions. Please [see trac ticket #22400](https://core.trac.wordpress.org/ticket/22400) for complete details. As stated before, the codex was also updated accordingly, so you can look at the examples given in the [Shortcode API](https://codex.wordpress.org/Shortcode_API) on how to construct a proper shortcode. With this all in mind, you can create your shortcode as follows: ``` function get_my_custom_field( $atts ) { $attributes = shortcode_atts( array( 'field' => ''; ), $atts ); global $post; if ( empty( $attributes['field'] ) ) return null; return get_post_meta( $post->ID, $attributes['field'], true ); } add_shortcode( 'insert-custom-field', 'get_my_custom_field' ); ``` EDIT ---- You will maybe want to sanitize the input as well according to your input. I will leave that up to you as I'm not exactly sure which data will be passed
182,116
<p>How to list all the categories that have a certain word in title - first word of the category? in category.php</p> <p>so, for example, if I am viewing the category "Green Apples Sells", it will list all the categories that start with the word "Green"</p> <p>Update, added another check: IF the category contains one of these two words "South" or "North", then check if the next word is the same, and if it's not, don't list the category - only list the categories that match the first and the second word.</p> <p>Example for the second check: I have categories for countries and continents: "South African Apples", "South African Oranges", "South Korean Apples", "South Korean Oranges" </p> <p>now, when I browse the category 'South African Apples' I want to show the categories from South Africa (so it must check if the second word is the same, because in this case we have "South" in the title, which is one of the two words mentioned), not from South Korea, that's why if you check for the second word after "South", you will get only the right country</p> <p>thank you</p>
[ { "answer_id": 182117, "author": "matheuscl", "author_id": 41008, "author_profile": "https://wordpress.stackexchange.com/users/41008", "pm_score": 2, "selected": false, "text": "<p>You can try this code below</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'name', \n 'order' =&gt; 'ASC',\n 'name__like' =&gt; '%LIKE%',\n 'description__like' =&gt; '%LIKE%',\n); \n\n$terms = get_terms( array( \"taxonomy\" ), $args );\n</code></pre>\n\n<p>See more in <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\">Codex</a></p>\n" }, { "answer_id": 182118, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 1, "selected": false, "text": "<p>You could do it for example like this:</p>\n\n<pre><code>function wpse182116_get_categories_starting_with($word) {\n$categories = get_categories();\n if (!empty($categories)) {\n $relevant_ids = array();\n foreach($categories as $c) {\n $cat_name = $c-&gt;name;\n if(substr($cat_name, 0, strlen($word)) == $word) { $relevant_ids[] = $c-&gt;cat_ID; }\n }\n $term_ids = implode(',' , $relevant_ids);\n $list = wp_list_categories( '&amp;title_li=&amp;style=none&amp;echo=0&amp;taxonomy=category&amp;include=' . $term_ids );\n $list = rtrim(trim(str_replace('&lt;br /&gt;', ' |', $list)), ' |');\n\n return $list;\n }\n}\n</code></pre>\n\n<p>Put that in your functions.php and then in your archive.php you echo them out like </p>\n\n<p><code>$title = single_cat_title('', false); \necho wpse182116_get_categories_starting_with(strtok($title, \" \"));</code>\n<br><strong>edit:</strong> fixed per comments</p>\n\n<p>You can of course change the styling in the function and what not. Now they are echoed like <code>Green shoes | Green other stuff</code> etc with links.</p>\n\n<p>I have no idea if this is efficient or anything, just whipped it up.</p>\n\n<p><strong>EDIT:</strong> by waiting a second and seeing the other answer, I think you should go with the args and name__like. I didn't do the research to see that something like that existed, sorry :D</p>\n\n<p>Also note that this only checks the word in the front of the category name, so <em>Pants Green</em> wouldn't be a match for the function I wrote.</p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6927/" ]
How to list all the categories that have a certain word in title - first word of the category? in category.php so, for example, if I am viewing the category "Green Apples Sells", it will list all the categories that start with the word "Green" Update, added another check: IF the category contains one of these two words "South" or "North", then check if the next word is the same, and if it's not, don't list the category - only list the categories that match the first and the second word. Example for the second check: I have categories for countries and continents: "South African Apples", "South African Oranges", "South Korean Apples", "South Korean Oranges" now, when I browse the category 'South African Apples' I want to show the categories from South Africa (so it must check if the second word is the same, because in this case we have "South" in the title, which is one of the two words mentioned), not from South Korea, that's why if you check for the second word after "South", you will get only the right country thank you
You can try this code below ``` $args = array( 'orderby' => 'name', 'order' => 'ASC', 'name__like' => '%LIKE%', 'description__like' => '%LIKE%', ); $terms = get_terms( array( "taxonomy" ), $args ); ``` See more in [Codex](https://codex.wordpress.org/Function_Reference/get_terms)
182,119
<p>please forgive me I'm relatively new to PHP...</p> <p>I would like to create a shortcode called [city-name] and have tried placing the following code in my functions.php file:</p> <pre><code>function get_city_name() { return $current_cityinfo['cityname']; } add_shortcode( 'city-name', 'get_city_name' ); </code></pre> <p>Then entered the [city-name] shortcode into a page to test and there is no luck...</p> <p>Is there something wrong with my syntax.... I have entered the following into my category pages and that works absolutely fine:</p> <pre><code>&lt;h1 class="loop-title"&gt;&lt;?php single_cat_title(); ?&gt; - &lt;?php echo $current_cityinfo['cityname'];?&gt;&lt;/h1&gt; </code></pre> <p>I hope someone can help me out here... been searching for over 2 hrs now and no luck so thanks in advance!</p> <p>JAke</p>
[ { "answer_id": 182122, "author": "Ciprian", "author_id": 7349, "author_profile": "https://wordpress.stackexchange.com/users/7349", "pm_score": 1, "selected": false, "text": "<p>You need to get $current_cityinfo first. As in:</p>\n\n<pre><code>$current_cityinfo = get_option('current_cityinfo');\n</code></pre>\n\n<p>Or add this code:</p>\n\n<pre><code>global $current_cityinfo;\n</code></pre>\n\n<p>above your <code>return</code> line.</p>\n" }, { "answer_id": 182128, "author": "Alex Older", "author_id": 3365, "author_profile": "https://wordpress.stackexchange.com/users/3365", "pm_score": 1, "selected": false, "text": "<p>You should be passing the 'cityname' to your function:</p>\n\n<pre><code>function get_city_name($cityname) {\nreturn $cityname;\n}\nadd_shortcode( 'city-name', 'get_city_name' );\n</code></pre>\n\n<p>Your shortcode would then look like:</p>\n\n<pre><code>[city-name cityname=\"London\"]\n</code></pre>\n\n<p>chances are that your function will return an array, but this should help you move forward</p>\n" }, { "answer_id": 182698, "author": "user2277105", "author_id": 69857, "author_profile": "https://wordpress.stackexchange.com/users/69857", "pm_score": 0, "selected": false, "text": "<p>Okay, so found the solution (sorry for the delay)</p>\n\n<p>I had to put this:</p>\n\n<pre><code>// Add Shortcode\nfunction city_name() {\n\n global $current_cityinfo; return ' '.$current_cityinfo['cityname'];\n\n}\n\nadd_shortcode( 'city name', 'city_name' );\n</code></pre>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182119", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69538/" ]
please forgive me I'm relatively new to PHP... I would like to create a shortcode called [city-name] and have tried placing the following code in my functions.php file: ``` function get_city_name() { return $current_cityinfo['cityname']; } add_shortcode( 'city-name', 'get_city_name' ); ``` Then entered the [city-name] shortcode into a page to test and there is no luck... Is there something wrong with my syntax.... I have entered the following into my category pages and that works absolutely fine: ``` <h1 class="loop-title"><?php single_cat_title(); ?> - <?php echo $current_cityinfo['cityname'];?></h1> ``` I hope someone can help me out here... been searching for over 2 hrs now and no luck so thanks in advance! JAke
You need to get $current\_cityinfo first. As in: ``` $current_cityinfo = get_option('current_cityinfo'); ``` Or add this code: ``` global $current_cityinfo; ``` above your `return` line.
182,139
<p>I'm trying to implement a simple script:</p> <pre><code>jQuery(document).ready(function($){ $(window).scroll(function(){ if($(window).scrollTop() &gt;= $('#masthead').outerHeight()) { $("#masthead").addClass("minimize"); } else{ $("#masthead").removeClass("minimize"); } }); }); </code></pre> <p>It works perfectly when the user is logged in in to WP. For regular users the script gets loaded in the footer but does nothing.</p> <p>I also get this error from the console:</p> <pre><code>Uncaught ReferenceError: jQuery is not definedfixed-menu.js?ver=20150318:1 (anonymous function) </code></pre> <p>PD: I used <code>wp_enqueue_script</code> in my <code>functions.php</code> as I do with any other external js:</p> <pre><code>function nevermind_scripts() { wp_enqueue_style( 'nevermind-style', get_stylesheet_uri() ); wp_enqueue_style( 'nevermind-google-fonts', 'http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,900,300italic,400italic|Droid+Serif'); wp_enqueue_style( 'nevermind-font-awesome', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'); wp_enqueue_script( 'nevermind-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true ); wp_enqueue_script( 'nevermind-fixed-menu', get_template_directory_uri() . '/js/fixed-menu.js', array(), '20150318', true ); } add_action( 'wp_enqueue_scripts', 'nevermind_scripts' ); </code></pre>
[ { "answer_id": 182122, "author": "Ciprian", "author_id": 7349, "author_profile": "https://wordpress.stackexchange.com/users/7349", "pm_score": 1, "selected": false, "text": "<p>You need to get $current_cityinfo first. As in:</p>\n\n<pre><code>$current_cityinfo = get_option('current_cityinfo');\n</code></pre>\n\n<p>Or add this code:</p>\n\n<pre><code>global $current_cityinfo;\n</code></pre>\n\n<p>above your <code>return</code> line.</p>\n" }, { "answer_id": 182128, "author": "Alex Older", "author_id": 3365, "author_profile": "https://wordpress.stackexchange.com/users/3365", "pm_score": 1, "selected": false, "text": "<p>You should be passing the 'cityname' to your function:</p>\n\n<pre><code>function get_city_name($cityname) {\nreturn $cityname;\n}\nadd_shortcode( 'city-name', 'get_city_name' );\n</code></pre>\n\n<p>Your shortcode would then look like:</p>\n\n<pre><code>[city-name cityname=\"London\"]\n</code></pre>\n\n<p>chances are that your function will return an array, but this should help you move forward</p>\n" }, { "answer_id": 182698, "author": "user2277105", "author_id": 69857, "author_profile": "https://wordpress.stackexchange.com/users/69857", "pm_score": 0, "selected": false, "text": "<p>Okay, so found the solution (sorry for the delay)</p>\n\n<p>I had to put this:</p>\n\n<pre><code>// Add Shortcode\nfunction city_name() {\n\n global $current_cityinfo; return ' '.$current_cityinfo['cityname'];\n\n}\n\nadd_shortcode( 'city name', 'city_name' );\n</code></pre>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182139", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69239/" ]
I'm trying to implement a simple script: ``` jQuery(document).ready(function($){ $(window).scroll(function(){ if($(window).scrollTop() >= $('#masthead').outerHeight()) { $("#masthead").addClass("minimize"); } else{ $("#masthead").removeClass("minimize"); } }); }); ``` It works perfectly when the user is logged in in to WP. For regular users the script gets loaded in the footer but does nothing. I also get this error from the console: ``` Uncaught ReferenceError: jQuery is not definedfixed-menu.js?ver=20150318:1 (anonymous function) ``` PD: I used `wp_enqueue_script` in my `functions.php` as I do with any other external js: ``` function nevermind_scripts() { wp_enqueue_style( 'nevermind-style', get_stylesheet_uri() ); wp_enqueue_style( 'nevermind-google-fonts', 'http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,900,300italic,400italic|Droid+Serif'); wp_enqueue_style( 'nevermind-font-awesome', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'); wp_enqueue_script( 'nevermind-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true ); wp_enqueue_script( 'nevermind-fixed-menu', get_template_directory_uri() . '/js/fixed-menu.js', array(), '20150318', true ); } add_action( 'wp_enqueue_scripts', 'nevermind_scripts' ); ```
You need to get $current\_cityinfo first. As in: ``` $current_cityinfo = get_option('current_cityinfo'); ``` Or add this code: ``` global $current_cityinfo; ``` above your `return` line.
182,166
<p>I am not sure what is wrong but the navigation a:hover has a image that when you hover over it shows. I am looking to see why there is a small space between the end of the image and slideshow. I am wanting to to butt right up to it where there is no gap.</p> <p>See test board here </p> <p><a href="http://www.wpcreations.net/test/" rel="nofollow">http://www.wpcreations.net/test/</a></p>
[ { "answer_id": 182168, "author": "Sean Grant", "author_id": 67105, "author_profile": "https://wordpress.stackexchange.com/users/67105", "pm_score": 2, "selected": true, "text": "<p>This isn't a WordPress issue, although it <em>IS</em> an easy CSS fix.</p>\n\n<p>The small space between the end of image and the slideshow is axtually 2 pixels wide and caused by the <code>#left-area</code> div.</p>\n\n<p>You can just up the width by 2 pixels on #left-area. \nLike this:</p>\n\n<pre><code>#left-area {\n width: 639px;\n}\n</code></pre>\n\n<p>It is currently 637px.</p>\n\n<p>You could also up the padding-left by 2 pixels to acheive the same gap closure, although then the slideshow is a little off center.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 182169, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>It's this</p>\n\n<p><img src=\"https://i.stack.imgur.com/Id89b.png\" alt=\"this\"></p>\n\n<p>right here. Make that 100% or take it away and it works as you thought it should.</p>\n\n<p><strong>edit:</strong> I'm not sure I answered on the right thing afterall. But this will fix the one/two pixel gap between the left hand navigation against the picture on the right.</p>\n\n<p><strong>edit2:</strong> Yeah, it was what I thought, and the other fix does the same thing as well.</p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182166", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48825/" ]
I am not sure what is wrong but the navigation a:hover has a image that when you hover over it shows. I am looking to see why there is a small space between the end of the image and slideshow. I am wanting to to butt right up to it where there is no gap. See test board here <http://www.wpcreations.net/test/>
This isn't a WordPress issue, although it *IS* an easy CSS fix. The small space between the end of image and the slideshow is axtually 2 pixels wide and caused by the `#left-area` div. You can just up the width by 2 pixels on #left-area. Like this: ``` #left-area { width: 639px; } ``` It is currently 637px. You could also up the padding-left by 2 pixels to acheive the same gap closure, although then the slideshow is a little off center. Hope that helps.
182,167
<p>This isn't the usual "How do I change the media upload folder?" question. Our entire site is run through a CDN. The CDN drops POST requests with a 5-6MB file so the WordPress uploads fail. I can work around this I think by changing where WordPress sends file upload requests. </p> <p>If the normal site URL is www.example.com, I want uploads to be sent to just example.com which is our origin server and will have no problem handling larger file uploads. Any ideas? </p>
[ { "answer_id": 182170, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>I'm not quite sure what do you mean.</p>\n\n<p>You can change from where the WP loads the files if that's what you mean?\n<code>add_filter( 'pre_option_upload_url_path', function() { return 'http://yoursite.com/wp-content/uploads'; } );</code></p>\n\n<p>That's what I use to develop on a local server with all the \"real stuff/uploads\" being in the live servers anyway.</p>\n\n<p><strong>edit:</strong> so no, this won't change where your uploads end from the admin, this just changes where the WP loads the media files from. To change the default folder where media uploads will end I think you need a custom upload function.</p>\n\n<p><strong>edit2:</strong> quote from <a href=\"https://wordpress.stackexchange.com/questions/115781/setting-the-uploads-directory\">here</a></p>\n\n<p>You can use the 'upload_dir' filter</p>\n\n<pre><code>add_filter('upload_dir', 'set_upload_folder', 999);\n\nfunction set_upload_folder( $upload_data ) { \n // absolute dir path, must be writable by wordpress \n $upload_data['basedir'] = trailingslashit(ABSPATH). '/files';\n $upload_data['baseurl'] = 'http://subdomain.wptest.com/files';\n $subdir = $upload_data['subdir'];\n $upload_data['path'] = $upload_data['basedir'] . $subdir;\n $upload_data['url'] = $upload_data['baseurl'] . $subdir;\n return wp_parse_args($upload_data, $upload_data);\n}\n</code></pre>\n" }, { "answer_id": 182171, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 2, "selected": false, "text": "<p>It was actually easier than I thought. </p>\n\n<pre><code>function route_uploads_past_cdn( $url, $path ) {\n $upload_paths = array( 'async-upload.php', 'media-new.php' );\n if( !in_array( $path, $upload_paths ) ) {\n return $url;\n }\n\n return str_replace('www.', '', $url);\n}\nadd_filter( 'admin_url', 'pew_route_uploads_past_cdn', 10, 2 );\n</code></pre>\n\n<p>The URL for uploading media would normally be <code>http://www.example.com/wp-admin/media-new.php</code> would now be <code>http://example.com/wp-admin/media-new.php</code> since the URLs are passed through <code>admin_url()</code> which you can filter. </p>\n" } ]
2015/03/24
[ "https://wordpress.stackexchange.com/questions/182167", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2744/" ]
This isn't the usual "How do I change the media upload folder?" question. Our entire site is run through a CDN. The CDN drops POST requests with a 5-6MB file so the WordPress uploads fail. I can work around this I think by changing where WordPress sends file upload requests. If the normal site URL is www.example.com, I want uploads to be sent to just example.com which is our origin server and will have no problem handling larger file uploads. Any ideas?
It was actually easier than I thought. ``` function route_uploads_past_cdn( $url, $path ) { $upload_paths = array( 'async-upload.php', 'media-new.php' ); if( !in_array( $path, $upload_paths ) ) { return $url; } return str_replace('www.', '', $url); } add_filter( 'admin_url', 'pew_route_uploads_past_cdn', 10, 2 ); ``` The URL for uploading media would normally be `http://www.example.com/wp-admin/media-new.php` would now be `http://example.com/wp-admin/media-new.php` since the URLs are passed through `admin_url()` which you can filter.
182,201
<p>My Server configuration is:</p> <ul> <li>Nginx</li> <li>php-fpm5</li> </ul> <p>I set up WordPress and it's working fine with custom permalink 'Day and name'. Now I want to set the rewrite rule in the nginx file and it's not working with a clean URL. If I set the permalinks to 'default' the rule works fine.</p> <p>Also I disable the default WordPress 301 redirection from adding filter for 'redirect_canonical'.</p> <p>Suppose my post URL is <code>example.com/2015/03/22/abc-test</code> and I want to write a rule so that if I enter <code>example.com/2015/03/22/custom/abc-test</code> in browser then it should display the content of <code>example.com/2015/03/22/abc-test</code></p> <p>Nginx Rule:</p> <pre><code>location ~* ^(.*)/custom(.*)$ { rewrite ^(.*)/custom(.*)$ $1$2 last; } </code></pre> <p>I need assistance finding out how Nginx rewrite rules work with WordPress permalink.</p>
[ { "answer_id": 182243, "author": "Vikram Mandaviya", "author_id": 69606, "author_profile": "https://wordpress.stackexchange.com/users/69606", "pm_score": 1, "selected": false, "text": "<p>Use this plugin in wordpress and write rule which will overwrite nginx rule.</p>\n\n<p><a href=\"https://wordpress.org/plugins/rewrite/\" rel=\"nofollow\">https://wordpress.org/plugins/rewrite/</a></p>\n\n<p>When you have wordpress, you have to set permalink to default to work your webserver rule work and if you dont want to do that you have to install above plugin and write rule.</p>\n" }, { "answer_id": 307845, "author": "Awea", "author_id": 146483, "author_profile": "https://wordpress.stackexchange.com/users/146483", "pm_score": 0, "selected": false, "text": "<p>Here is a simple Nginx vhost configuration to work with WordPress URL rewriting:</p>\n\n<pre><code>server {\n listen 80;\n server_name example.com;\n root \"/var/www/staging/example\";\n index index.php;\n location / {\n try_files $uri $uri/ /index.php?$args;\n }\n\n location ~ \\.php$ {\n include snippets/fastcgi-php.conf;\n fastcgi_pass unix:/var/run/php7.0-fpm.sock;\n }\n\n}\n</code></pre>\n\n<p>There is a complete guide on how to configure Nginx with WordPress <a href=\"https://codex.wordpress.org/Nginx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2015/03/25
[ "https://wordpress.stackexchange.com/questions/182201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20843/" ]
My Server configuration is: * Nginx * php-fpm5 I set up WordPress and it's working fine with custom permalink 'Day and name'. Now I want to set the rewrite rule in the nginx file and it's not working with a clean URL. If I set the permalinks to 'default' the rule works fine. Also I disable the default WordPress 301 redirection from adding filter for 'redirect\_canonical'. Suppose my post URL is `example.com/2015/03/22/abc-test` and I want to write a rule so that if I enter `example.com/2015/03/22/custom/abc-test` in browser then it should display the content of `example.com/2015/03/22/abc-test` Nginx Rule: ``` location ~* ^(.*)/custom(.*)$ { rewrite ^(.*)/custom(.*)$ $1$2 last; } ``` I need assistance finding out how Nginx rewrite rules work with WordPress permalink.
Use this plugin in wordpress and write rule which will overwrite nginx rule. <https://wordpress.org/plugins/rewrite/> When you have wordpress, you have to set permalink to default to work your webserver rule work and if you dont want to do that you have to install above plugin and write rule.
182,223
<p>I have customized my admin users column to show the purchased leads of a role "lead buyer". The value of the column is a decimal (the number of leads). </p> <p>The "posts" column of the users table has a class "num" so the <code>&lt;th&gt;</code> and the <code>&lt;td&gt;</code> are styled with <code>text-align: center;</code>. </p> <p>I want to add a the "num" class to my custom column too.</p> <p>Does anyone know in which document you can find the "manage_users_columns" and "manage_users_custom_columns" functions to see if there is a possibility to add the class "num"?</p> <p><img src="https://i.stack.imgur.com/QIKHk.png" alt="Purchased leads column needs to be aligned center"></p> <p><img src="https://i.stack.imgur.com/SW8di.png" alt="The class num on the &quot;posts&quot; column"></p> <pre><code>// Add users table header columns add_filter( 'manage_users_columns', 'gtp_users_table_columns' ); function gtp_users_table_columns( $defaults ) { $defaults['purchased-leads'] = __( 'Purchased leads', 'gtp_translate' ); return $defaults; } // Add users table lead purchase column content add_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 ); function gtp_users_table_content( $value, $column_name, $user_id ) { $leads = gtp_get_leads_by_buyer( $user_id ); switch( $column_name ) { case 'purchased-leads' : return $leads-&gt;found_posts; break; } } </code></pre>
[ { "answer_id": 182907, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 2, "selected": false, "text": "<p>This is not possible, since the output of your <code>gtp_users_table_content</code> function for the <code>manage_users_custom_column</code> action hook is printed within predefined <code>&lt;td&gt;&lt;/td&gt;</code> elements. However, you can put a simple div with a class around your output:</p>\n\n<pre><code>// Add users table lead purchase column content\nadd_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 );\nfunction gtp_users_table_content( $value, $column_name, $user_id ) {\n $leads = gtp_get_leads_by_buyer( $user_id );\n switch( $column_name ) {\n case 'purchased-leads' : \n return '&lt;div class=\"num\"&gt;' . $leads-&gt;found_posts . '&lt;/div&gt;';\n break;\n\n }\n\n return '';\n}\n</code></pre>\n\n<p>Note that I added another return statement at the end of your function, to keep the return statements consistent.</p>\n\n<p><strong>Edit: added table header adjustments</strong></p>\n\n<p>To center the table header cells too:</p>\n\n<pre><code>// Add users table header columns\n add_filter( 'manage_users_columns', 'gtp_users_table_columns' );\n function gtp_users_table_columns( $defaults ) {\n $defaults['purchased-leads'] = '&lt;div class=\"num\"&gt;' . __( 'Purchased leads', 'gtp_translate' ) . '&lt;/div&gt;';\n return $defaults;\n }\n</code></pre>\n" }, { "answer_id": 183460, "author": "Bhavik Patel", "author_id": 26471, "author_profile": "https://wordpress.stackexchange.com/users/26471", "pm_score": 0, "selected": false, "text": "<p>Add Custom Class In Custom Column custom posttype / post/page/ and user list Table .</p>\n\n<p>This is a Simple Please Try This Add column name like \"purchased-leads num \" space between for separate class. Add Add \"num\" Class in Column And Auto Text align Center like Post count , no need Any Other css .</p>\n\n<p><pre>\nadd_filter( 'manage_users_columns', 'gtp_users_table_columns' );\nfunction gtp_users_table_columns( $defaults ) {\n $defaults['purchased-leads num'] = __( 'Purchased leads', 'gtp_translate' );\n return $defaults;\n}</p>\n\n<p>// Add users table lead purchase column content\nadd_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 );\nfunction gtp_users_table_content( $value, $column_name, $user_id ) {\n $leads = gtp_get_leads_by_buyer( $user_id );\n switch( $column_name ) {\n case 'purchased-leads num' : \n return $leads->found_posts;\n break;</p>\n\n<code>}}\n</code></pre>\n" }, { "answer_id": 210290, "author": "Richard Bonk", "author_id": 84481, "author_profile": "https://wordpress.stackexchange.com/users/84481", "pm_score": 1, "selected": true, "text": "<p>The solution is simple. Add the word <code>num</code> when defining the column like this:</p>\n\n<pre><code>// Add users table header columns\nadd_filter( 'manage_users_columns', 'gtp_users_table_columns' );\nfunction gtp_users_table_columns( $defaults ) {\n $defaults['purchased-leads num'] = __( 'Purchased leads', 'gtp_translate' );\n return $defaults;\n}\n\n// Add users table lead purchase column content\nadd_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 );\nfunction gtp_users_table_content( $value, $column_name, $user_id ) {\n $leads = gtp_get_leads_by_buyer( $user_id );\n switch( $column_name ) {\n case 'purchased-leads num' : \n return $leads-&gt;found_posts;\n break;\n }\n}\n</code></pre>\n\n<p>There are only two changes to your original code:</p>\n\n<ol>\n<li>changed <code>$defaults['purchased-leads']</code> to <code>$defaults['purchased-leads num']</code> in the first function</li>\n<li>changed <code>case 'purchased-leads'</code> to <code>case 'purchased-leads num'</code> in the second function</li>\n</ol>\n\n<p>WordPress will then assign the <code>num</code> class to both the header and the column.\nThere is no need for any additional div or other element. This will work also for any other custom classes that you would like to add.</p>\n" }, { "answer_id": 356585, "author": "Vuk Vukovic", "author_id": 45854, "author_profile": "https://wordpress.stackexchange.com/users/45854", "pm_score": 0, "selected": false, "text": "<p>Cleanest way is to add CSS to your own column. \nIn this case <code>wp_enqueue_style(...);</code> with:</p>\n\n<pre><code>.column-purchased-leads {\n width: 74px;\n text-align: center\n}\n</code></pre>\n\n<p>You'll get neat column as \"Posts\".</p>\n" } ]
2015/03/25
[ "https://wordpress.stackexchange.com/questions/182223", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25834/" ]
I have customized my admin users column to show the purchased leads of a role "lead buyer". The value of the column is a decimal (the number of leads). The "posts" column of the users table has a class "num" so the `<th>` and the `<td>` are styled with `text-align: center;`. I want to add a the "num" class to my custom column too. Does anyone know in which document you can find the "manage\_users\_columns" and "manage\_users\_custom\_columns" functions to see if there is a possibility to add the class "num"? ![Purchased leads column needs to be aligned center](https://i.stack.imgur.com/QIKHk.png) ![The class num on the "posts" column](https://i.stack.imgur.com/SW8di.png) ``` // Add users table header columns add_filter( 'manage_users_columns', 'gtp_users_table_columns' ); function gtp_users_table_columns( $defaults ) { $defaults['purchased-leads'] = __( 'Purchased leads', 'gtp_translate' ); return $defaults; } // Add users table lead purchase column content add_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 ); function gtp_users_table_content( $value, $column_name, $user_id ) { $leads = gtp_get_leads_by_buyer( $user_id ); switch( $column_name ) { case 'purchased-leads' : return $leads->found_posts; break; } } ```
The solution is simple. Add the word `num` when defining the column like this: ``` // Add users table header columns add_filter( 'manage_users_columns', 'gtp_users_table_columns' ); function gtp_users_table_columns( $defaults ) { $defaults['purchased-leads num'] = __( 'Purchased leads', 'gtp_translate' ); return $defaults; } // Add users table lead purchase column content add_action( 'manage_users_custom_column', 'gtp_users_table_content', 10, 3 ); function gtp_users_table_content( $value, $column_name, $user_id ) { $leads = gtp_get_leads_by_buyer( $user_id ); switch( $column_name ) { case 'purchased-leads num' : return $leads->found_posts; break; } } ``` There are only two changes to your original code: 1. changed `$defaults['purchased-leads']` to `$defaults['purchased-leads num']` in the first function 2. changed `case 'purchased-leads'` to `case 'purchased-leads num'` in the second function WordPress will then assign the `num` class to both the header and the column. There is no need for any additional div or other element. This will work also for any other custom classes that you would like to add.
182,230
<p>I've built a theme and have set the following image dimensions via functions.php: </p> <pre><code>set_post_thumbnail_size( 1064, 347, true ); // Upload @ 2128(W) x 708(H) add_image_size( 'standard', 352, 235, true ); // Upload @ 704(W) x 470(H) add_image_size( 'gallery', 750, 500, true ); // Upload @ 1500(W) x 1000(H) </code></pre> <p>I use <a href="http://code.tutsplus.com/tutorials/ensuring-your-theme-has-retina-support--wp-33430" rel="nofollow">this script</a> to push out 2 versions of the image for retina displays.</p> <p>I would like to use the image size <code>'standard'</code> for my catalog images and <code>'gallery'</code> for the single product image.</p> <p>Is there a way to disable the WooCommerce image sizes via functions.php and use the ones I have already created?</p> <p>I've tried customising the image sizes via Settings > Products, but it doesn't work with the retina script I'm using.</p>
[ { "answer_id": 182232, "author": "priyanka", "author_id": 69597, "author_profile": "https://wordpress.stackexchange.com/users/69597", "pm_score": -1, "selected": false, "text": "<p>You have to regenerate all the images with the specified sizes and for that you can use Regenerate Thumbnails plugin from wordpress. you can download it from <a href=\"http://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">http://wordpress.org/plugins/regenerate-thumbnails/</a> </p>\n" }, { "answer_id": 182233, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 3, "selected": true, "text": "<p>You have to use <code>single_product_large_thumbnail_size</code> filter for Single Product page.</p>\n\n<p>something like:</p>\n\n<pre><code>function custom_product_large_thumbnail_size() {\n return 'gallery';\n}\nadd_filter('single_product_large_thumbnail_size', 'custom_product_large_thumbnail_size');\n</code></pre>\n" } ]
2015/03/25
[ "https://wordpress.stackexchange.com/questions/182230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37548/" ]
I've built a theme and have set the following image dimensions via functions.php: ``` set_post_thumbnail_size( 1064, 347, true ); // Upload @ 2128(W) x 708(H) add_image_size( 'standard', 352, 235, true ); // Upload @ 704(W) x 470(H) add_image_size( 'gallery', 750, 500, true ); // Upload @ 1500(W) x 1000(H) ``` I use [this script](http://code.tutsplus.com/tutorials/ensuring-your-theme-has-retina-support--wp-33430) to push out 2 versions of the image for retina displays. I would like to use the image size `'standard'` for my catalog images and `'gallery'` for the single product image. Is there a way to disable the WooCommerce image sizes via functions.php and use the ones I have already created? I've tried customising the image sizes via Settings > Products, but it doesn't work with the retina script I'm using.
You have to use `single_product_large_thumbnail_size` filter for Single Product page. something like: ``` function custom_product_large_thumbnail_size() { return 'gallery'; } add_filter('single_product_large_thumbnail_size', 'custom_product_large_thumbnail_size'); ```
182,330
<p>I have a select dropdown in my custom meta box in the admin area. It offers two options <strong>Approved</strong> and <strong>In Progress</strong>. When I select an option and save it the database is updated, but the value in the admin area is not. What I see is the first item from the list displayed in the select box. i.e. if I select <strong>In Progress</strong> and save the admin shows <strong>Approved</strong> as the selected value even though it is saved as <strong>In Progress</strong> in the database and displays <strong>In Progress</strong> on the front end of the site.</p> <p>Here is my code:</p> <pre><code>&lt;label for="myplugin_meta_box_select"&gt;Status:&lt;/label&gt; &lt;select name="myplugin_meta_box_select" id="myplugin_meta_box_select"&gt; &lt;option value="Approved" &lt;?php selected( $selected, 'approved' ); ?&gt;&gt;Approved&lt;/option&gt; &lt;option value="In Progress" &lt;?php selected( $selected, 'inprogress' ); ?&gt;&gt;In Progress&lt;/option&gt; &lt;/select&gt; </code></pre> <p>And I save it with this:</p> <pre><code>if( isset( $_POST['myplugin_meta_box_select'] ) ) update_post_meta( $post_id, 'myplugin_meta_box_select', esc_attr( $_POST['myplugin_meta_box_select'] ) ); </code></pre> <p>What have I missed out?</p>
[ { "answer_id": 182259, "author": "Jonathan Foster", "author_id": 69306, "author_profile": "https://wordpress.stackexchange.com/users/69306", "pm_score": 0, "selected": false, "text": "<p>There isn't a way to get their email address without them signing up for your site first, or giving it willingly in some other way.</p>\n\n<p>If you <em>really</em> wanted to, you could create a newsletter campaign and duplicate it for each person you're trying to reach, and if they visit the site it'll show up as an open and a click on the campaign. That's pretty tedious though.</p>\n\n<p>A different way of going about it would be to grab a plugin that pops up a modal window when they visit the site, encouraging them to either A)register for your site, or B)opt-in to your newsletter etc. Either one of these would give you a better chance of getting visitor emails.</p>\n" }, { "answer_id": 182265, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if this is legal in all countries but you can send the emailadress back to you by adapting it in the link the user clicks to your website.</p>\n\n<p>e.g. The email they receive has a button that links to your website.<br>\nthe url of the button looks like this:<br>\n<code>&lt;a href=\"http://www.yourwebsite.com?email='[email protected]'\"&gt;&lt;img src=\"button.jpg\"&gt;&lt;/a&gt;</code></p>\n\n<p>Then all you have to do is use a <code>$GET_['email']</code> request and get the emailaddress and save it to a database.</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69240/" ]
I have a select dropdown in my custom meta box in the admin area. It offers two options **Approved** and **In Progress**. When I select an option and save it the database is updated, but the value in the admin area is not. What I see is the first item from the list displayed in the select box. i.e. if I select **In Progress** and save the admin shows **Approved** as the selected value even though it is saved as **In Progress** in the database and displays **In Progress** on the front end of the site. Here is my code: ``` <label for="myplugin_meta_box_select">Status:</label> <select name="myplugin_meta_box_select" id="myplugin_meta_box_select"> <option value="Approved" <?php selected( $selected, 'approved' ); ?>>Approved</option> <option value="In Progress" <?php selected( $selected, 'inprogress' ); ?>>In Progress</option> </select> ``` And I save it with this: ``` if( isset( $_POST['myplugin_meta_box_select'] ) ) update_post_meta( $post_id, 'myplugin_meta_box_select', esc_attr( $_POST['myplugin_meta_box_select'] ) ); ``` What have I missed out?
I'm not sure if this is legal in all countries but you can send the emailadress back to you by adapting it in the link the user clicks to your website. e.g. The email they receive has a button that links to your website. the url of the button looks like this: `<a href="http://www.yourwebsite.com?email='[email protected]'"><img src="button.jpg"></a>` Then all you have to do is use a `$GET_['email']` request and get the emailaddress and save it to a database.
182,341
<p>I don't know why when I'm using "Enter", that add <code>&amp;nbsp;</code> in Pages/Posts Editor. That doesn't matter, but on my website, when I look the code <code>&amp;nbsp;</code> makes this code :</p> <pre><code>&lt;p&gt; � &lt;/p&gt; </code></pre> <p>and � appears on my website...</p> <p>How can I change that to simple code :</p> <pre><code>&lt;p&gt; &lt;/p&gt; </code></pre>
[ { "answer_id": 182259, "author": "Jonathan Foster", "author_id": 69306, "author_profile": "https://wordpress.stackexchange.com/users/69306", "pm_score": 0, "selected": false, "text": "<p>There isn't a way to get their email address without them signing up for your site first, or giving it willingly in some other way.</p>\n\n<p>If you <em>really</em> wanted to, you could create a newsletter campaign and duplicate it for each person you're trying to reach, and if they visit the site it'll show up as an open and a click on the campaign. That's pretty tedious though.</p>\n\n<p>A different way of going about it would be to grab a plugin that pops up a modal window when they visit the site, encouraging them to either A)register for your site, or B)opt-in to your newsletter etc. Either one of these would give you a better chance of getting visitor emails.</p>\n" }, { "answer_id": 182265, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if this is legal in all countries but you can send the emailadress back to you by adapting it in the link the user clicks to your website.</p>\n\n<p>e.g. The email they receive has a button that links to your website.<br>\nthe url of the button looks like this:<br>\n<code>&lt;a href=\"http://www.yourwebsite.com?email='[email protected]'\"&gt;&lt;img src=\"button.jpg\"&gt;&lt;/a&gt;</code></p>\n\n<p>Then all you have to do is use a <code>$GET_['email']</code> request and get the emailaddress and save it to a database.</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182341", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68028/" ]
I don't know why when I'm using "Enter", that add `&nbsp;` in Pages/Posts Editor. That doesn't matter, but on my website, when I look the code `&nbsp;` makes this code : ``` <p> � </p> ``` and � appears on my website... How can I change that to simple code : ``` <p> </p> ```
I'm not sure if this is legal in all countries but you can send the emailadress back to you by adapting it in the link the user clicks to your website. e.g. The email they receive has a button that links to your website. the url of the button looks like this: `<a href="http://www.yourwebsite.com?email='[email protected]'"><img src="button.jpg"></a>` Then all you have to do is use a `$GET_['email']` request and get the emailaddress and save it to a database.
182,374
<blockquote> <p><strong>Fatal error</strong>: Cannot access protected property Some_Plugin::$_some_property</p> </blockquote> <p>What is the best/least-destructive way of accessing a protected property attached to a post.</p> <p>The property is being affixed to the post by a plugin but I need to access it's stored information to display.</p> <p>The options I can think of are:</p> <ol> <li>Altering the plug-in code. I'm not so familiar with Object Oriented PHP so I hesitate to do this to avoid damaging the functionality.</li> <li>Somehow invoke the plug-in so I'm in the correct context to retrieve the information (possibly with function in functions.php)</li> <li>Write a function which hooks to the publishing of this post type and duplicates the information to a new, non-protected property of the post.</li> </ol> <p>Does anyone have any suggestions or code samples illustrating the best way to go about this. If you need more information just comment and I'll update the question.</p> <p>Thanks!</p>
[ { "answer_id": 182380, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>The foolproof method here to grab a dynamic member variable is to use reflection!</p>\n\n<p>Lets say we have this class:</p>\n\n<pre><code>class MyClass {\n private $myProperty = true;\n}\n</code></pre>\n\n<p>We can use reflection to acquire the class, and the property:</p>\n\n<pre><code>$class = new ReflectionClass(\"MyClass\");\n$property = $class-&gt;getProperty(\"myProperty\");\n</code></pre>\n\n<p>We can then set that property to accessible:</p>\n\n<pre><code>$property-&gt;setAccessible(true);\n</code></pre>\n\n<p>Now we can access the private member variable using the new <code>$property</code> object:</p>\n\n<pre><code>$obj = new MyClass();\necho $property-&gt;getValue($obj); // Works\n</code></pre>\n\n<p>Note, that the member variable is still private if we access it directly:</p>\n\n<pre><code>echo $obj-&gt;myProperty; // Error\n</code></pre>\n\n<p>However your code implies a static member variable, e.g.:</p>\n\n<pre><code>class Some_Plugin\n private static $_some_property;\n}\n</code></pre>\n\n<p>Which this may not work for</p>\n" }, { "answer_id": 182390, "author": "rob-gordon", "author_id": 20557, "author_profile": "https://wordpress.stackexchange.com/users/20557", "pm_score": 0, "selected": false, "text": "<p>Thank you @TomJNowell, I didn't end up using a reflection class but your answer had enough information regarding classes to get me on the right track. My steps were this.</p>\n\n<p>I searched the plugin directory's php files for lines containing the property I wanted to use in my template.</p>\n\n<pre><code>grep --include=\\*.php -rnw '/path/to/plugin' -e \"_some_property\"\n</code></pre>\n\n<p>I searched through the lines and eventually found the property being called kind of like this:</p>\n\n<pre><code>$property = Plugin_Registry::instance()-&gt;load_model('Someproperty' )-&gt;get_property( $post_id );\n</code></pre>\n\n<p>In my template file I then tested to see if I had access to the <code>Plugin_Registry</code> class.</p>\n\n<pre><code>class_exists(Plugin_Registry) // = 1\n</code></pre>\n\n<p>Then I was able to just copy that line directly into my template and have all the properties I was looking for.</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182374", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20557/" ]
> > **Fatal error**: Cannot access protected property Some\_Plugin::$\_some\_property > > > What is the best/least-destructive way of accessing a protected property attached to a post. The property is being affixed to the post by a plugin but I need to access it's stored information to display. The options I can think of are: 1. Altering the plug-in code. I'm not so familiar with Object Oriented PHP so I hesitate to do this to avoid damaging the functionality. 2. Somehow invoke the plug-in so I'm in the correct context to retrieve the information (possibly with function in functions.php) 3. Write a function which hooks to the publishing of this post type and duplicates the information to a new, non-protected property of the post. Does anyone have any suggestions or code samples illustrating the best way to go about this. If you need more information just comment and I'll update the question. Thanks!
The foolproof method here to grab a dynamic member variable is to use reflection! Lets say we have this class: ``` class MyClass { private $myProperty = true; } ``` We can use reflection to acquire the class, and the property: ``` $class = new ReflectionClass("MyClass"); $property = $class->getProperty("myProperty"); ``` We can then set that property to accessible: ``` $property->setAccessible(true); ``` Now we can access the private member variable using the new `$property` object: ``` $obj = new MyClass(); echo $property->getValue($obj); // Works ``` Note, that the member variable is still private if we access it directly: ``` echo $obj->myProperty; // Error ``` However your code implies a static member variable, e.g.: ``` class Some_Plugin private static $_some_property; } ``` Which this may not work for
182,385
<p>I have a post type in called Publication. I also have few custom field in that post type such as Publication Year, Author... </p> <p>I want to have a search box with 3 drop-down fields which is All Field, Publication Year, and Author. When user select on All Field, it will search everything all post in this post type, but when user select custom field like Publication Year or Author then it search only that post match with that Publication Year or Author. </p> <p>I spend 3 days searching on this, but I got no luck so please help to advise me.</p> <p>Thanks</p>
[ { "answer_id": 182380, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>The foolproof method here to grab a dynamic member variable is to use reflection!</p>\n\n<p>Lets say we have this class:</p>\n\n<pre><code>class MyClass {\n private $myProperty = true;\n}\n</code></pre>\n\n<p>We can use reflection to acquire the class, and the property:</p>\n\n<pre><code>$class = new ReflectionClass(\"MyClass\");\n$property = $class-&gt;getProperty(\"myProperty\");\n</code></pre>\n\n<p>We can then set that property to accessible:</p>\n\n<pre><code>$property-&gt;setAccessible(true);\n</code></pre>\n\n<p>Now we can access the private member variable using the new <code>$property</code> object:</p>\n\n<pre><code>$obj = new MyClass();\necho $property-&gt;getValue($obj); // Works\n</code></pre>\n\n<p>Note, that the member variable is still private if we access it directly:</p>\n\n<pre><code>echo $obj-&gt;myProperty; // Error\n</code></pre>\n\n<p>However your code implies a static member variable, e.g.:</p>\n\n<pre><code>class Some_Plugin\n private static $_some_property;\n}\n</code></pre>\n\n<p>Which this may not work for</p>\n" }, { "answer_id": 182390, "author": "rob-gordon", "author_id": 20557, "author_profile": "https://wordpress.stackexchange.com/users/20557", "pm_score": 0, "selected": false, "text": "<p>Thank you @TomJNowell, I didn't end up using a reflection class but your answer had enough information regarding classes to get me on the right track. My steps were this.</p>\n\n<p>I searched the plugin directory's php files for lines containing the property I wanted to use in my template.</p>\n\n<pre><code>grep --include=\\*.php -rnw '/path/to/plugin' -e \"_some_property\"\n</code></pre>\n\n<p>I searched through the lines and eventually found the property being called kind of like this:</p>\n\n<pre><code>$property = Plugin_Registry::instance()-&gt;load_model('Someproperty' )-&gt;get_property( $post_id );\n</code></pre>\n\n<p>In my template file I then tested to see if I had access to the <code>Plugin_Registry</code> class.</p>\n\n<pre><code>class_exists(Plugin_Registry) // = 1\n</code></pre>\n\n<p>Then I was able to just copy that line directly into my template and have all the properties I was looking for.</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182385", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36921/" ]
I have a post type in called Publication. I also have few custom field in that post type such as Publication Year, Author... I want to have a search box with 3 drop-down fields which is All Field, Publication Year, and Author. When user select on All Field, it will search everything all post in this post type, but when user select custom field like Publication Year or Author then it search only that post match with that Publication Year or Author. I spend 3 days searching on this, but I got no luck so please help to advise me. Thanks
The foolproof method here to grab a dynamic member variable is to use reflection! Lets say we have this class: ``` class MyClass { private $myProperty = true; } ``` We can use reflection to acquire the class, and the property: ``` $class = new ReflectionClass("MyClass"); $property = $class->getProperty("myProperty"); ``` We can then set that property to accessible: ``` $property->setAccessible(true); ``` Now we can access the private member variable using the new `$property` object: ``` $obj = new MyClass(); echo $property->getValue($obj); // Works ``` Note, that the member variable is still private if we access it directly: ``` echo $obj->myProperty; // Error ``` However your code implies a static member variable, e.g.: ``` class Some_Plugin private static $_some_property; } ``` Which this may not work for
182,388
<p>As I'm making one page website. Here is question I asked earlier:</p> <p><a href="https://wordpress.stackexchange.com/questions/181270/calling-specific-pages-with-wp-query-part-ii">Calling Specific Pages with wp query Part II</a></p> <p>As I'm calling all pages by WP_Query which is "order by = ASC" I want to call it "order by menu structure" not menu_order.</p> <p>For E.g: <img src="https://i.imgur.com/lnIAx6r.png" alt="screenshot"></p> <p>Now I want home to the top then services then testimonials. depend on menu structure.. </p> <p>How can I achieve it.. Please Help .. Thanks in advance!</p>
[ { "answer_id": 182413, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>You <em>may</em> be able to use a WP_Query on <code>nav_menu_item</code> since it is its own post type. I've never done this but maybe it would work like you need it to, worth a shot. There are three other possibilities:</p>\n\n<h1>Option 1 - Get Your Nav Menu Items</h1>\n\n<p>There's a functions called <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items()</code></a> which will return you an array of your menu items that you can then loop through and display. Here's an example of how you could use it. There are a few \"Gotcha!\" here:</p>\n\n<ul>\n<li><code>$item-&gt;ID</code> is the current navigational items ID <strong>not</strong> the <code>post_id</code>. The post ID is now <code>$item-&gt;object_id</code>.</li>\n<li><code>$item-&gt;title</code> is the current navigational items title and not necessarily the <code>post_title</code> though by default it is, it can still be modified and changed. The most reliable way to get the post title is to use the <code>object_id</code> and pass it into <code>get_the_title()</code> function.</li>\n</ul>\n\n<hr>\n\n<pre><code>$nav_items = wp_get_nav_menu_items( 'Main Menu', array(\n 'order' =&gt; 'ASC', // List ASCending or DESCending\n 'orderby' =&gt; 'title', // Order by your usual, menu_order, post_title, etc. Check WP_Query\n 'post_type' =&gt; 'nav_menu_item', // To be honest, I'm not sure why this is an option, leave it be.\n 'post_status' =&gt; 'publish', // If there are private / draft posts in our menu, don't show them\n 'output' =&gt; ARRAY_A, // Return an Array of Objects\n 'output_key' =&gt; 'menu_order', // Not sure what this does\n 'nopaging' =&gt; true, // Not sure what this does\n 'update_post_term_cache' =&gt; false // Not sure what this does\n) );\n\nif( ! empty( $nav_items ) ) {\n foreach( $nav_items as $item ) {\n echo \"{$item-&gt;title} - \" . get_the_title( $item-&gt;object_id );\n echo \"&lt;br /&gt;\\n\";\n }\n}\n</code></pre>\n\n<h1>Option 2 - Custom Nav Walker</h1>\n\n<p>You could just display your menu as is using <code>wp_nav_menu()</code> and pass in a <a href=\"https://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function\" rel=\"nofollow noreferrer\">Custom Walker Function</a> to modify it's output. An example of this could be automatically pulling that menu items child pages, without actually adding those pages to the physical menu. <a href=\"https://codereview.stackexchange.com/questions/47903/automatic-submenu\">Child Walker Class</a></p>\n\n<h1>Option 3 - Page Menu Order</h1>\n\n<p>Usually when I create a website for a client I have a WordPress menu and I also mirror the admin panels page order with Page Attribute <code>menu_order</code>. This way you could query pages using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> and <code>orderby =&gt; 'menu_order'</code></p>\n\n<p><img src=\"https://i.stack.imgur.com/BVp0T.png\" alt=\"Image Found on codeholic.in\"></p>\n\n<hr>\n\n<p>Other than that, in short there is no easy <code>orderby =&gt; 'My Menu'</code>, you'll have to find an alternative or a workaround.</p>\n" }, { "answer_id": 182415, "author": "Amanda Giles", "author_id": 49937, "author_profile": "https://wordpress.stackexchange.com/users/49937", "pm_score": 2, "selected": false, "text": "<p>You could use the function <a href=\"https://codex.wordpress.org/Function_Reference/wp_nav_menu\" rel=\"nofollow\">wp_get_nav_menu_items()</a> instead of wp_query() to retrieve the menu items from a particular menu in the menu structure order. Once you've done that, you could loop through the menu items one by one to do with as you wish (including filtering them down further on type or other info). This is assuming all pages are in the menu (which they would need to be if you're using that to understand the order).</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182388", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68179/" ]
As I'm making one page website. Here is question I asked earlier: [Calling Specific Pages with wp query Part II](https://wordpress.stackexchange.com/questions/181270/calling-specific-pages-with-wp-query-part-ii) As I'm calling all pages by WP\_Query which is "order by = ASC" I want to call it "order by menu structure" not menu\_order. For E.g: ![screenshot](https://i.imgur.com/lnIAx6r.png) Now I want home to the top then services then testimonials. depend on menu structure.. How can I achieve it.. Please Help .. Thanks in advance!
You *may* be able to use a WP\_Query on `nav_menu_item` since it is its own post type. I've never done this but maybe it would work like you need it to, worth a shot. There are three other possibilities: Option 1 - Get Your Nav Menu Items ================================== There's a functions called [`wp_get_nav_menu_items()`](https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items) which will return you an array of your menu items that you can then loop through and display. Here's an example of how you could use it. There are a few "Gotcha!" here: * `$item->ID` is the current navigational items ID **not** the `post_id`. The post ID is now `$item->object_id`. * `$item->title` is the current navigational items title and not necessarily the `post_title` though by default it is, it can still be modified and changed. The most reliable way to get the post title is to use the `object_id` and pass it into `get_the_title()` function. --- ``` $nav_items = wp_get_nav_menu_items( 'Main Menu', array( 'order' => 'ASC', // List ASCending or DESCending 'orderby' => 'title', // Order by your usual, menu_order, post_title, etc. Check WP_Query 'post_type' => 'nav_menu_item', // To be honest, I'm not sure why this is an option, leave it be. 'post_status' => 'publish', // If there are private / draft posts in our menu, don't show them 'output' => ARRAY_A, // Return an Array of Objects 'output_key' => 'menu_order', // Not sure what this does 'nopaging' => true, // Not sure what this does 'update_post_term_cache' => false // Not sure what this does ) ); if( ! empty( $nav_items ) ) { foreach( $nav_items as $item ) { echo "{$item->title} - " . get_the_title( $item->object_id ); echo "<br />\n"; } } ``` Option 2 - Custom Nav Walker ============================ You could just display your menu as is using `wp_nav_menu()` and pass in a [Custom Walker Function](https://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function) to modify it's output. An example of this could be automatically pulling that menu items child pages, without actually adding those pages to the physical menu. [Child Walker Class](https://codereview.stackexchange.com/questions/47903/automatic-submenu) Option 3 - Page Menu Order ========================== Usually when I create a website for a client I have a WordPress menu and I also mirror the admin panels page order with Page Attribute `menu_order`. This way you could query pages using [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) and `orderby => 'menu_order'` ![Image Found on codeholic.in](https://i.stack.imgur.com/BVp0T.png) --- Other than that, in short there is no easy `orderby => 'My Menu'`, you'll have to find an alternative or a workaround.
182,389
<p>I have a set of custom post types and taxonomies I've added using the <a href="https://wordpress.org/plugins/custom-post-type-ui/" rel="nofollow">Custom Post Type UI</a> plugin, and need to enter several hundred entries ( >500 )</p> <p>How can I import this data in bulk? E.g. as a csv?</p>
[ { "answer_id": 182398, "author": "LindsayAnnB", "author_id": 69685, "author_profile": "https://wordpress.stackexchange.com/users/69685", "pm_score": -1, "selected": false, "text": "<p>You should really re-title this question and refine your question further. From what I gather you are actually trying to find out how to add posts to your custom post type that has custom fields via a CSV. </p>\n\n<p>My suggestion is to look for a plugin that imports posts from a CSV and either find one that already has a column for post_type and columns for custom fields for extend the plugin to include that. </p>\n\n<p>This plugin should do exactly the trick for you\n<a href=\"https://github.com/dansullyLT/rs-csv-importer\" rel=\"nofollow\">https://github.com/dansullyLT/rs-csv-importer</a></p>\n\n<p>I can't give any specific coding / programming advice seeing as this is an extremely broad question and not a question on a specific function. </p>\n" }, { "answer_id": 182414, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>There are many options, but these functions are your friends:</p>\n\n<ul>\n<li><code>wp_insert_post</code> - pass it some arguments and it will create a post and if succesful, return the post ID</li>\n<li><code>wp_set_object_terms</code> - pass it a post ID, a custom taxonomy, and the terms you'd like to set</li>\n<li><code>fopen</code> - for opening a csv file</li>\n<li><code>fgetcsv</code> - reads in a single line from a csv and returns it for processing</li>\n</ul>\n\n<h1>Option 1 - Loading a CSV</h1>\n\n<p>Use the functions earlier, load up a csv file, then for each line, take the values out, the use those values to call <code>wp_insert_post</code> and <code>wp_set_object_terms</code></p>\n\n<p>e.g. csv:</p>\n\n<pre><code>oranges,juicy and zesty,fruit\napples,juicy but not so zesty,fruit\ncucumber,sandwiches go well with it,vegetable\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if (($handle = fopen(\"food.csv\", \"r\")) !== FALSE) {\n while (($data = fgetcsv($handle, 1000, \",\")) !== FALSE) {\n $title = $data[0];\n $content = $data[1];\n $food_type = $data[2];\n $post_id = wp_insert_post( array(\n 'post_title' =&gt; $title,\n 'post_content' =&gt; $content,\n 'post_type' =&gt; 'toms_food_post_type',\n ));\n wp_set_object_terms( $post_id, $food_type, 'toms_food_taxonomy' );\n }\n fclose($handle);\n}\n</code></pre>\n\n<p>I based the above off of an example from php.net</p>\n\n<p>You may want some logic to skip the first row if you have headings, and some logic to do some error checking, e.g. if your post wasn't created, or setting the terms failed, etc</p>\n\n<h1>Option 2 - WXR</h1>\n\n<p>The import file format is based on RSS. So if you can output an RSS document with all your content, and add in the extra fields WordPress uses to signify post type and your custom taxonomy, then you can use the default WordPress importer</p>\n\n<p>As a side note, managing your posts once they're in WordPress, and the best way to register your post type are completely different questions. If you have 3 questions, create 3 questions rather than bundling them all together. That way you don't need somebody who has all 3 answers to get something.</p>\n\n<h1>Further Reading</h1>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/function.fgetcsv.php\" rel=\"nofollow\">fgetcsv docs at php.net</a></li>\n<li><a href=\"http://devtidbits.com/2011/03/16/the-wordpress-extended-rss-wxr-exportimport-xml-document-format-decoded-and-explained/\" rel=\"nofollow\">Information on the wxr format</a></li>\n</ul>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182389", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69679/" ]
I have a set of custom post types and taxonomies I've added using the [Custom Post Type UI](https://wordpress.org/plugins/custom-post-type-ui/) plugin, and need to enter several hundred entries ( >500 ) How can I import this data in bulk? E.g. as a csv?
There are many options, but these functions are your friends: * `wp_insert_post` - pass it some arguments and it will create a post and if succesful, return the post ID * `wp_set_object_terms` - pass it a post ID, a custom taxonomy, and the terms you'd like to set * `fopen` - for opening a csv file * `fgetcsv` - reads in a single line from a csv and returns it for processing Option 1 - Loading a CSV ======================== Use the functions earlier, load up a csv file, then for each line, take the values out, the use those values to call `wp_insert_post` and `wp_set_object_terms` e.g. csv: ``` oranges,juicy and zesty,fruit apples,juicy but not so zesty,fruit cucumber,sandwiches go well with it,vegetable ``` PHP: ``` if (($handle = fopen("food.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $title = $data[0]; $content = $data[1]; $food_type = $data[2]; $post_id = wp_insert_post( array( 'post_title' => $title, 'post_content' => $content, 'post_type' => 'toms_food_post_type', )); wp_set_object_terms( $post_id, $food_type, 'toms_food_taxonomy' ); } fclose($handle); } ``` I based the above off of an example from php.net You may want some logic to skip the first row if you have headings, and some logic to do some error checking, e.g. if your post wasn't created, or setting the terms failed, etc Option 2 - WXR ============== The import file format is based on RSS. So if you can output an RSS document with all your content, and add in the extra fields WordPress uses to signify post type and your custom taxonomy, then you can use the default WordPress importer As a side note, managing your posts once they're in WordPress, and the best way to register your post type are completely different questions. If you have 3 questions, create 3 questions rather than bundling them all together. That way you don't need somebody who has all 3 answers to get something. Further Reading =============== * [fgetcsv docs at php.net](http://php.net/manual/en/function.fgetcsv.php) * [Information on the wxr format](http://devtidbits.com/2011/03/16/the-wordpress-extended-rss-wxr-exportimport-xml-document-format-decoded-and-explained/)
182,393
<p>Right now I have a metakey called 'epicredvote', it sorts my posts by this epicredvote number. It is doing it on a daily basis at the moment, so if I have 2 posts the post with the highest epicredvote # will be at the top. I am wanting to sort it by the WEEK not the DAY. I am wanting all my posts for that week to then be ordered by the epicredvote. With the highest # being at the top.</p> <pre><code>$querystr = ” SELECT $wpdb-&gt;posts.*, YEAR(post_date) AS year, MONTH(post_date) AS month, DAYOFMONTH(post_date) AS dayofmonth FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta WHERE $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id AND $wpdb-&gt;postmeta.meta_key = ‘epicredvote’ AND $wpdb-&gt;posts.post_status = ‘publish’ AND $wpdb-&gt;posts.post_type = ‘post’ GROUP BY ID ORDER BY LEFT($wpdb-&gt;posts.post_date, 10) DESC, $wpdb-&gt;postmeta.meta_value+0 DESC “; </code></pre> <p>Please any help with this would be amazing. Thanks to all you dev rockstars!</p>
[ { "answer_id": 182405, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>This is more of an MySQL question than WordPress one.</p>\n\n<p>You are already using date functions there, from a quick check there is (unsurprisingly) one for <a href=\"https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week\" rel=\"nofollow\"><code>WEEK(date[,mode])</code></a>, you could use in similar fashion for order.</p>\n" }, { "answer_id": 182409, "author": "Amanda Giles", "author_id": 49937, "author_profile": "https://wordpress.stackexchange.com/users/49937", "pm_score": 3, "selected": true, "text": "<p>I agree with Rarst about the WEEK function, but be sure to also use YEAR as well to order the posts. So your order by would look something like this:</p>\n\n<pre><code>ORDER BY YEAR($wpdb-&gt;posts.post_date) DESC, WEEK($wpdb-&gt;posts.post_date) DESC, $wpdb-&gt;postmeta.meta_value+0 DESC\n</code></pre>\n\n<p>Of course, this is still pulling all posts, so you might also want to just limit the query to only pull the current year by adding this to your WHERE clause.</p>\n\n<pre><code>AND YEAR($wpdb-&gt;posts.post_date) = YEAR(CURDATE())\n</code></pre>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22960/" ]
Right now I have a metakey called 'epicredvote', it sorts my posts by this epicredvote number. It is doing it on a daily basis at the moment, so if I have 2 posts the post with the highest epicredvote # will be at the top. I am wanting to sort it by the WEEK not the DAY. I am wanting all my posts for that week to then be ordered by the epicredvote. With the highest # being at the top. ``` $querystr = ” SELECT $wpdb->posts.*, YEAR(post_date) AS year, MONTH(post_date) AS month, DAYOFMONTH(post_date) AS dayofmonth FROM $wpdb->posts, $wpdb->postmeta WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = ‘epicredvote’ AND $wpdb->posts.post_status = ‘publish’ AND $wpdb->posts.post_type = ‘post’ GROUP BY ID ORDER BY LEFT($wpdb->posts.post_date, 10) DESC, $wpdb->postmeta.meta_value+0 DESC “; ``` Please any help with this would be amazing. Thanks to all you dev rockstars!
I agree with Rarst about the WEEK function, but be sure to also use YEAR as well to order the posts. So your order by would look something like this: ``` ORDER BY YEAR($wpdb->posts.post_date) DESC, WEEK($wpdb->posts.post_date) DESC, $wpdb->postmeta.meta_value+0 DESC ``` Of course, this is still pulling all posts, so you might also want to just limit the query to only pull the current year by adding this to your WHERE clause. ``` AND YEAR($wpdb->posts.post_date) = YEAR(CURDATE()) ```
182,408
<p>I'm developing a plug-in that adds the possibility to import/export settings from another plug-in. However, I don't have access to the options ids saved by that plug-in.</p> <p>Is it possible to get all options saved by a specific plug-in?</p> <p>What I would like is something like this:</p> <pre><code>get_plugin_options($pluginId); // returns all options ids in a array or similar </code></pre> <p>I know its possible to just look at the plug-in code and write down the options names... but hard-coding options names wouldn't be nice.</p> <p>Thanks!</p>
[ { "answer_id": 182410, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>I don't think this is possible or a universal function for this exists. Whenever you add an option you do so by adding an <code>option_name</code> and <code>option_value</code> - <a href=\"https://codex.wordpress.org/Function_Reference/add_option\" rel=\"nofollow\"><code>add_option()</code></a>. </p>\n\n<pre><code>&lt;?php add_option( $option, $value, $deprecated, $autoload ); ?&gt;\n</code></pre>\n\n<p>So whenever plugins add their options to the database, they use that function and <em>usually</em> prefix the option name with whatever their plugin is about <code>wpseo_option_name</code> or <code>woocommerce_option_name</code> followed by whatever the option is. Only the developers and their documentation keep track of the options they've created, WordPress does not really. It just lobs them in with all the other options created by other plugins, users, and WordPress itself.</p>\n\n<p>You would manually have to find out all the option names their using, <em>if</em> they're using a prefix, and loop through each of their options: <code>$prefix_$option_name</code>. </p>\n" }, { "answer_id": 182412, "author": "Amanda Giles", "author_id": 49937, "author_profile": "https://wordpress.stackexchange.com/users/49937", "pm_score": 2, "selected": false, "text": "<p>Your best option is likely to copy all the names into your plugin to use for retrieval. Of course, this could change when the plugin is updated. When options are saved in the database using update_option() there's no indication of which plugin they came from that gets stored anywhere. If the options all use a particular prefix though, you could construct a SQL query to pull them from the options table based on that prefix.</p>\n\n<p>For instance, if the prefix to all options for the plugin was 'abcd_', you could use a query like this:</p>\n\n<pre><code>select * from $wpdb-&gt;options where option_name like 'abcd_%'\n</code></pre>\n" }, { "answer_id": 182468, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 2, "selected": false, "text": "<p>You can't get that data on an option already saved by a plugin, but what you can do is monitor <code>add_option</code>, <code>update_option</code> and possibly <code>get_option</code> activity to find out which plugins are using which options with simple backtracing. I put together a little snippet for you:</p>\n\n<pre><code>function gimme_your_options( $option_name ) {\n $blame = 'core';\n $debug_backtrace = debug_backtrace();\n foreach ( $debug_backtrace as $call ) {\n if ( empty( $call['file'] ) )\n continue;\n\n if ( ! preg_match( '#wp-content/((?:(?:mu-)?plugins|themes)/.+)#i', $call['file'], $matches ) )\n continue;\n\n $blame = $matches[1];\n break;\n }\n\n error_log( sprintf( 'blame %s for %s', $blame, $option_name ) );\n}\n\nadd_action( 'add_option', 'gimme_your_options' );\nadd_action( 'update_option', 'gimme_your_options' );\n</code></pre>\n\n<p>Not to throw Jetpack under the bus, but here's an example response in my error.log:</p>\n\n<pre><code>[23-Mar-2015 05:39:27 UTC] blame core for active_plugins\n[23-Mar-2015 05:39:27 UTC] blame core for _transient_doing_cron\n[23-Mar-2015 05:39:27 UTC] blame core for cron\n[23-Mar-2015 05:39:27 UTC] blame core for cron\n[23-Mar-2015 05:39:28 UTC] blame plugins/jetpack/class.jetpack.php for _transient_timeout_jetpack_https_test\n[23-Mar-2015 05:39:28 UTC] blame plugins/jetpack/class.jetpack.php for _transient_jetpack_https_test\n[23-Mar-2015 05:39:28 UTC] blame plugins/jetpack/class.jetpack-options.php for jetpack_options\n</code></pre>\n\n<p>Hope that helps.</p>\n\n<p>Also note that there may be false positives, i.e. if a plugin for example adds a cron schedule, the function would be the one blamed for accessing the cron option, however, the plugin certainly doesn't <em>own</em> that option.</p>\n" } ]
2015/03/26
[ "https://wordpress.stackexchange.com/questions/182408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69694/" ]
I'm developing a plug-in that adds the possibility to import/export settings from another plug-in. However, I don't have access to the options ids saved by that plug-in. Is it possible to get all options saved by a specific plug-in? What I would like is something like this: ``` get_plugin_options($pluginId); // returns all options ids in a array or similar ``` I know its possible to just look at the plug-in code and write down the options names... but hard-coding options names wouldn't be nice. Thanks!
Your best option is likely to copy all the names into your plugin to use for retrieval. Of course, this could change when the plugin is updated. When options are saved in the database using update\_option() there's no indication of which plugin they came from that gets stored anywhere. If the options all use a particular prefix though, you could construct a SQL query to pull them from the options table based on that prefix. For instance, if the prefix to all options for the plugin was 'abcd\_', you could use a query like this: ``` select * from $wpdb->options where option_name like 'abcd_%' ```
182,421
<p>I would like style the main horizontal Wordpress menu so that the first 3 items are aligned to the left and the last 3 items are aligned to the right.</p> <p>This will create the appearance of two menus (with login, etc., on the right) but make it easy to restyle it to create a responsive menu with the last three items at the bottom. </p> <p>MENU:</p> <pre><code>&lt;UL&gt; &lt;li&gt;1a&lt;/li&gt;&lt;li&gt;2a&lt;/li&gt;&lt;li&gt;3a&lt;/li&gt; &lt;-left right-&gt; &lt;li&gt;4a&lt;/li&gt;&lt;li&gt;5a&lt;/li&gt;&lt;li&gt;6a&lt;/li&gt; &lt;/UL&gt; </code></pre> <p>Using float left and right causes the last 3 items to change order, I need them to stay in order.</p> <p>I would like a solution that does not require creating a separate menu or changing the order of the menu items to make the float:right put them back in the right order. </p> <p>I have tried various combinations of display:inline-block and text-align:left/right, with no luck. </p> <p>EDIT: I would like to do this without adding markup into the menu itself. (Unless the answer also illustrates how to add markup into a Wordpress horizontal menu.) </p>
[ { "answer_id": 182422, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>You need to wrap your two groups (left and right aligned items) in two containers. You than set <code>float</code> <code>left</code>, respectively <code>right</code> on those containers. </p>\n\n<pre><code>&lt;UL&gt; \n &lt;div class=\"pull-left\"&gt;&lt;li&gt;1a&lt;/li&gt;&lt;li&gt;2a&lt;/li&gt;&lt;li&gt;3a&lt;/li&gt;&lt;/div&gt;\n &lt;div class=\"pull-right\"&gt;&lt;li&gt;4a&lt;/li&gt;&lt;li&gt;5a&lt;/li&gt;&lt;li&gt;6a&lt;/li&gt;&lt;/div&gt;\n&lt;/UL&gt;\n</code></pre>\n\n<p>And make sure the inside elements have <code>display</code> set to <code>inline-block</code>. You also want to set <code>overflow</code> property of <code>ul</code> element to 'hidden', to make sure it expands to contain all the children, since both are floating.</p>\n\n<pre><code>.pull-left { float: left; }\n.pull-right { float: right; }\n.pull-left li, .pull-right li { display: inline-block; }\nul { overflow: hidden; }\n</code></pre>\n\n<p>Setting <code>overflow: hidden</code> for all the <code>ul</code> elements in your project might not be a very good idea, so you might want to find a parent selector of your <code>ul</code> and add it in front of the <code>ul</code> selector. (ex: <code>.some-container-class-here ul { overflow: hidden;}</code> )</p>\n" }, { "answer_id": 182426, "author": "cfx", "author_id": 28957, "author_profile": "https://wordpress.stackexchange.com/users/28957", "pm_score": 3, "selected": true, "text": "<p>There's an easier way with no markup changes and minimal CSS. <a href=\"http://jsfiddle.net/silb3r/1eyk7pa4/2/\" rel=\"nofollow\">Live demo/fiddle here</a>, code below:</p>\n\n<pre><code>&lt;ul&gt; \n &lt;li&gt;1a&lt;/li&gt;&lt;li&gt;2a&lt;/li&gt;&lt;li&gt;3a&lt;/li&gt;&lt;li&gt;4a&lt;/li&gt;&lt;li&gt;5a&lt;/li&gt;&lt;li&gt;6a&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<hr>\n\n<pre><code>ul {\n list-style: none;\n margin: 0;\n padding: 0;\n text-align: right;\n}\nli {\n float: left;\n}\nli:nth-last-child(1), li:nth-last-child(2), li:nth-last-child(3) {\n float: none;\n display: inline-block;\n}\n</code></pre>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59712/" ]
I would like style the main horizontal Wordpress menu so that the first 3 items are aligned to the left and the last 3 items are aligned to the right. This will create the appearance of two menus (with login, etc., on the right) but make it easy to restyle it to create a responsive menu with the last three items at the bottom. MENU: ``` <UL> <li>1a</li><li>2a</li><li>3a</li> <-left right-> <li>4a</li><li>5a</li><li>6a</li> </UL> ``` Using float left and right causes the last 3 items to change order, I need them to stay in order. I would like a solution that does not require creating a separate menu or changing the order of the menu items to make the float:right put them back in the right order. I have tried various combinations of display:inline-block and text-align:left/right, with no luck. EDIT: I would like to do this without adding markup into the menu itself. (Unless the answer also illustrates how to add markup into a Wordpress horizontal menu.)
There's an easier way with no markup changes and minimal CSS. [Live demo/fiddle here](http://jsfiddle.net/silb3r/1eyk7pa4/2/), code below: ``` <ul> <li>1a</li><li>2a</li><li>3a</li><li>4a</li><li>5a</li><li>6a</li> </ul> ``` --- ``` ul { list-style: none; margin: 0; padding: 0; text-align: right; } li { float: left; } li:nth-last-child(1), li:nth-last-child(2), li:nth-last-child(3) { float: none; display: inline-block; } ```
182,424
<p>I have two pages - new.hillsong.com/australia/sisterhood - new.hillsong.com/hills/sisterhood</p> <p>Both pages are displaying the content for the /hills/sisterhood site but they are different pages with different content. I can't seem to find anything online about this. Is this possible? Are there any ways to make this work.</p> <p>Thanks for the help! Paul</p>
[ { "answer_id": 182425, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><strong>No, at the time of writing this, no you cannot</strong>. Once a slug is used by a page, it cannot be used by other pages. It also can't be used by other posts, regardless of post types</p>\n\n<p>There is a Trac ticket on WP Core that's attempting to fix this so that a slug can be reused by post type, but that would still only allow you one use of your page slug. The chances that you could do what you're trying to do are remote at best, and vanishingly small at worst.</p>\n\n<p>The nearest you could get to this is by adding a /sisterhood/ endpoint via the rewrite rules interface, which would allow you to change the content of a page when the sisterhood endpoint is present. However, this endpoint is just that, an endpoint, it isn't a page with post meta and content, it's just the same page but with an endpoint ( in this case, you'd still be on the Australia page, you'd just have the option to show something different )</p>\n\n<p>Rewrite rules and endpoints are not for the faint of heart, if you're interested in this, I advise you ask the question:</p>\n\n<blockquote>\n <p>\"How do I add a page endpoint? I'm trying to add a sisterhood endpoint to my pages, so that I can display a different template. How do I add the endpoint then load a different template?\"</p>\n</blockquote>\n\n<p>Make sure you link here, and you put the new question link here too</p>\n" }, { "answer_id": 182438, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The easiest way to do it is to not use pages for that, but instead create a new post types for \"hills\" and/or \"australia\" this can be a PITA but you need to understand that the combination of post type and slug should be unique (the reason it is done this way is to let you change the permalink structure without having to update whole of the content).</p>\n\n<p>Another option it seems like you need to consider is to use a multisite install with a subdirectory structure. This depends on how distinct are \"australia\" and \"hills\" sections and if you have to have aggregating things like native search working on all of your content.</p>\n\n<p>Most complex option is to write your own url parsing. For example, check in your functions.php if the url is \"hills/sisterhood\" before any template handling code is loaded, and replace the query with one that will serve the specific page you want. The problems here is that it is hard to scale and you might need to find a solution to generating a proper permalink for the page for example to be used in your site map.</p>\n" }, { "answer_id": 243148, "author": "Eoin H", "author_id": 86679, "author_profile": "https://wordpress.stackexchange.com/users/86679", "pm_score": 1, "selected": false, "text": "<p>I know its an old post, but thought is was worth mentioning (for those like me finding it in search engines).. What I use to get around something similar is a Custom Permalinks plugin. (<a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow\">https://wordpress.org/plugins/custom-permalinks/</a>).</p>\n\n<p>I have been using this plugin for a number of years on about 30 client websites and have never had an issue with it, and it will allow you to create almost any url you like.. if you have 2 or more URLs ending in /sisterhood/, it will do that without any issues, regardless of what the slug is.</p>\n" }, { "answer_id": 313463, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": false, "text": "<p><strong>Yes, you can.</strong></p>\n\n<p>In the old days, this was not possible (as evident from other answers). However, it's possible now.</p>\n\n<p>WordPress now lets child pages (of any post type that is hierarchical) from different parents to have the same slug / name. This is possible because now WordPress considers the entire hierarchical tree (parent-child combination) for uniqueness check.</p>\n\n<p>So the following page URL(s) are possible now:</p>\n\n<pre><code>example.com/parent-1/child\nexample.com/parent-2/child\n</code></pre>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182424", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69701/" ]
I have two pages - new.hillsong.com/australia/sisterhood - new.hillsong.com/hills/sisterhood Both pages are displaying the content for the /hills/sisterhood site but they are different pages with different content. I can't seem to find anything online about this. Is this possible? Are there any ways to make this work. Thanks for the help! Paul
**Yes, you can.** In the old days, this was not possible (as evident from other answers). However, it's possible now. WordPress now lets child pages (of any post type that is hierarchical) from different parents to have the same slug / name. This is possible because now WordPress considers the entire hierarchical tree (parent-child combination) for uniqueness check. So the following page URL(s) are possible now: ``` example.com/parent-1/child example.com/parent-2/child ```
182,429
<p>So, I don't know how to explain properly, but here is the current situation.</p> <p>Let say the site is called "Demo.com" and site admin email is "[email protected]"</p> <p>Then, </p> <ol> <li>An author(example, [email protected]) posts a post.</li> <li>a visitor (another user, [email protected]) leaves a comment or reply on the post.</li> <li>the author(user-X) gets an email notification.</li> </ol> <p>Here is the thing. </p> <p>The email sender is the admin "[email protected]" and not the visitor.</p> <p>Thus, when the author tries to reply back directly from the email, he is replying back to the "[email protected]" and not "[email protected]".</p> <p>How can I change it so that the reply can be sent to the original viewer (user-y)?</p> <p>Any suggestions?</p>
[ { "answer_id": 182430, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>What you need to do is to modify the code that sends the email to the author and in it set the \"reply-to\" header of the email, pass it as part of the headers parameters to <code>wp-mail</code>.</p>\n\n<p>Your code should be something like (adapted from the php mail function documentation).</p>\n\n<pre><code>$to = '[email protected]';\n$subject = 'new comment';\n$message = 'hello';\n$headers = 'From: [email protected]' . \"\\r\\n\" .\n 'Reply-To: [email protected]';\n\nwp_mail($to, $subject, $message, $headers);\n</code></pre>\n\n<p>Of course you will need to get the relevant email addresses from the post author and the comment author fields, and you will probably want to specify the \"nice names\" of all the people involved with the actual email address</p>\n" }, { "answer_id": 182433, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 0, "selected": false, "text": "<p>you could use this filter: <code>comment_notification_headers</code></p>\n\n<p>for reference:</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/pluggable.php#L1434\" rel=\"nofollow\">https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/pluggable.php#L1434</a></p>\n\n<p>line: 1434 and 1471</p>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, I don't know how to explain properly, but here is the current situation. Let say the site is called "Demo.com" and site admin email is "[email protected]" Then, 1. An author(example, [email protected]) posts a post. 2. a visitor (another user, [email protected]) leaves a comment or reply on the post. 3. the author(user-X) gets an email notification. Here is the thing. The email sender is the admin "[email protected]" and not the visitor. Thus, when the author tries to reply back directly from the email, he is replying back to the "[email protected]" and not "[email protected]". How can I change it so that the reply can be sent to the original viewer (user-y)? Any suggestions?
What you need to do is to modify the code that sends the email to the author and in it set the "reply-to" header of the email, pass it as part of the headers parameters to `wp-mail`. Your code should be something like (adapted from the php mail function documentation). ``` $to = '[email protected]'; $subject = 'new comment'; $message = 'hello'; $headers = 'From: [email protected]' . "\r\n" . 'Reply-To: [email protected]'; wp_mail($to, $subject, $message, $headers); ``` Of course you will need to get the relevant email addresses from the post author and the comment author fields, and you will probably want to specify the "nice names" of all the people involved with the actual email address
182,431
<p>Why it is bad to use this </p> <p><code>include("../../../wp-load.php");</code> ??</p> <p>What is the proper way of use this?? </p> <p>Thanks</p>
[ { "answer_id": 182469, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>The problem in this solution is, that the location of this file are different. WordPress allow the definition of the folder of plugins and themes, different to your static path check for the <code>wp-load.php</code>.</p>\n\n<h3>Example for custom paths</h3>\n\n<pre><code>//*\n// Custom content directory\ndefine( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' );\ndefine( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );\n// Custom plugin directory\ndefine( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' );\ndefine( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' );\n// Custom mu plugin directory\ndefine( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' );\ndefine( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' );\n/**/\n</code></pre>\n\n<h3>Why this is wrong</h3>\n\n<p>The follow 3 points are copied form <a href=\"http://ottopress.com/2010/dont-include-wp-load-please/\" rel=\"nofollow\">Ottos post</a>. You find also alternatives in this post.</p>\n\n<ul>\n<li>You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around in the installation. ALL the WordPress files could be moved about in this manner, are you going to search around for them?</li>\n<li>You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every page load. Once to produce the page, and then again to produce your generated javascript.</li>\n<li>You’re generating javascript on the fly. That’s simply crap for caching and speed and such.</li>\n</ul>\n" }, { "answer_id": 182470, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>It is bad because on any security aware wordpress setting you will not be able to directly execute php on any folder except for the root one, which is the situation in which that line of code is usually used.</p>\n\n<p>there is no proper way to do \"that\", it should never be done.</p>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
Why it is bad to use this `include("../../../wp-load.php");` ?? What is the proper way of use this?? Thanks
The problem in this solution is, that the location of this file are different. WordPress allow the definition of the folder of plugins and themes, different to your static path check for the `wp-load.php`. ### Example for custom paths ``` //* // Custom content directory define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); // Custom plugin directory define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); // Custom mu plugin directory define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); /**/ ``` ### Why this is wrong The follow 3 points are copied form [Ottos post](http://ottopress.com/2010/dont-include-wp-load-please/). You find also alternatives in this post. * You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around in the installation. ALL the WordPress files could be moved about in this manner, are you going to search around for them? * You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every page load. Once to produce the page, and then again to produce your generated javascript. * You’re generating javascript on the fly. That’s simply crap for caching and speed and such.
182,434
<p>I want to create a video gallery plugin. I am using this code to create a post: </p> <pre><code>global $user_ID; $new_post = array( 'post_title' =&gt; 'chapter1', 'post_content' =&gt; 'Lorem ipsum dolor sit amet...', 'post_status' =&gt; 'publish', 'post_date' =&gt; date( 'Y-m-d H:i:s' ), 'post_author' =&gt; $user_ID, 'post_type' =&gt; 'post', 'post_category' =&gt; array(0) ); $post_id = wp_insert_post( $new_post ); </code></pre> <p>It's working well, but the problem is the created post shows in the admin dashboard "All Posts" panel; I don't want to show programmatically created posts there, or in the latest posts.</p> <p>Is there any way I can do this? I tried to change the post type, but the generated post link gives me a page not found error. </p>
[ { "answer_id": 182447, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p><strong>Edit:</strong> I thought this would be fairly simple but seems I'm just not competent enough.</p>\n\n<p>You could get around it by adding an arbitrary category (like <code>my_prog_cat_to_hide</code>) for these programmatically added posts and then filtering them out in the admin listing.</p>\n\n<pre><code>function wpse182434_get_category_id($cat_name){\n $term = get_term_by('name', $cat_name, 'category');\n return $term-&gt;term_id;\n}\n\nfunction wpse182434_filter_admin_query( $query ) {\n if(is_admin() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; !filter_input(INPUT_GET, 'post_status') &amp;&amp; ( $screen = get_current_screen() ) instanceof \\WP_Screen &amp;&amp; 'edit-post' === $screen-&gt;id) {\n $query-&gt;set( 'cat', '-'.wpse182434_get_category_id('my_prog_cat_to_hide') );\n }\n}\nadd_action( 'pre_get_posts', 'wpse182434_filter_admin_query' );\n</code></pre>\n\n<p>Of course this leaves you with handling stuff like not showing that category on the front end and/or in feeds and what not.</p>\n\n<p>in that <code>wpse182434_filter_admin_query</code> the if conditions are so that if you select <em>published</em> or any other filter than <em>all posts</em> from the top, you still see the articles. They are just filtered out in the all posts listing.</p>\n\n<p>And all this goes in your functions.php of course.</p>\n" }, { "answer_id": 182453, "author": "erichmond", "author_id": 31057, "author_profile": "https://wordpress.stackexchange.com/users/31057", "pm_score": 2, "selected": false, "text": "<p>And to create a custom post type is not an option?</p>\n\n<pre><code>'post_type' =&gt; 'custom_post_type'\n</code></pre>\n\n<p>then just hide the custom post type from the UI</p>\n\n<p>see <a href=\"https://wordpress.stackexchange.com/questions/28782/possible-to-hide-custom-post-type-ui-menu-from-specific-user-roles\">Possible to hide Custom Post Type UI/Menu from specific User Roles?</a></p>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182434", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69703/" ]
I want to create a video gallery plugin. I am using this code to create a post: ``` global $user_ID; $new_post = array( 'post_title' => 'chapter1', 'post_content' => 'Lorem ipsum dolor sit amet...', 'post_status' => 'publish', 'post_date' => date( 'Y-m-d H:i:s' ), 'post_author' => $user_ID, 'post_type' => 'post', 'post_category' => array(0) ); $post_id = wp_insert_post( $new_post ); ``` It's working well, but the problem is the created post shows in the admin dashboard "All Posts" panel; I don't want to show programmatically created posts there, or in the latest posts. Is there any way I can do this? I tried to change the post type, but the generated post link gives me a page not found error.
And to create a custom post type is not an option? ``` 'post_type' => 'custom_post_type' ``` then just hide the custom post type from the UI see [Possible to hide Custom Post Type UI/Menu from specific User Roles?](https://wordpress.stackexchange.com/questions/28782/possible-to-hide-custom-post-type-ui-menu-from-specific-user-roles)
182,444
<p>I am adding a new post format on my plugin activation using this code:</p> <pre><code>wp_insert_term( 'post-format-interviews_ans', 'post_format' ); </code></pre> <p>It's not working. The rest of the plugin activation code, like table generation, is working.</p> <p><code>post_format</code> is a WordPress default taxonomy type.</p> <p>What is the issue?</p>
[ { "answer_id": 182445, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Post_Formats\" rel=\"nofollow\">Post Formats</a> aren't like other taxonomies, they are fixed and new ones can't be added.</p>\n\n<blockquote>\n <p>New formats cannot be introduced by themes or even plugins. The standardization of this list provides both compatibility between numerous themes and an avenue for external blogging tools to access this feature in a consistent fashion.</p>\n</blockquote>\n" }, { "answer_id": 182446, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Unlike the other taxonomies, you cannot use <code>wp_inset_term()</code> to add terms to the <code>post_format</code> taxonomy as you cannot add new terms to this taxonomy.</p>\n\n<p>You need to add the terms for the <code>post_format</code> via <a href=\"https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Formats\" rel=\"nofollow\"><code>add_theme_support()</code></a>, something like </p>\n\n<pre><code>add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );\n</code></pre>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69710/" ]
I am adding a new post format on my plugin activation using this code: ``` wp_insert_term( 'post-format-interviews_ans', 'post_format' ); ``` It's not working. The rest of the plugin activation code, like table generation, is working. `post_format` is a WordPress default taxonomy type. What is the issue?
Unlike the other taxonomies, you cannot use `wp_inset_term()` to add terms to the `post_format` taxonomy as you cannot add new terms to this taxonomy. You need to add the terms for the `post_format` via [`add_theme_support()`](https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Formats), something like ``` add_theme_support( 'post-formats', array( 'aside', 'gallery' ) ); ```
182,455
<p>Apologies I am a PHp beginner and I have no idea why this loop is not working on my tag.php page any help would be welcome.</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="posts"&gt;&lt;!-- BLOG --&gt; &lt;!-- Shapes on sides --&gt; &lt;div class="shapes_left"&gt; &lt;/div&gt; &lt;div class="shapes_right"&gt; &lt;/div&gt; &lt;?php if (is_tag()) { ?&gt; &lt;div id="archive_title"&gt; &lt;h1&gt;&lt;?php single_tag_title(); ?&gt;&lt;/h1&gt; &lt;?php }?&gt; &lt;/div&gt; &lt;div id="featured_home"&gt; &lt;?php $counter = 0; while ( have_posts() ) { $counter += 1; if ( $counter &gt; 5 ) { break; } the_post(); ?&gt; &lt;article class="sticky"&gt; &lt;div class="desc"&gt; &lt;div class="desc_over"&gt;&lt;h2&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;&lt;/div&gt; &lt;?php the_post_thumbnail(large); ?&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php }?&gt; &lt;/div&gt; &lt;?php while( have_posts() ) { the_post(); // it's a post! Display the post! } ?&gt; &lt;div class="post_main"&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;ul class="postinfo"&gt; &lt;li&gt;Posted by &lt;?php the_author_link(); ?&gt;&lt;/li&gt; &lt;li&gt;&lt;?php the_time( 'jS F Y'); ?&gt;&lt;/li&gt; &lt;/ul&gt; &lt;?php the_content( ''); ?&gt; &lt;div class="read_more_blog"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Read More&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;nav id="pagination"&gt; &lt;!-- PAGINATION FOR BLOG --&gt; &lt;ul&gt; &lt;li class="older"&gt;&lt;?php next_posts_link( 'Older posts'); ?&gt;&lt;/li&gt; &lt;li class="newer"&gt;&lt;?php previous_posts_link( 'Newer posts'); ?&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;!-- END OF BLOG PAGINATION --&gt; &lt;?php else : ?&gt; &lt;div id="post"&gt; &lt;!-- 404 Messege --&gt; &lt;h3&gt;404 ERROR!!&lt;/h3&gt; &lt;p&gt;Sorry we can't seem able to find what you are looking for&lt;/p&gt; &lt;p&gt;&lt;a href="&lt;?php echo home_url(); ?&gt;"&gt;Click here to get back to the homepage&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php get_sidebar(); ?&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 182445, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Post_Formats\" rel=\"nofollow\">Post Formats</a> aren't like other taxonomies, they are fixed and new ones can't be added.</p>\n\n<blockquote>\n <p>New formats cannot be introduced by themes or even plugins. The standardization of this list provides both compatibility between numerous themes and an avenue for external blogging tools to access this feature in a consistent fashion.</p>\n</blockquote>\n" }, { "answer_id": 182446, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Unlike the other taxonomies, you cannot use <code>wp_inset_term()</code> to add terms to the <code>post_format</code> taxonomy as you cannot add new terms to this taxonomy.</p>\n\n<p>You need to add the terms for the <code>post_format</code> via <a href=\"https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Formats\" rel=\"nofollow\"><code>add_theme_support()</code></a>, something like </p>\n\n<pre><code>add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );\n</code></pre>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67583/" ]
Apologies I am a PHp beginner and I have no idea why this loop is not working on my tag.php page any help would be welcome. ``` <?php get_header(); ?> <div class="posts"><!-- BLOG --> <!-- Shapes on sides --> <div class="shapes_left"> </div> <div class="shapes_right"> </div> <?php if (is_tag()) { ?> <div id="archive_title"> <h1><?php single_tag_title(); ?></h1> <?php }?> </div> <div id="featured_home"> <?php $counter = 0; while ( have_posts() ) { $counter += 1; if ( $counter > 5 ) { break; } the_post(); ?> <article class="sticky"> <div class="desc"> <div class="desc_over"><h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2></div> <?php the_post_thumbnail(large); ?> </div> </article> <?php }?> </div> <?php while( have_posts() ) { the_post(); // it's a post! Display the post! } ?> <div class="post_main"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <ul class="postinfo"> <li>Posted by <?php the_author_link(); ?></li> <li><?php the_time( 'jS F Y'); ?></li> </ul> <?php the_content( ''); ?> <div class="read_more_blog"><a href="<?php the_permalink(); ?>">Read More</a></div> </div> <?php endwhile; ?> <nav id="pagination"> <!-- PAGINATION FOR BLOG --> <ul> <li class="older"><?php next_posts_link( 'Older posts'); ?></li> <li class="newer"><?php previous_posts_link( 'Newer posts'); ?></li> </ul> </nav> </div> <!-- END OF BLOG PAGINATION --> <?php else : ?> <div id="post"> <!-- 404 Messege --> <h3>404 ERROR!!</h3> <p>Sorry we can't seem able to find what you are looking for</p> <p><a href="<?php echo home_url(); ?>">Click here to get back to the homepage</a> </p> </div> <?php endif; ?> <?php get_sidebar(); ?> </div> <?php get_footer(); ?> ```
Unlike the other taxonomies, you cannot use `wp_inset_term()` to add terms to the `post_format` taxonomy as you cannot add new terms to this taxonomy. You need to add the terms for the `post_format` via [`add_theme_support()`](https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Formats), something like ``` add_theme_support( 'post-formats', array( 'aside', 'gallery' ) ); ```
182,482
<p>I have saved a string in post_meta table in wordpress database with html entities like-</p> <p><code>&lt;p&gt;Hello &lt;b&gt;Shashank&lt;/b&gt;, I have an idea.&lt;/p&gt;</code></p> <p>When I get this string on frontend using function </p> <p><code>get_post_meta(get_the_id(),field_name, true)</code>. </p> <p>It echoes string with HTML entities as same as it stores in DB.</p> <p>But I want to show this sting as "Hello <strong>Shashank</strong>, I have an idea."</p> <p>How can I do this.? </p>
[ { "answer_id": 182490, "author": "M-R", "author_id": 17061, "author_profile": "https://wordpress.stackexchange.com/users/17061", "pm_score": 0, "selected": false, "text": "<p>I believe, you would need to decode encoded saved entities before echo them out using <a href=\"http://codex.wordpress.org/Function_Reference/wp_kses_decode_entities\" rel=\"nofollow\"><code>wp_kses_decode_entities</code></a> like this</p>\n\n<pre><code>$field = get_post_meta(get_the_id(),field_name, true)\necho wp_kses_decode_entities($field);\n</code></pre>\n" }, { "answer_id": 226837, "author": "frenchy black", "author_id": 28580, "author_profile": "https://wordpress.stackexchange.com/users/28580", "pm_score": 2, "selected": false, "text": "<p>Use the htmlspecialchars() function in PHP in the templates, because the wordpress-api does htmlspecialchars on import.</p>\n\n<p>The following code works fine</p>\n\n<pre><code>&lt;?php print htmlspecialchars_decode(get_post_meta($post-&gt;ID, 'field_name', true)); ?&gt;\n</code></pre>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182482", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67983/" ]
I have saved a string in post\_meta table in wordpress database with html entities like- `<p>Hello <b>Shashank</b>, I have an idea.</p>` When I get this string on frontend using function `get_post_meta(get_the_id(),field_name, true)`. It echoes string with HTML entities as same as it stores in DB. But I want to show this sting as "Hello **Shashank**, I have an idea." How can I do this.?
Use the htmlspecialchars() function in PHP in the templates, because the wordpress-api does htmlspecialchars on import. The following code works fine ``` <?php print htmlspecialchars_decode(get_post_meta($post->ID, 'field_name', true)); ?> ```
182,498
<p>I have a big amount of images in WP, that are not attach to any post. They are grouped in custom taxonomies (ignored in code below). The images get uploaded to WP in random order and the post_date is set to the time the image was taken. Therefor the IDs and the post_date are not in the same order.</p> <p>I need the ID for the next/prev image in time to browse throw time.</p> <p>For this reasons and more I thought using the date_query of WP_Query would make sense. I wrote this code:</p> <pre><code>function get_relative_attachment_id( $this_post_ID, $prev = true ) { // Set the return var, so it can be overwritten $attachment_id = null; // WP_Query arguments $args = array( 'post_type' =&gt; 'attachment', 'post_status' =&gt; 'any', 'posts_per_page' =&gt; '1', 'orderby' =&gt; 'date', 'relation' =&gt; 'AND', 'post__not_in' =&gt; array( $this_post_ID ), ); if ( $prev ) { $args['date_query'] = array( array( 'year' =&gt; intval( get_the_date( 'Y', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), array( 'monthnum' =&gt; intval( get_the_date( 'n', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), array( 'day' =&gt; intval( get_the_date( 'j', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), array( 'hour' =&gt; intval( get_the_date( ' G', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), array( 'minute' =&gt; intval( get_the_date( 'i', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), array( 'second' =&gt; intval( get_the_date( 's', $this_post_ID ) ), 'compare' =&gt; '&lt;=', ), ); } else { $args['order'] = 'ASC'; $args['date_query'] = array( array( 'year' =&gt; intval( get_the_date( 'Y', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), array( 'monthnum' =&gt; intval( get_the_date( 'n', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), array( 'day' =&gt; intval( get_the_date( 'j', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), array( 'hour' =&gt; intval( get_the_date( ' G', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), array( 'minute' =&gt; intval( get_the_date( 'i', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), array( 'second' =&gt; intval( get_the_date( 's', $this_post_ID ) ), 'compare' =&gt; '&gt;=', ), ); } // The Query $query_next_attachment = new WP_Query( $args ); // The Loop if ( $query_next_attachment-&gt;have_posts() ) { while ( $query_next_attachment-&gt;have_posts() ) { $query_next_attachment-&gt;the_post(); // Put the new attachment id into return var $attachment_id = get_the_ID(); } } else { // make the return var null $attachment_id = null; } // Restore original Post Data wp_reset_postdata(); return $attachment_id; } </code></pre> <p>When the images are uploaded in chronological order the returns are fine within one day. But when I hit the beginning of the day it starts to skip whole days. Example (* get returned):</p> <pre><code>[...] 2015-03-11 04:58 * 2015-03-11 03:58 * 2015-03-11 02:58 * 2015-03-11 01:58 * 2015-03-11 00:58 * ---- 2015-03-10 23:58 [...] 2015-03-10 01:58 2015-03-10 00:58 * ---- 2015-03-09 23:58 [...] 2015-03-09 01:58 2015-03-09 00:58 * ---- 2015-03-08 23:58 [...] </code></pre> <p>A similar behavior into the other direction.<br> If the order of date and ID is out of sync the return is even more chaos. I would like to fix the "regular" order first.</p> <p>Is there a mistake in the date_query? Did I miss to set a parameter?</p>
[ { "answer_id": 182522, "author": "Jan Beck", "author_id": 18760, "author_profile": "https://wordpress.stackexchange.com/users/18760", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/get_adjacent_post\" rel=\"nofollow\">get_adjacent_post</a> function already does what you are asking for. Its only downside is that it uses the global $post variable to determine the current post. You would need to overwrite it in a wrapper function like so:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nfunction get_adjacent_post_by_id( $post_id, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {\n global $post;\n\n $post = get_post( $post_id ); // overwrite global $post variable\n $adjacent_post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );\n\n wp_reset_postdata(); // reset global $post variable\n\n return $adjacent_post;\n\n}\n\n// get previous post of post with ID 1337: \n$previous_post = get_adjacent_post_by_id( 1337 );\n\n// get next post of post with ID 1337: \n$next_post = get_adjacent_post_by_id( 1337, false, '', false );\n?&gt;\n</code></pre>\n\n<p>I kept all the original arguments of the get_adjacent_post function. You may remove or reorder them for how you need them.</p>\n" }, { "answer_id": 182524, "author": "Nabeel", "author_id": 35155, "author_profile": "https://wordpress.stackexchange.com/users/35155", "pm_score": 0, "selected": false, "text": "<p>Try this out</p>\n\n<pre><code>&lt;?php\n/**\n * Get next/preview post by post_date\n * \n * @param int|WP_Post $post\n * @param boolean $next_post\n * @return WP_Post|WP_Error\n */\nfunction get_next_prev_post_by_date( $post, $next_post = true ) \n{\n global $wpdb;\n\n // get current post data\n if ( !is_a( $post, 'WP_Post' ) )\n $post = get_post( $post );\n\n // build select SQL query\n $query = \"SELECT * FROM {$wpdb-&gt;posts}\";\n $query .= \" WHERE post_date \". ( $next_post ? '&gt;' : '&lt;' ) .\" %s\";\n $query .= \" AND ID NOT IN (%d)\";\n $query .= \" ORDER BY post_date DESC LIMIT 1\";\n\n // run query\n $target_post_row = $wpdb-&gt;get_row( $wpdb-&gt;prepare( $query, $post-&gt;ID, $post-&gt;post_date ) );\n\n // return post object if found\n if ( $target_post_row )\n return new WP_Post( $target_post_row );\n\n // return error if no match found\n return new WP_Error( 'no_match_found', __( 'No matched post found' ) );\n}\n</code></pre>\n" }, { "answer_id": 182684, "author": "Drivingralle", "author_id": 45303, "author_profile": "https://wordpress.stackexchange.com/users/45303", "pm_score": 2, "selected": true, "text": "<p>Based on the answer by @jan-becker I build this snippet. This works for me:</p>\n\n<pre><code>/*\n * Get the next/prev image id inside c-tax: my_snapshot_position_ctax\n */\nfunction my_return_relative_attachment_id( $this_post_ID, $prev = true ) {\n global $post;\n\n // overwrite global $post variable\n $post = get_post( $this_post_ID );\n\n // filter sql query to work with attachment\n add_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );\n add_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );\n\n // Get the new post object\n $adjacent_post = get_adjacent_post( true, array(), $prev, 'my_snapshot_position_ctax' );\n\n // reset global $post variable\n wp_reset_postdata();\n\n // remove sql query filter\n remove_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10 );\n remove_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10 );\n\n // check if returned value is a post\n if ( ! is_object( $adjacent_post ) ) {\n // not a post, return an empty string\n return '';\n }\n\n // return the post id\n return $adjacent_post-&gt;ID;\n}\n\n/*\n * Filter to modify sql query because attachments have different post status value\n */\nfunction my_filter_next_prev_post_where_query( $sql_query, $in_same_term, $excluded_terms ) {\n\n // replace 'publish' with 'inherit' because we work with attachments\n $sql_query = str_replace( 'publish', 'inherit', $sql_query );\n\n // return the modified query string\n return $sql_query;\n}\n</code></pre>\n\n<p>Maybe moving the filter into the function above makes less code. But this is more readable to me.</p>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45303/" ]
I have a big amount of images in WP, that are not attach to any post. They are grouped in custom taxonomies (ignored in code below). The images get uploaded to WP in random order and the post\_date is set to the time the image was taken. Therefor the IDs and the post\_date are not in the same order. I need the ID for the next/prev image in time to browse throw time. For this reasons and more I thought using the date\_query of WP\_Query would make sense. I wrote this code: ``` function get_relative_attachment_id( $this_post_ID, $prev = true ) { // Set the return var, so it can be overwritten $attachment_id = null; // WP_Query arguments $args = array( 'post_type' => 'attachment', 'post_status' => 'any', 'posts_per_page' => '1', 'orderby' => 'date', 'relation' => 'AND', 'post__not_in' => array( $this_post_ID ), ); if ( $prev ) { $args['date_query'] = array( array( 'year' => intval( get_the_date( 'Y', $this_post_ID ) ), 'compare' => '<=', ), array( 'monthnum' => intval( get_the_date( 'n', $this_post_ID ) ), 'compare' => '<=', ), array( 'day' => intval( get_the_date( 'j', $this_post_ID ) ), 'compare' => '<=', ), array( 'hour' => intval( get_the_date( ' G', $this_post_ID ) ), 'compare' => '<=', ), array( 'minute' => intval( get_the_date( 'i', $this_post_ID ) ), 'compare' => '<=', ), array( 'second' => intval( get_the_date( 's', $this_post_ID ) ), 'compare' => '<=', ), ); } else { $args['order'] = 'ASC'; $args['date_query'] = array( array( 'year' => intval( get_the_date( 'Y', $this_post_ID ) ), 'compare' => '>=', ), array( 'monthnum' => intval( get_the_date( 'n', $this_post_ID ) ), 'compare' => '>=', ), array( 'day' => intval( get_the_date( 'j', $this_post_ID ) ), 'compare' => '>=', ), array( 'hour' => intval( get_the_date( ' G', $this_post_ID ) ), 'compare' => '>=', ), array( 'minute' => intval( get_the_date( 'i', $this_post_ID ) ), 'compare' => '>=', ), array( 'second' => intval( get_the_date( 's', $this_post_ID ) ), 'compare' => '>=', ), ); } // The Query $query_next_attachment = new WP_Query( $args ); // The Loop if ( $query_next_attachment->have_posts() ) { while ( $query_next_attachment->have_posts() ) { $query_next_attachment->the_post(); // Put the new attachment id into return var $attachment_id = get_the_ID(); } } else { // make the return var null $attachment_id = null; } // Restore original Post Data wp_reset_postdata(); return $attachment_id; } ``` When the images are uploaded in chronological order the returns are fine within one day. But when I hit the beginning of the day it starts to skip whole days. Example (\* get returned): ``` [...] 2015-03-11 04:58 * 2015-03-11 03:58 * 2015-03-11 02:58 * 2015-03-11 01:58 * 2015-03-11 00:58 * ---- 2015-03-10 23:58 [...] 2015-03-10 01:58 2015-03-10 00:58 * ---- 2015-03-09 23:58 [...] 2015-03-09 01:58 2015-03-09 00:58 * ---- 2015-03-08 23:58 [...] ``` A similar behavior into the other direction. If the order of date and ID is out of sync the return is even more chaos. I would like to fix the "regular" order first. Is there a mistake in the date\_query? Did I miss to set a parameter?
Based on the answer by @jan-becker I build this snippet. This works for me: ``` /* * Get the next/prev image id inside c-tax: my_snapshot_position_ctax */ function my_return_relative_attachment_id( $this_post_ID, $prev = true ) { global $post; // overwrite global $post variable $post = get_post( $this_post_ID ); // filter sql query to work with attachment add_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10, 3 ); add_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10, 3 ); // Get the new post object $adjacent_post = get_adjacent_post( true, array(), $prev, 'my_snapshot_position_ctax' ); // reset global $post variable wp_reset_postdata(); // remove sql query filter remove_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10 ); remove_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10 ); // check if returned value is a post if ( ! is_object( $adjacent_post ) ) { // not a post, return an empty string return ''; } // return the post id return $adjacent_post->ID; } /* * Filter to modify sql query because attachments have different post status value */ function my_filter_next_prev_post_where_query( $sql_query, $in_same_term, $excluded_terms ) { // replace 'publish' with 'inherit' because we work with attachments $sql_query = str_replace( 'publish', 'inherit', $sql_query ); // return the modified query string return $sql_query; } ``` Maybe moving the filter into the function above makes less code. But this is more readable to me.
182,502
<p>I have developed a custom wordpress panel with a custom front-end recently. In single post pages there is a slider. I display the result of get_attached_media( 'image' ) function as the images of slider. </p> <p>I told editor that upload only the images you would like to see in slider to post from edit post page, upload other images from the media link on the side menu. The problem is that, if the user uploads an image from media screen, then inserts it to content of the post, the image happens to be attached to that post since it is not attached to any post. </p> <p>How can I prevent this? Or is there a way to show images which are uploaded from edit post page?</p>
[ { "answer_id": 182522, "author": "Jan Beck", "author_id": 18760, "author_profile": "https://wordpress.stackexchange.com/users/18760", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/get_adjacent_post\" rel=\"nofollow\">get_adjacent_post</a> function already does what you are asking for. Its only downside is that it uses the global $post variable to determine the current post. You would need to overwrite it in a wrapper function like so:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nfunction get_adjacent_post_by_id( $post_id, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) {\n global $post;\n\n $post = get_post( $post_id ); // overwrite global $post variable\n $adjacent_post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );\n\n wp_reset_postdata(); // reset global $post variable\n\n return $adjacent_post;\n\n}\n\n// get previous post of post with ID 1337: \n$previous_post = get_adjacent_post_by_id( 1337 );\n\n// get next post of post with ID 1337: \n$next_post = get_adjacent_post_by_id( 1337, false, '', false );\n?&gt;\n</code></pre>\n\n<p>I kept all the original arguments of the get_adjacent_post function. You may remove or reorder them for how you need them.</p>\n" }, { "answer_id": 182524, "author": "Nabeel", "author_id": 35155, "author_profile": "https://wordpress.stackexchange.com/users/35155", "pm_score": 0, "selected": false, "text": "<p>Try this out</p>\n\n<pre><code>&lt;?php\n/**\n * Get next/preview post by post_date\n * \n * @param int|WP_Post $post\n * @param boolean $next_post\n * @return WP_Post|WP_Error\n */\nfunction get_next_prev_post_by_date( $post, $next_post = true ) \n{\n global $wpdb;\n\n // get current post data\n if ( !is_a( $post, 'WP_Post' ) )\n $post = get_post( $post );\n\n // build select SQL query\n $query = \"SELECT * FROM {$wpdb-&gt;posts}\";\n $query .= \" WHERE post_date \". ( $next_post ? '&gt;' : '&lt;' ) .\" %s\";\n $query .= \" AND ID NOT IN (%d)\";\n $query .= \" ORDER BY post_date DESC LIMIT 1\";\n\n // run query\n $target_post_row = $wpdb-&gt;get_row( $wpdb-&gt;prepare( $query, $post-&gt;ID, $post-&gt;post_date ) );\n\n // return post object if found\n if ( $target_post_row )\n return new WP_Post( $target_post_row );\n\n // return error if no match found\n return new WP_Error( 'no_match_found', __( 'No matched post found' ) );\n}\n</code></pre>\n" }, { "answer_id": 182684, "author": "Drivingralle", "author_id": 45303, "author_profile": "https://wordpress.stackexchange.com/users/45303", "pm_score": 2, "selected": true, "text": "<p>Based on the answer by @jan-becker I build this snippet. This works for me:</p>\n\n<pre><code>/*\n * Get the next/prev image id inside c-tax: my_snapshot_position_ctax\n */\nfunction my_return_relative_attachment_id( $this_post_ID, $prev = true ) {\n global $post;\n\n // overwrite global $post variable\n $post = get_post( $this_post_ID );\n\n // filter sql query to work with attachment\n add_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );\n add_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );\n\n // Get the new post object\n $adjacent_post = get_adjacent_post( true, array(), $prev, 'my_snapshot_position_ctax' );\n\n // reset global $post variable\n wp_reset_postdata();\n\n // remove sql query filter\n remove_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10 );\n remove_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10 );\n\n // check if returned value is a post\n if ( ! is_object( $adjacent_post ) ) {\n // not a post, return an empty string\n return '';\n }\n\n // return the post id\n return $adjacent_post-&gt;ID;\n}\n\n/*\n * Filter to modify sql query because attachments have different post status value\n */\nfunction my_filter_next_prev_post_where_query( $sql_query, $in_same_term, $excluded_terms ) {\n\n // replace 'publish' with 'inherit' because we work with attachments\n $sql_query = str_replace( 'publish', 'inherit', $sql_query );\n\n // return the modified query string\n return $sql_query;\n}\n</code></pre>\n\n<p>Maybe moving the filter into the function above makes less code. But this is more readable to me.</p>\n" } ]
2015/03/27
[ "https://wordpress.stackexchange.com/questions/182502", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69753/" ]
I have developed a custom wordpress panel with a custom front-end recently. In single post pages there is a slider. I display the result of get\_attached\_media( 'image' ) function as the images of slider. I told editor that upload only the images you would like to see in slider to post from edit post page, upload other images from the media link on the side menu. The problem is that, if the user uploads an image from media screen, then inserts it to content of the post, the image happens to be attached to that post since it is not attached to any post. How can I prevent this? Or is there a way to show images which are uploaded from edit post page?
Based on the answer by @jan-becker I build this snippet. This works for me: ``` /* * Get the next/prev image id inside c-tax: my_snapshot_position_ctax */ function my_return_relative_attachment_id( $this_post_ID, $prev = true ) { global $post; // overwrite global $post variable $post = get_post( $this_post_ID ); // filter sql query to work with attachment add_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10, 3 ); add_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10, 3 ); // Get the new post object $adjacent_post = get_adjacent_post( true, array(), $prev, 'my_snapshot_position_ctax' ); // reset global $post variable wp_reset_postdata(); // remove sql query filter remove_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10 ); remove_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10 ); // check if returned value is a post if ( ! is_object( $adjacent_post ) ) { // not a post, return an empty string return ''; } // return the post id return $adjacent_post->ID; } /* * Filter to modify sql query because attachments have different post status value */ function my_filter_next_prev_post_where_query( $sql_query, $in_same_term, $excluded_terms ) { // replace 'publish' with 'inherit' because we work with attachments $sql_query = str_replace( 'publish', 'inherit', $sql_query ); // return the modified query string return $sql_query; } ``` Maybe moving the filter into the function above makes less code. But this is more readable to me.
182,558
<p>God, this little problem drives me crazy and I really hope that you'll help me how to figure it out.</p> <p>I searched over all previous threads and in the codex of wordpress, I find some close situations but none of the answers solved my problems.</p> <p>This is it : I've one host with a wordpress installed at the root. I've one domain pointing it. Everything is fine. I've need now a second install of wordpress, that i've installed in a subfolder. I've a second domain, linked to this subdfoler.</p> <p>Like this : </p> <ul> <li>root > domain.net</li> <li>root/subfolder > anotherdomain.net</li> </ul> <p>If I let the "site url" setting and the "wordpress url" setting with "domain.net/subfolder", this is OK, I can access to my second site and all permalinks work.</p> <p>But if I edit my site url/wordpress url in "anotherdomain.net" it renders the "domain.net" homepage without style...</p> <p>I'm sure this is a question of HTACCESS but I can't find how to properly write it...</p> <p>Thanks for your answers !</p> <p>(sorry for my english, not my mother tongue)</p> <p>Here are .htaccess (at this state, I let them in order to access subfolder via domain.net/subfolder)</p> <p>root:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; </code></pre> <p>root/subfolder</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /subfolder RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /subfolder/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I do not need a multisite, since the two installs are for two separate sites and users, who are just sharing same host.</p>
[ { "answer_id": 182573, "author": "Squish", "author_id": 28821, "author_profile": "https://wordpress.stackexchange.com/users/28821", "pm_score": 0, "selected": false, "text": "<p>In your subdirectory, open your access and change it to the stock setting.</p>\n\n<p><strong>root/subfolder:</strong></p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond. %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n\n<p>That <em>should</em> work.</p>\n" }, { "answer_id": 184422, "author": "cilce", "author_id": 69777, "author_profile": "https://wordpress.stackexchange.com/users/69777", "pm_score": 1, "selected": true, "text": "<p>All the config were good, the problem was with my host provider.</p>\n\n<p>For the record, the htaccess for the site in the subfolder, when everything is ok : </p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n\n<p>And the site and wordpress urls pointing to the new domain.</p>\n" }, { "answer_id": 301590, "author": "Prashant Walke", "author_id": 142260, "author_profile": "https://wordpress.stackexchange.com/users/142260", "pm_score": 1, "selected": false, "text": "<p>If your second subfolder installation is successful, you may likely run into an issue when WordPress writes its Permalink (within the subfolder). The issue apparently has to do with the subfolder installation and how it sees the site root path. WordPress will normally write a .htaccess file in the installation directory, and that folder is usually the website root folder. Here is the applied solution:</p>\n\n<p>change to new WordPress .htaccess (within the demo subfolder) </p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /demo/\nRewriteRule ^index.php$ – [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /demo/index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2015/03/28
[ "https://wordpress.stackexchange.com/questions/182558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69777/" ]
God, this little problem drives me crazy and I really hope that you'll help me how to figure it out. I searched over all previous threads and in the codex of wordpress, I find some close situations but none of the answers solved my problems. This is it : I've one host with a wordpress installed at the root. I've one domain pointing it. Everything is fine. I've need now a second install of wordpress, that i've installed in a subfolder. I've a second domain, linked to this subdfoler. Like this : * root > domain.net * root/subfolder > anotherdomain.net If I let the "site url" setting and the "wordpress url" setting with "domain.net/subfolder", this is OK, I can access to my second site and all permalinks work. But if I edit my site url/wordpress url in "anotherdomain.net" it renders the "domain.net" homepage without style... I'm sure this is a question of HTACCESS but I can't find how to properly write it... Thanks for your answers ! (sorry for my english, not my mother tongue) Here are .htaccess (at this state, I let them in order to access subfolder via domain.net/subfolder) root: ``` # 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> ``` root/subfolder ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /subfolder RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /subfolder/index.php [L] </IfModule> # END WordPress ``` I do not need a multisite, since the two installs are for two separate sites and users, who are just sharing same host.
All the config were good, the problem was with my host provider. For the record, the htaccess for the site in the subfolder, when everything is ok : ``` # 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 the site and wordpress urls pointing to the new domain.
182,582
<p>I would like the user to be automatically logged in without entering username and password when they click the link in the email sent after completing the registration form.</p> <p>How can I do that?</p>
[ { "answer_id": 182586, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>Here's a basic approach.</p>\n\n<p>First, you would need to pass something in the link to give some user info you can use to log the user in. To do this, you need to filter the email that goes to the user. (It would be possible to actually load a custom new user registration email, but this would have to be done as a plugin as that function is a pluggable function. Instead of doing that, this method just filters the email content based on the subject line for the registration email.)</p>\n\n<p>// Add filter for registration email body</p>\n\n<pre><code>add_filter( 'wp_mail', 'set_up_auto_login_link' );\n\nfunction set_up_auto_login_link( $atts ) {\n\n // if the email subject is \"Your username and password\"\n if ( isset ( $atts ['subject'] ) &amp;&amp; $atts['subject'] = 'Your username and password' ) {\n if ( isset( $atts['message'] ) ) {\n\n $old = '/wp-login.php';\n $new = '/wp-login.php?user=' . $_POST['user_login'];\n\n $atts['message'] = str_replace( $old, $new, $atts['message'] );\n }\n }\n return $atts;\n}\n</code></pre>\n\n<p>This will put the selected username from the registration form into the email in the form of a query string added to the login link. That username can be used to log the user in when they click the link.</p>\n\n<p>To do this, I've hooked to the init action. This will check for the \"user\" parameter in the query string. If that exists, it uses get_user_by to get the user data by their username (login). If that returns a valid user, we can use the username and the retrieved user ID to log the user in:</p>\n\n<pre><code>add_action( 'init', 'log_user_in' );\nfunction log_user_in() {\n if ( isset( $_GET['user'] ) ) {\n\n // get the username from the URL\n $user_login = $_GET['user'];\n\n // get the user data (need the ID for login)\n $user = get_user_by( 'login', $user_login );\n\n // if a user is returned, log them in\n if ( $user &amp;&amp; ! user_can( $user-&gt;ID, 'manage_options' ) ) {\n wp_set_current_user( $user-&gt;ID, $user_login );\n wp_set_auth_cookie( $user-&gt;ID );\n do_action( 'wp_login', $user_login );\n wp_redirect( home_url() );\n exit();\n }\n }\n}\n</code></pre>\n\n<p>Note, this process doesn't give you any real security since anyone with a valid username could log in as that user. It does check to make sure the user being logged in is not an admin (user_can('manage_options')) otherwise anyone with the admin user login could gain access. It would be wise to build in some additional checks - probably create a key or hash to add to the link as well, something done at registration that could be used to validate the user.</p>\n" }, { "answer_id": 182606, "author": "Timama", "author_id": 69774, "author_profile": "https://wordpress.stackexchange.com/users/69774", "pm_score": -1, "selected": false, "text": "<pre><code>// Connect auto the new user\n $creds = array();\n $creds['user_login'] = $nom;\n $creds['user_password'] = $pass;\n $creds['remember'] = false;\n $user = wp_signon( $creds, false );\n</code></pre>\n" } ]
2015/03/28
[ "https://wordpress.stackexchange.com/questions/182582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69664/" ]
I would like the user to be automatically logged in without entering username and password when they click the link in the email sent after completing the registration form. How can I do that?
Here's a basic approach. First, you would need to pass something in the link to give some user info you can use to log the user in. To do this, you need to filter the email that goes to the user. (It would be possible to actually load a custom new user registration email, but this would have to be done as a plugin as that function is a pluggable function. Instead of doing that, this method just filters the email content based on the subject line for the registration email.) // Add filter for registration email body ``` add_filter( 'wp_mail', 'set_up_auto_login_link' ); function set_up_auto_login_link( $atts ) { // if the email subject is "Your username and password" if ( isset ( $atts ['subject'] ) && $atts['subject'] = 'Your username and password' ) { if ( isset( $atts['message'] ) ) { $old = '/wp-login.php'; $new = '/wp-login.php?user=' . $_POST['user_login']; $atts['message'] = str_replace( $old, $new, $atts['message'] ); } } return $atts; } ``` This will put the selected username from the registration form into the email in the form of a query string added to the login link. That username can be used to log the user in when they click the link. To do this, I've hooked to the init action. This will check for the "user" parameter in the query string. If that exists, it uses get\_user\_by to get the user data by their username (login). If that returns a valid user, we can use the username and the retrieved user ID to log the user in: ``` add_action( 'init', 'log_user_in' ); function log_user_in() { if ( isset( $_GET['user'] ) ) { // get the username from the URL $user_login = $_GET['user']; // get the user data (need the ID for login) $user = get_user_by( 'login', $user_login ); // if a user is returned, log them in if ( $user && ! user_can( $user->ID, 'manage_options' ) ) { wp_set_current_user( $user->ID, $user_login ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user_login ); wp_redirect( home_url() ); exit(); } } } ``` Note, this process doesn't give you any real security since anyone with a valid username could log in as that user. It does check to make sure the user being logged in is not an admin (user\_can('manage\_options')) otherwise anyone with the admin user login could gain access. It would be wise to build in some additional checks - probably create a key or hash to add to the link as well, something done at registration that could be used to validate the user.
182,594
<p>I inherited a WordPress site from a previous developer who had gone a little crazy with image sizes. As I was uploading it to the server I noticed there were at least 10 image sizes for every image. This resulted in a nice and long 9 hour upload time. </p> <p>On the site, I reckon only 3-4 of these image sizes are actually being used. </p> <p>My question is, is there a way to delete all images of a particular size? </p>
[ { "answer_id": 182586, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>Here's a basic approach.</p>\n\n<p>First, you would need to pass something in the link to give some user info you can use to log the user in. To do this, you need to filter the email that goes to the user. (It would be possible to actually load a custom new user registration email, but this would have to be done as a plugin as that function is a pluggable function. Instead of doing that, this method just filters the email content based on the subject line for the registration email.)</p>\n\n<p>// Add filter for registration email body</p>\n\n<pre><code>add_filter( 'wp_mail', 'set_up_auto_login_link' );\n\nfunction set_up_auto_login_link( $atts ) {\n\n // if the email subject is \"Your username and password\"\n if ( isset ( $atts ['subject'] ) &amp;&amp; $atts['subject'] = 'Your username and password' ) {\n if ( isset( $atts['message'] ) ) {\n\n $old = '/wp-login.php';\n $new = '/wp-login.php?user=' . $_POST['user_login'];\n\n $atts['message'] = str_replace( $old, $new, $atts['message'] );\n }\n }\n return $atts;\n}\n</code></pre>\n\n<p>This will put the selected username from the registration form into the email in the form of a query string added to the login link. That username can be used to log the user in when they click the link.</p>\n\n<p>To do this, I've hooked to the init action. This will check for the \"user\" parameter in the query string. If that exists, it uses get_user_by to get the user data by their username (login). If that returns a valid user, we can use the username and the retrieved user ID to log the user in:</p>\n\n<pre><code>add_action( 'init', 'log_user_in' );\nfunction log_user_in() {\n if ( isset( $_GET['user'] ) ) {\n\n // get the username from the URL\n $user_login = $_GET['user'];\n\n // get the user data (need the ID for login)\n $user = get_user_by( 'login', $user_login );\n\n // if a user is returned, log them in\n if ( $user &amp;&amp; ! user_can( $user-&gt;ID, 'manage_options' ) ) {\n wp_set_current_user( $user-&gt;ID, $user_login );\n wp_set_auth_cookie( $user-&gt;ID );\n do_action( 'wp_login', $user_login );\n wp_redirect( home_url() );\n exit();\n }\n }\n}\n</code></pre>\n\n<p>Note, this process doesn't give you any real security since anyone with a valid username could log in as that user. It does check to make sure the user being logged in is not an admin (user_can('manage_options')) otherwise anyone with the admin user login could gain access. It would be wise to build in some additional checks - probably create a key or hash to add to the link as well, something done at registration that could be used to validate the user.</p>\n" }, { "answer_id": 182606, "author": "Timama", "author_id": 69774, "author_profile": "https://wordpress.stackexchange.com/users/69774", "pm_score": -1, "selected": false, "text": "<pre><code>// Connect auto the new user\n $creds = array();\n $creds['user_login'] = $nom;\n $creds['user_password'] = $pass;\n $creds['remember'] = false;\n $user = wp_signon( $creds, false );\n</code></pre>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182594", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48204/" ]
I inherited a WordPress site from a previous developer who had gone a little crazy with image sizes. As I was uploading it to the server I noticed there were at least 10 image sizes for every image. This resulted in a nice and long 9 hour upload time. On the site, I reckon only 3-4 of these image sizes are actually being used. My question is, is there a way to delete all images of a particular size?
Here's a basic approach. First, you would need to pass something in the link to give some user info you can use to log the user in. To do this, you need to filter the email that goes to the user. (It would be possible to actually load a custom new user registration email, but this would have to be done as a plugin as that function is a pluggable function. Instead of doing that, this method just filters the email content based on the subject line for the registration email.) // Add filter for registration email body ``` add_filter( 'wp_mail', 'set_up_auto_login_link' ); function set_up_auto_login_link( $atts ) { // if the email subject is "Your username and password" if ( isset ( $atts ['subject'] ) && $atts['subject'] = 'Your username and password' ) { if ( isset( $atts['message'] ) ) { $old = '/wp-login.php'; $new = '/wp-login.php?user=' . $_POST['user_login']; $atts['message'] = str_replace( $old, $new, $atts['message'] ); } } return $atts; } ``` This will put the selected username from the registration form into the email in the form of a query string added to the login link. That username can be used to log the user in when they click the link. To do this, I've hooked to the init action. This will check for the "user" parameter in the query string. If that exists, it uses get\_user\_by to get the user data by their username (login). If that returns a valid user, we can use the username and the retrieved user ID to log the user in: ``` add_action( 'init', 'log_user_in' ); function log_user_in() { if ( isset( $_GET['user'] ) ) { // get the username from the URL $user_login = $_GET['user']; // get the user data (need the ID for login) $user = get_user_by( 'login', $user_login ); // if a user is returned, log them in if ( $user && ! user_can( $user->ID, 'manage_options' ) ) { wp_set_current_user( $user->ID, $user_login ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user_login ); wp_redirect( home_url() ); exit(); } } } ``` Note, this process doesn't give you any real security since anyone with a valid username could log in as that user. It does check to make sure the user being logged in is not an admin (user\_can('manage\_options')) otherwise anyone with the admin user login could gain access. It would be wise to build in some additional checks - probably create a key or hash to add to the link as well, something done at registration that could be used to validate the user.
182,595
<p>I'm attempting to add a <a href="http://codex.wordpress.org/Function_Reference/WP_List_Table">list table</a> to a custom admin page. I've been following <a href="http://www.smashingmagazine.com/2011/11/03/native-admin-tables-wordpress/">this guide</a> and <a href="https://wordpress.org/plugins/custom-list-table-example/">this reference implementation</a>.</p> <p>Unfortunately when I define <code>$this-&gt;items</code> to add the data, <strong>nothing</strong> displays in the admin page (not even the html around the list table) and there are no error messages. If I comment that line out (line <code>135</code>), then it works except for the obvious lack of data.</p> <p>My code:</p> <pre><code>&lt;?php add_action('admin_menu', 'add_example_menues'); function add_example_menues() { add_menu_page('test', 'test', 'administrator', 'test-top', 'build_test_page'); add_submenu_page('test-top', 'All tests', 'All tests', 'administrator', 'test-top'); } if(!class_exists('WP_List_Table')){ require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } class test_List_Table extends WP_List_Table { function __construct() { parent::__construct( array( 'singular' =&gt; 'test', 'plural' =&gt; 'tests', 'ajax' =&gt; false )); } function extra_tablenav ($which) { if ($which == "top") { echo "Top"; } if ($which == "bottom") { echo "Bottom"; } } function get_columns() { $columns = array( 'id' =&gt; 'ID', 'title' =&gt; 'Title', 'user_id' =&gt; 'User ID', 'description' =&gt; 'Description' ); return $columns; } function get_sortable_columns() { return $sortable = array( 'id' =&gt; array('id',false), 'title' =&gt; array('title',false), 'user_id' =&gt; array('user_id',false) ); } function prepare_items() { global $wpdb; //data normally gotten from non-wp database. Wordpress db user has access, as per this SE post: //http://wordpress.stackexchange.com/questions/1604/using-wpdb-to-connect-to-a-separate-database $query = "SELECT `id`, `title`, `user_id`, `description` FROM otherdb.example_table"; //pagination stuff $orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC'; $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : ''; if(!empty($orderby) &amp; !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; } $totalitems = $wpdb-&gt;query($query); echo "$totalitems"; $per_page = 5; $paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : ''; if(empty($paged) || !is_numeric($paged) || $paged&lt;=0 ){ $paged=1; } $totalpages = ceil($totalitems/$perpage); if(!empty($paged) &amp;&amp; !empty($perpage)){ $offset=($paged-1)*$perpage; $query.=' LIMIT '.(int)$offset.','.(int)$perpage; } $this-&gt;set_pagination_args( array( "total_items" =&gt; 4, "total_pages" =&gt; 1, "per_page" =&gt; 5, ) ); $columns = $this-&gt;get_columns(); $hidden = array(); $sortable = $this-&gt;get_sortable_columns(); $this-&gt;_column_headers = array($columns, $hidden, $sortable); //actual data gotten from database, but for SE use hardcoded array //$data = $wpdb-&gt;get_results($query, ARRAY_N); $example_data = array( array( 'id' =&gt; 1, 'title' =&gt; 'nonsense', 'user_id' =&gt; 1, 'description' =&gt; 'asdf' ), array( 'id' =&gt; 2, 'title' =&gt; 'notanumber', 'user_id' =&gt; 2, 'description' =&gt; '404' ), array( 'id' =&gt; 3, 'title' =&gt; 'I Am A Title', 'user_id' =&gt; 3, 'description' =&gt; 'desc' ), array( 'id' =&gt; 4, 'title' =&gt; 'Example', 'user_id' =&gt; 4, 'description' =&gt; 'useless' ), array( 'id' =&gt; 5, 'title' =&gt; 'aeou', 'user_id' =&gt; 5, 'description' =&gt; 'keyboard layouts' ), array( 'id' =&gt; 6, 'title' =&gt; 'example data', 'user_id' =&gt; 6, 'description' =&gt; 'data example' ), array( 'id' =&gt; 7, 'title' =&gt; 'last one', 'user_id' =&gt; 7, 'description' =&gt; 'done' ) ); //This is the line: $this-&gt;items = $example_data; //When the above line is commented, it works as expected (except for the lack of data, of course) } } function build_test_page() { $testListTable = new test_List_Table(); $testListTable-&gt;prepare_items(); ?&gt; &lt;div class="wrap"&gt; &lt;div id="icon-users" class="icon32"&gt;&lt;br/&gt;&lt;/div&gt; &lt;h2&gt;List Table Test&lt;/h2&gt; &lt;?php $testListTable-&gt;display() ?&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>The above code is in a separate file, included into <code>functions.php</code> with a <code>require_once()</code>.</p> <p>I'm using wordpress 4.1.1</p> <p>What is going on here? Why would <em>everything</em> disappear and no error be given?</p>
[ { "answer_id": 182846, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>Now at home, I actually ran your code. I got this:</p>\n\n<blockquote>\n <p>Fatal error: Call to undefined function convert_to_screen() in\n .../wp-admin/includes/class-wp-list-table.php\n on line 88</p>\n</blockquote>\n\n<p><strong>Note:</strong></p>\n\n<blockquote>\n <p>Please turn on <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">Debugging_in_WordPress</a> when developing.</p>\n</blockquote>\n\n<p>Anyway this lead me to the following question on <em>Stackoverflow</em>:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/22371861/wordpress-wp-list-table-implemantation\">Wordpress WP List Table Implemantation</a></li>\n</ul>\n\n<p>@brasofilo's answer helped a lot, not surprising as he is one of the leading people on <em>WordPress Development</em> too.</p>\n\n<p>Anyway following his answer, you are missing the method <code>column_default</code>, additionally the <code>_construct</code> method is different. But you can read that up yourself, here is some working - stripped down - code:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_test_list_table_menues' );\nfunction add_test_list_table_menues() {\n add_menu_page(\n 'test', \n 'test', \n 'manage_options', \n 'test-top', \n 'test_list_table_output'\n );\n}\n\nfunction test_list_table_output() { \n echo '&lt;div class=\"wrap\"&gt;';\n echo '&lt;h2&gt;Test List Table&lt;/h2&gt;';\n new Test_List_Table(); \n echo '&lt;/div&gt;';\n}\n\nif( ! class_exists( 'WP_List_Table' ) ) {\n require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );\n}\n\nclass Test_List_Table extends WP_List_Table {\n public function __construct() {\n parent::__construct( array(\n 'singular' =&gt; 'test',\n 'plural' =&gt; 'tests',\n 'ajax' =&gt; false\n ));\n $this-&gt;prepare_items();\n $this-&gt;display();\n }\n\n function get_columns() {\n $columns = array(\n 'tid' =&gt; 'ID',\n 'title' =&gt; 'Title',\n 'user_id' =&gt; 'User ID',\n 'description' =&gt; 'Description'\n );\n return $columns;\n }\n\n function column_default( $item, $column_name ) {\n switch( $column_name ) {\n case 'tid':\n case 'title':\n case 'user_id':\n case 'description':\n return $item[ $column_name ];\n default:\n return print_r( $item, true ) ;\n }\n }\n\n function prepare_items() {\n $example_data = array(\n array(\n 'tid' =&gt; 1,\n 'title' =&gt; 'nonsense',\n 'user_id' =&gt; 1,\n 'description' =&gt; 'asdf'\n ),\n array(\n 'tid' =&gt; 2,\n 'title' =&gt; 'notanumber',\n 'user_id' =&gt; 2,\n 'description' =&gt; '404'\n ),\n array(\n 'tid' =&gt; 3,\n 'title' =&gt; 'I Am A Title',\n 'user_id' =&gt; 3,\n 'description' =&gt; 'desc'\n ),\n array(\n 'tid' =&gt; 4,\n 'title' =&gt; 'Example',\n 'user_id' =&gt; 4,\n 'description' =&gt; 'useless'\n ),\n array(\n 'tid' =&gt; 5,\n 'title' =&gt; 'aeou',\n 'user_id' =&gt; 5,\n 'description' =&gt; 'keyboard layouts'\n ),\n array(\n 'tid' =&gt; 6,\n 'title' =&gt; 'example data',\n 'user_id' =&gt; 6,\n 'description' =&gt; 'data example'\n ),\n array(\n 'tid' =&gt; 7,\n 'title' =&gt; 'last one',\n 'user_id' =&gt; 7,\n 'description' =&gt; 'done'\n )\n );\n\n $columns = $this-&gt;get_columns();\n $hidden = array();\n $sortable = $this-&gt;get_sortable_columns();\n $this-&gt;_column_headers = array($columns, $hidden, $sortable);\n $this-&gt;items = $example_data;\n }\n}\n</code></pre>\n" }, { "answer_id": 182866, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 5, "selected": true, "text": "<p>I did same error first time I implemented <code>WP_List_Table</code>.</p>\n\n<p>The problem is that when you call <code>WP_List_Table::display()</code> WordPress in turn calls:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/wp_list_table/display_rows_or_placeholder/\">WP_List_Table::display_rows_or_placeholder()</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/wp_list_table/display_rows/\">WP_List_Table::display_rows()</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/wp_list_table/single_row/\">WP_List_Table::single_row()</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/wp_list_table/single_row_columns/\">WP_List_Table::single_row_columns()</a></li>\n</ul>\n\n<p>Last function is called for every row. If you look at its code (see <a href=\"https://github.com/WordPress/WordPress/blob/19dbf7b998019ec87f7088339945d1c56f4b86d7/wp-admin/includes/class-wp-list-table.php#L1073-L1087\">source</a>), it has:</p>\n\n<pre><code>if ( 'cb' == $column_name ) {\n // you don't have 'cb' column, code remove because not relevant\n} elseif ( method_exists( $this, 'column_' . $column_name ) ) {\n // you don't have method named 'column_{$column_name}',\n // code remove because not relevant \n} else {\n // not relevant line\n echo $this-&gt;column_default( $item, $column_name );\n}\n</code></pre>\n\n<p>So WordPress calls <code>WP_List_Table::column_default()</code> for every row, but... that method <a href=\"https://developer.wordpress.org/reference/classes/wp_list_table/\"><strong>doesn't exist</strong></a>.</p>\n\n<p>Add to your class:</p>\n\n<pre><code>public function column_default($item, $column_name) {\n return $item[$column_name];\n}\n</code></pre>\n\n<p>And your data will be correctly displayed.</p>\n\n<p>When you don't add data, error doesn't show up because with no data WordPress never calls <code>display_rows()</code> and other methods after that.</p>\n\n<hr>\n\n<h2>Bonus Notes:</h2>\n\n<ol>\n<li><p>In your <code>prepare_items()</code> method you use the variable <code>$perpage</code> but you define it as <code>$per_page</code> (notice the underscore), that cause a division-by-zero warning (and pagination doesn't work)</p></li>\n<li><p>the code <code>mysql_real_escape_string($_GET[\"orderby\"])</code> is <strong>not</strong> safe, because for <code>'orderby'</code> SQL clause <code>mysql_real_escape_string()</code> is not enough. (see <a href=\"https://wpvulndb.com/vulnerabilities/7841\">recent Yoast SQL injection bug</a>).</p>\n\n<p>Do something like:</p>\n\n<pre><code>$orderby = 'id'; // default\n$by = strtolower(filter_input(INPUT_GET, 'orderby', FILTER_SANITIZE_STRING));\nif (in_array($by, array('title', 'description', 'user_id'), true) {\n $orderby = $by;\n}\n</code></pre>\n\n<p>and do something similar to for <code>'order'</code> clause as well: very probably it can only be either <code>ASC</code> or <code>DESC</code>: don't allow anything else.</p></li>\n</ol>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68936/" ]
I'm attempting to add a [list table](http://codex.wordpress.org/Function_Reference/WP_List_Table) to a custom admin page. I've been following [this guide](http://www.smashingmagazine.com/2011/11/03/native-admin-tables-wordpress/) and [this reference implementation](https://wordpress.org/plugins/custom-list-table-example/). Unfortunately when I define `$this->items` to add the data, **nothing** displays in the admin page (not even the html around the list table) and there are no error messages. If I comment that line out (line `135`), then it works except for the obvious lack of data. My code: ``` <?php add_action('admin_menu', 'add_example_menues'); function add_example_menues() { add_menu_page('test', 'test', 'administrator', 'test-top', 'build_test_page'); add_submenu_page('test-top', 'All tests', 'All tests', 'administrator', 'test-top'); } if(!class_exists('WP_List_Table')){ require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } class test_List_Table extends WP_List_Table { function __construct() { parent::__construct( array( 'singular' => 'test', 'plural' => 'tests', 'ajax' => false )); } function extra_tablenav ($which) { if ($which == "top") { echo "Top"; } if ($which == "bottom") { echo "Bottom"; } } function get_columns() { $columns = array( 'id' => 'ID', 'title' => 'Title', 'user_id' => 'User ID', 'description' => 'Description' ); return $columns; } function get_sortable_columns() { return $sortable = array( 'id' => array('id',false), 'title' => array('title',false), 'user_id' => array('user_id',false) ); } function prepare_items() { global $wpdb; //data normally gotten from non-wp database. Wordpress db user has access, as per this SE post: //http://wordpress.stackexchange.com/questions/1604/using-wpdb-to-connect-to-a-separate-database $query = "SELECT `id`, `title`, `user_id`, `description` FROM otherdb.example_table"; //pagination stuff $orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC'; $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : ''; if(!empty($orderby) & !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; } $totalitems = $wpdb->query($query); echo "$totalitems"; $per_page = 5; $paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : ''; if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; } $totalpages = ceil($totalitems/$perpage); if(!empty($paged) && !empty($perpage)){ $offset=($paged-1)*$perpage; $query.=' LIMIT '.(int)$offset.','.(int)$perpage; } $this->set_pagination_args( array( "total_items" => 4, "total_pages" => 1, "per_page" => 5, ) ); $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array($columns, $hidden, $sortable); //actual data gotten from database, but for SE use hardcoded array //$data = $wpdb->get_results($query, ARRAY_N); $example_data = array( array( 'id' => 1, 'title' => 'nonsense', 'user_id' => 1, 'description' => 'asdf' ), array( 'id' => 2, 'title' => 'notanumber', 'user_id' => 2, 'description' => '404' ), array( 'id' => 3, 'title' => 'I Am A Title', 'user_id' => 3, 'description' => 'desc' ), array( 'id' => 4, 'title' => 'Example', 'user_id' => 4, 'description' => 'useless' ), array( 'id' => 5, 'title' => 'aeou', 'user_id' => 5, 'description' => 'keyboard layouts' ), array( 'id' => 6, 'title' => 'example data', 'user_id' => 6, 'description' => 'data example' ), array( 'id' => 7, 'title' => 'last one', 'user_id' => 7, 'description' => 'done' ) ); //This is the line: $this->items = $example_data; //When the above line is commented, it works as expected (except for the lack of data, of course) } } function build_test_page() { $testListTable = new test_List_Table(); $testListTable->prepare_items(); ?> <div class="wrap"> <div id="icon-users" class="icon32"><br/></div> <h2>List Table Test</h2> <?php $testListTable->display() ?> </div> <?php } ?> ``` The above code is in a separate file, included into `functions.php` with a `require_once()`. I'm using wordpress 4.1.1 What is going on here? Why would *everything* disappear and no error be given?
I did same error first time I implemented `WP_List_Table`. The problem is that when you call `WP_List_Table::display()` WordPress in turn calls: * [WP\_List\_Table::display\_rows\_or\_placeholder()](https://developer.wordpress.org/reference/classes/wp_list_table/display_rows_or_placeholder/) * [WP\_List\_Table::display\_rows()](https://developer.wordpress.org/reference/classes/wp_list_table/display_rows/) * [WP\_List\_Table::single\_row()](https://developer.wordpress.org/reference/classes/wp_list_table/single_row/) * [WP\_List\_Table::single\_row\_columns()](https://developer.wordpress.org/reference/classes/wp_list_table/single_row_columns/) Last function is called for every row. If you look at its code (see [source](https://github.com/WordPress/WordPress/blob/19dbf7b998019ec87f7088339945d1c56f4b86d7/wp-admin/includes/class-wp-list-table.php#L1073-L1087)), it has: ``` if ( 'cb' == $column_name ) { // you don't have 'cb' column, code remove because not relevant } elseif ( method_exists( $this, 'column_' . $column_name ) ) { // you don't have method named 'column_{$column_name}', // code remove because not relevant } else { // not relevant line echo $this->column_default( $item, $column_name ); } ``` So WordPress calls `WP_List_Table::column_default()` for every row, but... that method [**doesn't exist**](https://developer.wordpress.org/reference/classes/wp_list_table/). Add to your class: ``` public function column_default($item, $column_name) { return $item[$column_name]; } ``` And your data will be correctly displayed. When you don't add data, error doesn't show up because with no data WordPress never calls `display_rows()` and other methods after that. --- Bonus Notes: ------------ 1. In your `prepare_items()` method you use the variable `$perpage` but you define it as `$per_page` (notice the underscore), that cause a division-by-zero warning (and pagination doesn't work) 2. the code `mysql_real_escape_string($_GET["orderby"])` is **not** safe, because for `'orderby'` SQL clause `mysql_real_escape_string()` is not enough. (see [recent Yoast SQL injection bug](https://wpvulndb.com/vulnerabilities/7841)). Do something like: ``` $orderby = 'id'; // default $by = strtolower(filter_input(INPUT_GET, 'orderby', FILTER_SANITIZE_STRING)); if (in_array($by, array('title', 'description', 'user_id'), true) { $orderby = $by; } ``` and do something similar to for `'order'` clause as well: very probably it can only be either `ASC` or `DESC`: don't allow anything else.
182,615
<p>I´m trying to do an simple Wordpress-App for my Homepage.</p> <p>I started using Appery.io, which is actually a good environment for a non-programmer.</p> <p>But I wonder if anybody has experiences in hooking up a Wordpress Site to an App by Appery? Where would I start?</p> <p>What my basic needs are:</p> <p>1) Read the Articles 2) Comment on Articles directly in-App 3) Push-Notification about new article/comment</p>
[ { "answer_id": 182640, "author": "vozer", "author_id": 45103, "author_profile": "https://wordpress.stackexchange.com/users/45103", "pm_score": 0, "selected": false, "text": "<p>I got it done! </p>\n\n<p>The key to all of it is to use a Plugin like \"JSON API\" in your Wordprss Installation to get your posts/etc. </p>\n\n<p>For example you can later type www.example.com/json?get_posts</p>\n\n<p>With the generated link you can go to appery and connect it as a REST API Service.</p>\n\n<p>Haven´t tried all the functionalities yet, but i believe this is the way to go.</p>\n" }, { "answer_id": 236655, "author": "connorb", "author_id": 85542, "author_profile": "https://wordpress.stackexchange.com/users/85542", "pm_score": 2, "selected": false, "text": "<p>If you're using Wordpress 4.6, you can use the REST API without the need for the plugin by simply using the following:</p>\n\n<pre><code>add_action('rest_api_init', function() {\n\n $namespace = 'myapi';\n\n register_rest_route($namespace, '/myroute', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'handle_my_route'\n ), true);\n\n function handle_my_route() {\n return 'Hello World!';\n }\n}\n</code></pre>\n\n<p>Then, going to: <code>yourwebsite/wp-json/myapi/myroute</code> would return the callback value, which in the case above is 'Hello World'.</p>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45103/" ]
I´m trying to do an simple Wordpress-App for my Homepage. I started using Appery.io, which is actually a good environment for a non-programmer. But I wonder if anybody has experiences in hooking up a Wordpress Site to an App by Appery? Where would I start? What my basic needs are: 1) Read the Articles 2) Comment on Articles directly in-App 3) Push-Notification about new article/comment
If you're using Wordpress 4.6, you can use the REST API without the need for the plugin by simply using the following: ``` add_action('rest_api_init', function() { $namespace = 'myapi'; register_rest_route($namespace, '/myroute', array( 'methods' => 'GET', 'callback' => 'handle_my_route' ), true); function handle_my_route() { return 'Hello World!'; } } ``` Then, going to: `yourwebsite/wp-json/myapi/myroute` would return the callback value, which in the case above is 'Hello World'.
182,621
<p>Instead of weighing the site down with plugins I've hardcoded a couple of sharing links.</p> <p>I've used the_permalink to create the links, in the sidebar, which work ok on posts and pages, but on the homepage it shows the link of the last post, not the homepage.</p> <p>The code I'm using is pretty basic:</p> <pre><code>&lt;a href="http://www.facebook.com/sharer.php?u=&lt;?php the_permalink();?&gt;&amp;amp;t=&lt;?php the_title(); ?&gt;" target="_blank"&gt;Share this on Facebook&lt;/a&gt; </code></pre> <p>How can I get the homepage sharing link to use the homepage url, while also working for the posts and pages?</p>
[ { "answer_id": 182640, "author": "vozer", "author_id": 45103, "author_profile": "https://wordpress.stackexchange.com/users/45103", "pm_score": 0, "selected": false, "text": "<p>I got it done! </p>\n\n<p>The key to all of it is to use a Plugin like \"JSON API\" in your Wordprss Installation to get your posts/etc. </p>\n\n<p>For example you can later type www.example.com/json?get_posts</p>\n\n<p>With the generated link you can go to appery and connect it as a REST API Service.</p>\n\n<p>Haven´t tried all the functionalities yet, but i believe this is the way to go.</p>\n" }, { "answer_id": 236655, "author": "connorb", "author_id": 85542, "author_profile": "https://wordpress.stackexchange.com/users/85542", "pm_score": 2, "selected": false, "text": "<p>If you're using Wordpress 4.6, you can use the REST API without the need for the plugin by simply using the following:</p>\n\n<pre><code>add_action('rest_api_init', function() {\n\n $namespace = 'myapi';\n\n register_rest_route($namespace, '/myroute', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'handle_my_route'\n ), true);\n\n function handle_my_route() {\n return 'Hello World!';\n }\n}\n</code></pre>\n\n<p>Then, going to: <code>yourwebsite/wp-json/myapi/myroute</code> would return the callback value, which in the case above is 'Hello World'.</p>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182621", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58011/" ]
Instead of weighing the site down with plugins I've hardcoded a couple of sharing links. I've used the\_permalink to create the links, in the sidebar, which work ok on posts and pages, but on the homepage it shows the link of the last post, not the homepage. The code I'm using is pretty basic: ``` <a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php the_title(); ?>" target="_blank">Share this on Facebook</a> ``` How can I get the homepage sharing link to use the homepage url, while also working for the posts and pages?
If you're using Wordpress 4.6, you can use the REST API without the need for the plugin by simply using the following: ``` add_action('rest_api_init', function() { $namespace = 'myapi'; register_rest_route($namespace, '/myroute', array( 'methods' => 'GET', 'callback' => 'handle_my_route' ), true); function handle_my_route() { return 'Hello World!'; } } ``` Then, going to: `yourwebsite/wp-json/myapi/myroute` would return the callback value, which in the case above is 'Hello World'.
182,635
<p>How can I add a single WordPress function for all WordPress actions/event.</p> <p>I want to add something equivalent to the one which is below</p> <pre><code>add_Action('All WordPress Event/Actions', 'My_Function'); </code></pre> <p>And also I wanted to make this function compatible such a way that I will get all system implicit arguments like below</p> <ul> <li><p><code>My_Function($content);</code></p></li> <li><p><code>My_Function($postId);</code> </p></li> </ul> <p><code>$content</code> and <code>$postId</code> are implicit arguments passed by WordPress system...</p>
[ { "answer_id": 182637, "author": "David Lawrence", "author_id": 69813, "author_profile": "https://wordpress.stackexchange.com/users/69813", "pm_score": 1, "selected": false, "text": "<p>This is a very very bad idea.</p>\n\n<p>You can achieve this by doing something like this:</p>\n\n<pre><code>add_action( 'init', function(){\n do_action()//rinse recycle repeat for every hook\n});\n</code></pre>\n\n<p>I highly highly HIGHLY recommend you do not take this route. It can cause a lot of problems of hooks firing when not needed etc.</p>\n\n<p>The idea of a hook is to extend the functionality of the process being processed at the given time, they are supplied data that is only available during certain actions like adding comments.</p>\n\n<p>If you do_action for every single hook, it could be catastrophic. Not to mention you'd not have data for each hook.</p>\n\n<p>If you are looking to fire a function literally every time a page is loaded, then use the init hook, for admin panel only use admin_init</p>\n\n<p>But don't fire every single WordPress action in one hook. It's just not a good idea</p>\n\n<p>Just to cover <strong>all</strong> grounds</p>\n\n<p>Do:</p>\n\n<pre><code>add_action( 'init', function(){\n add_action( 'hook', function(){\n // do code here\n })\n})\n</code></pre>\n\n<p>This will fire the function on every hook but don't fire every hook on one hook.\nOf course you would do a separate add_action for every hook you wanted to fire the function on, but there is no real way to fire hooks.</p>\n\n<p>A little better route to reuse code could be:</p>\n\n<pre><code>add_action( 'init', function(){\n $hooks = array(\n 'hook1',\n 'hook2',\n 'hook3'//and so on.\n );\n\n foreach( $hooks as $hook ){\n\n add_action( $hook, function(){\n // Do code\n });\n }\n\n // Do the same but in add_filter\n});\n</code></pre>\n\n<p>Again to cover all grounds, this method directly above would add the action / filter but the action / filter would not fire until it is fired with apply_filter or do_action, this simply just adds the function to the action or filter.</p>\n\n<p>Then you'd have to work on accepting the args of the function, without supplying the 4th argument on add_action you are guaranteed only 1 argument so you would have to filter in your code what argument you are work with, with some if or elses.</p>\n\n<p>In response to a comment to elaborate on the arg you could do something similar to:</p>\n\n<pre><code>add_action( 'init', function(){\n $hooks = array(\n 'hook1' =&gt; array( 'argname1', 'argname2', 'argname3' ),\n 'hook2' =&gt; array( 'argname1', 'argname2', 'argname3' ),\n 'hook3' =&gt; array( 'argname1', 'argname2', 'argname3' )//and so on.\n );\n\n foreach( $hooks as $hook=&gt;$args ){\n add_action( $hook, function(){\n\n $numargs = func_num_args();\n for( $i=0; $i&lt;$numargs; $i++ ){\n $$args[$i] = func_get_arg($i);\n }\n // Do code\n }, 10, count( $args ) );\n }\n\n // Do the same but in add_filter\n });\n</code></pre>\n\n<p>Then with the for you'd obviously judge the number of args you need to avoid errors.</p>\n\n<p>To better avoid errors, check the $args[$i] exists or is not empty, before setting a func_get_arg to it.</p>\n\n<p>Response to comment: here's a real time example of how you would use this with save_post action</p>\n\n<pre><code>add_action( 'init', function(){\n $hooks = array(\n 'save_post' =&gt; array( 'post_id', 'post', 'update' )\n );\n\n foreach( $hooks as $hook=&gt;$arg ){\n add_action( $hook, function(){ // Note we dont do any args here \n $num_args = func_num_args(); // would return 3 because we supplied 3 args\n for( $i=0; $i&lt;$num_args; $i++ ){\n if( !empty( $arg[$i] ) ){\n $$arg[$i] = func_get_arg( $i );\n // We use !empty as it will check if isset AND not empty\n // This would set all three array values to the respective variable\n // $post_id, $post, $update\n // Make sure you put the args in the right order in the hooks array above to avoid mixing up var names.\n\n }\n }\n\n if( isset( $post ) ){\n update_post_meta( $post-&gt;ID, 'meta_key_whatever_you_want', 'meta_value_whateveryouwant' );\n // I used $post to show you that the second argumnet supplied by do_action is $post and we set $$arg[1] as $post and retrieved the arg with same key 1 Normally you would just use post_id\n\n }\n\n // Can do with any of the args just be carefull.\n }, 10, count( $args ) ); \n // We count the hook arg array which is the array with simple strings for our variable names and supply it to add_action to let wordpress know we want 3 arguments. If you supply more than 3 arguments you may get errors for this hook, so setting array with 50 args for a hook that only supplies 3 is not good.\n // 10 is simply priority in which this hook fires.\n }\n});\n</code></pre>\n\n<p>This is just one way you can do this, then you would just do a array key for hook and array for arguments for each hook and check if the variable is set. You may want to do some additional verification on variables to make sure you have the right data as some hooks share variable names, though you can customize, so $post_id can be set to $$arg[0] and in the arg array set as 'post_id_custom' which would be set to $post_id_custom with the hooks $post_id supplied data.</p>\n\n<p>One more thing, to really completely simplify things you can do this too:</p>\n\n<pre><code>function someFunc(){\n // do code here\n}\n\nadd_action('hook1', 'someFunc' );\nadd_action('hook2', 'someFunc' );\nadd_action('hook3', 'someFunc' );\nadd_action('hook4', 'someFunc' );\n</code></pre>\n\n<p>this will fire the same fun with all of the action hooks supplied.</p>\n\n<pre><code>add_action( 'all', function() {\n static $hooks = [];\n global $allhooks;\n\n $filter = current_filter();\n\n if ( isset ( $hooks[ $filter ] ) )\n return;\n\n $types = array_map( function ( $arg ) {\n return $arg;\n }, func_get_args() );\n\n $hooks[$filter] = $types;\n\n if( 'shutdown' !== $filter )\n return;\n\n foreach( $hooks as $hook=&gt;$args ){\n $allhooks[$hook] = $args;\n }\n\n});\n\nadd_action( 'shutdown', function(){\n global $allhooks;\n var_dump( $allhooks );\n});\n</code></pre>\n\n<p>This will print all hooks and all args that come with the hooks fyi. Simple modification of toscho's code, it var_dumps something like this for every hook.</p>\n\n<pre><code>array (size=809)\n 'after_setup_theme' =&gt; \n array (size=1)\n 0 =&gt; string 'after_setup_theme' (length=17)\n 'ot_theme_mode' =&gt; \n array (size=2)\n 0 =&gt; string 'ot_theme_mode' (length=13)\n 1 =&gt; boolean false\n 'ot_child_theme_mode' =&gt; \n array (size=2)\n 0 =&gt; string 'ot_child_theme_mode' (length=19)\n 1 =&gt; boolean false\n 'ot_show_pages' =&gt; \n array (size=2)\n 0 =&gt; string 'ot_show_pages' (length=13)\n 1 =&gt; boolean true\n</code></pre>\n\n<p>This just dumps it to the browser, simply reiterating and helping explain to you what toscho is saying that argument names are not supplied only values.</p>\n\n<p>After review, it's missing hooks like save_post. So even the all hook doesn't supply every action and filter.</p>\n\n<p>There really is no way to accomplish this, and it is really a bad idea.</p>\n\n<p>Again I'm not a WordPress expert.</p>\n" }, { "answer_id": 182639, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>There is a special action <code>all</code> that you can use. Be aware, this will be very slow, don’t do that in production.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>add_action( 'all', function() {\n\n static $hooks = [];\n\n $filter = current_filter();\n\n if ( isset ( $hooks[ $filter ] ) )\n return;\n\n $types = array_map( function ( $arg ) {\n return gettype( $arg );\n }, func_get_args() );\n\n $hooks[ $filter ] = count( $types ) . ' arguments: ' . join( \",\\t\", $types );\n\n if ( 'shutdown' !== $filter )\n return;\n\n $text = \"\\n\\nFILE: \" . $_SERVER['REQUEST_URI'] . ' ' . date( 'Y.m.d. H:i:s' ) . \"\\n\\n\";\n\n foreach ( $hooks as $hook =&gt; $args )\n $text .= str_pad( $hook, 50 ) . \" =&gt; $args\\n\";\n\n $file = WP_CONTENT_DIR . '/hook.log';\n file_put_contents( $file, $text, FILE_APPEND | LOCK_EX );\n});\n</code></pre>\n\n<p>Now you get all hooks listed in a file <code>hooks.log</code>. Sample output:</p>\n\n<pre><code>FILE: /wp-admin/admin-ajax.php 2015.03.29. 17:25:41\n\nmuplugins_loaded =&gt; 1 arguments: string\npre_site_option_siteurl =&gt; 2 arguments: string, boolean\nsite_option_siteurl =&gt; 2 arguments: string, string\npre_option_siteurl =&gt; 2 arguments: string, boolean\noption_siteurl =&gt; 2 arguments: string, string\ngettext_with_context =&gt; 5 arguments: string, string, string, string, string\ngettext =&gt; 4 arguments: string, string, string, string\nregistered_taxonomy =&gt; 4 arguments: string, string, string, array\nsanitize_key =&gt; 3 arguments: string, string, string\npost_type_labels_post =&gt; 2 arguments: string, object\nregistered_post_type =&gt; 3 arguments: string, string, object\npost_type_labels_page =&gt; 2 arguments: string, object\npost_type_labels_attachment =&gt; 2 arguments: string, object\npost_type_labels_revision =&gt; 2 arguments: string, object\npost_type_labels_nav_menu_item =&gt; 2 arguments: string, object\ntheme_root =&gt; 2 arguments: string, string\npre_option_active_plugins =&gt; 2 arguments: string, boolean\n…\n</code></pre>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182635", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69814/" ]
How can I add a single WordPress function for all WordPress actions/event. I want to add something equivalent to the one which is below ``` add_Action('All WordPress Event/Actions', 'My_Function'); ``` And also I wanted to make this function compatible such a way that I will get all system implicit arguments like below * `My_Function($content);` * `My_Function($postId);` `$content` and `$postId` are implicit arguments passed by WordPress system...
There is a special action `all` that you can use. Be aware, this will be very slow, don’t do that in production. Here is an example: ``` add_action( 'all', function() { static $hooks = []; $filter = current_filter(); if ( isset ( $hooks[ $filter ] ) ) return; $types = array_map( function ( $arg ) { return gettype( $arg ); }, func_get_args() ); $hooks[ $filter ] = count( $types ) . ' arguments: ' . join( ",\t", $types ); if ( 'shutdown' !== $filter ) return; $text = "\n\nFILE: " . $_SERVER['REQUEST_URI'] . ' ' . date( 'Y.m.d. H:i:s' ) . "\n\n"; foreach ( $hooks as $hook => $args ) $text .= str_pad( $hook, 50 ) . " => $args\n"; $file = WP_CONTENT_DIR . '/hook.log'; file_put_contents( $file, $text, FILE_APPEND | LOCK_EX ); }); ``` Now you get all hooks listed in a file `hooks.log`. Sample output: ``` FILE: /wp-admin/admin-ajax.php 2015.03.29. 17:25:41 muplugins_loaded => 1 arguments: string pre_site_option_siteurl => 2 arguments: string, boolean site_option_siteurl => 2 arguments: string, string pre_option_siteurl => 2 arguments: string, boolean option_siteurl => 2 arguments: string, string gettext_with_context => 5 arguments: string, string, string, string, string gettext => 4 arguments: string, string, string, string registered_taxonomy => 4 arguments: string, string, string, array sanitize_key => 3 arguments: string, string, string post_type_labels_post => 2 arguments: string, object registered_post_type => 3 arguments: string, string, object post_type_labels_page => 2 arguments: string, object post_type_labels_attachment => 2 arguments: string, object post_type_labels_revision => 2 arguments: string, object post_type_labels_nav_menu_item => 2 arguments: string, object theme_root => 2 arguments: string, string pre_option_active_plugins => 2 arguments: string, boolean … ```
182,655
<p>I need some help I have the iteration working for listing the wordpress users however I also want to wrap their names in links and can't seem to get the user url to work... Nothing is returned to me.</p> <p>Here is what I have so far.... You will see that I am trying to pull in the user_url however it just returns as nothing. Any help would be great! Thanks</p> <pre><code>&lt;?php $blogusers = get_users( array( 'role' =&gt; 'subscriber', 'fields' =&gt; 'all' ) ); echo '&lt;ul&gt;'; foreach ( $blogusers as $user ) { echo '&lt;li&gt;&lt;a href="' . $user-&gt;user_url . '"&gt;' . $user-&gt;display_name . '&lt;/a&gt;'; } echo '&lt;/ul&gt;' ?&gt; </code></pre>
[ { "answer_id": 182658, "author": "bjrdesign", "author_id": 69824, "author_profile": "https://wordpress.stackexchange.com/users/69824", "pm_score": -1, "selected": false, "text": "<p>Just needed to use <code>get_author_posts_url($user-&gt;ID)</code></p>\n" }, { "answer_id": 182666, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 1, "selected": false, "text": "<p>You could take a look at the contributors function included in Twenty Fourteen</p>\n\n<pre><code>if ( ! function_exists( 'twentyfourteen_list_authors' ) ) :\n/**\n * Print a list of all site contributors who published at least one post.\n *\n * @since Twenty Fourteen 1.0\n */\nfunction twentyfourteen_list_authors() {\n $contributor_ids = get_users( array(\n 'fields' =&gt; 'ID',\n 'orderby' =&gt; 'post_count',\n 'order' =&gt; 'DESC',\n 'who' =&gt; 'authors',\n ) );\n\n foreach ( $contributor_ids as $contributor_id ) :\n $post_count = count_user_posts( $contributor_id );\n\n // Move on if user has not published a post (yet).\n if ( ! $post_count ) {\n continue;\n }\n ?&gt;\n\n &lt;div class=\"contributor\"&gt;\n &lt;div class=\"contributor-info\"&gt;\n &lt;div class=\"contributor-avatar\"&gt;&lt;?php echo get_avatar( $contributor_id, 132 ); ?&gt;&lt;/div&gt;\n &lt;div class=\"contributor-summary\"&gt;\n &lt;h2 class=\"contributor-name\"&gt;&lt;?php echo get_the_author_meta( 'display_name', $contributor_id ); ?&gt;&lt;/h2&gt;\n &lt;p class=\"contributor-bio\"&gt;\n &lt;?php echo get_the_author_meta( 'description', $contributor_id ); ?&gt;\n &lt;/p&gt;\n &lt;a class=\"button contributor-posts-link\" href=\"&lt;?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?&gt;\"&gt;\n &lt;?php printf( _n( '%d Article', '%d Articles', $post_count, 'twentyfourteen' ), $post_count ); ?&gt;\n &lt;/a&gt;\n &lt;/div&gt;&lt;!-- .contributor-summary --&gt;\n &lt;/div&gt;&lt;!-- .contributor-info --&gt;\n &lt;/div&gt;&lt;!-- .contributor --&gt;\n\n &lt;?php\n endforeach;\n}\nendif;\n</code></pre>\n\n<p>You could also change the <a href=\"https://codex.wordpress.org/Function_Reference/get_users#Parameters\" rel=\"nofollow\"><code>get_users</code></a> function to <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\"><code>WP_User_Query</code></a> if you need to use other parameters.</p>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182655", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69824/" ]
I need some help I have the iteration working for listing the wordpress users however I also want to wrap their names in links and can't seem to get the user url to work... Nothing is returned to me. Here is what I have so far.... You will see that I am trying to pull in the user\_url however it just returns as nothing. Any help would be great! Thanks ``` <?php $blogusers = get_users( array( 'role' => 'subscriber', 'fields' => 'all' ) ); echo '<ul>'; foreach ( $blogusers as $user ) { echo '<li><a href="' . $user->user_url . '">' . $user->display_name . '</a>'; } echo '</ul>' ?> ```
You could take a look at the contributors function included in Twenty Fourteen ``` if ( ! function_exists( 'twentyfourteen_list_authors' ) ) : /** * Print a list of all site contributors who published at least one post. * * @since Twenty Fourteen 1.0 */ function twentyfourteen_list_authors() { $contributor_ids = get_users( array( 'fields' => 'ID', 'orderby' => 'post_count', 'order' => 'DESC', 'who' => 'authors', ) ); foreach ( $contributor_ids as $contributor_id ) : $post_count = count_user_posts( $contributor_id ); // Move on if user has not published a post (yet). if ( ! $post_count ) { continue; } ?> <div class="contributor"> <div class="contributor-info"> <div class="contributor-avatar"><?php echo get_avatar( $contributor_id, 132 ); ?></div> <div class="contributor-summary"> <h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name', $contributor_id ); ?></h2> <p class="contributor-bio"> <?php echo get_the_author_meta( 'description', $contributor_id ); ?> </p> <a class="button contributor-posts-link" href="<?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?>"> <?php printf( _n( '%d Article', '%d Articles', $post_count, 'twentyfourteen' ), $post_count ); ?> </a> </div><!-- .contributor-summary --> </div><!-- .contributor-info --> </div><!-- .contributor --> <?php endforeach; } endif; ``` You could also change the [`get_users`](https://codex.wordpress.org/Function_Reference/get_users#Parameters) function to [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) if you need to use other parameters.
182,657
<p>Here is what I tried and couldn't reach it. Maybe I need a whole different approach?</p> <p>1) I created a custom field in a post, called <code>post-class</code> and inserted the value <code>cita-flow800000</code> (weird class name means: citations flow structure using the <code>#800000</code> as the main color, for those who might be curious)</p> <p>2) I called the new custom_value in my <code>content-single.php</code> in front of the <code>post_class</code> function, and inserted the variable inside the <code>post_class</code> function, like this:</p> <pre><code>&lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('class-1 class-2' . $custom_variable); ?&gt;&gt; &lt;?php $custom_values = get_post_meta($post-&gt;ID, 'post_class'); ?&gt; </code></pre> <p>3) I selected the class in my <code>style.css</code>:</p> <pre><code>.cita-flow800000 p { font-size: 30px; } </code></pre> <p>As an example, but nothing happens. </p> <p>Could it be done, to style posts differently and accordingly to post classes? Creating different classes for different post structures and selecting/creating them in the post meta custom fields and in the <code>style.css</code> sheet?</p> <p>PS - I tried changing the variable inside the post_class function into <code>$custom_values</code>, thinking that <code>$custom_variable</code> could be a typo from the post that shared the recipe, but it still didn't work. All functions seem to be calling all variables correctly, so why doesn't it work? </p> <p>Anyone who can point me in the direction where I could learn and apply this?</p>
[ { "answer_id": 182664, "author": "mrwweb", "author_id": 9844, "author_profile": "https://wordpress.stackexchange.com/users/9844", "pm_score": 1, "selected": false, "text": "<p>I believe the primary problem in your code is the <code>$custom_values</code> is set <em>after</em> you try to use it (and you need to use the same variable name). Otherwise, it doesn't have a value when it's in <code>post_class()</code>. In fact, I'm surprised you're not getting an error. That variable needs to get the value <em>before</em> the call to <code>post_class</code>.</p>\n\n<pre><code>&lt;?php $custom_values = get_post_meta($post-&gt;ID, 'post_class'); ?&gt;\n&lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( 'class-1 class-2' . $custom_values ); ?&gt;&gt; \n</code></pre>\n\n<p>In the above snippet, you also need to account for the fact that <code>get_post_meta()</code> returns an <code>array</code> by default. (This means the above code snippet still probably wouldn't work.)</p>\n\n<p>So instead of all that, the best practice is to use the <a href=\"https://codex.wordpress.org/Function_Reference/post_class#Add_Classes_By_Filters\" rel=\"nofollow\"><code>post_class</code> filter</a> (which would also mean you get this class if the post shows up on an archive page too.</p>\n\n<p>To use the filter, you'd use a snippet like this (untested), probably in your <code>functions.php</code> file:</p>\n\n<pre><code>add_filter( 'post_class', 'wpse182657_post_class', 10, 2 );\nfunction wpse182657_post_class( $classes, $post_id ) {\n // get the meta\n // true assumes you only use one value per this key on any single post\n // if false, you'd have to loop through the array with a foreach loop\n $post_class = get_post_meta( $post_id, 'post_class', true );\n\n // add $post_class variable to $classes array\n $classes[] = esc_attr( $post_class );\n\n // run along now, $classes\n return $classes;\n}\n</code></pre>\n" }, { "answer_id": 182736, "author": "Rodrigo Cardoso", "author_id": 69825, "author_profile": "https://wordpress.stackexchange.com/users/69825", "pm_score": 0, "selected": false, "text": "<p>It's working, finaly. The link to the source and the code which worked out are below.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/64124/69825\">https://wordpress.stackexchange.com/a/64124/69825</a> (Check for the Update #1 edit in the answer)\nIt was through editing the content-single.php rather than through a filter in the functions.php file. I tried 2 or 3 recipes of each. I couldn't understand why they didn't work out.</p>\n\n<pre><code>&lt;?php $my_class = get_post_meta($post-&gt;ID, \"your_meta_name\") ?&gt;\n&lt;div id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( $my_class ); ?&gt;&gt;\n</code></pre>\n\n<p>It creates a variable $my_class and adds it to the post_class function. The value is determined in the custom fields of the post meta data.</p>\n\n<p>The variable is created before it is called in the function, as mrwweb advised in the previous answer here above.</p>\n" } ]
2015/03/29
[ "https://wordpress.stackexchange.com/questions/182657", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69825/" ]
Here is what I tried and couldn't reach it. Maybe I need a whole different approach? 1) I created a custom field in a post, called `post-class` and inserted the value `cita-flow800000` (weird class name means: citations flow structure using the `#800000` as the main color, for those who might be curious) 2) I called the new custom\_value in my `content-single.php` in front of the `post_class` function, and inserted the variable inside the `post_class` function, like this: ``` <article id="post-<?php the_ID(); ?>" <?php post_class('class-1 class-2' . $custom_variable); ?>> <?php $custom_values = get_post_meta($post->ID, 'post_class'); ?> ``` 3) I selected the class in my `style.css`: ``` .cita-flow800000 p { font-size: 30px; } ``` As an example, but nothing happens. Could it be done, to style posts differently and accordingly to post classes? Creating different classes for different post structures and selecting/creating them in the post meta custom fields and in the `style.css` sheet? PS - I tried changing the variable inside the post\_class function into `$custom_values`, thinking that `$custom_variable` could be a typo from the post that shared the recipe, but it still didn't work. All functions seem to be calling all variables correctly, so why doesn't it work? Anyone who can point me in the direction where I could learn and apply this?
I believe the primary problem in your code is the `$custom_values` is set *after* you try to use it (and you need to use the same variable name). Otherwise, it doesn't have a value when it's in `post_class()`. In fact, I'm surprised you're not getting an error. That variable needs to get the value *before* the call to `post_class`. ``` <?php $custom_values = get_post_meta($post->ID, 'post_class'); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'class-1 class-2' . $custom_values ); ?>> ``` In the above snippet, you also need to account for the fact that `get_post_meta()` returns an `array` by default. (This means the above code snippet still probably wouldn't work.) So instead of all that, the best practice is to use the [`post_class` filter](https://codex.wordpress.org/Function_Reference/post_class#Add_Classes_By_Filters) (which would also mean you get this class if the post shows up on an archive page too. To use the filter, you'd use a snippet like this (untested), probably in your `functions.php` file: ``` add_filter( 'post_class', 'wpse182657_post_class', 10, 2 ); function wpse182657_post_class( $classes, $post_id ) { // get the meta // true assumes you only use one value per this key on any single post // if false, you'd have to loop through the array with a foreach loop $post_class = get_post_meta( $post_id, 'post_class', true ); // add $post_class variable to $classes array $classes[] = esc_attr( $post_class ); // run along now, $classes return $classes; } ```
182,668
<p>I searched the web for last couple of days for &quot;Reply-to Address&quot; in the email but had no luck so, here I am.</p> <p>In my wordpress site, there are multiple store owners who can sell their products. When visitors buy a certain item (listed by different owners), that particular owner gets an email notification (Note that it is mandatory to put the visitor's email address during checkout process)</p> <p>However the email is from &quot;Admin&quot; email account.</p> <p>I searched for how to set up &quot;reply-to&quot; address so the owners can reply directly to the customer's email address instead of admin account.</p> <p>Here is an example that I saw which I am trying to achieve:</p> <p><img src="https://i.stack.imgur.com/Q8Glx.png" alt="enter image description here" /></p> <p>In this image, the site is <code>abc.ca</code> and the <code>[email protected]</code> bought something. Then the <code>[email protected]</code> got the email, which the owner can now send a reply back to the customer directly from the email.</p> <p>How can I achieve something like this?</p> <h2>EDIT:</h2> <p>Here is the code that I have now:</p> <pre><code> add_filter('woocommerce_email_headers', 'my_from_reply'); function my_from_reply() { return 'From: [email protected]' . &quot;\r\n&quot;; } </code></pre> <p>And this is the customer's billing email.</p> <pre><code> &lt;?php echo $order-&gt;billing_email; ?&gt; </code></pre> <p>How can I modify the first one to include the &quot;billing_email&quot; instead of &quot;[email protected]&quot;</p> <p>Thank you</p>
[ { "answer_id": 182691, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 6, "selected": true, "text": "<p>If and when you are using <a href=\"https://codex.wordpress.org/Function_Reference/wp_mail\" rel=\"noreferrer\"><code>wp_mail()</code></a>, then you can just set <code>Reply-To</code> for the <code>$headers</code> parameter. Exemplary usage below:</p>\n\n<pre><code>$to = \"[email protected]\";\n$subject = \"Using Reply-To with wp_mail\";\n$message = \"This is an example for using Reply-To with wp_mail.\";\n$headers[] = 'Reply-To: Name Name &lt;[email protected]&gt;';\n$attachments = array();\nwp_mail( $to, $subject, $message, $headers, $attachments ); \n</code></pre>\n\n<p>There is a hook <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail\" rel=\"noreferrer\"><code>wp_mail</code></a> hook too, which you could use to change the parameters.</p>\n" }, { "answer_id": 375071, "author": "DevWL", "author_id": 108994, "author_profile": "https://wordpress.stackexchange.com/users/108994", "pm_score": 0, "selected": false, "text": "<p>In functions.php</p>\n<pre><code>// Function changes email that your site sending from\nfunction change_my_from_address( $original_email_address ) {\n return '[email protected]';\n}\nadd_filter( 'wp_mail_from', 'change_my_from_address' );\n\n// Change sender name\nfunction change_my_sender_name( $original_email_from ) {\n return 'example.pl';\n}\nadd_filter( 'wp_mail_from_name', 'change_my_sender_name' );\n</code></pre>\n" } ]
2015/03/30
[ "https://wordpress.stackexchange.com/questions/182668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
I searched the web for last couple of days for "Reply-to Address" in the email but had no luck so, here I am. In my wordpress site, there are multiple store owners who can sell their products. When visitors buy a certain item (listed by different owners), that particular owner gets an email notification (Note that it is mandatory to put the visitor's email address during checkout process) However the email is from "Admin" email account. I searched for how to set up "reply-to" address so the owners can reply directly to the customer's email address instead of admin account. Here is an example that I saw which I am trying to achieve: ![enter image description here](https://i.stack.imgur.com/Q8Glx.png) In this image, the site is `abc.ca` and the `[email protected]` bought something. Then the `[email protected]` got the email, which the owner can now send a reply back to the customer directly from the email. How can I achieve something like this? EDIT: ----- Here is the code that I have now: ``` add_filter('woocommerce_email_headers', 'my_from_reply'); function my_from_reply() { return 'From: [email protected]' . "\r\n"; } ``` And this is the customer's billing email. ``` <?php echo $order->billing_email; ?> ``` How can I modify the first one to include the "billing\_email" instead of "[email protected]" Thank you
If and when you are using [`wp_mail()`](https://codex.wordpress.org/Function_Reference/wp_mail), then you can just set `Reply-To` for the `$headers` parameter. Exemplary usage below: ``` $to = "[email protected]"; $subject = "Using Reply-To with wp_mail"; $message = "This is an example for using Reply-To with wp_mail."; $headers[] = 'Reply-To: Name Name <[email protected]>'; $attachments = array(); wp_mail( $to, $subject, $message, $headers, $attachments ); ``` There is a hook [`wp_mail`](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail) hook too, which you could use to change the parameters.
182,675
<p><strike>I need to import users to my WP database once a day. So I have a script that runs once a day to do an action. The problem that I'm having is that I'm a little over my head on this one.</p> <p>Another company provides me with userdata in a .csv file. I then need to import this file to my WP database.</p> <p>The script I use for running once a day is the following (this is in my functions.php): </p> <pre><code>add_action( 'wp', 'prefix_setup_schedule' ); /** * On an early action hook, check if the hook is scheduled - if not, schedule it. */ function prefix_setup_schedule() { if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) { wp_schedule_event( time(), 'hourly', 'prefix_hourly_event'); } } add_action( 'prefix_hourly_event', 'prefix_do_this_hourly' ); /** * On the scheduled action hook, run a function. */ function prefix_do_this_hourly() { wp_mail( '[email protected]', 'Automatic email sent at '.time(), 'Automatic scheduled email from WordPress.'); } </code></pre> <p>On the server runs a cronjob that activates <code>wp-cron.php</code> once a day. If there aren't any users the script won't run so I activate it. Once there is activity it runs.</p> <p>This is a simple working example of an email that is sent every hour. Now I need to import users.</p> <p>Here is what I found:</p> <pre><code>LOAD DATA INFILE 'path/to/file/users.csv' INTO TABLE discounts FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS; </code></pre> <p>I don't know if this works I'm not there yet. The problem I'm facing now it that the usersystem of WordPres exists of two tables <code>wp_user</code> and <code>wp_usermeta</code>.</p> <p>Can anybody tell me if I'm even on the right track and how to solve this. Is there maybe a way to seperate the .csv file and select what to import where including the fact that there is a refference between the <code>user</code> and <code>usermeta</code> tables?</p> <p>M.</strike></p> <p>I changed my way of thinking and want to do the following:</p> <pre><code>$row = 1; ini_set('auto_detect_line_endings',TRUE); if (($handle = fopen(get_bloginfo('template_directory')."/import_test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { $num = count($data); echo "&lt;p&gt; $num fields in line $row: &lt;br /&gt;&lt;/p&gt;\n"; $row++; for ($c=0; $c &lt; $num; $c++) { echo $data[$c] . "&lt;br /&gt;\n"; } } fclose($handle); } </code></pre> <p>This is a direct copy from <a href="http://php.net/fgetcsv" rel="nofollow">http://php.net/fgetcsv</a>. <br> Now I want to replace the for loop with an <code>wp_create_user</code> function to add the user.<br> At the same time I need to add user_meta to that user (I think). Any ideas how I can add a user with metafields and select the right values from my csv file matching the <code>vars</code>?</p> <ul> <li><p>EDIT -<br> I have come so far but I can't get the last part to work. I have the adding of a new user fixed. <br> The foreach loops through the csv to add all users:</p> <pre><code>$filepath = get_bloginfo('template_directory')."/import_test.csv"; ini_set('auto_detect_line_endings',TRUE); $file = fopen($filepath, "r") or die("Error opening file"); $i = 0; while(($line = fgetcsv($file, 1000, ";")) !== FALSE) { if($i == 0) { $c = 0; foreach($line as $col) { $cols[$c] = $col; $c++; } } else if($i &gt; 0) { $c = 0; foreach($line as $col) { $data[$i][$cols[$c]] = $col; $c++; } } $i++; </code></pre> <p>}</p> <pre><code>foreach ($data as $gebruiker){ $username = $gebruiker['username']; if ( username_exists( $username ) ){ $user = get_user_by( 'login', $username); update_user_meta( $user-&gt;ID, 'meta_key', $gebruiker['email'] ); } else{ $users = wp_insert_user( array( 'user_login' =&gt; $gebruiker['username'], 'user_pass' =&gt; $gebruiker['password'], 'first_name' =&gt; $gebruiker['first_name'], 'last_name' =&gt; $gebruiker['last_name'], 'user_email' =&gt; $gebruiker['email'], 'display_name' =&gt; $gebruiker['first_name'] . ' ' . $gebruiker['last_name'], 'nickname' =&gt; $gebruiker['first_name'] . '' . $gebruiker['last_name'], 'role' =&gt; 'subscriber' ) ); foreach ($data as $update_user) { update_user_meta( $users, 'import_1', $update_user['first_name'] ); update_user_meta( $users, 'import_2', $update_user['last_name'] ); } } } </code></pre></li> </ul> <p>To add files to the <code>wp_usermeta</code> table I want to work with <code>update_user_meta</code> since the <code>wp_insert_user</code> comes back with an ID of the just created user.</p> <p>But no matter where I place the <code>update_user_meta</code> in the loop it gives me back the following error: <code>Fatal error: Cannot use object of type WP_Error as array in</code><br> The error is fixed. Because the users allready existed. So need to check for that later. This does mean that the fields are added to the usermeta but empty</p> <p>====== EDIT ======<br> The above code is final and working...</p>
[ { "answer_id": 182683, "author": "Mehul Kaklotar", "author_id": 54271, "author_profile": "https://wordpress.stackexchange.com/users/54271", "pm_score": 0, "selected": false, "text": "<p>You can make use of CSV importer/exporter libraries to extract the CSV file data and save them as user details. FYI - always use wordpress functions to save anything. for ex. <code>update_user_meta</code> etc.</p>\n\n<p>Cron you are using is correct and should run properly.</p>\n\n<p>Library for extracting CSV data : <a href=\"https://github.com/goodby/csv\" rel=\"nofollow\">goodby</a></p>\n\n<p>EDIT:</p>\n\n<p>try adding a error handling in your code:</p>\n\n<p><code>//On success \nif( !is_wp_error($user) ) {\n echo \"User created : \". $user; // update your meta here\n}</code> </p>\n" }, { "answer_id": 182789, "author": "shyammakwana.me", "author_id": 49267, "author_profile": "https://wordpress.stackexchange.com/users/49267", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"nofollow\">wp_create_user</a> and pass necessary information like <code>$username, $password, $email</code> , where <code>$email</code> is optional. </p>\n\n<p>If user created successfully it will return <code>ID</code> of newly created user, other wise will return error object.</p>\n\n<p>Then update user's other information using <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow\">update_user_meta.</a></p>\n" } ]
2015/03/30
[ "https://wordpress.stackexchange.com/questions/182675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52240/" ]
I need to import users to my WP database once a day. So I have a script that runs once a day to do an action. The problem that I'm having is that I'm a little over my head on this one. Another company provides me with userdata in a .csv file. I then need to import this file to my WP database. The script I use for running once a day is the following (this is in my functions.php): ``` add_action( 'wp', 'prefix_setup_schedule' ); /** * On an early action hook, check if the hook is scheduled - if not, schedule it. */ function prefix_setup_schedule() { if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) { wp_schedule_event( time(), 'hourly', 'prefix_hourly_event'); } } add_action( 'prefix_hourly_event', 'prefix_do_this_hourly' ); /** * On the scheduled action hook, run a function. */ function prefix_do_this_hourly() { wp_mail( '[email protected]', 'Automatic email sent at '.time(), 'Automatic scheduled email from WordPress.'); } ``` On the server runs a cronjob that activates `wp-cron.php` once a day. If there aren't any users the script won't run so I activate it. Once there is activity it runs. This is a simple working example of an email that is sent every hour. Now I need to import users. Here is what I found: ``` LOAD DATA INFILE 'path/to/file/users.csv' INTO TABLE discounts FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS; ``` I don't know if this works I'm not there yet. The problem I'm facing now it that the usersystem of WordPres exists of two tables `wp_user` and `wp_usermeta`. Can anybody tell me if I'm even on the right track and how to solve this. Is there maybe a way to seperate the .csv file and select what to import where including the fact that there is a refference between the `user` and `usermeta` tables? M. I changed my way of thinking and want to do the following: ``` $row = 1; ini_set('auto_detect_line_endings',TRUE); if (($handle = fopen(get_bloginfo('template_directory')."/import_test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ``` This is a direct copy from <http://php.net/fgetcsv>. Now I want to replace the for loop with an `wp_create_user` function to add the user. At the same time I need to add user\_meta to that user (I think). Any ideas how I can add a user with metafields and select the right values from my csv file matching the `vars`? * EDIT - I have come so far but I can't get the last part to work. I have the adding of a new user fixed. The foreach loops through the csv to add all users: ``` $filepath = get_bloginfo('template_directory')."/import_test.csv"; ini_set('auto_detect_line_endings',TRUE); $file = fopen($filepath, "r") or die("Error opening file"); $i = 0; while(($line = fgetcsv($file, 1000, ";")) !== FALSE) { if($i == 0) { $c = 0; foreach($line as $col) { $cols[$c] = $col; $c++; } } else if($i > 0) { $c = 0; foreach($line as $col) { $data[$i][$cols[$c]] = $col; $c++; } } $i++; ``` } ``` foreach ($data as $gebruiker){ $username = $gebruiker['username']; if ( username_exists( $username ) ){ $user = get_user_by( 'login', $username); update_user_meta( $user->ID, 'meta_key', $gebruiker['email'] ); } else{ $users = wp_insert_user( array( 'user_login' => $gebruiker['username'], 'user_pass' => $gebruiker['password'], 'first_name' => $gebruiker['first_name'], 'last_name' => $gebruiker['last_name'], 'user_email' => $gebruiker['email'], 'display_name' => $gebruiker['first_name'] . ' ' . $gebruiker['last_name'], 'nickname' => $gebruiker['first_name'] . '' . $gebruiker['last_name'], 'role' => 'subscriber' ) ); foreach ($data as $update_user) { update_user_meta( $users, 'import_1', $update_user['first_name'] ); update_user_meta( $users, 'import_2', $update_user['last_name'] ); } } } ``` To add files to the `wp_usermeta` table I want to work with `update_user_meta` since the `wp_insert_user` comes back with an ID of the just created user. But no matter where I place the `update_user_meta` in the loop it gives me back the following error: `Fatal error: Cannot use object of type WP_Error as array in` The error is fixed. Because the users allready existed. So need to check for that later. This does mean that the fields are added to the usermeta but empty ====== EDIT ====== The above code is final and working...
You can use [wp\_create\_user](https://codex.wordpress.org/Function_Reference/wp_create_user) and pass necessary information like `$username, $password, $email` , where `$email` is optional. If user created successfully it will return `ID` of newly created user, other wise will return error object. Then update user's other information using [update\_user\_meta.](https://codex.wordpress.org/Function_Reference/update_user_meta)
182,693
<p>I created a custom plugin which i want Users who are Editors to be able to use the plugin.</p> <p>I found a link here to allow access for editors to allow editors to edit menus<a href="https://wordpress.stackexchange.com/questions/4191/allow-editors-to-edit-menus">allow editors to edit menus?</a></p> <p>using this code.</p> <pre><code> $role_object = get_role( 'editor' ); // add $cap capability to this role object $role_object-&gt;add_cap( 'edit_theme_options' ); </code></pre> <p>So, is there a possible way i can allow Editors access to my custom added plugins</p>
[ { "answer_id": 182695, "author": "user123451", "author_id": 69128, "author_profile": "https://wordpress.stackexchange.com/users/69128", "pm_score": 2, "selected": false, "text": "<p>After a quick search, i got my answer here</p>\n\n<p><a href=\"https://wordpress.org/support/topic/how-to-allow-non-admins-editors-authors-to-use-certain-wordpress-plugins\" rel=\"nofollow\">https://wordpress.org/support/topic/how-to-allow-non-admins-editors-authors-to-use-certain-wordpress-plugins</a></p>\n\n<p>By changing all occurances of 'manage_options' to 'edit_pages' in my Plugins files.</p>\n\n<p>Editors are allowed to use plugins with Edit_pages</p>\n" }, { "answer_id": 255725, "author": "Liz Eipe C", "author_id": 108014, "author_profile": "https://wordpress.stackexchange.com/users/108014", "pm_score": 4, "selected": true, "text": "<p>Please add the following code. </p>\n\n<pre><code>function activate_plugin_name() {\n $role = get_role( 'editor' );\n $role-&gt;add_cap( 'manage_options' ); // capability\n}\n// Register our activation hook\nregister_activation_hook( __FILE__, 'activate_plugin_name' );\n\nfunction deactivate_plugin_name() {\n\n $role = get_role( 'editor' );\n $role-&gt;remove_cap( 'manage_options' ); // capability\n}\n// Register our de-activation hook\nregister_deactivation_hook( __FILE__, 'deactivate_plugin_name' );`\n</code></pre>\n\n<p>Refer my tutorial for further explanation.\n<a href=\"http://www.pearlbells.co.uk/user-role-editor-access-wordpress-plugins/\" rel=\"noreferrer\">http://www.pearlbells.co.uk/user-role-editor-access-wordpress-plugins/</a></p>\n" }, { "answer_id": 366665, "author": "Youssef", "author_id": 113304, "author_profile": "https://wordpress.stackexchange.com/users/113304", "pm_score": 0, "selected": false, "text": "<p>This is just a use case of a need to activate a plugin for \"editor\" user role. The plugin is called <a href=\"https://fr.wordpress.org/plugins/bulk-images-to-posts/\" rel=\"nofollow noreferrer\">bulk images to posts</a>. This plugin is active only for admin role. So to activate it for \"editor\" role, you have to go through the \"bulk-images-to-posts.php\" file and search for big_create_menu() function (responsible of creating a menu in the left admin bar)\n<strong>Now if you replace \"manage_options\" by \"edit_pages\"</strong> you will see that in \"editor\" role admin menu, the plugin becomes active.\n<strong>Again this is just an example of 1 use case to show the effect of \"edit_pages\"</strong></p>\n\n<p>Here is a code snippet showing this:</p>\n\n<pre><code>// create new top-level menu\nglobal $bip_admin_page;\n$bip_admin_page = add_menu_page(__('Bulk Images to Posts Uploader','bulk-images-to-posts'), __('Bulk','bulk-images-to-posts'), 'edit_pages', 'bulk-images-to-post','bip_upload_page','dashicons-images-alt2');\n// create submenu pages\nadd_submenu_page( 'bulk-images-to-post', __('Bulk Images to Post - Upload','bulk-images-to-posts'), __('Uploader','bulk-images-to-posts'), 'edit_pages', 'bulk-images-to-post');\n</code></pre>\n" }, { "answer_id": 378892, "author": "Vasco", "author_id": 150100, "author_profile": "https://wordpress.stackexchange.com/users/150100", "pm_score": 0, "selected": false, "text": "<p>Thanks Liz Eipe for <a href=\"https://wordpress.stackexchange.com/users/108014/liz-eipe-c\">your solution</a>, but unfortunately that did not work for me. What did work for me, was changing the 'capability' for all the <a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow noreferrer\">add_menu_page()</a> and the <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"nofollow noreferrer\">add_submenu_page()</a> hooks.</p>\n<p>Basically the capability value you set, corresponds to access for different types and combinations of users. You can view all the possible capabilities and their access <a href=\"https://wordpress.org/support/article/roles-and-capabilities/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I choose 'publish_posts' as value, which gives Super Admin, Admin, Editor and Author access to the admin page you register with your hooks.</p>\n<p>This was my code before:</p>\n<pre><code>add_menu_page(\n 'My Menu Title',\n 'custom menu',\n 'administrator', // Only a admin access\n 'myplugin/myplugin-admin.php',\n '',\n plugins_url( 'myplugin/images/icon.png' ),\n 3\n);\n</code></pre>\n<p>And now with Admin, Editor and Author access it's changed to:</p>\n<pre><code>add_menu_page(\n 'My Menu Title',\n 'custom menu',\n 'publish_posts', // Admin, Editor, Author access\n 'myplugin/myplugin-admin.php',\n '',\n plugins_url( 'myplugin/images/icon.png' ),\n 3\n);\n</code></pre>\n<p>One last small note; do not forget to change this for all the plugin admin pages you want other users to have access to, like all the submenu pages.</p>\n" } ]
2015/03/30
[ "https://wordpress.stackexchange.com/questions/182693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69128/" ]
I created a custom plugin which i want Users who are Editors to be able to use the plugin. I found a link here to allow access for editors to allow editors to edit menus[allow editors to edit menus?](https://wordpress.stackexchange.com/questions/4191/allow-editors-to-edit-menus) using this code. ``` $role_object = get_role( 'editor' ); // add $cap capability to this role object $role_object->add_cap( 'edit_theme_options' ); ``` So, is there a possible way i can allow Editors access to my custom added plugins
Please add the following code. ``` function activate_plugin_name() { $role = get_role( 'editor' ); $role->add_cap( 'manage_options' ); // capability } // Register our activation hook register_activation_hook( __FILE__, 'activate_plugin_name' ); function deactivate_plugin_name() { $role = get_role( 'editor' ); $role->remove_cap( 'manage_options' ); // capability } // Register our de-activation hook register_deactivation_hook( __FILE__, 'deactivate_plugin_name' );` ``` Refer my tutorial for further explanation. <http://www.pearlbells.co.uk/user-role-editor-access-wordpress-plugins/>
182,708
<p>I wonder if its possible to use a template file for a specific url without having to create a page for that template.</p> <p>This is my simplified problem:</p> <p>I have created a page in WP with some link content that points to a specific url with some trailing form data: <em>(mysite.com/retail/?a=test&amp;b=1234)</em>. </p> <p>I want that url (retail) to automatically use my template file template-retail.php that I have in the child theme directory, without having to create a page named ”retail” &amp; select the template page from there. There is only external content in the template-retail.php file, nothing from Wordpress itself.</p> <p>Is this possible?</p>
[ { "answer_id": 182718, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 6, "selected": true, "text": "<p>You can just look at url, load the file and exit.</p>\n\n<p>That can be done when WordPress loaded its environment, e.g. on <code>'init'</code>.</p>\n\n<pre><code>add_action('init', function() {\n $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');\n if ( $url_path === 'retail' ) {\n // load the file if exists\n $load = locate_template('template-retail.php', true);\n if ($load) {\n exit(); // just exit if template was found and loaded\n }\n }\n});\n</code></pre>\n\n<p>Note that doing so a <em>real</em> page with slug \"retail\" can never be used.</p>\n\n<p>This is pretty easy, but also hardcoded, so if you need this for a single page it's fine. If you need to control more urls, have a look to the solution proposed in <a href=\"https://wordpress.stackexchange.com/a/162476/35541\">this answer</a>.</p>\n" }, { "answer_id": 261575, "author": "adamj", "author_id": 67171, "author_profile": "https://wordpress.stackexchange.com/users/67171", "pm_score": 3, "selected": false, "text": "<p>The <code>init</code> action isn't appropriate for what you're trying to achieve. You should be using the <code>template_include</code> filter instead. You'd combine this with <code>get_query_var</code> to retrieve the URL params to check what template needs to be loaded. Here are the links:</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/template_include/</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_query_var/</a></li>\n</ul>\n<p>Code:</p>\n<pre><code>add_filter( 'template_include', 'portfolio_page_template', 99 );\n\nfunction portfolio_page_template( $template ) {\n\n if ( is_page( 'portfolio' ) ) {\n $new_template = locate_template( array( 'portfolio-page-template.php' ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n" }, { "answer_id": 262239, "author": "Shivanand Sharma", "author_id": 116231, "author_profile": "https://wordpress.stackexchange.com/users/116231", "pm_score": 2, "selected": false, "text": "<p>The WordPress-way to do this is with <code>page-templates</code>. <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a></p>\n\n<p>You only need a code for the WordPress template. In your WordPress theme you can create a page template and rename it to </p>\n\n<p><code>page-id.php</code></p>\n\n<p>That particular page will automatically pick it up and use the template.</p>\n\n<p>For example if your page has an id of 5874 you'll name the template as <code>page-5784.php</code></p>\n\n<p>You can also name the template based on the page slug. For example if the page slug is <code>hello-world</code> then the template name will be <code>page-hello-world.php</code></p>\n\n<p>Also see: \n - <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/files/2014/10/template-hierarchy.png</a></p>\n" }, { "answer_id": 282594, "author": "Jose Velandia", "author_id": 129436, "author_profile": "https://wordpress.stackexchange.com/users/129436", "pm_score": 0, "selected": false, "text": "<p>@shivanand-sharma this is perfect and cleaner method (<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a>) to create any page like any other in wordpress, and if you want to hide your page, i just use the simple and efective plugin '<a href=\"https://wordpress.org/plugins/exclude-pages/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/exclude-pages/</a>'</p>\n\n<p>I must say that i was in need of a URL to make <strong>POST</strong> or <strong>GET</strong> to my own page and save some session data 'WC()->session', and this solves this and other problems, because <strong>you can have a backbone of custom php code including all the 'require('wp-load') etc' of the entire wordpress, woocommerce etc</strong> to work with through, <strong>mysite.com/index.php/MYPAGE</strong> ..... </p>\n\n<p>You just need to :</p>\n\n<p><strong>First:</strong> Create a file inside your theme location as a template of the new page something like 'wp-content/themes/mytheme/customtemplate.php' (Comment is important so the 'Template Name' can be observed by Wordpress) :</p>\n\n<pre><code>&lt;?php /* Template Name: WhateverName */ \necho 'Hello World';echo '&lt;/br&gt;';\nvar_dump(WC()-&gt;session); \nvar_dump($_POST);\nvar_dump($_GET);\n?&gt;\n</code></pre>\n\n<p><strong>Second:</strong> Create a page at wordpress normally through 'wp-admin' > Pages (Let's say a name like <strong>MYPAGE</strong>, or you can change the slug whatever you want) and off course link the previous template as the template of this page which is name <strong>'WhateverName'</strong> on the template attributtes section.</p>\n\n<p>So, Let's open the new page <strong>'mysite.com/index.php/MYPAGE'</strong> and you will see.</p>\n\n<pre><code>Hello World\nobject(WC_Session_Handler)#880 .....................\n</code></pre>\n\n<p><strong>Extras:</strong> Let's create javascript or jquery functions in cart, checkout, whatever you can imagine inside 'script' HTML tags, and include code like this: </p>\n\n<pre><code>var data = { action : actionName, dataA : etcA, dataB : etcB}\n$.ajax({\n type: 'post',\n url: 'index.php/MYPAGE',\n data: data,\n success: function( response ) {\n },\n complete: function() {\n }\n});\n</code></pre>\n" } ]
2015/03/30
[ "https://wordpress.stackexchange.com/questions/182708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15228/" ]
I wonder if its possible to use a template file for a specific url without having to create a page for that template. This is my simplified problem: I have created a page in WP with some link content that points to a specific url with some trailing form data: *(mysite.com/retail/?a=test&b=1234)*. I want that url (retail) to automatically use my template file template-retail.php that I have in the child theme directory, without having to create a page named ”retail” & select the template page from there. There is only external content in the template-retail.php file, nothing from Wordpress itself. Is this possible?
You can just look at url, load the file and exit. That can be done when WordPress loaded its environment, e.g. on `'init'`. ``` add_action('init', function() { $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/'); if ( $url_path === 'retail' ) { // load the file if exists $load = locate_template('template-retail.php', true); if ($load) { exit(); // just exit if template was found and loaded } } }); ``` Note that doing so a *real* page with slug "retail" can never be used. This is pretty easy, but also hardcoded, so if you need this for a single page it's fine. If you need to control more urls, have a look to the solution proposed in [this answer](https://wordpress.stackexchange.com/a/162476/35541).
182,775
<p>i have created new custom menu that act like link to some page using this code:</p> <pre><code>add_menu_page( __( 'Gallery', '' ), __( 'Gallery', '' ), 'edit_posts', 'post.php?post='. $gallery_page_id .'&amp;action=edit', '', 'dashicons-admin-gallery', 6 ); </code></pre> <p>the problem is that, when i click on this link, active class become on "pages" and not on my custom menu link (i know this is part of pages).</p> <p>the question is how to add active class to my custom link and remove from the "pages".</p>
[ { "answer_id": 182735, "author": "Hybrid Web Dev", "author_id": 36506, "author_profile": "https://wordpress.stackexchange.com/users/36506", "pm_score": 0, "selected": false, "text": "<p>It's easy. Just put this in your plugin/theme or what have you:</p>\n\n<pre><code>function remove_teh_menu_barz() {\n\n add_filter('show_admin_bar', 'show_admin_bar');\n}\n\n\nfunction show_admin_bar() {\n\n return false;\n\n}\n\nadd_action('init', 'remove_teh_menu_barz');\n</code></pre>\n\n<p>This hooks into the init action hook in wordpress and fires the function. The function drops in a filter(which references the show_admin_bar()) telling WP not to show the admin bar. Notice the return false; This will hide the admin bar, but still keep you logged in. You can also just do away with the initial action hook, and drop the call to the show_admin_bar into the filter on an early enough hook and it will do the same thing. </p>\n" }, { "answer_id": 182738, "author": "Tracy Rhodes", "author_id": 66447, "author_profile": "https://wordpress.stackexchange.com/users/66447", "pm_score": 4, "selected": true, "text": "<p>OR you can go into your own user profile (hover over your name on the right end of the bar and click on Edit My Profile) and uncheck the box that says Show Toolbar when viewing site. Click Update Profile at the bottom of the page and the bar will go away. </p>\n\n<p>Reverse the process when you want to bring it back.</p>\n" }, { "answer_id": 248021, "author": "Marieke", "author_id": 108090, "author_profile": "https://wordpress.stackexchange.com/users/108090", "pm_score": 0, "selected": false, "text": "<p>You can also: right click> open in incognito window</p>\n" } ]
2015/03/31
[ "https://wordpress.stackexchange.com/questions/182775", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36923/" ]
i have created new custom menu that act like link to some page using this code: ``` add_menu_page( __( 'Gallery', '' ), __( 'Gallery', '' ), 'edit_posts', 'post.php?post='. $gallery_page_id .'&action=edit', '', 'dashicons-admin-gallery', 6 ); ``` the problem is that, when i click on this link, active class become on "pages" and not on my custom menu link (i know this is part of pages). the question is how to add active class to my custom link and remove from the "pages".
OR you can go into your own user profile (hover over your name on the right end of the bar and click on Edit My Profile) and uncheck the box that says Show Toolbar when viewing site. Click Update Profile at the bottom of the page and the bar will go away. Reverse the process when you want to bring it back.
182,798
<p>I am developing a plugin for my own rapid development that creates a custom post type. The 'list' for this post type is displayed on a specific page that is created and managed by the plugin. This page can be place anywhere within the site's page hierarchy, so the slug for the single posts need to update if the site admin changes the list page location.</p> <p>When creating the post type during the <code>init</code>, I accomplish this by assigning the following rewrite rules to the custom post type (code trimmed for brevity):</p> <pre><code>$post_type_slug = "/" . get_page_uri( $page_id ); register_post_type( 'post_type_name', ... 'rewrite' =&gt; array( 'slug' =&gt; $post_type_slug, 'with_front' =&gt; true), ... ) ); </code></pre> <p>This seems to work perfectly for setting everything up initially. When the user saves the 'list' page, I run the following code to update the rewrite rules:</p> <pre><code>add_action( 'save_post', array(__CLASS__, 'flush_permalinks'), 2000 ); function flush_permalinks( $post_id ) { if($post_id == get_option( $custom_page_id )){ flush_rewrite_rules(false); } } </code></pre> <p>However, when the user changes the location of the page, the newly updated permalinks return 404 (even though the list page displays the links correctly). But if I save the page a second time, it works perfectly! I've attempted changing the priority of the <code>save_post</code> action (from 1 to 2000), but that does not seem to make a different. I've also tried to both hard and soft flush the rewrite rules, but that doesn't change the two-save (first save doesn't change the rewrite rules, but the second does) behavior either.</p> <p>Any suggestions on what I might be doing wrong?</p>
[ { "answer_id": 182836, "author": "Eric K", "author_id": 40585, "author_profile": "https://wordpress.stackexchange.com/users/40585", "pm_score": 1, "selected": false, "text": "<p>I was able to resolve this problem. It would appear that the 'save_post' action occurs prior to the <code>init</code> that is registering the custom post type. Therefore, the post type's rewrite slug is not updated prior to the request to <code>flush_rewrite_rules</code>, essentially resulting in no update. This also explains why it works if the post is saved a second time, since the post type has a chance to update its rewrite rules.</p>\n\n<p>Therefore, I solve it by changing my code as such:</p>\n\n<pre><code>add_action( 'save_post', array(__CLASS__, 'flush_permalinks'));\nfunction flush_permalinks( $post_id ) { \n if($post_id == get_option( $custom_page_id )){\n update_option( 'unique_page_updated_key', 'true');\n }\n}\n</code></pre>\n\n<p>I then added the following just below my <code>register_post_type</code> code:</p>\n\n<pre><code>if((bool)get_option( 'unique_page_updated_key' )){\n flush_rewrite_rules(); \n update_option( 'unique_page_updated_key', 'false');\n}\n</code></pre>\n\n<p>This prevents the rewrite rules from being flushed on each and every <code>init</code>.</p>\n" }, { "answer_id": 263285, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 3, "selected": true, "text": "<p>I know this has already been answered, but I felt as if it wasn't 100% real clear what the actual solution was.</p>\n\n<p>Here's my answer to add some clarification.</p>\n\n<p>He's right... You can't flush rewrite rules on <code>save_post</code>, because that action hook is fired AFTER the <code>init</code> action hook has been fired. </p>\n\n<p>As you know, Post Types and Taxonomies are registered on the <code>init</code> hook. </p>\n\n<blockquote>\n <p><strong>TLDR;</strong> You can't <code>flush_rewrite_rules();</code> on <code>save_post</code> action hook.</p>\n</blockquote>\n\n<p>There's a workaround...</p>\n\n<p>You need to set an option value to 1 on <code>save_post</code> action hook. Then check that option for value of 1 and flush rewrite rules on <code>init</code> action hook.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>function mbe_late_init_example() {\n\n if ( ! $option = get_option( 'my-plugin-flush-rewrite-rules' ) ) {\n return false;\n }\n\n if ( $option == 1 ) {\n\n flush_rewrite_rules();\n update_option( 'my-plugin-flush-rewrite-rules', 0 );\n\n }\n\n return true;\n\n}\n\nadd_action( 'init', 'mbe_late_init_example', 999999 );\n\n\nfunction mbe_save_post_example( Int $post_id = null, \\WP_Post $post_object = null ) {\n\n if ( ! $post_id || ! $post_object ) {\n return false;\n }\n\n # Specific Post Type\n if ( $post_object-&gt;post_type != 'my-plugin-settings' ) {\n return false;\n }\n\n # Specific Post Object (OPTIONAL)\n if ( $post_object-&gt;post_name != 'general-settings' ) {\n return false;\n }\n\n update_option( 'my-plugin-flush-rewrite-rules', 1 );\n\n return true;\n\n}\n\nadd_action( 'save_post', 'mbe_save_post_example', 10, 2 );\n</code></pre>\n" } ]
2015/03/31
[ "https://wordpress.stackexchange.com/questions/182798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40585/" ]
I am developing a plugin for my own rapid development that creates a custom post type. The 'list' for this post type is displayed on a specific page that is created and managed by the plugin. This page can be place anywhere within the site's page hierarchy, so the slug for the single posts need to update if the site admin changes the list page location. When creating the post type during the `init`, I accomplish this by assigning the following rewrite rules to the custom post type (code trimmed for brevity): ``` $post_type_slug = "/" . get_page_uri( $page_id ); register_post_type( 'post_type_name', ... 'rewrite' => array( 'slug' => $post_type_slug, 'with_front' => true), ... ) ); ``` This seems to work perfectly for setting everything up initially. When the user saves the 'list' page, I run the following code to update the rewrite rules: ``` add_action( 'save_post', array(__CLASS__, 'flush_permalinks'), 2000 ); function flush_permalinks( $post_id ) { if($post_id == get_option( $custom_page_id )){ flush_rewrite_rules(false); } } ``` However, when the user changes the location of the page, the newly updated permalinks return 404 (even though the list page displays the links correctly). But if I save the page a second time, it works perfectly! I've attempted changing the priority of the `save_post` action (from 1 to 2000), but that does not seem to make a different. I've also tried to both hard and soft flush the rewrite rules, but that doesn't change the two-save (first save doesn't change the rewrite rules, but the second does) behavior either. Any suggestions on what I might be doing wrong?
I know this has already been answered, but I felt as if it wasn't 100% real clear what the actual solution was. Here's my answer to add some clarification. He's right... You can't flush rewrite rules on `save_post`, because that action hook is fired AFTER the `init` action hook has been fired. As you know, Post Types and Taxonomies are registered on the `init` hook. > > **TLDR;** You can't `flush_rewrite_rules();` on `save_post` action hook. > > > There's a workaround... You need to set an option value to 1 on `save_post` action hook. Then check that option for value of 1 and flush rewrite rules on `init` action hook. **Example:** ``` function mbe_late_init_example() { if ( ! $option = get_option( 'my-plugin-flush-rewrite-rules' ) ) { return false; } if ( $option == 1 ) { flush_rewrite_rules(); update_option( 'my-plugin-flush-rewrite-rules', 0 ); } return true; } add_action( 'init', 'mbe_late_init_example', 999999 ); function mbe_save_post_example( Int $post_id = null, \WP_Post $post_object = null ) { if ( ! $post_id || ! $post_object ) { return false; } # Specific Post Type if ( $post_object->post_type != 'my-plugin-settings' ) { return false; } # Specific Post Object (OPTIONAL) if ( $post_object->post_name != 'general-settings' ) { return false; } update_option( 'my-plugin-flush-rewrite-rules', 1 ); return true; } add_action( 'save_post', 'mbe_save_post_example', 10, 2 ); ```
182,811
<p>OK, I had no idea how to title this topic.</p> <p>I'm trying to override the default behavior with ajax. The problem here is not actually a problem, but a wish more.</p> <p>I have this url:</p> <pre><code>&lt;a href="http://example.com/?reaction=smk_remove_post&amp;id=1226&amp;_nonce=7be82cd4a0" class="smk-remove-post"&gt;Remove post&lt;/a&gt; </code></pre> <p>In the <code>functions.php</code> I have this function and the call right after:</p> <pre><code>function smk_remove_post(){ if( !empty( $_GET['reaction'] ) &amp;&amp; 'smk_remove_post' == $_GET['reaction'] &amp;&amp; !empty( $_GET['id'] ) ){ if( current_user_can('edit_others_posts') &amp;&amp; !empty($_GET['_nonce']) ){ if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){ // Delete the post wp_delete_post( absint( $_GET['id'] ), true ); } } } } smk_remove_post(); </code></pre> <p>Now if I click on the link the post with ID <code>1226</code> will be removed. All is ok. The task is done successfuly and the page is reloaded.</p> <p>Here is where I need the AJAX. I want to process this URL using ajax and not reload the page, <strong>and get a proper response</strong>.</p> <p>I've added this jQuery script:</p> <pre><code>function smk_remove_post(){ $('.smk-remove-post').on( 'click', function( event ){ event.preventDefault(); var _this = $(this); jQuery.ajax({ type: "GET", url: _this.attr('href'), success: function(response){ console.log(response); _this.text('All great, the post is removed.'); } }); }); } smk_remove_post(); </code></pre> <p>Everything works as expected. The post is removed via ajax and no need to reload the page. But I can't get a proper response, instead I get the full HTML source of the current page.</p> <p>I know that I should use <code>admin-ajax.php</code>(ajaxurl), but how do I do it? I need to send the query from URL and get the response back.</p> <p><strong>Here is what I've tryied:</strong></p> <p>I have added this to the jQuery script above:</p> <pre><code>data: { 'action': 'smk_remove_post_ajax', }, </code></pre> <p>And this to the PHP:</p> <pre><code>function smk_remove_post_ajax(){ smk_remove_post(); die(); } add_action('wp_ajax_smk_remove_post_ajax', 'smk_remove_post_ajax'); </code></pre> <p>It does not work. It's ignored, the previous call is executed insted, just like this would be done without ajax.</p> <p>I understand that I need somehow to send the query to admin-ajax.php instead, but how?</p>
[ { "answer_id": 182815, "author": "Rene Korss", "author_id": 69908, "author_profile": "https://wordpress.stackexchange.com/users/69908", "pm_score": 1, "selected": false, "text": "<p>Make link like this</p>\n\n<pre><code>&lt;a href=\"http://example.com/?reaction=smk_remove_post&amp;id=1226&amp;_nonce=7be82cd4a0\" data-id=\"1226\" data-nonce=\"7be82cd4a0\" class=\"smk-remove-post\"&gt;Remove post&lt;/a&gt;\n</code></pre>\n\n<p>And jQuery</p>\n\n<pre><code>$('.smk-remove-post').on( 'click', function( event ){\n event.preventDefault();\n var _this = $(this);\n\n var data = {\n 'action': 'smk_remove_post_ajax',\n 'reaction': 'smk_remove_post',\n 'id': _this.data('id'),\n '_nonce': _this.data('nonce')\n };\n\n // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php\n jQuery.ajax({\n type: \"GET\",\n url: ajaxurl,\n data: data,\n success: function(response){\n console.log(response);\n _this.text('All great, the post is removed.');\n }\n });\n});\n</code></pre>\n\n<p>See Codex about <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">AJAX in Plugins</a>.\nAnd in Codex, it says:</p>\n\n<blockquote>\n <p>Most of the time you should be using wp_die() in your Ajax callback function. This provides better integration with WordPress and makes it easier to test your code.</p>\n</blockquote>\n\n<p>So use <code>wp_die();</code> instead of <code>die();</code></p>\n" }, { "answer_id": 182816, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>AJAX is not magical and when you request url X you will receive the same HTML for that url if you do it from the browser address bar, link or ajax. Therefor, if you want different response then the HTML you <strong>can not</strong> use the same url for the ajax request as in the link.</p>\n\n<p>Wordpress has a special \"end point\" to handle ajax request - admin-ajax.php and all ajax request should be send only to it, something like <code>$.ajax({url:....admin-ajax.php})</code></p>\n\n<p>Next you need do let wordpress know what you want to do and for that there is a special parameter in the request named <code>action</code>. This parameter will identify the hook to be used at the server side to handle the request. This part you have done right in your code.</p>\n\n<p>Now you need the additional parameters that identifies which object should be manipulated or retrieved by the AJAX operation. You can use the permalink of the post, or the post id for example, but it all depends on the complexity of the operation you are trying to do. In your specific case I would guess that a post id will be the best parameter to pass in the request.</p>\n\n<p>How to send the parameters? most people do a POST request when doing AJAX but if you want a GET the you can pass them as part of the url (which I assume is exactly what jquery will do for you).</p>\n" }, { "answer_id": 182824, "author": "Andrei Surdu", "author_id": 31111, "author_profile": "https://wordpress.stackexchange.com/users/31111", "pm_score": 3, "selected": true, "text": "<p>I finally got it.</p>\n\n<p>First mistake was to process the same function twice. I've called it once after the function and one more time in ajax action. So when using the ajax call, the function got executed twice. In the example from the OP, this is not a problem at all, because it is simplified to do only one thing, but in my real code it does much more and can result in lost of unwanted data.</p>\n\n<p>Also, I just needed to stop the ajax and get a custom responce, nothing more. Here is what I've did:</p>\n\n<p><strong>1.</strong> <em>I've changed this:</em></p>\n\n<pre><code>smk_remove_post();\n</code></pre>\n\n<p><em>to this:</em></p>\n\n<pre><code>add_action('parse_query', 'smk_remove_post');\n</code></pre>\n\n<p>It is better to run the function later when needed in special action.</p>\n\n<p><strong>2.</strong> <em>Next, I've modified the ajax handler:</em>\nI've deleted this line <code>smk_remove_post();</code> and changed the ajax action from <code>wp_ajax_smk_remove_post_ajax</code> to <code>wp_ajax_smk_remove_post</code>:</p>\n\n<pre><code>function smk_remove_post_ajax(){\n wp_die( 'ok' );\n}\nadd_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax');\n</code></pre>\n\n<p><strong>3.</strong> I've renamed the query string <code>reaction</code> to <code>action</code>. Changed it in the url, and function:</p>\n\n<p><strong>4.</strong> Finally modified the jQuery script. So it uses the admin-ajax.php and sends the url as data:</p>\n\n<pre><code>url: ajaxurl,\ndata: _this.attr('href'),\n</code></pre>\n\n<h2>Here is the final code:</h2>\n\n<p><strong>Link:</strong></p>\n\n<pre><code>&lt;a href=\"http://example.com/?action=smk_remove_post&amp;id=1226&amp;_nonce=7be82cd4a0\" class=\"smk-remove-post\"&gt;Remove post&lt;/a&gt;\n</code></pre>\n\n<p><strong>PHP code:</strong></p>\n\n<pre><code>function smk_remove_post(){\n if( !empty( $_GET['action'] ) &amp;&amp; 'smk_remove_post' == $_GET['action'] &amp;&amp; !empty( $_GET['id'] ) ){\n if( current_user_can('edit_others_posts') &amp;&amp; !empty($_GET['_nonce']) ){\n if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){\n // Delete the post\n wp_delete_post( absint( $_GET['id'] ), true );\n }\n }\n }\n}\nadd_action('parse_query', 'smk_remove_post');\n\nfunction smk_remove_post_ajax(){\n wp_die( 'ok' );\n}\nadd_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax');\n</code></pre>\n\n<p><strong>Javascript:</strong></p>\n\n<pre><code>function smk_remove_post(){\n $('.smk-remove-post').on( 'click', function( event ){\n event.preventDefault();\n var _this = $(this);\n\n jQuery.ajax({\n type: \"GET\",\n url: ajaxurl,\n data: _this.attr('href').split('?')[1],\n success: function(response){\n console.log(response); // ok\n _this.text('All great, the post is removed.');\n }\n });\n });\n}\nsmk_remove_post();\n</code></pre>\n\n<p><strong>Edit:</strong>\nAlso a small update to the code above. To process the query strings is required to delete the site path, else it may create unexpected problems. I've added this to <code>data href</code>:</p>\n\n<pre><code>.split('?')[1]\n</code></pre>\n" } ]
2015/03/31
[ "https://wordpress.stackexchange.com/questions/182811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31111/" ]
OK, I had no idea how to title this topic. I'm trying to override the default behavior with ajax. The problem here is not actually a problem, but a wish more. I have this url: ``` <a href="http://example.com/?reaction=smk_remove_post&id=1226&_nonce=7be82cd4a0" class="smk-remove-post">Remove post</a> ``` In the `functions.php` I have this function and the call right after: ``` function smk_remove_post(){ if( !empty( $_GET['reaction'] ) && 'smk_remove_post' == $_GET['reaction'] && !empty( $_GET['id'] ) ){ if( current_user_can('edit_others_posts') && !empty($_GET['_nonce']) ){ if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){ // Delete the post wp_delete_post( absint( $_GET['id'] ), true ); } } } } smk_remove_post(); ``` Now if I click on the link the post with ID `1226` will be removed. All is ok. The task is done successfuly and the page is reloaded. Here is where I need the AJAX. I want to process this URL using ajax and not reload the page, **and get a proper response**. I've added this jQuery script: ``` function smk_remove_post(){ $('.smk-remove-post').on( 'click', function( event ){ event.preventDefault(); var _this = $(this); jQuery.ajax({ type: "GET", url: _this.attr('href'), success: function(response){ console.log(response); _this.text('All great, the post is removed.'); } }); }); } smk_remove_post(); ``` Everything works as expected. The post is removed via ajax and no need to reload the page. But I can't get a proper response, instead I get the full HTML source of the current page. I know that I should use `admin-ajax.php`(ajaxurl), but how do I do it? I need to send the query from URL and get the response back. **Here is what I've tryied:** I have added this to the jQuery script above: ``` data: { 'action': 'smk_remove_post_ajax', }, ``` And this to the PHP: ``` function smk_remove_post_ajax(){ smk_remove_post(); die(); } add_action('wp_ajax_smk_remove_post_ajax', 'smk_remove_post_ajax'); ``` It does not work. It's ignored, the previous call is executed insted, just like this would be done without ajax. I understand that I need somehow to send the query to admin-ajax.php instead, but how?
I finally got it. First mistake was to process the same function twice. I've called it once after the function and one more time in ajax action. So when using the ajax call, the function got executed twice. In the example from the OP, this is not a problem at all, because it is simplified to do only one thing, but in my real code it does much more and can result in lost of unwanted data. Also, I just needed to stop the ajax and get a custom responce, nothing more. Here is what I've did: **1.** *I've changed this:* ``` smk_remove_post(); ``` *to this:* ``` add_action('parse_query', 'smk_remove_post'); ``` It is better to run the function later when needed in special action. **2.** *Next, I've modified the ajax handler:* I've deleted this line `smk_remove_post();` and changed the ajax action from `wp_ajax_smk_remove_post_ajax` to `wp_ajax_smk_remove_post`: ``` function smk_remove_post_ajax(){ wp_die( 'ok' ); } add_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax'); ``` **3.** I've renamed the query string `reaction` to `action`. Changed it in the url, and function: **4.** Finally modified the jQuery script. So it uses the admin-ajax.php and sends the url as data: ``` url: ajaxurl, data: _this.attr('href'), ``` Here is the final code: ----------------------- **Link:** ``` <a href="http://example.com/?action=smk_remove_post&id=1226&_nonce=7be82cd4a0" class="smk-remove-post">Remove post</a> ``` **PHP code:** ``` function smk_remove_post(){ if( !empty( $_GET['action'] ) && 'smk_remove_post' == $_GET['action'] && !empty( $_GET['id'] ) ){ if( current_user_can('edit_others_posts') && !empty($_GET['_nonce']) ){ if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){ // Delete the post wp_delete_post( absint( $_GET['id'] ), true ); } } } } add_action('parse_query', 'smk_remove_post'); function smk_remove_post_ajax(){ wp_die( 'ok' ); } add_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax'); ``` **Javascript:** ``` function smk_remove_post(){ $('.smk-remove-post').on( 'click', function( event ){ event.preventDefault(); var _this = $(this); jQuery.ajax({ type: "GET", url: ajaxurl, data: _this.attr('href').split('?')[1], success: function(response){ console.log(response); // ok _this.text('All great, the post is removed.'); } }); }); } smk_remove_post(); ``` **Edit:** Also a small update to the code above. To process the query strings is required to delete the site path, else it may create unexpected problems. I've added this to `data href`: ``` .split('?')[1] ```
182,859
<p>I've set up some custom post types with Pods, but can't seem to get it to display my manual excerpt. It's working fine for my normal posts.</p> <p>I've tried displaying it with echo get_the_excerpt() and the_excerpt(). I've tried doing it using get_posts() and setup_postdata(). I've also tried a standard WP_Query loop.</p> <p>No matter what I do, it just gives me the automatically generated excerpt.</p> <p>Any ideas?</p> <pre><code> &lt;?php $posts = get_posts(array( 'post_type' =&gt; 'press-release' )); foreach ($posts as $i =&gt; $post) { setup_postdata($post); ?&gt; &lt;div class="row press appear" on-visible="{class: 'visible'}"&gt; &lt;div class="columns small-3"&gt; &lt;p class="date"&gt;&lt;?php echo get_the_date('M j Y'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="columns small-9"&gt; &lt;h2&gt;&lt;a target="_blank" href="&lt;?php echo get_the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt; &amp;nbsp; &gt;&lt;/a&gt;&lt;/h2&gt; &lt;div class="excerpt"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 182815, "author": "Rene Korss", "author_id": 69908, "author_profile": "https://wordpress.stackexchange.com/users/69908", "pm_score": 1, "selected": false, "text": "<p>Make link like this</p>\n\n<pre><code>&lt;a href=\"http://example.com/?reaction=smk_remove_post&amp;id=1226&amp;_nonce=7be82cd4a0\" data-id=\"1226\" data-nonce=\"7be82cd4a0\" class=\"smk-remove-post\"&gt;Remove post&lt;/a&gt;\n</code></pre>\n\n<p>And jQuery</p>\n\n<pre><code>$('.smk-remove-post').on( 'click', function( event ){\n event.preventDefault();\n var _this = $(this);\n\n var data = {\n 'action': 'smk_remove_post_ajax',\n 'reaction': 'smk_remove_post',\n 'id': _this.data('id'),\n '_nonce': _this.data('nonce')\n };\n\n // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php\n jQuery.ajax({\n type: \"GET\",\n url: ajaxurl,\n data: data,\n success: function(response){\n console.log(response);\n _this.text('All great, the post is removed.');\n }\n });\n});\n</code></pre>\n\n<p>See Codex about <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">AJAX in Plugins</a>.\nAnd in Codex, it says:</p>\n\n<blockquote>\n <p>Most of the time you should be using wp_die() in your Ajax callback function. This provides better integration with WordPress and makes it easier to test your code.</p>\n</blockquote>\n\n<p>So use <code>wp_die();</code> instead of <code>die();</code></p>\n" }, { "answer_id": 182816, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>AJAX is not magical and when you request url X you will receive the same HTML for that url if you do it from the browser address bar, link or ajax. Therefor, if you want different response then the HTML you <strong>can not</strong> use the same url for the ajax request as in the link.</p>\n\n<p>Wordpress has a special \"end point\" to handle ajax request - admin-ajax.php and all ajax request should be send only to it, something like <code>$.ajax({url:....admin-ajax.php})</code></p>\n\n<p>Next you need do let wordpress know what you want to do and for that there is a special parameter in the request named <code>action</code>. This parameter will identify the hook to be used at the server side to handle the request. This part you have done right in your code.</p>\n\n<p>Now you need the additional parameters that identifies which object should be manipulated or retrieved by the AJAX operation. You can use the permalink of the post, or the post id for example, but it all depends on the complexity of the operation you are trying to do. In your specific case I would guess that a post id will be the best parameter to pass in the request.</p>\n\n<p>How to send the parameters? most people do a POST request when doing AJAX but if you want a GET the you can pass them as part of the url (which I assume is exactly what jquery will do for you).</p>\n" }, { "answer_id": 182824, "author": "Andrei Surdu", "author_id": 31111, "author_profile": "https://wordpress.stackexchange.com/users/31111", "pm_score": 3, "selected": true, "text": "<p>I finally got it.</p>\n\n<p>First mistake was to process the same function twice. I've called it once after the function and one more time in ajax action. So when using the ajax call, the function got executed twice. In the example from the OP, this is not a problem at all, because it is simplified to do only one thing, but in my real code it does much more and can result in lost of unwanted data.</p>\n\n<p>Also, I just needed to stop the ajax and get a custom responce, nothing more. Here is what I've did:</p>\n\n<p><strong>1.</strong> <em>I've changed this:</em></p>\n\n<pre><code>smk_remove_post();\n</code></pre>\n\n<p><em>to this:</em></p>\n\n<pre><code>add_action('parse_query', 'smk_remove_post');\n</code></pre>\n\n<p>It is better to run the function later when needed in special action.</p>\n\n<p><strong>2.</strong> <em>Next, I've modified the ajax handler:</em>\nI've deleted this line <code>smk_remove_post();</code> and changed the ajax action from <code>wp_ajax_smk_remove_post_ajax</code> to <code>wp_ajax_smk_remove_post</code>:</p>\n\n<pre><code>function smk_remove_post_ajax(){\n wp_die( 'ok' );\n}\nadd_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax');\n</code></pre>\n\n<p><strong>3.</strong> I've renamed the query string <code>reaction</code> to <code>action</code>. Changed it in the url, and function:</p>\n\n<p><strong>4.</strong> Finally modified the jQuery script. So it uses the admin-ajax.php and sends the url as data:</p>\n\n<pre><code>url: ajaxurl,\ndata: _this.attr('href'),\n</code></pre>\n\n<h2>Here is the final code:</h2>\n\n<p><strong>Link:</strong></p>\n\n<pre><code>&lt;a href=\"http://example.com/?action=smk_remove_post&amp;id=1226&amp;_nonce=7be82cd4a0\" class=\"smk-remove-post\"&gt;Remove post&lt;/a&gt;\n</code></pre>\n\n<p><strong>PHP code:</strong></p>\n\n<pre><code>function smk_remove_post(){\n if( !empty( $_GET['action'] ) &amp;&amp; 'smk_remove_post' == $_GET['action'] &amp;&amp; !empty( $_GET['id'] ) ){\n if( current_user_can('edit_others_posts') &amp;&amp; !empty($_GET['_nonce']) ){\n if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){\n // Delete the post\n wp_delete_post( absint( $_GET['id'] ), true );\n }\n }\n }\n}\nadd_action('parse_query', 'smk_remove_post');\n\nfunction smk_remove_post_ajax(){\n wp_die( 'ok' );\n}\nadd_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax');\n</code></pre>\n\n<p><strong>Javascript:</strong></p>\n\n<pre><code>function smk_remove_post(){\n $('.smk-remove-post').on( 'click', function( event ){\n event.preventDefault();\n var _this = $(this);\n\n jQuery.ajax({\n type: \"GET\",\n url: ajaxurl,\n data: _this.attr('href').split('?')[1],\n success: function(response){\n console.log(response); // ok\n _this.text('All great, the post is removed.');\n }\n });\n });\n}\nsmk_remove_post();\n</code></pre>\n\n<p><strong>Edit:</strong>\nAlso a small update to the code above. To process the query strings is required to delete the site path, else it may create unexpected problems. I've added this to <code>data href</code>:</p>\n\n<pre><code>.split('?')[1]\n</code></pre>\n" } ]
2015/03/31
[ "https://wordpress.stackexchange.com/questions/182859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69939/" ]
I've set up some custom post types with Pods, but can't seem to get it to display my manual excerpt. It's working fine for my normal posts. I've tried displaying it with echo get\_the\_excerpt() and the\_excerpt(). I've tried doing it using get\_posts() and setup\_postdata(). I've also tried a standard WP\_Query loop. No matter what I do, it just gives me the automatically generated excerpt. Any ideas? ``` <?php $posts = get_posts(array( 'post_type' => 'press-release' )); foreach ($posts as $i => $post) { setup_postdata($post); ?> <div class="row press appear" on-visible="{class: 'visible'}"> <div class="columns small-3"> <p class="date"><?php echo get_the_date('M j Y'); ?></p> </div> <div class="columns small-9"> <h2><a target="_blank" href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?> &nbsp; ></a></h2> <div class="excerpt"><?php the_excerpt(); ?></div> </div> </div> <?php } ?> ```
I finally got it. First mistake was to process the same function twice. I've called it once after the function and one more time in ajax action. So when using the ajax call, the function got executed twice. In the example from the OP, this is not a problem at all, because it is simplified to do only one thing, but in my real code it does much more and can result in lost of unwanted data. Also, I just needed to stop the ajax and get a custom responce, nothing more. Here is what I've did: **1.** *I've changed this:* ``` smk_remove_post(); ``` *to this:* ``` add_action('parse_query', 'smk_remove_post'); ``` It is better to run the function later when needed in special action. **2.** *Next, I've modified the ajax handler:* I've deleted this line `smk_remove_post();` and changed the ajax action from `wp_ajax_smk_remove_post_ajax` to `wp_ajax_smk_remove_post`: ``` function smk_remove_post_ajax(){ wp_die( 'ok' ); } add_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax'); ``` **3.** I've renamed the query string `reaction` to `action`. Changed it in the url, and function: **4.** Finally modified the jQuery script. So it uses the admin-ajax.php and sends the url as data: ``` url: ajaxurl, data: _this.attr('href'), ``` Here is the final code: ----------------------- **Link:** ``` <a href="http://example.com/?action=smk_remove_post&id=1226&_nonce=7be82cd4a0" class="smk-remove-post">Remove post</a> ``` **PHP code:** ``` function smk_remove_post(){ if( !empty( $_GET['action'] ) && 'smk_remove_post' == $_GET['action'] && !empty( $_GET['id'] ) ){ if( current_user_can('edit_others_posts') && !empty($_GET['_nonce']) ){ if( wp_verify_nonce( esc_html( $_GET['_nonce'] ), 'smk_remove_post' ) ){ // Delete the post wp_delete_post( absint( $_GET['id'] ), true ); } } } } add_action('parse_query', 'smk_remove_post'); function smk_remove_post_ajax(){ wp_die( 'ok' ); } add_action('wp_ajax_smk_remove_post', 'smk_remove_post_ajax'); ``` **Javascript:** ``` function smk_remove_post(){ $('.smk-remove-post').on( 'click', function( event ){ event.preventDefault(); var _this = $(this); jQuery.ajax({ type: "GET", url: ajaxurl, data: _this.attr('href').split('?')[1], success: function(response){ console.log(response); // ok _this.text('All great, the post is removed.'); } }); }); } smk_remove_post(); ``` **Edit:** Also a small update to the code above. To process the query strings is required to delete the site path, else it may create unexpected problems. I've added this to `data href`: ``` .split('?')[1] ```
182,891
<p>I create custom plugin for import categories. now i have categories array from api.but when import categories into my wordpress woo commerce means not working.</p> <p>My code is given below.</p> <pre><code>public function sample_insert_category() { if(!term_exists('sample-category')) { wp_insert_term( 'Sample Category', 'category', array( 'description' =&gt; 'This is an sample category.', 'slug' =&gt; 'sample-category' ) ); } } add_action( 'init', 'sample_insert_category' ); </code></pre> <p>already i have used this code in function.php file. now i create a plugin. so i need to include this to my plugin. When i add this code into my plugin class means i got the warning. </p> <pre><code>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'admin_menu_top' not found or invalid function name </code></pre> <p>i want to add category and sub category using code.. help me anyone.</p>
[ { "answer_id": 182892, "author": "Christopher Carvache", "author_id": 15341, "author_profile": "https://wordpress.stackexchange.com/users/15341", "pm_score": 1, "selected": false, "text": "<p>The syntax for adding an action in WordPress WITHIN a class is somewhat different. Your code will have to look somewhat more like the following...</p>\n\n<pre><code>class MyPluginClass {\n\n public function __construct() {\n\n add_action( 'init', array( $this, 'sample_insert_category') );\n }\n\n public function sample_insert_category() {\n\n if(!term_exists('sample-category')) {\n wp_insert_term(\n 'Sample Category',\n 'category',\n array(\n 'description' =&gt; 'This is an sample category.',\n 'slug' =&gt; 'sample-category'\n )\n );\n }\n\n }\n}\n\n$mypluginclass = new MyPluginClass(); \n</code></pre>\n" }, { "answer_id": 182932, "author": "Padmanathan J", "author_id": 33786, "author_profile": "https://wordpress.stackexchange.com/users/33786", "pm_score": 1, "selected": true, "text": "<p>Finally i used the following code and i add category from my plug in.</p>\n\n<pre><code>class MyPluginClass {\n public function __construct() {\n add_action( 'init', array( $this, 'sample_insert_category') );\n }\n\n\n public function sample_insert_category() {\n\n\n if(!term_exists('Test','product_cat')) {\n\n wp_insert_term(\n 'Test',\n 'product_cat',\n array(\n 'description' =&gt; 'This is an sample category.',\n 'slug' =&gt; 'Test'\n )\n );\n }\n\n }\n\n\n}\n\n$mypluginclass = new MyPluginClass(); \n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33786/" ]
I create custom plugin for import categories. now i have categories array from api.but when import categories into my wordpress woo commerce means not working. My code is given below. ``` public function sample_insert_category() { if(!term_exists('sample-category')) { wp_insert_term( 'Sample Category', 'category', array( 'description' => 'This is an sample category.', 'slug' => 'sample-category' ) ); } } add_action( 'init', 'sample_insert_category' ); ``` already i have used this code in function.php file. now i create a plugin. so i need to include this to my plugin. When i add this code into my plugin class means i got the warning. ``` Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'admin_menu_top' not found or invalid function name ``` i want to add category and sub category using code.. help me anyone.
Finally i used the following code and i add category from my plug in. ``` class MyPluginClass { public function __construct() { add_action( 'init', array( $this, 'sample_insert_category') ); } public function sample_insert_category() { if(!term_exists('Test','product_cat')) { wp_insert_term( 'Test', 'product_cat', array( 'description' => 'This is an sample category.', 'slug' => 'Test' ) ); } } } $mypluginclass = new MyPluginClass(); ```
182,896
<p>I'm trying to customize <code>single-product.php</code> to achieve the often requested <strong>different categories = different single product templates</strong>, but it seems this file it's not affecting anything at all.</p> <p>It's like only <code>content-single-product.php</code> is doing what it should <em>(eg. if i customize it, the changes are reflected in the single product pages</em>) and the other files are useless in rendering the single products (!). </p> <p>I even completely delete all php files in <code>plugins/woocommerce/templates</code> folder, and if i leave there <strong>only</strong> <code>content-single-product.php</code>, everything still works and every single product is correctly shown!</p> <p>What am i missing about woocommerce's logic?!</p>
[ { "answer_id": 182892, "author": "Christopher Carvache", "author_id": 15341, "author_profile": "https://wordpress.stackexchange.com/users/15341", "pm_score": 1, "selected": false, "text": "<p>The syntax for adding an action in WordPress WITHIN a class is somewhat different. Your code will have to look somewhat more like the following...</p>\n\n<pre><code>class MyPluginClass {\n\n public function __construct() {\n\n add_action( 'init', array( $this, 'sample_insert_category') );\n }\n\n public function sample_insert_category() {\n\n if(!term_exists('sample-category')) {\n wp_insert_term(\n 'Sample Category',\n 'category',\n array(\n 'description' =&gt; 'This is an sample category.',\n 'slug' =&gt; 'sample-category'\n )\n );\n }\n\n }\n}\n\n$mypluginclass = new MyPluginClass(); \n</code></pre>\n" }, { "answer_id": 182932, "author": "Padmanathan J", "author_id": 33786, "author_profile": "https://wordpress.stackexchange.com/users/33786", "pm_score": 1, "selected": true, "text": "<p>Finally i used the following code and i add category from my plug in.</p>\n\n<pre><code>class MyPluginClass {\n public function __construct() {\n add_action( 'init', array( $this, 'sample_insert_category') );\n }\n\n\n public function sample_insert_category() {\n\n\n if(!term_exists('Test','product_cat')) {\n\n wp_insert_term(\n 'Test',\n 'product_cat',\n array(\n 'description' =&gt; 'This is an sample category.',\n 'slug' =&gt; 'Test'\n )\n );\n }\n\n }\n\n\n}\n\n$mypluginclass = new MyPluginClass(); \n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69810/" ]
I'm trying to customize `single-product.php` to achieve the often requested **different categories = different single product templates**, but it seems this file it's not affecting anything at all. It's like only `content-single-product.php` is doing what it should *(eg. if i customize it, the changes are reflected in the single product pages*) and the other files are useless in rendering the single products (!). I even completely delete all php files in `plugins/woocommerce/templates` folder, and if i leave there **only** `content-single-product.php`, everything still works and every single product is correctly shown! What am i missing about woocommerce's logic?!
Finally i used the following code and i add category from my plug in. ``` class MyPluginClass { public function __construct() { add_action( 'init', array( $this, 'sample_insert_category') ); } public function sample_insert_category() { if(!term_exists('Test','product_cat')) { wp_insert_term( 'Test', 'product_cat', array( 'description' => 'This is an sample category.', 'slug' => 'Test' ) ); } } } $mypluginclass = new MyPluginClass(); ```
182,909
<p>Is there some wordpress magic/plugin that will make the media library only show images that were uploaded to a specific custom post type? I have a custom post type called "artists", I want, when admin click to upload/attach an image, that the media library popup only show images that have been uploaded to the artists custom type, and not the entire site.</p> <p>I use the ACF plugin for handling custom fields, and custom post types ui. Is this possible?</p>
[ { "answer_id": 190880, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 4, "selected": true, "text": "<p>I'm not 100% sure if I get your problem right, but... Maybe this will help you...</p>\n\n<p>Media uploader gets attachments with simple <code>WP_Query</code>, so you can use many filters to modify it's contents.</p>\n\n<p>The only problem is that you can't query posts with specific CPT as parent using <code>WP_Query</code> arguments... So, we will have to use <code>posts_where</code> and <code>posts_join</code> filters.</p>\n\n<p>To be sure, that we'll change only media uploader's query, we'll use <code>ajax_query_attachments_args</code>.</p>\n\n<p>And this is how it looks, when combined:</p>\n\n<pre><code>function my_posts_where($where) {\n global $wpdb;\n\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n\n $post = get_post($post_id);\n if ( $post ) {\n $where .= $wpdb-&gt;prepare(\" AND my_post_parent.post_type = %s \", $post-&gt;post_type);\n }\n }\n\n return $where;\n}\n\nfunction my_posts_join($join) {\n global $wpdb;\n\n $join .= \" LEFT JOIN {$wpdb-&gt;posts} as my_post_parent ON ({$wpdb-&gt;posts}.post_parent = my_post_parent.ID) \";\n\n return $join;\n}\n\n\nfunction my_bind_media_uploader_special_filters($query) {\n add_filter('posts_where', 'my_posts_where');\n add_filter('posts_join', 'my_posts_join');\n\n return $query;\n}\nadd_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters');\n</code></pre>\n\n<p>When you open media uploader dialog while editing post (post/page/CPT), you'll see only images attached to this specific post type.</p>\n\n<p>If you'd like it to work only for one specific post type (let's say pages), you'll have to change condition in <code>my_posts_where</code> function like so:</p>\n\n<pre><code>function my_posts_where($where) {\n global $wpdb;\n\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n\n $post = get_post($post_id);\n if ( $post &amp;&amp; 'page' == $post-&gt;post_type ) { // you can change 'page' to any other post type\n $where .= $wpdb-&gt;prepare(\" AND my_post_parent.post_type = %s \", $post-&gt;post_type);\n }\n }\n\n return $where;\n}\n</code></pre>\n" }, { "answer_id": 354343, "author": "A.Azzam", "author_id": 179605, "author_profile": "https://wordpress.stackexchange.com/users/179605", "pm_score": 0, "selected": false, "text": "<p>Display only the images of the property when editing the featured image</p>\n\n<pre><code>function my_bind_media_uploader_special_filters($query) \n{\n\n add_filter('posts_where', 'my_posts_where');\n return $query;\n}\n\nadd_filter('ajax_query_attachments_args','my_bind_media_uploader_special_filters');\n\nfunction my_posts_where ($where) \n{\n\n global $wpdb;\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n $post = get_post($post_id);\n if ( $post &amp;&amp; 'property' == $post-&gt;post_type) {\n $where .= $wpdb-&gt;prepare(\" AND id in (select distinct meta_value from \n wpdb_postmeta where meta_key='fave_property_images' and post_id = $post_id)\", \n $post-&gt;post_type);\n }\n }\n return $where;\n}\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182909", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27260/" ]
Is there some wordpress magic/plugin that will make the media library only show images that were uploaded to a specific custom post type? I have a custom post type called "artists", I want, when admin click to upload/attach an image, that the media library popup only show images that have been uploaded to the artists custom type, and not the entire site. I use the ACF plugin for handling custom fields, and custom post types ui. Is this possible?
I'm not 100% sure if I get your problem right, but... Maybe this will help you... Media uploader gets attachments with simple `WP_Query`, so you can use many filters to modify it's contents. The only problem is that you can't query posts with specific CPT as parent using `WP_Query` arguments... So, we will have to use `posts_where` and `posts_join` filters. To be sure, that we'll change only media uploader's query, we'll use `ajax_query_attachments_args`. And this is how it looks, when combined: ``` function my_posts_where($where) { global $wpdb; $post_id = false; if ( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; $post = get_post($post_id); if ( $post ) { $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type); } } return $where; } function my_posts_join($join) { global $wpdb; $join .= " LEFT JOIN {$wpdb->posts} as my_post_parent ON ({$wpdb->posts}.post_parent = my_post_parent.ID) "; return $join; } function my_bind_media_uploader_special_filters($query) { add_filter('posts_where', 'my_posts_where'); add_filter('posts_join', 'my_posts_join'); return $query; } add_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters'); ``` When you open media uploader dialog while editing post (post/page/CPT), you'll see only images attached to this specific post type. If you'd like it to work only for one specific post type (let's say pages), you'll have to change condition in `my_posts_where` function like so: ``` function my_posts_where($where) { global $wpdb; $post_id = false; if ( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; $post = get_post($post_id); if ( $post && 'page' == $post->post_type ) { // you can change 'page' to any other post type $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type); } } return $where; } ```
182,912
<p>I am an editor of a blog with nearly 200 published articles that have been published within the last two years. All the popular posts plugins I've found show the most popular posts of all time. Understandably, the older posts have significantly more views because, well, they've been live for a lot longer than posts published in 2015.</p> <p>I'm trying to figure out a way to display a number of posts in list form based on how many hits they received within the first 30 days of being published.</p> <p>Any ideas as to where I should get started?</p>
[ { "answer_id": 190880, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 4, "selected": true, "text": "<p>I'm not 100% sure if I get your problem right, but... Maybe this will help you...</p>\n\n<p>Media uploader gets attachments with simple <code>WP_Query</code>, so you can use many filters to modify it's contents.</p>\n\n<p>The only problem is that you can't query posts with specific CPT as parent using <code>WP_Query</code> arguments... So, we will have to use <code>posts_where</code> and <code>posts_join</code> filters.</p>\n\n<p>To be sure, that we'll change only media uploader's query, we'll use <code>ajax_query_attachments_args</code>.</p>\n\n<p>And this is how it looks, when combined:</p>\n\n<pre><code>function my_posts_where($where) {\n global $wpdb;\n\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n\n $post = get_post($post_id);\n if ( $post ) {\n $where .= $wpdb-&gt;prepare(\" AND my_post_parent.post_type = %s \", $post-&gt;post_type);\n }\n }\n\n return $where;\n}\n\nfunction my_posts_join($join) {\n global $wpdb;\n\n $join .= \" LEFT JOIN {$wpdb-&gt;posts} as my_post_parent ON ({$wpdb-&gt;posts}.post_parent = my_post_parent.ID) \";\n\n return $join;\n}\n\n\nfunction my_bind_media_uploader_special_filters($query) {\n add_filter('posts_where', 'my_posts_where');\n add_filter('posts_join', 'my_posts_join');\n\n return $query;\n}\nadd_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters');\n</code></pre>\n\n<p>When you open media uploader dialog while editing post (post/page/CPT), you'll see only images attached to this specific post type.</p>\n\n<p>If you'd like it to work only for one specific post type (let's say pages), you'll have to change condition in <code>my_posts_where</code> function like so:</p>\n\n<pre><code>function my_posts_where($where) {\n global $wpdb;\n\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n\n $post = get_post($post_id);\n if ( $post &amp;&amp; 'page' == $post-&gt;post_type ) { // you can change 'page' to any other post type\n $where .= $wpdb-&gt;prepare(\" AND my_post_parent.post_type = %s \", $post-&gt;post_type);\n }\n }\n\n return $where;\n}\n</code></pre>\n" }, { "answer_id": 354343, "author": "A.Azzam", "author_id": 179605, "author_profile": "https://wordpress.stackexchange.com/users/179605", "pm_score": 0, "selected": false, "text": "<p>Display only the images of the property when editing the featured image</p>\n\n<pre><code>function my_bind_media_uploader_special_filters($query) \n{\n\n add_filter('posts_where', 'my_posts_where');\n return $query;\n}\n\nadd_filter('ajax_query_attachments_args','my_bind_media_uploader_special_filters');\n\nfunction my_posts_where ($where) \n{\n\n global $wpdb;\n $post_id = false;\n if ( isset($_POST['post_id']) ) {\n $post_id = $_POST['post_id'];\n $post = get_post($post_id);\n if ( $post &amp;&amp; 'property' == $post-&gt;post_type) {\n $where .= $wpdb-&gt;prepare(\" AND id in (select distinct meta_value from \n wpdb_postmeta where meta_key='fave_property_images' and post_id = $post_id)\", \n $post-&gt;post_type);\n }\n }\n return $where;\n}\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37786/" ]
I am an editor of a blog with nearly 200 published articles that have been published within the last two years. All the popular posts plugins I've found show the most popular posts of all time. Understandably, the older posts have significantly more views because, well, they've been live for a lot longer than posts published in 2015. I'm trying to figure out a way to display a number of posts in list form based on how many hits they received within the first 30 days of being published. Any ideas as to where I should get started?
I'm not 100% sure if I get your problem right, but... Maybe this will help you... Media uploader gets attachments with simple `WP_Query`, so you can use many filters to modify it's contents. The only problem is that you can't query posts with specific CPT as parent using `WP_Query` arguments... So, we will have to use `posts_where` and `posts_join` filters. To be sure, that we'll change only media uploader's query, we'll use `ajax_query_attachments_args`. And this is how it looks, when combined: ``` function my_posts_where($where) { global $wpdb; $post_id = false; if ( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; $post = get_post($post_id); if ( $post ) { $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type); } } return $where; } function my_posts_join($join) { global $wpdb; $join .= " LEFT JOIN {$wpdb->posts} as my_post_parent ON ({$wpdb->posts}.post_parent = my_post_parent.ID) "; return $join; } function my_bind_media_uploader_special_filters($query) { add_filter('posts_where', 'my_posts_where'); add_filter('posts_join', 'my_posts_join'); return $query; } add_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters'); ``` When you open media uploader dialog while editing post (post/page/CPT), you'll see only images attached to this specific post type. If you'd like it to work only for one specific post type (let's say pages), you'll have to change condition in `my_posts_where` function like so: ``` function my_posts_where($where) { global $wpdb; $post_id = false; if ( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; $post = get_post($post_id); if ( $post && 'page' == $post->post_type ) { // you can change 'page' to any other post type $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type); } } return $where; } ```
182,921
<p>I have two links in </p> <ul> <li>"news" where all the news posts goes </li> <li>"blog" where the rest goes</li> </ul> <p>just wanted to exclude the category "news" in the blog page</p> <p>I use the code </p> <pre><code>$news = new WP_query ('category_name =-news') </code></pre> <p>and it is not working</p> <p>Essentially, I want tell wordpress, I want all the posts to go into the "blog" page but not in the post that is categorize as "news"</p>
[ { "answer_id": 182925, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>Use the parameters <code>cat</code> or <code>category__not_in</code>:</p>\n\n<pre><code>$query = new WP_Query( 'cat=-1234' );\n</code></pre>\n\n<p>The minus means to exclude, the ID is used.</p>\n\n<pre><code>$query = new WP_Query( array( 'category__not_in' =&gt; array( 1234 ) ) );\n</code></pre>\n\n<p>Uses the ID too.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_cat_ID\" rel=\"nofollow\"><code>get_cat_ID()</code></a> to get the ID by name or <a href=\"https://codex.wordpress.org/Function_Reference/get_category_by_slug\" rel=\"nofollow\"><code>get_category_by_slug()</code></a> to do it by slug, the latter returns an object though.</p>\n" }, { "answer_id": 182928, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 1, "selected": false, "text": "<p>In your functions.php file, use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> and swap out the -1 in the following code with the category I.D you want to exclude from your posts page.</p>\n\n<pre><code>function exclude_category( $query ) {\n if ( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'cat', '-1' );\n }\n}\nadd_action( 'pre_get_posts', 'exclude_category' );\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182921", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69971/" ]
I have two links in * "news" where all the news posts goes * "blog" where the rest goes just wanted to exclude the category "news" in the blog page I use the code ``` $news = new WP_query ('category_name =-news') ``` and it is not working Essentially, I want tell wordpress, I want all the posts to go into the "blog" page but not in the post that is categorize as "news"
In your functions.php file, use [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) and swap out the -1 in the following code with the category I.D you want to exclude from your posts page. ``` function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-1' ); } } add_action( 'pre_get_posts', 'exclude_category' ); ```
182,929
<p>Could someone please point me in the right direction, im currently using : </p> <pre><code>&lt;?php if (get_the_time('H') &gt;= 8 &amp;&amp; get_the_time('H') &lt; 20) : ?&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/assets/images/picture1.jpg" alt="randomalt2" /&gt; &lt;?php else : ?&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/assets/images/pictur2.jpg" alt="randomalt1" /&gt; &lt;?php endif; ?&gt; </code></pre> <p>Which is suppose to change image at certain times of the day, currently set at 8 in the morning and 8 at night ( 20 ).</p> <p>The image shows but it isnt changing, is there something ive missed ?</p>
[ { "answer_id": 182925, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>Use the parameters <code>cat</code> or <code>category__not_in</code>:</p>\n\n<pre><code>$query = new WP_Query( 'cat=-1234' );\n</code></pre>\n\n<p>The minus means to exclude, the ID is used.</p>\n\n<pre><code>$query = new WP_Query( array( 'category__not_in' =&gt; array( 1234 ) ) );\n</code></pre>\n\n<p>Uses the ID too.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_cat_ID\" rel=\"nofollow\"><code>get_cat_ID()</code></a> to get the ID by name or <a href=\"https://codex.wordpress.org/Function_Reference/get_category_by_slug\" rel=\"nofollow\"><code>get_category_by_slug()</code></a> to do it by slug, the latter returns an object though.</p>\n" }, { "answer_id": 182928, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 1, "selected": false, "text": "<p>In your functions.php file, use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> and swap out the -1 in the following code with the category I.D you want to exclude from your posts page.</p>\n\n<pre><code>function exclude_category( $query ) {\n if ( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'cat', '-1' );\n }\n}\nadd_action( 'pre_get_posts', 'exclude_category' );\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69976/" ]
Could someone please point me in the right direction, im currently using : ``` <?php if (get_the_time('H') >= 8 && get_the_time('H') < 20) : ?> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/picture1.jpg" alt="randomalt2" /> <?php else : ?> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/pictur2.jpg" alt="randomalt1" /> <?php endif; ?> ``` Which is suppose to change image at certain times of the day, currently set at 8 in the morning and 8 at night ( 20 ). The image shows but it isnt changing, is there something ive missed ?
In your functions.php file, use [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) and swap out the -1 in the following code with the category I.D you want to exclude from your posts page. ``` function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-1' ); } } add_action( 'pre_get_posts', 'exclude_category' ); ```
182,943
<p>I have a the following</p> <ul> <li><p>Custom post type: <code>episode</code> </p></li> <li><p>Custom taxonomy: <code>series</code> </p> <ul> <li>sub terms <code>real deal</code> -> <code>season 1</code>, <code>season 2</code>, <code>season 3</code>, etc. </li> </ul></li> </ul> <p>The terms are hierarchical, and the entire thing is intended to be structured like a TV series (each "series" has "seasons").</p> <p>On the <code>single-episode.php</code> page, I want to display the current episode, AS WELL AS links to the next 3 episodes and previous 3 episodes in that season. </p> <p>As an example, if on the "Season 1 - Episode 5" page, I need to get content for Season 1,</p> <blockquote> <p>Episodes 4,3,2 + Season 1 Episodes 6,7,8.</p> </blockquote> <p>I'm having trouble figuring out how to do this inside the loop on a single episode page. </p> <p>Here's what I currently have, however it does not work -- it just repeats the current page episode title over and over with a </p> <blockquote> <p>trying to get property of non-object</p> </blockquote> <p>error.</p> <pre><code>&lt;?php $args = array( 'post-type' =&gt; 'episode', 'post-status' =&gt; 'publish', 'posts_per_page' =&gt; 6, 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'series', 'field' =&gt; 'slug', /* Name of the "series" (in slug format) */ 'terms' =&gt; array( 'season-1' ), ), array( 'taxonomy' =&gt; 'series', 'field' =&gt; 'slug', /* Name of the "seasons" (in slug format) DYNAMIC */ 'terms' =&gt; array( $term-&gt;slug ), ) ) ); $episodes = new WP_Query( $args ); foreach( $episodes as $episode ) { echo get_the_title($episode-&gt;id); } ?&gt; </code></pre> <hr> <p><strong>EDIT</strong>: </p> <p>Here's my updated query, still a work in progress. It does not seem to be getting anything at the moment. I want to get a total of 6 results, 3 posted BEFORE to the current post, 3 posted AFTER the current post. I'm trying to use the <code>post_date</code> for both the <code>before</code> and <code>after</code> properties of <code>date_query</code> but not sure if I'm doing it right.</p> <pre><code>$args = [ 'tax_query' =&gt; [ 'relation' =&gt; 'AND', [ 'taxonomy' =&gt; 'series', 'field' =&gt; 'slug', /* Name of the "series" (in slug format) */ 'terms' =&gt; ['season-1'], ] ], 'posts_per_page' =&gt; 6, /* make query more efficient */ 'no_found_rows' =&gt; true, /* dont let filters/pre_get_posts modify query */ 'suppress_filters' =&gt; true, 'date_query' =&gt; [ [ 'before' =&gt; $post_object-&gt;post_date, 'after' =&gt; $post_object-&gt;post_date, ], 'inclusive' =&gt; false ] ]; $q = new WP_Query( $args ); return $q-&gt;posts; </code></pre> <hr> <p><strong>EDIT 2:</strong></p> <p>I've gotten my desired effect working using a very inefficient method -- it works, but I'd LOVE to hear some tips to optimize it! seems very expensive in terms of queries right now.</p> <pre><code>$orig_post = $post; $orig_terms = wp_get_post_terms($orig_post-&gt;ID, 'series'); $current_post = $post; $adjPost = [ 'prev' =&gt; [], 'next' =&gt; [] ]; for($i = 1; $i &lt;= 3; $i++){ $post = get_previous_post(true, '', 'series'); // this uses $post-&gt;ID if ( $post ) { $these_terms = wp_get_post_terms($post-&gt;ID, 'series'); if ( $these_terms[1]-&gt;slug === $orig_terms[1]-&gt;slug) { array_push( $adjPost['prev'], $post ); } } } $post = $current_post; for($i = 1; $i &lt;= 3; $i++){ $post = get_next_post(true, '', 'series'); // this uses $post-&gt;ID if ( $post ) { $these_terms = wp_get_post_terms($post-&gt;ID, 'series'); if ( $these_terms[1]-&gt;slug === $orig_terms[1]-&gt;slug) { array_push( $adjPost['next'], $post ); } } } $post = $current_post; echo "&lt;h1&gt;Prev:&lt;/h1&gt;"; foreach ( $adjPost['prev'] as $prev ) { echo '&lt;br&gt;'; echo $prev-&gt;post_title; } echo "&lt;h1&gt;Next:&lt;/h1&gt;"; foreach ( $adjPost['next'] as $next ) { echo '&lt;br&gt;'; echo $next-&gt;post_title; } </code></pre>
[ { "answer_id": 182945, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 0, "selected": false, "text": "<p>Your syntax is slightly off - <code>$episodes</code> is an instance of <code>WP_Query</code>, not an array. If you want a full-blown loop for using all template tags, use:</p>\n\n<pre><code>while ( $episodes-&gt;have_posts() ) {\n $episodes-&gt;the_post();\n\n the_title(); // Episode title\n the_content(); // Episode content\n}\n\nwp_reset_postdata(); // Restore current episode\n</code></pre>\n\n<p>Otherwise you can just <code>foreach</code> on the <code>posts</code> property:</p>\n\n<pre><code>foreach ( $episodes-&gt;posts as $episode ) {\n echo get_the_title( $episode ); // Most template tags accept a post object\n echo get_the_post_thumbnail( $episode-&gt;ID ); // Only accepts post ID\n echo get_the_content(); // Does not accept a post argument, you'd need the loop above to set up the global post object\n}\n</code></pre>\n" }, { "answer_id": 182990, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>You second approach (<strong>EDIT 2</strong>) is quite buggy and inefficient unfortunately. Also, you are not going to do this in one query. </p>\n\n<p>As I already stated, you need to look at the approach in <a href=\"https://wordpress.stackexchange.com/a/182786/31545\">this answer</a> I have recently done. You were almost there in your first edit, the only problem is, you cannot do this in one query, you will have to do two, one to get the previous set of posts, the other to get the next set of posts.</p>\n\n<p>I have optimized the code to do only get the necessary info and nothing more. <code>WP_Query</code> results is also cached, so you really don't have to to worry that much about efficiency. </p>\n\n<p>I'm not going to rerun through all the detail again in this answer, you should go through the linked post in detail, but you can try something like this (<em>CAVEAT: Untested. Please see the notes in linked answer</em>)</p>\n\n<pre><code>$post_object = get_queried_object();\n$terms = wp_get_post_terms( $post_object-&gt;ID, 'series', array( 'fields' =&gt; 'ids' ) ); // Set fields to get only term ID's to make this more effient\n$args = [\n 'post_type' =&gt; $post_object-&gt;post_type,\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; 'series',\n 'terms' =&gt; $terms,\n ]\n ],\n 'posts_per_page' =&gt; 3,\n 'order' =&gt; 'ASC' // CHANDE TO DESC IF NOT CORRECT\n /* make query more efficient */\n 'no_found_rows' =&gt; true,\n /* dont let filters modify query */\n 'suppress_filters' =&gt; true,\n 'date_query' =&gt; [\n [\n 'before' =&gt; $post_object-&gt;post_date,\n 'inclusive' =&gt; false\n ],\n ]\n];\n$q1 = new WP_Query( $args );\nvar_dump( $q1-&gt;posts );\n\n$args1 = [\n 'post_type' =&gt; $post_object-&gt;post_type,\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; 'series',\n 'terms' =&gt; $terms,\n ]\n ],\n 'posts_per_page' =&gt; 3,\n 'order' =&gt; 'DESC' // CHANDE TO ASC IF NOT CORRECT\n /* make query more efficient */\n 'no_found_rows' =&gt; true,\n /* dont let filters modify query */\n 'suppress_filters' =&gt; true,\n 'date_query' =&gt; [\n [\n 'after' =&gt; $post_object-&gt;post_date,\n 'inclusive' =&gt; false\n ],\n ]\n];\n$q2 = new WP_Query( $args1 );\nvar_dump( $q2-&gt;posts );\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52619/" ]
I have a the following * Custom post type: `episode` * Custom taxonomy: `series` + sub terms `real deal` -> `season 1`, `season 2`, `season 3`, etc. The terms are hierarchical, and the entire thing is intended to be structured like a TV series (each "series" has "seasons"). On the `single-episode.php` page, I want to display the current episode, AS WELL AS links to the next 3 episodes and previous 3 episodes in that season. As an example, if on the "Season 1 - Episode 5" page, I need to get content for Season 1, > > Episodes 4,3,2 + Season 1 Episodes 6,7,8. > > > I'm having trouble figuring out how to do this inside the loop on a single episode page. Here's what I currently have, however it does not work -- it just repeats the current page episode title over and over with a > > trying to get property of non-object > > > error. ``` <?php $args = array( 'post-type' => 'episode', 'post-status' => 'publish', 'posts_per_page' => 6, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'series', 'field' => 'slug', /* Name of the "series" (in slug format) */ 'terms' => array( 'season-1' ), ), array( 'taxonomy' => 'series', 'field' => 'slug', /* Name of the "seasons" (in slug format) DYNAMIC */ 'terms' => array( $term->slug ), ) ) ); $episodes = new WP_Query( $args ); foreach( $episodes as $episode ) { echo get_the_title($episode->id); } ?> ``` --- **EDIT**: Here's my updated query, still a work in progress. It does not seem to be getting anything at the moment. I want to get a total of 6 results, 3 posted BEFORE to the current post, 3 posted AFTER the current post. I'm trying to use the `post_date` for both the `before` and `after` properties of `date_query` but not sure if I'm doing it right. ``` $args = [ 'tax_query' => [ 'relation' => 'AND', [ 'taxonomy' => 'series', 'field' => 'slug', /* Name of the "series" (in slug format) */ 'terms' => ['season-1'], ] ], 'posts_per_page' => 6, /* make query more efficient */ 'no_found_rows' => true, /* dont let filters/pre_get_posts modify query */ 'suppress_filters' => true, 'date_query' => [ [ 'before' => $post_object->post_date, 'after' => $post_object->post_date, ], 'inclusive' => false ] ]; $q = new WP_Query( $args ); return $q->posts; ``` --- **EDIT 2:** I've gotten my desired effect working using a very inefficient method -- it works, but I'd LOVE to hear some tips to optimize it! seems very expensive in terms of queries right now. ``` $orig_post = $post; $orig_terms = wp_get_post_terms($orig_post->ID, 'series'); $current_post = $post; $adjPost = [ 'prev' => [], 'next' => [] ]; for($i = 1; $i <= 3; $i++){ $post = get_previous_post(true, '', 'series'); // this uses $post->ID if ( $post ) { $these_terms = wp_get_post_terms($post->ID, 'series'); if ( $these_terms[1]->slug === $orig_terms[1]->slug) { array_push( $adjPost['prev'], $post ); } } } $post = $current_post; for($i = 1; $i <= 3; $i++){ $post = get_next_post(true, '', 'series'); // this uses $post->ID if ( $post ) { $these_terms = wp_get_post_terms($post->ID, 'series'); if ( $these_terms[1]->slug === $orig_terms[1]->slug) { array_push( $adjPost['next'], $post ); } } } $post = $current_post; echo "<h1>Prev:</h1>"; foreach ( $adjPost['prev'] as $prev ) { echo '<br>'; echo $prev->post_title; } echo "<h1>Next:</h1>"; foreach ( $adjPost['next'] as $next ) { echo '<br>'; echo $next->post_title; } ```
You second approach (**EDIT 2**) is quite buggy and inefficient unfortunately. Also, you are not going to do this in one query. As I already stated, you need to look at the approach in [this answer](https://wordpress.stackexchange.com/a/182786/31545) I have recently done. You were almost there in your first edit, the only problem is, you cannot do this in one query, you will have to do two, one to get the previous set of posts, the other to get the next set of posts. I have optimized the code to do only get the necessary info and nothing more. `WP_Query` results is also cached, so you really don't have to to worry that much about efficiency. I'm not going to rerun through all the detail again in this answer, you should go through the linked post in detail, but you can try something like this (*CAVEAT: Untested. Please see the notes in linked answer*) ``` $post_object = get_queried_object(); $terms = wp_get_post_terms( $post_object->ID, 'series', array( 'fields' => 'ids' ) ); // Set fields to get only term ID's to make this more effient $args = [ 'post_type' => $post_object->post_type, 'tax_query' => [ [ 'taxonomy' => 'series', 'terms' => $terms, ] ], 'posts_per_page' => 3, 'order' => 'ASC' // CHANDE TO DESC IF NOT CORRECT /* make query more efficient */ 'no_found_rows' => true, /* dont let filters modify query */ 'suppress_filters' => true, 'date_query' => [ [ 'before' => $post_object->post_date, 'inclusive' => false ], ] ]; $q1 = new WP_Query( $args ); var_dump( $q1->posts ); $args1 = [ 'post_type' => $post_object->post_type, 'tax_query' => [ [ 'taxonomy' => 'series', 'terms' => $terms, ] ], 'posts_per_page' => 3, 'order' => 'DESC' // CHANDE TO ASC IF NOT CORRECT /* make query more efficient */ 'no_found_rows' => true, /* dont let filters modify query */ 'suppress_filters' => true, 'date_query' => [ [ 'after' => $post_object->post_date, 'inclusive' => false ], ] ]; $q2 = new WP_Query( $args1 ); var_dump( $q2->posts ); ```
182,946
<p>I'm using the <a href="https://wordpress.org/plugins/wp-job-manager/" rel="nofollow">WP Job Manager plugin</a> in my wordpress website. The list of my jobs is currently found on <code>/jobs</code> . I would like to have it on <code>/careers</code> . The listing of all jobs is not a page so I can't change the url there. </p> <p>I've found <a href="https://wpjobmanager.com/document/tutorial-changing-the-job-slugpermalink/" rel="nofollow">this</a> topic that shows an example on how to change the slug from <code>/job/titlejob</code> to <code>/careers/titlejob</code>. But it doesn't show how I can change <strong>/jobs</strong> to <strong>/careers</strong>.</p> <p>In the example they are doing this:</p> <pre><code>function change_job_listing_slug( $args ) { $args['rewrite']['slug'] = _x( 'careers', 'Job permalink - resave permalinks after changing this', 'job_manager' ); return $args; } add_filter( 'register_post_type_job_listing', 'change_job_listing_slug' ); </code></pre> <p>When I add this to my <strong>functions.php</strong> my job detail pages are found at <strong>/careers/jobtitle</strong>. But the overview is still on <strong>/jobs</strong> . How can I change that?</p> <p>I also tried to change the jobs translation to careers but this also only works for the single job and not for my overview of jobs. </p>
[ { "answer_id": 183761, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>If you check out the <code>output()</code> method in the <code>includes/admin/class-wp-job-manager-setup.php</code> file, namely this part:</p>\n\n<pre><code>/**\n * Output addons page\n */\npublic function output() {\n $step = ! empty( $_GET['step'] ) ? absint( $_GET['step'] ) : 1;\n\n if ( 3 === $step &amp;&amp; ! empty( $_POST ) ) {\n $create_pages = isset( $_POST['wp-job-manager-create-page'] ) ? $_POST['wp-job-manager-create-page'] : array();\n $page_titles = $_POST['wp-job-manager-page-title'];\n $pages_to_create = array(\n 'submit_job_form' =&gt; '[submit_job_form]',\n 'job_dashboard' =&gt; '[job_dashboard]',\n 'jobs' =&gt; '[jobs]'\n );\n\n foreach ( $pages_to_create as $page =&gt; $content ) {\n if ( ! isset( $create_pages[ $page ] ) || empty( $page_titles[ $page ] ) ) {\n continue;\n }\n $this-&gt;create_page( sanitize_text_field( $page_titles[ $page ] ), $content, 'job_manager_' . $page . '_page_id' );\n }\n }\n</code></pre>\n\n<p>you can see that it's creating a page, with the <code>jobs</code> slug (by default) that contains the <code>[jobs]</code> shortcode to list the available jobs. </p>\n\n<p>So you should be able to simply create a page with the <code>careers</code> slug, that contains the <code>[jobs]</code> shortcode. </p>\n" }, { "answer_id": 184191, "author": "robert-jakobson", "author_id": 70624, "author_profile": "https://wordpress.stackexchange.com/users/70624", "pm_score": 0, "selected": false, "text": "<p>Alright, here to help :) If you find this helpful please share the bounty!</p>\n\n<p><strong>Step 1: The Research</strong></p>\n\n<p>My first hint was that these parts of the slugs are usually controlled by custom post type settings, thus I combed through the plugin files - finally finding that in the plugins in the file \"class-wp-job-manager-post-types.php\" inside the \"Includes\" folder on line 161, it states (1):</p>\n\n<pre><code>if ( current_theme_supports( 'job-manager-templates' ) ) {\n $has_archive = _x( 'jobs', 'Post type archive slug - resave permalinks after changing this', 'wp-job-manager' );\n } else {\n $has_archive = false;\n }\n</code></pre>\n\n<p><strong>Step 2: The Change</strong></p>\n\n<p>Now the \"current_theme_supports\" function gives us an important hint - we need to enable something within the currently active theme for things to work out. A bit of Googling and this is how to do it, straight from the documentation for the plugin (2):</p>\n\n<pre><code>add_theme_support( 'job-manager-templates' );\n</code></pre>\n\n<p>Simply add this to your theme´s functions.php file. And follow the rest of the instructions in the documentation page referenced above (link below), which include:</p>\n\n<ul>\n<li>resaving the permalinks after changing the slug</li>\n<li>then adding the custom archives and taxonomy templates</li>\n<li>while I do not have the plugin installed currently this should do the trick</li>\n</ul>\n\n<p><strong>References:</strong></p>\n\n<ul>\n<li>(1) <a href=\"https://github.com/mikejolley/WP-Job-Manager/blob/master/includes/class-wp-job-manager-post-types.php\" rel=\"nofollow\">https://github.com/mikejolley/WP-Job-Manager/blob/master/includes/class-wp-job-manager-post-types.php</a> </li>\n<li>(2) <a href=\"https://wpjobmanager.com/document/enabling-full-template-support/\" rel=\"nofollow\">https://wpjobmanager.com/document/enabling-full-template-support/</a></li>\n</ul>\n" }, { "answer_id": 184212, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><sub><strong>Please Note:</strong> Questions regarding 3rd-party plugins and themes are considered\n <a href=\"https://wordpress.stackexchange.com/help/on-topic\">off-topic</a> here at\n the WordPress Development SE. The best place to receive support for\n such items is the 3rd-party's official support channels. Please review\n the <a href=\"https://wordpress.stackexchange.com/help/how-to-ask\">How to Ask</a> section of our <a href=\"https://wordpress.stackexchange.com/help/help\">Help Center</a> to learn more about what questions are\n on-topic and a good fit.</sub></p>\n</blockquote>\n\n<hr>\n\n<p>That said, I took a glance at the plugin, in particular the file <code>includes/class-wp-job-manager-post-types.php</code> where the plugin actually registers the <code>'job_listing'</code> post-type. The plugin author supplies the <code>'register_post_type_job_listing'</code> filter hook in such a manner that you can alter any and every argument to the custom post-type's registration.</p>\n\n<p>Keeping that in mind, reading <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">the Codex entry for <code>register_post_type()</code></a>, take note of the <code>has_archive</code> argument, which allows you to specify which slug to use for archive pages. The most direct solution, then, should be to update the function in your theme's <strong><code>functions.php</code></strong> file to something similar to the following:</p>\n\n<pre><code>function wpse182946_change_job_listing_slugs( $args ) {\n $args['rewrite']['slug'] = _x( 'career', 'Job CPT slug', 'my_site_identifier' );\n $args['has_archive'] = _x( 'careers', 'Job CPT archive slug', 'my_site_identifier' );\n\n return $args;\n}\n\nadd_filter( 'register_post_type_job_listing', 'wpse182946_change_job_listing_slugs' );\n</code></pre>\n\n<p>Manually flush your installation's rewrite rules by saving your permalink settings on the Dashboard in order for the changes to take effect.</p>\n\n<p>If you wished to change the text every (or just a few) place it appears on the site, you should additionally alter the <code>labels</code> array argument:</p>\n\n<pre><code>function wpse182946_modify_job_listing_cpt( $args ) {\n $singular = 'Career';\n $plural = 'Careers';\n\n // Alter URL permalinks/slugs\n $args['rewrite']['slug'] = _x( strtolower( $singular ), 'Job CPT slug', 'my_site_identifier' );\n $args['has_archive'] = _x( strtolower( $plural ), 'Job CPT archive slug', 'my_site_identifier' );\n\n // Alter CPT labels\n $args['labels']['name'] = $plural;\n $args['labels']['singular_name'] = $singular;\n $args['labels']['menu_name'] = __( $singular . ' Listings', 'my_site_identifier' );\n $args['labels']['all_items'] = __( 'All ' . $plural, 'my_site_identifier' );\n $args['labels']['add_new'] = __( 'Add New', 'my_site_identifier' );\n $args['labels']['add_new_item'] = __( 'Add ' . $singular, 'my_site_identifier' );\n $args['labels']['edit'] = __( 'Edit', 'my_site_identifier' );\n $args['labels']['edit_item'] = __( 'Edit ' . $singular, 'my_site_identifier' );\n $args['labels']['new_item'] = __( 'New ' . $singular, 'my_site_identifier' );\n $args['labels']['view'] = __( 'View ' . $singular, 'my_site_identifier' );\n $args['labels']['view_item'] = __( 'View ' . $singular, 'my_site_identifier' );\n $args['labels']['search_items'] = __( 'Search ' . $plural, 'my_site_identifier' );\n $args['labels']['not_found'] = __( 'No ' . $plural . ' found', 'my_site_identifier' );\n $args['labels']['not_found_in_trash'] = __( 'No ' . $plural . ' found in trash', 'my_site_identifier' );\n $args['labels']['parent'] = __( 'Parent ' . $singular, 'my_site_identifier' );\n\n return $args;\n}\n\nadd_filter( 'register_post_type_job_listing', 'wpse182946_modify_job_listing_cpt' );\n</code></pre>\n" } ]
2015/04/01
[ "https://wordpress.stackexchange.com/questions/182946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65180/" ]
I'm using the [WP Job Manager plugin](https://wordpress.org/plugins/wp-job-manager/) in my wordpress website. The list of my jobs is currently found on `/jobs` . I would like to have it on `/careers` . The listing of all jobs is not a page so I can't change the url there. I've found [this](https://wpjobmanager.com/document/tutorial-changing-the-job-slugpermalink/) topic that shows an example on how to change the slug from `/job/titlejob` to `/careers/titlejob`. But it doesn't show how I can change **/jobs** to **/careers**. In the example they are doing this: ``` function change_job_listing_slug( $args ) { $args['rewrite']['slug'] = _x( 'careers', 'Job permalink - resave permalinks after changing this', 'job_manager' ); return $args; } add_filter( 'register_post_type_job_listing', 'change_job_listing_slug' ); ``` When I add this to my **functions.php** my job detail pages are found at **/careers/jobtitle**. But the overview is still on **/jobs** . How can I change that? I also tried to change the jobs translation to careers but this also only works for the single job and not for my overview of jobs.
If you check out the `output()` method in the `includes/admin/class-wp-job-manager-setup.php` file, namely this part: ``` /** * Output addons page */ public function output() { $step = ! empty( $_GET['step'] ) ? absint( $_GET['step'] ) : 1; if ( 3 === $step && ! empty( $_POST ) ) { $create_pages = isset( $_POST['wp-job-manager-create-page'] ) ? $_POST['wp-job-manager-create-page'] : array(); $page_titles = $_POST['wp-job-manager-page-title']; $pages_to_create = array( 'submit_job_form' => '[submit_job_form]', 'job_dashboard' => '[job_dashboard]', 'jobs' => '[jobs]' ); foreach ( $pages_to_create as $page => $content ) { if ( ! isset( $create_pages[ $page ] ) || empty( $page_titles[ $page ] ) ) { continue; } $this->create_page( sanitize_text_field( $page_titles[ $page ] ), $content, 'job_manager_' . $page . '_page_id' ); } } ``` you can see that it's creating a page, with the `jobs` slug (by default) that contains the `[jobs]` shortcode to list the available jobs. So you should be able to simply create a page with the `careers` slug, that contains the `[jobs]` shortcode.
182,989
<p>I have a WordPress website running on a machine. PHP has allocated memory of 128MB. Since I have two WP sites being host under same hosting it is consuming around 95MB out of 128MB on normal load..</p> <p>I wanted to move new theme with custom fields types (Advanced Custom Fields). We created a test environment on other server. Developed theme their and prepared the content we require to move on production website (posts, pages etc with custom fields). Since we were done with development. I wanted to move it to the mail website.</p> <p>While trying to import the WordPress backup, server just went down and I could see the following message displaying when I tried to refresh the page / hit the homepage. </p> <pre><code>Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. </code></pre> <p>I didn't get Fatal memory error that means the website does not have memory issues..</p> <p>Most of the times, I can see almost 95% of the memory is being utilized. What could be the error? </p> <p>Edit : We already have allocated more memory to PHP (i.e. 256MB) but I still get the same error.. Now, the site is totally down and I have no idea how to make it up again. </p>
[ { "answer_id": 187734, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": false, "text": "<p>Please check your .htacess files there might be some issues in it. You may even try to rename it.Hope it helps I was stuck with similar issues little time ago. </p>\n" }, { "answer_id": 187739, "author": "shyammakwana.me", "author_id": 49267, "author_profile": "https://wordpress.stackexchange.com/users/49267", "pm_score": 1, "selected": false, "text": "<p>When I had developed a theme, and I was trying to automate the import process by tweaking wordpress-importer plugin. I had faced the same issue. </p>\n\n<p>When importing server processes numerous DB operations at same time, that's why it's not able to respond and it results in 500 Internal server error. </p>\n\n<h1>Try 1 :</h1>\n\n<p>To fix the issue, you have to import one by one. \nWhatever importer you are using, tweak it such that it works with AJAX and imports data with some time gap.</p>\n\n<pre><code>setTimeout( function () {\n $.ajax({\n // import one part of your data\n });\n\n}, 2000 ) ; \n</code></pre>\n\n<h1>Try 2:</h1>\n\n<p>Try setting time limit of PHP to 0. \nPut this in starting of your importer's main file.</p>\n\n<pre><code>@set_time_limit(0); \n</code></pre>\n\n<p>You are not getting fatal error, still you should to give it a try. </p>\n" }, { "answer_id": 188053, "author": "Rahul Patil", "author_id": 26151, "author_profile": "https://wordpress.stackexchange.com/users/26151", "pm_score": 3, "selected": true, "text": "<p>Sorted it out myself.</p>\n\n<p>The problem was, server was very slow to process the import. The process was happening behind the scene but server actually went down.</p>\n\n<p>When server was up, I could see all the content on the other site.</p>\n" } ]
2015/04/02
[ "https://wordpress.stackexchange.com/questions/182989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26151/" ]
I have a WordPress website running on a machine. PHP has allocated memory of 128MB. Since I have two WP sites being host under same hosting it is consuming around 95MB out of 128MB on normal load.. I wanted to move new theme with custom fields types (Advanced Custom Fields). We created a test environment on other server. Developed theme their and prepared the content we require to move on production website (posts, pages etc with custom fields). Since we were done with development. I wanted to move it to the mail website. While trying to import the WordPress backup, server just went down and I could see the following message displaying when I tried to refresh the page / hit the homepage. ``` Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. ``` I didn't get Fatal memory error that means the website does not have memory issues.. Most of the times, I can see almost 95% of the memory is being utilized. What could be the error? Edit : We already have allocated more memory to PHP (i.e. 256MB) but I still get the same error.. Now, the site is totally down and I have no idea how to make it up again.
Sorted it out myself. The problem was, server was very slow to process the import. The process was happening behind the scene but server actually went down. When server was up, I could see all the content on the other site.
183,005
<p>My code theme archive.php is</p> <pre><code>&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', 'test' get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php semplicemente_paging_nav(); ?&gt; &lt;?php else : ?&gt; &lt;?php get_template_part( 'content', 'none' ); ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>So i want to change order from desc to acs , orderby date and post per page is 100. </p> <p>I found it.</p> <pre><code>$args = ( array( 'order' =&gt; 'ASC', 'orderby' =&gt; 'date', 'posts_per_page' =&gt; '100',) ); </code></pre> <p>So i put $args to get_post_format(), the_post() put nothing happen?</p> <p>Any idea?</p> <p>Thank for you help</p>
[ { "answer_id": 187734, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": false, "text": "<p>Please check your .htacess files there might be some issues in it. You may even try to rename it.Hope it helps I was stuck with similar issues little time ago. </p>\n" }, { "answer_id": 187739, "author": "shyammakwana.me", "author_id": 49267, "author_profile": "https://wordpress.stackexchange.com/users/49267", "pm_score": 1, "selected": false, "text": "<p>When I had developed a theme, and I was trying to automate the import process by tweaking wordpress-importer plugin. I had faced the same issue. </p>\n\n<p>When importing server processes numerous DB operations at same time, that's why it's not able to respond and it results in 500 Internal server error. </p>\n\n<h1>Try 1 :</h1>\n\n<p>To fix the issue, you have to import one by one. \nWhatever importer you are using, tweak it such that it works with AJAX and imports data with some time gap.</p>\n\n<pre><code>setTimeout( function () {\n $.ajax({\n // import one part of your data\n });\n\n}, 2000 ) ; \n</code></pre>\n\n<h1>Try 2:</h1>\n\n<p>Try setting time limit of PHP to 0. \nPut this in starting of your importer's main file.</p>\n\n<pre><code>@set_time_limit(0); \n</code></pre>\n\n<p>You are not getting fatal error, still you should to give it a try. </p>\n" }, { "answer_id": 188053, "author": "Rahul Patil", "author_id": 26151, "author_profile": "https://wordpress.stackexchange.com/users/26151", "pm_score": 3, "selected": true, "text": "<p>Sorted it out myself.</p>\n\n<p>The problem was, server was very slow to process the import. The process was happening behind the scene but server actually went down.</p>\n\n<p>When server was up, I could see all the content on the other site.</p>\n" } ]
2015/04/02
[ "https://wordpress.stackexchange.com/questions/183005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66796/" ]
My code theme archive.php is ``` <?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', 'test' get_post_format() ); ?> <?php endwhile; ?> <?php semplicemente_paging_nav(); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> ``` So i want to change order from desc to acs , orderby date and post per page is 100. I found it. ``` $args = ( array( 'order' => 'ASC', 'orderby' => 'date', 'posts_per_page' => '100',) ); ``` So i put $args to get\_post\_format(), the\_post() put nothing happen? Any idea? Thank for you help
Sorted it out myself. The problem was, server was very slow to process the import. The process was happening behind the scene but server actually went down. When server was up, I could see all the content on the other site.
183,058
<p>I'm grabbing a remote feed in my plugin and some entries have iframe code I want to keep. However, SimplePie <code>fetch_feed</code> keeps stripping it out. Here is my code and what I've tried already:</p> <pre><code>kses_remove_filters(); # remove kses filters but SimplePie strips codes anyway $rss = fetch_feed( 'http://www.someblog.com/feed/' ); $rss_items = $rss-&gt;get_items( 0, 2 ); # get two entries for this example foreach ( $rss_items as $item ) { # just dump to screen: echo "&lt;div id='message' class='updated'&gt;&lt;p&gt;" . $item-&gt;get_content() . "&lt;/p&gt;&lt;/div&gt;"; } kses_init_filters(); # remove kses filters but SimplePie strips codes anyway # also tried adding iframe to kses_allowed_html filter: function se87359_add_filter( &amp;$feed, $url ) { add_filter('wp_kses_allowed_html', 'se87359_add_allowed_tags'); } add_filter( 'wp_feed_options', 'se87359_add_filter', 10, 2 ); function se87359_add_allowed_tags($tags) { // Ensure we remove it so it doesn't run on anything else remove_filter('wp_kses_allowed_html', 'se87359_add_allowed_tags'); $tags['iframe'] = array( 'src' =&gt; true, 'width' =&gt; true, 'height' =&gt; true, 'class' =&gt; true, 'frameborder' =&gt; true, 'webkitAllowFullScreen' =&gt; true, 'mozallowfullscreen' =&gt; true, 'allowFullScreen' =&gt; true ); return $tags; } # also made sure not to cache the feed (for testing only): function do_not_cache_feeds(&amp;$feed) { $feed-&gt;enable_cache(false); } add_action( 'wp_feed_options', 'do_not_cache_feeds' ); # in case above doesn't work, set transient lifetime to 1 second: add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', 'return 1;' ) ); </code></pre>
[ { "answer_id": 301259, "author": "Cubakos", "author_id": 107648, "author_profile": "https://wordpress.stackexchange.com/users/107648", "pm_score": 1, "selected": false, "text": "<p>From the SimplePie docs <a href=\"http://simplepie.org/wiki/reference/simplepie/strip_htmltags\" rel=\"nofollow noreferrer\">here</a>: there is a <code>strip_htmltags</code> property in the SimplePie object, which among others it has the iframe tag we want to keep.</p>\n<p>So, apart from the wp_kses, probably we want to remove the tag from the above property.</p>\n<p>For instance, the <code>$rss = fetch_feed( 'http://www.someblog.com/feed/' );</code> gives us the SimplePie object.</p>\n<p>If we <code>var_dump($rss)</code></p>\n<p>or even better &quot;pretty print&quot; it by using:</p>\n<p><code>highlight_string(&quot;&lt;?php\\n\\$rss =\\n&quot; . var_export($rss, true) . &quot;;\\n?&gt;&quot;);</code></p>\n<p>we will see all fetched entries and all properties of the <code>$rss</code> object.\nAmong those there is the one we are looking for, and we can isolate it by using:</p>\n<p><code>highlight_string(&quot;&lt;?php\\n\\$rss-&gt;strip_htmltags =\\n&quot; . var_export($rss-&gt;strip_htmltags, true) . &quot;;\\n?&gt;&quot;);</code></p>\n<p>this will give us something like the below:</p>\n<pre><code>&lt;?php\n $rss-&gt;strip_htmltags =\n array (\n 0 =&gt; 'base',\n 1 =&gt; 'blink',\n 2 =&gt; 'body',\n 3 =&gt; 'doctype',\n 4 =&gt; 'embed',\n 5 =&gt; 'font',\n 6 =&gt; 'form',\n 7 =&gt; 'frame',\n 8 =&gt; 'frameset',\n 9 =&gt; 'html',\n 10 =&gt; 'iframe',\n 11 =&gt; 'input',\n 12 =&gt; 'marquee',\n 13 =&gt; 'meta',\n 14 =&gt; 'noscript',\n 15 =&gt; 'object',\n 16 =&gt; 'param',\n 17 =&gt; 'script',\n 18 =&gt; 'style',\n );\n?&gt;\n</code></pre>\n<p>From the above we note that the <code>key</code> of the iframe entry is 10. So we use array_splice to remove the entry, like:</p>\n<pre><code>// Remove these tags from the list\n$strip_htmltags = $rss-&gt;strip_htmltags; //get a copy of the strip entries array\narray_splice($strip_htmltags, 10, 1); //remove the iframe entry\n$rss-&gt;strip_htmltags = $strip_htmltags; // assign the strip entries without those we want\n</code></pre>\n<p>Now the iframe entry is out and of the <code>$strip_htmltags</code> property and probably we are set.</p>\n<p><em>Notice</em>: I couldn't find a &quot;test&quot; rss feed containing some iframe to test the above. So if anyone can verify it, please provide some feedback.</p>\n" }, { "answer_id": 410316, "author": "AndPicc", "author_id": 86235, "author_profile": "https://wordpress.stackexchange.com/users/86235", "pm_score": 0, "selected": false, "text": "<p>Just a clarification about Cubakos answer.</p>\n<p>in order to actually change the $strip_htmltags you need to use this method at the end of his code:</p>\n<pre><code>$rss-&gt;strip_htmltags($strip_htmltags);\n</code></pre>\n<p>because that method will also set the same array for the class Sanitize, which is the important one.</p>\n<p>I found this info in this answer <a href=\"https://stackoverflow.com/a/19399733/2734331\">https://stackoverflow.com/a/19399733/2734331</a></p>\n" } ]
2015/04/02
[ "https://wordpress.stackexchange.com/questions/183058", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50675/" ]
I'm grabbing a remote feed in my plugin and some entries have iframe code I want to keep. However, SimplePie `fetch_feed` keeps stripping it out. Here is my code and what I've tried already: ``` kses_remove_filters(); # remove kses filters but SimplePie strips codes anyway $rss = fetch_feed( 'http://www.someblog.com/feed/' ); $rss_items = $rss->get_items( 0, 2 ); # get two entries for this example foreach ( $rss_items as $item ) { # just dump to screen: echo "<div id='message' class='updated'><p>" . $item->get_content() . "</p></div>"; } kses_init_filters(); # remove kses filters but SimplePie strips codes anyway # also tried adding iframe to kses_allowed_html filter: function se87359_add_filter( &$feed, $url ) { add_filter('wp_kses_allowed_html', 'se87359_add_allowed_tags'); } add_filter( 'wp_feed_options', 'se87359_add_filter', 10, 2 ); function se87359_add_allowed_tags($tags) { // Ensure we remove it so it doesn't run on anything else remove_filter('wp_kses_allowed_html', 'se87359_add_allowed_tags'); $tags['iframe'] = array( 'src' => true, 'width' => true, 'height' => true, 'class' => true, 'frameborder' => true, 'webkitAllowFullScreen' => true, 'mozallowfullscreen' => true, 'allowFullScreen' => true ); return $tags; } # also made sure not to cache the feed (for testing only): function do_not_cache_feeds(&$feed) { $feed->enable_cache(false); } add_action( 'wp_feed_options', 'do_not_cache_feeds' ); # in case above doesn't work, set transient lifetime to 1 second: add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', 'return 1;' ) ); ```
From the SimplePie docs [here](http://simplepie.org/wiki/reference/simplepie/strip_htmltags): there is a `strip_htmltags` property in the SimplePie object, which among others it has the iframe tag we want to keep. So, apart from the wp\_kses, probably we want to remove the tag from the above property. For instance, the `$rss = fetch_feed( 'http://www.someblog.com/feed/' );` gives us the SimplePie object. If we `var_dump($rss)` or even better "pretty print" it by using: `highlight_string("<?php\n\$rss =\n" . var_export($rss, true) . ";\n?>");` we will see all fetched entries and all properties of the `$rss` object. Among those there is the one we are looking for, and we can isolate it by using: `highlight_string("<?php\n\$rss->strip_htmltags =\n" . var_export($rss->strip_htmltags, true) . ";\n?>");` this will give us something like the below: ``` <?php $rss->strip_htmltags = array ( 0 => 'base', 1 => 'blink', 2 => 'body', 3 => 'doctype', 4 => 'embed', 5 => 'font', 6 => 'form', 7 => 'frame', 8 => 'frameset', 9 => 'html', 10 => 'iframe', 11 => 'input', 12 => 'marquee', 13 => 'meta', 14 => 'noscript', 15 => 'object', 16 => 'param', 17 => 'script', 18 => 'style', ); ?> ``` From the above we note that the `key` of the iframe entry is 10. So we use array\_splice to remove the entry, like: ``` // Remove these tags from the list $strip_htmltags = $rss->strip_htmltags; //get a copy of the strip entries array array_splice($strip_htmltags, 10, 1); //remove the iframe entry $rss->strip_htmltags = $strip_htmltags; // assign the strip entries without those we want ``` Now the iframe entry is out and of the `$strip_htmltags` property and probably we are set. *Notice*: I couldn't find a "test" rss feed containing some iframe to test the above. So if anyone can verify it, please provide some feedback.
183,067
<p>I have a wodpress site, and I have submitted it to google webmaster tools. When I search on google by my site name, the results come, and on clicking the searched result, I can open the website on my PC. But when doing the same thing on my mobile, i get this</p> <pre><code>Error 406: Not accebtable </code></pre> <p>How can can resolve it?</p>
[ { "answer_id": 183071, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 1, "selected": false, "text": "<p>A <code>406 Not Acceptable</code> HTTP error usually indicates that the content type of your webpage is not in the <code>Accept</code> request header that your browser sent to the webserver.</p>\n\n<p>When you load a website, your browser sends a <code>Accept</code> header with the content types that it will accept, like <code>text/html</code> or <code>text/xml</code>. But when the webserver sends a format your browser doesn't accept, it will give you a 406 HTTP error.</p>\n\n<p>My guess is that a plugin or theme is changing the content type header, or your phone's browser is acting weird.</p>\n" }, { "answer_id": 220256, "author": "Jeremy", "author_id": 90303, "author_profile": "https://wordpress.stackexchange.com/users/90303", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.</p>\n\n<p>The solution is to disable the mod_security firewall within your <code>.htaccess</code> file.</p>\n\n<p>My fix was to install a plugin called \"WP Htaccess Editor\" (free WP plugin), then update the <code>.htaccess</code> file to the following, between the \"Begin WordPress\" and \"End WordPress\" tags:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 365943, "author": "RonaldPaguay", "author_id": 187489, "author_profile": "https://wordpress.stackexchange.com/users/187489", "pm_score": 0, "selected": false, "text": "<p>This happened to me while using WooCommerce API for Node JS.\nI just changed the verb put to post and it worked.</p>\n" }, { "answer_id": 371985, "author": "Carlos Bezerra", "author_id": 192383, "author_profile": "https://wordpress.stackexchange.com/users/192383", "pm_score": 0, "selected": false, "text": "<p>Here was fixed using this lines on .htaccess file (public_html)</p>\n<pre><code> &lt;IfModule mod_security.c&gt;\nSecFilterEngineOff\nSecFilterScanPOSTOff\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2015/04/02
[ "https://wordpress.stackexchange.com/questions/183067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70049/" ]
I have a wodpress site, and I have submitted it to google webmaster tools. When I search on google by my site name, the results come, and on clicking the searched result, I can open the website on my PC. But when doing the same thing on my mobile, i get this ``` Error 406: Not accebtable ``` How can can resolve it?
I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result. The solution is to disable the mod\_security firewall within your `.htaccess` file. My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` Hope this helps.
183,075
<p>So i've been trying to figure this out for awhile now. The following code does not seem to work for me. The javascript file will not be included in the footer ( or anywhere for that matter )</p> <pre><code>function add_scripts_plz(){ wp_enqueue_script( 'wowjs', get_template_directory_uri() . '/js/wow.min.js', array('jquery'), '2', true ); } add_action('wp_enqueue_scripts', 'add_scripts_plz'); </code></pre> <p>If I were to just include this in functions.php outside of the action like so:</p> <pre><code> wp_enqueue_script( 'wowjs', get_template_directory_uri() . '/js/wow.min.js', array('jquery'), '2', true ); </code></pre> <p>everything works fine, except for I get the warning message about improperly using the function and I'd like to only enqueue scripts on certain pages anyways...</p> <p>Any ideas why it's not working inside of the <code>wp_enqueue_scripts</code> function ? </p>
[ { "answer_id": 183071, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 1, "selected": false, "text": "<p>A <code>406 Not Acceptable</code> HTTP error usually indicates that the content type of your webpage is not in the <code>Accept</code> request header that your browser sent to the webserver.</p>\n\n<p>When you load a website, your browser sends a <code>Accept</code> header with the content types that it will accept, like <code>text/html</code> or <code>text/xml</code>. But when the webserver sends a format your browser doesn't accept, it will give you a 406 HTTP error.</p>\n\n<p>My guess is that a plugin or theme is changing the content type header, or your phone's browser is acting weird.</p>\n" }, { "answer_id": 220256, "author": "Jeremy", "author_id": 90303, "author_profile": "https://wordpress.stackexchange.com/users/90303", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.</p>\n\n<p>The solution is to disable the mod_security firewall within your <code>.htaccess</code> file.</p>\n\n<p>My fix was to install a plugin called \"WP Htaccess Editor\" (free WP plugin), then update the <code>.htaccess</code> file to the following, between the \"Begin WordPress\" and \"End WordPress\" tags:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 365943, "author": "RonaldPaguay", "author_id": 187489, "author_profile": "https://wordpress.stackexchange.com/users/187489", "pm_score": 0, "selected": false, "text": "<p>This happened to me while using WooCommerce API for Node JS.\nI just changed the verb put to post and it worked.</p>\n" }, { "answer_id": 371985, "author": "Carlos Bezerra", "author_id": 192383, "author_profile": "https://wordpress.stackexchange.com/users/192383", "pm_score": 0, "selected": false, "text": "<p>Here was fixed using this lines on .htaccess file (public_html)</p>\n<pre><code> &lt;IfModule mod_security.c&gt;\nSecFilterEngineOff\nSecFilterScanPOSTOff\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2015/04/02
[ "https://wordpress.stackexchange.com/questions/183075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16334/" ]
So i've been trying to figure this out for awhile now. The following code does not seem to work for me. The javascript file will not be included in the footer ( or anywhere for that matter ) ``` function add_scripts_plz(){ wp_enqueue_script( 'wowjs', get_template_directory_uri() . '/js/wow.min.js', array('jquery'), '2', true ); } add_action('wp_enqueue_scripts', 'add_scripts_plz'); ``` If I were to just include this in functions.php outside of the action like so: ``` wp_enqueue_script( 'wowjs', get_template_directory_uri() . '/js/wow.min.js', array('jquery'), '2', true ); ``` everything works fine, except for I get the warning message about improperly using the function and I'd like to only enqueue scripts on certain pages anyways... Any ideas why it's not working inside of the `wp_enqueue_scripts` function ?
I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result. The solution is to disable the mod\_security firewall within your `.htaccess` file. My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` Hope this helps.
183,114
<p>After switching from the homepage displaying latest blog posts on urls /page/1/ /page/2/ etc to a static front page with the posts displayed on /blog/page/1/ we would like to redirect the original /page/#/ to the new url /blog/page/#/</p> <p>Is there a best way to do this? Perhaps a plugin, though searching has yielded little result, or htaccess redirects? </p>
[ { "answer_id": 183071, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 1, "selected": false, "text": "<p>A <code>406 Not Acceptable</code> HTTP error usually indicates that the content type of your webpage is not in the <code>Accept</code> request header that your browser sent to the webserver.</p>\n\n<p>When you load a website, your browser sends a <code>Accept</code> header with the content types that it will accept, like <code>text/html</code> or <code>text/xml</code>. But when the webserver sends a format your browser doesn't accept, it will give you a 406 HTTP error.</p>\n\n<p>My guess is that a plugin or theme is changing the content type header, or your phone's browser is acting weird.</p>\n" }, { "answer_id": 220256, "author": "Jeremy", "author_id": 90303, "author_profile": "https://wordpress.stackexchange.com/users/90303", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.</p>\n\n<p>The solution is to disable the mod_security firewall within your <code>.htaccess</code> file.</p>\n\n<p>My fix was to install a plugin called \"WP Htaccess Editor\" (free WP plugin), then update the <code>.htaccess</code> file to the following, between the \"Begin WordPress\" and \"End WordPress\" tags:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 365943, "author": "RonaldPaguay", "author_id": 187489, "author_profile": "https://wordpress.stackexchange.com/users/187489", "pm_score": 0, "selected": false, "text": "<p>This happened to me while using WooCommerce API for Node JS.\nI just changed the verb put to post and it worked.</p>\n" }, { "answer_id": 371985, "author": "Carlos Bezerra", "author_id": 192383, "author_profile": "https://wordpress.stackexchange.com/users/192383", "pm_score": 0, "selected": false, "text": "<p>Here was fixed using this lines on .htaccess file (public_html)</p>\n<pre><code> &lt;IfModule mod_security.c&gt;\nSecFilterEngineOff\nSecFilterScanPOSTOff\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2015/04/03
[ "https://wordpress.stackexchange.com/questions/183114", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70073/" ]
After switching from the homepage displaying latest blog posts on urls /page/1/ /page/2/ etc to a static front page with the posts displayed on /blog/page/1/ we would like to redirect the original /page/#/ to the new url /blog/page/#/ Is there a best way to do this? Perhaps a plugin, though searching has yielded little result, or htaccess redirects?
I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result. The solution is to disable the mod\_security firewall within your `.htaccess` file. My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` Hope this helps.
183,154
<p>Can items have multiple permalinks?</p> <p>I am currently struggling to setup routing for a custom taxonomy that I have setup. </p> <p>I have a custom post type, say hotels.</p> <p>A standard URL for one of these posts might be /hotels/the-marriot-hotel</p> <p>But I also have a custom taxonomy, Locations.</p> <p>I want to be able to access each hotel via the standard URL and a URL that resembles a breadcrumb of the taxonomy, such as /Locations/United-Kingdom/the-marriot-hotel or even /Locations/Liverpool/the-marriot-hotel.</p> <p>I have tried getting term link and appending <code>$post-&gt;post_name</code> on the end but I just get a 404 error so its not matching the route</p> <p>Is this possible?</p> <p>I have setup my taxonomy with a rewrite and give it a slug, so I can browse hotels in Liverpool for example with the url /Locations/Liverpool. This part works fine but when a user clicks one of the posts on this page I'd like it to follow the URL scheme for that section</p> <p>Thanks</p>
[ { "answer_id": 183071, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 1, "selected": false, "text": "<p>A <code>406 Not Acceptable</code> HTTP error usually indicates that the content type of your webpage is not in the <code>Accept</code> request header that your browser sent to the webserver.</p>\n\n<p>When you load a website, your browser sends a <code>Accept</code> header with the content types that it will accept, like <code>text/html</code> or <code>text/xml</code>. But when the webserver sends a format your browser doesn't accept, it will give you a 406 HTTP error.</p>\n\n<p>My guess is that a plugin or theme is changing the content type header, or your phone's browser is acting weird.</p>\n" }, { "answer_id": 220256, "author": "Jeremy", "author_id": 90303, "author_profile": "https://wordpress.stackexchange.com/users/90303", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.</p>\n\n<p>The solution is to disable the mod_security firewall within your <code>.htaccess</code> file.</p>\n\n<p>My fix was to install a plugin called \"WP Htaccess Editor\" (free WP plugin), then update the <code>.htaccess</code> file to the following, between the \"Begin WordPress\" and \"End WordPress\" tags:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 365943, "author": "RonaldPaguay", "author_id": 187489, "author_profile": "https://wordpress.stackexchange.com/users/187489", "pm_score": 0, "selected": false, "text": "<p>This happened to me while using WooCommerce API for Node JS.\nI just changed the verb put to post and it worked.</p>\n" }, { "answer_id": 371985, "author": "Carlos Bezerra", "author_id": 192383, "author_profile": "https://wordpress.stackexchange.com/users/192383", "pm_score": 0, "selected": false, "text": "<p>Here was fixed using this lines on .htaccess file (public_html)</p>\n<pre><code> &lt;IfModule mod_security.c&gt;\nSecFilterEngineOff\nSecFilterScanPOSTOff\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2015/04/03
[ "https://wordpress.stackexchange.com/questions/183154", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70099/" ]
Can items have multiple permalinks? I am currently struggling to setup routing for a custom taxonomy that I have setup. I have a custom post type, say hotels. A standard URL for one of these posts might be /hotels/the-marriot-hotel But I also have a custom taxonomy, Locations. I want to be able to access each hotel via the standard URL and a URL that resembles a breadcrumb of the taxonomy, such as /Locations/United-Kingdom/the-marriot-hotel or even /Locations/Liverpool/the-marriot-hotel. I have tried getting term link and appending `$post->post_name` on the end but I just get a 404 error so its not matching the route Is this possible? I have setup my taxonomy with a rewrite and give it a slug, so I can browse hotels in Liverpool for example with the url /Locations/Liverpool. This part works fine but when a user clicks one of the posts on this page I'd like it to follow the URL scheme for that section Thanks
I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result. The solution is to disable the mod\_security firewall within your `.htaccess` file. My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` Hope this helps.
183,178
<p>I think I'm missing a step here, but for the life of me I can't see it. I'm trying to display a simple list of users who all have the same role and have the same meta data value for a certain key - namely, teachers associated with a school. </p> <p>Here is my code: </p> <pre><code> &lt;div class="teachers-list"&gt; &lt;h3&gt;Your School's Teachers&lt;/h3&gt; &lt;ul&gt; &lt;?php $champion_user = wp_get_current_user(); $school = $champion_user-&gt;school; // echo $school just to test it's right.... ?&gt; Your school: &lt;?php echo $school; ?&gt; &lt;?php $args = array( 'role' =&gt; 'subscriber', 'meta_key' =&gt; 'school', 'meta_value' =&gt; $school ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query-&gt;results ) ) { foreach ( $user_query-&gt;results as $user ) { echo '&lt;li&gt;' . $user-&gt;display_name . '&lt;/li&gt;'; } } else { echo '&lt;li&gt;No teachers found.&lt;/li&gt;'; } ?&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>The school variable echoes properly, but then in the WP_User_Query I only get the "no teachers found" result. If I comment out the meta_key and meta_value fields, I get a list of subscribers, so that far works. If I manually code in the meta_value I'm looking for - in this case, "school_one", it still returns "no teachers found". I checked the usermeta table in the db and all the users have the school meta key and the proper school values there, so... I'm stumped. </p> <p>I've read and re-read the codex for both WP_User_Query() and get_user_meta(), and written this out both with the pre-WP 3.7 syntax and now the current syntax, but clearly I've missed the main point to get this working. Do I need to reset the query somehow? Do I need the "compare" argument too? Am I using the $school variable improperly in the arguments? I've tried so many methods I'm not sure what's left. </p> <p>Any help is greatly appreciated. Thank you in advance for reading. </p>
[ { "answer_id": 183071, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 1, "selected": false, "text": "<p>A <code>406 Not Acceptable</code> HTTP error usually indicates that the content type of your webpage is not in the <code>Accept</code> request header that your browser sent to the webserver.</p>\n\n<p>When you load a website, your browser sends a <code>Accept</code> header with the content types that it will accept, like <code>text/html</code> or <code>text/xml</code>. But when the webserver sends a format your browser doesn't accept, it will give you a 406 HTTP error.</p>\n\n<p>My guess is that a plugin or theme is changing the content type header, or your phone's browser is acting weird.</p>\n" }, { "answer_id": 220256, "author": "Jeremy", "author_id": 90303, "author_profile": "https://wordpress.stackexchange.com/users/90303", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.</p>\n\n<p>The solution is to disable the mod_security firewall within your <code>.htaccess</code> file.</p>\n\n<p>My fix was to install a plugin called \"WP Htaccess Editor\" (free WP plugin), then update the <code>.htaccess</code> file to the following, between the \"Begin WordPress\" and \"End WordPress\" tags:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 365943, "author": "RonaldPaguay", "author_id": 187489, "author_profile": "https://wordpress.stackexchange.com/users/187489", "pm_score": 0, "selected": false, "text": "<p>This happened to me while using WooCommerce API for Node JS.\nI just changed the verb put to post and it worked.</p>\n" }, { "answer_id": 371985, "author": "Carlos Bezerra", "author_id": 192383, "author_profile": "https://wordpress.stackexchange.com/users/192383", "pm_score": 0, "selected": false, "text": "<p>Here was fixed using this lines on .htaccess file (public_html)</p>\n<pre><code> &lt;IfModule mod_security.c&gt;\nSecFilterEngineOff\nSecFilterScanPOSTOff\n&lt;/IfModule&gt;\n</code></pre>\n" } ]
2015/04/03
[ "https://wordpress.stackexchange.com/questions/183178", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70112/" ]
I think I'm missing a step here, but for the life of me I can't see it. I'm trying to display a simple list of users who all have the same role and have the same meta data value for a certain key - namely, teachers associated with a school. Here is my code: ``` <div class="teachers-list"> <h3>Your School's Teachers</h3> <ul> <?php $champion_user = wp_get_current_user(); $school = $champion_user->school; // echo $school just to test it's right.... ?> Your school: <?php echo $school; ?> <?php $args = array( 'role' => 'subscriber', 'meta_key' => 'school', 'meta_value' => $school ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query->results ) ) { foreach ( $user_query->results as $user ) { echo '<li>' . $user->display_name . '</li>'; } } else { echo '<li>No teachers found.</li>'; } ?> </ul> </div> ``` The school variable echoes properly, but then in the WP\_User\_Query I only get the "no teachers found" result. If I comment out the meta\_key and meta\_value fields, I get a list of subscribers, so that far works. If I manually code in the meta\_value I'm looking for - in this case, "school\_one", it still returns "no teachers found". I checked the usermeta table in the db and all the users have the school meta key and the proper school values there, so... I'm stumped. I've read and re-read the codex for both WP\_User\_Query() and get\_user\_meta(), and written this out both with the pre-WP 3.7 syntax and now the current syntax, but clearly I've missed the main point to get this working. Do I need to reset the query somehow? Do I need the "compare" argument too? Am I using the $school variable improperly in the arguments? I've tried so many methods I'm not sure what's left. Any help is greatly appreciated. Thank you in advance for reading.
I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result. The solution is to disable the mod\_security firewall within your `.htaccess` file. My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` Hope this helps.
183,182
<p>First of all, I know it's a duplicate, but none of the older answers were helpful.</p> <p>I'm searching in posts through <code>post_meta</code>. Here's my code, which currently returns nothing.</p> <pre><code>$args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'post', 'meta_query' =&gt; array( array( 'key' =&gt; 'system_power_supply', 'value' =&gt; array('single', 'redundant'), 'compare' =&gt; 'IN', ) ) ); $query = new WP_Query($args); echo $query-&gt;found_posts; </code></pre> <p>If I remove <code>meta_query</code> it works. I'm sure of these things:</p> <ul> <li>There's no spelling mistake in the <code>key</code> or the <code>value</code>.</li> <li>post type is <code>post</code></li> <li>There <strong>is</strong> a post with the value 'single' in 'system_power_supply'. However, post fields are generated by <a href="http://advancedcustomfields.com" rel="noreferrer">Advanced Custom Fields</a>.</li> </ul>
[ { "answer_id": 183188, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 5, "selected": true, "text": "<p>There's no easy way to search serialized values in a meta query. If the list of values isn't crazy long, potentially you could set up multiple meta queries:</p>\n\n<pre><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'system_power_supply',\n 'value' =&gt; 'single',\n 'compare' =&gt; 'LIKE',\n ),\n array(\n 'key' =&gt; 'system_power_supply',\n 'value' =&gt; 'redundant',\n 'compare' =&gt; 'LIKE',\n )\n)\n</code></pre>\n\n<p>Or if you wanted to get super fancy, you could set it up dynamically:</p>\n\n<pre><code>$values_to_search = array('single', 'redundant');\n$meta_query = array('relation' =&gt; 'OR');\nforeach ($values_to_search as $value) {\n $meta_query[] = array(\n 'key' =&gt; 'system_power_supply',\n 'value' =&gt; $value,\n 'compare' =&gt; 'LIKE',\n );\n}\n</code></pre>\n" }, { "answer_id": 289198, "author": "Badr", "author_id": 121783, "author_profile": "https://wordpress.stackexchange.com/users/121783", "pm_score": 3, "selected": false, "text": "<p>I know it's been a long time, but just in case someone has the same issue. Well i've been pulling my hair for hours before i found the issue: 'meta_query' with 'IN' comparison operator doesn't seem to accept the usual array. instead, you need to join it first with ', '.</p>\n\n<p>So, in your case, something like this should work : </p>\n\n<pre><code>$args = array(\n'posts_per_page' =&gt; -1,\n'post_type' =&gt; 'post',\n'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'system_power_supply',\n 'value' =&gt; join(', ', array('single', 'redundant')),\n 'compare' =&gt; 'IN',\n )\n)\n);\n$query = new WP_Query($args);\necho $query-&gt;found_posts;\n</code></pre>\n" } ]
2015/04/03
[ "https://wordpress.stackexchange.com/questions/183182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56815/" ]
First of all, I know it's a duplicate, but none of the older answers were helpful. I'm searching in posts through `post_meta`. Here's my code, which currently returns nothing. ``` $args = array( 'numberposts' => -1, 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'system_power_supply', 'value' => array('single', 'redundant'), 'compare' => 'IN', ) ) ); $query = new WP_Query($args); echo $query->found_posts; ``` If I remove `meta_query` it works. I'm sure of these things: * There's no spelling mistake in the `key` or the `value`. * post type is `post` * There **is** a post with the value 'single' in 'system\_power\_supply'. However, post fields are generated by [Advanced Custom Fields](http://advancedcustomfields.com).
There's no easy way to search serialized values in a meta query. If the list of values isn't crazy long, potentially you could set up multiple meta queries: ``` 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'system_power_supply', 'value' => 'single', 'compare' => 'LIKE', ), array( 'key' => 'system_power_supply', 'value' => 'redundant', 'compare' => 'LIKE', ) ) ``` Or if you wanted to get super fancy, you could set it up dynamically: ``` $values_to_search = array('single', 'redundant'); $meta_query = array('relation' => 'OR'); foreach ($values_to_search as $value) { $meta_query[] = array( 'key' => 'system_power_supply', 'value' => $value, 'compare' => 'LIKE', ); } ```
183,196
<p>I am trying to get the value of the 'new-post-slug' (the bit that you can edit to customize your slug for a post, but bizarrely doesn't have a 'name' attribute as you'd expect a form field to have ... the update must be done in ajax in the background)</p> <p>What I am stuck on is 2 things:</p> <ul> <li><p>Why do posts not get their post_name (slug) updated on saving a draft? (not autosaving, I mean hitting the 'Save Draft' button)</p></li> <li><p>If I was to try and do this manually (using the <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/save_post" rel="nofollow">save_post</a> hook), how can I get the value of the 'new-post-slug' (since this field is not available in the $_POST var). I guess I could try and do a pre-form-submit jQuery append-to-form type thing which gets this field .</p></li> </ul> <p>When using the <code>wp_handle_upload_prefilter</code> to catch the filename before it gets uploaded, the post_name (the slug) is not set:</p> <pre><code>add_filter('wp_generate_attachment_metadata', 'check_images_file_to_slug', 10, 2); public function check_images_file_to_slug($image_info) { // Get the parent post ID, if there is one if( isset($_GET['post_id']) ) { $post_id = $_GET['post_id']; } elseif( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; } // Only do this if we got the post ID--otherwise they're probably in // the media section rather than uploading an image from a post. if(is_numeric($post_id)) { /* @var @post WP_Post */ $post = get_post($post_id); // Here $post-&gt;post_name (the slug), is empty for post-new.php (Adding new post) } } </code></pre>
[ { "answer_id": 185077, "author": "user28206", "author_id": 28206, "author_profile": "https://wordpress.stackexchange.com/users/28206", "pm_score": -1, "selected": false, "text": "<p>When a new post is created (regardless of status) <code>post_name</code> which is the slug is saved to the WP_Post object.</p>\n\n<p>You can fire off a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\"><code>wp_ajax_$youraction()</code></a> in the backend to get the post object and return the slug.</p>\n" }, { "answer_id": 331448, "author": "Kevin", "author_id": 197, "author_profile": "https://wordpress.stackexchange.com/users/197", "pm_score": 1, "selected": false, "text": "<p>I run into a similar issue. I had to remove <code>remove_meta_box('slugdiv', ['post', 'page'], 'normal');</code> from my code. When you remove the <em>slugdiv</em> meta box the slug edit box for WP does stops working.</p>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183196", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51271/" ]
I am trying to get the value of the 'new-post-slug' (the bit that you can edit to customize your slug for a post, but bizarrely doesn't have a 'name' attribute as you'd expect a form field to have ... the update must be done in ajax in the background) What I am stuck on is 2 things: * Why do posts not get their post\_name (slug) updated on saving a draft? (not autosaving, I mean hitting the 'Save Draft' button) * If I was to try and do this manually (using the [save\_post](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) hook), how can I get the value of the 'new-post-slug' (since this field is not available in the $\_POST var). I guess I could try and do a pre-form-submit jQuery append-to-form type thing which gets this field . When using the `wp_handle_upload_prefilter` to catch the filename before it gets uploaded, the post\_name (the slug) is not set: ``` add_filter('wp_generate_attachment_metadata', 'check_images_file_to_slug', 10, 2); public function check_images_file_to_slug($image_info) { // Get the parent post ID, if there is one if( isset($_GET['post_id']) ) { $post_id = $_GET['post_id']; } elseif( isset($_POST['post_id']) ) { $post_id = $_POST['post_id']; } // Only do this if we got the post ID--otherwise they're probably in // the media section rather than uploading an image from a post. if(is_numeric($post_id)) { /* @var @post WP_Post */ $post = get_post($post_id); // Here $post->post_name (the slug), is empty for post-new.php (Adding new post) } } ```
I run into a similar issue. I had to remove `remove_meta_box('slugdiv', ['post', 'page'], 'normal');` from my code. When you remove the *slugdiv* meta box the slug edit box for WP does stops working.
183,197
<p>I have a 'single' page for individual workshop events and i'm tying to create an 'add to calendar' functionality. Right now i have a link setup, which passes the current post ID in a query string to the PHP file that generates the iCal file. I'm pretty sure I should be able to generate such a file from a wp_query, but i know my code is probably grotesquely incorrect. I've been working on this all day and can't seem to make any other post i've found on the matter work. Any help would really be appreciated. I'm semi-new to wordpress so be gentle! </p> <p>Here's the file: </p> <pre><code>//allow access to the wp_query method: $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-blog-header.php' ); //get the post ID from the incoming query string: $workshop_id = @$_GET['workshop_id']; $args = array( 'p' =&gt; $workshop_id, 'post_type' =&gt; 'any'); $the_query = new WP_Query($args); // The Loop if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $workshop = array( 'workshop_title' =&gt; get_field('workshop'); ); header("Content-Type: text/Calendar"); header("Content-Disposition: inline; filename=calendar.ics"); echo "BEGIN:VCALENDAR\n"; echo "VERSION:2.0\n"; echo "PRODID:-//Foobar Corporation//NONSGML Foobar//EN\n"; echo "METHOD:REQUEST\n"; // requied by Outlook echo "BEGIN:VEVENT\n"; echo "UID:".date('Ymd').'T'.date('His')."-".rand()."-example.com\n"; // required by Outlok echo "DTSTAMP:".date('Ymd').'T'.date('His')."\n"; // required by Outlook echo "DTSTART:20080413T000000\n"; // echo "SUMMARY:{$workshop['workshop_title']}\n"; echo "DESCRIPTION: this is just a test\n"; echo "END:VEVENT\n"; echo "END:VCALENDAR\n"; endwhile; endif; ?&gt; </code></pre>
[ { "answer_id": 185077, "author": "user28206", "author_id": 28206, "author_profile": "https://wordpress.stackexchange.com/users/28206", "pm_score": -1, "selected": false, "text": "<p>When a new post is created (regardless of status) <code>post_name</code> which is the slug is saved to the WP_Post object.</p>\n\n<p>You can fire off a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\"><code>wp_ajax_$youraction()</code></a> in the backend to get the post object and return the slug.</p>\n" }, { "answer_id": 331448, "author": "Kevin", "author_id": 197, "author_profile": "https://wordpress.stackexchange.com/users/197", "pm_score": 1, "selected": false, "text": "<p>I run into a similar issue. I had to remove <code>remove_meta_box('slugdiv', ['post', 'page'], 'normal');</code> from my code. When you remove the <em>slugdiv</em> meta box the slug edit box for WP does stops working.</p>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183197", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70117/" ]
I have a 'single' page for individual workshop events and i'm tying to create an 'add to calendar' functionality. Right now i have a link setup, which passes the current post ID in a query string to the PHP file that generates the iCal file. I'm pretty sure I should be able to generate such a file from a wp\_query, but i know my code is probably grotesquely incorrect. I've been working on this all day and can't seem to make any other post i've found on the matter work. Any help would really be appreciated. I'm semi-new to wordpress so be gentle! Here's the file: ``` //allow access to the wp_query method: $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-blog-header.php' ); //get the post ID from the incoming query string: $workshop_id = @$_GET['workshop_id']; $args = array( 'p' => $workshop_id, 'post_type' => 'any'); $the_query = new WP_Query($args); // The Loop if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); $workshop = array( 'workshop_title' => get_field('workshop'); ); header("Content-Type: text/Calendar"); header("Content-Disposition: inline; filename=calendar.ics"); echo "BEGIN:VCALENDAR\n"; echo "VERSION:2.0\n"; echo "PRODID:-//Foobar Corporation//NONSGML Foobar//EN\n"; echo "METHOD:REQUEST\n"; // requied by Outlook echo "BEGIN:VEVENT\n"; echo "UID:".date('Ymd').'T'.date('His')."-".rand()."-example.com\n"; // required by Outlok echo "DTSTAMP:".date('Ymd').'T'.date('His')."\n"; // required by Outlook echo "DTSTART:20080413T000000\n"; // echo "SUMMARY:{$workshop['workshop_title']}\n"; echo "DESCRIPTION: this is just a test\n"; echo "END:VEVENT\n"; echo "END:VCALENDAR\n"; endwhile; endif; ?> ```
I run into a similar issue. I had to remove `remove_meta_box('slugdiv', ['post', 'page'], 'normal');` from my code. When you remove the *slugdiv* meta box the slug edit box for WP does stops working.
183,227
<p>I'm building a Wordpress site in which an admin can upload a video file from post metabox. </p> <p>After that post is saved and the video file is attached to the post, I used ffmpeg to get the screenshot at the first second of video, then save this screenshot as a JPG file in 'tmp' directory in theme directory.</p> <p>Finally, I want to programmatically make this screenshot as post featured image. I use media_sideload_image function, which generally be used to get image from another server and set that image as post featured image and I think this function could be used in this case also.</p> <p>In my case, the video screenshot was successfully saved to 'tmp' directory in my theme dir, but the media_sideload_image part did not return anything for further process. Here's my function:</p> <pre><code>function create_video_featured_image($post_id, $image_uri) { // $image_uri = 'http://localhost/demo-site/wp-content/themes/mytheme/tmp/video_thumb_952.jpg'; $media = media_sideload_image($image_uri, $post_id); if(!empty($media) &amp;&amp; !is_wp_error($media)){ $args = array( 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; -1, 'post_status' =&gt; 'any', 'post_parent' =&gt; $post_id ); // reference new image to set as featured $attachments = get_posts($args); if(isset($attachments) &amp;&amp; is_array($attachments)){ foreach($attachments as $attachment){ // grab source of full size images (so no 300x150 nonsense in path) $image = wp_get_attachment_image_src($attachment-&gt;ID, 'full'); // determine if in the $media image we created, the string of the URL exists if(strpos($media, $image[0]) !== false){ // if so, we found our image. set it as thumbnail set_post_thumbnail($post_id, $attachment-&gt;ID); // only want one image break; } } } } } </code></pre> <p>Am I missing anything or is there another way to work around in this case ?</p> <p>Thank you very much !</p>
[ { "answer_id": 185077, "author": "user28206", "author_id": 28206, "author_profile": "https://wordpress.stackexchange.com/users/28206", "pm_score": -1, "selected": false, "text": "<p>When a new post is created (regardless of status) <code>post_name</code> which is the slug is saved to the WP_Post object.</p>\n\n<p>You can fire off a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow\"><code>wp_ajax_$youraction()</code></a> in the backend to get the post object and return the slug.</p>\n" }, { "answer_id": 331448, "author": "Kevin", "author_id": 197, "author_profile": "https://wordpress.stackexchange.com/users/197", "pm_score": 1, "selected": false, "text": "<p>I run into a similar issue. I had to remove <code>remove_meta_box('slugdiv', ['post', 'page'], 'normal');</code> from my code. When you remove the <em>slugdiv</em> meta box the slug edit box for WP does stops working.</p>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70137/" ]
I'm building a Wordpress site in which an admin can upload a video file from post metabox. After that post is saved and the video file is attached to the post, I used ffmpeg to get the screenshot at the first second of video, then save this screenshot as a JPG file in 'tmp' directory in theme directory. Finally, I want to programmatically make this screenshot as post featured image. I use media\_sideload\_image function, which generally be used to get image from another server and set that image as post featured image and I think this function could be used in this case also. In my case, the video screenshot was successfully saved to 'tmp' directory in my theme dir, but the media\_sideload\_image part did not return anything for further process. Here's my function: ``` function create_video_featured_image($post_id, $image_uri) { // $image_uri = 'http://localhost/demo-site/wp-content/themes/mytheme/tmp/video_thumb_952.jpg'; $media = media_sideload_image($image_uri, $post_id); if(!empty($media) && !is_wp_error($media)){ $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => $post_id ); // reference new image to set as featured $attachments = get_posts($args); if(isset($attachments) && is_array($attachments)){ foreach($attachments as $attachment){ // grab source of full size images (so no 300x150 nonsense in path) $image = wp_get_attachment_image_src($attachment->ID, 'full'); // determine if in the $media image we created, the string of the URL exists if(strpos($media, $image[0]) !== false){ // if so, we found our image. set it as thumbnail set_post_thumbnail($post_id, $attachment->ID); // only want one image break; } } } } } ``` Am I missing anything or is there another way to work around in this case ? Thank you very much !
I run into a similar issue. I had to remove `remove_meta_box('slugdiv', ['post', 'page'], 'normal');` from my code. When you remove the *slugdiv* meta box the slug edit box for WP does stops working.
183,240
<p>I use this code to create the dropdown and then save the dropdown chosen values:</p> <pre><code>&lt;?php // Display Fields add_action( 'show_user_profile', 'add_multiple_choice_dropdown ' ); add_action( 'edit_user_profile', 'add_multiple_choice_dropdown ' ); function add_multiple_choice_dropdown ( $user ) { ?&gt; &lt;h3&gt;Extra profile information&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="multi_dropdown"&gt;The dropdown with multiple choices&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;?php //get dropdown saved value $selected = esc_attr(get_user_meta( $user-&gt;ID, 'multi_dropdown', true )); ?&gt; &lt;select name="multi_dropdown" id="multi_dropdown" multiple&gt; &lt;option value="first_choice" &lt;?php echo ($selected == "first_choice")? 'selected="selected"' : '' ?&gt;&gt;First Choice&lt;/option&gt; &lt;option value="second_choice" &lt;?php echo ($selected == "second_choice")? 'selected="selected"' : '' ?&gt;&gt;Second Choice&lt;/option&gt; &lt;option value="third_choice" &lt;?php echo ($selected == "third_choice")? 'selected="selected"' : '' ?&gt;&gt;Third Choice&lt;/option&gt; &lt;/select&gt; &lt;p class="description"&gt;Choose from the options above.&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } // Save fields add_action( 'personal_options_update', 'save_multiple_choices' ); add_action( 'edit_user_profile_update', 'save_multiple_choices' ); function save_multiple_choices( $user_id ) { if ( isset( $_POST['multi_dropdown'] ) ) { update_user_meta( $user_id, 'multi_dropdown', $_POST['multi_dropdown'] ); } ?&gt; </code></pre> <p>But of course, it doesn't save but one value, because I guess I have to save the selected values of the dropdown in an array. But I don't know how to do this.</p> <p>Can someone please share the knowledge?</p>
[ { "answer_id": 183334, "author": "Mike", "author_id": 69112, "author_profile": "https://wordpress.stackexchange.com/users/69112", "pm_score": 2, "selected": true, "text": "<p>You will need an opening select tag that tells PHP it is an array. Something along the lines of the following should get you on your way...</p>\n\n<pre><code>&lt;?php\n// Display Fields \nadd_action( 'show_user_profile', 'add_multiple_choice_dropdown ' );\nadd_action( 'edit_user_profile', 'add_multiple_choice_dropdown ' );\n\nfunction add_multiple_choice_dropdown ( $user ) {\n $current_selections = get_user_meta( $user-&gt;ID, 'multi_dropdown', true );\n?&gt;\n\n&lt;h3&gt;Extra profile information&lt;/h3&gt;\n\n&lt;table class=\"form-table\"&gt; \n&lt;tr&gt;\n&lt;th&gt;&lt;label for=\"multi_dropdown\" multiple=\"multiple\"&gt;The dropdown with multiple choices&lt;/label&gt;&lt;/th&gt;\n&lt;td&gt;\n&lt;select name=\"multi_dropdown[]\"&gt;\n &lt;option value=\"first_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'first_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;First Choice&lt;/option&gt;\n &lt;option value=\"second_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'second_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;Second Choice&lt;/option&gt;\n &lt;option value=\"third_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'second_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;Third Choice&lt;/option&gt;\n&lt;/select&gt;\n&lt;p class=\"description\"&gt;Choose from the options above.&lt;/p&gt;\n&lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n\n&lt;?php\n}\n\n// Save fields\nadd_action( 'personal_options_update', 'save_multiple_choices' );\nadd_action( 'edit_user_profile_update', 'save_multiple_choices' );\n\nfunction save_multiple_choices( $user_id ) {\n if ( isset( $_POST['multi_dropdown'] ) ) {\n update_user_meta( $user_id, 'multi_dropdown', $_POST['multi_dropdown'] );\n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 300289, "author": "contempoinc", "author_id": 51369, "author_profile": "https://wordpress.stackexchange.com/users/51369", "pm_score": 0, "selected": false, "text": "<p>Modified code from the above answer so it will properly show the multiple selections made when viewing the users profile, as well as added the \"multiple\" attribute to the select itself.</p>\n\n<pre><code>&lt;?php\n// Display Fields \nadd_action( 'show_user_profile', 'add_multiple_choice_dropdown ' );\nadd_action( 'edit_user_profile', 'add_multiple_choice_dropdown ' );\n\n$current_selections = get_user_meta( $user-&gt;ID, 'multi_dropdown', true );\n?&gt;\n\n&lt;h3&gt;Extra profile information&lt;/h3&gt;\n\n&lt;table class=\"form-table\"&gt; \n&lt;tr&gt;\n &lt;th&gt;&lt;label for=\"multi_dropdown\"&gt;The dropdown with multiple choices&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;select name=\"multi_dropdown[]\" multiple&gt;\n &lt;option value=\"first_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'first_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;First Choice&lt;/option&gt;\n &lt;option value=\"second_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'second_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;Second Choice&lt;/option&gt;\n &lt;option value=\"third_choice\" &lt;?php echo ( !empty( $current_selections ) &amp;&amp; in_array( 'second_choice', $current_selections ) ? ' selected=\"selected\"' : '' ) ?&gt;&gt;Third Choice&lt;/option&gt;\n &lt;/select&gt;\n &lt;p class=\"description\"&gt;Choose from the options above.&lt;/p&gt;\n &lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n\n&lt;?php\n}\n\n// Save fields\nadd_action( 'personal_options_update', 'save_multiple_choices' );\nadd_action( 'edit_user_profile_update', 'save_multiple_choices' );\n\nfunction save_multiple_choices( $user_id ) {\n if ( isset( $_POST['multi_dropdown'] ) ) {\n update_user_meta( $user_id, 'multi_dropdown', $_POST['multi_dropdown'] );\n }\n}\n?&gt;\n</code></pre>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70145/" ]
I use this code to create the dropdown and then save the dropdown chosen values: ``` <?php // Display Fields add_action( 'show_user_profile', 'add_multiple_choice_dropdown ' ); add_action( 'edit_user_profile', 'add_multiple_choice_dropdown ' ); function add_multiple_choice_dropdown ( $user ) { ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="multi_dropdown">The dropdown with multiple choices</label></th> <td> <?php //get dropdown saved value $selected = esc_attr(get_user_meta( $user->ID, 'multi_dropdown', true )); ?> <select name="multi_dropdown" id="multi_dropdown" multiple> <option value="first_choice" <?php echo ($selected == "first_choice")? 'selected="selected"' : '' ?>>First Choice</option> <option value="second_choice" <?php echo ($selected == "second_choice")? 'selected="selected"' : '' ?>>Second Choice</option> <option value="third_choice" <?php echo ($selected == "third_choice")? 'selected="selected"' : '' ?>>Third Choice</option> </select> <p class="description">Choose from the options above.</p> </td> </tr> </table> <?php } // Save fields add_action( 'personal_options_update', 'save_multiple_choices' ); add_action( 'edit_user_profile_update', 'save_multiple_choices' ); function save_multiple_choices( $user_id ) { if ( isset( $_POST['multi_dropdown'] ) ) { update_user_meta( $user_id, 'multi_dropdown', $_POST['multi_dropdown'] ); } ?> ``` But of course, it doesn't save but one value, because I guess I have to save the selected values of the dropdown in an array. But I don't know how to do this. Can someone please share the knowledge?
You will need an opening select tag that tells PHP it is an array. Something along the lines of the following should get you on your way... ``` <?php // Display Fields add_action( 'show_user_profile', 'add_multiple_choice_dropdown ' ); add_action( 'edit_user_profile', 'add_multiple_choice_dropdown ' ); function add_multiple_choice_dropdown ( $user ) { $current_selections = get_user_meta( $user->ID, 'multi_dropdown', true ); ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="multi_dropdown" multiple="multiple">The dropdown with multiple choices</label></th> <td> <select name="multi_dropdown[]"> <option value="first_choice" <?php echo ( !empty( $current_selections ) && in_array( 'first_choice', $current_selections ) ? ' selected="selected"' : '' ) ?>>First Choice</option> <option value="second_choice" <?php echo ( !empty( $current_selections ) && in_array( 'second_choice', $current_selections ) ? ' selected="selected"' : '' ) ?>>Second Choice</option> <option value="third_choice" <?php echo ( !empty( $current_selections ) && in_array( 'second_choice', $current_selections ) ? ' selected="selected"' : '' ) ?>>Third Choice</option> </select> <p class="description">Choose from the options above.</p> </td> </tr> </table> <?php } // Save fields add_action( 'personal_options_update', 'save_multiple_choices' ); add_action( 'edit_user_profile_update', 'save_multiple_choices' ); function save_multiple_choices( $user_id ) { if ( isset( $_POST['multi_dropdown'] ) ) { update_user_meta( $user_id, 'multi_dropdown', $_POST['multi_dropdown'] ); } } ?> ```
183,248
<p>I am currently in the middle of developing the front page for a online store. I am trying to resize the width of the image to expand it across the full width of the page, however the image will not expand any further than 960px I need to expand it 1440px. I have tried using both the CSS and HTML to correct this but I am finding no luck. As well as that I looked within the Wordpress media library to see if I checked the right box when uploading so that it is the full size, I am short on ideas and am clueless on what to do now.</p> <p><img src="https://i.stack.imgur.com/gZ6hi.png" alt="This is my CSS for the Image"></p> <p><img src="https://i.stack.imgur.com/5KGIP.png" alt="This is all my HTML, I have tried resizing it using styling within the HTML"></p> <p><a href="https://i.stack.imgur.com/1RmZO.png" rel="nofollow noreferrer">This is what I mean by the image not expanding to the full width of the page. </a></p>
[ { "answer_id": 183281, "author": "Jay", "author_id": 70162, "author_profile": "https://wordpress.stackexchange.com/users/70162", "pm_score": -1, "selected": false, "text": "<p>Did you try <code>width:100%;</code> in your css?</p>\n" }, { "answer_id": 183303, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>The maximum width of an image displayed in content is not just determined by the image sizes you set or CSS settings, it is also determined by the content width set in functions.php through code similar to the following</p>\n\n<pre><code>if ( ! isset( $content_width ) ) {\n $content_width = 960;\n}\n</code></pre>\n\n<p>You need to set this to your required size as well in order for the image to display correctly with this bigger image width. Without setting that accordingly, even if you set your image sizes correctly, the biggest an image will be in the content area will be 960 px as in example.</p>\n\n<p>You also need to remember, images can be up-scaled, so any image smaller than your new size will only be as wide as its original size</p>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183248", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70150/" ]
I am currently in the middle of developing the front page for a online store. I am trying to resize the width of the image to expand it across the full width of the page, however the image will not expand any further than 960px I need to expand it 1440px. I have tried using both the CSS and HTML to correct this but I am finding no luck. As well as that I looked within the Wordpress media library to see if I checked the right box when uploading so that it is the full size, I am short on ideas and am clueless on what to do now. ![This is my CSS for the Image](https://i.stack.imgur.com/gZ6hi.png) ![This is all my HTML, I have tried resizing it using styling within the HTML](https://i.stack.imgur.com/5KGIP.png) [This is what I mean by the image not expanding to the full width of the page.](https://i.stack.imgur.com/1RmZO.png)
The maximum width of an image displayed in content is not just determined by the image sizes you set or CSS settings, it is also determined by the content width set in functions.php through code similar to the following ``` if ( ! isset( $content_width ) ) { $content_width = 960; } ``` You need to set this to your required size as well in order for the image to display correctly with this bigger image width. Without setting that accordingly, even if you set your image sizes correctly, the biggest an image will be in the content area will be 960 px as in example. You also need to remember, images can be up-scaled, so any image smaller than your new size will only be as wide as its original size