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
174,175
<p>I have this :</p> <pre><code> &lt;?php the_posts_pagination( array( 'prev_text' =&gt; __( 'Previous page', 'twentyfifteen' ), 'next_text' =&gt; __( 'Next page', 'twentyfifteen' ), ) ); ?&gt; </code></pre> <p>Which gives this output : </p> <p><img src="https://i.stack.imgur.com/ZEaZV.png" alt="enter image description here"></p> <p>What I want is this : </p> <p><img src="https://i.stack.imgur.com/ZHeaV.png" alt="enter image description here"></p> <p>How to do this using the_posts_pagination() please ?</p>
[ { "answer_id": 174176, "author": "Rich", "author_id": 27716, "author_profile": "https://wordpress.stackexchange.com/users/27716", "pm_score": 3, "selected": true, "text": "<p>Do this to output only links for previous and next pages:</p>\n\n<pre><code>&lt;?php previous_posts_link ( 'Previous' ) ?&gt;\n&lt;?php next_posts_link ( 'Next' ); ?&gt;\n</code></pre>\n\n<p>Then add filters to your functions.php to add a class to each link:</p>\n\n<pre><code>function next_posts_link_css ( $content ) {\n return 'class=\"next\"';\n}\nadd_filter( 'next_posts_link_attributes', 'next_posts_link_css' );\n\nfunction previous_posts_link_css ( $content ) {\n return 'class=\"prev\"';\n}\nadd_filter( 'previous_posts_link_attributes', 'previous_posts_link_css' );\n</code></pre>\n\n<p>Then style the <code>.next</code> and <code>.prev</code> links using CSS.</p>\n" }, { "answer_id": 174177, "author": "Varun Kumar", "author_id": 48415, "author_profile": "https://wordpress.stackexchange.com/users/48415", "pm_score": 0, "selected": false, "text": "<p>Right click on next page and previous page links and inspect element (assuming you are using chrome). You will get to know the classes and then style as you like.</p>\n" } ]
2015/01/07
[ "https://wordpress.stackexchange.com/questions/174175", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2000/" ]
I have this : ``` <?php the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'twentyfifteen' ), 'next_text' => __( 'Next page', 'twentyfifteen' ), ) ); ?> ``` Which gives this output : ![enter image description here](https://i.stack.imgur.com/ZEaZV.png) What I want is this : ![enter image description here](https://i.stack.imgur.com/ZHeaV.png) How to do this using the\_posts\_pagination() please ?
Do this to output only links for previous and next pages: ``` <?php previous_posts_link ( 'Previous' ) ?> <?php next_posts_link ( 'Next' ); ?> ``` Then add filters to your functions.php to add a class to each link: ``` function next_posts_link_css ( $content ) { return 'class="next"'; } add_filter( 'next_posts_link_attributes', 'next_posts_link_css' ); function previous_posts_link_css ( $content ) { return 'class="prev"'; } add_filter( 'previous_posts_link_attributes', 'previous_posts_link_css' ); ``` Then style the `.next` and `.prev` links using CSS.
174,178
<p>I've created multiple custom post types with archives set to true with a custom slug. However, all of these archives have the body class of <code>blog</code> and <code>home</code> and no class related to the post type.</p> <p>I'm using <code>&lt;body &lt;?php body_class(); ?&gt;&gt;</code> in the header file that get's called on every page, but somehow it doesn't recognize these pages as cpt-archives.</p> <p>Is this expected functionality, or is it more likely I've done an error in coding the templates/post types?</p> <p><a href="http://ostforsk.screenpartner.no/publikasjoner/" rel="nofollow">Archive example</a></p> <p>My post type code (All CPT coded same way, minor variations):</p> <pre><code>function publikasjoner() { register_post_type( 'publikasjoner', array( 'labels' =&gt; array( 'name' =&gt; __( 'Publikasjoner', 'bonestheme' ), 'singular_name' =&gt; __( 'Publikasjon', 'bonestheme' ), 'all_items' =&gt; __( 'Alle publikasjoner', 'bonestheme' ), 'add_new' =&gt; __( 'Ny publikasjon', 'bonestheme' ), 'add_new_item' =&gt; __( 'Legg til ny publikasjon', 'bonestheme' ), 'edit' =&gt; __( 'Rediger', 'bonestheme' ), 'edit_item' =&gt; __( 'Rediger publikasjoner', 'bonestheme' ), 'new_item' =&gt; __( 'Ny publikasjon', 'bonestheme' ), 'view_item' =&gt; __( 'Vis publikasjon', 'bonestheme' ), 'search_items' =&gt; __( 'Søk etter publikasjon', 'bonestheme' ), 'not_found' =&gt; __( 'Fant ingenting i databasen.', 'bonestheme' ), 'not_found_in_trash' =&gt; __( 'Fant ingenting i søppelkassen', 'bonestheme' ), 'parent_item_colon' =&gt; '' ), 'description' =&gt; __( 'Østlandsforsknings publikasjoner legges til her', 'bonestheme' ), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_position' =&gt; 9, 'menu_icon' =&gt; 'dashicons-edit', 'rewrite' =&gt; array( 'slug' =&gt; 'publikasjoner', 'with_front' =&gt; false ), 'has_archive' =&gt; 'publikasjoner', 'capability_type' =&gt; 'post', 'hierarchical' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields', 'revisions') ) ); register_taxonomy_for_object_type( 'emne', 'publikasjoner' ); register_taxonomy_for_object_type( 'emneord', 'publikasjoner' ); register_taxonomy_for_object_type( 'emne', 'type_publikasjon' ); } </code></pre>
[ { "answer_id": 174209, "author": "setterGetter", "author_id": 8756, "author_profile": "https://wordpress.stackexchange.com/users/8756", "pm_score": 0, "selected": false, "text": "<p>You said:</p>\n\n<blockquote>\n <p>I do have the body_class() filter inside the body tag in the header.php file, which get's called on every page.</p>\n</blockquote>\n\n<p>And the fact that </p>\n\n<blockquote>\n <p>You should see a lot more classes.</p>\n</blockquote>\n\n<p>This has the symptoms of a classic mistake (that I've made tons of time) Make sure that the filter on body_class is returning what it should, e.g. this is wrong:</p>\n\n<pre><code>add_filter('body_class', function($classes){\n global $post;\n if ( 'foobar' === $post-&gt;post_type ) {\n $classes[] = 'barfoo';\n return $classes;\n }\n});\n</code></pre>\n\n<p>and failing to return classes, which could fubar the process, and should be done as such:</p>\n\n<pre><code>add_filter('body_class', function($classes){\n global $post;\n if ( 'foobar' === $post-&gt;post_type ) {\n $classes[] = 'barfoo';\n }\n return $classes;\n});\n</code></pre>\n\n<p>If you don't return on a filter, which would be in the case of my first (wrong) example, it will null out the value.</p>\n\n<p>Not sure if it helps, but I've accidentally done that in the past.</p>\n" }, { "answer_id": 292110, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>You can pass whatever class or array of classes to the body class function. So if you were to determine that this is indeed the page for 'publikasjoner' then you could add that class to the body class like this:</p>\n\n<pre><code>body_class('publikasjoner');\n</code></pre>\n\n<p>You can check if you're on an archive page of a post type with <code>is_post_type_archive()</code>.</p>\n\n<p>So you can do:</p>\n\n<pre><code>$cpt_class = \"not-a-cpt\";\nif(is_post_type_archive('publikasjoner')){\n $cpt_class = 'publikasjoner';\n}\n?&gt;&lt;html stuff&gt;&lt;?php\nbody_class($cpt_class);\n</code></pre>\n" }, { "answer_id": 299318, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>There's filter called <code>body_class</code> for that. </p>\n\n<pre><code>function my_own_body_classes($classes) {\n\n // Add Classes to body if the post type archive is 'publikasjoner'\n if ( is_post_type_archive( 'publikasjoner' ) ) {\n $classes[] = 'publikasjoner-archive';\n }\n // Go for other posts types here\n\n\n return $classes;\n}\nadd_filter('body_class', 'my_own_body_classes');\n</code></pre>\n" } ]
2015/01/07
[ "https://wordpress.stackexchange.com/questions/174178", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16605/" ]
I've created multiple custom post types with archives set to true with a custom slug. However, all of these archives have the body class of `blog` and `home` and no class related to the post type. I'm using `<body <?php body_class(); ?>>` in the header file that get's called on every page, but somehow it doesn't recognize these pages as cpt-archives. Is this expected functionality, or is it more likely I've done an error in coding the templates/post types? [Archive example](http://ostforsk.screenpartner.no/publikasjoner/) My post type code (All CPT coded same way, minor variations): ``` function publikasjoner() { register_post_type( 'publikasjoner', array( 'labels' => array( 'name' => __( 'Publikasjoner', 'bonestheme' ), 'singular_name' => __( 'Publikasjon', 'bonestheme' ), 'all_items' => __( 'Alle publikasjoner', 'bonestheme' ), 'add_new' => __( 'Ny publikasjon', 'bonestheme' ), 'add_new_item' => __( 'Legg til ny publikasjon', 'bonestheme' ), 'edit' => __( 'Rediger', 'bonestheme' ), 'edit_item' => __( 'Rediger publikasjoner', 'bonestheme' ), 'new_item' => __( 'Ny publikasjon', 'bonestheme' ), 'view_item' => __( 'Vis publikasjon', 'bonestheme' ), 'search_items' => __( 'Søk etter publikasjon', 'bonestheme' ), 'not_found' => __( 'Fant ingenting i databasen.', 'bonestheme' ), 'not_found_in_trash' => __( 'Fant ingenting i søppelkassen', 'bonestheme' ), 'parent_item_colon' => '' ), 'description' => __( 'Østlandsforsknings publikasjoner legges til her', 'bonestheme' ), 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'show_ui' => true, 'query_var' => true, 'menu_position' => 9, 'menu_icon' => 'dashicons-edit', 'rewrite' => array( 'slug' => 'publikasjoner', 'with_front' => false ), 'has_archive' => 'publikasjoner', 'capability_type' => 'post', 'hierarchical' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields', 'revisions') ) ); register_taxonomy_for_object_type( 'emne', 'publikasjoner' ); register_taxonomy_for_object_type( 'emneord', 'publikasjoner' ); register_taxonomy_for_object_type( 'emne', 'type_publikasjon' ); } ```
There's filter called `body_class` for that. ``` function my_own_body_classes($classes) { // Add Classes to body if the post type archive is 'publikasjoner' if ( is_post_type_archive( 'publikasjoner' ) ) { $classes[] = 'publikasjoner-archive'; } // Go for other posts types here return $classes; } add_filter('body_class', 'my_own_body_classes'); ```
174,185
<p>I'm trying to debug a strange issue that happens on one my plugin's users system. The issue: When i submit my Plugin's Settings form (option-general.php?page=pluginname), I get a 500 error message. Other setting pages work fine, just this one.</p> <p>I couldn't reproduce the error when simply using my plugin on a fresh wordpress copy. I have a local copy of his wordpress database + theme and plugins and now the issue occurs. I desactivated all its plugins (36!) and switched back to the default Twenty Fifteen Theme. The issue remains.</p> <p>In Apache error log file tells me this:</p> <pre><code>"fastcgi: incomplete headers (0 bytes) received from server" </code></pre> <p>So, I changed my PHP mode from "CGI" to "Module".</p> <p>And now, it works flawlessly, the issue has disappeared.</p> <p>I then switched back to CGI, and ... It works still. </p> <p>What may have happened here? I'm worried of not understanding what is the cause, since this plugin of mine is opensource and will run in many different setups.</p>
[ { "answer_id": 174207, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>500 errors can be for many reasons. In context of submitting form they are more common because of security setup, typically <code>mod_security</code>. It tends to have strict rules for form submissions / POST requests.</p>\n\n<p>There isn't much you can do about it really. At one host in the past I needed to ask support to disable some <code>mod_security</code> rules, because I couldn't even save some of my WordPress posts.</p>\n" }, { "answer_id": 174275, "author": "pixeline", "author_id": 82, "author_profile": "https://wordpress.stackexchange.com/users/82", "pm_score": 1, "selected": true, "text": "<p>It turns out it was a bug after all: one of my plugin options is a textfield in which the user can specify a message. It is provided with a default value, but that user chose not to have any message, so emptied it. It looked ok on the backend (field looked empty), but when i looked into the database it had become zillions and zillions of \"\\\" signs! This created a memory log issue. </p>\n\n<p>I feel stupid for forgetting to sanitize the input. I've patched it. </p>\n" } ]
2015/01/07
[ "https://wordpress.stackexchange.com/questions/174185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82/" ]
I'm trying to debug a strange issue that happens on one my plugin's users system. The issue: When i submit my Plugin's Settings form (option-general.php?page=pluginname), I get a 500 error message. Other setting pages work fine, just this one. I couldn't reproduce the error when simply using my plugin on a fresh wordpress copy. I have a local copy of his wordpress database + theme and plugins and now the issue occurs. I desactivated all its plugins (36!) and switched back to the default Twenty Fifteen Theme. The issue remains. In Apache error log file tells me this: ``` "fastcgi: incomplete headers (0 bytes) received from server" ``` So, I changed my PHP mode from "CGI" to "Module". And now, it works flawlessly, the issue has disappeared. I then switched back to CGI, and ... It works still. What may have happened here? I'm worried of not understanding what is the cause, since this plugin of mine is opensource and will run in many different setups.
It turns out it was a bug after all: one of my plugin options is a textfield in which the user can specify a message. It is provided with a default value, but that user chose not to have any message, so emptied it. It looked ok on the backend (field looked empty), but when i looked into the database it had become zillions and zillions of "\" signs! This created a memory log issue. I feel stupid for forgetting to sanitize the input. I've patched it.
174,220
<p>I have a couple of actions setup:</p> <pre><code>add_action('publish_post', array($this, 'newPost'), 10, 2); add_action('post_updated', array($this, 'updatePost'), 10, 3); </code></pre> <p>When I update an already published post the 'newPost' method is fired as opposed to the 'updatePost' method. I imagine this is because the post is already published so what would be a good way to fire a different method (or be able to identify that it's an update as opposed to a newly published post) when a previously published post is updated?</p>
[ { "answer_id": 174224, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"http://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow\">post status transition</a> actions for this.</p>\n\n<pre><code>function wpd_updating_a_published_post( $post ){\n // do something\n}\nadd_action( 'publish_to_publish', 'wpd_updating_a_published_post', 10, 1 );\n</code></pre>\n" }, { "answer_id": 174232, "author": "ifdion", "author_id": 6383, "author_profile": "https://wordpress.stackexchange.com/users/6383", "pm_score": 1, "selected": false, "text": "<p>You can user Milo 's answer or you can use the conditional inside the hooked function, and then compare the <code>post_date</code> and the <code>post_modified</code>.</p>\n\n<pre><code>add_action('save_post', array($this, 'updatePost'), 10, 3);\n\nfunction updatePost($post_id){\n\n// If this is just a revision, don't send the email.\nif ( wp_is_post_revision( $post_id ) )\n return;\n\n$post = get_post($post_id);\n\n// Compare the date\nif ($post-&gt;post_date == $post-&gt;post_modified){\n // Do something for a new post\n\n} elseif ($post-&gt;post_date &lt; $post-&gt;post_modified){\n // Do something for an updated post\n}\n</code></pre>\n" }, { "answer_id": 174237, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As an alternative, you can make use of the 'transition_post_status' hook for this. This hook is fired whenever a post's status is changed. In your case, you need to check whether the old and new status of the post is the same, which is <code>publish</code> </p>\n\n<p>You can also set conditionals according to <code>$post</code>, which is the current post being updated/published etc.</p>\n\n<p>You can try the following:</p>\n\n<pre><code>add_action('transition_post_status', function ($new_status, $old_status, $post) {\n\n if ( $old_status == 'publish' &amp;&amp; $new_status == 'publish' ) {\n //Do something when post is updated\n }\n\n}, 10, 3 );\n</code></pre>\n" } ]
2015/01/07
[ "https://wordpress.stackexchange.com/questions/174220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3264/" ]
I have a couple of actions setup: ``` add_action('publish_post', array($this, 'newPost'), 10, 2); add_action('post_updated', array($this, 'updatePost'), 10, 3); ``` When I update an already published post the 'newPost' method is fired as opposed to the 'updatePost' method. I imagine this is because the post is already published so what would be a good way to fire a different method (or be able to identify that it's an update as opposed to a newly published post) when a previously published post is updated?
As an alternative, you can make use of the 'transition\_post\_status' hook for this. This hook is fired whenever a post's status is changed. In your case, you need to check whether the old and new status of the post is the same, which is `publish` You can also set conditionals according to `$post`, which is the current post being updated/published etc. You can try the following: ``` add_action('transition_post_status', function ($new_status, $old_status, $post) { if ( $old_status == 'publish' && $new_status == 'publish' ) { //Do something when post is updated } }, 10, 3 ); ```
174,259
<p>I want to add a custom fields ("introduction" and "ensavoirplus") to search of Wordpress, but the SQL code is not exact. I don't understand if i do a mistake or if WP don't can do this. But my attempt fail... I don't know why because I do exactly what the codex says.</p> <p>This is my code :</p> <pre><code>function recherche_avancee( $query ) { if ( !is_admin() &amp;&amp; $query-&gt;is_search ) { $custom_fields = array( "introduction", "en_savoir_plus_page" ); $meta_query = array('relation' =&gt; 'OR'); foreach($custom_fields as $cf) { array_push($meta_query, array( 'key' =&gt; $cf, 'value' =&gt; $_GET['s'], 'compare' =&gt; 'LIKE' )); } $query-&gt;set("meta_query", $meta_query); } } add_action( 'pre_get_posts', 'recherche_avancee'); </code></pre> <p>And this is the SQL code :</p> <pre><code>1. SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 2. FROM wp_posts 3. INNER JOIN wp_postmeta 4. ON ( wp_posts.ID = wp_postmeta.post_id ) 5. WHERE 1=1 6. AND (((wp_posts.post_title LIKE '%environnement%') 7. OR (wp_posts.post_content LIKE '%environnement%'))) 8. AND wp_posts.post_type IN ('post', 'page', 'attachment') 9. AND (wp_posts.post_status = 'publish' 10. OR wp_posts.post_status = 'miseenavant' 11. OR wp_posts.post_author = 3 12. AND wp_posts.post_status = 'private') 13. AND ( ( wp_postmeta.meta_key = 'introduction' 14. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%environnement%' ) 15. OR ( wp_postmeta.meta_key = 'en_savoir_plus_page' 16. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%environnement%' ) ) 17. GROUP BY wp_posts.ID 18. ORDER BY wp_posts.menu_order ASC 19. LIMIT 0, 10 </code></pre> <p>The errors are on line 13, because I don't want a <strong>AND</strong> but a <strong>OR</strong> and the lines 13,14,15,16 should go right after line 7 that it all works.</p> <p>Someone already had the same kind of error and if so where did it come from?</p> <p>Thanks</p>
[ { "answer_id": 174356, "author": "ArnaudBan", "author_id": 25514, "author_profile": "https://wordpress.stackexchange.com/users/25514", "pm_score": 1, "selected": false, "text": "<p>Thanks to WordPress 4.1 you can do better for meta_query :\n<a href=\"https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/</a></p>\n<pre><code>function recherche_avancee($query) {\n if (!is_admin() &amp;&amp; $query-&gt;is_search) {\n $meta_query = array(\n 'relation' =&gt; 'OR',\n array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'introduction',\n 'value' =&gt; get_search_query(),\n 'compare' =&gt; 'LIKE',\n ),\n array(\n 'key' =&gt; 'en_savoir_plus_page',\n 'value' =&gt; get_search_query(),\n 'compare' =&gt; 'LIKE',\n ),\n ),\n );\n \n $query-&gt;set('meta_query', $meta_query);\n }\n}\nadd_action('pre_get_posts', 'recherche_avancee');\n</code></pre>\n<p>Did not test but you get the idea...</p>\n" }, { "answer_id": 307041, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": -1, "selected": false, "text": "<p>I have reviewed your code but I can't find what is wrong with your code. I have an easy solution. You can use third party free WordPress plugin, WP Extended Search and select meta keys which you want to add in your search results. This plugin helps to extend WordPress default search and include post meta, taxonomies and custom post types in search results.</p>\n<p>WP Extended Search:\n<a href=\"https://wordpress.org/plugins/wp-extended-search/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-extended-search/</a></p>\n<p><a href=\"https://i.stack.imgur.com/8iW23.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8iW23.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Hope this helps...!!</p>\n" }, { "answer_id": 318639, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 1, "selected": false, "text": "<p>please never do this: <code>'value' =&gt; $_GET['s']</code> ... <code>$query-&gt;get('s');</code>, <a href=\"https://codex.wordpress.org/Function_Reference/get_search_query\" rel=\"nofollow noreferrer\">get_search_query</a>, or <code>sanitize_key($_GET['s'])</code> are all safer options. Technically we shouldn't be using get-params in wordpress at all, it's not a best-practice. That get value could be all sorts of bad things, &amp; we don't want to pass it along to the db without making sure it's clean.</p>\n\n<p>Also, you're using the <code>LIKE</code> operator... so you might want to add quotes around the value for stricter matching.</p>\n\n<pre><code>'value' =&gt; '\"'.$query-&gt;get('s').'\"';\n</code></pre>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65699/" ]
I want to add a custom fields ("introduction" and "ensavoirplus") to search of Wordpress, but the SQL code is not exact. I don't understand if i do a mistake or if WP don't can do this. But my attempt fail... I don't know why because I do exactly what the codex says. This is my code : ``` function recherche_avancee( $query ) { if ( !is_admin() && $query->is_search ) { $custom_fields = array( "introduction", "en_savoir_plus_page" ); $meta_query = array('relation' => 'OR'); foreach($custom_fields as $cf) { array_push($meta_query, array( 'key' => $cf, 'value' => $_GET['s'], 'compare' => 'LIKE' )); } $query->set("meta_query", $meta_query); } } add_action( 'pre_get_posts', 'recherche_avancee'); ``` And this is the SQL code : ``` 1. SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 2. FROM wp_posts 3. INNER JOIN wp_postmeta 4. ON ( wp_posts.ID = wp_postmeta.post_id ) 5. WHERE 1=1 6. AND (((wp_posts.post_title LIKE '%environnement%') 7. OR (wp_posts.post_content LIKE '%environnement%'))) 8. AND wp_posts.post_type IN ('post', 'page', 'attachment') 9. AND (wp_posts.post_status = 'publish' 10. OR wp_posts.post_status = 'miseenavant' 11. OR wp_posts.post_author = 3 12. AND wp_posts.post_status = 'private') 13. AND ( ( wp_postmeta.meta_key = 'introduction' 14. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%environnement%' ) 15. OR ( wp_postmeta.meta_key = 'en_savoir_plus_page' 16. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%environnement%' ) ) 17. GROUP BY wp_posts.ID 18. ORDER BY wp_posts.menu_order ASC 19. LIMIT 0, 10 ``` The errors are on line 13, because I don't want a **AND** but a **OR** and the lines 13,14,15,16 should go right after line 7 that it all works. Someone already had the same kind of error and if so where did it come from? Thanks
Thanks to WordPress 4.1 you can do better for meta\_query : <https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/> ``` function recherche_avancee($query) { if (!is_admin() && $query->is_search) { $meta_query = array( 'relation' => 'OR', array( 'relation' => 'OR', array( 'key' => 'introduction', 'value' => get_search_query(), 'compare' => 'LIKE', ), array( 'key' => 'en_savoir_plus_page', 'value' => get_search_query(), 'compare' => 'LIKE', ), ), ); $query->set('meta_query', $meta_query); } } add_action('pre_get_posts', 'recherche_avancee'); ``` Did not test but you get the idea...
174,260
<p>in my Wordpress plugin i used the post_where filter but it's effect all other post type of my site.</p> <p>my question is how to set this filter only for "property" post only</p> <pre><code>add_filter('posts_where', 'posts_where'); function posts_where($where) { global $wpdb,$wp_query; $where .= ' AND latitude.meta_key="wp_gp_latitude" '; $where .= ' AND longitude.meta_key="wp_gp_longitude" '; return $where; } </code></pre>
[ { "answer_id": 174896, "author": "guest1", "author_id": 66040, "author_profile": "https://wordpress.stackexchange.com/users/66040", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter( 'posts_where' , 'posts_where', 10, 2);\n\nfunction posts_where( $where, $query ) {\n global $wpdb,$wp_query;\n if ($query-&gt;query_vars['post_type'] == 'property') {\n $where .= ' AND latitude.meta_key=\"wp_gp_latitude\" ';\n $where .= ' AND longitude.meta_key=\"wp_gp_longitude\" ';\n }\n return $where;\n}\n</code></pre>\n\n<p>If you add <code>$priority = 10 //normal</code> and <code>$accepted_args = 2</code> to your <code>add_filter</code> function,\nyou will have a <code>$query</code> object in your <code>posts_where</code> function that you can put a conditional on your <code>post_type</code> for 'property' to have it only affect your custom post type.</p>\n\n<p>Here is a link to the WP codex documentation for the <code>add_filter</code> function:\n<a href=\"http://codex.wordpress.org/Function_Reference/add_filter\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/add_filter</a></p>\n" }, { "answer_id": 353343, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 1, "selected": false, "text": "<p>Please note that the post_Type query variable is not set for standard types (page, post and attachment, see <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L2396\" rel=\"nofollow noreferrer\">WP_QUery class file line 2396 on trac</a>), only for custom post types, so this is how you can test for each type,</p>\n\n<pre><code>add_filter( 'posts_where' , 'posts_where', 10, 2);\nfunction posts_where( $args, $wp_query_obj ) {\n $type = $wp_query_obj-&gt;query_vars['post_type'];\n switch(true){\n case 'any'==$type: //query any type (see codex for more details).\n break;\n case !empty($type) &amp;&amp; is_array($type):\n //multiple post types define\n break;\n case !empty($type):\n //post type is a custom post.\n //this is where you would check for your post type,\n if ($type == 'property') {\n $args .= ' AND latitude.meta_key=\"wp_gp_latitude\" ';\n $args .= ' AND longitude.meta_key=\"wp_gp_longitude\" ';\n }\n break;\n case $wp_query_obj-&gt;is_attachment():\n //post type is empty but is a media.\n $type='attachemnt';\n break;\n case $wp_query_obj-&gt;is_page():\n //post type is empty but is a page.\n $type='page';\n break;\n default:\n //post type is empty and not an attachment nor a page, so is a post.\n $type='post';\n break;\n }\n return $where;\n}\n</code></pre>\n\n<p>for more information on the WP_Query object and its methods, see the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">codex</a> page.</p>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174260", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41546/" ]
in my Wordpress plugin i used the post\_where filter but it's effect all other post type of my site. my question is how to set this filter only for "property" post only ``` add_filter('posts_where', 'posts_where'); function posts_where($where) { global $wpdb,$wp_query; $where .= ' AND latitude.meta_key="wp_gp_latitude" '; $where .= ' AND longitude.meta_key="wp_gp_longitude" '; return $where; } ```
Please note that the post\_Type query variable is not set for standard types (page, post and attachment, see [WP\_QUery class file line 2396 on trac](https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L2396)), only for custom post types, so this is how you can test for each type, ``` add_filter( 'posts_where' , 'posts_where', 10, 2); function posts_where( $args, $wp_query_obj ) { $type = $wp_query_obj->query_vars['post_type']; switch(true){ case 'any'==$type: //query any type (see codex for more details). break; case !empty($type) && is_array($type): //multiple post types define break; case !empty($type): //post type is a custom post. //this is where you would check for your post type, if ($type == 'property') { $args .= ' AND latitude.meta_key="wp_gp_latitude" '; $args .= ' AND longitude.meta_key="wp_gp_longitude" '; } break; case $wp_query_obj->is_attachment(): //post type is empty but is a media. $type='attachemnt'; break; case $wp_query_obj->is_page(): //post type is empty but is a page. $type='page'; break; default: //post type is empty and not an attachment nor a page, so is a post. $type='post'; break; } return $where; } ``` for more information on the WP\_Query object and its methods, see the [codex](https://developer.wordpress.org/reference/classes/wp_query/) page.
174,266
<p>I posted a similar question about this before but I changed a bit of the code so I figured I'd start a new topic. Below is the setup I currently have to load single posts on the front page.</p> <p><a href="http://themetrust.com/demos/reveal/" rel="nofollow noreferrer">This is what I'm trying to do.</a> Notice that when you click a post, it loads in a hidden container.</p> <p>Can someone help me figure this out?</p> <p><strong>Front-page.php</strong></p> <pre><code>&lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;div id="project-container"&gt; &lt;img id="loading-animation" src="http://i.imgur.com/5RMfW8P.gif" style="display:none"&gt; &lt;/div&gt; &lt;!-- Start the loop --&gt; &lt;?php $home_query = new WP_Query('post_type=projects'); while($home_query-&gt;have_posts()) : $home_query-&gt;the_post(); ?&gt; &lt;a class="post-link" href="#" rel="&lt;?php the_ID(); ?&gt;"&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;div class="post-info"&gt; &lt;h1 class="entry-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;/div&gt; &lt;?php the_post_thumbnail( "home-thumb", array( 'class' =&gt; 'grayscale grayscale-fade') ); ?&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; &lt;/a&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_postdata(); // reset the query ?&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; </code></pre> <p><strong>Functions.php</strong></p> <pre><code>/** * Enqueue scripts and styles. */ function starter_scripts() { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-effects-core'); wp_enqueue_style( 'starter-style', get_stylesheet_uri() ); wp_enqueue_script( 'gray', get_template_directory_uri() . '/js/min/jquery.gray.min.js', array('jquery'), '', true ); wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', array('jquery'), '', true ); wp_localize_script( 'includes', 'site', array( 'theme_path' =&gt; get_template_directory_uri(), 'ajaxurl' =&gt; admin_url('admin-ajax.php') ) ); } add_action( 'wp_enqueue_scripts', 'starter_scripts' ); /** * Return the post content to the AJAX call */ function my_load_ajax_content () { $args = array( 'p' =&gt; $_POST['post_id'] ); $post_query = new WP_Query( $args ); while( $post_query-&gt;have_posts() ) : $post_query-&gt;the_post(); ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php printf( esc_attr( 'Permalink to %s' ), the_title_attribute( 'echo=0' ) ); ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;!-- end .entry-content --&gt; &lt;/div&gt; &lt;?php endwhile; exit; } add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); </code></pre> <p><strong>Includes.js</strong></p> <pre><code>// Load posts via AJAX $(".post-link").click(function(e) { e.preventDefault(); $("#loading-animation").show(); var post_id = $(this).attr('rel'); var ajaxURL = site.ajaxurl; $.ajax({ type: 'POST', url: ajaxURL, data: {"action": "load-content", post_id: post_id }, success: function(response) { $("#project-container").html(response); $("#loading-animation").hide(); return false; } }); }); </code></pre> <p><strong>Single.php</strong></p> <pre><code>&lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;div class="post-container"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt;&lt;!-- #post-## --&gt; &lt;?php starter_post_nav(); ?&gt; &lt;?php endwhile; // end of the loop. ?&gt; </code></pre>
[ { "answer_id": 174290, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>The difference between the code you linked and your version, is that your post link has the permalink as the href value, where the original has just a hash. When you add a click handler to an anchor tag, it doesn't prevent what normally occurs when you click that link, it just executes the javascript and normal link behavior continues as it otherwise would. If you want to prevent links from being followed on a click event, you have to <a href=\"http://api.jquery.com/event.preventdefault/\" rel=\"nofollow\">explicitly prevent that in your javascript</a>:</p>\n\n<pre><code>$(\".post-link\").click(function(event) {\n event.preventDefault();\n // the rest of your code... \n});\n</code></pre>\n" }, { "answer_id": 185398, "author": "Vadim Goncharov", "author_id": 71190, "author_profile": "https://wordpress.stackexchange.com/users/71190", "pm_score": 0, "selected": false, "text": "<p>To load your <code>single.php</code> template, first you need to move your <code>functions.php</code> code</p>\n\n<pre><code>&lt;div id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;div class=\"entry-content\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Place the above code into <code>single.php</code>. Make sure you replace everything, because single.php has a while loop, but we already doing a loop in the functions.php.</p>\n\n<p>And in place of the above code add <code>get_template_part('single');</code> to your <code>functions.php</code> between the while loop.</p>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18320/" ]
I posted a similar question about this before but I changed a bit of the code so I figured I'd start a new topic. Below is the setup I currently have to load single posts on the front page. [This is what I'm trying to do.](http://themetrust.com/demos/reveal/) Notice that when you click a post, it loads in a hidden container. Can someone help me figure this out? **Front-page.php** ``` <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <div id="project-container"> <img id="loading-animation" src="http://i.imgur.com/5RMfW8P.gif" style="display:none"> </div> <!-- Start the loop --> <?php $home_query = new WP_Query('post_type=projects'); while($home_query->have_posts()) : $home_query->the_post(); ?> <a class="post-link" href="#" rel="<?php the_ID(); ?>"> <article id="post-<?php the_ID(); ?>"> <div class="post-info"> <h1 class="entry-title"><?php the_title(); ?></h1> </div> <?php the_post_thumbnail( "home-thumb", array( 'class' => 'grayscale grayscale-fade') ); ?> </article><!-- #post-## --> </a> <?php endwhile; ?> <?php wp_reset_postdata(); // reset the query ?> </main><!-- #main --> </div><!-- #primary --> ``` **Functions.php** ``` /** * Enqueue scripts and styles. */ function starter_scripts() { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-effects-core'); wp_enqueue_style( 'starter-style', get_stylesheet_uri() ); wp_enqueue_script( 'gray', get_template_directory_uri() . '/js/min/jquery.gray.min.js', array('jquery'), '', true ); wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', array('jquery'), '', true ); wp_localize_script( 'includes', 'site', array( 'theme_path' => get_template_directory_uri(), 'ajaxurl' => admin_url('admin-ajax.php') ) ); } add_action( 'wp_enqueue_scripts', 'starter_scripts' ); /** * Return the post content to the AJAX call */ function my_load_ajax_content () { $args = array( 'p' => $_POST['post_id'] ); $post_query = new WP_Query( $args ); while( $post_query->have_posts() ) : $post_query->the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr( 'Permalink to %s' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <div class="entry-content"> <?php the_content(); ?> </div> <!-- end .entry-content --> </div> <?php endwhile; exit; } add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); ``` **Includes.js** ``` // Load posts via AJAX $(".post-link").click(function(e) { e.preventDefault(); $("#loading-animation").show(); var post_id = $(this).attr('rel'); var ajaxURL = site.ajaxurl; $.ajax({ type: 'POST', url: ajaxURL, data: {"action": "load-content", post_id: post_id }, success: function(response) { $("#project-container").html(response); $("#loading-animation").hide(); return false; } }); }); ``` **Single.php** ``` <?php while ( have_posts() ) : the_post(); ?> <div class="post-container"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> <?php the_content(); ?> </div><!-- #post-## --> <?php starter_post_nav(); ?> <?php endwhile; // end of the loop. ?> ```
The difference between the code you linked and your version, is that your post link has the permalink as the href value, where the original has just a hash. When you add a click handler to an anchor tag, it doesn't prevent what normally occurs when you click that link, it just executes the javascript and normal link behavior continues as it otherwise would. If you want to prevent links from being followed on a click event, you have to [explicitly prevent that in your javascript](http://api.jquery.com/event.preventdefault/): ``` $(".post-link").click(function(event) { event.preventDefault(); // the rest of your code... }); ```
174,276
<p>I was trying to make the "name field" &amp; "phone field" in the events booking form a required field as well and I managed to look for some answers from here --> <a href="https://wordpress.org/support/topic/booking-form-required-fields?replies=13" rel="nofollow">https://wordpress.org/support/topic/booking-form-required-fields?replies=13</a>. Have also added the below codes into my child theme functions.php. On the single event page (with the booking form), after clicking on the "Send your booking" (without entering anything into the fields), error message still shows only "ERROR: Please type your e-mail address." only. Is there any steps I'm missing here? Have anyone experience the same issue before and could anyone point me in the right direction? </p> <pre><code>function em_validate($result, $EM_Event){ if (!is_user_logged_in() &amp;&amp; $_REQUEST['user_name'] == ''){ $EM_Event-&gt;add_error('Your Name is Required...'); $result = false; } if (!is_user_logged_in() &amp;&amp; $_REQUEST['dbem_phone'] == ''){ $EM_Event-&gt;add_error('Your Contact Number is Required...'); $result = false; } if (!is_user_logged_in() &amp;&amp; $_REQUEST['user_email'] == ''){ $EM_Event-&gt;add_error('Your Email is Required...'); $result = false; } return $result; } add_filter('em_event_validate','em_validate', 1, 2); </code></pre>
[ { "answer_id": 174374, "author": "stanley", "author_id": 65709, "author_profile": "https://wordpress.stackexchange.com/users/65709", "pm_score": 2, "selected": false, "text": "<p>I manage to get the answers from this post --> <a href=\"https://wordpress.org/support/topic/change-required-fields-in-registration-form?replies=3\" rel=\"nofollow\">https://wordpress.org/support/topic/change-required-fields-in-registration-form?replies=3</a></p>\n\n<p>Instead of using 'em_event_validate'</p>\n\n<pre><code>add_filter('em_event_validate','em_validate', 1, 2);\n</code></pre>\n\n<p>should be using 'em_booking_validate' in the filter hook</p>\n\n<pre><code>add_filter('em_booking_validate','em_validate', 1, 2);\n</code></pre>\n" }, { "answer_id": 250882, "author": "Fredhimself", "author_id": 109978, "author_profile": "https://wordpress.stackexchange.com/users/109978", "pm_score": 0, "selected": false, "text": "<p>I found a way to make those fields required with html required attribute. Search for <code>booking-fields.php</code> and make a copy to add it here: <code>your-child-theme\\plugins\\events-manager\\forms\\bookingform\\</code> , create each folder needed for that path ... Then within this copy of <code>booking-form.php</code> edit the code:</p>\n\n<pre><code>&lt;input type=\"text\" maxlength=\"50\" required name=\"user_name\" id=\"user_name\" class=\"input\" value=\"&lt;?php if(!empty($_REQUEST['user_name'])) echo esc_attr($_REQUEST['user_name']); ?&gt;\" /&gt; \n</code></pre>\n\n<p>You have now a 'safe-upgrade' customisation of EM plugin. This works with all files inside the plugin's 'template' folder / copy-to=> <code>your-child-theme\\plugins\\events-manager\\</code></p>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174276", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65709/" ]
I was trying to make the "name field" & "phone field" in the events booking form a required field as well and I managed to look for some answers from here --> <https://wordpress.org/support/topic/booking-form-required-fields?replies=13>. Have also added the below codes into my child theme functions.php. On the single event page (with the booking form), after clicking on the "Send your booking" (without entering anything into the fields), error message still shows only "ERROR: Please type your e-mail address." only. Is there any steps I'm missing here? Have anyone experience the same issue before and could anyone point me in the right direction? ``` function em_validate($result, $EM_Event){ if (!is_user_logged_in() && $_REQUEST['user_name'] == ''){ $EM_Event->add_error('Your Name is Required...'); $result = false; } if (!is_user_logged_in() && $_REQUEST['dbem_phone'] == ''){ $EM_Event->add_error('Your Contact Number is Required...'); $result = false; } if (!is_user_logged_in() && $_REQUEST['user_email'] == ''){ $EM_Event->add_error('Your Email is Required...'); $result = false; } return $result; } add_filter('em_event_validate','em_validate', 1, 2); ```
I manage to get the answers from this post --> <https://wordpress.org/support/topic/change-required-fields-in-registration-form?replies=3> Instead of using 'em\_event\_validate' ``` add_filter('em_event_validate','em_validate', 1, 2); ``` should be using 'em\_booking\_validate' in the filter hook ``` add_filter('em_booking_validate','em_validate', 1, 2); ```
174,287
<p>Most of (if not all) the <code>is_*</code> methods in the <code>WP_Query</code> class have a matching public property and the methods appear to just return the property e.g:</p> <pre><code>public function is_search() { return (bool) $this-&gt;is_search; } </code></pre> <p>What is the purpose of the method when the property is already set? Are there use cases when you would use one over the other? Surely it's more efficient to check <code>$wp_query-&gt;is_search</code> over <code>$wp_query-&gt;is_search()</code>?</p> <p><strong>Edit</strong>: it would be nice to get an answer relating to the <code>WP_Query</code> methods. Whilst I appreciate the answers given they both refer to the global <code>is_*</code> functions rather than the class methods which is what I am referring to</p>
[ { "answer_id": 174294, "author": "Andrew Bartel", "author_id": 17879, "author_profile": "https://wordpress.stackexchange.com/users/17879", "pm_score": 0, "selected": false, "text": "<p>Makes it easier for people getting started with development who are only used to using function template tags, i.e. <code>is_single()</code>, <code>is_archive()</code> etc without forcing them to take a crash course on OOP. That and it avoids another global declaration for <code>$wp_query</code> I suppose. On a semantic level, the code does look cleaner imo if you're using template tags along with <code>have_posts()</code>, <code>the_post</code> etc in templates rather than mixing in checks against <code>$wp_query</code>.</p>\n\n<p>Edit: Regarding efficiency, my C is pretty terrible so I can't definitively look at the interpreter and see how a function call compares to accessing a public property but I bet if you benchmarked it that the results would be negligible.</p>\n" }, { "answer_id": 177689, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 2, "selected": true, "text": "<p>While your example of is_search() is a rather trivial one and harder to justify, it's generally recommended in OOP styles to use getters and setters for things like this instead of public properties, for a number of reasons.</p>\n\n<ul>\n<li><p>Encapsulation. The behavior of <code>is_search()</code> returns a boolean, but the method by which it determines whether or not a search is taking place could change in the future. Right now, the <code>is_search</code> variable is set earlier in the process and then this function returns it. A later version might do an immediate check to see if the current URL is a search one instead, depending on how the template system changes. For example, the property, though public, might change later. Right now it's stored as a boolean, but maybe something like \"<code>search_string</code>\" could be checked instead and a boolean then returned by <code>is_search()</code>. The output by the function hides the internal state of the variables being used, because the outside doesn't need to know those necessarily.</p></li>\n<li><p>Public methods like <code>is_search()</code> are your interface, and the interface can thus remain more constant over time. Better to use something that's less likely to change (<code>is_search()</code> is only ever going to return a boolean, realistically). </p></li>\n<li><p>Lots of other libraries and development systems know about getters and setters and work better when they exist. It's a common style choice, best to fit the mold.</p></li>\n<li><p>Classes that inherit from your class can change how the fundamental basics work, and these functions allow them to use these to override behavior. Having to keep variables public and modify them internally is more difficult and error prone.</p></li>\n<li><p>Functions, even object methods, can be passed around as callbacks to things like filter functions and such. Variables can't.</p></li>\n</ul>\n\n<p>So, the real answer to your question is that the is_search variable probably should not be public. The method existing is relatively normal.</p>\n\n<p>When coding, code defensively. Even if you can access the <code>is_search</code> variable directly, use the <code>is_search()</code> function instead. If the variable changes at all in the future, the function will change to accommodate it and still give you the correct output.</p>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43719/" ]
Most of (if not all) the `is_*` methods in the `WP_Query` class have a matching public property and the methods appear to just return the property e.g: ``` public function is_search() { return (bool) $this->is_search; } ``` What is the purpose of the method when the property is already set? Are there use cases when you would use one over the other? Surely it's more efficient to check `$wp_query->is_search` over `$wp_query->is_search()`? **Edit**: it would be nice to get an answer relating to the `WP_Query` methods. Whilst I appreciate the answers given they both refer to the global `is_*` functions rather than the class methods which is what I am referring to
While your example of is\_search() is a rather trivial one and harder to justify, it's generally recommended in OOP styles to use getters and setters for things like this instead of public properties, for a number of reasons. * Encapsulation. The behavior of `is_search()` returns a boolean, but the method by which it determines whether or not a search is taking place could change in the future. Right now, the `is_search` variable is set earlier in the process and then this function returns it. A later version might do an immediate check to see if the current URL is a search one instead, depending on how the template system changes. For example, the property, though public, might change later. Right now it's stored as a boolean, but maybe something like "`search_string`" could be checked instead and a boolean then returned by `is_search()`. The output by the function hides the internal state of the variables being used, because the outside doesn't need to know those necessarily. * Public methods like `is_search()` are your interface, and the interface can thus remain more constant over time. Better to use something that's less likely to change (`is_search()` is only ever going to return a boolean, realistically). * Lots of other libraries and development systems know about getters and setters and work better when they exist. It's a common style choice, best to fit the mold. * Classes that inherit from your class can change how the fundamental basics work, and these functions allow them to use these to override behavior. Having to keep variables public and modify them internally is more difficult and error prone. * Functions, even object methods, can be passed around as callbacks to things like filter functions and such. Variables can't. So, the real answer to your question is that the is\_search variable probably should not be public. The method existing is relatively normal. When coding, code defensively. Even if you can access the `is_search` variable directly, use the `is_search()` function instead. If the variable changes at all in the future, the function will change to accommodate it and still give you the correct output.
174,304
<p>For one of my project I just want to change the post status of all the posts inside a specific category from publish to pending.</p> <p>It is possible to change status of multiple posts at once? I want to use this functionality in a custom theme I am developing.</p> <p>thanks</p>
[ { "answer_id": 174310, "author": "gdaniel", "author_id": 30984, "author_profile": "https://wordpress.stackexchange.com/users/30984", "pm_score": 2, "selected": true, "text": "<p>I am sure there's an easier way to accomplish this, but this how I would've done.</p>\n\n<ol>\n<li>Query all posts with category X and status X</li>\n<li><p>Update query results with status Y.</p>\n\n<pre><code>$target_category = 'news';\n$change_status_from = 'draft';\n$change_status_to = 'publish';\n$update_query = new WP_Query(array('post_status'=&gt;$change_status_from, 'category_name'=&gt;$target_category, 'posts_per_page'=&gt;-1));\n\nif($update_query-&gt;have_posts()){\n\n while($update_query-&gt;have_posts()){\n\n $update_query-&gt;the_post();\n wp_update_post(array('ID'=&gt;$post-&gt;ID, 'post_status'=&gt;$change_status_to));\n\n }\n\n}\n</code></pre></li>\n</ol>\n\n<p>You can place this code inside a page template, or in functions.php. It's likely that you only need to run it every now and then. So I would create a template for it. Add it to the template and then assign that template to a specific page that's maybe marked as private or draft.</p>\n" }, { "answer_id": 288022, "author": "Jen", "author_id": 132901, "author_profile": "https://wordpress.stackexchange.com/users/132901", "pm_score": 2, "selected": false, "text": "<p>Or you can do this in MySQL using a query such as:</p>\n\n<pre><code>UPDATE tb_posts \nSET post_status = 'pending' \nWHERE ID IN ( \n SELECT object_id FROM `tb_term_relationships` \n WHERE term_taxonomy_id = {your_cat_id} \n)\n</code></pre>\n\n<p>If you hover over a category on the category page, you can see its ID in the URL</p>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65347/" ]
For one of my project I just want to change the post status of all the posts inside a specific category from publish to pending. It is possible to change status of multiple posts at once? I want to use this functionality in a custom theme I am developing. thanks
I am sure there's an easier way to accomplish this, but this how I would've done. 1. Query all posts with category X and status X 2. Update query results with status Y. ``` $target_category = 'news'; $change_status_from = 'draft'; $change_status_to = 'publish'; $update_query = new WP_Query(array('post_status'=>$change_status_from, 'category_name'=>$target_category, 'posts_per_page'=>-1)); if($update_query->have_posts()){ while($update_query->have_posts()){ $update_query->the_post(); wp_update_post(array('ID'=>$post->ID, 'post_status'=>$change_status_to)); } } ``` You can place this code inside a page template, or in functions.php. It's likely that you only need to run it every now and then. So I would create a template for it. Add it to the template and then assign that template to a specific page that's maybe marked as private or draft.
174,308
<p>I have a list of post ids and need to get all the standard data plus the thumbnail of the posts. As there will be several hundred posts i need an efficient way to retrieve the data, just looping over all the ids and using has_thummbnail... and all the other versions of the same 'one by one' approach will just not work fast enough.</p> <p><strong>So the question is:</strong></p> <p>how can i retrieve multiple post with their thumbnail url without making one query for each id</p> <p><strong>UPDATE:</strong></p> <p>As cybmeta pointed out with the linked posts, <a href="http://codex.wordpress.org/Function_Reference/get_post_meta" rel="nofollow">get_post_meta</a> does not create an additional DB Query and with that function it is possible to retrieve a post's custom fields.</p> <p><strong>BUT</strong> that still doesn't give me the URL of the thumbnail, just the thumbnail's ID. When retrieving the URL by one of the possible methods (<a href="https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src" rel="nofollow">wp_get_attachment_image_src</a>, <a href="http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata" rel="nofollow">wp_get_attachment_metadata</a>, ...) i create an additional DB Query for each thumbnail as those functions do not take multiple IDs!</p> <p><strong>More specific question:</strong></p> <p>How can i retrieve the url of multiple thumbnails via their id in one query</p>
[ { "answer_id": 174392, "author": "Larzan", "author_id": 34517, "author_profile": "https://wordpress.stackexchange.com/users/34517", "pm_score": 3, "selected": true, "text": "<p><strong>EXPLANATION</strong></p>\n\n<p>As mentioned in my update above, to retrieve the ID of a thumbnail the <a href=\"http://codex.wordpress.org/Function_Reference/get_post_meta\" rel=\"nofollow\">get_post_meta</a> function can be used without any additional DB overhead.\nThe 'normal' way to get the url to a thumbnail id is with <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src\" rel=\"nofollow\">wp_get_attachment_image_src</a> or similar functions, but those do not accept an array of IDs.</p>\n\n<p>What i noticed using <em>wp_get_attachment_image_src</em> was that it created even TWO querys per call (ergo per thumbnail), one to get the post data and then another one for the actual url.</p>\n\n<p><strong>SOLUTION</strong></p>\n\n<p>The only solution i found to retrieve more than one url at the same time was to directly query the DB postmeta table via <a href=\"http://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow\">wpdb</a>.</p>\n\n<p>There is a <em>postmeta</em> entry for the relation post->thumbnail with the <em>meta_key</em> <em>_thumbnail_id</em> and the thumbnails id as the <em>meta_value</em> and then two more entries per thumbnail with the <em>meta_tags</em> <em>_wp_attachment_metadata</em> and <em>_wp_attached_file</em> and the thumbnail's id as the <em>post_id</em>.</p>\n\n<p>So the interesting part of the postmeta table looks like this:</p>\n\n<pre><code>meta_id post_id meta_key meta_value\n328 136 _wp_attached_file 2015/01/Dog-w-Glasses.jpg\n329 136 _wp_attachment_metadata a:5{s:5:\"width\";i:...\n...\n335 138 _thumbnail_id 136\n</code></pre>\n\n<p>with 138 being the post's id and the <em>meta_id</em> being irrelevant for this example.</p>\n\n<p>As the <em>_thumbnail_id</em> was linked to the <em>post_id</em> it could be retrieved via the get_post_meta, but as the actual url was stored under the thumbnails id it had to be retrieved seperately.</p>\n\n<p>So what i did was retrieving all the thumbnail ids for each post via <em>get_post_meta</em> and then creating a query to the postmeta table of the WP Database:</p>\n\n<pre><code>$thumb_ids = '( 23, 89, 24, 69 )'; // just an example\nglobal $wpdb;\n$qstr =\n \"SELECT post_id, meta_value\n FROM $wpdb-&gt;postmeta\n WHERE post_id IN \" . $thumb_ids. ' AND meta_key = \"_wp_attached_file\"';\n$results = $wpdb-&gt;get_results( $qstr, ARRAY_N );\n</code></pre>\n\n<p>this will return the results in the form of a non-associative array, see the wpdb page for more info on the parameters of that function.</p>\n\n<p>This way only one extra DB call is being used to retrieve all the urls for all the posts.</p>\n\n<p><strong>p.s.:</strong> I used <a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"nofollow\">Query Monitor</a> and <a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow\">Debug Bar</a> to analyse the DB queries.</p>\n" }, { "answer_id": 284250, "author": "Zaheer Abbas Aghani", "author_id": 83079, "author_profile": "https://wordpress.stackexchange.com/users/83079", "pm_score": -1, "selected": false, "text": "<p>More clear code to achieve post thumbnail full URL. After getting post thumbnail you just has to use word-press built in method <strong>wp_get_attachment_url( get_post_thumbnail_id( $id ) );</strong> to achieve full URL.</p>\n\n<p>global $wpdb;</p>\n\n<pre><code> $to = \"2017/10/25\";\n $from = \"2017/10/27\";\n $tablename = $wpdb-&gt;prefix . \"posts\";\n $sql = $wpdb-&gt;prepare( \"SELECT * FROM $tablename \n /*JOIN $wpdb-&gt;term_relationships tr ON (p.ID = tr.object_id)\n JOIN $wpdb-&gt;term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)\n JOIN $wpdb-&gt;terms t ON (tt.term_id = t.term_id)*/\n Where post_type =%s AND post_date BETWEEN %s AND %s \",'post',$to, $from);\n $results = $wpdb-&gt;get_results( $sql , ARRAY_A );\n //print_r($results);\n foreach ( $results as $post )\n {\n\n $id = $post['ID'];\n //echo $post['parent'].'&lt;br/&gt;';\n echo wp_get_attachment_url( get_post_thumbnail_id( $id ) );\n\n\n }\n</code></pre>\n" } ]
2015/01/08
[ "https://wordpress.stackexchange.com/questions/174308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34517/" ]
I have a list of post ids and need to get all the standard data plus the thumbnail of the posts. As there will be several hundred posts i need an efficient way to retrieve the data, just looping over all the ids and using has\_thummbnail... and all the other versions of the same 'one by one' approach will just not work fast enough. **So the question is:** how can i retrieve multiple post with their thumbnail url without making one query for each id **UPDATE:** As cybmeta pointed out with the linked posts, [get\_post\_meta](http://codex.wordpress.org/Function_Reference/get_post_meta) does not create an additional DB Query and with that function it is possible to retrieve a post's custom fields. **BUT** that still doesn't give me the URL of the thumbnail, just the thumbnail's ID. When retrieving the URL by one of the possible methods ([wp\_get\_attachment\_image\_src](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src), [wp\_get\_attachment\_metadata](http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata), ...) i create an additional DB Query for each thumbnail as those functions do not take multiple IDs! **More specific question:** How can i retrieve the url of multiple thumbnails via their id in one query
**EXPLANATION** As mentioned in my update above, to retrieve the ID of a thumbnail the [get\_post\_meta](http://codex.wordpress.org/Function_Reference/get_post_meta) function can be used without any additional DB overhead. The 'normal' way to get the url to a thumbnail id is with [wp\_get\_attachment\_image\_src](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src) or similar functions, but those do not accept an array of IDs. What i noticed using *wp\_get\_attachment\_image\_src* was that it created even TWO querys per call (ergo per thumbnail), one to get the post data and then another one for the actual url. **SOLUTION** The only solution i found to retrieve more than one url at the same time was to directly query the DB postmeta table via [wpdb](http://codex.wordpress.org/Class_Reference/wpdb). There is a *postmeta* entry for the relation post->thumbnail with the *meta\_key* *\_thumbnail\_id* and the thumbnails id as the *meta\_value* and then two more entries per thumbnail with the *meta\_tags* *\_wp\_attachment\_metadata* and *\_wp\_attached\_file* and the thumbnail's id as the *post\_id*. So the interesting part of the postmeta table looks like this: ``` meta_id post_id meta_key meta_value 328 136 _wp_attached_file 2015/01/Dog-w-Glasses.jpg 329 136 _wp_attachment_metadata a:5{s:5:"width";i:... ... 335 138 _thumbnail_id 136 ``` with 138 being the post's id and the *meta\_id* being irrelevant for this example. As the *\_thumbnail\_id* was linked to the *post\_id* it could be retrieved via the get\_post\_meta, but as the actual url was stored under the thumbnails id it had to be retrieved seperately. So what i did was retrieving all the thumbnail ids for each post via *get\_post\_meta* and then creating a query to the postmeta table of the WP Database: ``` $thumb_ids = '( 23, 89, 24, 69 )'; // just an example global $wpdb; $qstr = "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE post_id IN " . $thumb_ids. ' AND meta_key = "_wp_attached_file"'; $results = $wpdb->get_results( $qstr, ARRAY_N ); ``` this will return the results in the form of a non-associative array, see the wpdb page for more info on the parameters of that function. This way only one extra DB call is being used to retrieve all the urls for all the posts. **p.s.:** I used [Query Monitor](https://wordpress.org/plugins/query-monitor/) and [Debug Bar](https://wordpress.org/plugins/debug-bar/) to analyse the DB queries.
174,333
<p>I am making some changes to a custom WP template and have hit an odd issue. Published posts work absolutely fine, but when you view a scheduled post the Featured Image disappears.</p> <p>It's as if there was no featured image at all and <code>has_post_thumbnail()</code> returns false. Here's the relevant piece of code I'm working with, relatively simple stuff really:</p> <pre><code>while (have_posts()) : the_post(); if (has_post_thumbnail($post-&gt;ID)) { $featuredImage = wp_get_attachment_url(get_post_thumbnail_id($post-&gt;ID)); } } </code></pre> <p>And again, this works fine on published posts but as soon as I set the date to the future the image stops coming through. It seems strange that images would be treated differently based on the publish date, is there anything which WP changes on scheduled posts vs live posts which could be causing this?</p>
[ { "answer_id": 174352, "author": "Irfan", "author_id": 65344, "author_profile": "https://wordpress.stackexchange.com/users/65344", "pm_score": -1, "selected": false, "text": "<p>Its too much simple</p>\n\n<pre><code>while (have_posts()) : the_post();\n if (has_post_thumbnail($post-&gt;ID)) {\n $featuredImage = wp_get_attachment_image_src(get_post_thumbnail_id($post-&gt;ID,'full'));\n echo $featuredImage;\n }\n}\n</code></pre>\n" }, { "answer_id": 174930, "author": "Andrew", "author_id": 49386, "author_profile": "https://wordpress.stackexchange.com/users/49386", "pm_score": 1, "selected": true, "text": "<p>Well it turns out that the reason <code>has_post_thumbnail()</code> was failing was because <code>get_post_meta()</code> was returning empty for scheduled posts. I'm still not sure why, but in case someone else has the issue, my workaround was to create a new function to fetch the featured image ID without relying on <code>get_post_meta()</code>:</p>\n\n<pre><code>function get_featured_image_id($postID) {\n global $wpdb;\n $data = $wpdb-&gt;get_results($wpdb-&gt;prepare(\"SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = '_thumbnail_id'\", $postID));\n if (!empty($data[0]-&gt;meta_value)) {\n return $data[0]-&gt;meta_value;\n }\n}\n</code></pre>\n\n<p>Then you can get a featured image URL in your template with the following line:</p>\n\n<pre><code>wp_get_attachment_url(get_featured_image_id($post-&gt;ID))\n</code></pre>\n" } ]
2015/01/09
[ "https://wordpress.stackexchange.com/questions/174333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49386/" ]
I am making some changes to a custom WP template and have hit an odd issue. Published posts work absolutely fine, but when you view a scheduled post the Featured Image disappears. It's as if there was no featured image at all and `has_post_thumbnail()` returns false. Here's the relevant piece of code I'm working with, relatively simple stuff really: ``` while (have_posts()) : the_post(); if (has_post_thumbnail($post->ID)) { $featuredImage = wp_get_attachment_url(get_post_thumbnail_id($post->ID)); } } ``` And again, this works fine on published posts but as soon as I set the date to the future the image stops coming through. It seems strange that images would be treated differently based on the publish date, is there anything which WP changes on scheduled posts vs live posts which could be causing this?
Well it turns out that the reason `has_post_thumbnail()` was failing was because `get_post_meta()` was returning empty for scheduled posts. I'm still not sure why, but in case someone else has the issue, my workaround was to create a new function to fetch the featured image ID without relying on `get_post_meta()`: ``` function get_featured_image_id($postID) { global $wpdb; $data = $wpdb->get_results($wpdb->prepare("SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = '_thumbnail_id'", $postID)); if (!empty($data[0]->meta_value)) { return $data[0]->meta_value; } } ``` Then you can get a featured image URL in your template with the following line: ``` wp_get_attachment_url(get_featured_image_id($post->ID)) ```
174,369
<p>is there any way to add "follow" functionality to Wordpress ?</p> <p>so that every logged-in user can follow his favorite author</p> <p>and only can see post from authors that he followed them ..</p> <p>A possible solution would be that if a logged-in user (call it user #1) is clicking "follow" on another user's profile (call it user #2), you record user #2's ID as meta data on user #1. You can do this via the update_user_meta function. You can then retrieve posts from user #2 by using WP_Query with an author parameter. The author parameter can be an array, so you can get the posts of multiple users that way</p> <p>and maybe if we make this idea as a function called : "is_followed" which return True and False Then we can use it in index.php page in the following line :</p> <pre><code>&lt;?php if( have_posts() ) : ?&gt; &lt;div class="entries"&gt; &lt;?php while( have_posts() ) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>to be something like this:</p> <pre><code>&lt;?php if( have_posts() ) : ?&gt; &lt;div class="entries"&gt; &lt;?php while( have_posts() &amp; is_followed ) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>Sorry I don't know how to write codes :(</p> <p>I found a free plugin called: "User profiles" that can create a profile for each author: <a href="https://wordpress.org/plugins/user-profile/" rel="nofollow">https://wordpress.org/plugins/user-profile/</a> so that we can put the follow button in it :/</p>
[ { "answer_id": 174352, "author": "Irfan", "author_id": 65344, "author_profile": "https://wordpress.stackexchange.com/users/65344", "pm_score": -1, "selected": false, "text": "<p>Its too much simple</p>\n\n<pre><code>while (have_posts()) : the_post();\n if (has_post_thumbnail($post-&gt;ID)) {\n $featuredImage = wp_get_attachment_image_src(get_post_thumbnail_id($post-&gt;ID,'full'));\n echo $featuredImage;\n }\n}\n</code></pre>\n" }, { "answer_id": 174930, "author": "Andrew", "author_id": 49386, "author_profile": "https://wordpress.stackexchange.com/users/49386", "pm_score": 1, "selected": true, "text": "<p>Well it turns out that the reason <code>has_post_thumbnail()</code> was failing was because <code>get_post_meta()</code> was returning empty for scheduled posts. I'm still not sure why, but in case someone else has the issue, my workaround was to create a new function to fetch the featured image ID without relying on <code>get_post_meta()</code>:</p>\n\n<pre><code>function get_featured_image_id($postID) {\n global $wpdb;\n $data = $wpdb-&gt;get_results($wpdb-&gt;prepare(\"SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = '_thumbnail_id'\", $postID));\n if (!empty($data[0]-&gt;meta_value)) {\n return $data[0]-&gt;meta_value;\n }\n}\n</code></pre>\n\n<p>Then you can get a featured image URL in your template with the following line:</p>\n\n<pre><code>wp_get_attachment_url(get_featured_image_id($post-&gt;ID))\n</code></pre>\n" } ]
2015/01/09
[ "https://wordpress.stackexchange.com/questions/174369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65758/" ]
is there any way to add "follow" functionality to Wordpress ? so that every logged-in user can follow his favorite author and only can see post from authors that he followed them .. A possible solution would be that if a logged-in user (call it user #1) is clicking "follow" on another user's profile (call it user #2), you record user #2's ID as meta data on user #1. You can do this via the update\_user\_meta function. You can then retrieve posts from user #2 by using WP\_Query with an author parameter. The author parameter can be an array, so you can get the posts of multiple users that way and maybe if we make this idea as a function called : "is\_followed" which return True and False Then we can use it in index.php page in the following line : ``` <?php if( have_posts() ) : ?> <div class="entries"> <?php while( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php endif; ?> ``` to be something like this: ``` <?php if( have_posts() ) : ?> <div class="entries"> <?php while( have_posts() & is_followed ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php endif; ?> ``` Sorry I don't know how to write codes :( I found a free plugin called: "User profiles" that can create a profile for each author: <https://wordpress.org/plugins/user-profile/> so that we can put the follow button in it :/
Well it turns out that the reason `has_post_thumbnail()` was failing was because `get_post_meta()` was returning empty for scheduled posts. I'm still not sure why, but in case someone else has the issue, my workaround was to create a new function to fetch the featured image ID without relying on `get_post_meta()`: ``` function get_featured_image_id($postID) { global $wpdb; $data = $wpdb->get_results($wpdb->prepare("SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = '_thumbnail_id'", $postID)); if (!empty($data[0]->meta_value)) { return $data[0]->meta_value; } } ``` Then you can get a featured image URL in your template with the following line: ``` wp_get_attachment_url(get_featured_image_id($post->ID)) ```
174,402
<p>When creating meta boxes, in each meta box function it seems a reference to the <code>global $post</code> is passed as a parameter <code>($event)</code>. I prefer this as it seems consistent and less likely to fudge the <code>$post</code> var by declaring it explicitly as I have read elsewhere.</p> <pre><code>add_action('admin_init', 'events_admin'); function events_admin() { add_meta_box('display_events_date_meta_box', 'Dates', 'display_events_date_meta_box', 'events', 'normal', 'high' ); } function display_events_date_meta_box($event) // Referenced { //$event in this case is the $post global } </code></pre> <p>I have created a filter and various other functions which currently just use the <code>global $post</code> variable.</p> <pre><code>add_action( 'admin_head-post-new.php', 'test' ); add_action( 'admin_head-post.php', 'test' ); function test() { global $post; // Declared explicitly } </code></pre> <p>Is there a standard / recommended way to pass the <code>global $post</code> variable as a parameter to these functions? </p>
[ { "answer_id": 174451, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p><code>admin_head-{$hook_suffix}</code> is triggered on every admin page, so passing anything to that function probably wouldn't make sense. You can see in source that no arguments are passed:</p>\n\n<pre><code>do_action( \"admin_head-$hook_suffix\" );\n</code></pre>\n\n<p>In many cases you have no alternative to <code>global $post</code>, and if you look through just about any core source file, you'll see <code>global</code> litter everywhere, due to the mostly procedural construction of core and a primary objective to maintain backward compatibility. It's messy but mostly harmless <strong>if you're just accessing its value within a known context</strong>.</p>\n" }, { "answer_id": 174455, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You can not easily modify the parameters used with an existing filter/action as they are set by the \"calling\" code, therefor you can't inject additional parameters. There might be some possibility to do that by hacking the core code behind do_action/apply_filter but if you will succeed you most likely will break all the other code that hooks on those actions/filters.</p>\n" }, { "answer_id": 174478, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<p>When I need to deal with <code>$post</code> variable on admin, I usually use a class to early catch and wrap global <code>$post</code> variable, obtaining an <em>universal</em> way to access to it, without repetitely relying on the global variable.</p>\n\n<pre><code>class MyAdminPost \n{\n\n private static $post;\n\n public static function init()\n {\n $p_get = filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT);\n $p_post = filter_input(INPUT_POST, 'post', FILTER_SANITIZE_NUMBER_INT);\n if ($p_get &gt; 0 || $p_post &gt; 0) {\n self::$post = $p_get &gt; 0 ? get_post($p_get) : get_post($p_post);\n } elseif ($GLOBALS['pagenow'] === 'post-new.php') {\n add_action('new_to_auto-draft', function(\\WP_Post $post) {\n if (is_null(MyAdminPost::$post)) {\n MyAdminPost::$post = $post;\n }\n }, 0);\n }\n }\n\n public function get()\n {\n return self::$post;\n }\n}\n\nadd_action('admin_init', array('MyAdminPost', 'init'));\n</code></pre>\n\n<p>On early stage of admin loading, that is <code>'admin_init'</code> hook, <code>'MyAdminPost'</code> class looks for post ID variable sent with request and store related post object.</p>\n\n<p>That works on <code>post.php</code> page, but not on <code>post-new.php</code>, because on that page post ID is not sent with request because it does't exist yet. In that case I add a callback to <code>'new_to_auto-draft'</code> that is one the <a href=\"https://developer.wordpress.org/reference/hooks/old_status_to_new_status/\" rel=\"nofollow\"><code>\"{old_status}_to_{new_status}\"</code></a> hooks to store the post immediately after it is created on <code>post-new.php</code> page.</p>\n\n<p>In this way, in both pages, post object is stored in a class property very early.</p>\n\n<h1>Usage Example (Procedural)</h1>\n\n<pre><code>function get_my_admin_post()\n{\n static $post = null;\n if (is_null($post) &amp;&amp; did_action('admin_init')) {\n $map = new MyAdminPost();\n $post = $map-&gt;get(); \n }\n\n return $post;\n}\n\nadd_action('admin_head-post.php', 'test');\n\nfunction test()\n{\n $post = get_my_admin_post();\n}\n</code></pre>\n\n<h1>Usage Example (OOP)</h1>\n\n<pre><code>class ClassThatUsesPostObject\n{\n\n private $post_provider;\n\n function __construct(MyAdminPost $map)\n {\n $this-&gt;post_provider = $map;\n }\n\n function doSomethingWithPost()\n {\n $post = $this-&gt;post_provider-&gt;get();\n }\n}\n</code></pre>\n\n<h1>Benefits</h1>\n\n<ul>\n<li><p>you can obtain post object very early in a way that is compatible to both <code>post.php</code> and <code>post-new.php</code> pages, so in <strong>all</strong> the hooks fired in those pages you have access to post object with no effort</p></li>\n<li><p>you remove any global <code>$post</code> variable reference in your code</p></li>\n<li><p>your code becomes testable in isolation</p></li>\n</ul>\n" } ]
2015/01/09
[ "https://wordpress.stackexchange.com/questions/174402", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51823/" ]
When creating meta boxes, in each meta box function it seems a reference to the `global $post` is passed as a parameter `($event)`. I prefer this as it seems consistent and less likely to fudge the `$post` var by declaring it explicitly as I have read elsewhere. ``` add_action('admin_init', 'events_admin'); function events_admin() { add_meta_box('display_events_date_meta_box', 'Dates', 'display_events_date_meta_box', 'events', 'normal', 'high' ); } function display_events_date_meta_box($event) // Referenced { //$event in this case is the $post global } ``` I have created a filter and various other functions which currently just use the `global $post` variable. ``` add_action( 'admin_head-post-new.php', 'test' ); add_action( 'admin_head-post.php', 'test' ); function test() { global $post; // Declared explicitly } ``` Is there a standard / recommended way to pass the `global $post` variable as a parameter to these functions?
When I need to deal with `$post` variable on admin, I usually use a class to early catch and wrap global `$post` variable, obtaining an *universal* way to access to it, without repetitely relying on the global variable. ``` class MyAdminPost { private static $post; public static function init() { $p_get = filter_input(INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT); $p_post = filter_input(INPUT_POST, 'post', FILTER_SANITIZE_NUMBER_INT); if ($p_get > 0 || $p_post > 0) { self::$post = $p_get > 0 ? get_post($p_get) : get_post($p_post); } elseif ($GLOBALS['pagenow'] === 'post-new.php') { add_action('new_to_auto-draft', function(\WP_Post $post) { if (is_null(MyAdminPost::$post)) { MyAdminPost::$post = $post; } }, 0); } } public function get() { return self::$post; } } add_action('admin_init', array('MyAdminPost', 'init')); ``` On early stage of admin loading, that is `'admin_init'` hook, `'MyAdminPost'` class looks for post ID variable sent with request and store related post object. That works on `post.php` page, but not on `post-new.php`, because on that page post ID is not sent with request because it does't exist yet. In that case I add a callback to `'new_to_auto-draft'` that is one the [`"{old_status}_to_{new_status}"`](https://developer.wordpress.org/reference/hooks/old_status_to_new_status/) hooks to store the post immediately after it is created on `post-new.php` page. In this way, in both pages, post object is stored in a class property very early. Usage Example (Procedural) ========================== ``` function get_my_admin_post() { static $post = null; if (is_null($post) && did_action('admin_init')) { $map = new MyAdminPost(); $post = $map->get(); } return $post; } add_action('admin_head-post.php', 'test'); function test() { $post = get_my_admin_post(); } ``` Usage Example (OOP) =================== ``` class ClassThatUsesPostObject { private $post_provider; function __construct(MyAdminPost $map) { $this->post_provider = $map; } function doSomethingWithPost() { $post = $this->post_provider->get(); } } ``` Benefits ======== * you can obtain post object very early in a way that is compatible to both `post.php` and `post-new.php` pages, so in **all** the hooks fired in those pages you have access to post object with no effort * you remove any global `$post` variable reference in your code * your code becomes testable in isolation
174,403
<p>I'd like my homepage to only display posts from a single tag. Is this possible? If yes, please advise.</p> <p>For instance,</p> <blockquote> <p>www.mysite.com/tag/sometag </p> </blockquote> <p>will only display posts with the <code>sometag</code> tag, but how do I get www.mysite.com to automatically display only the posts seen on</p> <blockquote> <p>www.mysite.com/tag/sometag page?</p> </blockquote>
[ { "answer_id": 174411, "author": "Mohammad Mursaleen", "author_id": 35899, "author_profile": "https://wordpress.stackexchange.com/users/35899", "pm_score": 0, "selected": false, "text": "<p>For that; first you have to make <a href=\"http://codex.wordpress.org/Tag_Templates\" rel=\"nofollow\">Custom Page template</a> and add following <a href=\"http://codex.wordpress.org/The_Loop\" rel=\"nofollow\">loop</a> in it and customize it in what ever way you want.</p>\n\n<pre><code>&lt;?php\n\n $args=array(\n 'tag' =&gt; 'yourtag',\n 'showposts'=&gt;5 // set number of post you want to display\n );\n $my_query = new WP_Query($args);\n if( $my_query-&gt;have_posts() ) {\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt;\n\n &lt;p&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"Permanent Link to &lt;?php the_title_attribute(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt;\n\n // display what ever you want in this post\n\n &lt;?php\n endwhile;\n }\n wp_reset_query(); // Restore global post data stomped by the_post().\n?&gt;\n</code></pre>\n\n<p>Then <a href=\"http://codex.wordpress.org/Pages\" rel=\"nofollow\">create a Page</a> and <a href=\"http://codex.wordpress.org/Page_Templates#Selecting_a_Page_Template\" rel=\"nofollow\">select this custom page template</a> for it.</p>\n\n<p>Next from settings <a href=\"http://codex.wordpress.org/Creating_a_Static_Front_Page#WordPress_Static_Front_Page_Process\" rel=\"nofollow\">set this page as static home page</a> and you are ready to GO.</p>\n" }, { "answer_id": 174413, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You should use <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"noreferrer\"><code>pre_get_posts</code></a> to alter the main query on the home page. </p>\n\n<p>With the proper conditional tags and parameters (check <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code></a> for available parameters) you can achieve what you need</p>\n\n<p>You can do the following to just display posts from a given tag on your homepage</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $query ) {\n if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'tag', 'SLUG_OF_TAG' );\n }\n});\n</code></pre>\n" }, { "answer_id": 301097, "author": "Zbigniew", "author_id": 141981, "author_profile": "https://wordpress.stackexchange.com/users/141981", "pm_score": -1, "selected": false, "text": "<p>Custom wp queries will work perfectly, but in many cases pagination or a other elements gone or be \"broken\".</p>\n\n<p>I use a not a ideal but \"simplest\" way: 301 redirection in Custom Page template for a orginal WP tag page.</p>\n\n<p>Example piece of code:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Your Custom Redirect Name\n */\nheader(\"HTTP/1.1 301 Moved Permanently\");\nheader(\"Location: hxxp://yoursite.com/tag/your-tag-slug/\");\n ?&gt;\n</code></pre>\n" } ]
2015/01/09
[ "https://wordpress.stackexchange.com/questions/174403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64181/" ]
I'd like my homepage to only display posts from a single tag. Is this possible? If yes, please advise. For instance, > > www.mysite.com/tag/sometag > > > will only display posts with the `sometag` tag, but how do I get www.mysite.com to automatically display only the posts seen on > > www.mysite.com/tag/sometag > page? > > >
You should use [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to alter the main query on the home page. With the proper conditional tags and parameters (check [`WP_Query`](http://codex.wordpress.org/Class_Reference/WP_Query) for available parameters) you can achieve what you need You can do the following to just display posts from a given tag on your homepage ``` add_action( 'pre_get_posts', function ( $query ) { if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'tag', 'SLUG_OF_TAG' ); } }); ```
174,412
<p>I am using a plugin called The Events Calendar. I don't always set the featured image for each individual event. Each event has an organizer ID (tribe_get_organizer_id).</p> <p>I want to add a filter that looks if an event from a custom post type (tribe_events) has a featured image attached. If not, than the filter should call up the organizer and assign the organizer's featured image as the event's featured image.</p> <p>I'm not even sure with what hook to start. Something like this?</p> <pre><code> function set_featured_event_image () { if ( get_post_type() == 'tribe_events') { if ( has_post_thumbnail() ) { the_post_thumbnail(); } else { GRAB THE IMAGE FROM THE RELATED ORGANIZER } } } add_filter( '**WHAT HOOK?**', 'set_featured_event_image'); </code></pre> <p>I might be terribly off with any of this. Any help in the right direction is appreciated.</p>
[ { "answer_id": 174411, "author": "Mohammad Mursaleen", "author_id": 35899, "author_profile": "https://wordpress.stackexchange.com/users/35899", "pm_score": 0, "selected": false, "text": "<p>For that; first you have to make <a href=\"http://codex.wordpress.org/Tag_Templates\" rel=\"nofollow\">Custom Page template</a> and add following <a href=\"http://codex.wordpress.org/The_Loop\" rel=\"nofollow\">loop</a> in it and customize it in what ever way you want.</p>\n\n<pre><code>&lt;?php\n\n $args=array(\n 'tag' =&gt; 'yourtag',\n 'showposts'=&gt;5 // set number of post you want to display\n );\n $my_query = new WP_Query($args);\n if( $my_query-&gt;have_posts() ) {\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt;\n\n &lt;p&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"Permanent Link to &lt;?php the_title_attribute(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt;\n\n // display what ever you want in this post\n\n &lt;?php\n endwhile;\n }\n wp_reset_query(); // Restore global post data stomped by the_post().\n?&gt;\n</code></pre>\n\n<p>Then <a href=\"http://codex.wordpress.org/Pages\" rel=\"nofollow\">create a Page</a> and <a href=\"http://codex.wordpress.org/Page_Templates#Selecting_a_Page_Template\" rel=\"nofollow\">select this custom page template</a> for it.</p>\n\n<p>Next from settings <a href=\"http://codex.wordpress.org/Creating_a_Static_Front_Page#WordPress_Static_Front_Page_Process\" rel=\"nofollow\">set this page as static home page</a> and you are ready to GO.</p>\n" }, { "answer_id": 174413, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You should use <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"noreferrer\"><code>pre_get_posts</code></a> to alter the main query on the home page. </p>\n\n<p>With the proper conditional tags and parameters (check <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code></a> for available parameters) you can achieve what you need</p>\n\n<p>You can do the following to just display posts from a given tag on your homepage</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $query ) {\n if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'tag', 'SLUG_OF_TAG' );\n }\n});\n</code></pre>\n" }, { "answer_id": 301097, "author": "Zbigniew", "author_id": 141981, "author_profile": "https://wordpress.stackexchange.com/users/141981", "pm_score": -1, "selected": false, "text": "<p>Custom wp queries will work perfectly, but in many cases pagination or a other elements gone or be \"broken\".</p>\n\n<p>I use a not a ideal but \"simplest\" way: 301 redirection in Custom Page template for a orginal WP tag page.</p>\n\n<p>Example piece of code:</p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Your Custom Redirect Name\n */\nheader(\"HTTP/1.1 301 Moved Permanently\");\nheader(\"Location: hxxp://yoursite.com/tag/your-tag-slug/\");\n ?&gt;\n</code></pre>\n" } ]
2015/01/09
[ "https://wordpress.stackexchange.com/questions/174412", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65779/" ]
I am using a plugin called The Events Calendar. I don't always set the featured image for each individual event. Each event has an organizer ID (tribe\_get\_organizer\_id). I want to add a filter that looks if an event from a custom post type (tribe\_events) has a featured image attached. If not, than the filter should call up the organizer and assign the organizer's featured image as the event's featured image. I'm not even sure with what hook to start. Something like this? ``` function set_featured_event_image () { if ( get_post_type() == 'tribe_events') { if ( has_post_thumbnail() ) { the_post_thumbnail(); } else { GRAB THE IMAGE FROM THE RELATED ORGANIZER } } } add_filter( '**WHAT HOOK?**', 'set_featured_event_image'); ``` I might be terribly off with any of this. Any help in the right direction is appreciated.
You should use [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to alter the main query on the home page. With the proper conditional tags and parameters (check [`WP_Query`](http://codex.wordpress.org/Class_Reference/WP_Query) for available parameters) you can achieve what you need You can do the following to just display posts from a given tag on your homepage ``` add_action( 'pre_get_posts', function ( $query ) { if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'tag', 'SLUG_OF_TAG' ); } }); ```
174,447
<p>Is there a way to get all users that: 1) uploaded an avatar or 2) have a Gravatar? I want to filter users that doesn't meet one of these conditions.</p> <p><strong>UPDATE</strong></p> <p>I forget to mention that this is for Buddypress. Anyway, I found an answer for the first condition, this is the <code>bp_get_user_has_avatar()</code> function that checks if a given user ID has an uploaded avatar.</p> <p>Now I need only a Gravatar validation for the second condition.</p>
[ { "answer_id": 174448, "author": "Brandt Solovij", "author_id": 38927, "author_profile": "https://wordpress.stackexchange.com/users/38927", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/get_avatar</a></p>\n\n<p>run a user lookup and qualify via <code>get_avatar</code></p>\n" }, { "answer_id": 174469, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 2, "selected": true, "text": "<p>This function <code>bp_get_user_has_avatar()</code> calls <code>bp_core_fetch_avatar</code> with this argument <code>'no_grav' =&gt; true</code> so you could write your own function to see if a user is not using the default avatar: </p>\n\n<pre><code>function lurie_avatar_check( $user_id ) {\n $retval = false;\n\n if ( bp_core_fetch_avatar( array( 'item_id' =&gt; $user_id, 'no_grav' =&gt; false, 'html' =&gt; false ) ) != bp_core_avatar_default( 'local' ) )\n $retval = true;\n\n return $retval;\n}\n</code></pre>\n" } ]
2015/01/10
[ "https://wordpress.stackexchange.com/questions/174447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
Is there a way to get all users that: 1) uploaded an avatar or 2) have a Gravatar? I want to filter users that doesn't meet one of these conditions. **UPDATE** I forget to mention that this is for Buddypress. Anyway, I found an answer for the first condition, this is the `bp_get_user_has_avatar()` function that checks if a given user ID has an uploaded avatar. Now I need only a Gravatar validation for the second condition.
This function `bp_get_user_has_avatar()` calls `bp_core_fetch_avatar` with this argument `'no_grav' => true` so you could write your own function to see if a user is not using the default avatar: ``` function lurie_avatar_check( $user_id ) { $retval = false; if ( bp_core_fetch_avatar( array( 'item_id' => $user_id, 'no_grav' => false, 'html' => false ) ) != bp_core_avatar_default( 'local' ) ) $retval = true; return $retval; } ```
174,480
<p>I created a style sheet </p> <blockquote> <p>editor-style.css</p> </blockquote> <p>I want to load this css file using add_editor_style() function, </p> <p>In my functions.php</p> <pre><code>function my_theme_add_editor_styles() { add_editor_style( 'css/editor-style.css' ); } add_action( 'after_setup_theme', 'my_theme_add_editor_styles' ); </code></pre> <p>I also tried this solution</p> <p><a href="https://wordpress.stackexchange.com/questions/87256/add-editor-style-is-not-loading-in-frontend-any-solution">add_editor_style is not loading in frontend. Any solution?</a></p>
[ { "answer_id": 174482, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": 4, "selected": true, "text": "<p>You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php:</p>\n\n<pre><code>add_editor_style('css/editor-style.css');\n</code></pre>\n" }, { "answer_id": 242328, "author": "Jake", "author_id": 11966, "author_profile": "https://wordpress.stackexchange.com/users/11966", "pm_score": 2, "selected": false, "text": "<p>Use an absolute path for the stylesheet:</p>\n\n<pre><code>add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n</code></pre>\n" }, { "answer_id": 351479, "author": "Willster", "author_id": 33705, "author_profile": "https://wordpress.stackexchange.com/users/33705", "pm_score": 4, "selected": false, "text": "<p>You need to do two things (see additional add_theme_support):</p>\n<pre><code>add_theme_support( 'editor-styles' );\nadd_action('admin_init', 'el_add_editor_styles');\n\nfunction el_add_editor_styles() {\n add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n}\n</code></pre>\n" } ]
2015/01/10
[ "https://wordpress.stackexchange.com/questions/174480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64198/" ]
I created a style sheet > > editor-style.css > > > I want to load this css file using add\_editor\_style() function, In my functions.php ``` function my_theme_add_editor_styles() { add_editor_style( 'css/editor-style.css' ); } add_action( 'after_setup_theme', 'my_theme_add_editor_styles' ); ``` I also tried this solution [add\_editor\_style is not loading in frontend. Any solution?](https://wordpress.stackexchange.com/questions/87256/add-editor-style-is-not-loading-in-frontend-any-solution)
You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php: ``` add_editor_style('css/editor-style.css'); ```
174,485
<p>so I am trying to use a foreach to pull content from a custom field in multiple posts, but it just wont work. I can get it to work for a simple textarea string but I am struggling getting it to work for arrays. This is the working code for a string:</p> <pre><code>$posts = get_posts(array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'post',)); foreach($posts as $post) { $string = get_post_meta($post-&gt;ID, 'simple_string', true); echo $string; } </code></pre> <p>And elsewhere in the site this code works for getting into a specific posts custom field array:</p> <pre><code>$arr = get_field('array'); $arr2 = $arr[0]['string']; $string = implode(", ",$arr2); echo $string; </code></pre> <p>Why doesn't this work?</p> <pre><code>$posts = get_posts(array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'post',)); foreach($posts as $post) { $arr = get_post_meta($post-&gt;ID, 'array', true); $arr2 = $arr[0]['string']; $string = implode(", ",$arr2); echo $string; } </code></pre> <p>Thanks in advance for taking a look.</p>
[ { "answer_id": 174482, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": 4, "selected": true, "text": "<p>You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php:</p>\n\n<pre><code>add_editor_style('css/editor-style.css');\n</code></pre>\n" }, { "answer_id": 242328, "author": "Jake", "author_id": 11966, "author_profile": "https://wordpress.stackexchange.com/users/11966", "pm_score": 2, "selected": false, "text": "<p>Use an absolute path for the stylesheet:</p>\n\n<pre><code>add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n</code></pre>\n" }, { "answer_id": 351479, "author": "Willster", "author_id": 33705, "author_profile": "https://wordpress.stackexchange.com/users/33705", "pm_score": 4, "selected": false, "text": "<p>You need to do two things (see additional add_theme_support):</p>\n<pre><code>add_theme_support( 'editor-styles' );\nadd_action('admin_init', 'el_add_editor_styles');\n\nfunction el_add_editor_styles() {\n add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n}\n</code></pre>\n" } ]
2015/01/10
[ "https://wordpress.stackexchange.com/questions/174485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37486/" ]
so I am trying to use a foreach to pull content from a custom field in multiple posts, but it just wont work. I can get it to work for a simple textarea string but I am struggling getting it to work for arrays. This is the working code for a string: ``` $posts = get_posts(array( 'numberposts' => -1, 'post_type' => 'post',)); foreach($posts as $post) { $string = get_post_meta($post->ID, 'simple_string', true); echo $string; } ``` And elsewhere in the site this code works for getting into a specific posts custom field array: ``` $arr = get_field('array'); $arr2 = $arr[0]['string']; $string = implode(", ",$arr2); echo $string; ``` Why doesn't this work? ``` $posts = get_posts(array( 'numberposts' => -1, 'post_type' => 'post',)); foreach($posts as $post) { $arr = get_post_meta($post->ID, 'array', true); $arr2 = $arr[0]['string']; $string = implode(", ",$arr2); echo $string; } ``` Thanks in advance for taking a look.
You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php: ``` add_editor_style('css/editor-style.css'); ```
174,502
<p>Something is going wrong when I try to use the bootstrap nav with a child theme and I can't figure it out for the life of me. </p> <p>The parent theme is called Revera.</p> <p>This is a bootstrap theme. It includes bootstrap.min.js and bootstrap.min.css files. However, the version used appears old and I think it is what is causing the bootstrap Navbar I added to not quite work (it seems to function, but the styling isn't right. The three bars for the mobile menu are missing and the word "Toggle Navigation" shows up inside the nav button) .</p> <p>What I would like to do is use an updated version of bootstrap with a child theme. But every way I've tried to achieve this doesn't seem to work. In the functions.php of the child theme I have:</p> <pre><code>function enqueue_child_theme_styles() { wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.min.js', array('jquery'), NULL, true ); wp_register_style( 'bootstrap-css', get_template_directory_uri() . '/bootstrap/css/bootstrap.min.css', false, NULL, 'all' ); wp_enqueue_script( 'bootstrap-js' ); wp_enqueue_style( 'bootstrap-css' ); } add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX); </code></pre> <p>The above code doesn't seem to do anything however. I've tried all kinds of things to try and troubleshoot this, but nothing seems to work. What am I missing?</p>
[ { "answer_id": 174482, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": 4, "selected": true, "text": "<p>You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php:</p>\n\n<pre><code>add_editor_style('css/editor-style.css');\n</code></pre>\n" }, { "answer_id": 242328, "author": "Jake", "author_id": 11966, "author_profile": "https://wordpress.stackexchange.com/users/11966", "pm_score": 2, "selected": false, "text": "<p>Use an absolute path for the stylesheet:</p>\n\n<pre><code>add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n</code></pre>\n" }, { "answer_id": 351479, "author": "Willster", "author_id": 33705, "author_profile": "https://wordpress.stackexchange.com/users/33705", "pm_score": 4, "selected": false, "text": "<p>You need to do two things (see additional add_theme_support):</p>\n<pre><code>add_theme_support( 'editor-styles' );\nadd_action('admin_init', 'el_add_editor_styles');\n\nfunction el_add_editor_styles() {\n add_editor_style( get_template_directory_uri() . '/css/editor-style.css' );\n}\n</code></pre>\n" } ]
2015/01/11
[ "https://wordpress.stackexchange.com/questions/174502", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65830/" ]
Something is going wrong when I try to use the bootstrap nav with a child theme and I can't figure it out for the life of me. The parent theme is called Revera. This is a bootstrap theme. It includes bootstrap.min.js and bootstrap.min.css files. However, the version used appears old and I think it is what is causing the bootstrap Navbar I added to not quite work (it seems to function, but the styling isn't right. The three bars for the mobile menu are missing and the word "Toggle Navigation" shows up inside the nav button) . What I would like to do is use an updated version of bootstrap with a child theme. But every way I've tried to achieve this doesn't seem to work. In the functions.php of the child theme I have: ``` function enqueue_child_theme_styles() { wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.min.js', array('jquery'), NULL, true ); wp_register_style( 'bootstrap-css', get_template_directory_uri() . '/bootstrap/css/bootstrap.min.css', false, NULL, 'all' ); wp_enqueue_script( 'bootstrap-js' ); wp_enqueue_style( 'bootstrap-css' ); } add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX); ``` The above code doesn't seem to do anything however. I've tried all kinds of things to try and troubleshoot this, but nothing seems to work. What am I missing?
You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php: ``` add_editor_style('css/editor-style.css'); ```
174,517
<p>How can group posts by month and year by a separate headline?</p> <p>Example (output with this date format):</p> <p>Dezmber 2014<br> - 4. Dez 2014<br> - 5. Dez 2014</p> <p>I have a custom field (datepicker) "event_date". </p> <pre><code> &lt;?php $the_query = new WP_Query( array( 'post_status' =&gt; 'publish', 'meta_key' =&gt; 'event_date', 'orderby' =&gt; 'meta_value' ) ); $current_header = ''; while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $temp_date = get_post_meta( get_the_ID(), 'event_date', true ); if ( $temp_date != $current_header ) { $current_header = $temp_date; echo "&lt;div class='sub_category_name_wrapper'&gt;&lt;h5&gt;$current_header&lt;/h5&gt;&lt;/div&gt;"; } ?&gt; &lt;div class="event_content_wrapper"&gt; &lt;ul&gt; &lt;li&gt; &lt;span&gt;&lt;?php the_field('event_date'); ?&gt;&lt;/span&gt;&amp;nbsp;&lt;span&gt;&lt;?php the_field('event_region'); ?&gt;&lt;/span&gt; &lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;br&gt; &lt;?php the_excerpt(); ?&gt; &lt;a class="content_button" href="&lt;?php the_permalink(); ?&gt;"&gt;mehr&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 224133, "author": "Fint", "author_id": 92618, "author_profile": "https://wordpress.stackexchange.com/users/92618", "pm_score": 0, "selected": false, "text": "<p>Following the advanced example on <a href=\"https://www.advancedcustomfields.com/resources/date-picker/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/date-picker/</a> this worked for me:</p>\n\n<p>There is a post type called 'event' with two acf custom fields 'event_date_start' and 'event_date_end'.</p>\n\n<p>The query shows all future events from today on and every month gets its title. So you can say the events are grouped by month.\nMaybe this is not exaclty what you are asking for but at least it could be an interesting approach...</p>\n\n<p><strong>March 2017</strong><br>\n- Event 1<br>\n- Event 2<br>\n- Event 3<br>\n<strong>April 2017</strong><br>\n- Event 4<br>\n- Event 5<br>\n...</p>\n\n<pre><code>&lt;?php \n$today = date('Ymd');\n\n\n$args = array(\n 'post_type' =&gt; 'event',\n 'posts_per_page' =&gt; -1,\n 'meta_key' =&gt; 'event_date_start',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'event_date_end' , \n 'compare' =&gt; '&gt;=',\n 'value' =&gt; $today,\n 'type' =&gt; 'date'\n ),\n array(\n 'key' =&gt; 'event_date_start' , \n 'compare' =&gt; '&gt;=',\n 'value' =&gt; $today,\n 'type' =&gt; 'date'\n ),\n\n\n )\n);\n$shows = get_posts($args );\n\n\n$current_header = '';\n\nforeach ($shows as $post ) : setup_postdata($post); \n\n// get raw date\n$date = get_field('event_date_start', false, false);\n\n\n$temp_header = date_i18n('F Y', strtotime($date));\n\nif ( $temp_header != $current_header ) {\n $current_header = $temp_header;\n echo \"&lt;h3&gt;\".$current_header.'&lt;/h3&gt;';\n\n}\n// echo content of event\nget_template_part('templates/content', 'events');\nendforeach; \nwp_reset_postdata();\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 259864, "author": "Laxmana", "author_id": 40948, "author_profile": "https://wordpress.stackexchange.com/users/40948", "pm_score": 3, "selected": false, "text": "<p>When you query the posts with <code>orderby</code> argument as a <code>event_date</code> (it could be any field with date format) the posts are ordered by date, desc or asc. So the only thing you have to do afterwards is to group them by year and month.</p>\n\n<p>So: </p>\n\n<pre><code>&lt;?php\n\n $posts = get_posts(array(\n 'post_type' =&gt; 'post',\n 'meta_key' =&gt; 'event_date',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'DESC'\n ));\n\n $group_posts = array();\n\n if( $posts ) {\n\n foreach( $posts as $post ) {\n\n $date = get_field('event_date', $post-&gt;ID, false);\n\n $date = new DateTime($date);\n\n $year = $date-&gt;format('Y');\n $month = $date-&gt;format('F');\n\n $group_posts[$year][$month][] = array($post, $date);\n\n }\n\n }\n\n foreach ($group_posts as $yearKey =&gt; $years) {\n\n echo $yearKey;\n echo '&lt;br&gt;';\n\n foreach ($years as $monthKey =&gt; $months) {\n\n echo $monthKey;\n echo '&lt;br&gt;';\n\n foreach ($months as $postKey =&gt; $posts) {\n\n echo $posts[1]-&gt;format('d-m-Y');\n echo '&lt;br&gt;';\n echo $posts[0]-&gt;title;\n echo '&lt;br&gt;';\n }\n\n }\n\n }\n\n ?&gt;\n</code></pre>\n\n<p>You can change the year and month format to your desire. This is just a demonstration. The same applies for HTML formatting.</p>\n" } ]
2015/01/11
[ "https://wordpress.stackexchange.com/questions/174517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65842/" ]
How can group posts by month and year by a separate headline? Example (output with this date format): Dezmber 2014 - 4. Dez 2014 - 5. Dez 2014 I have a custom field (datepicker) "event\_date". ``` <?php $the_query = new WP_Query( array( 'post_status' => 'publish', 'meta_key' => 'event_date', 'orderby' => 'meta_value' ) ); $current_header = ''; while ( $the_query->have_posts() ) : $the_query->the_post(); $temp_date = get_post_meta( get_the_ID(), 'event_date', true ); if ( $temp_date != $current_header ) { $current_header = $temp_date; echo "<div class='sub_category_name_wrapper'><h5>$current_header</h5></div>"; } ?> <div class="event_content_wrapper"> <ul> <li> <span><?php the_field('event_date'); ?></span>&nbsp;<span><?php the_field('event_region'); ?></span> <h4><?php the_title(); ?></h4> <br> <?php the_excerpt(); ?> <a class="content_button" href="<?php the_permalink(); ?>">mehr</a> </li> </ul> </div> <?php endwhile; ?> ```
When you query the posts with `orderby` argument as a `event_date` (it could be any field with date format) the posts are ordered by date, desc or asc. So the only thing you have to do afterwards is to group them by year and month. So: ``` <?php $posts = get_posts(array( 'post_type' => 'post', 'meta_key' => 'event_date', 'orderby' => 'meta_value_num', 'order' => 'DESC' )); $group_posts = array(); if( $posts ) { foreach( $posts as $post ) { $date = get_field('event_date', $post->ID, false); $date = new DateTime($date); $year = $date->format('Y'); $month = $date->format('F'); $group_posts[$year][$month][] = array($post, $date); } } foreach ($group_posts as $yearKey => $years) { echo $yearKey; echo '<br>'; foreach ($years as $monthKey => $months) { echo $monthKey; echo '<br>'; foreach ($months as $postKey => $posts) { echo $posts[1]->format('d-m-Y'); echo '<br>'; echo $posts[0]->title; echo '<br>'; } } } ?> ``` You can change the year and month format to your desire. This is just a demonstration. The same applies for HTML formatting.
174,582
<p>The default behavior when it comes to full-width images in posts is this:</p> <ul> <li>If you insert an image alone, this HTML structure is produced: <code>&lt;p&gt;&lt;img/&gt;&lt;/p&gt;</code></li> <li>If you insert an image <strong>with a caption</strong>, the HTML structure is produced: <code>&lt;figure&gt;&lt;img/&gt;&lt;figcaption/&gt;&lt;/figure&gt;</code></li> </ul> <p>For the sake of styling (I want to have larger margin around images compared to standard paragraphs), I'd like to get <code>&lt;figure&gt;</code> in both cases, not just when there is a caption. How to do it?</p> <p><strong>Edit</strong>: one thing I noticed is that the behavior changes as soon as <em>Visual</em> and <em>Text</em> tabs are switched in the editor, i.e., even before previewing or saving the post. Maybe the correct solution would be to somehow force WordPress editor to always use the <code>[caption]</code> shortcode no matter what.</p>
[ { "answer_id": 174585, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>You can try the <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"noreferrer\"><code>image_send_to_editor</code></a> filter:</p>\n\n<pre><code>/**\n * Wrap the inserted image html with &lt;figure&gt; \n * if the theme supports html5 and the current image has no caption:\n */\n\nadd_filter( 'image_send_to_editor', \n function( $html, $id, $caption, $title, $align, $url, $size, $alt ) \n {\n if( current_theme_supports( 'html5' ) &amp;&amp; ! $caption )\n $html = sprintf( '&lt;figure&gt;%s&lt;/figure&gt;', $html ); // Modify to your needs!\n\n return $html;\n }\n, 10, 8 );\n</code></pre>\n\n<p>where you can modify the html of the image when it's inserted into the editor. </p>\n\n<p>I added the check for <code>current_theme_supports( 'html5' )</code> in the above filter, to check if you have something like:</p>\n\n<pre><code>add_theme_support( 'html5', array( ... ) );\n</code></pre>\n\n<p>in your theme. But you might not want to have this filter callback dependent on your current theme, so you can remove it if you want.</p>\n\n<p>You could also try out the <a href=\"https://developer.wordpress.org/reference/hooks/get_image_tag/\" rel=\"noreferrer\"><code>get_image_tag</code></a> filter.</p>\n\n<p><strong>Update</strong>: Here's the useful unautop function from @bueltge's comment (for better readability):</p>\n\n<pre><code>// unautop for images \nfunction fb_unautop_4_img( $content )\n{ \n $content = preg_replace( \n '/&lt;p&gt;\\\\s*?(&lt;a rel=\\\"attachment.*?&gt;&lt;img.*?&gt;&lt;\\\\/a&gt;|&lt;img.*?&gt;)?\\\\s*&lt;\\\\/p&gt;/s', \n '&lt;figure&gt;$1&lt;/figure&gt;', \n $content \n ); \n return $content; \n} \nadd_filter( 'the_content', 'fb_unautop_4_img', 99 );\n</code></pre>\n" }, { "answer_id": 292729, "author": "powerbuoy", "author_id": 23714, "author_profile": "https://wordpress.stackexchange.com/users/23714", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question with an accepted answer, but I used the <code>the_content</code> version of this answer and in some circumstances it actually fails and wraps more than the image in a figure.</p>\n\n<p>I guess this is the reason one shouldn't parse code using regular expressions.</p>\n\n<p><em>So</em>... I came up with another solution using DOMDocument. It's nowhere near as short as the regexp one but it feel stable:</p>\n\n<pre><code>&lt;?php\nadd_filter('the_content', function ($content) {\n # Prevent errors so we can parse HTML5\n libxml_use_internal_errors(true); # https://stackoverflow.com/questions/9149180/domdocumentloadhtml-error\n\n # Load the content\n $dom = new DOMDocument();\n\n # With UTF-8 support\n # https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly\n $dom-&gt;loadHTML('&lt;?xml encoding=\"utf-8\" ?&gt;' . $content);\n\n # Find all images\n $images = $dom-&gt;getElementsByTagName('img');\n\n # Go through all the images\n foreach ($images as $image) {\n $child = $image; # Store the child element\n $wrapper = $image-&gt;parentNode; # And the wrapping element\n\n # If the image is linked\n if ($wrapper-&gt;tagName == 'a') {\n $child = $wrapper; # Store the link as the child\n $wrapper = $wrapper-&gt;parentNode; # And its parent as the wrapper\n }\n\n # If the parent is a &lt;p&gt; - replace it with a &lt;figure&gt;\n if ($wrapper-&gt;tagName == 'p') {\n $figure = $dom-&gt;createElement('figure');\n\n $figure-&gt;setAttribute('class', $image-&gt;getAttribute('class')); # Give figure same class as img\n $image-&gt;setAttribute('class', ''); # Remove img class\n $figure-&gt;appendChild($child); # Add img to figure\n $wrapper-&gt;parentNode-&gt;replaceChild($figure, $wrapper); # Replace &lt;p&gt; with &lt;figure&gt;\n }\n }\n\n # Turn on errors again...\n libxml_use_internal_errors(false);\n\n # Strip DOCTYPE etc from output\n return str_replace(['&lt;body&gt;', '&lt;/body&gt;'], '', $dom-&gt;saveHTML($dom-&gt;getElementsByTagName('body')-&gt;item(0)));\n}, 99);\n</code></pre>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12248/" ]
The default behavior when it comes to full-width images in posts is this: * If you insert an image alone, this HTML structure is produced: `<p><img/></p>` * If you insert an image **with a caption**, the HTML structure is produced: `<figure><img/><figcaption/></figure>` For the sake of styling (I want to have larger margin around images compared to standard paragraphs), I'd like to get `<figure>` in both cases, not just when there is a caption. How to do it? **Edit**: one thing I noticed is that the behavior changes as soon as *Visual* and *Text* tabs are switched in the editor, i.e., even before previewing or saving the post. Maybe the correct solution would be to somehow force WordPress editor to always use the `[caption]` shortcode no matter what.
You can try the [`image_send_to_editor`](https://developer.wordpress.org/reference/hooks/image_send_to_editor/) filter: ``` /** * Wrap the inserted image html with <figure> * if the theme supports html5 and the current image has no caption: */ add_filter( 'image_send_to_editor', function( $html, $id, $caption, $title, $align, $url, $size, $alt ) { if( current_theme_supports( 'html5' ) && ! $caption ) $html = sprintf( '<figure>%s</figure>', $html ); // Modify to your needs! return $html; } , 10, 8 ); ``` where you can modify the html of the image when it's inserted into the editor. I added the check for `current_theme_supports( 'html5' )` in the above filter, to check if you have something like: ``` add_theme_support( 'html5', array( ... ) ); ``` in your theme. But you might not want to have this filter callback dependent on your current theme, so you can remove it if you want. You could also try out the [`get_image_tag`](https://developer.wordpress.org/reference/hooks/get_image_tag/) filter. **Update**: Here's the useful unautop function from @bueltge's comment (for better readability): ``` // unautop for images function fb_unautop_4_img( $content ) { $content = preg_replace( '/<p>\\s*?(<a rel=\"attachment.*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '<figure>$1</figure>', $content ); return $content; } add_filter( 'the_content', 'fb_unautop_4_img', 99 ); ```
174,586
<p>I'm trying to do a string replacement using <code>gettext</code> filter (<a href="https://wordpress.stackexchange.com/a/127590/22728">source</a>):</p> <pre><code>function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { if( stripos( $untranslated_text, 'comment' !== FALSE ) ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } is_admin() &amp;&amp; add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); </code></pre> <p>I want it to work only on a specific Post Type (in admin). So I tried <a href="http://codex.wordpress.org/Function_Reference/get_current_screen" rel="nofollow noreferrer"><code>get_current_screen()</code></a> within the function:</p> <pre><code>function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { $screen = get_current_screen(); if( $screen-&gt;post_type == 'mycpt' ) { if( stripos( $untranslated_text, 'comment' !== FALSE ) ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } } is_admin() &amp;&amp; add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); </code></pre> <p>But I'm getting error:</p> <blockquote> <p><strong>Fatal error:</strong> Call to undefined function <code>get_current_screen()</code></p> </blockquote> <p>With several testing I understood, <code>gettext</code> is not the correct filter to trigger the <code>get_current_screen()</code> function.</p> <p>Then how could I do that, specific to my custom post type only?</p>
[ { "answer_id": 174588, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>According <a href=\"http://codex.wordpress.org/Function_Reference/get_current_screen#Usage_Restrictions\" rel=\"noreferrer\">with the codex</a>, <code>get_current_screen()</code> has to be used later than <code>admin_init</code> hook. After a few tests, it seems that the safiest way is to use <code>current_screen</code> action hook instead of <code>get_current_screen()</code>:</p>\n\n<pre><code>add_action('current_screen', 'current_screen_callback');\nfunction current_screen_callback($screen) {\n if( is_object($screen) &amp;&amp; $screen-&gt;post_type == 'mycpt' ) {\n add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n }\n}\n\nfunction theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {\n\n if( stripos( $untranslated_text, 'comment' ) !== FALSE ) {\n $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;\n }\n\n return $translated_text;\n\n}\n</code></pre>\n\n<p>You can reuse the filter if you want, for example in the frontend for \"mycpt\" archives:</p>\n\n<pre><code>add_action('init', function() {\n if( is_post_type_archive( 'mycpt' ) ) {\n add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n }\n});\n</code></pre>\n" }, { "answer_id": 174596, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 2, "selected": false, "text": "<p><code>get_current_screen()</code> is a pain, I use the following code to avoid/wrap it:</p>\n\n<pre><code>/*\n * Convenience function to tell if we're on a specified page.\n */\nfunction theme_is_current_screen( $base = null, $post_type = null ) {\n if ( ! $base &amp;&amp; ! $post_type ) {\n return false;\n }\n $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;\n if ( ! $screen ) {\n // Fake it.\n $screen = new StdClass;\n $screen-&gt;post_type = $screen-&gt;base = '';\n\n global $pagenow;\n if ( $pagenow == 'admin-ajax.php' ) {\n if ( isset( $_REQUEST['action'] ) ) {\n $screen-&gt;base = $_REQUEST['action'];\n }\n } else {\n $screen-&gt;post_type = isset( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : '';\n if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' || $pagenow == 'edit.php' ) {\n $screen-&gt;base = preg_replace( '/[^a-z].+$/', '', $pagenow );\n if ( ! $screen-&gt;post_type ) {\n $screen-&gt;post_type = get_post_type( theme_get_post_id() );\n }\n } else {\n $page_hook = '';\n global $plugin_page;\n if ( ! empty( $plugin_page ) ) {\n if ( $screen-&gt;post_type ) {\n $the_parent = $pagenow . '?post_type=' . $screen-&gt;post_type;\n } else {\n $the_parent = $pagenow;\n }\n if ( ! ( $page_hook = get_plugin_page_hook( $plugin_page, $the_parent ) ) ) {\n $page_hook = get_plugin_page_hook( $plugin_page, $plugin_page );\n }\n }\n $screen-&gt;base = $page_hook ? $page_hook : pathinfo( $pagenow, PATHINFO_FILENAME );\n }\n }\n }\n // The base type of the screen. This is typically the same as $id but with any post types and taxonomies stripped.\n if ( $base ) {\n if ( ! is_array( $base ) ) $base = array( $base );\n if ( ! in_array( $screen-&gt;base, $base ) ) {\n return false;\n }\n }\n if ( $post_type ) {\n if ( ! is_array( $post_type ) ) $post_type = array( $post_type );\n if ( ! in_array( $screen-&gt;post_type, $post_type ) ) {\n return false;\n }\n }\n return true;\n}\n\n/*\n * Attempt to determine post id in uncertain (admin) situations.\n * Based on WPAlchemy_MetaBox::_get_post_id().\n */\nfunction theme_get_post_id() {\n global $post;\n\n $ret = 0;\n\n if ( ! empty( $post-&gt;ID ) ) {\n $ret = $post-&gt;ID;\n } elseif ( ! empty( $_GET['post'] ) &amp;&amp; ctype_digit( $_GET['post'] ) ) {\n $ret = $_GET['post'];\n } elseif ( ! empty( $_POST['post_ID'] ) &amp;&amp; ctype_digit( $_POST['post_ID'] ) ) {\n $ret = $_POST['post_ID'];\n }\n\n return $ret;\n}\n</code></pre>\n\n<p>Your function would then become:</p>\n\n<pre><code>function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {\n if( theme_is_current_screen( null, 'mycpt' ) ) {\n if( stripos( $untranslated_text, 'comment' ) !== FALSE ) {\n $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;\n }\n }\n return $translated_text;\n}\nis_admin() &amp;&amp; add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n</code></pre>\n\n<p>It's also useful for shortcircuiting custom type <code>admin_init</code>s, or only registering your settings on your own settings page.</p>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174586", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm trying to do a string replacement using `gettext` filter ([source](https://wordpress.stackexchange.com/a/127590/22728)): ``` function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { if( stripos( $untranslated_text, 'comment' !== FALSE ) ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } is_admin() && add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); ``` I want it to work only on a specific Post Type (in admin). So I tried [`get_current_screen()`](http://codex.wordpress.org/Function_Reference/get_current_screen) within the function: ``` function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { $screen = get_current_screen(); if( $screen->post_type == 'mycpt' ) { if( stripos( $untranslated_text, 'comment' !== FALSE ) ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } } is_admin() && add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); ``` But I'm getting error: > > **Fatal error:** Call to undefined function `get_current_screen()` > > > With several testing I understood, `gettext` is not the correct filter to trigger the `get_current_screen()` function. Then how could I do that, specific to my custom post type only?
According [with the codex](http://codex.wordpress.org/Function_Reference/get_current_screen#Usage_Restrictions), `get_current_screen()` has to be used later than `admin_init` hook. After a few tests, it seems that the safiest way is to use `current_screen` action hook instead of `get_current_screen()`: ``` add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) && $screen->post_type == 'mycpt' ) { add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); } } function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { if( stripos( $untranslated_text, 'comment' ) !== FALSE ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } ``` You can reuse the filter if you want, for example in the frontend for "mycpt" archives: ``` add_action('init', function() { if( is_post_type_archive( 'mycpt' ) ) { add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); } }); ```
174,587
<p>I used the code provided in <a href="http://code.tutsplus.com/articles/quick-tip-create-a-wordpress-global-options-page--wp-24570" rel="nofollow">this tutorial</a> to create an option menu in dashboard, but contrary to what was expected, I don't see any new menu in dashboard:</p> <pre><code>&lt;?php add_action('admin_menu', 'add_global_custom_options'); function add_global_custom_options() { add_options_page('Global Custom Options', 'Global Custom Options', 'manage_options', 'functions','global_custom_options'); } function global_custom_options() { ?&gt; &lt;div class="wrap"&gt; &lt;h2&gt;Global Custom Options&lt;/h2&gt; &lt;form method="post" action="options.php"&gt; &lt;?php wp_nonce_field('update-options') ?&gt; &lt;p&gt;&lt;strong&gt;Twitter ID:&lt;/strong&gt;&lt;br /&gt; &lt;input type="text" name="twitterid" size="45" value="&lt;?php echo get_option('twitterid'); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt;&lt;input type="submit" name="Submit" value="Store Options" /&gt;&lt;/p&gt; &lt;input type="hidden" name="action" value="update" /&gt; &lt;input type="hidden" name="page_options" value="twitterid" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>What did I do wrong? I added this code in my child theme's <code>functions.php</code>.</p>
[ { "answer_id": 174588, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>According <a href=\"http://codex.wordpress.org/Function_Reference/get_current_screen#Usage_Restrictions\" rel=\"noreferrer\">with the codex</a>, <code>get_current_screen()</code> has to be used later than <code>admin_init</code> hook. After a few tests, it seems that the safiest way is to use <code>current_screen</code> action hook instead of <code>get_current_screen()</code>:</p>\n\n<pre><code>add_action('current_screen', 'current_screen_callback');\nfunction current_screen_callback($screen) {\n if( is_object($screen) &amp;&amp; $screen-&gt;post_type == 'mycpt' ) {\n add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n }\n}\n\nfunction theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {\n\n if( stripos( $untranslated_text, 'comment' ) !== FALSE ) {\n $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;\n }\n\n return $translated_text;\n\n}\n</code></pre>\n\n<p>You can reuse the filter if you want, for example in the frontend for \"mycpt\" archives:</p>\n\n<pre><code>add_action('init', function() {\n if( is_post_type_archive( 'mycpt' ) ) {\n add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n }\n});\n</code></pre>\n" }, { "answer_id": 174596, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 2, "selected": false, "text": "<p><code>get_current_screen()</code> is a pain, I use the following code to avoid/wrap it:</p>\n\n<pre><code>/*\n * Convenience function to tell if we're on a specified page.\n */\nfunction theme_is_current_screen( $base = null, $post_type = null ) {\n if ( ! $base &amp;&amp; ! $post_type ) {\n return false;\n }\n $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;\n if ( ! $screen ) {\n // Fake it.\n $screen = new StdClass;\n $screen-&gt;post_type = $screen-&gt;base = '';\n\n global $pagenow;\n if ( $pagenow == 'admin-ajax.php' ) {\n if ( isset( $_REQUEST['action'] ) ) {\n $screen-&gt;base = $_REQUEST['action'];\n }\n } else {\n $screen-&gt;post_type = isset( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : '';\n if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' || $pagenow == 'edit.php' ) {\n $screen-&gt;base = preg_replace( '/[^a-z].+$/', '', $pagenow );\n if ( ! $screen-&gt;post_type ) {\n $screen-&gt;post_type = get_post_type( theme_get_post_id() );\n }\n } else {\n $page_hook = '';\n global $plugin_page;\n if ( ! empty( $plugin_page ) ) {\n if ( $screen-&gt;post_type ) {\n $the_parent = $pagenow . '?post_type=' . $screen-&gt;post_type;\n } else {\n $the_parent = $pagenow;\n }\n if ( ! ( $page_hook = get_plugin_page_hook( $plugin_page, $the_parent ) ) ) {\n $page_hook = get_plugin_page_hook( $plugin_page, $plugin_page );\n }\n }\n $screen-&gt;base = $page_hook ? $page_hook : pathinfo( $pagenow, PATHINFO_FILENAME );\n }\n }\n }\n // The base type of the screen. This is typically the same as $id but with any post types and taxonomies stripped.\n if ( $base ) {\n if ( ! is_array( $base ) ) $base = array( $base );\n if ( ! in_array( $screen-&gt;base, $base ) ) {\n return false;\n }\n }\n if ( $post_type ) {\n if ( ! is_array( $post_type ) ) $post_type = array( $post_type );\n if ( ! in_array( $screen-&gt;post_type, $post_type ) ) {\n return false;\n }\n }\n return true;\n}\n\n/*\n * Attempt to determine post id in uncertain (admin) situations.\n * Based on WPAlchemy_MetaBox::_get_post_id().\n */\nfunction theme_get_post_id() {\n global $post;\n\n $ret = 0;\n\n if ( ! empty( $post-&gt;ID ) ) {\n $ret = $post-&gt;ID;\n } elseif ( ! empty( $_GET['post'] ) &amp;&amp; ctype_digit( $_GET['post'] ) ) {\n $ret = $_GET['post'];\n } elseif ( ! empty( $_POST['post_ID'] ) &amp;&amp; ctype_digit( $_POST['post_ID'] ) ) {\n $ret = $_POST['post_ID'];\n }\n\n return $ret;\n}\n</code></pre>\n\n<p>Your function would then become:</p>\n\n<pre><code>function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {\n if( theme_is_current_screen( null, 'mycpt' ) ) {\n if( stripos( $untranslated_text, 'comment' ) !== FALSE ) {\n $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;\n }\n }\n return $translated_text;\n}\nis_admin() &amp;&amp; add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );\n</code></pre>\n\n<p>It's also useful for shortcircuiting custom type <code>admin_init</code>s, or only registering your settings on your own settings page.</p>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11634/" ]
I used the code provided in [this tutorial](http://code.tutsplus.com/articles/quick-tip-create-a-wordpress-global-options-page--wp-24570) to create an option menu in dashboard, but contrary to what was expected, I don't see any new menu in dashboard: ``` <?php add_action('admin_menu', 'add_global_custom_options'); function add_global_custom_options() { add_options_page('Global Custom Options', 'Global Custom Options', 'manage_options', 'functions','global_custom_options'); } function global_custom_options() { ?> <div class="wrap"> <h2>Global Custom Options</h2> <form method="post" action="options.php"> <?php wp_nonce_field('update-options') ?> <p><strong>Twitter ID:</strong><br /> <input type="text" name="twitterid" size="45" value="<?php echo get_option('twitterid'); ?>" /> </p> <p><input type="submit" name="Submit" value="Store Options" /></p> <input type="hidden" name="action" value="update" /> <input type="hidden" name="page_options" value="twitterid" /> </form> </div> <?php } ``` What did I do wrong? I added this code in my child theme's `functions.php`.
According [with the codex](http://codex.wordpress.org/Function_Reference/get_current_screen#Usage_Restrictions), `get_current_screen()` has to be used later than `admin_init` hook. After a few tests, it seems that the safiest way is to use `current_screen` action hook instead of `get_current_screen()`: ``` add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) && $screen->post_type == 'mycpt' ) { add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); } } function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) { if( stripos( $untranslated_text, 'comment' ) !== FALSE ) { $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ; } return $translated_text; } ``` You can reuse the filter if you want, for example in the frontend for "mycpt" archives: ``` add_action('init', function() { if( is_post_type_archive( 'mycpt' ) ) { add_filter( 'gettext', 'theme_change_comments_label', 99, 3 ); } }); ```
174,593
<p>I am looking for a way to show all post tags on post edit screen/tags sidebox in WordPress admin section. By default WordPress shows 45 most used tags but I need a way to list all tags there or at least increase this limit.</p> <p>I found similar question here <a href="https://wordpress.stackexchange.com/questions/64058/">Showing all tags in admin -> edit post</a>. But it suggests to edit/modify WordPress core files which is not what I really want. Because upgrading WordPress will be a huge problem then.</p> <p>I also could not find anything in Google search. So is there are way to list all or more than 45 tags on post edit page.</p>
[ { "answer_id": 174597, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>I'd say the easiest way to do it is use the <code>get_terms_args</code> filter and unset the <code>number</code> limit if the context is right (the AJAX request to get the tag cloud):</p>\n\n<pre><code>function wpse_64058_all_tags ( $args ) {\n if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX &amp;&amp; isset( $_POST['action'] ) &amp;&amp; $_POST['action'] === 'get-tagcloud' )\n unset( $args['number'] );\n return $args;\n}\n\nadd_filter( 'get_terms_args', 'wpse_64058_all_tags' );\n</code></pre>\n\n<p>Note: In the edit box the link will still read \"Choose from the most used tags\", even though we're now displaying all of them.</p>\n\n<p>Edit: As @bonger suggested, you <em>could</em> determine the post type from the referer:</p>\n\n<pre><code>if ( $qs = parse_url( wp_get_referer(), PHP_URL_QUERY ) ) {\n parse_str( $qs, $args );\n\n if ( ! empty( $args['post_type'] ) )\n $post_type = $args['post_type'];\n elseif ( ! empty( $args['post'] ) )\n $post_type = get_post_type( $args['post'] );\n else\n $post_type = 'post';\n}\n</code></pre>\n" }, { "answer_id": 198778, "author": "Somi", "author_id": 69451, "author_profile": "https://wordpress.stackexchange.com/users/69451", "pm_score": 0, "selected": false, "text": "<p>Addition to TheDeadMedic's answer, to show ALL tags:</p>\n\n<pre><code>if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX &amp;&amp; isset( $_POST['action'] ) &amp;&amp; $_POST['action'] === 'get-tagcloud' ) {\n unset( $args['number'] );\n $args['hide_empty'] = 0;\n}\nreturn $args;\n</code></pre>\n" }, { "answer_id": 345860, "author": "user315338", "author_id": 159259, "author_profile": "https://wordpress.stackexchange.com/users/159259", "pm_score": 0, "selected": false, "text": "<p>Just adding some basic relevant info:</p>\n\n<p>When setting a taxonomy setting to <code>'hierarchical'=&gt;true</code> it will use the category format side box and will show all terms by default.</p>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22461/" ]
I am looking for a way to show all post tags on post edit screen/tags sidebox in WordPress admin section. By default WordPress shows 45 most used tags but I need a way to list all tags there or at least increase this limit. I found similar question here [Showing all tags in admin -> edit post](https://wordpress.stackexchange.com/questions/64058/). But it suggests to edit/modify WordPress core files which is not what I really want. Because upgrading WordPress will be a huge problem then. I also could not find anything in Google search. So is there are way to list all or more than 45 tags on post edit page.
I'd say the easiest way to do it is use the `get_terms_args` filter and unset the `number` limit if the context is right (the AJAX request to get the tag cloud): ``` function wpse_64058_all_tags ( $args ) { if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'get-tagcloud' ) unset( $args['number'] ); return $args; } add_filter( 'get_terms_args', 'wpse_64058_all_tags' ); ``` Note: In the edit box the link will still read "Choose from the most used tags", even though we're now displaying all of them. Edit: As @bonger suggested, you *could* determine the post type from the referer: ``` if ( $qs = parse_url( wp_get_referer(), PHP_URL_QUERY ) ) { parse_str( $qs, $args ); if ( ! empty( $args['post_type'] ) ) $post_type = $args['post_type']; elseif ( ! empty( $args['post'] ) ) $post_type = get_post_type( $args['post'] ); else $post_type = 'post'; } ```
174,605
<p>Im working on some customizer settings for my theme. Im using chrome. I created a number input field:</p> <pre><code>$wp_customize-&gt;add_setting( 'st_opacity', array( 'default' =&gt; '100', 'type' =&gt; 'theme_mod', 'capability' =&gt; 'edit_theme_options', 'transport' =&gt; 'postMessage', ) ); $wp_customize-&gt;add_control( new WP_Customize_Control( $wp_customize, 'st_opacity', array( 'label' =&gt; 'Opacity (%)', 'section' =&gt; 'sitetitle_options', 'settings' =&gt; 'st_opacity', 'type' =&gt; 'number', 'input_attrs' =&gt; array('min' =&gt; '0', 'max' =&gt; '100'), 'priority' =&gt; 41, ) ) ); </code></pre> <p>The preview updates under 2 circumstances: - When I use my arrow keys while the number field is selected. - When I type into the number field and then click outside of it.</p> <p>I want the preview to update while I'm just typing into the number field. How can I do that? </p> <p>When I use a normal text input, it updates the preview instantly. But with a number input, it works differently.</p>
[ { "answer_id": 174597, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>I'd say the easiest way to do it is use the <code>get_terms_args</code> filter and unset the <code>number</code> limit if the context is right (the AJAX request to get the tag cloud):</p>\n\n<pre><code>function wpse_64058_all_tags ( $args ) {\n if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX &amp;&amp; isset( $_POST['action'] ) &amp;&amp; $_POST['action'] === 'get-tagcloud' )\n unset( $args['number'] );\n return $args;\n}\n\nadd_filter( 'get_terms_args', 'wpse_64058_all_tags' );\n</code></pre>\n\n<p>Note: In the edit box the link will still read \"Choose from the most used tags\", even though we're now displaying all of them.</p>\n\n<p>Edit: As @bonger suggested, you <em>could</em> determine the post type from the referer:</p>\n\n<pre><code>if ( $qs = parse_url( wp_get_referer(), PHP_URL_QUERY ) ) {\n parse_str( $qs, $args );\n\n if ( ! empty( $args['post_type'] ) )\n $post_type = $args['post_type'];\n elseif ( ! empty( $args['post'] ) )\n $post_type = get_post_type( $args['post'] );\n else\n $post_type = 'post';\n}\n</code></pre>\n" }, { "answer_id": 198778, "author": "Somi", "author_id": 69451, "author_profile": "https://wordpress.stackexchange.com/users/69451", "pm_score": 0, "selected": false, "text": "<p>Addition to TheDeadMedic's answer, to show ALL tags:</p>\n\n<pre><code>if ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX &amp;&amp; isset( $_POST['action'] ) &amp;&amp; $_POST['action'] === 'get-tagcloud' ) {\n unset( $args['number'] );\n $args['hide_empty'] = 0;\n}\nreturn $args;\n</code></pre>\n" }, { "answer_id": 345860, "author": "user315338", "author_id": 159259, "author_profile": "https://wordpress.stackexchange.com/users/159259", "pm_score": 0, "selected": false, "text": "<p>Just adding some basic relevant info:</p>\n\n<p>When setting a taxonomy setting to <code>'hierarchical'=&gt;true</code> it will use the category format side box and will show all terms by default.</p>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174605", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48867/" ]
Im working on some customizer settings for my theme. Im using chrome. I created a number input field: ``` $wp_customize->add_setting( 'st_opacity', array( 'default' => '100', 'type' => 'theme_mod', 'capability' => 'edit_theme_options', 'transport' => 'postMessage', ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'st_opacity', array( 'label' => 'Opacity (%)', 'section' => 'sitetitle_options', 'settings' => 'st_opacity', 'type' => 'number', 'input_attrs' => array('min' => '0', 'max' => '100'), 'priority' => 41, ) ) ); ``` The preview updates under 2 circumstances: - When I use my arrow keys while the number field is selected. - When I type into the number field and then click outside of it. I want the preview to update while I'm just typing into the number field. How can I do that? When I use a normal text input, it updates the preview instantly. But with a number input, it works differently.
I'd say the easiest way to do it is use the `get_terms_args` filter and unset the `number` limit if the context is right (the AJAX request to get the tag cloud): ``` function wpse_64058_all_tags ( $args ) { if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'get-tagcloud' ) unset( $args['number'] ); return $args; } add_filter( 'get_terms_args', 'wpse_64058_all_tags' ); ``` Note: In the edit box the link will still read "Choose from the most used tags", even though we're now displaying all of them. Edit: As @bonger suggested, you *could* determine the post type from the referer: ``` if ( $qs = parse_url( wp_get_referer(), PHP_URL_QUERY ) ) { parse_str( $qs, $args ); if ( ! empty( $args['post_type'] ) ) $post_type = $args['post_type']; elseif ( ! empty( $args['post'] ) ) $post_type = get_post_type( $args['post'] ); else $post_type = 'post'; } ```
174,646
<p>I have a page where I show the teams of a football club. I order these with 'order' => 'ASC'. But the problem is that the teams order like I want it to.</p> <p>It orders like this: Team E1, Team E10, Team E11, Team E2</p> <p>It must be like this: Team E1, Team E2 ..... Team E10, Team E11</p> <p>What is the best solution to order this the right way?</p>
[ { "answer_id": 174676, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 0, "selected": false, "text": "<p>PHP has a <a href=\"http://php.net/manual/en/function.sort.php\" rel=\"nofollow\">sort_natural</a> flag on its sort() function (MySQL doesn't). So if you built them into an array before displaying them, you could sort it that way.</p>\n\n<p>Something like:</p>\n\n<pre><code>$teams = array(\n 'Team E1',\n 'Team E10',\n 'Team E2',\n 'Team E11',\n);\n\nsort($teams, SORT_NATURAL);\n\nprint_r($teams);\n</code></pre>\n\n<p>Will output:</p>\n\n<pre><code>Array\n(\n [0] =&gt; Team E1\n [1] =&gt; Team E2\n [2] =&gt; Team E10\n [3] =&gt; Team E11\n)\n</code></pre>\n" }, { "answer_id": 174739, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 4, "selected": true, "text": "<p><strong>Old answer (which no longer works):</strong></p>\n\n<p>A sneaky way to do it using MySQL, assuming the number's always at the end, is to reverse the title, convert it to a number (<code>+0</code>), and then reverse again and convert it to a number:</p>\n\n<pre><code>function wpse174646_posts_orderby( $orderby, $query ) {\n if ( $query-&gt;get( 'orderby' ) != 'title_number' ) return $orderby;\n global $wpdb;\n return 'REVERSE(REVERSE(TRIM(' . $wpdb-&gt;posts . '.post_title))+0)+0 ' . $query-&gt;get( 'order' );\n}\n$args = array( 'orderby' =&gt; 'title_number', 'order' =&gt; 'ASC' );\nadd_filter( 'posts_orderby', 'wpse174646_posts_orderby', 10, 2 );\n$query = new WP_Query( $args );\nremove_filter( 'posts_orderby', 'wpse174646_posts_orderby', 10 );\n</code></pre>\n\n<p><strong>New answer:</strong></p>\n\n<p>A robust (hopefully) way to do it is to use the answer I posted on stackexchange (<a href=\"https://stackoverflow.com/a/28808798/664741\">https://stackoverflow.com/a/28808798/664741</a>), a simplified non-udf version of the best response there of @plaix/Richard Toth/Luke Hoggett, which pads out the (first encountered) number with zeros:</p>\n\n<pre><code>add_filter( 'posts_clauses', function ( $pieces, $query ) {\n if ( $query-&gt;get( 'orderby' ) != 'title_number' ) return $pieces;\n global $wpdb;\n $field = $wpdb-&gt;posts . '.post_title';\n $pieces[ 'fields' ] .= $wpdb-&gt;prepare(\n ', LEAST(' . implode( ',', array_fill( 0, 10, 'IFNULL(NULLIF(LOCATE(%s, ' . $field . '), 0), ~0)' ) )\n . ') AS first_int',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'\n );\n $pieces[ 'orderby' ] = $wpdb-&gt;prepare(\n 'IF(first_int = ~0, ' . $field . ', CONCAT('\n . 'SUBSTR(' . $field . ', 1, first_int - 1),'\n . 'LPAD(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED), LENGTH(~0), %s),'\n . 'SUBSTR(' . $field . ', first_int + LENGTH(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED)))'\n . ')) ' . $query-&gt;get( 'order' )\n , 0\n );\n return $pieces;\n}, 10, 2 );\n$args = array( 'orderby' =&gt; 'title_number', 'order' =&gt; 'ASC' );\n$query = new WP_Query( $args );\n</code></pre>\n" } ]
2015/01/12
[ "https://wordpress.stackexchange.com/questions/174646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9513/" ]
I have a page where I show the teams of a football club. I order these with 'order' => 'ASC'. But the problem is that the teams order like I want it to. It orders like this: Team E1, Team E10, Team E11, Team E2 It must be like this: Team E1, Team E2 ..... Team E10, Team E11 What is the best solution to order this the right way?
**Old answer (which no longer works):** A sneaky way to do it using MySQL, assuming the number's always at the end, is to reverse the title, convert it to a number (`+0`), and then reverse again and convert it to a number: ``` function wpse174646_posts_orderby( $orderby, $query ) { if ( $query->get( 'orderby' ) != 'title_number' ) return $orderby; global $wpdb; return 'REVERSE(REVERSE(TRIM(' . $wpdb->posts . '.post_title))+0)+0 ' . $query->get( 'order' ); } $args = array( 'orderby' => 'title_number', 'order' => 'ASC' ); add_filter( 'posts_orderby', 'wpse174646_posts_orderby', 10, 2 ); $query = new WP_Query( $args ); remove_filter( 'posts_orderby', 'wpse174646_posts_orderby', 10 ); ``` **New answer:** A robust (hopefully) way to do it is to use the answer I posted on stackexchange (<https://stackoverflow.com/a/28808798/664741>), a simplified non-udf version of the best response there of @plaix/Richard Toth/Luke Hoggett, which pads out the (first encountered) number with zeros: ``` add_filter( 'posts_clauses', function ( $pieces, $query ) { if ( $query->get( 'orderby' ) != 'title_number' ) return $pieces; global $wpdb; $field = $wpdb->posts . '.post_title'; $pieces[ 'fields' ] .= $wpdb->prepare( ', LEAST(' . implode( ',', array_fill( 0, 10, 'IFNULL(NULLIF(LOCATE(%s, ' . $field . '), 0), ~0)' ) ) . ') AS first_int', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ); $pieces[ 'orderby' ] = $wpdb->prepare( 'IF(first_int = ~0, ' . $field . ', CONCAT(' . 'SUBSTR(' . $field . ', 1, first_int - 1),' . 'LPAD(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED), LENGTH(~0), %s),' . 'SUBSTR(' . $field . ', first_int + LENGTH(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED)))' . ')) ' . $query->get( 'order' ) , 0 ); return $pieces; }, 10, 2 ); $args = array( 'orderby' => 'title_number', 'order' => 'ASC' ); $query = new WP_Query( $args ); ```
174,662
<p>While I was trying to convert a Static HTML page to Wordpress Theme , I had an issue . the page Doesn't run properly After Checking Google Chrome Console it turns that it loads the CSS file with the wrong path</p> <p>it loads Website/css/styles.css and Website/css/style-desktop.css</p> <p>here are how I've imported stylesheets from header.php</p> <pre><code>&lt;link rel="stylesheet" href="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/skel.css" /&gt; &lt;link rel="stylesheet" href="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/style.css" /&gt; &lt;link rel="stylesheet" href="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/style-desktop.css" /&gt; &lt;link rel="stylesheet" href="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/style-noscript.css" /&gt; &lt;!--[if lte IE 8]&gt;&lt;link rel="stylesheet" href="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/ie/v8.css" /&gt;&lt;![endif]--&gt; &lt;!--[if lte IE 8]&gt;&lt;script src="&lt;?php bloginfo( 'template_directory' ); ?&gt;/css/ie/html5shiv.js"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;script src="&lt;?php bloginfo( 'template_directory' ); ?&gt;/js/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="&lt;?php bloginfo( 'template_directory' ); ?&gt;/js/skel.min.js"&gt;&lt;/script&gt; &lt;script src="&lt;?php bloginfo( 'template_directory' ); ?&gt;/js/init.js"&gt;&lt;/script&gt; </code></pre> <p>It should get the stylesheet as website.com/wp-content/theme/themename/css/styles.css</p> <p>I'm not sure if there anything I should write in function.php </p> <p><strong>UPDATE1:</strong></p> <p>It turns out one of the JS files loads the CSS file directly , so I had to change the path of CSS files</p> <p>It looks ok with the CSS but there are some conflict in the theme .</p>
[ { "answer_id": 174674, "author": "shuvroMithun", "author_id": 65928, "author_profile": "https://wordpress.stackexchange.com/users/65928", "pm_score": 0, "selected": false, "text": "<p>Try like this </p>\n\n<pre><code>&lt;script src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/js/jquery.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>But it is a good practice to en queue your script in function.php <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">Function Reference/wp enqueue script</a> </p>\n" }, { "answer_id": 174689, "author": "user3325126", "author_id": 56674, "author_profile": "https://wordpress.stackexchange.com/users/56674", "pm_score": 2, "selected": true, "text": "<p>As said, you should enqueue your style sheets like this in your functions.php in your theme:</p>\n\n<pre><code>function adds_to_the_head() { // Our own unique function called adds_to_the_head\n\nwp_register_style( 'custom-style-css', get_stylesheet_directory_uri() . '/css/styles.css','','', 'screen' ); // Register style.css\n\nwp_enqueue_style( 'custom-style-css' ); // Enqueue our stylesheet\n\n}\nadd_action( 'wp_enqueue_scripts', 'adds_to_the_head' );\n</code></pre>\n" }, { "answer_id": 257124, "author": "Abdus Salam", "author_id": 113729, "author_profile": "https://wordpress.stackexchange.com/users/113729", "pm_score": 0, "selected": false, "text": "<p>You can use this way. And It is also standard </p>\n\n<pre><code>/**\n * Enqueue scripts and styles.\n */\nfunction test_name_scripts() {\n wp_enqueue_style( 'test-name-style', get_stylesheet_uri() );\n\n wp_enqueue_script( 'test-name-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );\n\n wp_enqueue_script( 'test-name-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );\n\n if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) {\n wp_enqueue_script( 'comment-reply' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'test_name_scripts' );\n</code></pre>\n\n<p>And Also follow this tutorial:\n<a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/including-css-javascript/</a></p>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65924/" ]
While I was trying to convert a Static HTML page to Wordpress Theme , I had an issue . the page Doesn't run properly After Checking Google Chrome Console it turns that it loads the CSS file with the wrong path it loads Website/css/styles.css and Website/css/style-desktop.css here are how I've imported stylesheets from header.php ``` <link rel="stylesheet" href="<?php bloginfo( 'template_directory' ); ?>/css/skel.css" /> <link rel="stylesheet" href="<?php bloginfo( 'template_directory' ); ?>/css/style.css" /> <link rel="stylesheet" href="<?php bloginfo( 'template_directory' ); ?>/css/style-desktop.css" /> <link rel="stylesheet" href="<?php bloginfo( 'template_directory' ); ?>/css/style-noscript.css" /> <!--[if lte IE 8]><link rel="stylesheet" href="<?php bloginfo( 'template_directory' ); ?>/css/ie/v8.css" /><![endif]--> <!--[if lte IE 8]><script src="<?php bloginfo( 'template_directory' ); ?>/css/ie/html5shiv.js"></script><![endif]--> <script src="<?php bloginfo( 'template_directory' ); ?>/js/jquery.min.js"></script> <script src="<?php bloginfo( 'template_directory' ); ?>/js/skel.min.js"></script> <script src="<?php bloginfo( 'template_directory' ); ?>/js/init.js"></script> ``` It should get the stylesheet as website.com/wp-content/theme/themename/css/styles.css I'm not sure if there anything I should write in function.php **UPDATE1:** It turns out one of the JS files loads the CSS file directly , so I had to change the path of CSS files It looks ok with the CSS but there are some conflict in the theme .
As said, you should enqueue your style sheets like this in your functions.php in your theme: ``` function adds_to_the_head() { // Our own unique function called adds_to_the_head wp_register_style( 'custom-style-css', get_stylesheet_directory_uri() . '/css/styles.css','','', 'screen' ); // Register style.css wp_enqueue_style( 'custom-style-css' ); // Enqueue our stylesheet } add_action( 'wp_enqueue_scripts', 'adds_to_the_head' ); ```
174,669
<p>I'm trying to figure out how to do this. I have many posts. I want it so that when someone pulls up the site, the front page shows all the posts that were done on the same month and day -- but disregards the year. So, if I were to pull up the website on Jan. 30, I would see all posts done on Jan. 30th of ANY year... a historical listing. I was also thinking of doing it by category, if the category was named Jan-30, is there a way I can get the system to take today's date and compare it to the categories, and show the one that matches (no year, of course)?</p> <p>Can anyone help?</p>
[ { "answer_id": 174670, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>If you go the Category route, you could do something like this:</p>\n\n<p>First, get a slug of today's date:</p>\n\n<pre><code>$date_slug = current_time('M-d');\n</code></pre>\n\n<p>Then, create a taxonomy query argument array:</p>\n\n<pre><code>$tax_query = array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $date_slug,\n )\n);\n</code></pre>\n\n<p>Then, build a query using the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query</a> class:</p>\n\n<pre><code>$r = new WP_Query(\n array(\n 'tax_query' =&gt; $tax_query,\n )\n);\n</code></pre>\n\n<p>Then, build your <a href=\"http://codex.wordpress.org/the_loop\" rel=\"nofollow\">loop</a>:</p>\n\n<pre><code>&lt;?php if ($r-&gt;have_posts()) : ?&gt;\n\n &lt;?php while ( $r-&gt;have_posts() ) : $r-&gt;the_post(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n\n&lt;?php endif; ?&gt;\n\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 174672, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You can achieve this with the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow\"><code>date_query</code> parameters</a> added in version 3.7.</p>\n\n<p>To modify the main query on your posts page before it is run and apply the <code>date_query</code> parameters, we use the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> action:</p>\n\n<pre><code>function historical_posts_list( $query ){\n if( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ){\n $date_query = array(\n array(\n 'month' =&gt; date( 'n', current_time( 'timestamp' ) ),\n 'day' =&gt; date( 'j', current_time( 'timestamp' ) )\n )\n );\n $query-&gt;set( 'date_query', $date_query );\n }\n}\nadd_action( 'pre_get_posts', 'historical_posts_list' );\n</code></pre>\n\n<p>If the page you want this on isn't your posts page, you can add a custom query in your template with the same parameters, and run a separate loop:</p>\n\n<pre><code>$posts_from_today = new WP_Query( array(\n 'date_query' =&gt; array(\n array(\n 'month' =&gt; date( 'n', current_time( 'timestamp' ) ),\n 'day' =&gt; date( 'j', current_time( 'timestamp' ) )\n ),\n ),\n 'posts_per_page' =&gt; -1,\n) );\n\nif( $posts_from_today-&gt;have_posts() ){\n while( $posts_from_today-&gt;have_posts() ){\n $posts_from_today-&gt;the_post();\n the_title();\n }\n}\n</code></pre>\n" }, { "answer_id": 174673, "author": "chrisguitarguy", "author_id": 6035, "author_profile": "https://wordpress.stackexchange.com/users/6035", "pm_score": 2, "selected": false, "text": "<pre><code>$q = new \\WP_Query([\n 'monthnum' =&gt; date('n'), // beware the date function!\n 'day' =&gt; date('j'),\n]);\n\nwhile ($q-&gt;have_posts()) {\n $q-&gt;the_post();\n // ...\n}\nwp_reset_query();\n</code></pre>\n\n<p>See the documentation on <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow\">date parameters</a>.</p>\n\n<p>Since you want to modify the home page query specifically, you might hook into <code>pre_get_posts</code> and modify the main query on the home page only.</p>\n\n<pre><code>add_action('pre_get_posts', 'wpse174669_pre_get_posts');\nfunction wpse174669_pre_get_posts($q)\n{\n if (is_home() &amp;&amp; $q-&gt;is_main_query()) {\n $q-&gt;set('ignore_sticky_posts', true);\n $q-&gt;set('monthnum', date('n'));\n $q-&gt;set('day', date('j'));\n }\n}\n</code></pre>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174669", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65925/" ]
I'm trying to figure out how to do this. I have many posts. I want it so that when someone pulls up the site, the front page shows all the posts that were done on the same month and day -- but disregards the year. So, if I were to pull up the website on Jan. 30, I would see all posts done on Jan. 30th of ANY year... a historical listing. I was also thinking of doing it by category, if the category was named Jan-30, is there a way I can get the system to take today's date and compare it to the categories, and show the one that matches (no year, of course)? Can anyone help?
You can achieve this with the [`date_query` parameters](http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters) added in version 3.7. To modify the main query on your posts page before it is run and apply the `date_query` parameters, we use the [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) action: ``` function historical_posts_list( $query ){ if( $query->is_home() && $query->is_main_query() ){ $date_query = array( array( 'month' => date( 'n', current_time( 'timestamp' ) ), 'day' => date( 'j', current_time( 'timestamp' ) ) ) ); $query->set( 'date_query', $date_query ); } } add_action( 'pre_get_posts', 'historical_posts_list' ); ``` If the page you want this on isn't your posts page, you can add a custom query in your template with the same parameters, and run a separate loop: ``` $posts_from_today = new WP_Query( array( 'date_query' => array( array( 'month' => date( 'n', current_time( 'timestamp' ) ), 'day' => date( 'j', current_time( 'timestamp' ) ) ), ), 'posts_per_page' => -1, ) ); if( $posts_from_today->have_posts() ){ while( $posts_from_today->have_posts() ){ $posts_from_today->the_post(); the_title(); } } ```
174,709
<p>I am loading my php file by putting this into my theme's functions.php:</p> <pre><code>require get_stylesheet_directory() . '/inc/manage-menus.php'; alter_menu('my-user', 'plugins.php', false); </code></pre> <p>The code in manage-menus.php looks like this:</p> <pre><code>function alter_item ($user, $items, $action) { global $current_user, $menu; get_currentuserinfo(); switch ($action) { case false: if ($current_user-&gt;user_login == $user) { remove_menu_page ($items); } break; case true: if ($current_user-&gt;user_login == $user) { //Do something else } break; } } function alter_menu($user, $items, $action) { add_action( 'admin_menu', 'alter_item' ); alter_item( $user, $items, $action ); } </code></pre> <p>I though when I use the admin_menu hook I should be on the safe side... but it tells me that:</p> <pre><code>Call to undefined function remove_menu_page() in .... </code></pre> <p>Any ideas?</p> <hr> <p>PS I tried an OOP approach, which gave me the same result:</p> <p>manage-menus.php:</p> <pre><code>abstract class admin_menu_alterations { function hook_alter_menu(){ echo 'executing hook'; add_action( 'admin_menu',array( $this, 'alter_menu' ) ); } public abstract function alter_menu($user, $items); } class hide_admin_menu_items extends admin_menu_alterations { public function alter_menu($user, $items) { $this-&gt;hook_alter_mennu(); global $current_user; get_currentuserinfo(); echo $current_user-&gt;user_login; if ($current_user-&gt;user_login == $user) { remove_menu_page ($items_to_be_removed); } } } </code></pre> <p>functions.php:</p> <pre><code>$hide_menu_items = new hide_admin_menu_items(); $hide_menu_items-&gt;alter_menu("my-user", "plugins.php"); </code></pre>
[ { "answer_id": 174722, "author": "Михаил Семёнов", "author_id": 65524, "author_profile": "https://wordpress.stackexchange.com/users/65524", "pm_score": 1, "selected": false, "text": "<p>It's becouse you'r calling alter_item function outside action <code>admin_menu</code></p>\n\n<p>here's working example i just made, try to figure what's wrong with your's by your self, if you fail i'll explain</p>\n\n<pre><code>add_action( 'admin_menu', 'alter_items' );\nfunction alter_items() {\n global $current_user, $menu;\n get_currentuserinfo();\n $scopes = apply_filters( 'alter_items', array() );\n if( ! empty( $scopes ) ) {\n foreach( $scopes as $scope ) {\n switch ($scope['action']) {\n case false:\n if ($current_user-&gt;user_login == $scope['user']) {\n remove_menu_page( $scope['items'] );\n }\n break;\n\n case true:\n if ($current_user-&gt;user_login == $scope['user']) {\n //Do something else\n }\n break;\n }\n }\n }\n}\nfunction alter_menu($user, $items, $action) {\n add_filter( 'alter_items', function( $scope ) use( $user, $items, $action ) {\n //echo '&lt;pre&gt;'; var_dump( $user, $items, $action ); echo '&lt;/pre&gt;';\n $scope[] = array(\n 'user' =&gt; $user,\n 'items' =&gt; $items,\n 'action' =&gt; $action\n );\n return $scope;\n } );\n}\n\nalter_menu('admin', 'plugins.php', false);\n</code></pre>\n\n<p>PS: note that you need PHP 5.3.0 minimum </p>\n" }, { "answer_id": 175072, "author": "wxT3APyGfkYJVK", "author_id": 48146, "author_profile": "https://wordpress.stackexchange.com/users/48146", "pm_score": 1, "selected": true, "text": "<p>I think Михаил Семёнов is right, but I had to get another push by cybmeta in another thread, which lead to this:</p>\n\n<p>functions.php:</p>\n\n<pre><code>$menu_alterations = array(\n 'user' =&gt; array('my-userA', 'my-userB'),\n 'items' =&gt; array('plugins.php', 'options-general.php'),\n 'action' =&gt; false,\n); \n\ninclude get_template_directory() . '/inc/manage-menus.php';\n</code></pre>\n\n<p>/inc/manage-menus.php:</p>\n\n<pre><code>add_action( 'admin_menu', function() use ($menu_alterations) {\n global $current_user, $menu;\n get_currentuserinfo();\n foreach ($menu_alterations['user'] as $user) {\n switch ($menu_alterations['action']) {\n case false:\n if ($current_user-&gt;user_login == $user) {\n foreach ($menu_alterations['items'] as $item) {\n remove_menu_page ($item);\n }\n }\n break;\n }\n }\n} );\n</code></pre>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174709", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48146/" ]
I am loading my php file by putting this into my theme's functions.php: ``` require get_stylesheet_directory() . '/inc/manage-menus.php'; alter_menu('my-user', 'plugins.php', false); ``` The code in manage-menus.php looks like this: ``` function alter_item ($user, $items, $action) { global $current_user, $menu; get_currentuserinfo(); switch ($action) { case false: if ($current_user->user_login == $user) { remove_menu_page ($items); } break; case true: if ($current_user->user_login == $user) { //Do something else } break; } } function alter_menu($user, $items, $action) { add_action( 'admin_menu', 'alter_item' ); alter_item( $user, $items, $action ); } ``` I though when I use the admin\_menu hook I should be on the safe side... but it tells me that: ``` Call to undefined function remove_menu_page() in .... ``` Any ideas? --- PS I tried an OOP approach, which gave me the same result: manage-menus.php: ``` abstract class admin_menu_alterations { function hook_alter_menu(){ echo 'executing hook'; add_action( 'admin_menu',array( $this, 'alter_menu' ) ); } public abstract function alter_menu($user, $items); } class hide_admin_menu_items extends admin_menu_alterations { public function alter_menu($user, $items) { $this->hook_alter_mennu(); global $current_user; get_currentuserinfo(); echo $current_user->user_login; if ($current_user->user_login == $user) { remove_menu_page ($items_to_be_removed); } } } ``` functions.php: ``` $hide_menu_items = new hide_admin_menu_items(); $hide_menu_items->alter_menu("my-user", "plugins.php"); ```
I think Михаил Семёнов is right, but I had to get another push by cybmeta in another thread, which lead to this: functions.php: ``` $menu_alterations = array( 'user' => array('my-userA', 'my-userB'), 'items' => array('plugins.php', 'options-general.php'), 'action' => false, ); include get_template_directory() . '/inc/manage-menus.php'; ``` /inc/manage-menus.php: ``` add_action( 'admin_menu', function() use ($menu_alterations) { global $current_user, $menu; get_currentuserinfo(); foreach ($menu_alterations['user'] as $user) { switch ($menu_alterations['action']) { case false: if ($current_user->user_login == $user) { foreach ($menu_alterations['items'] as $item) { remove_menu_page ($item); } } break; } } } ); ```
174,738
<p>I am trying to add active states for my custom menu navigation, but so far everything I try is just not working. I have set the navigation menu in a separate file nav.php, then I included the nav.php into my header.php file like this:</p> <pre><code>&lt;?php include('nav.php'); ?&gt; </code></pre> <p>I created custom Wordpress pages in the child folder and included the header.php just after the template name:</p> <pre><code>&lt;?php /* Template Name: Website Design Page*/ ?&gt; &lt;?php get_header(); ?&gt; </code></pre> <p>Here is my current html and php code in my nav.php and I added a unique id attribute "currentpage" to indicate which menu item reflects the user’s current page:</p> <pre><code>&lt;ul id="menu" class="clearfix"&gt; &lt;li&lt;?php if ($thisPage=="About") echo " id=\"currentpage\""; ?&gt; class="parent-item"&gt;&lt;a href="/about" title="Welcome page" class="parent-link menu-item-2" id="main-menu-item-4"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&lt;?php if ($thisPage=="Portfolio") echo " id=\"currentpage\""; ?&gt; class="parent-item"&gt;&lt;a href="/portfolio" class="parent-link menu-item-3"&gt;Portfolio&lt;/a&gt;&lt;/li&gt; &lt;li&lt;?php if ($thisPage=="Services") echo " id=\"currentpage\""; ?&gt; class="parent-item"&gt;&lt;a href="/services" class="parent-link menu-item-4"&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li&lt;?php if ($thisPage=="Prices") echo " id=\"currentpage\""; ?&gt; class="parent-item"&gt;&lt;a href="/prices" class="parent-link menu-item-5"&gt;Prices&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And this is my Css for hover and active states:</p> <pre><code>ul#menu li a:hover { background-color: #999999; color: #fff; } ul#menu li #currentpage a { background: #fff; color: #333; } </code></pre> <p>For each pages I assigned the value after the template name, here is my Home page:</p> <pre><code>&lt;?php /* Template Name: Website Design Page */ ?&gt; &lt;?php $thisPage="Home"; ?&gt; &lt;?php get_header(); ?&gt; </code></pre> <p>I hope somebody will be able to help, I really don't undestand why this code or any other php code i try I cannot make these custom menus work.</p>
[ { "answer_id": 174741, "author": "Dan ", "author_id": 5827, "author_profile": "https://wordpress.stackexchange.com/users/5827", "pm_score": 1, "selected": false, "text": "<p>If your theme is using wp_nav_menu() you will have the class <code>current-menu-item</code> added to the relevant <code>&lt;li&gt;</code> element for you. Does this help?</p>\n" }, { "answer_id": 174787, "author": "giolliano sulit", "author_id": 65984, "author_profile": "https://wordpress.stackexchange.com/users/65984", "pm_score": 0, "selected": false, "text": "<p>What I would do is remove all that code you have in <em>nav.php</em> displaying the menu, create the menu inside the Wordpress backend, then you'll be able to use <code>.current-menu-item</code> in your css.</p>\n\n<p>Then all you need to call the menu will be <code>wp_nav_menu();</code></p>\n\n<p>Here is the documentation for that function:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_nav_menu\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_nav_menu</a></p>\n" }, { "answer_id": 174926, "author": "Tejas", "author_id": 66047, "author_profile": "https://wordpress.stackexchange.com/users/66047", "pm_score": 1, "selected": true, "text": "<p>In your PHP file, set <code>$thisPage</code> before you <code>include('nav.php');</code>. Then, the variable <code>$thisPage</code> will be passed to <code>nav.php</code> and processed in its <code>if</code> statement.</p>\n\n<p>This is <em>really</em> bad practice though, and a better way of doing it would be by creating your menu in WordPress itself and hooking it into your template. WordPress documents <a href=\"http://codex.wordpress.org/Navigation_Menus\" rel=\"nofollow\">how to do this</a> well.</p>\n" }, { "answer_id": 175027, "author": "Steven Donea", "author_id": 65923, "author_profile": "https://wordpress.stackexchange.com/users/65923", "pm_score": 0, "selected": false, "text": "<p>I have deleted the nav.php file from my header.php,\nand added back the old menu code that comes with Wordpress.\nI did some hooking into my style.css file to adjust the styles for the desired design\nand I only used the #menu-navmenu that I created in WordPress to float right my menu bar.</p>\n\n<pre><code>ul#menu-navmenu{float: right;}\n</code></pre>\n\n<p>So before I had this ul#menu {float: right; margin: 15px;}</p>\n\n<p>and now I added 15px margin to this code in wordpress style.css template:</p>\n\n<pre><code>#access .menu-header ul,\ndiv.menu ul {\n list-style: none;\n /*margin: 0;*/margin: 15px;\n}\n</code></pre>\n\n<p>Everything works as expected and\nthank you for all your help in this matter, this is a great WordPress community.</p>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174738", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65923/" ]
I am trying to add active states for my custom menu navigation, but so far everything I try is just not working. I have set the navigation menu in a separate file nav.php, then I included the nav.php into my header.php file like this: ``` <?php include('nav.php'); ?> ``` I created custom Wordpress pages in the child folder and included the header.php just after the template name: ``` <?php /* Template Name: Website Design Page*/ ?> <?php get_header(); ?> ``` Here is my current html and php code in my nav.php and I added a unique id attribute "currentpage" to indicate which menu item reflects the user’s current page: ``` <ul id="menu" class="clearfix"> <li<?php if ($thisPage=="About") echo " id=\"currentpage\""; ?> class="parent-item"><a href="/about" title="Welcome page" class="parent-link menu-item-2" id="main-menu-item-4">About</a></li> <li<?php if ($thisPage=="Portfolio") echo " id=\"currentpage\""; ?> class="parent-item"><a href="/portfolio" class="parent-link menu-item-3">Portfolio</a></li> <li<?php if ($thisPage=="Services") echo " id=\"currentpage\""; ?> class="parent-item"><a href="/services" class="parent-link menu-item-4">Services</a></li> <li<?php if ($thisPage=="Prices") echo " id=\"currentpage\""; ?> class="parent-item"><a href="/prices" class="parent-link menu-item-5">Prices</a></li> </ul> ``` And this is my Css for hover and active states: ``` ul#menu li a:hover { background-color: #999999; color: #fff; } ul#menu li #currentpage a { background: #fff; color: #333; } ``` For each pages I assigned the value after the template name, here is my Home page: ``` <?php /* Template Name: Website Design Page */ ?> <?php $thisPage="Home"; ?> <?php get_header(); ?> ``` I hope somebody will be able to help, I really don't undestand why this code or any other php code i try I cannot make these custom menus work.
In your PHP file, set `$thisPage` before you `include('nav.php');`. Then, the variable `$thisPage` will be passed to `nav.php` and processed in its `if` statement. This is *really* bad practice though, and a better way of doing it would be by creating your menu in WordPress itself and hooking it into your template. WordPress documents [how to do this](http://codex.wordpress.org/Navigation_Menus) well.
174,744
<p>I wrote some code, that helps secure my clients files, and added it to wordpresses function file. however, whenever updates come in, it obviously overwrites my function.</p> <p>So I wanted to create it as a plugin.</p> <p>However, I keep getting this error:</p> <pre><code>PHP Warning: Cannot modify header information - headers already sent by... </code></pre> <p>So I need to execute my code, BEFORE wordpress sends the headers.</p> <p>How do I do that?</p> <p>Thanks, Richard</p> <p>Update. Okay, here is the code, I changed the tags though, but same premise...</p> <pre><code>&lt;?php /* * Plugin Name: My WP Plugin * Plugin URI: http://www.example.com/plugins * Description: My Plugin * Version: 1.0 * Author: My Name * Author URI: http://www.example.com/ */ function somebit_init() { $_permaStruc = get_option('permalink_structure'); if($_permaStruc != "") { if($_GET['dl']) { header("Location: http://google.com"); exit; } else if($_GET['download']) { header("Location: http://google.com"); exit; } } } add_action('init', 'somebit_init'); ?&gt; </code></pre> <p>I'm still getting the "PHP Warning: Cannot modify header information - headers already sent by..." error.</p> <p>Do you see why? I cannot find it. maybe I did something wrong that I cannot see.</p> <p>Richard</p>
[ { "answer_id": 174745, "author": "Rizzo", "author_id": 37054, "author_profile": "https://wordpress.stackexchange.com/users/37054", "pm_score": 2, "selected": false, "text": "<p>use <code>add_action('init', 'your_function');</code></p>\n\n<p>or any action hook before headers are sent: <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">http://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n" }, { "answer_id": 174780, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 0, "selected": false, "text": "<p>Your checks, <code>if($_GET['dl'])</code> and <code>else if($_GET['download'])</code> are throwing <code>Undefined index:</code> errors, and that appears to be causing a headers issue with your My Security Plugin.</p>\n\n<p>Try changing it to:</p>\n\n<pre><code>function somebit_init() {\n $_permaStruc = get_option('permalink_structure');\n if($_permaStruc != \"\") {\n if( !empty($_GET['dl'])) {\n header(\"Location: http://google.com\");\n exit;\n } else if( !empty($_GET['download'])) {\n header(\"Location: http://google.com\");\n exit;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 223780, "author": "juz", "author_id": 68207, "author_profile": "https://wordpress.stackexchange.com/users/68207", "pm_score": 2, "selected": false, "text": "<p>How about using this action?\n<a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/send_headers\" rel=\"nofollow\">Codex Link - send_headers action</a></p>\n\n<pre><code>add_action( 'send_headers', 'add_redirect_header' );\nfunction add_redirect_header() {\n header( 'Location: http://www.google.com' );\n}\n</code></pre>\n" }, { "answer_id": 244288, "author": "Ashraf Slamang", "author_id": 32069, "author_profile": "https://wordpress.stackexchange.com/users/32069", "pm_score": 3, "selected": false, "text": "<p>The correct hook to use is <code>template_redirect</code> which allows you to have the necessary info available to do checks while also early enough to actually redirect. As per the example on the codex page:</p>\n\n<pre><code>function my_page_template_redirect()\n {\n if( is_page( 'goodies' ) &amp;&amp; ! is_user_logged_in() )\n {\n wp_redirect( home_url( '/signup/' ) );\n exit();\n }\n}\nadd_action( 'template_redirect', 'my_page_template_redirect' );\n</code></pre>\n\n<p>Codex page here - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"noreferrer\">template_redirect</a></p>\n" }, { "answer_id": 338483, "author": "Gendrith", "author_id": 162581, "author_profile": "https://wordpress.stackexchange.com/users/162581", "pm_score": 0, "selected": false, "text": "<p>This is a function I used to check if a non logged in user is trying to enter directly in custom page (only for users), it check if someone entered certain page. </p>\n\n<p>Even makes a second check if the main cookies are created (useful to avoid undefined index errors)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function validate_sesion() {\n if ((is_page('something'))||(is_singular('something'))) {\n if (!is_user_logged_in()) {\n wp_redirect(home_url('log-out'));\n exit();\n } elseif ((empty($_COOKIE[\"user_id\"])) || (empty($_COOKIE[\"user_role\"]))) {\n if (is_user_logged_in()) {\n wp_redirect(home_url('log-out'));\n exit();\n }\n }\n }\n</code></pre>\n\n<p>Just like the other answers, I used the 'template_redirect' hook</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action('template_redirect', 'validate_sesion');\n</code></pre>\n\n<p>I hope it can help someone</p>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65966/" ]
I wrote some code, that helps secure my clients files, and added it to wordpresses function file. however, whenever updates come in, it obviously overwrites my function. So I wanted to create it as a plugin. However, I keep getting this error: ``` PHP Warning: Cannot modify header information - headers already sent by... ``` So I need to execute my code, BEFORE wordpress sends the headers. How do I do that? Thanks, Richard Update. Okay, here is the code, I changed the tags though, but same premise... ``` <?php /* * Plugin Name: My WP Plugin * Plugin URI: http://www.example.com/plugins * Description: My Plugin * Version: 1.0 * Author: My Name * Author URI: http://www.example.com/ */ function somebit_init() { $_permaStruc = get_option('permalink_structure'); if($_permaStruc != "") { if($_GET['dl']) { header("Location: http://google.com"); exit; } else if($_GET['download']) { header("Location: http://google.com"); exit; } } } add_action('init', 'somebit_init'); ?> ``` I'm still getting the "PHP Warning: Cannot modify header information - headers already sent by..." error. Do you see why? I cannot find it. maybe I did something wrong that I cannot see. Richard
The correct hook to use is `template_redirect` which allows you to have the necessary info available to do checks while also early enough to actually redirect. As per the example on the codex page: ``` function my_page_template_redirect() { if( is_page( 'goodies' ) && ! is_user_logged_in() ) { wp_redirect( home_url( '/signup/' ) ); exit(); } } add_action( 'template_redirect', 'my_page_template_redirect' ); ``` Codex page here - [template\_redirect](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect)
174,753
<p>I'm using the following code to display the WP Editor on the front end page:</p> <pre><code>$content = ''; $editor_id = 'mycustomeditor'; wp_editor( $content, $editor_id ); </code></pre> <p>When a user clicks on an image in the Media Library I would like to take away the ability to Permanently delete the image.</p> <p>I unset some options for the Media Uploader already with the following code:</p> <pre><code>function member_media_view_strings( $strings ) { unset( $string['uploadImagesTitle'] ); unset( $strings['createGalleryTitle'] ); return $strings; } add_filter( 'media_view_strings', 'member_media_view_strings', 99 ); </code></pre> <p>I know there is a <code>warnDelete</code> string but nothing that actually removes that link. Is there a simple way to do this? </p>
[ { "answer_id": 174762, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>That link is hard-coded in <code>/wp-includes/media-template.php</code> ~ln 526. Since it can't be removed via apply_filters, you could probably use a small js script like <code>$('a.delete-attachment').remove();</code> to remove the link.</p>\n" }, { "answer_id": 174871, "author": "user1048676", "author_id": 13472, "author_profile": "https://wordpress.stackexchange.com/users/13472", "pm_score": 1, "selected": true, "text": "<p>I actually found this:<br>\n<a href=\"https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields\">https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields</a></p>\n\n<p>I actually just added the following in my CSS file to basically remove the links at all times:</p>\n\n<pre><code>.media-sidebar .details .edit-attachment {\n display: none;\n}\n.media-sidebar .details .delete-attachment {\n display: none;\n}\n</code></pre>\n\n<p>To actually show this within the admin section I actually show it by using the following code:</p>\n\n<pre><code>foreach( array( 'post.php', 'post-new.php' ) as $hook )\n add_action( \"admin_print_styles-$hook\", 'admin_styles_so_25894288');\n\nfunction admin_styles_so_25894288() {\n global $typenow;\n if( 'post' !== $typenow )\n return;\n ?&gt;\n &lt;style&gt;\n .media-sidebar .details .delete-attachment\n { \n display: block; \n }\n .media-sidebar .details .edit-attachment\n { \n display: block; \n }\n &lt;/style&gt;\n &lt;?php\n\n}\n</code></pre>\n\n<p>This is tested in Wordpress 4.0.</p>\n" } ]
2015/01/13
[ "https://wordpress.stackexchange.com/questions/174753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13472/" ]
I'm using the following code to display the WP Editor on the front end page: ``` $content = ''; $editor_id = 'mycustomeditor'; wp_editor( $content, $editor_id ); ``` When a user clicks on an image in the Media Library I would like to take away the ability to Permanently delete the image. I unset some options for the Media Uploader already with the following code: ``` function member_media_view_strings( $strings ) { unset( $string['uploadImagesTitle'] ); unset( $strings['createGalleryTitle'] ); return $strings; } add_filter( 'media_view_strings', 'member_media_view_strings', 99 ); ``` I know there is a `warnDelete` string but nothing that actually removes that link. Is there a simple way to do this?
I actually found this: <https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields> I actually just added the following in my CSS file to basically remove the links at all times: ``` .media-sidebar .details .edit-attachment { display: none; } .media-sidebar .details .delete-attachment { display: none; } ``` To actually show this within the admin section I actually show it by using the following code: ``` foreach( array( 'post.php', 'post-new.php' ) as $hook ) add_action( "admin_print_styles-$hook", 'admin_styles_so_25894288'); function admin_styles_so_25894288() { global $typenow; if( 'post' !== $typenow ) return; ?> <style> .media-sidebar .details .delete-attachment { display: block; } .media-sidebar .details .edit-attachment { display: block; } </style> <?php } ``` This is tested in Wordpress 4.0.
174,769
<p>I have this piece of code which works but it's showing only 5 posts (with custom taxonomy) where should be 7. If I hit the tag url, it shows the 7 registries, so the problem it's in this code and its query. I already tried nopaging = true, posts_per_page = -1 numberposts = -1 and setting the last two to fixed numbers, like 7 or 999; but none of this options seem to do the trick.</p> <p>Hope someone can help me. Thanks.</p> <pre><code>add_shortcode('gpp_prod', function( $atts, $content = null ){ ob_start(); $atts = shortcode_atts( array( 'category' =&gt; '0' ), $atts); extract($atts); $args = array( 'post_type'=&gt;'gpp_prod', 'orderby' =&gt; 'title', 'order' =&gt; 'ASC' ); if($category &gt; 0 ){ $args['tax_query'] = array( array( 'posts_per_page' =&gt; -1, 'taxonomy' =&gt; 'cat_prod', 'field' =&gt; 'term_id', 'nopaging' =&gt; true, 'terms' =&gt; $category ) ); } ?&gt; &lt;?php $products = get_posts($args); $termt = get_term($category, 'cat_prod'); &lt;div class="prod-cats"&gt; &lt;h1&gt;&lt;?php echo $termt-&gt;name;?&gt;&lt;/h1&gt; &lt;?php if(count($products)&gt;0) { foreach ($products as $key =&gt; $value) { ?&gt; &lt;div class="prod-group"&gt; &lt;div class="prod-title"&gt;&lt;?php echo do_shortcode( $value-&gt;post_title); ?&gt;&lt;/div&gt; &lt;div class="prod-low"&gt; &lt;div class="prod-image"&gt;&lt;img src="&lt;?php echo wp_get_attachment_url( get_post_thumbnail_id($value-&gt;ID)); ?&gt;"/&gt;&lt;/div&gt; &lt;div role="tabpanel" class="prod-info"&gt; &lt;!-- Nav tabs --&gt; &lt;ul class="nav nav-tabs" role="tablist"&gt; &lt;li role="presentation" class="active"&gt;&lt;a href="#tab-1-&lt;?php echo $value-&gt;ID?&gt;" aria-controls="home" role="tab" data-toggle="tab"&gt;Desc&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation"&gt;&lt;a href="#tab-2-&lt;?php echo $value-&gt;ID?&gt;" aria-controls="profile" role="tab" data-toggle="tab"&gt;Specs&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- Tab panes --&gt; &lt;div class="tab-content"&gt; &lt;div role="tabpanel" class="tab-pane active" id="tab-1-&lt;?php echo $value-&gt;ID?&gt;"&gt;&lt;?php echo do_shortcode( $value-&gt;post_content); ?&gt;&lt;/div&gt; &lt;div role="tabpanel" class="tab-pane" id="tab-2-&lt;?php echo $value-&gt;ID?&gt;"&gt;&lt;?php $meta_value = get_post_meta( $value-&gt;ID, 'meta-text', false ); if( !empty( $meta_value ) ) { echo $meta_value[0]; } else { echo 'No specs available'; } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); return ob_get_clean(); </code></pre> <p>});</p>
[ { "answer_id": 174762, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>That link is hard-coded in <code>/wp-includes/media-template.php</code> ~ln 526. Since it can't be removed via apply_filters, you could probably use a small js script like <code>$('a.delete-attachment').remove();</code> to remove the link.</p>\n" }, { "answer_id": 174871, "author": "user1048676", "author_id": 13472, "author_profile": "https://wordpress.stackexchange.com/users/13472", "pm_score": 1, "selected": true, "text": "<p>I actually found this:<br>\n<a href=\"https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields\">https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields</a></p>\n\n<p>I actually just added the following in my CSS file to basically remove the links at all times:</p>\n\n<pre><code>.media-sidebar .details .edit-attachment {\n display: none;\n}\n.media-sidebar .details .delete-attachment {\n display: none;\n}\n</code></pre>\n\n<p>To actually show this within the admin section I actually show it by using the following code:</p>\n\n<pre><code>foreach( array( 'post.php', 'post-new.php' ) as $hook )\n add_action( \"admin_print_styles-$hook\", 'admin_styles_so_25894288');\n\nfunction admin_styles_so_25894288() {\n global $typenow;\n if( 'post' !== $typenow )\n return;\n ?&gt;\n &lt;style&gt;\n .media-sidebar .details .delete-attachment\n { \n display: block; \n }\n .media-sidebar .details .edit-attachment\n { \n display: block; \n }\n &lt;/style&gt;\n &lt;?php\n\n}\n</code></pre>\n\n<p>This is tested in Wordpress 4.0.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65980/" ]
I have this piece of code which works but it's showing only 5 posts (with custom taxonomy) where should be 7. If I hit the tag url, it shows the 7 registries, so the problem it's in this code and its query. I already tried nopaging = true, posts\_per\_page = -1 numberposts = -1 and setting the last two to fixed numbers, like 7 or 999; but none of this options seem to do the trick. Hope someone can help me. Thanks. ``` add_shortcode('gpp_prod', function( $atts, $content = null ){ ob_start(); $atts = shortcode_atts( array( 'category' => '0' ), $atts); extract($atts); $args = array( 'post_type'=>'gpp_prod', 'orderby' => 'title', 'order' => 'ASC' ); if($category > 0 ){ $args['tax_query'] = array( array( 'posts_per_page' => -1, 'taxonomy' => 'cat_prod', 'field' => 'term_id', 'nopaging' => true, 'terms' => $category ) ); } ?> <?php $products = get_posts($args); $termt = get_term($category, 'cat_prod'); <div class="prod-cats"> <h1><?php echo $termt->name;?></h1> <?php if(count($products)>0) { foreach ($products as $key => $value) { ?> <div class="prod-group"> <div class="prod-title"><?php echo do_shortcode( $value->post_title); ?></div> <div class="prod-low"> <div class="prod-image"><img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($value->ID)); ?>"/></div> <div role="tabpanel" class="prod-info"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab-1-<?php echo $value->ID?>" aria-controls="home" role="tab" data-toggle="tab">Desc</a></li> <li role="presentation"><a href="#tab-2-<?php echo $value->ID?>" aria-controls="profile" role="tab" data-toggle="tab">Specs</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="tab-1-<?php echo $value->ID?>"><?php echo do_shortcode( $value->post_content); ?></div> <div role="tabpanel" class="tab-pane" id="tab-2-<?php echo $value->ID?>"><?php $meta_value = get_post_meta( $value->ID, 'meta-text', false ); if( !empty( $meta_value ) ) { echo $meta_value[0]; } else { echo 'No specs available'; } ?> </div> </div> </div> </div> </div> <?php } ?> <?php } ?> </div> <?php wp_reset_postdata(); return ob_get_clean(); ``` });
I actually found this: <https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields> I actually just added the following in my CSS file to basically remove the links at all times: ``` .media-sidebar .details .edit-attachment { display: none; } .media-sidebar .details .delete-attachment { display: none; } ``` To actually show this within the admin section I actually show it by using the following code: ``` foreach( array( 'post.php', 'post-new.php' ) as $hook ) add_action( "admin_print_styles-$hook", 'admin_styles_so_25894288'); function admin_styles_so_25894288() { global $typenow; if( 'post' !== $typenow ) return; ?> <style> .media-sidebar .details .delete-attachment { display: block; } .media-sidebar .details .edit-attachment { display: block; } </style> <?php } ``` This is tested in Wordpress 4.0.
174,800
<p>I have a lot of <code>Pages</code> which can be (need to be) grouped under a number of different Categories. ** Then the more important thing is, i need to control those pages (of different groups) programatically via <code>functions.php</code>.</p> <p>Lets say, i would have:</p> <ul> <li>Page A (Categorized as: <code>Fruits</code>)</li> <li>Page B (Categorized as: <code>Vehicles</code>)</li> <li>Page C (Categorized as: <code>Vehicles</code>)</li> <li>Page D (Categorized as: <code>Fruits</code>)</li> <li>Page E (Categorized as: <code>Technology</code>)</li> </ul> <p>Then from <code>functions.php</code>, there would be some logics, like:</p> <ul> <li>If Page is under <code>Fruits</code> Category, then <code>echo "This is related to Fruits.";</code>.</li> <li>If Page is under <code>Vehicles</code> Category, then <code>echo "This is related to Vehicles.";</code>.</li> <li>If Page is under <code>Technology</code> Category, then <code>echo "This is related to Technologies.";</code>.</li> </ul> <p>I dont know this is about Taxonomy or Tagging or Custom Field or something. But:</p> <ul> <li><strong>What is the ideal way to do it please? <em>(Especially to be able to control from backend coding.)</em></strong></li> </ul> <hr> <p>And again please <strong>let me repeat, "Pages"</strong>. <em>(Not about Posts or any other)</em></p>
[ { "answer_id": 174762, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>That link is hard-coded in <code>/wp-includes/media-template.php</code> ~ln 526. Since it can't be removed via apply_filters, you could probably use a small js script like <code>$('a.delete-attachment').remove();</code> to remove the link.</p>\n" }, { "answer_id": 174871, "author": "user1048676", "author_id": 13472, "author_profile": "https://wordpress.stackexchange.com/users/13472", "pm_score": 1, "selected": true, "text": "<p>I actually found this:<br>\n<a href=\"https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields\">https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields</a></p>\n\n<p>I actually just added the following in my CSS file to basically remove the links at all times:</p>\n\n<pre><code>.media-sidebar .details .edit-attachment {\n display: none;\n}\n.media-sidebar .details .delete-attachment {\n display: none;\n}\n</code></pre>\n\n<p>To actually show this within the admin section I actually show it by using the following code:</p>\n\n<pre><code>foreach( array( 'post.php', 'post-new.php' ) as $hook )\n add_action( \"admin_print_styles-$hook\", 'admin_styles_so_25894288');\n\nfunction admin_styles_so_25894288() {\n global $typenow;\n if( 'post' !== $typenow )\n return;\n ?&gt;\n &lt;style&gt;\n .media-sidebar .details .delete-attachment\n { \n display: block; \n }\n .media-sidebar .details .edit-attachment\n { \n display: block; \n }\n &lt;/style&gt;\n &lt;?php\n\n}\n</code></pre>\n\n<p>This is tested in Wordpress 4.0.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35907/" ]
I have a lot of `Pages` which can be (need to be) grouped under a number of different Categories. \*\* Then the more important thing is, i need to control those pages (of different groups) programatically via `functions.php`. Lets say, i would have: * Page A (Categorized as: `Fruits`) * Page B (Categorized as: `Vehicles`) * Page C (Categorized as: `Vehicles`) * Page D (Categorized as: `Fruits`) * Page E (Categorized as: `Technology`) Then from `functions.php`, there would be some logics, like: * If Page is under `Fruits` Category, then `echo "This is related to Fruits.";`. * If Page is under `Vehicles` Category, then `echo "This is related to Vehicles.";`. * If Page is under `Technology` Category, then `echo "This is related to Technologies.";`. I dont know this is about Taxonomy or Tagging or Custom Field or something. But: * **What is the ideal way to do it please? *(Especially to be able to control from backend coding.)*** --- And again please **let me repeat, "Pages"**. *(Not about Posts or any other)*
I actually found this: <https://stackoverflow.com/questions/25894288/wordpress-remove-attachment-fields> I actually just added the following in my CSS file to basically remove the links at all times: ``` .media-sidebar .details .edit-attachment { display: none; } .media-sidebar .details .delete-attachment { display: none; } ``` To actually show this within the admin section I actually show it by using the following code: ``` foreach( array( 'post.php', 'post-new.php' ) as $hook ) add_action( "admin_print_styles-$hook", 'admin_styles_so_25894288'); function admin_styles_so_25894288() { global $typenow; if( 'post' !== $typenow ) return; ?> <style> .media-sidebar .details .delete-attachment { display: block; } .media-sidebar .details .edit-attachment { display: block; } </style> <?php } ``` This is tested in Wordpress 4.0.
174,816
<p>Our client would like to embed his site into an iframe in their software backend. I get a query string on the first link but need to make sure that string persists across URLs for all links and navigation on the iframed site. How do I do that? </p> <p>This only needs to happen when the query string is present. </p> <p>EDIT: Come this far, just don't know what to do to persist the clean=true query where it appears.</p> <pre><code>function add_rewrite_rules($aRules) { $aNewRules = array('^/([^/]+)/?$' =&gt; 'index.php?clean=$matches[1]'); $aRules = $aNewRules + $aRules; return $aRules; } add_filter('rewrite_rules_array', 'add_rewrite_rules'); function add_query_vars($qvars) { $qvars[] = "clean"; return $qvars; } add_filter('query_vars', 'add_query_vars'); </code></pre>
[ { "answer_id": 174928, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>As I understand your Question, you need to hook into most of the Link Filters (which are listed here: <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference#Link_Filters\" rel=\"nofollow\">http://codex.wordpress.org/Plugin_API/Filter_Reference#Link_Filters</a> ) and then add the query to them if the queryvar \"clean\" is set.</p>\n\n<p>Happy Coding,\nKuchenundkakao</p>\n" }, { "answer_id": 272101, "author": "ahendwh2", "author_id": 112098, "author_profile": "https://wordpress.stackexchange.com/users/112098", "pm_score": 1, "selected": false, "text": "<p>You could use some JavaScript to change all links on page load. It's maybe not the best solution, but it works. I've written a <a href=\"https://jsfiddle.net/ahendwh2/9L0wyjs6/\" rel=\"nofollow noreferrer\">JSFiddle</a> for demonstration.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65999/" ]
Our client would like to embed his site into an iframe in their software backend. I get a query string on the first link but need to make sure that string persists across URLs for all links and navigation on the iframed site. How do I do that? This only needs to happen when the query string is present. EDIT: Come this far, just don't know what to do to persist the clean=true query where it appears. ``` function add_rewrite_rules($aRules) { $aNewRules = array('^/([^/]+)/?$' => 'index.php?clean=$matches[1]'); $aRules = $aNewRules + $aRules; return $aRules; } add_filter('rewrite_rules_array', 'add_rewrite_rules'); function add_query_vars($qvars) { $qvars[] = "clean"; return $qvars; } add_filter('query_vars', 'add_query_vars'); ```
You could use some JavaScript to change all links on page load. It's maybe not the best solution, but it works. I've written a [JSFiddle](https://jsfiddle.net/ahendwh2/9L0wyjs6/) for demonstration.
174,831
<p>I've scoured the web for the solution to this small issue, but I keep getting results that tell me how to customise the notification e-mail not the email address.</p> <p>I have the admin email address in the WP settings as [email protected] which is great, but all new user registrations I want to go to a different email address.</p> <p>e.g.</p> <p>New user registered, email is sent to [email protected]</p> <p>Plugins, themes, etc. need updating, all emails go to JUST [email protected]</p>
[ { "answer_id": 174837, "author": "krishna", "author_id": 66009, "author_profile": "https://wordpress.stackexchange.com/users/66009", "pm_score": 3, "selected": false, "text": "<p>Yes, you can Change email address by using wp_mail function.\nYou can check this how to do this \n<a href=\"http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/\" rel=\"nofollow noreferrer\">http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/</a></p>\n\n<p>Use this plugin for user management it supports email address when new user registers\n<a href=\"https://wordpress.org/plugins/wp-members/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-members/</a></p>\n\n<p>Use this code in your functions.php file.</p>\n\n<pre><code>function so174837_registration_email_alert( $user_id ) {\n $user = get_userdata( $user_id );\n $email = $user-&gt;user_email;\n $message = $email . ' has registered to your website.';\n wp_mail( '[email protected]', 'New User registration', $message );\n}\nadd_action('user_register', 'so174837_registration_email_alert');\n</code></pre>\n" }, { "answer_id": 256341, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>I was led to this post while doing a Google search for a particular email question. Funny thing was that the posted answer references one of my blog posts and my plugin. That's kind of awesome - except that I don't think in this case that really answers the OP.</p>\n\n<p>The question was that all notifications to the admin need to go to the specified email address, EXCEPT one - the new user notification.</p>\n\n<p>My approach to that (provided the process was the WP native registration) would be to use a filter on <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">wp_mail()</a> (which, BTW, has <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail\" rel=\"nofollow noreferrer\">a filter at the end of the entire process</a>). </p>\n\n<p>I would use that filter to look at the content of the message and if it was the email being sent for new user notification, then use the filter to change the \"to\" address. </p>\n\n<p>In this example, the subject is examined to see if it contains 'New User Registration' which is part of the subject line in the WP default admin notification email. If that is the case, then the \"to\" email address is changed to the desired address. Otherwise, all other cases pass through the filter untouched.</p>\n\n<pre><code>add_filter( 'wp_mail', 'my_wp_mail_filter' );\nfunction my_wp_mail_filter( $args ) {\n // Check the message subject for a known string in the notification email.\n if ( strpos( $args['subject'], 'New User Registration' ) ) {\n // This is the notification email, so change the \"to\" address.\n $args['to'] = '[email protected]';\n }\n return $args;\n}\n</code></pre>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66010/" ]
I've scoured the web for the solution to this small issue, but I keep getting results that tell me how to customise the notification e-mail not the email address. I have the admin email address in the WP settings as [email protected] which is great, but all new user registrations I want to go to a different email address. e.g. New user registered, email is sent to [email protected] Plugins, themes, etc. need updating, all emails go to JUST [email protected]
Yes, you can Change email address by using wp\_mail function. You can check this how to do this <http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/> Use this plugin for user management it supports email address when new user registers <https://wordpress.org/plugins/wp-members/> Use this code in your functions.php file. ``` function so174837_registration_email_alert( $user_id ) { $user = get_userdata( $user_id ); $email = $user->user_email; $message = $email . ' has registered to your website.'; wp_mail( '[email protected]', 'New User registration', $message ); } add_action('user_register', 'so174837_registration_email_alert'); ```
174,836
<p>I'm facing a strange problem. After I've moved to another server, my wp_enqueue_script calls don't do anything. I do have this function:</p> <pre><code>function moemax_scripts() { wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/lib/bootstrap/css/bootstrap.min.css' ); wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/lib/bootstrap/js/bootstrap.min.js', array(), '3.3.1', true ); wp_enqueue_script( 'main-js', get_template_directory_uri() . '/js/main.min.js', array(), array(), '1.0.0', true ); wp_enqueue_style( 'moemax-style', get_stylesheet_uri() ); wp_enqueue_script( 'moemax-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '1.0.0', true ); wp_enqueue_script( 'moemax-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '1.0.0', true ); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } wp_enqueue_style( 'core-css', get_template_directory_uri() . '/css/core.min.css', false, '1.0.0' ); } </code></pre> <p>The strange thing is, all my css files get included, but none of the js files are added to the site. I tried to change $handle, $ver or even $src but nothing is happening. I don't get any errors in console.</p>
[ { "answer_id": 174837, "author": "krishna", "author_id": 66009, "author_profile": "https://wordpress.stackexchange.com/users/66009", "pm_score": 3, "selected": false, "text": "<p>Yes, you can Change email address by using wp_mail function.\nYou can check this how to do this \n<a href=\"http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/\" rel=\"nofollow noreferrer\">http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/</a></p>\n\n<p>Use this plugin for user management it supports email address when new user registers\n<a href=\"https://wordpress.org/plugins/wp-members/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-members/</a></p>\n\n<p>Use this code in your functions.php file.</p>\n\n<pre><code>function so174837_registration_email_alert( $user_id ) {\n $user = get_userdata( $user_id );\n $email = $user-&gt;user_email;\n $message = $email . ' has registered to your website.';\n wp_mail( '[email protected]', 'New User registration', $message );\n}\nadd_action('user_register', 'so174837_registration_email_alert');\n</code></pre>\n" }, { "answer_id": 256341, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>I was led to this post while doing a Google search for a particular email question. Funny thing was that the posted answer references one of my blog posts and my plugin. That's kind of awesome - except that I don't think in this case that really answers the OP.</p>\n\n<p>The question was that all notifications to the admin need to go to the specified email address, EXCEPT one - the new user notification.</p>\n\n<p>My approach to that (provided the process was the WP native registration) would be to use a filter on <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">wp_mail()</a> (which, BTW, has <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail\" rel=\"nofollow noreferrer\">a filter at the end of the entire process</a>). </p>\n\n<p>I would use that filter to look at the content of the message and if it was the email being sent for new user notification, then use the filter to change the \"to\" address. </p>\n\n<p>In this example, the subject is examined to see if it contains 'New User Registration' which is part of the subject line in the WP default admin notification email. If that is the case, then the \"to\" email address is changed to the desired address. Otherwise, all other cases pass through the filter untouched.</p>\n\n<pre><code>add_filter( 'wp_mail', 'my_wp_mail_filter' );\nfunction my_wp_mail_filter( $args ) {\n // Check the message subject for a known string in the notification email.\n if ( strpos( $args['subject'], 'New User Registration' ) ) {\n // This is the notification email, so change the \"to\" address.\n $args['to'] = '[email protected]';\n }\n return $args;\n}\n</code></pre>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64921/" ]
I'm facing a strange problem. After I've moved to another server, my wp\_enqueue\_script calls don't do anything. I do have this function: ``` function moemax_scripts() { wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/lib/bootstrap/css/bootstrap.min.css' ); wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/lib/bootstrap/js/bootstrap.min.js', array(), '3.3.1', true ); wp_enqueue_script( 'main-js', get_template_directory_uri() . '/js/main.min.js', array(), array(), '1.0.0', true ); wp_enqueue_style( 'moemax-style', get_stylesheet_uri() ); wp_enqueue_script( 'moemax-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '1.0.0', true ); wp_enqueue_script( 'moemax-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '1.0.0', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } wp_enqueue_style( 'core-css', get_template_directory_uri() . '/css/core.min.css', false, '1.0.0' ); } ``` The strange thing is, all my css files get included, but none of the js files are added to the site. I tried to change $handle, $ver or even $src but nothing is happening. I don't get any errors in console.
Yes, you can Change email address by using wp\_mail function. You can check this how to do this <http://www.butlerblog.com/2011/07/14/changing-the-wp_mail-from-address-with-a-plugin/> Use this plugin for user management it supports email address when new user registers <https://wordpress.org/plugins/wp-members/> Use this code in your functions.php file. ``` function so174837_registration_email_alert( $user_id ) { $user = get_userdata( $user_id ); $email = $user->user_email; $message = $email . ' has registered to your website.'; wp_mail( '[email protected]', 'New User registration', $message ); } add_action('user_register', 'so174837_registration_email_alert'); ```
174,850
<p>I'm creating a function in functions.php with a custom hook, and from what I've read somewhere, <strong>it's good practice to return instead of use echo in a WordPress function</strong>? Correct me if I'm wrong.</p> <p>Anyway, so with echo, my function works, but breaks everything else. With return, the function is no longer outputting anything, but nothing's broken. I tried to use <a href="https://wordpress.stackexchange.com/questions/139096/return-vs-echo-shortcode">this question as a reference</a> to fix mine.</p> <p>Here's what I have:</p> <pre><code>function display_collections_menu(){ /* Get WooCommerce's product categories which is custom taxonomy */ $prod_cat_args = array( 'taxonomy' =&gt; 'product_cat', //woocommerce 'orderby' =&gt; 'name', 'empty' =&gt; 0 ); $woo_categories = get_categories( $prod_cat_args ); $woo_menu = ''; $woo_menu.= '&lt;ul class="menu-collections"&gt;'; /* For each first level category, get the image, name, and link */ foreach ( $woo_categories as $woo_cat ) { if( $woo_cat-&gt;category_parent == 0 ) { $woo_cat_id = $woo_cat-&gt;term_id; //category ID $woo_img_id = get_woocommerce_term_meta( $woo_cat_id, 'thumbnail_id', true ); //category image ID $woo_parent_image = wp_get_attachment_url( $woo_img_id ); //category image url $woo_cat_slug = $woo_cat-&gt;slug; //category slug for classes $woo_cat_name = $woo_cat-&gt;name; //category name for link /* return the image/link/name */ $orw_woo_menu.= '&lt;li class="menu-product menu-item menu-item-object-' . $woo_cat_slug . ' "&gt; &lt;a href="' . get_term_link( $woo_cat_slug, 'product_cat' ) . '" class="menu-product-link"&gt; &lt;img src="' . $woo_parent_image . '" alt=" ' . $woo_cat_name . ' " class="menu-product-thumb" /&gt; &lt;p class="menu-product-name"&gt;' . $woo_cat_name . '&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;'; } }//end of $woo_categories foreach $woo_menu.= '&lt;/ul&gt;'; return $woo_menu; } add_action('woo_collections_menu', 'display_collections_menu'); </code></pre> <p>It'll work if instead of using return and a variable, I just echo out the values, but it breaks things. Am I using return wrong?</p> <hr> <p><strong>Updated with an attempt Privateer's solution - still doesn't work:</strong></p> <pre><code>function display_collections_menu( $input = '' ){ /* Get WooCommerce's product categories which is custom taxonomy */ $prod_cat_args = array( 'taxonomy' =&gt; 'product_cat', //woocommerce 'orderby' =&gt; 'name', 'empty' =&gt; 0 ); $woo_categories = get_categories( $prod_cat_args ); $woo_menu = ''; $woo_menu.= '&lt;ul class="menu-collections"&gt;'; /* For each first level category, get the image, name, and link */ foreach ( $woo_categories as $woo_cat ) { if( $woo_cat-&gt;category_parent == 0 ) { $woo_cat_id = $woo_cat-&gt;term_id; //category ID $woo_img_id = get_woocommerce_term_meta( $woo_cat_id, 'thumbnail_id', true ); //category image ID $woo_parent_image = wp_get_attachment_url( $woo_img_id ); //category image url $woo_cat_slug = $woo_cat-&gt;slug; //category slug for classes $woo_cat_name = $woo_cat-&gt;name; //category name for link /* return the image/link/name */ $orw_woo_menu.= '&lt;li class="menu-product menu-item menu-item-object-' . $woo_cat_slug . ' "&gt; &lt;a href="' . get_term_link( $woo_cat_slug, 'product_cat' ) . '" class="menu-product-link"&gt; &lt;img src="' . $woo_parent_image . '" alt=" ' . $woo_cat_name . ' " class="menu-product-thumb" /&gt; &lt;p class="menu-product-name"&gt;' . $woo_cat_name . '&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;'; } }//end of $woo_categories foreach $woo_menu.= '&lt;/ul&gt;'; return $woo_menu; } add_filter('collections_menu', 'display_collections_menu', 10, 1); $html_block = apply_filters('collections_menu', $input_html); </code></pre> <p>And then this in a template:</p> <pre><code>&lt;?php echo $html_block; ?&gt; </code></pre> <p>Am I still doing this wrong?</p>
[ { "answer_id": 174852, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 1, "selected": false, "text": "<p>From my understanding of actions (as opposed to filters), an action simply does something and stops processing. No return value is actually made use of.</p>\n\n<p>You might change your code to be a filter by accepting an argument (say the html to append to) and then make a call like the following where you want to grab the code:</p>\n\n<pre><code>$html_block = apply_filters('woo_collections_menu', $input_html);\n</code></pre>\n\n<p>To do this, you might change your function definition:</p>\n\n<pre><code>function display_collections_menu( $input = '' ){\n #code here\n}\nadd_filter('woo_collections_menu', 'display_collections_menu', 10, 1);\n</code></pre>\n\n<p>That would then put our output into the variable <code>$html_block</code> for use as you see fit.</p>\n" }, { "answer_id": 174876, "author": "RachieVee", "author_id": 42783, "author_profile": "https://wordpress.stackexchange.com/users/42783", "pm_score": 0, "selected": false, "text": "<p>I still couldn't figure out how to return <strong>$woo_menu;</strong> with my first example code, but I realized things don't break if I keep the rest of the structure as far as the variable goes and just echo once at the very end. This seems to work for me. Whether this is good practice or not, leave me a comment, but for now, this is the solution I'm using.</p>\n\n<p>Thanks.</p>\n\n<pre><code>function display_collections_menu(){\n/* Get WooCommerce's product categories which is custom taxonomy */\n $prod_cat_args = array(\n 'taxonomy' =&gt; 'product_cat', //woocommerce\n 'orderby' =&gt; 'name',\n 'empty' =&gt; 0\n );\n\n $woo_categories = get_categories( $prod_cat_args );\n\n $woo_menu = '';\n\n $woo_menu.= '&lt;ul class=\"menu-collections\"&gt;';\n\n /* For each first level category, get the image, name, and link */\n foreach ( $woo_categories as $woo_cat ) {\n\n if( $woo_cat-&gt;category_parent == 0 ) {\n $woo_cat_id = $woo_cat-&gt;term_id; //category ID\n $woo_img_id = get_woocommerce_term_meta( $woo_cat_id, 'thumbnail_id', true ); //category image ID\n $woo_parent_image = wp_get_attachment_url( $woo_img_id ); //category image url\n $woo_cat_slug = $woo_cat-&gt;slug; //category slug for classes\n $woo_cat_name = $woo_cat-&gt;name; //category name for link\n\n /* return the image/link/name */\n $orw_woo_menu.= '&lt;li class=\"menu-product menu-item menu-item-object-' . $woo_cat_slug . ' \"&gt;\n &lt;a href=\"' . get_term_link( $woo_cat_slug, 'product_cat' ) . '\" class=\"menu-product-link\"&gt;\n &lt;img src=\"' . $woo_parent_image . '\" alt=\" ' . $woo_cat_name . ' \" class=\"menu-product-thumb\" /&gt;\n &lt;p class=\"menu-product-name\"&gt;' . $woo_cat_name . '&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;';\n } \n\n }//end of $woo_categories foreach\n\n $woo_menu.= '&lt;/ul&gt;';\n\n echo $woo_menu; //ECHO at the very end instead of return works for me \n}\nadd_action('woo_collections_menu', 'display_collections_menu');\n</code></pre>\n" }, { "answer_id": 174878, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>If you use <code>do_action( 'woo_collections_menu' );</code> in the template, then your function must echo its value. Otherwise, you are <code>return</code>ing the data into a black hole, nothing is outputting what you're returning.</p>\n\n<p>If you use a filter, then you should <code>return</code> the value. The point of a filter is to take a value, filter that value through a function, then do something with the result. In the context of your template, using <code>apply_filters</code> would be a bit strange, because your menu has no value until you construct it. So in the template it would look like:</p>\n\n<pre><code>echo apply_filters( 'collections_menu', '' );\n</code></pre>\n\n<p>Which is just potentially confusing and unnecessary. That empty string could be a default menu or something, but putting that in the template is probably not the wisest choice.</p>\n\n<p>However, a filter <em>would</em> make sense within the function itself, to allow someone to change the output.</p>\n\n<pre><code>function display_collections_menu(){\n $default_menu = 'my complete menu markup here';\n return apply_filters( 'collections_menu', $default_menu );\n}\n</code></pre>\n\n<p>Then in the template, you could just output the function directly:</p>\n\n<pre><code>echo display_collections_menu();\n</code></pre>\n\n<p>and someone can add their own filter to modify output if they'd like. Another helpful inclusion could be a filter on the arguments that you fetch terms with, so someone can change menu output without having to reproduce the whole function.</p>\n\n<p>But going back to your original code, adding <code>do_action( 'woo_collections_menu' );</code> and then echoing menu output directly in the function should also work.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42783/" ]
I'm creating a function in functions.php with a custom hook, and from what I've read somewhere, **it's good practice to return instead of use echo in a WordPress function**? Correct me if I'm wrong. Anyway, so with echo, my function works, but breaks everything else. With return, the function is no longer outputting anything, but nothing's broken. I tried to use [this question as a reference](https://wordpress.stackexchange.com/questions/139096/return-vs-echo-shortcode) to fix mine. Here's what I have: ``` function display_collections_menu(){ /* Get WooCommerce's product categories which is custom taxonomy */ $prod_cat_args = array( 'taxonomy' => 'product_cat', //woocommerce 'orderby' => 'name', 'empty' => 0 ); $woo_categories = get_categories( $prod_cat_args ); $woo_menu = ''; $woo_menu.= '<ul class="menu-collections">'; /* For each first level category, get the image, name, and link */ foreach ( $woo_categories as $woo_cat ) { if( $woo_cat->category_parent == 0 ) { $woo_cat_id = $woo_cat->term_id; //category ID $woo_img_id = get_woocommerce_term_meta( $woo_cat_id, 'thumbnail_id', true ); //category image ID $woo_parent_image = wp_get_attachment_url( $woo_img_id ); //category image url $woo_cat_slug = $woo_cat->slug; //category slug for classes $woo_cat_name = $woo_cat->name; //category name for link /* return the image/link/name */ $orw_woo_menu.= '<li class="menu-product menu-item menu-item-object-' . $woo_cat_slug . ' "> <a href="' . get_term_link( $woo_cat_slug, 'product_cat' ) . '" class="menu-product-link"> <img src="' . $woo_parent_image . '" alt=" ' . $woo_cat_name . ' " class="menu-product-thumb" /> <p class="menu-product-name">' . $woo_cat_name . '</p></a></li>'; } }//end of $woo_categories foreach $woo_menu.= '</ul>'; return $woo_menu; } add_action('woo_collections_menu', 'display_collections_menu'); ``` It'll work if instead of using return and a variable, I just echo out the values, but it breaks things. Am I using return wrong? --- **Updated with an attempt Privateer's solution - still doesn't work:** ``` function display_collections_menu( $input = '' ){ /* Get WooCommerce's product categories which is custom taxonomy */ $prod_cat_args = array( 'taxonomy' => 'product_cat', //woocommerce 'orderby' => 'name', 'empty' => 0 ); $woo_categories = get_categories( $prod_cat_args ); $woo_menu = ''; $woo_menu.= '<ul class="menu-collections">'; /* For each first level category, get the image, name, and link */ foreach ( $woo_categories as $woo_cat ) { if( $woo_cat->category_parent == 0 ) { $woo_cat_id = $woo_cat->term_id; //category ID $woo_img_id = get_woocommerce_term_meta( $woo_cat_id, 'thumbnail_id', true ); //category image ID $woo_parent_image = wp_get_attachment_url( $woo_img_id ); //category image url $woo_cat_slug = $woo_cat->slug; //category slug for classes $woo_cat_name = $woo_cat->name; //category name for link /* return the image/link/name */ $orw_woo_menu.= '<li class="menu-product menu-item menu-item-object-' . $woo_cat_slug . ' "> <a href="' . get_term_link( $woo_cat_slug, 'product_cat' ) . '" class="menu-product-link"> <img src="' . $woo_parent_image . '" alt=" ' . $woo_cat_name . ' " class="menu-product-thumb" /> <p class="menu-product-name">' . $woo_cat_name . '</p></a></li>'; } }//end of $woo_categories foreach $woo_menu.= '</ul>'; return $woo_menu; } add_filter('collections_menu', 'display_collections_menu', 10, 1); $html_block = apply_filters('collections_menu', $input_html); ``` And then this in a template: ``` <?php echo $html_block; ?> ``` Am I still doing this wrong?
If you use `do_action( 'woo_collections_menu' );` in the template, then your function must echo its value. Otherwise, you are `return`ing the data into a black hole, nothing is outputting what you're returning. If you use a filter, then you should `return` the value. The point of a filter is to take a value, filter that value through a function, then do something with the result. In the context of your template, using `apply_filters` would be a bit strange, because your menu has no value until you construct it. So in the template it would look like: ``` echo apply_filters( 'collections_menu', '' ); ``` Which is just potentially confusing and unnecessary. That empty string could be a default menu or something, but putting that in the template is probably not the wisest choice. However, a filter *would* make sense within the function itself, to allow someone to change the output. ``` function display_collections_menu(){ $default_menu = 'my complete menu markup here'; return apply_filters( 'collections_menu', $default_menu ); } ``` Then in the template, you could just output the function directly: ``` echo display_collections_menu(); ``` and someone can add their own filter to modify output if they'd like. Another helpful inclusion could be a filter on the arguments that you fetch terms with, so someone can change menu output without having to reproduce the whole function. But going back to your original code, adding `do_action( 'woo_collections_menu' );` and then echoing menu output directly in the function should also work.
174,855
<p>I created a page and selected the "Full-width Page Template, No Sidebar" option in the Twenty-Twelve Theme. The viewed page has the following body tag:</p> <pre><code>&lt;body class="page page-id-2 page-template page-template-page-templates page-template-full-width page-template-page-templatesfull-width-php logged-in admin-bar full-width custom-font-enabled single-author customize-support"&gt; </code></pre> <p>I want to create a child theme with a custom full width page, but I am not sure why I would need to include so many similar classes, or what the best practice would be for creating them. Most of them do not appear to actually be used in styling the page. For example, I can't see the use for page-template-page-templatesfull-width-php. Perhaps it is a bug.</p>
[ { "answer_id": 174858, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Those classes are output by the <a href=\"http://codex.wordpress.org/Function_Reference/body_class\" rel=\"nofollow\"><code>body_class</code></a> function, which can be filtered by plugins to add their own classes. You don't need to (and shouldn't) harcode classes into the body tag in your template, just add that function within the body tag:</p>\n\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 174879, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 0, "selected": false, "text": "<p>Twenty Twelve adds for instance the CSS class <code>.full-width</code> to the body_class via a filter function in functions.php of the theme when the buld-in 'Full-width Page Template, No Sidebar' template gets used. \nCorresponding code from Twenty Twelve:</p>\n\n<pre><code>if ( ! is_active_sidebar( 'sidebar-1' ) || is_page_template( 'page-templates/full-width.php' ) )\n $classes[] = 'full-width';\n</code></pre>\n\n<p>This CSS class is used within style.css to format the full width pages.\nTo make formatting easier, you might want to consider to do the same for your page template.</p>\n\n<p>Possible code for a child theme (based on the file name and location of the custom page template - example <strong>/page-templates/custom-full-width.php</strong>):</p>\n\n<pre><code>function wpse_174855_twentytwelve_child_body_class( $classes ) {\n if( is_page_template( 'page-templates/custom-full-width.php' ) ) {\n $classes[] = 'full-width';\n }\n return $classes; \n}\nadd_filter( 'body_class', 'wpse_174855_twentytwelve_child_body_class', 20 );\n</code></pre>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64351/" ]
I created a page and selected the "Full-width Page Template, No Sidebar" option in the Twenty-Twelve Theme. The viewed page has the following body tag: ``` <body class="page page-id-2 page-template page-template-page-templates page-template-full-width page-template-page-templatesfull-width-php logged-in admin-bar full-width custom-font-enabled single-author customize-support"> ``` I want to create a child theme with a custom full width page, but I am not sure why I would need to include so many similar classes, or what the best practice would be for creating them. Most of them do not appear to actually be used in styling the page. For example, I can't see the use for page-template-page-templatesfull-width-php. Perhaps it is a bug.
Those classes are output by the [`body_class`](http://codex.wordpress.org/Function_Reference/body_class) function, which can be filtered by plugins to add their own classes. You don't need to (and shouldn't) harcode classes into the body tag in your template, just add that function within the body tag: ``` <body <?php body_class(); ?>> ```
174,859
<p>I have created custom post type for videos. Here is my code.</p> <pre><code>function video_register() { $labels = array( 'name' =&gt; _x('Video', 'post type general name'), 'singular_name' =&gt; _x('Video', 'post type singular name'), 'add_new' =&gt; _x('Add New', 'video'), 'add_new_item' =&gt; __('Add New Video'), 'edit_item' =&gt; __('Edit Video'), 'new_item' =&gt; __('New Video'), 'view_item' =&gt; __('View Video'), 'search_items' =&gt; __('Search Videos'), 'not_found' =&gt; __('Nothing found'), 'not_found_in_trash' =&gt; __('Nothing found in Trash'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_icon' =&gt; null, 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array('title', 'editor', 'thumbnail', 'comments', 'custom-fields') ); register_post_type('video', $args); } </code></pre> <p>and I have displayed this video post at home page using this code.</p> <pre><code>$paged = (get_query_var('page')) ? get_query_var('page') : 1; $temp = $wp_query; $wp_query= null; $vcount = 20; $wp_query = new WP_Query(); $wp_query-&gt;query('posts_per_page='.$vcount.'&amp;post_type=video&amp;paged='.$paged); </code></pre> <p>It all working fine. But its pagination is giving me 404 error when I hit to /page/2. </p> <p>This pagination is showing me at homepage only. On category pages it is working fine. I did not understand what I have mistaken. I searched every where on internet but could not found any solution. Please suggest me what is wrong with my code.</p>
[ { "answer_id": 174858, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Those classes are output by the <a href=\"http://codex.wordpress.org/Function_Reference/body_class\" rel=\"nofollow\"><code>body_class</code></a> function, which can be filtered by plugins to add their own classes. You don't need to (and shouldn't) harcode classes into the body tag in your template, just add that function within the body tag:</p>\n\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 174879, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 0, "selected": false, "text": "<p>Twenty Twelve adds for instance the CSS class <code>.full-width</code> to the body_class via a filter function in functions.php of the theme when the buld-in 'Full-width Page Template, No Sidebar' template gets used. \nCorresponding code from Twenty Twelve:</p>\n\n<pre><code>if ( ! is_active_sidebar( 'sidebar-1' ) || is_page_template( 'page-templates/full-width.php' ) )\n $classes[] = 'full-width';\n</code></pre>\n\n<p>This CSS class is used within style.css to format the full width pages.\nTo make formatting easier, you might want to consider to do the same for your page template.</p>\n\n<p>Possible code for a child theme (based on the file name and location of the custom page template - example <strong>/page-templates/custom-full-width.php</strong>):</p>\n\n<pre><code>function wpse_174855_twentytwelve_child_body_class( $classes ) {\n if( is_page_template( 'page-templates/custom-full-width.php' ) ) {\n $classes[] = 'full-width';\n }\n return $classes; \n}\nadd_filter( 'body_class', 'wpse_174855_twentytwelve_child_body_class', 20 );\n</code></pre>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66024/" ]
I have created custom post type for videos. Here is my code. ``` function video_register() { $labels = array( 'name' => _x('Video', 'post type general name'), 'singular_name' => _x('Video', 'post type singular name'), 'add_new' => _x('Add New', 'video'), 'add_new_item' => __('Add New Video'), 'edit_item' => __('Edit Video'), 'new_item' => __('New Video'), 'view_item' => __('View Video'), 'search_items' => __('Search Videos'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'menu_icon' => null, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('title', 'editor', 'thumbnail', 'comments', 'custom-fields') ); register_post_type('video', $args); } ``` and I have displayed this video post at home page using this code. ``` $paged = (get_query_var('page')) ? get_query_var('page') : 1; $temp = $wp_query; $wp_query= null; $vcount = 20; $wp_query = new WP_Query(); $wp_query->query('posts_per_page='.$vcount.'&post_type=video&paged='.$paged); ``` It all working fine. But its pagination is giving me 404 error when I hit to /page/2. This pagination is showing me at homepage only. On category pages it is working fine. I did not understand what I have mistaken. I searched every where on internet but could not found any solution. Please suggest me what is wrong with my code.
Those classes are output by the [`body_class`](http://codex.wordpress.org/Function_Reference/body_class) function, which can be filtered by plugins to add their own classes. You don't need to (and shouldn't) harcode classes into the body tag in your template, just add that function within the body tag: ``` <body <?php body_class(); ?>> ```
174,863
<p>I have the following filter, but do not know how to add custom attributes to image field, when attaching media to post.</p> <p>example</p> <pre><code>&lt;img data-ext-link-title="" data-ext-link-url=""&gt; </code></pre> <p>functions.php</p> <pre><code>function pp_external_link_edit( $form_fields, $post ) { $form_fields['pp-external-link-title'] = array( 'label' =&gt; 'External Link Title', 'input' =&gt; 'text', 'value' =&gt; get_post_meta( $post-&gt;ID, 'pp_external_link_title', true ), 'helps' =&gt; 'Link for button at bottom of pretty photo modal', ); $form_fields['pp-external-link-url'] = array( 'label' =&gt; 'External Link URL', 'input' =&gt; 'text', 'value' =&gt; get_post_meta( $post-&gt;ID, 'pp_external_link_url', true ), 'helps' =&gt; 'Link for button at bottom of pretty photo modal', ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'pp_external_link_edit', 10, 2 ); function pp_external_link_save( $post, $attachment ) { if( isset( $attachment['pp-external-link-title'] ) ) update_post_meta( $post['ID'], 'pp_external_link_title', $attachment['pp-external-link-title']); if( isset( $attachment['pp-external-link-url'] ) ) update_post_meta( $post['ID'], 'pp_external_link_url', $attachment['pp-external-link-url']); return $post; } add_filter( 'attachment_fields_to_save', 'pp_external_link_save', 10, 2 ); </code></pre>
[ { "answer_id": 175804, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I wonder if you want to modify the HTML of the inserted image, with the <code>image_send_to_editor</code> or <code>get_image_tag</code> filters?</p>\n\n<p>If that's the case, then here's one example:</p>\n\n<pre><code>/** \n * Add the data-ext-link-title and data-ext-link-url attributes to inserted images. \n */\n\nadd_filter( 'image_send_to_editor',\n function( $html, $id, $caption, $title, $align, $url, $size, $alt )\n { \n if( $id &gt; 0 )\n {\n $ext_title = get_post_meta( $id, 'pp_external_link_title', true ); \n $ext_url = get_post_meta( $id, 'pp_external_link_url', true ); \n $data = sprintf( ' data-ext-link-title=\"%s\" ', esc_attr( $ext_title ) );\n $data .= sprintf( ' data-ext-link-url=\"%s\" ', esc_url( $ext_url ) );\n $html = str_replace( \"&lt;img src\", \"&lt;img{$data}src\", $html );\n }\n return $html;\n }\n, 10, 8 );\n</code></pre>\n\n<p>Here I assume you want empty <code>data-ext-link-title</code> or <code>data-ext-link-url</code> attributes, if the corresponding meta values are empty or missing.</p>\n\n<p>Hopefully you can adjust this to your needs.</p>\n" }, { "answer_id": 176406, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 0, "selected": false, "text": "<p>I was doing something similar the other day and simply could not get attachment_fields_to_save to work no matter what I tried.</p>\n\n<p>I ended up using the edit_attachment filter instead along with code like the following:</p>\n\n<pre><code>public function action_edit_attachment( $attachment_id ) {\n # Check to make sure we were sent by the side of the media editor, not by the real edit form\n # - if the real edit form was used, action would be editpost instead\n if ( isset($_REQUEST['action']) ) {\n $our_fields = array(\n 'pp-external-link-title' =&gt; 'text',\n 'pp-external-link-url' =&gt; 'text'\n );\n foreach ( $our_fields as $field_name =&gt; $input_type ) {\n if ( isset( $_REQUEST['attachments'][$attachment_id][\"{$field_name}\"] ) ) {\n switch ( \"{$input_type}\" ) {\n case 'text':\n $value = stripcslashes($_REQUEST['attachments'][$attachment_id][\"{$field_name}\"]);\n update_post_meta( $attachment_id, \"{$field_name}\", $value );\n break;\n default:\n # Not implemented\n break;\n }\n }\n }\n }\n return $attachment_id;\n}\nadd_filter( 'edit_attachment', 'action_edit_attachment' );\n</code></pre>\n\n<p>If you only want it to save from the media screen, you could change the _REQUEST check</p>\n\n<pre><code>if ( isset($_REQUEST['action']) &amp;&amp; 'save-attachment-compat' == \"{$_REQUEST['action']}\" ) {\n</code></pre>\n\n<p>Or from the full attachment post editor</p>\n\n<pre><code>if ( isset($_REQUEST['action']) &amp;&amp; 'editpost' == \"{$_REQUEST['action']}\" ) {\n</code></pre>\n\n<p>Anywise, I had no luck with the older method ... and saw at least a few people had just as much difficulty with it as I did.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174863", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3178/" ]
I have the following filter, but do not know how to add custom attributes to image field, when attaching media to post. example ``` <img data-ext-link-title="" data-ext-link-url=""> ``` functions.php ``` function pp_external_link_edit( $form_fields, $post ) { $form_fields['pp-external-link-title'] = array( 'label' => 'External Link Title', 'input' => 'text', 'value' => get_post_meta( $post->ID, 'pp_external_link_title', true ), 'helps' => 'Link for button at bottom of pretty photo modal', ); $form_fields['pp-external-link-url'] = array( 'label' => 'External Link URL', 'input' => 'text', 'value' => get_post_meta( $post->ID, 'pp_external_link_url', true ), 'helps' => 'Link for button at bottom of pretty photo modal', ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'pp_external_link_edit', 10, 2 ); function pp_external_link_save( $post, $attachment ) { if( isset( $attachment['pp-external-link-title'] ) ) update_post_meta( $post['ID'], 'pp_external_link_title', $attachment['pp-external-link-title']); if( isset( $attachment['pp-external-link-url'] ) ) update_post_meta( $post['ID'], 'pp_external_link_url', $attachment['pp-external-link-url']); return $post; } add_filter( 'attachment_fields_to_save', 'pp_external_link_save', 10, 2 ); ```
I wonder if you want to modify the HTML of the inserted image, with the `image_send_to_editor` or `get_image_tag` filters? If that's the case, then here's one example: ``` /** * Add the data-ext-link-title and data-ext-link-url attributes to inserted images. */ add_filter( 'image_send_to_editor', function( $html, $id, $caption, $title, $align, $url, $size, $alt ) { if( $id > 0 ) { $ext_title = get_post_meta( $id, 'pp_external_link_title', true ); $ext_url = get_post_meta( $id, 'pp_external_link_url', true ); $data = sprintf( ' data-ext-link-title="%s" ', esc_attr( $ext_title ) ); $data .= sprintf( ' data-ext-link-url="%s" ', esc_url( $ext_url ) ); $html = str_replace( "<img src", "<img{$data}src", $html ); } return $html; } , 10, 8 ); ``` Here I assume you want empty `data-ext-link-title` or `data-ext-link-url` attributes, if the corresponding meta values are empty or missing. Hopefully you can adjust this to your needs.
174,874
<p>For example somebody replies-</p> <p>Hi! This is a Comment!</p> <p>but is published as </p> <p>Text- Hi! This is a Comment!</p> <p>Any ideas folks? I'm totally stumped. I want to add the extra text so it appears within the comment rather than before/around it in the theme.</p>
[ { "answer_id": 174877, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You can try the <a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/comment-template.php#L852\" rel=\"nofollow\"><code>comment_text</code></a> filter:</p>\n\n<pre><code>/**\n * Prepend text to each comment content.\n */\n\nadd_filter( 'comment_text', function( $comment_text )\n{\n $text = 'Some text';\n return $text . $comment_text;\n});\n</code></pre>\n\n<p>if you're displaying the comment text with:</p>\n\n<pre><code>&lt;?php comment_text(); ?&gt;\n</code></pre>\n" }, { "answer_id": 174987, "author": "Spacecat22", "author_id": 65965, "author_profile": "https://wordpress.stackexchange.com/users/65965", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n function addText() { \n var input = document.getElementById('comment');\n input.value = 'lots of new text ' + input.value;\n }\n&lt;/script&gt;\n\n&lt;p class=\"comment-form-comment\"&gt;\n&lt;label for=\"comment\"&gt;Comment&lt;/label&gt;\n&lt;textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" aria-describedby=\"form-allowed-tags\" aria-required=\"true\"&gt;\n&lt;/textarea&gt;\n&lt;/p&gt; \n</code></pre>\n\n<p>Ripped bits and pieces from elsewhere online.. eventually. Thanks for the help.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65965/" ]
For example somebody replies- Hi! This is a Comment! but is published as Text- Hi! This is a Comment! Any ideas folks? I'm totally stumped. I want to add the extra text so it appears within the comment rather than before/around it in the theme.
You can try the [`comment_text`](https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/comment-template.php#L852) filter: ``` /** * Prepend text to each comment content. */ add_filter( 'comment_text', function( $comment_text ) { $text = 'Some text'; return $text . $comment_text; }); ``` if you're displaying the comment text with: ``` <?php comment_text(); ?> ```
174,880
<p>Specifically, I am using the <code>add_image_attachment_fields_to_edit</code> function. I have my declaration of label, input..</p> <pre><code>$form_fields["custom4"]["label"] = __("Custom Select"); $form_fields["custom4"]["input"] = "html"; </code></pre> <p>But when I try to iterate through my categories for the select, I get errors, or an empty html select. So far I have..</p> <pre><code>$form_fields["custom4"]["html"] = " &lt;select name='attachments[{$post-&gt;ID}][custom4]' id='attachments[{$post-&gt;ID}][custom4]'&gt;" . foreach ($categories as $category) { return "&lt;option value=$category&gt;$category&lt;/option&gt;"; } . " &lt;/select&gt;"; </code></pre> <p>Is it possible to run a foreach loop within the <code>$form_fields</code> assignment, how can I create an html select constructed with my category names?</p>
[ { "answer_id": 174877, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You can try the <a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/comment-template.php#L852\" rel=\"nofollow\"><code>comment_text</code></a> filter:</p>\n\n<pre><code>/**\n * Prepend text to each comment content.\n */\n\nadd_filter( 'comment_text', function( $comment_text )\n{\n $text = 'Some text';\n return $text . $comment_text;\n});\n</code></pre>\n\n<p>if you're displaying the comment text with:</p>\n\n<pre><code>&lt;?php comment_text(); ?&gt;\n</code></pre>\n" }, { "answer_id": 174987, "author": "Spacecat22", "author_id": 65965, "author_profile": "https://wordpress.stackexchange.com/users/65965", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n function addText() { \n var input = document.getElementById('comment');\n input.value = 'lots of new text ' + input.value;\n }\n&lt;/script&gt;\n\n&lt;p class=\"comment-form-comment\"&gt;\n&lt;label for=\"comment\"&gt;Comment&lt;/label&gt;\n&lt;textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" aria-describedby=\"form-allowed-tags\" aria-required=\"true\"&gt;\n&lt;/textarea&gt;\n&lt;/p&gt; \n</code></pre>\n\n<p>Ripped bits and pieces from elsewhere online.. eventually. Thanks for the help.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65912/" ]
Specifically, I am using the `add_image_attachment_fields_to_edit` function. I have my declaration of label, input.. ``` $form_fields["custom4"]["label"] = __("Custom Select"); $form_fields["custom4"]["input"] = "html"; ``` But when I try to iterate through my categories for the select, I get errors, or an empty html select. So far I have.. ``` $form_fields["custom4"]["html"] = " <select name='attachments[{$post->ID}][custom4]' id='attachments[{$post->ID}][custom4]'>" . foreach ($categories as $category) { return "<option value=$category>$category</option>"; } . " </select>"; ``` Is it possible to run a foreach loop within the `$form_fields` assignment, how can I create an html select constructed with my category names?
You can try the [`comment_text`](https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/comment-template.php#L852) filter: ``` /** * Prepend text to each comment content. */ add_filter( 'comment_text', function( $comment_text ) { $text = 'Some text'; return $text . $comment_text; }); ``` if you're displaying the comment text with: ``` <?php comment_text(); ?> ```
174,885
<p>Is there a way for the menu to be translated when I choose the website language? Does anyone have a solution to do it without using the plugin?</p>
[ { "answer_id": 175073, "author": "Vincent Wong", "author_id": 66041, "author_profile": "https://wordpress.stackexchange.com/users/66041", "pm_score": 1, "selected": false, "text": "<p>You can create a menu use another language. Then you use conditional code to switch the menu. or you can use title attribute of menu.</p>\n\n<pre><code>if($language=='us'):\nwp_nav_menu(menu1);\nelse:\nwp_nav_menu(menu2);\nendif;\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/AQ6sD.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 246777, "author": "elicohenator", "author_id": 98507, "author_profile": "https://wordpress.stackexchange.com/users/98507", "pm_score": 0, "selected": false, "text": "<p>you could use Polylang plugin which will create different template for each language, and integrate different menu for each language.</p>\n\n<p>start reading here and dig in: <a href=\"https://wordpress.org/plugins/polylang/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/polylang/</a></p>\n" }, { "answer_id": 286946, "author": "Sam Bull", "author_id": 121281, "author_profile": "https://wordpress.stackexchange.com/users/121281", "pm_score": 0, "selected": false, "text": "<p>I just wrote a simple hook to use the normal translation functions, which I just added into my theme's <code>functions.php</code> file.</p>\n\n<pre><code>/** Translate menu items. */\nfunction translate_menu_item_frontend($item_output, $item) {\n if (property_exists($item, 'title')) {\n $parts = explode('|', $item-&gt;title);\n $context = count($parts) &gt; 1 ? $parts[0] : null;\n $text = end($parts);\n\n return preg_replace(\n '/(&lt;.*?&gt;).*(&lt;\\/.*?&gt;)/s', '$1' . _x($text, $context) . '$2', $item_output, 1);\n }\n\n return $item_output;\n}\nadd_filter('walker_nav_menu_start_el', 'translate_menu_item_frontend', 20, 2);\nadd_filter('megamenu_walker_nav_menu_start_el', 'translate_menu_item_frontend', 20, 2);\n</code></pre>\n\n<p>This means you can, for example, set a menu item navigation label to 'Home' and it will be translated with the builtin core translations. You can also specify a context separated with <code>|</code>, so for example 'Theme starter content|Contact' would use the builtin core translations for the word 'Contact'.</p>\n\n<p>This can easily be adapted to support custom domains if you want to provide your own translations too.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65666/" ]
Is there a way for the menu to be translated when I choose the website language? Does anyone have a solution to do it without using the plugin?
You can create a menu use another language. Then you use conditional code to switch the menu. or you can use title attribute of menu. ``` if($language=='us'): wp_nav_menu(menu1); else: wp_nav_menu(menu2); endif; ``` ![enter image description here](https://i.stack.imgur.com/AQ6sD.jpg)
174,886
<p>How can limit the size of posts that authors can create on my WordPress site and the number of posts they can create?</p>
[ { "answer_id": 174901, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 2, "selected": true, "text": "<p>The best way I know of would be to filter the data.</p>\n\n<p>For posts, you might do:</p>\n\n<pre><code>function my_check_post_not_crazy( $data, $post_arr ) {\n $max_content_length = 2048; # max length in characters\n $max_num_posts = 200; # maximum number of posts\n\n if ( !current_user_can('activate_plugins') &amp;&amp; empty( $post_arr['ID'] ) ) {\n $die_args = array('back_link' =&gt; true);\n # Not an admin user and trying to add another post of some type\n if ( strlen($data['post_content']) &gt; $max_content_length ) {\n # Too long\n wp_die(\"{$max_content_length} characters maximum\", 'Cannot Post', $die_args);\n }\n\n $args = array( \n 'author' =&gt; $data['post_author'],\n 'posts_per_page' =&gt; 1\n );\n $posts = new WP_Query( $args );\n if ( $posts-&gt;found_posts &gt;= $max_per_user ) {\n wp_die(\"{$max_num_posts} per user. Limit Reached.\", 'Cannot Post', $die_args );\n }\n }\n}\nadd_filter('wp_insert_post_data', 'my_check_post_not_crazy', 10, 2 );\n</code></pre>\n\n<p>The same idea works for attachments using the wp_insert_attachment_data filter.</p>\n\n<p>I just realized a couple of things looking at this again:</p>\n\n<ol>\n<li>Rather than stop them from posting a new post, it would be more user friendly to prevent them from trying in the first place. Maybe there is a hook to check and see if they can post, grab their current post count, and then give a message right when they click \"New Post\".</li>\n<li>Rather than setting back_link to true when they have exceeded their post length, it would be more user friendly to set it to false and tell them to hit the back button. I think that will ensure they still have their new text in the editor so they can adjust it. Another option would be to use javascript to track the length of the post and alert/abort with an error if they try to save/publish when there is too much content. </li>\n</ol>\n" }, { "answer_id": 174991, "author": "Yosi Mor", "author_id": 31324, "author_profile": "https://wordpress.stackexchange.com/users/31324", "pm_score": 0, "selected": false, "text": "<p>A partial solution, that addresses the second half of your request -- i.e. limiting the <strong>number</strong> of posts allowed, on a per-user basis -- would be to use the \"<a href=\"http://wordpress.org/plugins/bainternet-posts-creation-limits/\" rel=\"nofollow\"><strong>Bainternet Posts Creation Limits</strong></a>\" plugin.</p>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64351/" ]
How can limit the size of posts that authors can create on my WordPress site and the number of posts they can create?
The best way I know of would be to filter the data. For posts, you might do: ``` function my_check_post_not_crazy( $data, $post_arr ) { $max_content_length = 2048; # max length in characters $max_num_posts = 200; # maximum number of posts if ( !current_user_can('activate_plugins') && empty( $post_arr['ID'] ) ) { $die_args = array('back_link' => true); # Not an admin user and trying to add another post of some type if ( strlen($data['post_content']) > $max_content_length ) { # Too long wp_die("{$max_content_length} characters maximum", 'Cannot Post', $die_args); } $args = array( 'author' => $data['post_author'], 'posts_per_page' => 1 ); $posts = new WP_Query( $args ); if ( $posts->found_posts >= $max_per_user ) { wp_die("{$max_num_posts} per user. Limit Reached.", 'Cannot Post', $die_args ); } } } add_filter('wp_insert_post_data', 'my_check_post_not_crazy', 10, 2 ); ``` The same idea works for attachments using the wp\_insert\_attachment\_data filter. I just realized a couple of things looking at this again: 1. Rather than stop them from posting a new post, it would be more user friendly to prevent them from trying in the first place. Maybe there is a hook to check and see if they can post, grab their current post count, and then give a message right when they click "New Post". 2. Rather than setting back\_link to true when they have exceeded their post length, it would be more user friendly to set it to false and tell them to hit the back button. I think that will ensure they still have their new text in the editor so they can adjust it. Another option would be to use javascript to track the length of the post and alert/abort with an error if they try to save/publish when there is too much content.
174,889
<p>By default whenever you disable indexing via Admin Settings </p> <blockquote> <p>[ x ] Discourage search engines from indexing this site</p> </blockquote> <p>It adds a meta tag in the header like so:</p> <pre><code>&lt;meta name='robots' content='noindex,follow' /&gt; </code></pre> <p>How do I change that to be <code>nofollow</code> instead of <code>follow</code>? I find it odd it enables "follow" and overall want it <code>noindex,nofollow</code>.</p> <p>I could echo directly into <code>wp_head</code> but this doesn't account for pages such as wp-login and the likes.</p>
[ { "answer_id": 174891, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>I suppose this ended up working for me. I was more hoping for some kind of better filter but it works just as well. Throw this in a <code>functions.php</code> file and you're good to go.</p>\n\n<pre><code>/** No Index No Follow Entire Website **/\nfunction nofollow_meta() {\n echo \"&lt;meta name='robots' content='noindex,nofollow' /&gt;\\n\";\n}\nadd_action( 'wp_head', 'nofollow_meta', 1 );\nadd_action( 'login_enqueue_scripts', 'nofollow_meta', 1 );\n</code></pre>\n" }, { "answer_id": 174892, "author": "Andrew Bartel", "author_id": 17879, "author_profile": "https://wordpress.stackexchange.com/users/17879", "pm_score": 3, "selected": true, "text": "<p>Thought this was a great question so I went digging. In default-filters.php on line 208 there's <code>add_action('wp_head', 'noindex', 1);</code> as of WordPress 4.1. The noindex() function in turn checks to see if you have set blog_public option to 0. If you have, it calls wp_no_robots() which is simply:</p>\n\n<pre><code>function wp_no_robots() {\n echo \"&lt;meta name='robots' content='noindex,follow' /&gt;\\n\";\n}\n</code></pre>\n\n<p>Neither of last methods are filterable, but a simple plugin will do the trick to remove the hook:</p>\n\n<pre><code>/*\n * Declare plugin stuff here\n */\n\nremove_action('wp_head','noindex',1);\n</code></pre>\n\n<p>Now, you're free to hook your own action on to echo out what you want.</p>\n\n<pre><code>add_action('wp_head', 'my_no_follow', 1);\n\nfunction my_no_follow() {\n if ( '0' == get_option('blog_public') ) {\n echo \"&lt;meta name='robots' content='noindex,nofollow' /&gt;\\n\";\n }\n}\n</code></pre>\n" } ]
2015/01/14
[ "https://wordpress.stackexchange.com/questions/174889", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7355/" ]
By default whenever you disable indexing via Admin Settings > > [ x ] Discourage search engines from indexing this site > > > It adds a meta tag in the header like so: ``` <meta name='robots' content='noindex,follow' /> ``` How do I change that to be `nofollow` instead of `follow`? I find it odd it enables "follow" and overall want it `noindex,nofollow`. I could echo directly into `wp_head` but this doesn't account for pages such as wp-login and the likes.
Thought this was a great question so I went digging. In default-filters.php on line 208 there's `add_action('wp_head', 'noindex', 1);` as of WordPress 4.1. The noindex() function in turn checks to see if you have set blog\_public option to 0. If you have, it calls wp\_no\_robots() which is simply: ``` function wp_no_robots() { echo "<meta name='robots' content='noindex,follow' />\n"; } ``` Neither of last methods are filterable, but a simple plugin will do the trick to remove the hook: ``` /* * Declare plugin stuff here */ remove_action('wp_head','noindex',1); ``` Now, you're free to hook your own action on to echo out what you want. ``` add_action('wp_head', 'my_no_follow', 1); function my_no_follow() { if ( '0' == get_option('blog_public') ) { echo "<meta name='robots' content='noindex,nofollow' />\n"; } } ```
174,900
<p>I have a wordpress page which loads all the artists in two columns... here is what I believe to be the relevant bit of code</p> <pre><code>&lt;?php global $paged; if ( is_front_page() ) { $paged = (get_query_var('page')) ? get_query_var('page') : 1; } else { $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; } query_posts(array( 'post_type' =&gt; 'artists', 'posts_per_page' =&gt; $ppp_artists, 'order' =&gt; $order, 'orderby' =&gt; $orderby, 'paged' =&gt; $paged )); if ( have_posts() ) : ?&gt; &lt;div class="remix_items grid clearfix &lt;?php echo $artists_col; ?&gt;"&gt; &lt;?php while ( have_posts() ): the_post(); ?&gt; &lt;a class="item" href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;" rel="bookmark"&gt; &lt;figure class="effect-bubba"&gt; &lt;?php the_post_thumbnail('type_cover'); ?&gt; &lt;figcaption&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;/figcaption&gt; &lt;/figure&gt; &lt;/a&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; </code></pre> <p>I think I need to change the </p> <pre><code>'posts_per_page' =&gt; $ppp_artists, </code></pre> <p>which is earlier defined where </p> <pre><code>global $post; $artists_col = 'two_col'; $ppp_artists = ot_get_option('ppp_artists'); $orderby = ot_get_option('artists_orderby'); $order = ot_get_option('artists_order'); </code></pre> <p>But what needs to be changed to make this only load 2 items? and not have pages buttons.</p>
[ { "answer_id": 174902, "author": "Henry Aspden", "author_id": 58960, "author_profile": "https://wordpress.stackexchange.com/users/58960", "pm_score": 0, "selected": false, "text": "<p>so i removed the pagination by removing this from lower</p>\n\n<pre><code>&lt;?php get_template_part('inc/pagination'); ?&gt;\n &lt;?php else: ?&gt;\n &lt;h3&gt;&lt;?php echo ot_get_option('no_artists'); ?&gt;&lt;/h3&gt;\n</code></pre>\n\n<p>then changed</p>\n\n<pre><code>$ppp_artists = ot_get_option('ppp_artists');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$ppp_artists = 2;\n</code></pre>\n\n<p>which changed the number of posts to 2 however I need to load the first 2 posts not the last two so now I need to change it to load the oldest posts somehow :/</p>\n\n<p>I changed the array at the top to </p>\n\n<p>global $post;\n $artists_col = 'two_col';\n $ppp_artists = 2;\n $orderby = date;\n $order = ASC;</p>\n\n<p>and I was away !</p>\n" }, { "answer_id": 174903, "author": "Leo Caseiro", "author_id": 52791, "author_profile": "https://wordpress.stackexchange.com/users/52791", "pm_score": 2, "selected": true, "text": "<p>if you want to show only 2, put it as a value, like so:</p>\n\n<pre><code>'posts_per_page' =&gt; 2\n</code></pre>\n\n<p>For the newest posts, you need to change the sort using the order and orderby params:</p>\n\n<pre><code>'orderby' =&gt; 'date',\n'order' =&gt; 'ASC'\n</code></pre>\n\n<p>Details about orderby params here: <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\">http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters</a></p>\n\n<p>Also, you should avoid the query_posts use. Except if you are using a part of your page only, I believe that's the case.</p>\n\n<p>On Codex you can see on description about avoiding the query_posts use.</p>\n\n<p>Check this video where a WP Core developer talks about query_posts and so on: <a href=\"http://wordpress.tv/2013/03/15/andrew-nacin-wp_query-wordpress-in-depth/\" rel=\"nofollow\">http://wordpress.tv/2013/03/15/andrew-nacin-wp_query-wordpress-in-depth/</a></p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174900", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58960/" ]
I have a wordpress page which loads all the artists in two columns... here is what I believe to be the relevant bit of code ``` <?php global $paged; if ( is_front_page() ) { $paged = (get_query_var('page')) ? get_query_var('page') : 1; } else { $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; } query_posts(array( 'post_type' => 'artists', 'posts_per_page' => $ppp_artists, 'order' => $order, 'orderby' => $orderby, 'paged' => $paged )); if ( have_posts() ) : ?> <div class="remix_items grid clearfix <?php echo $artists_col; ?>"> <?php while ( have_posts() ): the_post(); ?> <a class="item" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="bookmark"> <figure class="effect-bubba"> <?php the_post_thumbnail('type_cover'); ?> <figcaption> <h2><?php the_title(); ?></h2> </figcaption> </figure> </a> <?php endwhile; ?> </div> ``` I think I need to change the ``` 'posts_per_page' => $ppp_artists, ``` which is earlier defined where ``` global $post; $artists_col = 'two_col'; $ppp_artists = ot_get_option('ppp_artists'); $orderby = ot_get_option('artists_orderby'); $order = ot_get_option('artists_order'); ``` But what needs to be changed to make this only load 2 items? and not have pages buttons.
if you want to show only 2, put it as a value, like so: ``` 'posts_per_page' => 2 ``` For the newest posts, you need to change the sort using the order and orderby params: ``` 'orderby' => 'date', 'order' => 'ASC' ``` Details about orderby params here: <http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters> Also, you should avoid the query\_posts use. Except if you are using a part of your page only, I believe that's the case. On Codex you can see on description about avoiding the query\_posts use. Check this video where a WP Core developer talks about query\_posts and so on: <http://wordpress.tv/2013/03/15/andrew-nacin-wp_query-wordpress-in-depth/>
174,906
<p>I have done this before but it doesn't seem to be working in this case. I am trying to get the category ID from the supplied slug and then add a metabox to the page if the page id matches the category id. My site is throwing me two errors in the admin area </p> <p>Undefined index: post and undefined index post_id</p> <pre><code> add_action('admin_init', 'add_meta_boxes', 1); function add_meta_boxes() { global $post; $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ; $cat = get_category_by_slug('audio'); $id = $cat-&gt;term_id; if ($post_id == $id) { add_meta_box( 'repeatable-fields', 'Audio Playlist', 'repeatable_meta_box_display', 'post', 'normal', 'high'); } } </code></pre>
[ { "answer_id": 174909, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 0, "selected": false, "text": "<p>I'd recommend using an action to place your meta box:</p>\n\n<pre><code>function my_add_meta_box() {\n global $post;\n if ( $post &amp;&amp; is_a( $post, 'WP_Post' ) ) {\n $cat = get_category_by_slug('audio');\n if ( !is_wp_error($cat) ) {\n if ( $post-&gt;ID == $cat-&gt;term_id ) {\n add_meta_box( 'repeatable-fields', 'Audio Playlist', 'repeatable_meta_box_display', 'post', 'normal', 'high');\n } else {\n # for debug only\n wp_die(\"Post ID {$post-&gt;ID} and Cat ID {$cat-&gt;term_id}\");\n }\n } else {\n # For debug only\n wp_die('Cat not found by slug!');\n }\n } else {\n # For debug only\n wp_die('Post not found in global space!');\n }\n}\nadd_action('admin_init', 'my_add_meta_box');\n</code></pre>\n\n<h1>Edit - removed check from box display ... so box is gone and not just empty.</h1>\n\n<pre><code>function repeatable_meta_box_display( $post ) {\n # Draw out your meta box fields\n\n}\n</code></pre>\n\n<p>This will change the logic, but the effect should be the same and you should stop getting undefined index errors.</p>\n\n<p>You are getting the errors, because not all admin pages have a post id. Using an action will make the code only work when needed.</p>\n\n<p>If it works otherwise and you just want to get rid of the errors, try the following in place of your checking code:</p>\n\n<pre><code>global $post;\nif ( $post &amp;&amp; is_a( $post, 'WP_Post' ) ) {\n $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;\n $cat = get_category_by_slug('audio');\n $id = $cat-&gt;term_id;\n if ($post_id == $id) {\n # Add meta box call here\n }\n}\n</code></pre>\n\n<p>That should make sure that post is what you are looking for.</p>\n\n<p>You might have to add a second action later in the wordpress load to check post (maybe it is not declared at admin_init) and then remove the meta box if not wanted.</p>\n\n<pre><code># Revised version without debug info\n\n# Add the meta box\nfunction my_add_meta_box() {\n add_meta_box( 'repeatable-fields', 'Audio Playlist', 'repeatable_meta_box_display', 'post', 'normal', 'high');\n}\nadd_action('admin_init', 'my_add_meta_box');\n\n\n# Remove the meta box if not needed once post is available\nfunction maybe_remove_my_boxes() {\n $remove = true;\n global $post;\n if ( $post &amp;&amp; is_a( $post, 'WP_Post' ) ) {\n $cat = get_category_by_slug('audio');\n if ( !is_wp_error($cat) ) {\n if ( $post-&gt;ID == $cat-&gt;term_id ) {\n $remove = false;\n }\n }\n }\n if ( $remove ) {\n remove_meta_box( 'repeatable-fields', 'post', 'normal' );\n # echo( 'Removed as not needed' );\n }\n}\nadd_action('admin_head', 'maybe_remove_my_boxes');\n</code></pre>\n" }, { "answer_id": 174922, "author": "Jamie", "author_id": 14761, "author_profile": "https://wordpress.stackexchange.com/users/14761", "pm_score": 3, "selected": true, "text": "<p>I got it to work by doing it this way</p>\n\n<pre><code> if (is_admin() ){\n $post_id = isset($_GET['post']) ? $_GET['post'] : isset($_POST['post_ID']) ;\n if( $post_id &amp;&amp; in_category('audio', $post_id) ){\n\n add_action('admin_init', 'add_meta_boxes', 1);\n }\n}\n</code></pre>\n\n<p>The only problem with this method is that it won't display the metabox until after you have published the post. The $post_id variable shows bool(false) until you publish. </p>\n\n<p>so the big problem is that when you go to make a new post, there is no category ID to get. So using the link posted to Toscho's post, you can add category information and use $_GET to test for that information. Looks like it gets populated when you tick the category for that post. </p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174906", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14761/" ]
I have done this before but it doesn't seem to be working in this case. I am trying to get the category ID from the supplied slug and then add a metabox to the page if the page id matches the category id. My site is throwing me two errors in the admin area Undefined index: post and undefined index post\_id ``` add_action('admin_init', 'add_meta_boxes', 1); function add_meta_boxes() { global $post; $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ; $cat = get_category_by_slug('audio'); $id = $cat->term_id; if ($post_id == $id) { add_meta_box( 'repeatable-fields', 'Audio Playlist', 'repeatable_meta_box_display', 'post', 'normal', 'high'); } } ```
I got it to work by doing it this way ``` if (is_admin() ){ $post_id = isset($_GET['post']) ? $_GET['post'] : isset($_POST['post_ID']) ; if( $post_id && in_category('audio', $post_id) ){ add_action('admin_init', 'add_meta_boxes', 1); } } ``` The only problem with this method is that it won't display the metabox until after you have published the post. The $post\_id variable shows bool(false) until you publish. so the big problem is that when you go to make a new post, there is no category ID to get. So using the link posted to Toscho's post, you can add category information and use $\_GET to test for that information. Looks like it gets populated when you tick the category for that post.
174,907
<p>WordPress have <code>the_posts_navigation</code> function since 4.1.0. But I don't know how to use with <code>wp_query</code> or <code>get_posts</code>. the following code is in a template file of page.<br><strong>wp_query method:</strong></p> <pre><code> &lt;?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $get_posts=new wp_query('post_type=case&amp;posts_per_page=2&amp;paged='.$paged); while($get_posts-&gt;have_posts()):$get_posts-&gt;the_post(); the_title(); endwhile; the_posts_pagination( array( 'prev_text' =&gt; __( 'Previous page', 'cm' ), 'next_text' =&gt; __( 'Next page', 'cm' ), 'before_page_number' =&gt; '&lt;span class="meta-nav screen-reader-text"&gt;' . __( 'Page', 'cm' ) . ' &lt;/span&gt;', ) ); ?&gt; </code></pre> <p><strong>get_posts method:</strong></p> <pre><code> &lt;? while(have_posts()):the_post(); if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $case_posts=get_posts('post_type=case&amp;posts_per_page=2&amp;paged='.$paged); echo '&lt;pre&gt;'; print_r($case_posts); echo '&lt;/pre&gt;'; foreach($case_posts as $case_post){ echo $case_post-&gt;post_title; } endwhile; // Previous/next page navigation. the_posts_pagination( array( 'prev_text' =&gt; __( 'Previous page', 'cm' ), 'next_text' =&gt; __( 'Next page', 'cm' ), 'before_page_number' =&gt; '&lt;span class="meta-nav screen-reader-text"&gt;' . __( 'Page', 'cm' ) . ' &lt;/span&gt;', ) ); ?&gt; </code></pre> <p>They don't work and display pagination, but entering <a href="http://127.0.0.1/gdboer/?page_id=74&amp;page=2" rel="noreferrer">http://127.0.0.1/gdboer/?page_id=74&amp;page=2</a> manually in address bar, it works. Who can help me, thank you so much!</p>
[ { "answer_id": 174910, "author": "Leo Caseiro", "author_id": 52791, "author_profile": "https://wordpress.stackexchange.com/users/52791", "pm_score": 2, "selected": false, "text": "<p>This function uses the <a href=\"https://developer.wordpress.org/reference/functions/get_the_posts_pagination/\" rel=\"nofollow\"><code>get_the_posts_pagination()</code></a> which uses the GLOBAL <code>wp_query</code> to setup the <code>paginate_links()</code> function, so I believe that doesn't work for <code>get_posts</code>.</p>\n\n<p>Try use the function <code>paginate_links()</code> by itself or the function <code>posts_nav_link()</code></p>\n\n<p>PS: Make sure you use <code>wp_reset_query()</code></p>\n" }, { "answer_id": 174948, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p><code>the_posts_navigation()</code> is simply a wrapper function for <a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L2233\" rel=\"nofollow noreferrer\"><code>get_the_posts_navigation()</code></a> which issimply a wrapper function for <code>paginate_links</code>. The first two functions uses the the same exact parameters that is being used by <code>paginate_links</code> and actually passes it to the latter function as well</p>\n\n<p><code>get_the_posts_navigation()</code> and <code>the_posts_navigation()</code> is good new functions as it eliminates a lot of custom coding and it is more user friendly for new unexperienced users who would like numbered pagination links</p>\n\n<p>The only flaw in this <code>get_the_posts_navigation()</code> is that the developers went and wrapped the <code>paginate_links</code> function in a conditional statement that states that if the main query (<code>$wp_query</code>) has less than 1 page, (remember, the first page is <code>0</code> and the second page is <code>2</code>), don't show the links. This is problematic for custom queries on page templates. Pages will always have just one page, so these functions does not work with custom queries</p>\n\n<p>The only true workaround if you have to use <code>the_posts_navigation()</code>, is to make use of @ChipBennet answer in <a href=\"https://wordpress.stackexchange.com/a/120408/31545\">this post</a>. I really don't like nullifying the main query (quite hacky, in my opinion this is just like using <code>query_posts</code>) but I can't see any other solution to make <code>get_the_posts_navigation()</code> to work with custom queries </p>\n" }, { "answer_id": 185317, "author": "Eran Or", "author_id": 71150, "author_profile": "https://wordpress.stackexchange.com/users/71150", "pm_score": 3, "selected": false, "text": "<p>I have a custom template and I struggled hours to show the pagination component.\nhere what's worked for me. </p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args = array(\n 'posts_per_page' =&gt; 3,\n 'orderby' =&gt; 'menu_order',\n 'order'=&gt; 'ASC',\n 'paged'=&gt;$paged,\n 'post_type' =&gt; 'projects'\n );\n\n$projects = new WP_Query($args);\n\n &lt;!-- working example of pagination with numbers --&gt;\n ...&lt;?php endwhile;?&gt;\n &lt;?php \n $GLOBALS['wp_query']-&gt;max_num_pages = $projects-&gt;max_num_pages;\n the_posts_pagination( array(\n 'mid_size' =&gt; 1,\n 'prev_text' =&gt; __( 'Back', 'green' ),\n 'next_text' =&gt; __( 'Onward', 'green' ),\n 'screen_reader_text' =&gt; __( 'Posts navigation' )\n ) ); ?&gt;\n OR\n &lt;!-- working example of pagination without numbers --&gt;\n ...&lt;?php endwhile;?&gt; \n &lt;?php next_posts_link( 'next', $projects-&gt;max_num_pages ); ?&gt;\n &lt;?php previous_posts_link('prev') ?&gt;\n</code></pre>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66041/" ]
WordPress have `the_posts_navigation` function since 4.1.0. But I don't know how to use with `wp_query` or `get_posts`. the following code is in a template file of page. **wp\_query method:** ``` <?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $get_posts=new wp_query('post_type=case&posts_per_page=2&paged='.$paged); while($get_posts->have_posts()):$get_posts->the_post(); the_title(); endwhile; the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'cm' ), 'next_text' => __( 'Next page', 'cm' ), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'cm' ) . ' </span>', ) ); ?> ``` **get\_posts method:** ``` <? while(have_posts()):the_post(); if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $case_posts=get_posts('post_type=case&posts_per_page=2&paged='.$paged); echo '<pre>'; print_r($case_posts); echo '</pre>'; foreach($case_posts as $case_post){ echo $case_post->post_title; } endwhile; // Previous/next page navigation. the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'cm' ), 'next_text' => __( 'Next page', 'cm' ), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'cm' ) . ' </span>', ) ); ?> ``` They don't work and display pagination, but entering <http://127.0.0.1/gdboer/?page_id=74&page=2> manually in address bar, it works. Who can help me, thank you so much!
`the_posts_navigation()` is simply a wrapper function for [`get_the_posts_navigation()`](https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L2233) which issimply a wrapper function for `paginate_links`. The first two functions uses the the same exact parameters that is being used by `paginate_links` and actually passes it to the latter function as well `get_the_posts_navigation()` and `the_posts_navigation()` is good new functions as it eliminates a lot of custom coding and it is more user friendly for new unexperienced users who would like numbered pagination links The only flaw in this `get_the_posts_navigation()` is that the developers went and wrapped the `paginate_links` function in a conditional statement that states that if the main query (`$wp_query`) has less than 1 page, (remember, the first page is `0` and the second page is `2`), don't show the links. This is problematic for custom queries on page templates. Pages will always have just one page, so these functions does not work with custom queries The only true workaround if you have to use `the_posts_navigation()`, is to make use of @ChipBennet answer in [this post](https://wordpress.stackexchange.com/a/120408/31545). I really don't like nullifying the main query (quite hacky, in my opinion this is just like using `query_posts`) but I can't see any other solution to make `get_the_posts_navigation()` to work with custom queries
174,912
<p>I need to order my Wordpress posts (that happen to be Woocommerce products) alphabetically, but I want to ignore certain words, eg. 'The' and 'A' and 'An'.</p> <p>Is there a function or filter that can be targeted to the custom post query on top of orderby=ASC to ignore certain chosen words?</p> <pre><code>&lt;?php // My custom query $args = array( 'post_type' =&gt; 'product', ... ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; </code></pre>
[ { "answer_id": 174916, "author": "Leo Caseiro", "author_id": 52791, "author_profile": "https://wordpress.stackexchange.com/users/52791", "pm_score": 0, "selected": false, "text": "<p>WordPress runs with MySQL and it's not really possible to do using MySQL: \n<a href=\"https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc\">https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the\">https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the</a></p>\n\n<p>Every good answer suggest a new column which not ideal to the WP.</p>\n\n<p>You would be able to create a function to execute by PHP, and run it after the MySQL. So it can fix the problem, or maybe using JSON to load your products/posts and a Java Script script, like they Table Sorter here:\n<a href=\"http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html\" rel=\"nofollow noreferrer\">http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html</a></p>\n" }, { "answer_id": 174921, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 3, "selected": true, "text": "<p>Ok, worked it out via a little workaround. </p>\n\n<ol>\n<li>Add a new sorting function in Woocommerce, something like: <a href=\"https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php\" rel=\"nofollow\">https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php</a> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too).</li>\n<li>Change the orderby to be 'name'. Eg post slug rather than post title.</li>\n<li>Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story</li>\n<li>Choose the new sorting option as the default option in Woocommerce settings (products).</li>\n</ol>\n\n<p>Here's the final code for your functions.php:</p>\n\n<pre><code> /**\n * Cool orderby function from Monkey Puzzle. Adapted from:\n * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/\n **/\nfunction monkey_ordering_args( $sort_args ) {\n\n$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );\nswitch( $orderby_value ) {\n\n // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function\n case 'slug':\n $sort_args['orderby'] = 'name';\n // Sort by ASC because we're using alphabetic sorting\n $sort_args['order'] = 'asc';\n break; \n}\n\nreturn $sort_args;\n}\nadd_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' );\n\n\n// Add these new sorting arguments to the sortby options on the frontend\nfunction monkey_add_new_orderby( $sortby ) {\n\n// Adjust the text as desired\n$sortby['slug'] = __( 'Sort by name', 'woocommerce' );\n\nreturn $sortby;\n}\nadd_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' );\nadd_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' );\n</code></pre>\n" }, { "answer_id": 174923, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Sometimes the easiest solution to this kind of problem is to use a meta data field in which you store the relevant value by which you want to sort. For \"the stackexchange\" you store \"stackexhange\" but for \"mark kaplun\" you just store \"mark kaplun\". This should be very trivial code to write.\nOnce you have the sort values in place all that is left to do is sort by the meta field. </p>\n\n<p>The biggest advantage of this approach is performance since you can in this way leave all the heavy sorting to the MYSQL and in addition it is much easier to implement paging or additional filter.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48568/" ]
I need to order my Wordpress posts (that happen to be Woocommerce products) alphabetically, but I want to ignore certain words, eg. 'The' and 'A' and 'An'. Is there a function or filter that can be targeted to the custom post query on top of orderby=ASC to ignore certain chosen words? ``` <?php // My custom query $args = array( 'post_type' => 'product', ... ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> ```
Ok, worked it out via a little workaround. 1. Add a new sorting function in Woocommerce, something like: <https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too). 2. Change the orderby to be 'name'. Eg post slug rather than post title. 3. Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story 4. Choose the new sorting option as the default option in Woocommerce settings (products). Here's the final code for your functions.php: ``` /** * Cool orderby function from Monkey Puzzle. Adapted from: * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/ **/ function monkey_ordering_args( $sort_args ) { $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); switch( $orderby_value ) { // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function case 'slug': $sort_args['orderby'] = 'name'; // Sort by ASC because we're using alphabetic sorting $sort_args['order'] = 'asc'; break; } return $sort_args; } add_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' ); // Add these new sorting arguments to the sortby options on the frontend function monkey_add_new_orderby( $sortby ) { // Adjust the text as desired $sortby['slug'] = __( 'Sort by name', 'woocommerce' ); return $sortby; } add_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' ); add_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' ); ```
174,924
<p><strong>What I have done</strong></p> <p>I have a developed a custom WordPress plugin for displaying a custom calculator on my website. And regarding the same I have created a short-code for it which I am using to place it on any page of my website.</p> <p><strong>What I want to achieve</strong></p> <p>Now I want to create an embedded code for it so that by using that embedded code, we can place this calculator on any website. Means simply how we can create an embedded code for a short-code in WordPress.</p> <p>I have an idea that we can achieve the same using iframe but still want some guidance on it.<br> Any help will be much appreciated.</p>
[ { "answer_id": 174916, "author": "Leo Caseiro", "author_id": 52791, "author_profile": "https://wordpress.stackexchange.com/users/52791", "pm_score": 0, "selected": false, "text": "<p>WordPress runs with MySQL and it's not really possible to do using MySQL: \n<a href=\"https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc\">https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the\">https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the</a></p>\n\n<p>Every good answer suggest a new column which not ideal to the WP.</p>\n\n<p>You would be able to create a function to execute by PHP, and run it after the MySQL. So it can fix the problem, or maybe using JSON to load your products/posts and a Java Script script, like they Table Sorter here:\n<a href=\"http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html\" rel=\"nofollow noreferrer\">http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html</a></p>\n" }, { "answer_id": 174921, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 3, "selected": true, "text": "<p>Ok, worked it out via a little workaround. </p>\n\n<ol>\n<li>Add a new sorting function in Woocommerce, something like: <a href=\"https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php\" rel=\"nofollow\">https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php</a> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too).</li>\n<li>Change the orderby to be 'name'. Eg post slug rather than post title.</li>\n<li>Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story</li>\n<li>Choose the new sorting option as the default option in Woocommerce settings (products).</li>\n</ol>\n\n<p>Here's the final code for your functions.php:</p>\n\n<pre><code> /**\n * Cool orderby function from Monkey Puzzle. Adapted from:\n * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/\n **/\nfunction monkey_ordering_args( $sort_args ) {\n\n$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );\nswitch( $orderby_value ) {\n\n // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function\n case 'slug':\n $sort_args['orderby'] = 'name';\n // Sort by ASC because we're using alphabetic sorting\n $sort_args['order'] = 'asc';\n break; \n}\n\nreturn $sort_args;\n}\nadd_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' );\n\n\n// Add these new sorting arguments to the sortby options on the frontend\nfunction monkey_add_new_orderby( $sortby ) {\n\n// Adjust the text as desired\n$sortby['slug'] = __( 'Sort by name', 'woocommerce' );\n\nreturn $sortby;\n}\nadd_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' );\nadd_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' );\n</code></pre>\n" }, { "answer_id": 174923, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Sometimes the easiest solution to this kind of problem is to use a meta data field in which you store the relevant value by which you want to sort. For \"the stackexchange\" you store \"stackexhange\" but for \"mark kaplun\" you just store \"mark kaplun\". This should be very trivial code to write.\nOnce you have the sort values in place all that is left to do is sort by the meta field. </p>\n\n<p>The biggest advantage of this approach is performance since you can in this way leave all the heavy sorting to the MYSQL and in addition it is much easier to implement paging or additional filter.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174924", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65707/" ]
**What I have done** I have a developed a custom WordPress plugin for displaying a custom calculator on my website. And regarding the same I have created a short-code for it which I am using to place it on any page of my website. **What I want to achieve** Now I want to create an embedded code for it so that by using that embedded code, we can place this calculator on any website. Means simply how we can create an embedded code for a short-code in WordPress. I have an idea that we can achieve the same using iframe but still want some guidance on it. Any help will be much appreciated.
Ok, worked it out via a little workaround. 1. Add a new sorting function in Woocommerce, something like: <https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too). 2. Change the orderby to be 'name'. Eg post slug rather than post title. 3. Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story 4. Choose the new sorting option as the default option in Woocommerce settings (products). Here's the final code for your functions.php: ``` /** * Cool orderby function from Monkey Puzzle. Adapted from: * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/ **/ function monkey_ordering_args( $sort_args ) { $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); switch( $orderby_value ) { // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function case 'slug': $sort_args['orderby'] = 'name'; // Sort by ASC because we're using alphabetic sorting $sort_args['order'] = 'asc'; break; } return $sort_args; } add_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' ); // Add these new sorting arguments to the sortby options on the frontend function monkey_add_new_orderby( $sortby ) { // Adjust the text as desired $sortby['slug'] = __( 'Sort by name', 'woocommerce' ); return $sortby; } add_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' ); add_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' ); ```
174,932
<p>Migrating between local and server with Wordpress (SQL) is a bit time consuming, and I'm wondering if there is a better way to do it. With Drupal, there is a module called BackUp&amp;Migrate, which lets you push SQL updates <strong>immediately</strong> from within the Drupal framework to the server. Is there something similar for Wordpress? At the moment, this is my work flow:</p> <p>1) Go into localhost/phpmyadmin and make a SQL dump</p> <p>2) Log into cPanel -> PhpMyAdmin</p> <p>3) Select db and drop tables</p> <p>4) Import new SQL dump</p> <p>5) Run a Search/Replace to update strings</p> <p>6) Log into the site again on the server side and update permalinks</p> <p>This gets a bit time consuming if doing it often. If anyone has a better solution, I would really love to hear it!:) Thanks so much!</p>
[ { "answer_id": 174916, "author": "Leo Caseiro", "author_id": 52791, "author_profile": "https://wordpress.stackexchange.com/users/52791", "pm_score": 0, "selected": false, "text": "<p>WordPress runs with MySQL and it's not really possible to do using MySQL: \n<a href=\"https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc\">https://stackoverflow.com/questions/3252577/how-to-sort-in-sql-ignoring-articles-the-a-an-etc</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the\">https://stackoverflow.com/questions/1285849/custom-order-by-to-ignore-the</a></p>\n\n<p>Every good answer suggest a new column which not ideal to the WP.</p>\n\n<p>You would be able to create a function to execute by PHP, and run it after the MySQL. So it can fix the problem, or maybe using JSON to load your products/posts and a Java Script script, like they Table Sorter here:\n<a href=\"http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html\" rel=\"nofollow noreferrer\">http://mottie.github.io/tablesorter/docs/example-parsers-ignore-articles.html</a></p>\n" }, { "answer_id": 174921, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 3, "selected": true, "text": "<p>Ok, worked it out via a little workaround. </p>\n\n<ol>\n<li>Add a new sorting function in Woocommerce, something like: <a href=\"https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php\" rel=\"nofollow\">https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php</a> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too).</li>\n<li>Change the orderby to be 'name'. Eg post slug rather than post title.</li>\n<li>Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story</li>\n<li>Choose the new sorting option as the default option in Woocommerce settings (products).</li>\n</ol>\n\n<p>Here's the final code for your functions.php:</p>\n\n<pre><code> /**\n * Cool orderby function from Monkey Puzzle. Adapted from:\n * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/\n **/\nfunction monkey_ordering_args( $sort_args ) {\n\n$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );\nswitch( $orderby_value ) {\n\n // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function\n case 'slug':\n $sort_args['orderby'] = 'name';\n // Sort by ASC because we're using alphabetic sorting\n $sort_args['order'] = 'asc';\n break; \n}\n\nreturn $sort_args;\n}\nadd_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' );\n\n\n// Add these new sorting arguments to the sortby options on the frontend\nfunction monkey_add_new_orderby( $sortby ) {\n\n// Adjust the text as desired\n$sortby['slug'] = __( 'Sort by name', 'woocommerce' );\n\nreturn $sortby;\n}\nadd_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' );\nadd_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' );\n</code></pre>\n" }, { "answer_id": 174923, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Sometimes the easiest solution to this kind of problem is to use a meta data field in which you store the relevant value by which you want to sort. For \"the stackexchange\" you store \"stackexhange\" but for \"mark kaplun\" you just store \"mark kaplun\". This should be very trivial code to write.\nOnce you have the sort values in place all that is left to do is sort by the meta field. </p>\n\n<p>The biggest advantage of this approach is performance since you can in this way leave all the heavy sorting to the MYSQL and in addition it is much easier to implement paging or additional filter.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58166/" ]
Migrating between local and server with Wordpress (SQL) is a bit time consuming, and I'm wondering if there is a better way to do it. With Drupal, there is a module called BackUp&Migrate, which lets you push SQL updates **immediately** from within the Drupal framework to the server. Is there something similar for Wordpress? At the moment, this is my work flow: 1) Go into localhost/phpmyadmin and make a SQL dump 2) Log into cPanel -> PhpMyAdmin 3) Select db and drop tables 4) Import new SQL dump 5) Run a Search/Replace to update strings 6) Log into the site again on the server side and update permalinks This gets a bit time consuming if doing it often. If anyone has a better solution, I would really love to hear it!:) Thanks so much!
Ok, worked it out via a little workaround. 1. Add a new sorting function in Woocommerce, something like: <https://gist.githubusercontent.com/bekarice/0df2b2d54d6ac8076f84/raw/wc-sort-by-postmeta.php> works nicely, but remove the bit about meta values and keys since we're not sorting by custom fields (though that could be a good workaround too). 2. Change the orderby to be 'name'. Eg post slug rather than post title. 3. Change all the products to remove the offending words from the slugs/permalinks so that /a-childs-story becomes /childs-story 4. Choose the new sorting option as the default option in Woocommerce settings (products). Here's the final code for your functions.php: ``` /** * Cool orderby function from Monkey Puzzle. Adapted from: * Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/ **/ function monkey_ordering_args( $sort_args ) { $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); switch( $orderby_value ) { // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function case 'slug': $sort_args['orderby'] = 'name'; // Sort by ASC because we're using alphabetic sorting $sort_args['order'] = 'asc'; break; } return $sort_args; } add_filter( 'woocommerce_get_catalog_ordering_args', 'monkey_ordering_args' ); // Add these new sorting arguments to the sortby options on the frontend function monkey_add_new_orderby( $sortby ) { // Adjust the text as desired $sortby['slug'] = __( 'Sort by name', 'woocommerce' ); return $sortby; } add_filter( 'woocommerce_default_catalog_orderby_options', 'monkey_add_new_orderby' ); add_filter( 'woocommerce_catalog_orderby', 'monkey_add_new_orderby' ); ```
174,934
<p>Sometimes, due to meta boxes added by plugins, the excerpt gets moved down the order in the admin page.</p> <p>Is there a way I can force it to <em>always</em> be directly below the post content?</p> <p>Here is the way I've tried:</p> <pre><code>function remove_wordpress_meta_boxes() { remove_meta_box( 'postexcerpt', 'page', 'normal' ); add_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', 'page', 'normal', 'high'); } add_action( 'admin_menu', 'remove_wordpress_meta_boxes' ); </code></pre> <p><code>remove_meta_box()</code> works as expected, but re-adding the excerpt meta box doesn't seem to do anything to the ordering - I still have a plugin metabox appear above the excerpt.</p>
[ { "answer_id": 174980, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>The reason why your code doesn't work is most likely that you've ordered your metaboxes before, and the that order has been saved into the <code>meta-box-order_page</code> meta value. This overrides the default setup.</p>\n\n<p>Here's an example of the <code>meta-box-order_post</code> meta value:</p>\n\n<pre><code>a:3:{\n s:4:\"side\"; \n s:61:\"submitdiv,formatdiv,categorydiv,tagsdiv-post_tag,postimagediv\";\n s:6:\"normal\"; \n s:96:\"revisionsdiv,postexcerpt,trackbacksdiv,postcustom,\n commentstatusdiv,commentsdiv,slugdiv,authordiv\";\n s:8:\"advanced\";\n s:0:\"\";\n}\n</code></pre>\n\n<p>Here I've just reformatted the serialized array for better readability.</p>\n\n<h2>Sticky MetaBoxes:</h2>\n\n<p>To move a given metabox to the <em>top</em> position, for a given <em>context</em> and <em>post-type</em>, you can use this code snippet:</p>\n\n<pre><code>/**\n * Set some sticky metaboxes\n */\n\nadd_action( 'admin_init', function()\n{\n if( function_exists( 'wpse_sticky_metabox' ) )\n {\n // Sticky metabox #1:\n wpse_sticky_metabox(\n array(\n 'cpt' =&gt; 'page',\n 'context' =&gt; 'normal',\n 'metabox' =&gt; 'postexcerpt'\n )\n );\n\n // Sticky metabox #2:\n wpse_sticky_metabox(\n array(\n 'cpt' =&gt; 'post',\n 'context' =&gt; 'side',\n 'metabox' =&gt; 'authordiv' \n )\n );\n }\n});\n</code></pre>\n\n<p>where you can adjust this to your needs.</p>\n\n<p>Some info on the input parameters:</p>\n\n<ul>\n<li><code>cpt</code> is the custom post type of the edit screen ( i.e. <em>post</em>, <em>page</em>, ...)</li>\n<li><code>context</code> is the section where you want to make the metabox sticky. ( i.e. <em>normal</em>, <em>side</em>, <em>advanced</em>, ... )</li>\n<li><code>metabox</code> is the <em>id</em> of the sticky meta-box ( i.e. <em>postexcerpt</em>, <em>authordiv</em>, ... )</li>\n</ul>\n\n<h2>Sticky MetaBoxes - the plugin:</h2>\n\n<p>This is supported by the following demo plugin:</p>\n\n<pre><code>/**\n * Plugin Name: Sticky Meta-Boxes\n * Description: Set a given meta-box to the top, for a given cpt and context.\n * Plugin URI: http://wordpress.stackexchange.com/a/174980/26350\n * Author: Birgir Erlendsson (birgire)\n * Version: 0.0.2\n */\n\nfunction wpse_sticky_metabox( $args = array() )\n{\n if( class_exists( 'MetaBoxSticker' ) )\n {\n $o = new MetaBoxSticker;\n $o-&gt;setup( $args )-&gt;activate();\n }\n}\n\nclass MetaBoxSticker\n{\n private $args;\n\n public function setup( $args = array() )\n {\n $default = array(\n 'cpt' =&gt; 'post',\n 'context' =&gt; 'normal',\n 'metabox' =&gt; 'postexcerpt'\n );\n $this-&gt;args = wp_parse_args( $args, $default );\n return $this;\n }\n\n public function activate()\n {\n add_filter(\n sprintf(\n 'get_user_option_meta-box-order_%s',\n $this-&gt;args['cpt']\n ),\n array( $this, 'filter' ),\n PHP_INT_MAX\n );\n\n add_action( \n 'add_meta_boxes', \n array( $this, 'relocate' ), \n PHP_INT_MAX \n );\n }\n\n public function relocate()\n {\n //-----------------------\n // Get the user input:\n //-----------------------\n $_cpt = sanitize_key( $this-&gt;args['cpt'] );\n $_metabox = sanitize_key( $this-&gt;args['metabox'] );\n $_context = sanitize_key( $this-&gt;args['context'] );\n\n //-----------------------\n // Relocate 'high' metaboxes to 'default' in the current context\n //----------------------- \n global $wp_meta_boxes;\n if( isset( $wp_meta_boxes[$_cpt][$_context]['high'] ) )\n { \n foreach( $wp_meta_boxes[$_cpt][$_context]['high'] as $id =&gt; $item )\n {\n if( isset( $item['callback'] ) )\n {\n remove_meta_box( \n $id, \n $_cpt, \n $_context \n );\n\n add_meta_box( \n $id, \n $item['title'], \n $item['callback'], \n $_cpt, \n $_context, \n 'default', \n $item['args'] \n );\n }\n }\n }\n }\n\n public function filter( $order )\n {\n //-----------------------\n // Get the user input:\n //----------------------- \n $_cpt = sanitize_key( $this-&gt;args['cpt'] );\n $_metabox = sanitize_key( $this-&gt;args['metabox'] );\n $_context = sanitize_key( $this-&gt;args['context'] );\n\n //-----------------------\n // Handle the case if the current user hasn't made any meta-box ordering before:\n //-----------------------\n if( empty( $order ) )\n {\n global $wp_meta_boxes;\n if( ! isset( $wp_meta_boxes[$_cpt][$_context] ) )\n return $order;\n\n $order = array();\n foreach( $wp_meta_boxes[$_cpt] as $context_key =&gt; $context_item )\n {\n $tmp = array();\n foreach( $context_item as $priority_key =&gt; $priority_item )\n {\n foreach( $priority_item as $metabox_key =&gt; $metabox_item )\n {\n $tmp[] = $metabox_key;\n }\n }\n $order[$context_key] = join( ',', $tmp );\n }\n }\n\n //-----------------------\n // Let's make sure the context exists:\n //-----------------------\n if( ! isset( $order[$_context] ) )\n return $order;\n\n //-----------------------\n // Remove the given meta-box from the whole order array:\n //-----------------------\n foreach( $order as $context_key =&gt; $string )\n {\n $tmp = explode( ',', $string );\n $key = array_search( $_metabox, $tmp );\n if( ! empty( $key ) )\n {\n unset( $tmp[$key] );\n $order[$context_key] = join( ',', $tmp );\n }\n }\n\n //-----------------------\n // Make the given meta-box sticky for a given context\n //-----------------------\n $tmp = explode( ',', $order[$_context] );\n array_unshift( $tmp, $_metabox );\n $order[$_context] = join( ',', $tmp );\n\n return $order;\n }\n\n} // end class\n</code></pre>\n\n<p>This plugin should also work, even if you haven't made any ordering before.</p>\n\n<p>It also respects the <em>Screen Options</em>, i.e. wether a meta-box is visible or not.</p>\n\n<p>I hope you can extend this further to your needs.</p>\n" }, { "answer_id": 195903, "author": "OzTheGreat", "author_id": 76899, "author_profile": "https://wordpress.stackexchange.com/users/76899", "pm_score": 1, "selected": false, "text": "<p>As pointed out, you can only change the default ordering, if a user has modified it there's not a huge amount you can do without writing a reset script.</p>\n\n<p>Either way, here's how you change the default order properly, (disclaimer, I wrote the article) <a href=\"https://ozthegreat.io/wordpress/wordpress-how-to-move-the-excerpt-meta-box-above-the-editor/\" rel=\"nofollow\">https://ozthegreat.io/wordpress/wordpress-how-to-move-the-excerpt-meta-box-above-the-editor/</a></p>\n\n<pre><code>/**\n * Removes the regular excerpt box. We're not getting rid\n * of it, we're just moving it above the wysiwyg editor\n *\n * @return null\n */\nfunction oz_remove_normal_excerpt() {\n remove_meta_box( 'postexcerpt' , 'post' , 'normal' );\n}\nadd_action( 'admin_menu' , 'oz_remove_normal_excerpt' );\n\n/**\n * Add the excerpt meta box back in with a custom screen location\n *\n * @param string $post_type\n * @return null\n */\nfunction oz_add_excerpt_meta_box( $post_type ) {\n if ( in_array( $post_type, array( 'post', 'page' ) ) ) {\n add_meta_box(\n 'oz_postexcerpt',\n __( 'Excerpt', 'thetab-theme' ),\n 'post_excerpt_meta_box',\n $post_type,\n 'after_title',\n 'high'\n );\n }\n}\nadd_action( 'add_meta_boxes', 'oz_add_excerpt_meta_box' );\n\n/**\n * You can't actually add meta boxes after the title by default in WP so\n * we're being cheeky. We've registered our own meta box position\n * `after_title` onto which we've regiestered our new meta boxes and\n * are now calling them in the `edit_form_after_title` hook which is run\n * after the post tile box is displayed.\n *\n * @return null\n */\nfunction oz_run_after_title_meta_boxes() {\n global $post, $wp_meta_boxes;\n # Output the `below_title` meta boxes:\n do_meta_boxes( get_current_screen(), 'after_title', $post );\n}\nadd_action( 'edit_form_after_title', 'oz_run_after_title_meta_boxes' );\n</code></pre>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60608/" ]
Sometimes, due to meta boxes added by plugins, the excerpt gets moved down the order in the admin page. Is there a way I can force it to *always* be directly below the post content? Here is the way I've tried: ``` function remove_wordpress_meta_boxes() { remove_meta_box( 'postexcerpt', 'page', 'normal' ); add_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', 'page', 'normal', 'high'); } add_action( 'admin_menu', 'remove_wordpress_meta_boxes' ); ``` `remove_meta_box()` works as expected, but re-adding the excerpt meta box doesn't seem to do anything to the ordering - I still have a plugin metabox appear above the excerpt.
The reason why your code doesn't work is most likely that you've ordered your metaboxes before, and the that order has been saved into the `meta-box-order_page` meta value. This overrides the default setup. Here's an example of the `meta-box-order_post` meta value: ``` a:3:{ s:4:"side"; s:61:"submitdiv,formatdiv,categorydiv,tagsdiv-post_tag,postimagediv"; s:6:"normal"; s:96:"revisionsdiv,postexcerpt,trackbacksdiv,postcustom, commentstatusdiv,commentsdiv,slugdiv,authordiv"; s:8:"advanced"; s:0:""; } ``` Here I've just reformatted the serialized array for better readability. Sticky MetaBoxes: ----------------- To move a given metabox to the *top* position, for a given *context* and *post-type*, you can use this code snippet: ``` /** * Set some sticky metaboxes */ add_action( 'admin_init', function() { if( function_exists( 'wpse_sticky_metabox' ) ) { // Sticky metabox #1: wpse_sticky_metabox( array( 'cpt' => 'page', 'context' => 'normal', 'metabox' => 'postexcerpt' ) ); // Sticky metabox #2: wpse_sticky_metabox( array( 'cpt' => 'post', 'context' => 'side', 'metabox' => 'authordiv' ) ); } }); ``` where you can adjust this to your needs. Some info on the input parameters: * `cpt` is the custom post type of the edit screen ( i.e. *post*, *page*, ...) * `context` is the section where you want to make the metabox sticky. ( i.e. *normal*, *side*, *advanced*, ... ) * `metabox` is the *id* of the sticky meta-box ( i.e. *postexcerpt*, *authordiv*, ... ) Sticky MetaBoxes - the plugin: ------------------------------ This is supported by the following demo plugin: ``` /** * Plugin Name: Sticky Meta-Boxes * Description: Set a given meta-box to the top, for a given cpt and context. * Plugin URI: http://wordpress.stackexchange.com/a/174980/26350 * Author: Birgir Erlendsson (birgire) * Version: 0.0.2 */ function wpse_sticky_metabox( $args = array() ) { if( class_exists( 'MetaBoxSticker' ) ) { $o = new MetaBoxSticker; $o->setup( $args )->activate(); } } class MetaBoxSticker { private $args; public function setup( $args = array() ) { $default = array( 'cpt' => 'post', 'context' => 'normal', 'metabox' => 'postexcerpt' ); $this->args = wp_parse_args( $args, $default ); return $this; } public function activate() { add_filter( sprintf( 'get_user_option_meta-box-order_%s', $this->args['cpt'] ), array( $this, 'filter' ), PHP_INT_MAX ); add_action( 'add_meta_boxes', array( $this, 'relocate' ), PHP_INT_MAX ); } public function relocate() { //----------------------- // Get the user input: //----------------------- $_cpt = sanitize_key( $this->args['cpt'] ); $_metabox = sanitize_key( $this->args['metabox'] ); $_context = sanitize_key( $this->args['context'] ); //----------------------- // Relocate 'high' metaboxes to 'default' in the current context //----------------------- global $wp_meta_boxes; if( isset( $wp_meta_boxes[$_cpt][$_context]['high'] ) ) { foreach( $wp_meta_boxes[$_cpt][$_context]['high'] as $id => $item ) { if( isset( $item['callback'] ) ) { remove_meta_box( $id, $_cpt, $_context ); add_meta_box( $id, $item['title'], $item['callback'], $_cpt, $_context, 'default', $item['args'] ); } } } } public function filter( $order ) { //----------------------- // Get the user input: //----------------------- $_cpt = sanitize_key( $this->args['cpt'] ); $_metabox = sanitize_key( $this->args['metabox'] ); $_context = sanitize_key( $this->args['context'] ); //----------------------- // Handle the case if the current user hasn't made any meta-box ordering before: //----------------------- if( empty( $order ) ) { global $wp_meta_boxes; if( ! isset( $wp_meta_boxes[$_cpt][$_context] ) ) return $order; $order = array(); foreach( $wp_meta_boxes[$_cpt] as $context_key => $context_item ) { $tmp = array(); foreach( $context_item as $priority_key => $priority_item ) { foreach( $priority_item as $metabox_key => $metabox_item ) { $tmp[] = $metabox_key; } } $order[$context_key] = join( ',', $tmp ); } } //----------------------- // Let's make sure the context exists: //----------------------- if( ! isset( $order[$_context] ) ) return $order; //----------------------- // Remove the given meta-box from the whole order array: //----------------------- foreach( $order as $context_key => $string ) { $tmp = explode( ',', $string ); $key = array_search( $_metabox, $tmp ); if( ! empty( $key ) ) { unset( $tmp[$key] ); $order[$context_key] = join( ',', $tmp ); } } //----------------------- // Make the given meta-box sticky for a given context //----------------------- $tmp = explode( ',', $order[$_context] ); array_unshift( $tmp, $_metabox ); $order[$_context] = join( ',', $tmp ); return $order; } } // end class ``` This plugin should also work, even if you haven't made any ordering before. It also respects the *Screen Options*, i.e. wether a meta-box is visible or not. I hope you can extend this further to your needs.
174,939
<p>Does someone know how to write the next line in wordpress PHP, because i'm not that great with PHP.</p> <p>If_theme_mode has content echo { my content } else { other content };</p> <p>thnx</p>
[ { "answer_id": 174941, "author": "Ravinder Kumar", "author_id": 29439, "author_profile": "https://wordpress.stackexchange.com/users/29439", "pm_score": 2, "selected": false, "text": "<p>try this code:</p>\n\n<pre><code>if( get_theme_mod('your_setting_name') ){\n //your code\n}else{\n //your code\n}\n</code></pre>\n\n<p><strong>Note:</strong> <a href=\"http://codex.wordpress.org/Function_Reference/get_theme_mod\" rel=\"nofollow\">get_theme_mod()</a> return false if no value exist for your setting</p>\n" }, { "answer_id": 302016, "author": "Brandon", "author_id": 142578, "author_profile": "https://wordpress.stackexchange.com/users/142578", "pm_score": 1, "selected": false, "text": "<p>You can check for a theme mod, echo it if it exists, or apply a default if not, all with one line:</p>\n\n<pre><code>echo get_theme_mod( 'example', 'Some default' );\n</code></pre>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65451/" ]
Does someone know how to write the next line in wordpress PHP, because i'm not that great with PHP. If\_theme\_mode has content echo { my content } else { other content }; thnx
try this code: ``` if( get_theme_mod('your_setting_name') ){ //your code }else{ //your code } ``` **Note:** [get\_theme\_mod()](http://codex.wordpress.org/Function_Reference/get_theme_mod) return false if no value exist for your setting
174,962
<p>I have posts whose each contains 4 attached images. what i'm trying to do in my single.php is to get all the 4 images src to be abble to add different classes to each images.</p> <pre><code>&lt;img class="image_1 no_lazy" src="first attached image src"/&gt; &lt;img class="image_2" src="second attached image src"/&gt; &lt;img class="image_3" src="third attached image src"/&gt; &lt;img class="image_4" src="fourth attached image src"/&gt; </code></pre> <p>here is what I've tried, but I get an array instead of getting the src... I think I'm really close to the solution, but I can't find out what I am doin wrong...</p> <pre><code>&lt;?php global $post; $args = array( 'post_parent' =&gt; $post-&gt;ID, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC', 'numberposts' =&gt; 4 ); $images = get_posts($args); ?&gt; &lt;img class="image_1 no_lazy" src="&lt;?php echo wp_get_attachment_image_src( $images[0]-&gt;ID, 'full' ); ?&gt;"/&gt; &lt;img class="image_2" src="&lt;?php echo wp_get_attachment_image_src( $images[1]-&gt;ID, 'full' ); ?&gt;"/&gt; &lt;img class="image_3" src="&lt;?php echo wp_get_attachment_image_src( $images[2]-&gt;ID, 'full' ); ?&gt;"/&gt; &lt;img class="image_4" src="&lt;?php echo wp_get_attachment_image_src( $images[3]-&gt;ID, 'full' ); ?&gt;"/&gt; </code></pre> <p>can anybody help me with this ?</p> <p>thanks</p>
[ { "answer_id": 174973, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 0, "selected": false, "text": "<p><code>wp_get_attachment_image_src</code> returns an array with 3 elements; the image URL, the width, and the height. You need to echo the first index of the result.</p>\n\n<p>In fact, you can make your code a little leaner by using a <code>foreach</code> loop:</p>\n\n<pre><code>foreach ( $images as $i =&gt; $image ) {\n $src = wp_get_attachment_image_src( $image-&gt;ID, 'full' );\n\n echo '&lt;img class=\"image_' . ++$i;\n if ( $i === 1 )\n echo ' no_lazy';\n echo '\" src=\"' . $src[0] . '\" /&gt;';\n}\n</code></pre>\n" }, { "answer_id": 236604, "author": "Ionut Staicu", "author_id": 223, "author_profile": "https://wordpress.stackexchange.com/users/223", "pm_score": 4, "selected": false, "text": "<p>If you only want to add an extra class, then you should use <code>wp_get_attachment_image</code>. It has few extra params, and the last one is used for setting class names.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>&lt;?php echo wp_get_attachment_image( get_the_ID(), 'thumbnail', \"\", [\"class\" =&gt; \"my-custom-class\"] ); ?&gt;\n</code></pre>\n\n<p>The main advantage of this aproach is that you will also get the whole <code>srcset</code> attributes for free.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40572/" ]
I have posts whose each contains 4 attached images. what i'm trying to do in my single.php is to get all the 4 images src to be abble to add different classes to each images. ``` <img class="image_1 no_lazy" src="first attached image src"/> <img class="image_2" src="second attached image src"/> <img class="image_3" src="third attached image src"/> <img class="image_4" src="fourth attached image src"/> ``` here is what I've tried, but I get an array instead of getting the src... I think I'm really close to the solution, but I can't find out what I am doin wrong... ``` <?php global $post; $args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 4 ); $images = get_posts($args); ?> <img class="image_1 no_lazy" src="<?php echo wp_get_attachment_image_src( $images[0]->ID, 'full' ); ?>"/> <img class="image_2" src="<?php echo wp_get_attachment_image_src( $images[1]->ID, 'full' ); ?>"/> <img class="image_3" src="<?php echo wp_get_attachment_image_src( $images[2]->ID, 'full' ); ?>"/> <img class="image_4" src="<?php echo wp_get_attachment_image_src( $images[3]->ID, 'full' ); ?>"/> ``` can anybody help me with this ? thanks
If you only want to add an extra class, then you should use `wp_get_attachment_image`. It has few extra params, and the last one is used for setting class names. Sample usage: ``` <?php echo wp_get_attachment_image( get_the_ID(), 'thumbnail', "", ["class" => "my-custom-class"] ); ?> ``` The main advantage of this aproach is that you will also get the whole `srcset` attributes for free.
174,978
<p>I'm in kind of a weird situation (for me)<br> My client has a website that runs on a custom CMS<br> He wants an online site that loads some data from the existing database.<br> This is an external MSSQL database and for security reasons a serialized table is created. So there is no way for me to "read" from the database.</p> <p>I contacted the company that hosts and maintains the database and they said that they could automatically create an <code>.csv</code> export for me every hour and save it at a location on the server.</p> <p>So I was very happy with this because this is a comma seperated <code>.csv</code> file.</p> <p>I learned that I could import this to my WP MySQL database with the following:</p> <pre><code>LOAD DATA INFILE '../tmp/file.csv' INTO TABLE $table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS; </code></pre> <p>So far so good. But now my headache starts. I want to do this every hour. So that if their database is altered mine get's updated. The file may overwrite every table/field in the database. (I only use it for reading)</p> <p>I know I can create a cronjob to do this. I simply don't know where to do this. This task must run every hour. So this does not go in a function.php file or even a template.php file.</p> <p>Come to think about it, maybe it shouldn't even be done in WordPress core/custom files.</p> <p>However. Because I don't know where to initiate the function I can not update my database.</p> <p>Hope somebody has a (alternative) solution.</p> <p>M.</p>
[ { "answer_id": 174979, "author": "Brandt Solovij", "author_id": 38927, "author_profile": "https://wordpress.stackexchange.com/users/38927", "pm_score": 1, "selected": false, "text": "<p>I setup something similar. Using IIS - look into writing a .bat file which fires off a php shell script to do whatever it is you need to accomplish.</p>\n\n<p>once you have that bat file working, setup a \"scheduled task\" in IIS <a href=\"http://technet.microsoft.com/en-us/library/cc721871.aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-us/library/cc721871.aspx</a></p>\n\n<p>if you are on a linux system, then use crontab <a href=\"https://www.freebsd.org/doc/handbook/configtuning-cron.html\" rel=\"nofollow\">https://www.freebsd.org/doc/handbook/configtuning-cron.html</a></p>\n\n<p>If you on a hosted, non-vps environment, then you will need to sort out how your site ISP handles this sort of task - each will be different and dependent on contracts / setup </p>\n" }, { "answer_id": 174982, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>WordPress has a <a href=\"http://codex.wordpress.org/Category:WP-Cron_Functions\" rel=\"nofollow\">WP-Cron</a> mechanism for running scheduled tasks. It is used internally for update checks and other tasks, as well as extensively by plugins.</p>\n\n<p>Pro/con break down is pretty much:</p>\n\n<ol>\n<li>Does not rely or require anything from server configuration</li>\n<li>Is triggered by visits to the site, so might not fire reliably on time</li>\n</ol>\n" }, { "answer_id": 176007, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 1, "selected": false, "text": "<p>So I made it happen :-)</p>\n\n<p>There is one thing that I didn't really like to do but for the time being there is no alternative: The CronJob from the server</p>\n\n<p>This PHP script runs in a single (no template) file:</p>\n\n<pre><code>$xmlData = file_get_contents(get_bloginfo('template_directory').'/import/external_db.xml'); \n// read XML data string\n$xml = simplexml_load_string($xmlData) or die(\"ERROR: Cannot create SimpleXML object\");\n\n foreach( $xml as $user )\n { \n $name = $user-&gt;firstname;\n $code = $user-&gt;code;\n $email = $user-&gt;email;\n $jobdescription = $user-&gt;jobdescription;\n $salary = $user-&gt;salary; \n $sql = \"INSERT INTO xxx_employees (name, code, email, jobdescription, salary) VALUES ('$name', '$code', '$email', '$jobdescription', '$salary')\";\n mysql_query($sql) or die (mysql_error());\n echo 'Success';\n } \n</code></pre>\n\n<p>The only thing this script does is get the XML file from a certain place on a server and dumps it in a table I allready created in the database.</p>\n\n<p>This needs to run every hour. So in my functions.php:</p>\n\n<pre><code>add_action( 'wp', 'prefix_setup_schedule' );\n/**\n * On an early action hook, check if the hook is scheduled - if not, schedule it.\n */\nfunction prefix_setup_schedule() {\nif ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) {\n wp_schedule_event( time(), 'hourly', 'prefix_hourly_event');\n}\n}\n\n\nadd_action( 'prefix_hourly_event', 'prefix_do_this_hourly' );\n/**\n * On the scheduled action hook, run a function.\n */\nfunction prefix_do_this_hourly() {\n//wp_mail( '[email protected]', 'Auto mail every hour', 'Automatic scheduled email from WordPress.');\n}\n</code></pre>\n\n<p>This so called \"CronJob\" does a dump in the database every hour (I need to add a function that clears the database before inputting new data)\nThe only problem that I had and still have with this is that WordPress doesn't do this every hour unless there is a request to load the page. If there are no visitors there will be no update. </p>\n\n<p>To fix this problem I created a CronJob on my server to execute a request every hour so that the database is updated.</p>\n\n<p>I hope I will find a solution to replace the CronJob from my server.</p>\n\n<p>But thats it. Now I need to execute the XML upload function to my <code>functions.php</code> and make sure the database is flushed before filling it with new data.</p>\n\n<p>@Rarst: Thanks for the WP-Cron heads up. Very usefull.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/174978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52240/" ]
I'm in kind of a weird situation (for me) My client has a website that runs on a custom CMS He wants an online site that loads some data from the existing database. This is an external MSSQL database and for security reasons a serialized table is created. So there is no way for me to "read" from the database. I contacted the company that hosts and maintains the database and they said that they could automatically create an `.csv` export for me every hour and save it at a location on the server. So I was very happy with this because this is a comma seperated `.csv` file. I learned that I could import this to my WP MySQL database with the following: ``` LOAD DATA INFILE '../tmp/file.csv' INTO TABLE $table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS; ``` So far so good. But now my headache starts. I want to do this every hour. So that if their database is altered mine get's updated. The file may overwrite every table/field in the database. (I only use it for reading) I know I can create a cronjob to do this. I simply don't know where to do this. This task must run every hour. So this does not go in a function.php file or even a template.php file. Come to think about it, maybe it shouldn't even be done in WordPress core/custom files. However. Because I don't know where to initiate the function I can not update my database. Hope somebody has a (alternative) solution. M.
I setup something similar. Using IIS - look into writing a .bat file which fires off a php shell script to do whatever it is you need to accomplish. once you have that bat file working, setup a "scheduled task" in IIS <http://technet.microsoft.com/en-us/library/cc721871.aspx> if you are on a linux system, then use crontab <https://www.freebsd.org/doc/handbook/configtuning-cron.html> If you on a hosted, non-vps environment, then you will need to sort out how your site ISP handles this sort of task - each will be different and dependent on contracts / setup
175,011
<p>I have an issue that has me scratching my head and if I scratch anymore I'm gonna go bald. I have looked all over for a solution but have not found anything so I thought I'd stop by and see if maybe any of you experts out there can assist.</p> <p>I created a theme called WP-Forge and then I created a child theme to be used with WP-Forge called WP-Starter <a href="http://wpstarter.themeawesome.com/" rel="nofollow">http://wpstarter.themeawesome.com/</a></p> <p>When I created WP-Starter, the method of @import was still being used and now I see that there is a new way of pulling in the parent css: <a href="http://codex.wordpress.org/Child_Themes" rel="nofollow">http://codex.wordpress.org/Child_Themes</a></p> <p>However, when I updated WP-Starter to use this new way of pulling in the parent css, it seems that I get two versions of WP-Starter's style sheet. If you look at the source of WP-Starter demo site listed above - you will see that wpforge-css is exactly the same as child-style-css.</p> <p>In my parent theme I have all of scripts and styles enqueued in the following manner:</p> <pre><code>function wpforge_scripts() { // Enqueue our stylesheets wp_enqueue_style('opensans-style', 'http://fonts.googleapis.com/css?family=Open+Sans:300,600'); wp_enqueue_style('font-style', get_template_directory_uri() . '/fonts/wpforge-fonts.css'); wp_enqueue_style('normalize-style', get_template_directory_uri() . '/css/normalize.css'); wp_enqueue_style('foundation-style', get_template_directory_uri() . '/css/foundation.css'); wp_enqueue_style('wpforge-style', get_stylesheet_uri()); // Register our scripts wp_enqueue_script ('modernizr', get_template_directory_uri() . '/js/vendor/modernizr.js', array('jquery'), '5.5.0.3', false); wp_enqueue_script ('foundation-js', get_template_directory_uri() . '/js/foundation.min.js', array('jquery'), '5.5.0.3', true); wp_enqueue_script ('functions-js', get_template_directory_uri() . '/js/wpforge-functions.js', array('jquery'), '5.5.0.3', true); // Make the "Back" string in Foudation mobile menu translatable $translation_array = array( 'nav_back' =&gt; __( 'Back', 'wpforge' ) ); wp_localize_script( 'foundation-js', 'foundation_strings', $translation_array ); } add_action( 'wp_enqueue_scripts', 'wpforge_scripts' ); </code></pre> <p>and in my child theme WP-Starter all I have is this:</p> <pre><code>function wpstarter_styles() { wp_enqueue_style( 'parent-theme', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpstarter_styles', 100 ); </code></pre> <p>Now when you look at the page source of the demo site you will see this:</p> <pre><code>&lt;title&gt;WP-Starter | A WordPress Child Theme for WP-Forge&lt;/title&gt; &lt;link rel='stylesheet' id='wpforge-fonts-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/fonts/wpforge-fonts.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='normalize-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/css/normalize.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='foundation-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/css/foundation.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='wpforge-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wpstarter/style.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='parent-style-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/style.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='child-style-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wpstarter/style.css' type='text/css' media='all' /&gt; </code></pre> <p>If you click on wpforge-css it is the same as child-style-css.</p> <p>Just wondering if anyone has ever run into this particular issue or if anyone can help by explaining why this may be happening so I can correct it?</p> <p>Your help is greatly appreciated and thank you in advance.</p>
[ { "answer_id": 175021, "author": "user3325126", "author_id": 56674, "author_profile": "https://wordpress.stackexchange.com/users/56674", "pm_score": 0, "selected": false, "text": "<p>Did you try adding the next line of code as it says in the codex?</p>\n\n<p><strong>Codex:</strong></p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n function theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_uri(), array( 'parent-style' ) );//Add this to wpstarter_styles();\n}\n</code></pre>\n" }, { "answer_id": 175022, "author": "Craig Pearson", "author_id": 17295, "author_profile": "https://wordpress.stackexchange.com/users/17295", "pm_score": 0, "selected": false, "text": "<p>It's been a while since I've worked with child themes but I presume the problem here is that you're registering your parent css using <code>get_stylesheet_uri</code> as opposed to <code>get_template_directory_uri</code></p>\n\n<p>Try using this instead, notice how I have changed the <code>get_stylesheet_uri</code> with <code>get_template_directory_uri</code></p>\n\n<pre><code>function wpforge_scripts() {\n\n // Enqueue our stylesheets\n wp_enqueue_style('opensans-style', 'http://fonts.googleapis.com/css?family=Open+Sans:300,600');\n wp_enqueue_style('font-style', get_template_directory_uri() . '/fonts/wpforge-fonts.css');\n wp_enqueue_style('normalize-style', get_template_directory_uri() . '/css/normalize.css');\n wp_enqueue_style('foundation-style', get_template_directory_uri() . '/css/foundation.css');\n wp_enqueue_style('wpforge-style', get_template_directory_uri() . '/style.css'); \n\n // Register our scripts\n wp_enqueue_script ('modernizr', get_template_directory_uri() . '/js/vendor/modernizr.js', array('jquery'), '5.5.0.3', false);\n wp_enqueue_script ('foundation-js', get_template_directory_uri() . '/js/foundation.min.js', array('jquery'), '5.5.0.3', true);\n wp_enqueue_script ('functions-js', get_template_directory_uri() . '/js/wpforge-functions.js', array('jquery'), '5.5.0.3', true);\n\n // Make the \"Back\" string in Foudation mobile menu translatable\n $translation_array = array( 'nav_back' =&gt; __( 'Back', 'wpforge' ) );\n wp_localize_script( 'foundation-js', 'foundation_strings', $translation_array );\n\n}\nadd_action( 'wp_enqueue_scripts', 'wpforge_scripts' );\n</code></pre>\n\n<p>Now the parent stylesheet is loaded properly we can call the child theme's stylesheet using <code>get_stylesheet_uri</code> and pass it a dependency of the parent theme stylesheet referenced by the handle it was registered with of <code>wpforge-style</code></p>\n\n<pre><code>function wpstarter_styles() {\n\n wp_enqueue_style( 'wp-starter', get_stylesheet_uri(), array( 'wpforge-style' ) );\n}\nadd_action( 'wp_enqueue_scripts', 'wpstarter_styles', 100 );\n</code></pre>\n\n<p>This is because <code>get_stylesheet_uri</code> gets the current active themes stylesheet URI. Therefore when the child theme is loaded first it performs the function <code>wpforge_scripts</code> from its parent theme - which in your code specified <code>get_stylesheet_uri</code> thus was actually getting the URI of the child theme as that is active, not the parent theme. Swapping this for get_template_directory_uri will get the correct template directory for the parent theme.</p>\n\n<p>All this is in theory I haven't had a chance to check it for you (fingers crossed)</p>\n" }, { "answer_id": 175225, "author": "tsquez", "author_id": 65047, "author_profile": "https://wordpress.stackexchange.com/users/65047", "pm_score": 1, "selected": false, "text": "<p>Actually @Pieter Goosen took care of the issue when he corrected the Codex and removed the call to the extra style sheet. So in fact this works the way it should</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n function theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n}\n</code></pre>\n\n<p>Thanks Pieter.</p>\n" } ]
2015/01/15
[ "https://wordpress.stackexchange.com/questions/175011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65047/" ]
I have an issue that has me scratching my head and if I scratch anymore I'm gonna go bald. I have looked all over for a solution but have not found anything so I thought I'd stop by and see if maybe any of you experts out there can assist. I created a theme called WP-Forge and then I created a child theme to be used with WP-Forge called WP-Starter <http://wpstarter.themeawesome.com/> When I created WP-Starter, the method of @import was still being used and now I see that there is a new way of pulling in the parent css: <http://codex.wordpress.org/Child_Themes> However, when I updated WP-Starter to use this new way of pulling in the parent css, it seems that I get two versions of WP-Starter's style sheet. If you look at the source of WP-Starter demo site listed above - you will see that wpforge-css is exactly the same as child-style-css. In my parent theme I have all of scripts and styles enqueued in the following manner: ``` function wpforge_scripts() { // Enqueue our stylesheets wp_enqueue_style('opensans-style', 'http://fonts.googleapis.com/css?family=Open+Sans:300,600'); wp_enqueue_style('font-style', get_template_directory_uri() . '/fonts/wpforge-fonts.css'); wp_enqueue_style('normalize-style', get_template_directory_uri() . '/css/normalize.css'); wp_enqueue_style('foundation-style', get_template_directory_uri() . '/css/foundation.css'); wp_enqueue_style('wpforge-style', get_stylesheet_uri()); // Register our scripts wp_enqueue_script ('modernizr', get_template_directory_uri() . '/js/vendor/modernizr.js', array('jquery'), '5.5.0.3', false); wp_enqueue_script ('foundation-js', get_template_directory_uri() . '/js/foundation.min.js', array('jquery'), '5.5.0.3', true); wp_enqueue_script ('functions-js', get_template_directory_uri() . '/js/wpforge-functions.js', array('jquery'), '5.5.0.3', true); // Make the "Back" string in Foudation mobile menu translatable $translation_array = array( 'nav_back' => __( 'Back', 'wpforge' ) ); wp_localize_script( 'foundation-js', 'foundation_strings', $translation_array ); } add_action( 'wp_enqueue_scripts', 'wpforge_scripts' ); ``` and in my child theme WP-Starter all I have is this: ``` function wpstarter_styles() { wp_enqueue_style( 'parent-theme', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpstarter_styles', 100 ); ``` Now when you look at the page source of the demo site you will see this: ``` <title>WP-Starter | A WordPress Child Theme for WP-Forge</title> <link rel='stylesheet' id='wpforge-fonts-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/fonts/wpforge-fonts.css' type='text/css' media='all' /> <link rel='stylesheet' id='normalize-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/css/normalize.css' type='text/css' media='all' /> <link rel='stylesheet' id='foundation-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/css/foundation.css' type='text/css' media='all' /> <link rel='stylesheet' id='wpforge-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wpstarter/style.css' type='text/css' media='all' /> <link rel='stylesheet' id='parent-style-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wp-forge/style.css' type='text/css' media='all' /> <link rel='stylesheet' id='child-style-css' href='http://wpstarter.themeawesome.com/wp-content/themes/wpstarter/style.css' type='text/css' media='all' /> ``` If you click on wpforge-css it is the same as child-style-css. Just wondering if anyone has ever run into this particular issue or if anyone can help by explaining why this may be happening so I can correct it? Your help is greatly appreciated and thank you in advance.
Actually @Pieter Goosen took care of the issue when he corrected the Codex and removed the call to the extra style sheet. So in fact this works the way it should ``` add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` Thanks Pieter.
175,028
<p>I'm trying to put 4 news with pictures 3 small and one large, have gotten displaying them but the "large" is repeated with the last "small"</p> <p><img src="https://i.stack.imgur.com/aWaTq.jpg" alt="enter image description here"></p> <pre><code>&lt;?php $b=1; $args = array( 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'gens', 'field' =&gt; 'slug', 'terms' =&gt; 'newsgen' ) ), 'post_type'=&gt;'', //add your post type name 'posts_per_page' =&gt; 4, 'orderby' =&gt; 'asc', ); query_posts($args); while ( have_posts() ) : the_post(); ?&gt; &lt;?php if($b%4==1 &amp;&amp; $b==1) : ?&gt; &lt;div id="news-big"&gt; &lt;?php $image_url = catch_that_image(); $image = thumb($image_url, 209, 97); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;img src="&lt;?php echo $image['url']; ?&gt;"/&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;div class="news-small"&gt; &lt;div class="container-small"&gt; &lt;?php $image_url = catch_that_image(); $image = thumb($image_url, 136, 75); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;img src="&lt;?php echo $image['url']; ?&gt;"/&gt;&lt;/a&gt; &lt;/div&gt; &lt;!-- End Thumb Container --&gt; &lt;?php $b++; endwhile; wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 175021, "author": "user3325126", "author_id": 56674, "author_profile": "https://wordpress.stackexchange.com/users/56674", "pm_score": 0, "selected": false, "text": "<p>Did you try adding the next line of code as it says in the codex?</p>\n\n<p><strong>Codex:</strong></p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n function theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_uri(), array( 'parent-style' ) );//Add this to wpstarter_styles();\n}\n</code></pre>\n" }, { "answer_id": 175022, "author": "Craig Pearson", "author_id": 17295, "author_profile": "https://wordpress.stackexchange.com/users/17295", "pm_score": 0, "selected": false, "text": "<p>It's been a while since I've worked with child themes but I presume the problem here is that you're registering your parent css using <code>get_stylesheet_uri</code> as opposed to <code>get_template_directory_uri</code></p>\n\n<p>Try using this instead, notice how I have changed the <code>get_stylesheet_uri</code> with <code>get_template_directory_uri</code></p>\n\n<pre><code>function wpforge_scripts() {\n\n // Enqueue our stylesheets\n wp_enqueue_style('opensans-style', 'http://fonts.googleapis.com/css?family=Open+Sans:300,600');\n wp_enqueue_style('font-style', get_template_directory_uri() . '/fonts/wpforge-fonts.css');\n wp_enqueue_style('normalize-style', get_template_directory_uri() . '/css/normalize.css');\n wp_enqueue_style('foundation-style', get_template_directory_uri() . '/css/foundation.css');\n wp_enqueue_style('wpforge-style', get_template_directory_uri() . '/style.css'); \n\n // Register our scripts\n wp_enqueue_script ('modernizr', get_template_directory_uri() . '/js/vendor/modernizr.js', array('jquery'), '5.5.0.3', false);\n wp_enqueue_script ('foundation-js', get_template_directory_uri() . '/js/foundation.min.js', array('jquery'), '5.5.0.3', true);\n wp_enqueue_script ('functions-js', get_template_directory_uri() . '/js/wpforge-functions.js', array('jquery'), '5.5.0.3', true);\n\n // Make the \"Back\" string in Foudation mobile menu translatable\n $translation_array = array( 'nav_back' =&gt; __( 'Back', 'wpforge' ) );\n wp_localize_script( 'foundation-js', 'foundation_strings', $translation_array );\n\n}\nadd_action( 'wp_enqueue_scripts', 'wpforge_scripts' );\n</code></pre>\n\n<p>Now the parent stylesheet is loaded properly we can call the child theme's stylesheet using <code>get_stylesheet_uri</code> and pass it a dependency of the parent theme stylesheet referenced by the handle it was registered with of <code>wpforge-style</code></p>\n\n<pre><code>function wpstarter_styles() {\n\n wp_enqueue_style( 'wp-starter', get_stylesheet_uri(), array( 'wpforge-style' ) );\n}\nadd_action( 'wp_enqueue_scripts', 'wpstarter_styles', 100 );\n</code></pre>\n\n<p>This is because <code>get_stylesheet_uri</code> gets the current active themes stylesheet URI. Therefore when the child theme is loaded first it performs the function <code>wpforge_scripts</code> from its parent theme - which in your code specified <code>get_stylesheet_uri</code> thus was actually getting the URI of the child theme as that is active, not the parent theme. Swapping this for get_template_directory_uri will get the correct template directory for the parent theme.</p>\n\n<p>All this is in theory I haven't had a chance to check it for you (fingers crossed)</p>\n" }, { "answer_id": 175225, "author": "tsquez", "author_id": 65047, "author_profile": "https://wordpress.stackexchange.com/users/65047", "pm_score": 1, "selected": false, "text": "<p>Actually @Pieter Goosen took care of the issue when he corrected the Codex and removed the call to the extra style sheet. So in fact this works the way it should</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n function theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n}\n</code></pre>\n\n<p>Thanks Pieter.</p>\n" } ]
2015/01/16
[ "https://wordpress.stackexchange.com/questions/175028", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54649/" ]
I'm trying to put 4 news with pictures 3 small and one large, have gotten displaying them but the "large" is repeated with the last "small" ![enter image description here](https://i.stack.imgur.com/aWaTq.jpg) ``` <?php $b=1; $args = array( 'tax_query' => array( array( 'taxonomy' => 'gens', 'field' => 'slug', 'terms' => 'newsgen' ) ), 'post_type'=>'', //add your post type name 'posts_per_page' => 4, 'orderby' => 'asc', ); query_posts($args); while ( have_posts() ) : the_post(); ?> <?php if($b%4==1 && $b==1) : ?> <div id="news-big"> <?php $image_url = catch_that_image(); $image = thumb($image_url, 209, 97); ?> <a href="<?php the_permalink(); ?>"> <img src="<?php echo $image['url']; ?>"/></a> </div> <?php endif; ?> <a href="<?php the_permalink(); ?>"><div class="news-small"> <div class="container-small"> <?php $image_url = catch_that_image(); $image = thumb($image_url, 136, 75); ?> <a href="<?php the_permalink(); ?>"> <img src="<?php echo $image['url']; ?>"/></a> </div> <!-- End Thumb Container --> <?php $b++; endwhile; wp_reset_query(); ?> ```
Actually @Pieter Goosen took care of the issue when he corrected the Codex and removed the call to the extra style sheet. So in fact this works the way it should ``` add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` Thanks Pieter.
175,090
<p>I am able to implement http basic auth in <code>wp_remote_get</code> using the following code</p> <pre><code>$args = array( 'headers' =&gt; array( 'Authorization' =&gt; 'Basic ' . base64_encode( $username . ':' . $password ) ) ); wp_remote_request( $url, $args ); </code></pre> <p>Is it possible to do http digest based authentication using <code>wp_remote_get</code> function?</p>
[ { "answer_id": 179825, "author": "Saurabh Shukla", "author_id": 20375, "author_profile": "https://wordpress.stackexchange.com/users/20375", "pm_score": 0, "selected": false, "text": "<p>Isn't that obvious? <em>wp_remote_get</em> is just a single request response function. The difference, as far as wp_remote_get is concerned is that basic authentication is just <em>one</em> request response and hence just one call to wp_remote_get.</p>\n\n<p>For digest based authentication, you have to make four request-response = four wp_remote_get calls.</p>\n" }, { "answer_id": 214072, "author": "Daniel Bachhuber", "author_id": 82349, "author_profile": "https://wordpress.stackexchange.com/users/82349", "pm_score": 2, "selected": false, "text": "<p>It is possible to do HTTP DIGEST authentication with <code>wp_remote_get()</code>, but it's somewhat complicated. I've written a <a href=\"http://blog.handbuilt.co/2016/01/08/using-http-digest-authentication-with-wordpress-wp_remote_get/\" rel=\"nofollow\">short wrapper function</a> you can use.</p>\n" } ]
2015/01/16
[ "https://wordpress.stackexchange.com/questions/175090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24579/" ]
I am able to implement http basic auth in `wp_remote_get` using the following code ``` $args = array( 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ) ) ); wp_remote_request( $url, $args ); ``` Is it possible to do http digest based authentication using `wp_remote_get` function?
It is possible to do HTTP DIGEST authentication with `wp_remote_get()`, but it's somewhat complicated. I've written a [short wrapper function](http://blog.handbuilt.co/2016/01/08/using-http-digest-authentication-with-wordpress-wp_remote_get/) you can use.
175,106
<p>I want to list all posts with a corresponding template for a custom taxonomy term of a custom post type. To make it easier to understand: </p> <p>The custom post type is called PUBLICATIONS and has a custom taxonomy called LISTS. Each list template is slighty different, so when all posts are listed on the archive-publications page, posts in term LIST A shall be displayed using Template A, LIST B Template B, and so on. </p> <p>I've tried this:</p> <pre><code>&lt;?php function publikationen_archive() { if ( is_archive('publikationen') &amp;&amp; is_tax('downloads') ) { get_template_part( 'templates/content-downloads' ); } elseif ( is_archive('publikationen') &amp;&amp; is_tax('sonderbaende-kataloge') ) { get_template_part( 'templates/content-sonderbaende-kataloge' ); } elseif ( is_archive('publikationen') &amp;&amp; is_tax('neuerscheinungen') ) { get_template_part( 'templates/content-neuerscheinungen' ); } elseif ( is_archive('publikationen') &amp;&amp; is_tax('untersuchungen') ) { get_template_part( 'templates/content-untersuchungen' ); } elseif ( is_archive('publikationen') &amp;&amp; is_tax('studien-materialien') ) { get_template_part( 'templates/content-studien-materialien' ); } } ?&gt; </code></pre> <p>which didn't work. Then I came across the filter <code>single_template</code>, <code>template_redirect</code> and <code>template_include</code> but don't really know what to do with them. </p>
[ { "answer_id": 175187, "author": "gfaw", "author_id": 29222, "author_profile": "https://wordpress.stackexchange.com/users/29222", "pm_score": 1, "selected": false, "text": "<p><strong>I solved it.</strong></p>\n\n<p>SOLUTION:</p>\n\n<pre><code>&lt;?php \nif ( has_term( 'downloads', 'listen', $post-&gt;ID ) ) {\n get_template_part( 'templates/content-downloads-vergriffener-baende' ); \n} \nelseif ( has_term( 'untersuchungen', 'listen', $post-&gt;ID ) ) { \n get_template_part( 'templates/content-untersuchungen' ); \n} \nelseif ( has_term( 'studien-materialien', 'listen', $post-&gt;ID ) ) { \n get_template_part( 'templates/content-studien-materialien' ); \n} \nelseif ( has_term( 'sonderbaende-kataloge', 'listen', $post-&gt;ID ) ) { \n get_template_part( 'templates/content-sonderbaende-kataloge' ); \n}\n?&gt;\n</code></pre>\n\n<p>This post: <a href=\"http://wpquestions.com/question/show/id/2038\" rel=\"nofollow\">http://wpquestions.com/question/show/id/2038</a> has been greatly helpful in the process. </p>\n" }, { "answer_id": 175240, "author": "Lemon Kazi", "author_id": 50144, "author_profile": "https://wordpress.stackexchange.com/users/50144", "pm_score": 0, "selected": false, "text": "<p>in your post loop.\nuse this code.</p>\n\n<pre><code>&lt;?php while (have_posts()) : the_post(); \n $post_type = get_post_type(get_the_ID());\n if($post_type !='post'){\n get_template_part('content-' . $post_type, get_post_format());\n }\n else {\n get_template_part( 'content', get_post_format() );\n }\n //If comments are open or we have at least one comment, load up the comment template.\n // if ( comments_open() || get_comments_number() ) {\n // comments_template( '', true );\n // }\n //endwhile; ?&gt;\n &lt;?php comments_template( '', true ); ?&gt;\n &lt;?php endwhile; // end of the loop. ?&gt;\n</code></pre>\n\n<p>then create content-publication.php for your post type page structure.</p>\n" } ]
2015/01/16
[ "https://wordpress.stackexchange.com/questions/175106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29222/" ]
I want to list all posts with a corresponding template for a custom taxonomy term of a custom post type. To make it easier to understand: The custom post type is called PUBLICATIONS and has a custom taxonomy called LISTS. Each list template is slighty different, so when all posts are listed on the archive-publications page, posts in term LIST A shall be displayed using Template A, LIST B Template B, and so on. I've tried this: ``` <?php function publikationen_archive() { if ( is_archive('publikationen') && is_tax('downloads') ) { get_template_part( 'templates/content-downloads' ); } elseif ( is_archive('publikationen') && is_tax('sonderbaende-kataloge') ) { get_template_part( 'templates/content-sonderbaende-kataloge' ); } elseif ( is_archive('publikationen') && is_tax('neuerscheinungen') ) { get_template_part( 'templates/content-neuerscheinungen' ); } elseif ( is_archive('publikationen') && is_tax('untersuchungen') ) { get_template_part( 'templates/content-untersuchungen' ); } elseif ( is_archive('publikationen') && is_tax('studien-materialien') ) { get_template_part( 'templates/content-studien-materialien' ); } } ?> ``` which didn't work. Then I came across the filter `single_template`, `template_redirect` and `template_include` but don't really know what to do with them.
**I solved it.** SOLUTION: ``` <?php if ( has_term( 'downloads', 'listen', $post->ID ) ) { get_template_part( 'templates/content-downloads-vergriffener-baende' ); } elseif ( has_term( 'untersuchungen', 'listen', $post->ID ) ) { get_template_part( 'templates/content-untersuchungen' ); } elseif ( has_term( 'studien-materialien', 'listen', $post->ID ) ) { get_template_part( 'templates/content-studien-materialien' ); } elseif ( has_term( 'sonderbaende-kataloge', 'listen', $post->ID ) ) { get_template_part( 'templates/content-sonderbaende-kataloge' ); } ?> ``` This post: <http://wpquestions.com/question/show/id/2038> has been greatly helpful in the process.
175,203
<p>I want to structure my site like such:</p> <pre><code>http://www.website.com/cars/ http://www.website.com/cars/blue/ http://www.website.com/cars/red/ </code></pre> <p>Where both <code>/cars/</code> and <code>/blue/</code> would be articles that can receive comments. If you went to <code>cars/</code> you would be able to display a listing of all of the children so you could click through to <code>/blue/</code> and <code>/red/</code> etc. I also want users to be able to comment on every page of the site.</p> <p>How can I accomplish this with wordpress? I can't do it with categories and posts because I need content and comments open on the parent. I would prefer the children to be posts as opposed to pages as the site is already setup to use this structure.</p>
[ { "answer_id": 175235, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>The thing about WordPress, while it doesn't have a <em>neat</em> routing system in principle it does same operation. It takes the URL input and matches it to a set of query variables.</p>\n\n<p>The not–neat thing about it is that it uses regular expressions for these not–quite–routes and <em>a lot</em> of them. The total number of rules fluctuates from about a hundred minimum to <em>thousands</em> for a complex site (dump <code>$wp_rewrite-&gt;rules</code> to see).</p>\n\n<p>This system is entirely possible to replace (it likely won't be particularly clean, bordering on crazy hack from WP perspective though).</p>\n\n<p>The main challenge is that you would have to spent enormous effort for <em>feature parity</em>, that is your router not breaking 90% of things that “just work” in WP.</p>\n\n<p>If you aren't concerned about feature parity you could very well just do a small subset of them and ignore the rest.</p>\n\n<p>PS or you could just make a WP site like it's meant to be done. That works for plenty of people. :)</p>\n" }, { "answer_id": 175249, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Combining wordpress with other frameworks will make it very easy for you to shot yourself in the foot. If all what your clients want is an editor then you can just use tinymce without dragging the whole of wordpress into it, but if they are after the workflow and flexibility then it will be pointless to try to make wordpress something that it isn't. you are more likely to both spend more time then you anticipate on development and even then produce something which will not fully satisfy your clients.</p>\n" }, { "answer_id": 175268, "author": "Squish", "author_id": 28821, "author_profile": "https://wordpress.stackexchange.com/users/28821", "pm_score": -1, "selected": false, "text": "<p>Have you looked at <a href=\"https://octobercms.com\" rel=\"nofollow\">October CMS</a>?</p>\n\n<p>The only reason I didn't use it for my newest project was because of SEO. Yoast's plugin on WordPress just handles a lot of stuff I don't want to deal with regularly.</p>\n" }, { "answer_id": 200463, "author": "Steve Jamesson", "author_id": 78756, "author_profile": "https://wordpress.stackexchange.com/users/78756", "pm_score": 0, "selected": false, "text": "<p>I've accomplished this with Laravel using wp-api.org, Guzzle, caching, and I extended <a href=\"https://github.com/Cyber-Duck/laravel-wp-api\" rel=\"nofollow\">CyberDuck's package</a> a bit to fit my needs. All my own views and my own routing.</p>\n\n<p>When approaching it in this way, I found it easier to think of the WP admin area as more of a structured content repository, and less of a page management CMS. I heavily used ACF and my own custom plugins.</p>\n\n<p>Many other WP plugins wouldn't work too well, as many produce output. You'd have to either figure out a way to get that output and print it yourself or build your own functionality instead.</p>\n\n<p>I never ended up launching this one, as the project needed a basic shopping cart and WooCommerce fit the bill, so stuck w/ a custom WP theme instead. But it was a great learning experience and did work quite well, especially once caching was running.</p>\n\n<p>But you will then have two applications to maintain. In my case, at least, it really only made good sense if I was going to build multiple websites or apps that all fed from the WP content repository.</p>\n\n<p><strong>Do you think this would be a nice approach to it?</strong></p>\n\n<p>Yes, if the application or domain warrants it. I greatly enjoyed using my own routing and views, so much more control. And I didn't have to touch any WP theme code, which is a huge bonus.</p>\n\n<p><strong>Any advantage of using only wordpress for the site rather than using an external framework for it?</strong> </p>\n\n<p>Absolutely, one less application to maintain and much less code to write. All routing is built-in to WP. But you're stuck with how WP routes things, unless you really dig in to its rewrite engine and hack it up, which could mess with other plugins you may be running.</p>\n\n<p><strong>Is there some way to connect the Laravel routing system with the WordPress rewrite system?</strong></p>\n\n<p>I didn't dig much into this, as if I needed to use a rewrite/route structure that's similar enough to WP, I would've just stuck with WP in the first place. The main motivator for my project was that my domain's route structure simply wouldn't cooperate with WP's.</p>\n\n<p>It really wasn't difficult to set up a route (i.e. <code>post/{slug}</code>) to query WP API for the {slug} and get the post's content.</p>\n" } ]
2015/01/17
[ "https://wordpress.stackexchange.com/questions/175203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65675/" ]
I want to structure my site like such: ``` http://www.website.com/cars/ http://www.website.com/cars/blue/ http://www.website.com/cars/red/ ``` Where both `/cars/` and `/blue/` would be articles that can receive comments. If you went to `cars/` you would be able to display a listing of all of the children so you could click through to `/blue/` and `/red/` etc. I also want users to be able to comment on every page of the site. How can I accomplish this with wordpress? I can't do it with categories and posts because I need content and comments open on the parent. I would prefer the children to be posts as opposed to pages as the site is already setup to use this structure.
The thing about WordPress, while it doesn't have a *neat* routing system in principle it does same operation. It takes the URL input and matches it to a set of query variables. The not–neat thing about it is that it uses regular expressions for these not–quite–routes and *a lot* of them. The total number of rules fluctuates from about a hundred minimum to *thousands* for a complex site (dump `$wp_rewrite->rules` to see). This system is entirely possible to replace (it likely won't be particularly clean, bordering on crazy hack from WP perspective though). The main challenge is that you would have to spent enormous effort for *feature parity*, that is your router not breaking 90% of things that “just work” in WP. If you aren't concerned about feature parity you could very well just do a small subset of them and ignore the rest. PS or you could just make a WP site like it's meant to be done. That works for plenty of people. :)
175,226
<p>I have a custom post type archive archive-projects.php that I am using as a page template because I have some custom fields that I want to display. I am trying to get the post id of this page but either get null or the id of the first post in the archive depending on what I try. I have tried putting my code above the loop on my page but without any luck.</p> <p>Apologies if this is a duplicate but I have tried searching many tutorials on this and still don't have an answer with my specific scenario of using a page template with a custom post type archive.</p> <p>I have tried this code and it works but I am still stumped as to why none of the other methods seem to work. I'm reluctant to keep this as a solution because if the user changes the page slug this won't work anymore:</p> <pre><code>$my_page_id = get_id_by_slug('projects'); function get_id_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) { return $page-&gt;ID; } else { return null; } } </code></pre> <p>I have tried the following without success (above my custom loop in my template):</p> <pre><code>get_queried_object_id(); // returns nothing $page_id = $wp_query-&gt;get_queried_object_id(); // returns 0 global $post; // I've tried including this and removing with same effect $post = $wp_query-&gt;post; $post_id = $post-&gt;ID; // returns the id of the first post in my archive </code></pre> <p>Any ideas on what I am doing wrong or the right way to get the actual id of my projects page?</p> <p><strong>UPDATE</strong> My custom post type had has_archive set to true. I tried creating a custom template but due to WordPress hierarchy it was looking for an archive page. I solved my issue by setting has_archive to false and creating a custom template called page-template-projects.php. I was then able to setup a page called Projects and use my custom template, while being able to correctly get an ID for the page.</p>
[ { "answer_id": 175228, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<h2>EDIT</h2>\n\n<p>I get the idea that I might have misread your question</p>\n\n<p>Just a few notes here</p>\n\n<ul>\n<li><p>If <code>archive-projects.php</code> is a page template, rename it. You should not use <em>archive</em> as a prefix for a page template, or for that matter any other reserved template name. Page templates should be named <code>page-{$name}.php</code> or any other name with prefixes used by the template hierarchy. This is confusing to Wordpress and messes with the template hierarchy</p></li>\n<li><p>If this is a page template, you should get the ID with <code>get_queried_object_id();</code> or display it with <code>echo get_queried_object_id();</code></p></li>\n<li><p>If this is a true archive page, you won't get an ID</p></li>\n</ul>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>Archive pages, whether post type archive pages, category archives, date archives etc, search pages, single pages and the homepage are pseudo pages, in other words, fake pages. They don't have ID's as they do not exist because they are not created pages which is saved in the db</p>\n\n<p>These pages \"inherits\" the ID of the specific post or archive they display, although they still don't have an ID themselves, accept the homepage, date archives, search pages and post type archive pages</p>\n\n<p>So, in short, your custom post archive page will not have an ID. </p>\n\n<h2>PROOF OF CONCEPT</h2>\n\n<p>You can do a <code>var_dump($wp_query)</code> on your archive page, you will see that only real pages have ID's</p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump($wp_query); ?&gt;&lt;/pre&gt;&lt;?php \n</code></pre>\n" }, { "answer_id": 175602, "author": "Greg", "author_id": 38099, "author_profile": "https://wordpress.stackexchange.com/users/38099", "pm_score": 0, "selected": false, "text": "<p>My custom post type had <code>has_archive</code> set to true. I tried creating a custom template but due to WordPress hierarchy it was looking for an archive page. <strong>I solved my issue by setting <code>has_archive</code> to false and creating a custom template called page-template-projects.php.</strong> (the name isn't important) I was then able to setup a page called Projects and use my custom template, while being able to correctly get an ID for the page.</p>\n\n<p>If you are setting up a custom post type then take note of <code>has_archive</code> and make sure you use it accordingly. If you set this to false you can easily create your own template and custom query using <code>WP_Query</code> in your template to list out your posts belonging to your custom post type.</p>\n" } ]
2015/01/18
[ "https://wordpress.stackexchange.com/questions/175226", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38099/" ]
I have a custom post type archive archive-projects.php that I am using as a page template because I have some custom fields that I want to display. I am trying to get the post id of this page but either get null or the id of the first post in the archive depending on what I try. I have tried putting my code above the loop on my page but without any luck. Apologies if this is a duplicate but I have tried searching many tutorials on this and still don't have an answer with my specific scenario of using a page template with a custom post type archive. I have tried this code and it works but I am still stumped as to why none of the other methods seem to work. I'm reluctant to keep this as a solution because if the user changes the page slug this won't work anymore: ``` $my_page_id = get_id_by_slug('projects'); function get_id_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) { return $page->ID; } else { return null; } } ``` I have tried the following without success (above my custom loop in my template): ``` get_queried_object_id(); // returns nothing $page_id = $wp_query->get_queried_object_id(); // returns 0 global $post; // I've tried including this and removing with same effect $post = $wp_query->post; $post_id = $post->ID; // returns the id of the first post in my archive ``` Any ideas on what I am doing wrong or the right way to get the actual id of my projects page? **UPDATE** My custom post type had has\_archive set to true. I tried creating a custom template but due to WordPress hierarchy it was looking for an archive page. I solved my issue by setting has\_archive to false and creating a custom template called page-template-projects.php. I was then able to setup a page called Projects and use my custom template, while being able to correctly get an ID for the page.
EDIT ---- I get the idea that I might have misread your question Just a few notes here * If `archive-projects.php` is a page template, rename it. You should not use *archive* as a prefix for a page template, or for that matter any other reserved template name. Page templates should be named `page-{$name}.php` or any other name with prefixes used by the template hierarchy. This is confusing to Wordpress and messes with the template hierarchy * If this is a page template, you should get the ID with `get_queried_object_id();` or display it with `echo get_queried_object_id();` * If this is a true archive page, you won't get an ID ORIGINAL ANSWER --------------- Archive pages, whether post type archive pages, category archives, date archives etc, search pages, single pages and the homepage are pseudo pages, in other words, fake pages. They don't have ID's as they do not exist because they are not created pages which is saved in the db These pages "inherits" the ID of the specific post or archive they display, although they still don't have an ID themselves, accept the homepage, date archives, search pages and post type archive pages So, in short, your custom post archive page will not have an ID. PROOF OF CONCEPT ---------------- You can do a `var_dump($wp_query)` on your archive page, you will see that only real pages have ID's ``` ?><pre><?php var_dump($wp_query); ?></pre><?php ```
175,227
<p>I just encountered weird problem. My shortcode output which is something like</p> <pre><code>'&lt;span class="link_container"&gt;&lt;a href="#"&gt;'.$content.'&lt;/a&gt;&lt;/span&gt; &lt;div class="upgrade_box"&gt; some more divs here &lt;/div&gt;' </code></pre> <p>is being broken by random <code>&lt;/p&gt;</code> closing tag inserted after <code>&lt;/span&gt;</code></p> <p>Changing wpautop priority didn't work. The only solution that seemed to work was removing wpautop filter altogether which is obviously not that great of a solution. </p> <p>P.S. I'm using wp 2015 theme on my testing site so it's not some theme forest theme ppl seem to have problems with. </p>
[ { "answer_id": 175238, "author": "NickFMC", "author_id": 56566, "author_profile": "https://wordpress.stackexchange.com/users/56566", "pm_score": 1, "selected": false, "text": "<p>Try this function out, be sure to add your shortcode in the array</p>\n\n<pre><code>// (OPT) STOP SHORTCODES THAT DON'T USE INLINE CONTENT FROM BEING WRAPPED IN A P TAG (until WP fixes this)\n\n// ** NOTE -&gt; BE SURE TO change the array to the shortcodes you are using!\n\nadd_filter('the_content', 'the_content_filter');\nfunction the_content_filter($content) {\n // array of custom shortcodes requiring the fix\n $block = join(\"|\",array( 'shortcode_name' ));\n // opening tag\n $rep = preg_replace(\"/(&lt;p&gt;)?\\[($block)(\\s[^\\]]+)?\\](&lt;\\/p&gt;|&lt;br \\/&gt;)?/\",\"[$2$3]\",$content);\n // closing tag\n $rep = preg_replace(\"/(&lt;p&gt;)?\\[\\/($block)](&lt;\\/p&gt;|&lt;br \\/&gt;)?/\",\"[/$2]\",$rep);\n return $rep;\n}\n</code></pre>\n" }, { "answer_id": 262580, "author": "Corey", "author_id": 115672, "author_profile": "https://wordpress.stackexchange.com/users/115672", "pm_score": 0, "selected": false, "text": "<p>Going off @nickfmc's comment, here is a revised version for latest WordPress that uses the correct priority on the filter and also fixes a couple issues with the regex.</p>\n\n<p>Note: it is best to keep each block format shortcode on its own line (separate paragraph in WYSIWYG editor).</p>\n\n<pre><code>&lt;?php\n\nadd_filter('the_content', function ($content) {\n $blocks = 'columns|column';\n\n $replace = [\n \"/(?:&lt;p&gt;)?\\[($blocks)(\\s[^\\]]+)?\\](?:&lt;\\/p&gt;|&lt;br\\s*\\/?&gt;)?/\" =&gt; '[$1$2]',\n \"/(?:&lt;p&gt;)?\\[\\/($blocks)\\](?:&lt;\\/p&gt;|&lt;br\\s*\\/?&gt;)?/\" =&gt; '[/$1]',\n ];\n\n return preg_replace(array_keys($replace), array_values($replace), $content);\n}, '10.1');\n</code></pre>\n\n<p>Of course, replace the <code>$blocks</code> variable with your own shortcodes.</p>\n" } ]
2015/01/18
[ "https://wordpress.stackexchange.com/questions/175227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13986/" ]
I just encountered weird problem. My shortcode output which is something like ``` '<span class="link_container"><a href="#">'.$content.'</a></span> <div class="upgrade_box"> some more divs here </div>' ``` is being broken by random `</p>` closing tag inserted after `</span>` Changing wpautop priority didn't work. The only solution that seemed to work was removing wpautop filter altogether which is obviously not that great of a solution. P.S. I'm using wp 2015 theme on my testing site so it's not some theme forest theme ppl seem to have problems with.
Try this function out, be sure to add your shortcode in the array ``` // (OPT) STOP SHORTCODES THAT DON'T USE INLINE CONTENT FROM BEING WRAPPED IN A P TAG (until WP fixes this) // ** NOTE -> BE SURE TO change the array to the shortcodes you are using! add_filter('the_content', 'the_content_filter'); function the_content_filter($content) { // array of custom shortcodes requiring the fix $block = join("|",array( 'shortcode_name' )); // opening tag $rep = preg_replace("/(<p>)?\[($block)(\s[^\]]+)?\](<\/p>|<br \/>)?/","[$2$3]",$content); // closing tag $rep = preg_replace("/(<p>)?\[\/($block)](<\/p>|<br \/>)?/","[/$2]",$rep); return $rep; } ```
175,232
<p>I am just getting reaquainted with writing plugins, after writing a whole two about three years ago. Following some example code I found:</p> <pre><code>if(!class_exists('QuizMaster_Plugin_Template')) { class QuizMaster_Plugin_Template { public function __construct() { // register actions. } public static function activate() { // Do nothing } public static function deactivate() { // Do nothing } } } if(class_exists('QuizMaster_Plugin_Template')) { register_activation_hook(__FILE__, array('QuizMaster_Plugin_Template', 'activate')); register_deactivation_hook(__FILE__, array('QuizMaster_Plugin_Template', 'deactivate')); $ewp_quiz_master = new QuizMaster_Plugin_Template(); } </code></pre> <p>When I run this code in PhpStorm, I get the following error rendered to the client:</p> <blockquote> <p>Fatal error: Call to undefined function register_activation_hook() in C:\WordPress\Plugins\ewp-quiz-master\ewp-quiz-master.php on line 33</p> </blockquote> <p>I'm kind of guessing I have to set up some include files for PhpStorm, or even just for the plugin, just for the dev phase, but I have no idea where to start, and Google hasn't seemed very helpful on this.</p>
[ { "answer_id": 175234, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>WP plugins are meant to be loaded in context of WordPress core load. They won't work as vanilla PHP, unless you purposely abstract some parts completely away from WordPress.</p>\n\n<p>The typical practice is to have actual working WP installation locally and develop in its context.</p>\n" }, { "answer_id": 175640, "author": "pSyToR", "author_id": 66412, "author_profile": "https://wordpress.stackexchange.com/users/66412", "pm_score": -1, "selected": false, "text": "<p>-<em>EDIT</em>- Because some people need more \"information\"</p>\n\n<p>On this Thursday January 22nd 2015, you can find on the following 2 links how to setup PHPStorm to work with WordPress (I'm sorry if later on those links don't work anymore).</p>\n\n<p><a href=\"https://confluence.jetbrains.com/display/PhpStorm/WordPress+Development+using+PhpStorm\" rel=\"nofollow\">https://confluence.jetbrains.com/display/PhpStorm/WordPress+Development+using+PhpStorm</a></p>\n\n<p><a href=\"http://www.trotch.com/blog/wordpress-and-phpstorm-howto/\" rel=\"nofollow\">http://www.trotch.com/blog/wordpress-and-phpstorm-howto/</a></p>\n\n<p>2 different sites should be able to guide you on how to setup PHPStorm to use with WordPress.</p>\n\n<p>The Procedure is a bit complex and takes sometime to understand and apply properly, which makes it irrelevant that I paste everything here just to have \"a \"good\" answer\" I'm not here to make points, but to help the person currently having problems.</p>\n\n<p>All in all you have to setup the configurations inside your PHPStorm to point towards your WordPress local install (or even remote from what I quickly read), and also point to your plugin or theme you are developing and some other configurations.</p>\n\n<p>If those links does not work anymore, it's probably that the version of PHPStorm and probably WordPress too changed, which would make the information here obsolete anyway.</p>\n" } ]
2015/01/18
[ "https://wordpress.stackexchange.com/questions/175232", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7268/" ]
I am just getting reaquainted with writing plugins, after writing a whole two about three years ago. Following some example code I found: ``` if(!class_exists('QuizMaster_Plugin_Template')) { class QuizMaster_Plugin_Template { public function __construct() { // register actions. } public static function activate() { // Do nothing } public static function deactivate() { // Do nothing } } } if(class_exists('QuizMaster_Plugin_Template')) { register_activation_hook(__FILE__, array('QuizMaster_Plugin_Template', 'activate')); register_deactivation_hook(__FILE__, array('QuizMaster_Plugin_Template', 'deactivate')); $ewp_quiz_master = new QuizMaster_Plugin_Template(); } ``` When I run this code in PhpStorm, I get the following error rendered to the client: > > Fatal error: Call to undefined function register\_activation\_hook() in > C:\WordPress\Plugins\ewp-quiz-master\ewp-quiz-master.php on line 33 > > > I'm kind of guessing I have to set up some include files for PhpStorm, or even just for the plugin, just for the dev phase, but I have no idea where to start, and Google hasn't seemed very helpful on this.
WP plugins are meant to be loaded in context of WordPress core load. They won't work as vanilla PHP, unless you purposely abstract some parts completely away from WordPress. The typical practice is to have actual working WP installation locally and develop in its context.
175,260
<p>I want to change the language of my WordPress installation based on a choice the user can make in his profile (dropdown menu).</p> <p>As I want to change frontend (prepared .mo files for the theme) and backend language I thought I could change the <code>$locale</code> variable and it would work out.</p> <p>So I came up with the following code in my <code>functions.php</code> but that won´t do the job:</p> <pre>function change_lang() { get_currentuserinfo(); $lang = get_user_meta($current_user->ID, 'user_lang'); $locale = $lang[0]; return $locale; } add_filter('locale', 'change_lang');</pre> <p>When I return the value of <code>$locale</code>, WP returns a simple <code>NULL</code>, nothing more. When I release the hook, the defined value from <code>WP_LANG()</code> is returned.</p> <p>So, I am obviously wrong somewhere, but I can´t find where. Any hints?</p> <p>Besides: <a href="https://wordpress.stackexchange.com/questions/53326/change-admin-language-based-on-user-in-single-site">I read this for inspiration and code</a>, but I don´t want to have it as a plugin if possible.</p> <p>Thanks in advance!</p> <p><strong>Edit:</strong> Fixed my code, but still no language change happens.</p>
[ { "answer_id": 175275, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": true, "text": "<p>Your use of <code>$current_user</code> is a little wrong, you should include the <code>global $current_user</code> or assign it to a variable, or shorter and cleaner just <code>get_current_user_id()</code>:</p>\n\n<pre><code>add_filter('locale', 'change_lang');\nfunction change_lang( $locale ) {\n\n if( $lang = get_user_meta( get_current_user_id(), 'user_lang', true) ) {\n return $lang;\n }\n\n return $locale;\n\n}\n</code></pre>\n" }, { "answer_id": 260001, "author": "l2aelba", "author_id": 6332, "author_profile": "https://wordpress.stackexchange.com/users/6332", "pm_score": -1, "selected": false, "text": "<p>Did you mean this option ?</p>\n\n<p><a href=\"https://i.stack.imgur.com/TpYGU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TpYGU.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>If yes, then...</strong></p>\n\n<pre><code>$user_locale = get_user_locale();\nfunction change_userlang_by_userlocale($locale){\n global $user_locale;\n return $user_locale ? $user_locale : $locale;\n}\nadd_filter('locale','change_userlang_by_userlocale');\n</code></pre>\n" }, { "answer_id": 400345, "author": "marciofao", "author_id": 192140, "author_profile": "https://wordpress.stackexchange.com/users/192140", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem in my plugin and nothing in here worked.</p>\n<p>After days looking into it. I've realized that it is impossible to get the current user inside the filter 'locale'.\nNot even calling the global <code>$user_locale</code>.</p>\n<p>Apparently the hook 'locale' is triggered before init, or anythig else.</p>\n<p>After all i found out that I was loading my plugin text domain before setting the locale. So, calling it right after <code>switch_to_locale()</code> fixed the problem.</p>\n<p>This worked for me:</p>\n<pre><code>function set_user_locale(){\n\n switch_to_locale(get_user_locale());\n\n load_plugin_textdomain( 'plugin-texdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); \n\n}\nadd_filter('init', 'set_user_locale');\n</code></pre>\n" } ]
2015/01/19
[ "https://wordpress.stackexchange.com/questions/175260", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65455/" ]
I want to change the language of my WordPress installation based on a choice the user can make in his profile (dropdown menu). As I want to change frontend (prepared .mo files for the theme) and backend language I thought I could change the `$locale` variable and it would work out. So I came up with the following code in my `functions.php` but that won´t do the job: ``` function change_lang() { get_currentuserinfo(); $lang = get_user_meta($current_user->ID, 'user_lang'); $locale = $lang[0]; return $locale; } add_filter('locale', 'change_lang'); ``` When I return the value of `$locale`, WP returns a simple `NULL`, nothing more. When I release the hook, the defined value from `WP_LANG()` is returned. So, I am obviously wrong somewhere, but I can´t find where. Any hints? Besides: [I read this for inspiration and code](https://wordpress.stackexchange.com/questions/53326/change-admin-language-based-on-user-in-single-site), but I don´t want to have it as a plugin if possible. Thanks in advance! **Edit:** Fixed my code, but still no language change happens.
Your use of `$current_user` is a little wrong, you should include the `global $current_user` or assign it to a variable, or shorter and cleaner just `get_current_user_id()`: ``` add_filter('locale', 'change_lang'); function change_lang( $locale ) { if( $lang = get_user_meta( get_current_user_id(), 'user_lang', true) ) { return $lang; } return $locale; } ```
175,285
<p>I have a single page site with posts that get loaded via Ajax on the same page via slide down div. When a post is 'activated,' I want that state to be set so that when I visit the url directly, it goes to that specific post already showing in the div.</p> <p><strong>My question is:</strong></p> <p>Do I create the posts in single.php and call them minus the header and footer? Or do I create the template as part of the Ajax function? Keep in mind that my next task would be figuring out how to implement <code>history.js</code> so the states are set in the url, history stack, etc.</p> <p><strong>Here's my Ajax function:</strong></p> <pre><code>function my_load_ajax_content () { $args = array( 'p' =&gt; $_POST['post_id'], 'post_type' =&gt; 'projects' ); $post_query = new WP_Query( $args ); while( $post_query-&gt;have_posts() ) : $post_query-&gt;the_post(); ?&gt; &lt;div class="post-container"&gt; &lt;div id="project-left-content"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;?php the_content(); ?&gt; &lt;!-- If there is a URL --&gt; &lt;?php if( get_field('url') ): ?&gt; &lt;a href="http://&lt;?php the_field('url'); ?&gt;" target="_blank"&gt;&lt;?php the_field('url'); ?&gt;&lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div id="project-right-content"&gt; &lt;?php if( have_rows('slides') ): ?&gt; &lt;div id="slider"&gt; &lt;!-- Slider Setup --&gt; &lt;?php if( have_rows('slides') ): $slideNumber = 0; while ( have_rows('slides') ) : the_row(); $slideNumber++; ?&gt; &lt;input type="radio" name="slider" id="slide&lt;?php echo $slideNumber; ?&gt;"&gt; &lt;?php endwhile;endif; ?&gt; &lt;!-- Slide --&gt; &lt;?php if( have_rows('slides') ): ?&gt; &lt;div id="slides"&gt; &lt;div id="overflow"&gt; &lt;div class="inner"&gt; &lt;?php if( have_rows('slides') ): while ( have_rows('slides') ) : the_row(); $slideImage = get_sub_field('slide_image'); ?&gt; &lt;article&gt; &lt;img src="&lt;?php echo $slideImage; ?&gt;" alt="&lt;?php the_title(); ?&gt;"&gt; &lt;/article&gt; &lt;?php endwhile;endif; ?&gt; &lt;/div&gt;&lt;!-- #inner --&gt; &lt;/div&gt;&lt;!-- #overflow --&gt; &lt;/div&gt;&lt;!-- #slides --&gt; &lt;?php endif; ?&gt; &lt;!-- Controls --&gt; &lt;?php if( have_rows('slides') ): $slideNumber = 0; ?&gt; &lt;div id="active"&gt; &lt;?php while ( have_rows('slides') ) : the_row(); $slideNumber++; ?&gt; &lt;label for="slide&lt;?php echo $slideNumber; ?&gt;"&gt;&lt;/label&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt;&lt;!-- #active --&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!-- #slider --&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!-- #project-right-content --&gt; &lt;/div&gt;&lt;!-- .post-container --&gt; &lt;?php endwhile; wp_die(); } add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); </code></pre> <p><strong>Here's a simplified version of my Ajax call:</strong></p> <pre><code>$('.post-link').on('click', function(e) { e.preventDefault(); var post_id = $(this).data('id'), projectTitle = $(this).data('title'), ajaxURL = site.ajaxurl; $.ajax({ type: 'POST', url: ajaxURL, context: this, data: {'action': 'load-content', post_id: post_id }, success: function(response) { $('#project-container').html(response); // response return false; } }); }); </code></pre> <p><strong>Here's my HTML:</strong></p> <pre><code>&lt;div id="project-container"&gt;&lt;/div&gt; &lt;div id="projects-list"&gt; &lt;!-- Start the loop --&gt; &lt;?php $home_query = new WP_Query('post_type=projects'); while($home_query-&gt;have_posts()) : $home_query-&gt;the_post(); ?&gt; &lt;article class="project"&gt; &lt;?php the_post_thumbnail( 'home-thumb' ); ?&gt; &lt;div class="overlay"&gt; &lt;a class="post-link" href="&lt;?php the_permalink(); ?&gt;" data-id="&lt;?php the_ID(); ?&gt;" data-title="&lt;?php the_title(); ?&gt;"&gt;+&lt;/a&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_postdata(); // reset the query ?&gt; &lt;/div&gt;&lt;!-- #projects-list --&gt; </code></pre> <p>If anyone can show me the way, I'd really appreciate it. I can't seem to find much info on single page WordPress sites and HTML5 history.</p> <p><em>Edit: Updated the Ajax function to the full version (was previously simplified).</em></p>
[ { "answer_id": 175275, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": true, "text": "<p>Your use of <code>$current_user</code> is a little wrong, you should include the <code>global $current_user</code> or assign it to a variable, or shorter and cleaner just <code>get_current_user_id()</code>:</p>\n\n<pre><code>add_filter('locale', 'change_lang');\nfunction change_lang( $locale ) {\n\n if( $lang = get_user_meta( get_current_user_id(), 'user_lang', true) ) {\n return $lang;\n }\n\n return $locale;\n\n}\n</code></pre>\n" }, { "answer_id": 260001, "author": "l2aelba", "author_id": 6332, "author_profile": "https://wordpress.stackexchange.com/users/6332", "pm_score": -1, "selected": false, "text": "<p>Did you mean this option ?</p>\n\n<p><a href=\"https://i.stack.imgur.com/TpYGU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TpYGU.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>If yes, then...</strong></p>\n\n<pre><code>$user_locale = get_user_locale();\nfunction change_userlang_by_userlocale($locale){\n global $user_locale;\n return $user_locale ? $user_locale : $locale;\n}\nadd_filter('locale','change_userlang_by_userlocale');\n</code></pre>\n" }, { "answer_id": 400345, "author": "marciofao", "author_id": 192140, "author_profile": "https://wordpress.stackexchange.com/users/192140", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem in my plugin and nothing in here worked.</p>\n<p>After days looking into it. I've realized that it is impossible to get the current user inside the filter 'locale'.\nNot even calling the global <code>$user_locale</code>.</p>\n<p>Apparently the hook 'locale' is triggered before init, or anythig else.</p>\n<p>After all i found out that I was loading my plugin text domain before setting the locale. So, calling it right after <code>switch_to_locale()</code> fixed the problem.</p>\n<p>This worked for me:</p>\n<pre><code>function set_user_locale(){\n\n switch_to_locale(get_user_locale());\n\n load_plugin_textdomain( 'plugin-texdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); \n\n}\nadd_filter('init', 'set_user_locale');\n</code></pre>\n" } ]
2015/01/19
[ "https://wordpress.stackexchange.com/questions/175285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18320/" ]
I have a single page site with posts that get loaded via Ajax on the same page via slide down div. When a post is 'activated,' I want that state to be set so that when I visit the url directly, it goes to that specific post already showing in the div. **My question is:** Do I create the posts in single.php and call them minus the header and footer? Or do I create the template as part of the Ajax function? Keep in mind that my next task would be figuring out how to implement `history.js` so the states are set in the url, history stack, etc. **Here's my Ajax function:** ``` function my_load_ajax_content () { $args = array( 'p' => $_POST['post_id'], 'post_type' => 'projects' ); $post_query = new WP_Query( $args ); while( $post_query->have_posts() ) : $post_query->the_post(); ?> <div class="post-container"> <div id="project-left-content"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> <?php the_content(); ?> <!-- If there is a URL --> <?php if( get_field('url') ): ?> <a href="http://<?php the_field('url'); ?>" target="_blank"><?php the_field('url'); ?></a> <?php endif; ?> </div> <div id="project-right-content"> <?php if( have_rows('slides') ): ?> <div id="slider"> <!-- Slider Setup --> <?php if( have_rows('slides') ): $slideNumber = 0; while ( have_rows('slides') ) : the_row(); $slideNumber++; ?> <input type="radio" name="slider" id="slide<?php echo $slideNumber; ?>"> <?php endwhile;endif; ?> <!-- Slide --> <?php if( have_rows('slides') ): ?> <div id="slides"> <div id="overflow"> <div class="inner"> <?php if( have_rows('slides') ): while ( have_rows('slides') ) : the_row(); $slideImage = get_sub_field('slide_image'); ?> <article> <img src="<?php echo $slideImage; ?>" alt="<?php the_title(); ?>"> </article> <?php endwhile;endif; ?> </div><!-- #inner --> </div><!-- #overflow --> </div><!-- #slides --> <?php endif; ?> <!-- Controls --> <?php if( have_rows('slides') ): $slideNumber = 0; ?> <div id="active"> <?php while ( have_rows('slides') ) : the_row(); $slideNumber++; ?> <label for="slide<?php echo $slideNumber; ?>"></label> <?php endwhile; ?> </div><!-- #active --> <?php endif; ?> </div><!-- #slider --> <?php endif; ?> </div><!-- #project-right-content --> </div><!-- .post-container --> <?php endwhile; wp_die(); } add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); ``` **Here's a simplified version of my Ajax call:** ``` $('.post-link').on('click', function(e) { e.preventDefault(); var post_id = $(this).data('id'), projectTitle = $(this).data('title'), ajaxURL = site.ajaxurl; $.ajax({ type: 'POST', url: ajaxURL, context: this, data: {'action': 'load-content', post_id: post_id }, success: function(response) { $('#project-container').html(response); // response return false; } }); }); ``` **Here's my HTML:** ``` <div id="project-container"></div> <div id="projects-list"> <!-- Start the loop --> <?php $home_query = new WP_Query('post_type=projects'); while($home_query->have_posts()) : $home_query->the_post(); ?> <article class="project"> <?php the_post_thumbnail( 'home-thumb' ); ?> <div class="overlay"> <a class="post-link" href="<?php the_permalink(); ?>" data-id="<?php the_ID(); ?>" data-title="<?php the_title(); ?>">+</a> </div> </article> <?php endwhile; ?> <?php wp_reset_postdata(); // reset the query ?> </div><!-- #projects-list --> ``` If anyone can show me the way, I'd really appreciate it. I can't seem to find much info on single page WordPress sites and HTML5 history. *Edit: Updated the Ajax function to the full version (was previously simplified).*
Your use of `$current_user` is a little wrong, you should include the `global $current_user` or assign it to a variable, or shorter and cleaner just `get_current_user_id()`: ``` add_filter('locale', 'change_lang'); function change_lang( $locale ) { if( $lang = get_user_meta( get_current_user_id(), 'user_lang', true) ) { return $lang; } return $locale; } ```
175,307
<p>I am using jQuery tinyMCE to populate dynamically generated text areas with tiny MCE editors.</p> <p>When I use the WordPress <code>wp_editor</code> function before I call the jQuery version, I have no issues. If I do not, I get;</p> <blockquote> <p>Uncaught ReferenceError: tinymce is not defined</p> </blockquote> <p>As a dreadful hack, I have used;</p> <pre><code>wp_editor('hacky', 'hackhack'); wp_register_script('admin_js', get_template_directory_uri() . '/assets/js/admin.min.js', array()); wp_enqueue_script('admin_js'); </code></pre> <p>Which allows the jQuery TinyMCE to work. I wish to eliminate this. Thinking WP wasn't loading the jQuery version (and not knowing a good way to get the path of <code>WP-includes</code>) I used;</p> <pre><code>?&gt;&lt;script type="text/javascript"src="//cdnjs.cloudflare.com/ajax/libs/tinymce/4.1.7/jquery.tinymce.min.js"&gt;&lt;/script&gt;&lt;?php wp_register_script('admin_js', get_template_directory_uri() . '/assets/js/admin.min.js', array()); wp_enqueue_script('admin_js'); </code></pre> <p>But this doesn't seem to be the issue. It seems that the WP version loads the required files I need - except I do not know what files I need.</p>
[ { "answer_id": 176222, "author": "myol", "author_id": 51823, "author_profile": "https://wordpress.stackexchange.com/users/51823", "pm_score": 4, "selected": true, "text": "<p>With help from a colleague, we dug through <code>class-wp-editor.php</code></p>\n\n<p>Here are the necessary scripts to initialise jQuery tinyMCE if <code>wp_editor</code> has not been used beforehand (which calls these scripts). </p>\n\n<pre><code>// Get the necessary scripts to launch tinymce\n$baseurl = includes_url( 'js/tinymce' );\n$cssurl = includes_url('css/');\n\nglobal $tinymce_version, $concatenate_scripts, $compress_scripts;\n\n$version = 'ver=' . $tinymce_version;\n$css = $cssurl . 'editor.css';\n\n$compressed = $compress_scripts &amp;&amp; $concatenate_scripts &amp;&amp; isset($_SERVER['HTTP_ACCEPT_ENCODING'])\n &amp;&amp; false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');\n\nif ( $compressed ) {\n echo \"&lt;script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;amp;$version'&gt;&lt;/script&gt;\\n\";\n} else {\n echo \"&lt;script type='text/javascript' src='{$baseurl}/tinymce.min.js?$version'&gt;&lt;/script&gt;\\n\";\n echo \"&lt;script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin.min.js?$version'&gt;&lt;/script&gt;\\n\";\n}\n\nadd_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50 );\nadd_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'enqueue_scripts' ), 1 );\n\nwp_register_style('tinymce_css', $css);\nwp_enqueue_style('tinymce_css');\n</code></pre>\n\n<p>This will create a dynamic tinyMCE editor without the tabs to switch between visual / text, nor the media upload functionality. I had to create these buttons manually as well as the respective jQuery for each.</p>\n\n<p>Edited in the required css the editor uses as well.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>More elegant solution but with less fallback (no versioning)</p>\n\n<pre><code>$js_src = includes_url('js/tinymce/') . 'tinymce.min.js';\n$css_src = includes_url('css/') . 'editor.css';\n\n// wp_enqueue doesn't seem to work at all\necho '&lt;script src=\"' . $js_src . '\" type=\"text/javascript\"&gt;&lt;/script&gt;';\n\nwp_register_style('tinymce_css', $css_src);\nwp_enqueue_style('tinymce_css');\n</code></pre>\n" }, { "answer_id": 178667, "author": "dave", "author_id": 67805, "author_profile": "https://wordpress.stackexchange.com/users/67805", "pm_score": 1, "selected": false, "text": "<p>For what it's worth - I recently ran into this problem with the editor disappearing with wp 4.1 after a site migration. The issue happened to be that \"accessibility mode\" (The link under screen options in the widget editor) was turned on.</p>\n" }, { "answer_id": 315828, "author": "Luke Chinworth", "author_id": 82308, "author_profile": "https://wordpress.stackexchange.com/users/82308", "pm_score": 0, "selected": false, "text": "<p>My problem was wordpress was not including the tinymce script tag because \n<code>user_can_richedit()</code> was returning false (I did not investigate why. My user is an admin, and it was previously working on a different install, so maybe some setting controls it?). In any case, you can filter the return value of <code>user_can_richedit()</code> to get wordpress to include the tinymce scripts and then tinymce will be defined.</p>\n\n<pre><code>add_filter('user_can_richedit', '__return_true');\n</code></pre>\n" }, { "answer_id": 346094, "author": "dMe", "author_id": 174241, "author_profile": "https://wordpress.stackexchange.com/users/174241", "pm_score": 0, "selected": false, "text": "<p>I had an error after I called wp_editor() saying:</p>\n\n<pre><code>j is undefined\n</code></pre>\n\n<p>It turned out that the option name I was using had a dot in the name (my_plugin_name_customer.subscription.updated) and it was breaking the editor. I replaced the dot with underscore and it fixed my problem.</p>\n" }, { "answer_id": 395575, "author": "DanielV", "author_id": 27863, "author_profile": "https://wordpress.stackexchange.com/users/27863", "pm_score": 0, "selected": false, "text": "<p>Anyone that has created their admin user from PhpMyAdmin, and comes across this issue - it may be because you have not copied the user_meta row for rich text editing. Simply check, and uncheck the &quot;Disable the visual editor when writing&quot; option in your user profile to test if this will fix your issue.</p>\n" } ]
2015/01/19
[ "https://wordpress.stackexchange.com/questions/175307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51823/" ]
I am using jQuery tinyMCE to populate dynamically generated text areas with tiny MCE editors. When I use the WordPress `wp_editor` function before I call the jQuery version, I have no issues. If I do not, I get; > > Uncaught ReferenceError: tinymce is not defined > > > As a dreadful hack, I have used; ``` wp_editor('hacky', 'hackhack'); wp_register_script('admin_js', get_template_directory_uri() . '/assets/js/admin.min.js', array()); wp_enqueue_script('admin_js'); ``` Which allows the jQuery TinyMCE to work. I wish to eliminate this. Thinking WP wasn't loading the jQuery version (and not knowing a good way to get the path of `WP-includes`) I used; ``` ?><script type="text/javascript"src="//cdnjs.cloudflare.com/ajax/libs/tinymce/4.1.7/jquery.tinymce.min.js"></script><?php wp_register_script('admin_js', get_template_directory_uri() . '/assets/js/admin.min.js', array()); wp_enqueue_script('admin_js'); ``` But this doesn't seem to be the issue. It seems that the WP version loads the required files I need - except I do not know what files I need.
With help from a colleague, we dug through `class-wp-editor.php` Here are the necessary scripts to initialise jQuery tinyMCE if `wp_editor` has not been used beforehand (which calls these scripts). ``` // Get the necessary scripts to launch tinymce $baseurl = includes_url( 'js/tinymce' ); $cssurl = includes_url('css/'); global $tinymce_version, $concatenate_scripts, $compress_scripts; $version = 'ver=' . $tinymce_version; $css = $cssurl . 'editor.css'; $compressed = $compress_scripts && $concatenate_scripts && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'); if ( $compressed ) { echo "<script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;$version'></script>\n"; } else { echo "<script type='text/javascript' src='{$baseurl}/tinymce.min.js?$version'></script>\n"; echo "<script type='text/javascript' src='{$baseurl}/plugins/compat3x/plugin.min.js?$version'></script>\n"; } add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50 ); add_action( 'wp_print_footer_scripts', array( '_WP_Editors', 'enqueue_scripts' ), 1 ); wp_register_style('tinymce_css', $css); wp_enqueue_style('tinymce_css'); ``` This will create a dynamic tinyMCE editor without the tabs to switch between visual / text, nor the media upload functionality. I had to create these buttons manually as well as the respective jQuery for each. Edited in the required css the editor uses as well. **EDIT:** More elegant solution but with less fallback (no versioning) ``` $js_src = includes_url('js/tinymce/') . 'tinymce.min.js'; $css_src = includes_url('css/') . 'editor.css'; // wp_enqueue doesn't seem to work at all echo '<script src="' . $js_src . '" type="text/javascript"></script>'; wp_register_style('tinymce_css', $css_src); wp_enqueue_style('tinymce_css'); ```
175,333
<p>I have 1458 post in category name news that id is 5.</p> <p>And i wont to copy all of this post and transfer it to custom post type name news.</p> <p>How can do that ??</p>
[ { "answer_id": 175334, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 0, "selected": false, "text": "<p>I would suggest an export/import procedure using a tool such as WP CSV. <a href=\"https://wordpress.org/plugins/wp-csv/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-csv/</a></p>\n\n<p>We use this plugin quite a bit for importing non-WP data and it's very reliable. </p>\n\n<ol>\n<li>Register your CPT (via your plugin or theme functions)</li>\n<li>Create at least one post in your CPT</li>\n<li>Export with WP CSV to use as an import template</li>\n<li>Export your 1458 category posts</li>\n<li>Copy / paste these into the correct columns in your CSV file for import</li>\n<li>Import the file as your new CPT posts</li>\n<li>Confirm all is well and accurately imported</li>\n<li>Delete the 1458 now duplicated posts from their original category home</li>\n</ol>\n\n<p>I would test this entire operation on a copy of your live site. Do this to a dev site - NOT a live production site.</p>\n" }, { "answer_id": 175398, "author": "Nathan Fitzgerald - Fitzgenius", "author_id": 7025, "author_profile": "https://wordpress.stackexchange.com/users/7025", "pm_score": 1, "selected": false, "text": "<p>Create your custom post type and then try this. (BACKUP FIRST AS THIS IS UNTESTED).</p>\n\n<pre><code>&lt;?php\n\n// Get all posts in category \"5\"\n$news_posts = get_posts(\n array(\n 'category' =&gt; 5\n )\n);\n\n// Loop through them\nforeach($news_posts as $p):\n\n // Update the post type\n wp_update_post(\n array(\n 'ID' =&gt; $p-&gt;ID,\n 'post_type' =&gt; 'news'\n );\n );\n\n // Delete term relationships for the post\n wp_delete_object_term_relationships( $p-&gt;ID, 'post_tag' );\n wp_delete_object_term_relationships( $p-&gt;ID, 'category' ); \n\nendforeach;\n\n?&gt;\n</code></pre>\n" } ]
2015/01/19
[ "https://wordpress.stackexchange.com/questions/175333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66189/" ]
I have 1458 post in category name news that id is 5. And i wont to copy all of this post and transfer it to custom post type name news. How can do that ??
Create your custom post type and then try this. (BACKUP FIRST AS THIS IS UNTESTED). ``` <?php // Get all posts in category "5" $news_posts = get_posts( array( 'category' => 5 ) ); // Loop through them foreach($news_posts as $p): // Update the post type wp_update_post( array( 'ID' => $p->ID, 'post_type' => 'news' ); ); // Delete term relationships for the post wp_delete_object_term_relationships( $p->ID, 'post_tag' ); wp_delete_object_term_relationships( $p->ID, 'category' ); endforeach; ?> ```
175,346
<p>I finally managed to <strong>update an old WP 3.3.1 site to WP 4.1</strong> with few issues, but one unexpected change seems to have come about with relation to file uploads.</p> <p>In the WP 3.3.1 version of the plugin, I enabled uploads for a custom Role via 'read' and 'upload_files'.</p> <p>NOTE: This is for content that is <strong>NOT</strong> post driven. It's just the editor I want to grab things for some <strong>custom db tables</strong>. The <strong>wp_editor</strong> call has content explicitly set to ''. I'm using a buffering hack to reposition the editor, which is detailed at: <a href="https://wordpress.stackexchange.com/a/66345">https://wordpress.stackexchange.com/a/66345</a></p> <pre><code>// capture the editor for later use... // HACK: https://wordpress.stackexchange.com/a/66345 ob_start(); wp_editor( '', 'xyz-note-editor', array( 'textarea_rows' =&gt; '10', ) ); $editor = ob_get_clean(); // ... $edit_form_template = str_replace('{{NotesEditor}}', $editor, $edit_form_template); </code></pre> <p>After the update to WP 4.1, everything <strong>works for Editors and Administrators</strong>.</p> <p><strong>It fails for Authors, Contributors and my custom role</strong> with the error: "You don't have permission to attach files to this post."</p> <p>(The "post" appears to be an unrelated custom post type instance, which the uploaded media gets assigned to, when successfully uploading as an Editor or Administrator.)</p> <p>Short of rebuilding things, or hunting down some plugin (like Members by Justin Tadlock, recommended elsewhere on StackExchange), I'm stuck.</p> <p><strong>Why can Editors circumvent upload restrictions in this case?</strong></p> <p>I've tried assigning edit/publish/read permissons for Editors (and below) to the custom Role with no success - based on <a href="http://codex.wordpress.org/Roles_and_Capabilities" rel="nofollow noreferrer">http://codex.wordpress.org/Roles_and_Capabilities</a>.</p> <pre><code>add_role( XxYyConfig::USER_ROLE(), 'Custom Data Manager', array( 'read' =&gt; true, // ADDED: to address changes in how WordPress "Add Media" works - re: "You don't have permission to attach files to this post." error // NOTE: Custom Data Managers, Contributors and Authors CANNOT add media -- BUT Editors/Administrators can. Trying to add to {custom_post_type} post (for reasons unknown). Content for editor set to ''... 'edit_files' =&gt; true, 'edit_others_pages' =&gt; true, 'edit_others_posts' =&gt; true, 'edit_pages' =&gt; true, 'edit_posts' =&gt; true, 'edit_private_pages' =&gt; true, 'edit_private_posts' =&gt; true, 'edit_published_pages' =&gt; true, 'edit_published_posts' =&gt; true, 'publish_pages' =&gt; true, 'publish_posts' =&gt; true, 'read_private_pages' =&gt; true, 'read_private_posts' =&gt; true, // ADDED: END 'upload_files' =&gt; true, ) ); </code></pre> <p>I know I'm out in left field a bit here, but this feels inconsistent (even if something from ages long since gone has been "fixed").</p> <p><strong>map_meta_cap</strong> looks like it might apply here, but no custom post type makes me think that's the wrong solution.</p> <p>Ideally, I'd like to know why the custom post type gets tagged during this whole thing, but I'm sticking to what permissions/capability handling needs to be set up to allow uploading through the WYSIWYG editor?</p> <p>EDIT: Since my role is set up during plugin activation, I've been sure to deactivate and reactivate the plugin to ensure nothing unusual is happening there.</p>
[ { "answer_id": 231207, "author": "user97667", "author_id": 97667, "author_profile": "https://wordpress.stackexchange.com/users/97667", "pm_score": 2, "selected": false, "text": "<p>Found the basic problem! Although a different context than the one you described, the root cause is probably the same.\nI was trying to allow users to setup a personal page and upload an image to display there. I kept getting the dreaded \"You don't have permission to attach files to this post\".</p>\n\n<p>The message itself comes from wp_ajax_upload_attachment() in /wp-admin/includes/ajax-actions.php, even though the user is working on the front-page, not the dashboard, because the plugin I'm using (Advanced Custom Fields -- recommended!) makes use of wordpress library routines (thankfully it restricts access to library). The error occurs if <strong>current_user_can()</strong> fails to give permission.\n(You can prove the message is in this routine by changing the message statement to something else.)</p>\n\n<p>In turn, current_user_can() calls <strong>$current_user->has_cap()</strong> to get current capabilities. </p>\n\n<p>has_cap() offers a nice filter that we can make use of, but it kept failing anyway. The reason was that it first calls <strong>map_meta_cap()</strong> which builds a large array of possible capabilities for this instance. If any one of those possible capabilities is left 'empty' then has_cap returns false. </p>\n\n<p>That means any custom filter that is determined to give permission must loop through the array and set everything true.\nSeems to me that a better permanent solution would be for Wordpress to ignore any cap that is not explicitly set to allow or disallow.</p>\n\n<p>For now, here's a sample filter function that works for me:</p>\n\n<pre><code>// allow users to add images to their home page\nfunction allow_own_attachments( $user_caps, $req_caps, $args, $UserObj ) {\n if ( empty($args[2]) ) {\n return $user_caps; // nothing to check\n }\n $post = get_post( $args[2] ); // post_id was passed here\n if ( $post-&gt;post_author == $UserObj-&gt;ID ) { // this is my post\n foreach ( (array) $req_caps as $cap ) {\n if ( empty( $user_caps[ $cap ] ) )\n $user_caps[ $cap ] = true;\n }\n }\n $user_caps['edit_post'] = true; // tested by wp_ajax_upload_attachment()\n return $user_caps;\n}\nadd_filter( 'user_has_cap', 'allow_own_attachments', 10, 4 );\n</code></pre>\n" }, { "answer_id": 343928, "author": "manu", "author_id": 171686, "author_profile": "https://wordpress.stackexchange.com/users/171686", "pm_score": 0, "selected": false, "text": "<p>The code in the previous answer worked for me, but I was getting this notice when in debug mode: \"Trying to get property 'post_author' of non-object\". I added a check to see if $post returns an object (if (is_object($post)). This gets rid of the notice.</p>\n\n<pre><code>function allow_own_attachments( $user_caps, $req_caps, $args, $UserObj ) {\nif ( empty($args[2]) ) {\n return $user_caps; // nothing to check\n}\n$post = get_post( $args[2] ); // post_id was passed here\n\nif (is_object($post)){ //check if $post is an object. If it is't checked the code throws this Notice: Trying to get property 'post_author' of non-object \n if ( $post-&gt;post_author == $UserObj-&gt;ID ) { // this is my post\n foreach ( (array) $req_caps as $cap ) {\n if ( empty( $user_caps[ $cap ] ) )\n $user_caps[ $cap ] = true;\n }\n }\n}\n$user_caps['edit_post'] = true; // tested by wp_ajax_upload_attachment()\nreturn $user_caps;\n}\n\nadd_filter( 'user_has_cap', 'allow_own_attachments', 10, 4 );\n</code></pre>\n" } ]
2015/01/19
[ "https://wordpress.stackexchange.com/questions/175346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60733/" ]
I finally managed to **update an old WP 3.3.1 site to WP 4.1** with few issues, but one unexpected change seems to have come about with relation to file uploads. In the WP 3.3.1 version of the plugin, I enabled uploads for a custom Role via 'read' and 'upload\_files'. NOTE: This is for content that is **NOT** post driven. It's just the editor I want to grab things for some **custom db tables**. The **wp\_editor** call has content explicitly set to ''. I'm using a buffering hack to reposition the editor, which is detailed at: <https://wordpress.stackexchange.com/a/66345> ``` // capture the editor for later use... // HACK: https://wordpress.stackexchange.com/a/66345 ob_start(); wp_editor( '', 'xyz-note-editor', array( 'textarea_rows' => '10', ) ); $editor = ob_get_clean(); // ... $edit_form_template = str_replace('{{NotesEditor}}', $editor, $edit_form_template); ``` After the update to WP 4.1, everything **works for Editors and Administrators**. **It fails for Authors, Contributors and my custom role** with the error: "You don't have permission to attach files to this post." (The "post" appears to be an unrelated custom post type instance, which the uploaded media gets assigned to, when successfully uploading as an Editor or Administrator.) Short of rebuilding things, or hunting down some plugin (like Members by Justin Tadlock, recommended elsewhere on StackExchange), I'm stuck. **Why can Editors circumvent upload restrictions in this case?** I've tried assigning edit/publish/read permissons for Editors (and below) to the custom Role with no success - based on <http://codex.wordpress.org/Roles_and_Capabilities>. ``` add_role( XxYyConfig::USER_ROLE(), 'Custom Data Manager', array( 'read' => true, // ADDED: to address changes in how WordPress "Add Media" works - re: "You don't have permission to attach files to this post." error // NOTE: Custom Data Managers, Contributors and Authors CANNOT add media -- BUT Editors/Administrators can. Trying to add to {custom_post_type} post (for reasons unknown). Content for editor set to ''... 'edit_files' => true, 'edit_others_pages' => true, 'edit_others_posts' => true, 'edit_pages' => true, 'edit_posts' => true, 'edit_private_pages' => true, 'edit_private_posts' => true, 'edit_published_pages' => true, 'edit_published_posts' => true, 'publish_pages' => true, 'publish_posts' => true, 'read_private_pages' => true, 'read_private_posts' => true, // ADDED: END 'upload_files' => true, ) ); ``` I know I'm out in left field a bit here, but this feels inconsistent (even if something from ages long since gone has been "fixed"). **map\_meta\_cap** looks like it might apply here, but no custom post type makes me think that's the wrong solution. Ideally, I'd like to know why the custom post type gets tagged during this whole thing, but I'm sticking to what permissions/capability handling needs to be set up to allow uploading through the WYSIWYG editor? EDIT: Since my role is set up during plugin activation, I've been sure to deactivate and reactivate the plugin to ensure nothing unusual is happening there.
Found the basic problem! Although a different context than the one you described, the root cause is probably the same. I was trying to allow users to setup a personal page and upload an image to display there. I kept getting the dreaded "You don't have permission to attach files to this post". The message itself comes from wp\_ajax\_upload\_attachment() in /wp-admin/includes/ajax-actions.php, even though the user is working on the front-page, not the dashboard, because the plugin I'm using (Advanced Custom Fields -- recommended!) makes use of wordpress library routines (thankfully it restricts access to library). The error occurs if **current\_user\_can()** fails to give permission. (You can prove the message is in this routine by changing the message statement to something else.) In turn, current\_user\_can() calls **$current\_user->has\_cap()** to get current capabilities. has\_cap() offers a nice filter that we can make use of, but it kept failing anyway. The reason was that it first calls **map\_meta\_cap()** which builds a large array of possible capabilities for this instance. If any one of those possible capabilities is left 'empty' then has\_cap returns false. That means any custom filter that is determined to give permission must loop through the array and set everything true. Seems to me that a better permanent solution would be for Wordpress to ignore any cap that is not explicitly set to allow or disallow. For now, here's a sample filter function that works for me: ``` // allow users to add images to their home page function allow_own_attachments( $user_caps, $req_caps, $args, $UserObj ) { if ( empty($args[2]) ) { return $user_caps; // nothing to check } $post = get_post( $args[2] ); // post_id was passed here if ( $post->post_author == $UserObj->ID ) { // this is my post foreach ( (array) $req_caps as $cap ) { if ( empty( $user_caps[ $cap ] ) ) $user_caps[ $cap ] = true; } } $user_caps['edit_post'] = true; // tested by wp_ajax_upload_attachment() return $user_caps; } add_filter( 'user_has_cap', 'allow_own_attachments', 10, 4 ); ```
175,393
<p>We have a custom post type <code>testimonial</code> and want to show the 1st, 2nd and 3rd in various bespoke locations on the page.</p> <p>Here's how we would do it if we just wanted to loop over testimonials and show them one after another (this works):</p> <pre><code>&lt;?php $args = array('post_type' =&gt; 'testimonial'); $testimonials = new WP_Query( $args ); while( $testimonials-&gt;have_posts() ) { $testimonials-&gt;the_post(); ?&gt; &lt;li&gt; &lt;?php echo get_the_content(); ?&gt; &lt;/li&gt; &lt;?php }?&gt; </code></pre> <p>But to show only the first or only the third or the Nth? Here's what we've got so far (to obtain the first), it's obviously wrong:</p> <pre><code>$args = array('post_type' =&gt; 'testimonial'); $testimonials = new WP_Query( $args ); $testimonial1 =$testimonials[0]-&gt;the_post; echo $testimonial1-&gt;the_content; </code></pre> <p>We get an error saying: </p> <blockquote> <p>Fatal error: Cannot use object of type WP_Query as array</p> </blockquote>
[ { "answer_id": 175399, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>Make use of an offset to skip the first 2 posts if you need the third post only, and then set you <code>posts_per_page</code> to <code>1</code> to get only that specific post</p>\n\n<p>You can try something like this in your arguments</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'testimonial',\n 'offset' =&gt; 2,\n 'posts_per_page' =&gt; 1\n);\n$testimonials = new WP_Query( $args );\n while( $testimonials-&gt;have_posts() ) {\n $testimonials-&gt;the_post();\n?&gt;\n &lt;li&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/li&gt;\n\n&lt;?php }\nwp_reset_postdata(); ?&gt;\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Before I start, a few notes on your code and my edited code. (<em>I have edited my original code to show a normal loop</em>). </p>\n\n<ul>\n<li><p>You don't need to use <code>echo get_the_content()</code>. You can just use <code>the_content()</code> directly</p></li>\n<li><p>Remember to reset your postdata after the loop with <code>wp_reset_postdata()</code>. </p></li>\n</ul>\n\n<p>As requested in comments, here is the alternative syntax where you don't use the loop. Also, a note or two first: </p>\n\n<ul>\n<li>With this alternative syntax, you cannot use the template tags as they will not be available</li>\n</ul>\n\n<p>You need to work with the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"noreferrer\"><code>WP_Post</code></a> objects directly and use filters as described in the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Post#Accessing_the_WP_Post_Object\" rel=\"noreferrer\">link</a></p>\n\n<ul>\n<li>You don't need to reset postdata as you are not altering the globals </li>\n</ul>\n\n<p>You can try </p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'testimonial',\n 'offset' =&gt; 2,\n 'posts_per_page' =&gt; 1\n);\n$testimonials = new WP_Query( $args );\n\n//Displays the title\necho apply_filters( 'the_title', $testimonials-&gt;posts[0]-&gt;post_title );\n\n//Displays the content\necho apply_filters( 'the_content', $testimonials-&gt;posts[0]-&gt;post_content );\n</code></pre>\n" }, { "answer_id": 175402, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You could use the <code>current_post</code> property and the <code>rewind_posts()</code> method of the <code>WP_Query</code> class, to target the relevant post objects.</p>\n\n<p>You could try playing with the following example (untested):</p>\n\n<pre><code>if( $testimonials-&gt;post_count &gt;= 3 )\n{\n // First post:\n $nr = 1;\n if( isset( $testimonials-&gt;posts[$nr-1] ) )\n {\n $testimonials-&gt;rewind_posts();\n $testimonials-&gt;current_post = $nr - 2;\n $testimonials-&gt;the_post();\n the_title();\n }\n\n // Third post:\n $nr = 3;\n if( isset( $testimonials-&gt;posts[$nr-1] ) )\n {\n $testimonials-&gt;rewind_posts();\n $testimonials-&gt;current_post = $nr - 2;\n $testimonials-&gt;the_post();\n the_title();\n }\n\n // Second post:\n $nr = 2;\n if( isset( $testimonials-&gt;posts[$nr-1] ) )\n {\n $testimonials-&gt;rewind_posts();\n $testimonials-&gt;current_post = $nr - 2;\n $testimonials-&gt;the_post();\n the_title();\n } \n\n wp_reset_postdata();\n} \n</code></pre>\n\n<p>You could also use it like this, with your current <code>while</code> loops:</p>\n\n<pre><code>$testimonials = new WP_Query( $args );\n\n// First post:\n$nr = 1; \nwhile( $testimonials-&gt;have_posts() &amp;&amp; ( $nr - 2 ) === $testimonials-&gt;current_post ) {\n $testimonials-&gt;the_post();\n // ...\n}\n\n// Third post:\n$nr = 3;\n$testimonials-&gt;rewind_posts();\nwhile( $testimonials-&gt;have_posts() &amp;&amp; ( $nr - 2 ) === $testimonials-&gt;current_post ) {\n $testimonials-&gt;the_post();\n // ...\n}\n\n// Second post:\n$nr = 2;\n$testimonials-&gt;rewind_posts();\nwhile( $testimonials-&gt;have_posts() &amp;&amp; ( $nr - 2 ) === $testimonials-&gt;current_post ) {\n $testimonials-&gt;the_post();\n // ...\n}\n\nwp_reset_postdata(); \n</code></pre>\n" } ]
2015/01/20
[ "https://wordpress.stackexchange.com/questions/175393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/875/" ]
We have a custom post type `testimonial` and want to show the 1st, 2nd and 3rd in various bespoke locations on the page. Here's how we would do it if we just wanted to loop over testimonials and show them one after another (this works): ``` <?php $args = array('post_type' => 'testimonial'); $testimonials = new WP_Query( $args ); while( $testimonials->have_posts() ) { $testimonials->the_post(); ?> <li> <?php echo get_the_content(); ?> </li> <?php }?> ``` But to show only the first or only the third or the Nth? Here's what we've got so far (to obtain the first), it's obviously wrong: ``` $args = array('post_type' => 'testimonial'); $testimonials = new WP_Query( $args ); $testimonial1 =$testimonials[0]->the_post; echo $testimonial1->the_content; ``` We get an error saying: > > Fatal error: Cannot use object of type WP\_Query as array > > >
Make use of an offset to skip the first 2 posts if you need the third post only, and then set you `posts_per_page` to `1` to get only that specific post You can try something like this in your arguments ``` $args = array( 'post_type' => 'testimonial', 'offset' => 2, 'posts_per_page' => 1 ); $testimonials = new WP_Query( $args ); while( $testimonials->have_posts() ) { $testimonials->the_post(); ?> <li> <?php the_content(); ?> </li> <?php } wp_reset_postdata(); ?> ``` EDIT ---- Before I start, a few notes on your code and my edited code. (*I have edited my original code to show a normal loop*). * You don't need to use `echo get_the_content()`. You can just use `the_content()` directly * Remember to reset your postdata after the loop with `wp_reset_postdata()`. As requested in comments, here is the alternative syntax where you don't use the loop. Also, a note or two first: * With this alternative syntax, you cannot use the template tags as they will not be available You need to work with the [`WP_Post`](http://codex.wordpress.org/Class_Reference/WP_Post) objects directly and use filters as described in the [link](http://codex.wordpress.org/Class_Reference/WP_Post#Accessing_the_WP_Post_Object) * You don't need to reset postdata as you are not altering the globals You can try ``` $args = array( 'post_type' => 'testimonial', 'offset' => 2, 'posts_per_page' => 1 ); $testimonials = new WP_Query( $args ); //Displays the title echo apply_filters( 'the_title', $testimonials->posts[0]->post_title ); //Displays the content echo apply_filters( 'the_content', $testimonials->posts[0]->post_content ); ```
175,418
<p>I have a page that is calling in the content from other posts (a custom post type, specifically) and inserting it into the page. It all works great, but I'm losing the functionality of WordPress taking youtube (and other embeddable links) and automatically inserting the embedded video.</p> <p>I've tried <code>apply_filters( 'the_content', $my_content );</code>, but I think that filter isn't even available via <code>admin-ajax.php</code>.</p> <p>I of course already call <code>do_shortcode( $my_content )</code>, but what can I use, in similar fashion, to get the embeddable links to embed?</p> <p>UPDATE:</p> <p>In response to bonger's answer, I've updated the code to this:</p> <p><code>wpautop( do_shortcode( $wp_embed-&gt;run_shortcode( $my_content ) ) )</code></p> <p>($wp_embed was globalized before this line of code)</p> <p>Note that the <code>wpautop()</code> and <code>do_shortcode()</code> are totally irrelevant to this issue, but I put them in here just for completeness. This code is outputting the youtube url as a link to the youtube video, but not embedding the video in the page.</p>
[ { "answer_id": 175421, "author": "Maks", "author_id": 66236, "author_profile": "https://wordpress.stackexchange.com/users/66236", "pm_score": 0, "selected": false, "text": "<p>try to use <code>get_the_content()</code>, like:</p>\n\n<pre><code>$my_content = get_the_content();\n$my_content = apply_filters('the_content', $my_content);\n</code></pre>\n" }, { "answer_id": 175427, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 1, "selected": false, "text": "<p>I think there's some weirdness with <code>[embed]</code> shortcodes where you have to run them through <code>WP_Embed::run_shortcode()</code>, eg</p>\n\n<pre><code> if ( strpos( $my_content, '[embed]' ) !== false ) {\n global $wp_embed;\n $my_content = $wp_embed-&gt;run_shortcode( $my_content );\n }\n $my_content = do_shortcode( $my_content );\n</code></pre>\n\n<p><strong>Update</strong>: however as no providers are registered this won't work as you noticed(!), so I think the easiest thing to do is to call <code>wp_oembed_get()</code> direct:</p>\n\n<pre><code> $args = array();\n global $content_width;\n $args['width'] = $content_width ? $content_width : 300;\n // Simplistic parse - look for a url on its own line.\n $lines = explode( \"\\n\", $my_content );\n foreach ( $lines as $i =&gt; $line ) {\n $line = trim( $line );\n if ( stripos( $line, 'http' ) === 0 ) {\n if ( $oembed_html = wp_oembed_get( $line, $args ) ) {\n $lines[$i] = $oembed_html;\n }\n }\n }\n $my_content = implode( \"\\n\", $lines );\n</code></pre>\n\n<p>You may want to use transients to avoid repeated calls to the provider - here's a version of stuff I use:</p>\n\n<pre><code>// Wrapper around wp_oembed_get() to use transients.\nfunction wpse175427_oembed_get( $url, $args ) {\n global $wpse175427_oembed_transient_expiration;\n if ( $wpse175427_oembed_transient_expiration ) {\n $transient_key = md5( $url . '_' . wpse175427_reduce_array( $args ) );\n if ( $oembed_html = get_transient( $transient_key ) ) {\n return $oembed_html;\n }\n }\n\n //add_filter( 'oembed_fetch_url', 'wpse175427_oembed_fetch_url', 10, 3 );\n //add_filter( 'oembed_result', 'wpse175427_oembed_result', 10, 3 );\n if ( $oembed_html = wp_oembed_get( $url, $args ) ) {\n if ( $wpse175427_oembed_transient_expiration ) {\n set_transient( $transient_key, $oembed_html, $wpse175427_oembed_transient_expiration );\n }\n return $oembed_html;\n }\n return '';\n}\n\n// Helper to stringify args array (for transient key).\nfunction wpse175427_reduce_array( $arr ) {\n $ret = array();\n foreach ( $arr as $key =&gt; $val ) {\n $ret[] = '`' . $key . '`=`' . $val . '`';\n }\n return implode( ',', $ret );\n}\n</code></pre>\n\n<p>Then set the global in your ajax callback, eg</p>\n\n<pre><code> global $wpse175427_oembed_transient_expiration;\n $wpse175427_oembed_transient_expiration = DAY_IN_SECONDS;\n</code></pre>\n\n<p>and call <code>wpse175427_oembed_get()</code> instead of <code>wp_oembed_get()</code>.</p>\n" }, { "answer_id": 175864, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I think the solution is amazingly simple here:</p>\n\n<p>You're just missing a single line of code in your <em>ajax</em> callback, namely:</p>\n\n<pre><code>global $post;\n</code></pre>\n\n<p>where I assume you're using:</p>\n\n<pre><code>$post = get_post( $post_id );\n</code></pre>\n\n<p>The reason is that there's a global post check in the <code>WP_Embed::shortcode()</code> method.</p>\n\n<p>More details in my answer <a href=\"https://wordpress.stackexchange.com/a/142597/26350\">here</a>.</p>\n" } ]
2015/01/20
[ "https://wordpress.stackexchange.com/questions/175418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45132/" ]
I have a page that is calling in the content from other posts (a custom post type, specifically) and inserting it into the page. It all works great, but I'm losing the functionality of WordPress taking youtube (and other embeddable links) and automatically inserting the embedded video. I've tried `apply_filters( 'the_content', $my_content );`, but I think that filter isn't even available via `admin-ajax.php`. I of course already call `do_shortcode( $my_content )`, but what can I use, in similar fashion, to get the embeddable links to embed? UPDATE: In response to bonger's answer, I've updated the code to this: `wpautop( do_shortcode( $wp_embed->run_shortcode( $my_content ) ) )` ($wp\_embed was globalized before this line of code) Note that the `wpautop()` and `do_shortcode()` are totally irrelevant to this issue, but I put them in here just for completeness. This code is outputting the youtube url as a link to the youtube video, but not embedding the video in the page.
I think the solution is amazingly simple here: You're just missing a single line of code in your *ajax* callback, namely: ``` global $post; ``` where I assume you're using: ``` $post = get_post( $post_id ); ``` The reason is that there's a global post check in the `WP_Embed::shortcode()` method. More details in my answer [here](https://wordpress.stackexchange.com/a/142597/26350).
175,521
<p>I found this code on stackoverflow, but how do I output the actual content rather than just that ID line in the example!</p> <pre><code>&lt;?php $the_slug = 'my-page'; $args=array( 'name' =&gt; $the_slug, 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'numberposts' =&gt; 1 ); $my_posts = get_posts($args); if( $my_posts ) { echo 'ID on the first post found '.$my_posts[0]-&gt;ID; the_content(); } ?&gt; </code></pre>
[ { "answer_id": 175522, "author": "Михаил Семёнов", "author_id": 65524, "author_profile": "https://wordpress.stackexchange.com/users/65524", "pm_score": 0, "selected": false, "text": "<p><code>$my_posts[0]-&gt;post_content</code></p>\n\n<p>for proper look you'll need to apply filter <code>the_content</code> and do some replace ( like <code>the_content()</code> does )</p>\n\n<p><code>str_replace( ']]&gt;', ']]&amp;gt;', apply_filters('the_content', $my_posts[0]-&gt;post_content ) );</code></p>\n\n<p>if your going to use it a lot i suggest u make your own function:</p>\n\n<p><code>function my_get_content( $content ) { return str_replace( ']]&gt;', ']]&amp;gt;', apply_filters('the_content', $content ) );</code></p>\n\n<p>and then call it like so: <code>echo my_get_content( $my_posts[0]-&gt;post_content );</code></p>\n" }, { "answer_id": 175524, "author": "Nathan Fitzgerald - Fitzgenius", "author_id": 7025, "author_profile": "https://wordpress.stackexchange.com/users/7025", "pm_score": 2, "selected": true, "text": "<p>This is a \"custom\" loop outside of the main WordPress query (<code>query_posts</code>), you will have to tell WordPress to setup the post data using <code>setup_postdata()</code></p>\n\n<p>More info on <code>get_posts()</code> is found here, giving you basically what I am about to write below: <a href=\"http://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">http://codex.wordpress.org/Template_Tags/get_posts</a></p>\n\n<p>Tip: The WordPress Codex is the best friend you will ever have, apart from Google.</p>\n\n<pre><code>&lt;?php\n\n$the_slug = 'my-page';\n\n$args = array(\n 'name' =&gt; $the_slug,\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n 'numberposts' =&gt; 1\n);\n\n$my_posts = get_posts($args);\n\nif( $my_posts ) {\n\n echo 'ID on the first post found '.$my_posts[0]-&gt;ID;\n\n // To get the content of the first post:\n echo apply_filters('the_content', $my_posts[0]-&gt;post_content);\n\n // if you now wanted to remove the first post from this loop and assign it to a different variable $first_post\n // However, it looks as if you are only grabbing one \"post\" being a \"page\" from the slug \"my-page\"\n $first_post = $my_posts[0];\n unset($my_posts[0]);\n\n foreach($my_posts as $p): setup_postdata($p); \n\n // Now you can use the_title(), the_content() etc as you normally would\n\n endforeach;\n\n}\n\n// Reset WordPress Loop &amp; WP_Query\nwp_reset_postdata();\n\n?&gt;\n</code></pre>\n" } ]
2015/01/21
[ "https://wordpress.stackexchange.com/questions/175521", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50150/" ]
I found this code on stackoverflow, but how do I output the actual content rather than just that ID line in the example! ``` <?php $the_slug = 'my-page'; $args=array( 'name' => $the_slug, 'post_type' => 'page', 'post_status' => 'publish', 'numberposts' => 1 ); $my_posts = get_posts($args); if( $my_posts ) { echo 'ID on the first post found '.$my_posts[0]->ID; the_content(); } ?> ```
This is a "custom" loop outside of the main WordPress query (`query_posts`), you will have to tell WordPress to setup the post data using `setup_postdata()` More info on `get_posts()` is found here, giving you basically what I am about to write below: <http://codex.wordpress.org/Template_Tags/get_posts> Tip: The WordPress Codex is the best friend you will ever have, apart from Google. ``` <?php $the_slug = 'my-page'; $args = array( 'name' => $the_slug, 'post_type' => 'page', 'post_status' => 'publish', 'numberposts' => 1 ); $my_posts = get_posts($args); if( $my_posts ) { echo 'ID on the first post found '.$my_posts[0]->ID; // To get the content of the first post: echo apply_filters('the_content', $my_posts[0]->post_content); // if you now wanted to remove the first post from this loop and assign it to a different variable $first_post // However, it looks as if you are only grabbing one "post" being a "page" from the slug "my-page" $first_post = $my_posts[0]; unset($my_posts[0]); foreach($my_posts as $p): setup_postdata($p); // Now you can use the_title(), the_content() etc as you normally would endforeach; } // Reset WordPress Loop & WP_Query wp_reset_postdata(); ?> ```
175,554
<p>I'm creating a theme option page and i try to display the values of two input in my front end : </p> <pre><code>function register_my_header() { register_setting( 'header_options', 'header_options'); } add_action('admin_init', 'register_my_header'); function add_header_settings() { add_menu_page('Options header', 'Options header', 'manage_options', 'edit_header', 'header_edit_page', null, 58); } add_action('admin_menu', 'add_header_settings'); function header_edit_page() { ?&gt; &lt;div id="theme-options-wrap"&gt; &lt;div class="icon32" id="icon-tools"&gt; &lt;br&gt; &lt;/div&gt; &lt;h2&gt;Header Options&lt;/h2&gt; &lt;p&gt;Description&lt;/p&gt; &lt;?php if ( false !== $_REQUEST['updated'] ) : ?&gt; &lt;div&gt;&lt;p&gt;&lt;strong&gt;&lt;?php _e( 'Options saved' ); ?&gt;&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields('header_options'); ?&gt; &lt;?php $options = get_option('header_options'); ?&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th scope="row"&gt;Mail&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="header_options[txt_mail]" value="&lt;?php echo $options['txt_mail']; ?&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row"&gt;Phone number&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="header_options[txt_number]" value="&lt;?php echo $options['txt_number']; ?&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p class="submit"&gt; &lt;input type="submit" class="button-primary" value="&lt;?php _e('Save Changes') ?&gt;" /&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } function header_validate_options($input) { $input['txt_mail'] = wp_filter_nohtml_kses($input['txt_mail']); $input['txt_number'] = wp_filter_nohtml_kses($input['txt_number']); return $input; } function header_add_content() { $options = get_option('header_options'); } add_filter("the_content", "header_add_content"); </code></pre> <p>I'm able to save the value but when i call it with : </p> <pre><code> &lt;div class="background-content"&gt;&lt;/div&gt; &lt;div class="layout-header"&gt; &lt;h1 id='logo' class="image-logo"&gt; &lt;a href="&lt;?php echo home_url(); ?&gt;"&gt;&lt;img &lt;?php do_shortcode('[sitelogo]'); ?&gt;&lt;/a&gt; &lt;/h1&gt; &lt;div id="contact"&gt; &lt;p&gt;Contact Us&lt;/p&gt; &lt;p&gt;&lt;?php echo $options['txt_mail']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php echo $options['txt_number']; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>To display it in the front nothing happens ! What am i doing wrong ?</p>
[ { "answer_id": 175584, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": -1, "selected": true, "text": "<p>Make the $options variable global by changing the header_add_content() function to the following: </p>\n\n<pre><code>function header_add_content() {\n global $options; \n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Then declare $options as the global $options on the front-end template before you use it, for example: </p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 176017, "author": "Style", "author_id": 66091, "author_profile": "https://wordpress.stackexchange.com/users/66091", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answer but this doesn't display my values ! </p>\n\n<p>First i tryed to just set $options to global like you said, but it changed nothing and i still can't get the values :</p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_number']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Also tryed to put <code>global $options = get_option('header_options');</code> hopping this will fix it :</p>\n\n<pre><code> &lt;div class=\"background-content\"&gt;&lt;/div&gt;\n &lt;div class=\"layout-header\"&gt;\n &lt;h1 id='logo' class=\"image-logo\"&gt;\n &lt;a href=\"&lt;?php echo home_url(); ?&gt;\"&gt;&lt;img &lt;?php do_shortcode('[sitelogo]'); ?&gt;&lt;/a&gt;\n &lt;/h1&gt;\n &lt;?php global $options = get_option('header_options'); ?&gt;\n &lt;div id=\"contact\"&gt;\n &lt;p&gt;Contact Us&lt;/p&gt;\n &lt;p&gt;&lt;?php echo $options['txt_mail']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php echo $options['txt_number']; ?&gt;&lt;/p&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n</code></pre>\n\n<p>Nothing too ! So i removed my form-table and replace it with section fields (that worked on another theme option page when it was offline but since i'm online impossible to get any value too) :</p>\n\n<pre><code>function add_header_settings() {\n add_menu_page('Option header', 'Options header', 'manage_options', 'edit_header', 'header_edit_page', null, 58); \n}\nadd_action('admin_menu', 'add_header_settings');\n\nfunction header_edit_page() {\n?&gt; \n &lt;div id=\"theme-options-wrap\"&gt;\n &lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt; \n &lt;h2&gt;Option Header&lt;/h2&gt;\n &lt;p&gt;Description&lt;/p&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php settings_fields('header_options'); ?&gt; \n &lt;?php do_settings_sections('edit_header'); ?&gt;\n &lt;p class=\"submit\"&gt;\n &lt;input name=\"Submit\" type=\"submit\" class=\"button-primary\" value=\"&lt;?php esc_attr_e('Save Changes'); ?&gt;\" /&gt;\n &lt;/p&gt;\n &lt;/form&gt; \n &lt;/div&gt;\n&lt;?php }\n\nfunction register_and_build_fields(){\n register_setting( 'header_options', 'header_options', 'validate_setting'); \n add_settings_section('homepage_settings', 'Homepage Settings', 'section_homepage', 'edit_header');\n\n function section_homepage() {}\n\n add_settings_field('number1', 'Enter your number', 'number_setting', 'edit_header', 'homepage_settings'); \n}\nadd_action('admin_init', 'register_and_build_fields'); \n\nfunction validate_setting($header_options) {\n return $header_options;\n} \n\nfunction number_setting() {\n $options = get_option('header_options'); echo \"&lt;input name='header_options[number_setting]' type='text' value='{$options['number_setting']}' /&gt;\";\n}\n\n // $options = get_option('header_options'); \n /* &lt;table class=\"form-table\"&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Mail&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_mail]\" value=\"&lt;?php echo $options['txt_mail']; ?&gt;\" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt; \n &lt;th scope=\"row\"&gt;Phone number&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_number]\" value=\"&lt;?php echo $options['txt_number']; ?&gt;\" /&gt;\n &lt;/td&gt; \n &lt;/tr&gt; \n\n &lt;/table&gt; \n\n\nfunction header_validate_options($input) {\n $input['txt_mail'] = wp_filter_nohtml_kses($input['txt_mail']); \n $input['txt_number'] = wp_filter_nohtml_kses($input['txt_number']);\n return $input;\n} */\n\nfunction header_add_content() {\n global $options;\n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Again i can save my value in the theme option page but the front-end don't want to get them :/</p>\n\n<p>By the way : <code>&lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt;</code> i saw this code several times but i don't have any icon next to the titles (even in my second computer with a new installation) is that since an update of WP ?</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>The save works when i do a <code>get_option</code> with another variable than <code>$options</code> like <code>$header_options</code> or whatever idk why but thanks for the help !</p>\n\n<p>If someone have an explanation for the icon problem i still wanna hear it !</p>\n" } ]
2015/01/21
[ "https://wordpress.stackexchange.com/questions/175554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66091/" ]
I'm creating a theme option page and i try to display the values of two input in my front end : ``` function register_my_header() { register_setting( 'header_options', 'header_options'); } add_action('admin_init', 'register_my_header'); function add_header_settings() { add_menu_page('Options header', 'Options header', 'manage_options', 'edit_header', 'header_edit_page', null, 58); } add_action('admin_menu', 'add_header_settings'); function header_edit_page() { ?> <div id="theme-options-wrap"> <div class="icon32" id="icon-tools"> <br> </div> <h2>Header Options</h2> <p>Description</p> <?php if ( false !== $_REQUEST['updated'] ) : ?> <div><p><strong><?php _e( 'Options saved' ); ?></strong></p></div> <?php endif; ?> <form method="post" action="options.php"> <?php settings_fields('header_options'); ?> <?php $options = get_option('header_options'); ?> <table class="form-table"> <tr> <th scope="row">Mail</th> <td> <input type="text" name="header_options[txt_mail]" value="<?php echo $options['txt_mail']; ?>" /> </td> </tr> <tr> <th scope="row">Phone number</th> <td> <input type="text" name="header_options[txt_number]" value="<?php echo $options['txt_number']; ?>" /> </td> </tr> </table> <p class="submit"> <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /> </p> </form> </div> <?php } function header_validate_options($input) { $input['txt_mail'] = wp_filter_nohtml_kses($input['txt_mail']); $input['txt_number'] = wp_filter_nohtml_kses($input['txt_number']); return $input; } function header_add_content() { $options = get_option('header_options'); } add_filter("the_content", "header_add_content"); ``` I'm able to save the value but when i call it with : ``` <div class="background-content"></div> <div class="layout-header"> <h1 id='logo' class="image-logo"> <a href="<?php echo home_url(); ?>"><img <?php do_shortcode('[sitelogo]'); ?></a> </h1> <div id="contact"> <p>Contact Us</p> <p><?php echo $options['txt_mail']; ?></p><p><?php echo $options['txt_number']; ?></p> </div> </div> ``` To display it in the front nothing happens ! What am i doing wrong ?
Make the $options variable global by changing the header\_add\_content() function to the following: ``` function header_add_content() { global $options; $options = get_option('header_options'); } add_filter("the_content", "header_add_content"); ``` Then declare $options as the global $options on the front-end template before you use it, for example: ``` <p><?php global $options; echo $options['txt_mail']; ?></p> ```
175,558
<p>I've set up some custom post types, and created custom archives, eg in the following format:</p> <p>archive-books.php (With a template name of "Books Template"). I then have a page (/books/) created in wordpress, with the above archive-books.php assigned as the template.</p> <p>How would I get the the meta title (wp_title) to be the title that I set on the page (/books/)? - At the moment it's just showing "books | sitename". Even if I change the All in One SEO custom title.</p> <p>I am using All in One SEO plugin also, but that doesn't seem to work. What I THINK is happening, is that it's just ignoring the page and jumping directly to the archive-books.php as it matches the Wordpress custom post type naming rule?</p>
[ { "answer_id": 175584, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": -1, "selected": true, "text": "<p>Make the $options variable global by changing the header_add_content() function to the following: </p>\n\n<pre><code>function header_add_content() {\n global $options; \n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Then declare $options as the global $options on the front-end template before you use it, for example: </p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 176017, "author": "Style", "author_id": 66091, "author_profile": "https://wordpress.stackexchange.com/users/66091", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answer but this doesn't display my values ! </p>\n\n<p>First i tryed to just set $options to global like you said, but it changed nothing and i still can't get the values :</p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_number']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Also tryed to put <code>global $options = get_option('header_options');</code> hopping this will fix it :</p>\n\n<pre><code> &lt;div class=\"background-content\"&gt;&lt;/div&gt;\n &lt;div class=\"layout-header\"&gt;\n &lt;h1 id='logo' class=\"image-logo\"&gt;\n &lt;a href=\"&lt;?php echo home_url(); ?&gt;\"&gt;&lt;img &lt;?php do_shortcode('[sitelogo]'); ?&gt;&lt;/a&gt;\n &lt;/h1&gt;\n &lt;?php global $options = get_option('header_options'); ?&gt;\n &lt;div id=\"contact\"&gt;\n &lt;p&gt;Contact Us&lt;/p&gt;\n &lt;p&gt;&lt;?php echo $options['txt_mail']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php echo $options['txt_number']; ?&gt;&lt;/p&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n</code></pre>\n\n<p>Nothing too ! So i removed my form-table and replace it with section fields (that worked on another theme option page when it was offline but since i'm online impossible to get any value too) :</p>\n\n<pre><code>function add_header_settings() {\n add_menu_page('Option header', 'Options header', 'manage_options', 'edit_header', 'header_edit_page', null, 58); \n}\nadd_action('admin_menu', 'add_header_settings');\n\nfunction header_edit_page() {\n?&gt; \n &lt;div id=\"theme-options-wrap\"&gt;\n &lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt; \n &lt;h2&gt;Option Header&lt;/h2&gt;\n &lt;p&gt;Description&lt;/p&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php settings_fields('header_options'); ?&gt; \n &lt;?php do_settings_sections('edit_header'); ?&gt;\n &lt;p class=\"submit\"&gt;\n &lt;input name=\"Submit\" type=\"submit\" class=\"button-primary\" value=\"&lt;?php esc_attr_e('Save Changes'); ?&gt;\" /&gt;\n &lt;/p&gt;\n &lt;/form&gt; \n &lt;/div&gt;\n&lt;?php }\n\nfunction register_and_build_fields(){\n register_setting( 'header_options', 'header_options', 'validate_setting'); \n add_settings_section('homepage_settings', 'Homepage Settings', 'section_homepage', 'edit_header');\n\n function section_homepage() {}\n\n add_settings_field('number1', 'Enter your number', 'number_setting', 'edit_header', 'homepage_settings'); \n}\nadd_action('admin_init', 'register_and_build_fields'); \n\nfunction validate_setting($header_options) {\n return $header_options;\n} \n\nfunction number_setting() {\n $options = get_option('header_options'); echo \"&lt;input name='header_options[number_setting]' type='text' value='{$options['number_setting']}' /&gt;\";\n}\n\n // $options = get_option('header_options'); \n /* &lt;table class=\"form-table\"&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Mail&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_mail]\" value=\"&lt;?php echo $options['txt_mail']; ?&gt;\" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt; \n &lt;th scope=\"row\"&gt;Phone number&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_number]\" value=\"&lt;?php echo $options['txt_number']; ?&gt;\" /&gt;\n &lt;/td&gt; \n &lt;/tr&gt; \n\n &lt;/table&gt; \n\n\nfunction header_validate_options($input) {\n $input['txt_mail'] = wp_filter_nohtml_kses($input['txt_mail']); \n $input['txt_number'] = wp_filter_nohtml_kses($input['txt_number']);\n return $input;\n} */\n\nfunction header_add_content() {\n global $options;\n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Again i can save my value in the theme option page but the front-end don't want to get them :/</p>\n\n<p>By the way : <code>&lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt;</code> i saw this code several times but i don't have any icon next to the titles (even in my second computer with a new installation) is that since an update of WP ?</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>The save works when i do a <code>get_option</code> with another variable than <code>$options</code> like <code>$header_options</code> or whatever idk why but thanks for the help !</p>\n\n<p>If someone have an explanation for the icon problem i still wanna hear it !</p>\n" } ]
2015/01/21
[ "https://wordpress.stackexchange.com/questions/175558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19452/" ]
I've set up some custom post types, and created custom archives, eg in the following format: archive-books.php (With a template name of "Books Template"). I then have a page (/books/) created in wordpress, with the above archive-books.php assigned as the template. How would I get the the meta title (wp\_title) to be the title that I set on the page (/books/)? - At the moment it's just showing "books | sitename". Even if I change the All in One SEO custom title. I am using All in One SEO plugin also, but that doesn't seem to work. What I THINK is happening, is that it's just ignoring the page and jumping directly to the archive-books.php as it matches the Wordpress custom post type naming rule?
Make the $options variable global by changing the header\_add\_content() function to the following: ``` function header_add_content() { global $options; $options = get_option('header_options'); } add_filter("the_content", "header_add_content"); ``` Then declare $options as the global $options on the front-end template before you use it, for example: ``` <p><?php global $options; echo $options['txt_mail']; ?></p> ```
175,564
<p>I want to know how wordpress displaying shortcode inserted in post content, so I can replicate what it does and implement it to my plugin.</p> <p><strong>Here is an example:</strong></p> <p>I want to show shortcode inserted between an html codes like this:</p> <pre><code> &lt;div class="akismet_activate"&gt; &lt;div class="aa_a"&gt;A&lt;/div&gt; &lt;div onclick="document.akismet_activate.submit();" class="aa_button_container"&gt; [the_shortcode id="4"] &lt;div class="aa_button_border"&gt; &lt;div class="aa_button"&gt;Activate your Akismet account&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="aa_description"&gt;&lt;strong&gt;Almost done&lt;/strong&gt; - [the_shortcode id="4"] activate your account and say goodbye to comment spam&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I've done several ways, but its only execute the shortcodes and ignoring the html goodies.</p> <p>What can I do to make the executed shortcode displayed between html codes like that example?</p>
[ { "answer_id": 175584, "author": "jetlej", "author_id": 9862, "author_profile": "https://wordpress.stackexchange.com/users/9862", "pm_score": -1, "selected": true, "text": "<p>Make the $options variable global by changing the header_add_content() function to the following: </p>\n\n<pre><code>function header_add_content() {\n global $options; \n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Then declare $options as the global $options on the front-end template before you use it, for example: </p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 176017, "author": "Style", "author_id": 66091, "author_profile": "https://wordpress.stackexchange.com/users/66091", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answer but this doesn't display my values ! </p>\n\n<p>First i tryed to just set $options to global like you said, but it changed nothing and i still can't get the values :</p>\n\n<pre><code>&lt;p&gt;&lt;?php global $options; echo $options['txt_number']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php global $options; echo $options['txt_mail']; ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Also tryed to put <code>global $options = get_option('header_options');</code> hopping this will fix it :</p>\n\n<pre><code> &lt;div class=\"background-content\"&gt;&lt;/div&gt;\n &lt;div class=\"layout-header\"&gt;\n &lt;h1 id='logo' class=\"image-logo\"&gt;\n &lt;a href=\"&lt;?php echo home_url(); ?&gt;\"&gt;&lt;img &lt;?php do_shortcode('[sitelogo]'); ?&gt;&lt;/a&gt;\n &lt;/h1&gt;\n &lt;?php global $options = get_option('header_options'); ?&gt;\n &lt;div id=\"contact\"&gt;\n &lt;p&gt;Contact Us&lt;/p&gt;\n &lt;p&gt;&lt;?php echo $options['txt_mail']; ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php echo $options['txt_number']; ?&gt;&lt;/p&gt; \n &lt;/div&gt; \n &lt;/div&gt;\n</code></pre>\n\n<p>Nothing too ! So i removed my form-table and replace it with section fields (that worked on another theme option page when it was offline but since i'm online impossible to get any value too) :</p>\n\n<pre><code>function add_header_settings() {\n add_menu_page('Option header', 'Options header', 'manage_options', 'edit_header', 'header_edit_page', null, 58); \n}\nadd_action('admin_menu', 'add_header_settings');\n\nfunction header_edit_page() {\n?&gt; \n &lt;div id=\"theme-options-wrap\"&gt;\n &lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt; \n &lt;h2&gt;Option Header&lt;/h2&gt;\n &lt;p&gt;Description&lt;/p&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php settings_fields('header_options'); ?&gt; \n &lt;?php do_settings_sections('edit_header'); ?&gt;\n &lt;p class=\"submit\"&gt;\n &lt;input name=\"Submit\" type=\"submit\" class=\"button-primary\" value=\"&lt;?php esc_attr_e('Save Changes'); ?&gt;\" /&gt;\n &lt;/p&gt;\n &lt;/form&gt; \n &lt;/div&gt;\n&lt;?php }\n\nfunction register_and_build_fields(){\n register_setting( 'header_options', 'header_options', 'validate_setting'); \n add_settings_section('homepage_settings', 'Homepage Settings', 'section_homepage', 'edit_header');\n\n function section_homepage() {}\n\n add_settings_field('number1', 'Enter your number', 'number_setting', 'edit_header', 'homepage_settings'); \n}\nadd_action('admin_init', 'register_and_build_fields'); \n\nfunction validate_setting($header_options) {\n return $header_options;\n} \n\nfunction number_setting() {\n $options = get_option('header_options'); echo \"&lt;input name='header_options[number_setting]' type='text' value='{$options['number_setting']}' /&gt;\";\n}\n\n // $options = get_option('header_options'); \n /* &lt;table class=\"form-table\"&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Mail&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_mail]\" value=\"&lt;?php echo $options['txt_mail']; ?&gt;\" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt; \n &lt;th scope=\"row\"&gt;Phone number&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"header_options[txt_number]\" value=\"&lt;?php echo $options['txt_number']; ?&gt;\" /&gt;\n &lt;/td&gt; \n &lt;/tr&gt; \n\n &lt;/table&gt; \n\n\nfunction header_validate_options($input) {\n $input['txt_mail'] = wp_filter_nohtml_kses($input['txt_mail']); \n $input['txt_number'] = wp_filter_nohtml_kses($input['txt_number']);\n return $input;\n} */\n\nfunction header_add_content() {\n global $options;\n $options = get_option('header_options');\n}\nadd_filter(\"the_content\", \"header_add_content\");\n</code></pre>\n\n<p>Again i can save my value in the theme option page but the front-end don't want to get them :/</p>\n\n<p>By the way : <code>&lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br&gt; &lt;/div&gt;</code> i saw this code several times but i don't have any icon next to the titles (even in my second computer with a new installation) is that since an update of WP ?</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>The save works when i do a <code>get_option</code> with another variable than <code>$options</code> like <code>$header_options</code> or whatever idk why but thanks for the help !</p>\n\n<p>If someone have an explanation for the icon problem i still wanna hear it !</p>\n" } ]
2015/01/21
[ "https://wordpress.stackexchange.com/questions/175564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32989/" ]
I want to know how wordpress displaying shortcode inserted in post content, so I can replicate what it does and implement it to my plugin. **Here is an example:** I want to show shortcode inserted between an html codes like this: ``` <div class="akismet_activate"> <div class="aa_a">A</div> <div onclick="document.akismet_activate.submit();" class="aa_button_container"> [the_shortcode id="4"] <div class="aa_button_border"> <div class="aa_button">Activate your Akismet account</div> </div> </div> <div class="aa_description"><strong>Almost done</strong> - [the_shortcode id="4"] activate your account and say goodbye to comment spam</div> </div> ``` I've done several ways, but its only execute the shortcodes and ignoring the html goodies. What can I do to make the executed shortcode displayed between html codes like that example?
Make the $options variable global by changing the header\_add\_content() function to the following: ``` function header_add_content() { global $options; $options = get_option('header_options'); } add_filter("the_content", "header_add_content"); ``` Then declare $options as the global $options on the front-end template before you use it, for example: ``` <p><?php global $options; echo $options['txt_mail']; ?></p> ```
175,597
<p>Here is the code I have. It is showing 100 custom post known as campaigns. I need it to only show the current users. So author/joe should only show joe's campaigns. </p> <pre><code> &lt;?php if(isset($_GET['author_name'])) : $curauth = get_userdatabylogin($author_name); else : $curauth = get_userdata(intval($author)); endif; ?&gt; &lt;h2&gt;Campaigns by &lt;?php echo $curauth-&gt;nickname; ?&gt;:&lt;/h2&gt; &lt;?php $args = array( 'posts_per_page' =&gt; 100, 'post_type' =&gt; 'campaigns' ); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link: &lt;?php the_title(); ?&gt;"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;, &lt;/li&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;&lt;?php _e('No posts by this author.'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 175601, "author": "Sagive", "author_id": 7990, "author_profile": "https://wordpress.stackexchange.com/users/7990", "pm_score": 0, "selected": false, "text": "<p><strong>i dont see the problam in using WP_Query...</strong><br>\nit has an author parameter.</p>\n\n<pre><code>$cuser_id = get_current_user_id();\n\n$args = array(\n 'post_type' =&gt; 'campaigns',\n 'posts_per_page' =&gt; 100,\n 'author' =&gt; $cuser_id,\n\n);\n$the_query = new WP_Query($args);\n\nif ($the_query-&gt;have_posts()) {\n while ($the_query-&gt;have_posts()) {\n $the_query-&gt;the_post();\n\n // BUILD AND DISPLY CAMPAIGN DATA\n $pid = get_the_ID();\n $ptitle = get_the_title();\n $plink = get_permalink();\n\n echo '&lt;li&gt;&lt;a href=\"'.$plink.'\"&gt;'.$ptitle.'&lt;/a&gt;&lt;/li&gt;';\n\n }\n\n} else {\n echo 'You have published any campaigns yet';\n}\nwp_reset_postdata();\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 175905, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>Do not use <code>query_posts</code>, and for that matter any custom query to replace the main query. It is always problematic and it creates more problems that solving it.</p>\n\n<p>Use the main query and make use of <code>pre_get_posts</code> to alter the main query as needed. </p>\n\n<p>To solve your issue, remove the <code>query_posts</code> line, this is how author.php should look.</p>\n\n<pre><code>&lt;?php\n\n if(isset($_GET['author_name'])) :\n\n $curauth = get_userdatabylogin($author_name);\n\n else :\n\n $curauth = get_userdata(intval($author));\n\n endif;\n\n?&gt;\n\n&lt;h2&gt;Campaigns by &lt;?php echo $curauth-&gt;nickname; ?&gt;:&lt;/h2&gt;\n\n&lt;?php\n\nif ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;li&gt;\n\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"Permanent Link: &lt;?php the_title(); ?&gt;\"&gt;\n\n &lt;?php the_title(); ?&gt;&lt;/a&gt;,\n\n\n\n &lt;/li&gt;\n\n\n&lt;?php endwhile; else: ?&gt;\n\n &lt;p&gt;&lt;?php _e('No posts by this author.'); ?&gt;&lt;/p&gt;\n\n\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Add the following in your <code>functions.php</code> file</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q ) {\n\n if( !is_admin() &amp;&amp; $q-&gt;is_main_query() &amp;&amp; $q-&gt;is_author() ) {\n\n $q-&gt;set( 'posts_per_page', 100 );\n $q-&gt;set( 'post_type', 'campaigns' );\n\n }\n\n});\n</code></pre>\n\n<p>This should solve your issue</p>\n" } ]
2015/01/22
[ "https://wordpress.stackexchange.com/questions/175597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49017/" ]
Here is the code I have. It is showing 100 custom post known as campaigns. I need it to only show the current users. So author/joe should only show joe's campaigns. ``` <?php if(isset($_GET['author_name'])) : $curauth = get_userdatabylogin($author_name); else : $curauth = get_userdata(intval($author)); endif; ?> <h2>Campaigns by <?php echo $curauth->nickname; ?>:</h2> <?php $args = array( 'posts_per_page' => 100, 'post_type' => 'campaigns' ); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"> <?php the_title(); ?></a>, </li> <?php endwhile; else: ?> <p><?php _e('No posts by this author.'); ?></p> <?php endif; ?> ```
Do not use `query_posts`, and for that matter any custom query to replace the main query. It is always problematic and it creates more problems that solving it. Use the main query and make use of `pre_get_posts` to alter the main query as needed. To solve your issue, remove the `query_posts` line, this is how author.php should look. ``` <?php if(isset($_GET['author_name'])) : $curauth = get_userdatabylogin($author_name); else : $curauth = get_userdata(intval($author)); endif; ?> <h2>Campaigns by <?php echo $curauth->nickname; ?>:</h2> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"> <?php the_title(); ?></a>, </li> <?php endwhile; else: ?> <p><?php _e('No posts by this author.'); ?></p> <?php endif; ?> ``` Add the following in your `functions.php` file ``` add_action( 'pre_get_posts', function ( $q ) { if( !is_admin() && $q->is_main_query() && $q->is_author() ) { $q->set( 'posts_per_page', 100 ); $q->set( 'post_type', 'campaigns' ); } }); ``` This should solve your issue
175,613
<p>I created a plugin with a cron to update all posts of a certain type every 5 minutes. I installed WP Crontrol to check if the cron is registered correctly and everything seems to be okay.</p> <p>This is how I registered my cron:</p> <pre><code>function custom_cron_interval( $schedules ) { $schedules['fiveminutes'] = array( 'interval' =&gt; 300, 'display' =&gt; __('Every five minutes') ); return $schedules; } add_filter( 'cron_schedules', 'custom_cron_interval' ); if ( ! wp_next_scheduled( 'recalculate_all_scores' ) ) { wp_schedule_event(time(), 'fiveminutes', 'recalculate_all_scores'); } </code></pre> <p>It is registered correctly but when the function executes, nothing happens. For testing purposes I hooked the function to the save_post action. Everything works fine this way. But when the scheduled task is called, it won't execute.</p> <p>Here is the code of the function</p> <pre><code>function recalculate_all_scores() { global $wpdb; $customers = $wpdb-&gt;get_results("SELECT * FROM wp_posts WHERE post_type = 'customer' AND post_status = 'publish';"); foreach ($customers as $customer){ set_score($customer); } } function set_score($customer){ $acf_key = "score"; $score = rand(0,50); update_field( $acf_key, $score, $customer-&gt;ID ); } </code></pre> <p>I also added the following lines to my wp-config.php:</p> <pre><code>define('ALTERNATE_WP_CRON', true); define('DISABLE_WP_CRON', false); </code></pre> <p>Any idea what is stopping the function from executing?</p> <p><strong>EDIT</strong></p> <ul> <li>I'm aware that the wp_cron system is not a real cron and that it relies on site visits. </li> <li>If I execute the function manually it takes about 15 seconds so the PHP execution time limit should not be a problem.</li> </ul>
[ { "answer_id": 176312, "author": "mtt_g", "author_id": 63255, "author_profile": "https://wordpress.stackexchange.com/users/63255", "pm_score": 0, "selected": false, "text": "<p>I was having the same issue recently, until I followed an example from the <a href=\"http://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow\">Wordpress Codex</a> which suggests using action hooks to run the function.</p>\n\n<p>I think if you add the following...</p>\n\n<pre><code>add_action( 'recalculate_all_scores_hook', 'recalculate_all_scores' );\n</code></pre>\n\n<p>...and amend the wp_schedule_event function to use the action hook name rather than the function directly...</p>\n\n<pre><code>wp_schedule_event( time(), 'fiveminutes', 'recalculate_all_scores_hook' );\n</code></pre>\n\n<p>...you might be in business.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 208783, "author": "kalpesh", "author_id": 83682, "author_profile": "https://wordpress.stackexchange.com/users/83682", "pm_score": -1, "selected": false, "text": "<p>WordPress only support hourly, daily and twise daily, so change five minutes with any of three and set your function with <code>sleep(10);</code> or any other time which suitable for your plugin</p>\n\n<p>Check <a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow\">here</a></p>\n" } ]
2015/01/22
[ "https://wordpress.stackexchange.com/questions/175613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43586/" ]
I created a plugin with a cron to update all posts of a certain type every 5 minutes. I installed WP Crontrol to check if the cron is registered correctly and everything seems to be okay. This is how I registered my cron: ``` function custom_cron_interval( $schedules ) { $schedules['fiveminutes'] = array( 'interval' => 300, 'display' => __('Every five minutes') ); return $schedules; } add_filter( 'cron_schedules', 'custom_cron_interval' ); if ( ! wp_next_scheduled( 'recalculate_all_scores' ) ) { wp_schedule_event(time(), 'fiveminutes', 'recalculate_all_scores'); } ``` It is registered correctly but when the function executes, nothing happens. For testing purposes I hooked the function to the save\_post action. Everything works fine this way. But when the scheduled task is called, it won't execute. Here is the code of the function ``` function recalculate_all_scores() { global $wpdb; $customers = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type = 'customer' AND post_status = 'publish';"); foreach ($customers as $customer){ set_score($customer); } } function set_score($customer){ $acf_key = "score"; $score = rand(0,50); update_field( $acf_key, $score, $customer->ID ); } ``` I also added the following lines to my wp-config.php: ``` define('ALTERNATE_WP_CRON', true); define('DISABLE_WP_CRON', false); ``` Any idea what is stopping the function from executing? **EDIT** * I'm aware that the wp\_cron system is not a real cron and that it relies on site visits. * If I execute the function manually it takes about 15 seconds so the PHP execution time limit should not be a problem.
I was having the same issue recently, until I followed an example from the [Wordpress Codex](http://codex.wordpress.org/Function_Reference/wp_schedule_event) which suggests using action hooks to run the function. I think if you add the following... ``` add_action( 'recalculate_all_scores_hook', 'recalculate_all_scores' ); ``` ...and amend the wp\_schedule\_event function to use the action hook name rather than the function directly... ``` wp_schedule_event( time(), 'fiveminutes', 'recalculate_all_scores_hook' ); ``` ...you might be in business. Good luck!
175,647
<p>Unless i use:</p> <pre><code>wp_enqueue_style( 'dazzling-style', get_template_directory_uri() . '/css/main.css?ver=', array(), rand(10,99999), 'all' ); </code></pre> <p>Then everytime I visit my site, be it local or live, I see that the version is 4.1 and even though I upload a new stylesheet or js, the browser still sees that 4.1 version.</p> <p>What's going on? Where is that 4.1 coming from?</p>
[ { "answer_id": 175650, "author": "Maikal", "author_id": 38034, "author_profile": "https://wordpress.stackexchange.com/users/38034", "pm_score": 0, "selected": false, "text": "<p>try to remove <code>?ver=</code></p>\n\n<p>4.1 is coming from wordpress, by default it set's a wordpress version</p>\n" }, { "answer_id": 175651, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>4.1 is coming from your WordPress version.</p>\n\n<p>Also you should not append <code>ver=</code> to the src manually but use the fourth parameter of <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\">wp_enqueue_style</a>.</p>\n" }, { "answer_id": 175658, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 2, "selected": false, "text": "<p>The solution is simple: Use the <strong>last time the file was changed</strong> as version number. You can use <a href=\"http://php.net/manual/de/function.filemtime.php\" rel=\"nofollow\"><code>filemtime()</code></a> (File Modified Time) on the <em>path</em> of the file. Example:</p>\n\n<pre><code>wp_enqueue_style(\n 'your-handle',\n get_template_directory_uri().'/assets/style.css', # use plugin_dir_url( __FILE__ ) for plugins\n array( 'dependencies', ), # use [] for PHP 5.4+\n filemtime( get_template_directory().'/assets/style.css' ) # use plugin_dir_path( __FILE__ ) for plugins\n);\n</code></pre>\n\n<p>This will append the <em>UNIX timestamp</em> as version number. And it will <strong>stay that way</strong> until you change your stylesheet again. That's the most convenient way I know of. It stays cached in browsers until there's a change. That btw works perfectly with stuff like watch and livereload tasks during development.</p>\n\n<p>And if you ask (in the comments) why WordPress doesn't do that per default, then my answer would be ... <em>\"Uhm, well. WordPress.\"</em></p>\n" } ]
2015/01/22
[ "https://wordpress.stackexchange.com/questions/175647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14378/" ]
Unless i use: ``` wp_enqueue_style( 'dazzling-style', get_template_directory_uri() . '/css/main.css?ver=', array(), rand(10,99999), 'all' ); ``` Then everytime I visit my site, be it local or live, I see that the version is 4.1 and even though I upload a new stylesheet or js, the browser still sees that 4.1 version. What's going on? Where is that 4.1 coming from?
4.1 is coming from your WordPress version. Also you should not append `ver=` to the src manually but use the fourth parameter of [wp\_enqueue\_style](http://codex.wordpress.org/Function_Reference/wp_enqueue_style).
175,699
<p>Is there a way we can set these to list the posts in the category by alphabetical order?</p>
[ { "answer_id": 175701, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 0, "selected": false, "text": "<p>If you're talking about general Wordpress coding, have a look here:\n<a href=\"http://codex.wordpress.org/Alphabetizing_Posts\" rel=\"nofollow\">http://codex.wordpress.org/Alphabetizing_Posts</a></p>\n\n<p>Look for 'order' => 'ASC' which will order posts in Ascending value (eg. A-Z)</p>\n\n<p>If you're talking about using or adapting a plugin, have a look in the plugin's instructions. For instance, the plugin <a href=\"https://wordpress.org/plugins/list-category-posts/\" rel=\"nofollow\">List Category Posts</a> has instructions about ordering posts in <a href=\"https://wordpress.org/plugins/list-category-posts/other_notes/\" rel=\"nofollow\">its notes here</a>.</p>\n\n<p>In that plugin's case, you'd want to use the shortcode: [catlist order=asc] </p>\n" }, { "answer_id": 175703, "author": "Alexey", "author_id": 7314, "author_profile": "https://wordpress.stackexchange.com/users/7314", "pm_score": 1, "selected": false, "text": "<p>Yes, there is. Paste this in your <code>function.php</code></p>\n\n<pre><code>add_action('pre_get_posts','wpse_175699_alphabetical_order');\n\nfunction wpse_175699_alphabetical_order($query) {\n\n if (is_category()) {\n $query-&gt;set('orderby', 'title');\n $query-&gt;set('order', 'ASC');\n }\n\n}\n</code></pre>\n" } ]
2015/01/22
[ "https://wordpress.stackexchange.com/questions/175699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66442/" ]
Is there a way we can set these to list the posts in the category by alphabetical order?
Yes, there is. Paste this in your `function.php` ``` add_action('pre_get_posts','wpse_175699_alphabetical_order'); function wpse_175699_alphabetical_order($query) { if (is_category()) { $query->set('orderby', 'title'); $query->set('order', 'ASC'); } } ```
175,712
<p>I made a custom post type with taxonomies and when I go to the taxonomy page and view one of the taxonomies I get a page not found error like the taxonomy wasnt made.</p> <p>Any suggestions?</p> <pre><code>/*Products*/ $labels = array( 'name' =&gt; _x('Products', 'post type general name'), 'singular_name' =&gt; _x('Product', 'post type singular name'), 'add_new' =&gt; _x('Add New', 'Product'), 'add_new_item' =&gt; __("Add New Product"), 'edit_item' =&gt; __("Edit Product"), 'new_item' =&gt; __("New Product"), 'view_item' =&gt; __("View Product"), 'search_items' =&gt; __("Search Product"), 'not_found' =&gt; __('No products found'), 'not_found_in_trash' =&gt; __('No products found in Trash'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'singular_label' =&gt; __('Products'), 'public' =&gt; true, 'show_ui' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'rewrite' =&gt; true, 'query_var' =&gt; 'products', 'taxonomies' =&gt; array('products-cat'), 'supports' =&gt; array('title', 'editor', 'custom-fields', 'thumbnail', 'excerpt'), 'has_archive' =&gt; true, ); register_post_type( 'products' , $args ); // Add to admin_init function add_filter('manage_edit-products_columns', 'add_new_products_columns'); function add_new_products_columns($columns) { $columns = array( 'cb' =&gt; '&lt;input type="checkbox" /&gt;', 'images' =&gt; 'Images', 'title' =&gt; 'Product Name', 'author' =&gt; 'Author', 'product-categories' =&gt; 'Categories', 'tags' =&gt; 'Tags', 'date' =&gt; 'Date', ); return $columns; } add_action('manage_products_posts_custom_column', 'manage_products_columns', 10, 2); function manage_products_columns($column_name, $id) { global $wpdb; switch ($column_name) { case 'images': //echo get_the_post_thumbnail( $page-&gt;ID, array(50,50) ); break; case 'product-categories': echo get_the_term_list($post-&gt;ID, 'products-cat', '', ', ',''); break; default: break; } } add_action( 'init', 'products_create_taxonomies', 0 ); function products_create_taxonomies() { // Photo Categories register_taxonomy('products-cat',array('products'),array( 'hierarchical' =&gt; true, 'label' =&gt; 'Product Categories', 'singular_name' =&gt; 'Products Category', 'show_ui' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'products' ) )); } /*End Products*/ </code></pre> <p>I have this in my archives page</p> <p>archive-products.php</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php while ( have_posts() ) : the_post();?&gt; &lt;?php the_title(); ?&gt; &lt;?php endwhile; endif; ?&gt; </code></pre>
[ { "answer_id": 175714, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 1, "selected": false, "text": "<p>I'd recommend at least two things:</p>\n\n<ol>\n<li><p>Change the priority for your <code>products_create_taxonomies</code> action to at least 1, if not 5 or higher. (I'm thinking 0 is not valid for action priorities for some reason)</p></li>\n<li><p>Add your post type creation into an init action just like you did your taxonomies at an earlier priority than your taxonomy (since you are connecting them via the taxonomy).</p></li>\n</ol>\n\n<p>If those two changes don't take care of it, try setting up both (without linking them via their own structures) and then call the following on a later priority (still during init):</p>\n\n<pre><code>register_taxonomy_for_object_type( 'products-cat', 'products' );\n</code></pre>\n\n<p>That should make sure that they are fully and properly linked up.</p>\n" }, { "answer_id": 175730, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>I think your main issue here is the rewrite for your <a href=\"http://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">taxonomy</a>. As it stands, your rewrite for the taxonomy looks like this</p>\n\n<pre><code>'rewrite' =&gt; array('slug' =&gt; 'products' )\n</code></pre>\n\n<p>This is what exactly what this rewrite means in your <a href=\"http://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">custom post type</a>. The following </p>\n\n<pre><code>'rewrite' =&gt; true,\n</code></pre>\n\n<p>translates to this in your custom post type</p>\n\n<pre><code>'rewrite' =&gt; array('slug' =&gt; 'products' )\n</code></pre>\n\n<p>By default, this clash in rewrites will 404 your taxonomy requests. As a solution, you can change your rewrite for your taxonomy, or have a look at <a href=\"https://wordpress.stackexchange.com/a/165256/31545\">this post</a> I have done recently on this site on a better workaround to this.</p>\n\n<p><strong>Important:</strong> Flush your permalinks after every update in your code to reset your permalinks to your new structure</p>\n" }, { "answer_id": 175738, "author": "Jeremy Love", "author_id": 2635, "author_profile": "https://wordpress.stackexchange.com/users/2635", "pm_score": 3, "selected": true, "text": "<p>After some research I have found a blog who actually had an answer to this problem.</p>\n\n<p>Here is the function along with the <a href=\"http://someweblog.com/wordpress-custom-taxonomy-with-same-slug-as-custom-post-type/\" rel=\"nofollow\">blog url</a>.</p>\n\n<pre><code>function taxonomy_slug_rewrite($wp_rewrite) {\n $rules = array();\n // get all custom taxonomies\n $taxonomies = get_taxonomies(array('_builtin' =&gt; false), 'objects');\n // get all custom post types\n $post_types = get_post_types(array('public' =&gt; true, '_builtin' =&gt; false), 'objects');\n\n foreach ($post_types as $post_type) {\n foreach ($taxonomies as $taxonomy) {\n\n // go through all post types which this taxonomy is assigned to\n foreach ($taxonomy-&gt;object_type as $object_type) {\n\n // check if taxonomy is registered for this custom type\n if ($object_type == $post_type-&gt;rewrite['slug']) {\n\n // get category objects\n $terms = get_categories(array('type' =&gt; $object_type, 'taxonomy' =&gt; $taxonomy-&gt;name, 'hide_empty' =&gt; 0));\n\n // make rules\n foreach ($terms as $term) {\n $rules[$object_type . '/' . $term-&gt;slug . '/?$'] = 'index.php?' . $term-&gt;taxonomy . '=' . $term-&gt;slug;\n }\n }\n }\n }\n }\n // merge with global rules\n $wp_rewrite-&gt;rules = $rules + $wp_rewrite-&gt;rules;\n}\nadd_filter('generate_rewrite_rules', 'taxonomy_slug_rewrite');\n</code></pre>\n" }, { "answer_id": 256694, "author": "Julien Menichini", "author_id": 113472, "author_profile": "https://wordpress.stackexchange.com/users/113472", "pm_score": 4, "selected": false, "text": "<p>I encountered the same problem on my local nginx platform.\nAfter I updated permalinks in the settings, everything worked fine.\nSettings > Permalinks > Save Changes (without modification)</p>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2635/" ]
I made a custom post type with taxonomies and when I go to the taxonomy page and view one of the taxonomies I get a page not found error like the taxonomy wasnt made. Any suggestions? ``` /*Products*/ $labels = array( 'name' => _x('Products', 'post type general name'), 'singular_name' => _x('Product', 'post type singular name'), 'add_new' => _x('Add New', 'Product'), 'add_new_item' => __("Add New Product"), 'edit_item' => __("Edit Product"), 'new_item' => __("New Product"), 'view_item' => __("View Product"), 'search_items' => __("Search Product"), 'not_found' => __('No products found'), 'not_found_in_trash' => __('No products found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'singular_label' => __('Products'), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => true, 'query_var' => 'products', 'taxonomies' => array('products-cat'), 'supports' => array('title', 'editor', 'custom-fields', 'thumbnail', 'excerpt'), 'has_archive' => true, ); register_post_type( 'products' , $args ); // Add to admin_init function add_filter('manage_edit-products_columns', 'add_new_products_columns'); function add_new_products_columns($columns) { $columns = array( 'cb' => '<input type="checkbox" />', 'images' => 'Images', 'title' => 'Product Name', 'author' => 'Author', 'product-categories' => 'Categories', 'tags' => 'Tags', 'date' => 'Date', ); return $columns; } add_action('manage_products_posts_custom_column', 'manage_products_columns', 10, 2); function manage_products_columns($column_name, $id) { global $wpdb; switch ($column_name) { case 'images': //echo get_the_post_thumbnail( $page->ID, array(50,50) ); break; case 'product-categories': echo get_the_term_list($post->ID, 'products-cat', '', ', ',''); break; default: break; } } add_action( 'init', 'products_create_taxonomies', 0 ); function products_create_taxonomies() { // Photo Categories register_taxonomy('products-cat',array('products'),array( 'hierarchical' => true, 'label' => 'Product Categories', 'singular_name' => 'Products Category', 'show_ui' => true, 'query_var' => true, 'rewrite' => array('slug' => 'products' ) )); } /*End Products*/ ``` I have this in my archives page archive-products.php ``` <?php get_header(); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post();?> <?php the_title(); ?> <?php endwhile; endif; ?> ```
After some research I have found a blog who actually had an answer to this problem. Here is the function along with the [blog url](http://someweblog.com/wordpress-custom-taxonomy-with-same-slug-as-custom-post-type/). ``` function taxonomy_slug_rewrite($wp_rewrite) { $rules = array(); // get all custom taxonomies $taxonomies = get_taxonomies(array('_builtin' => false), 'objects'); // get all custom post types $post_types = get_post_types(array('public' => true, '_builtin' => false), 'objects'); foreach ($post_types as $post_type) { foreach ($taxonomies as $taxonomy) { // go through all post types which this taxonomy is assigned to foreach ($taxonomy->object_type as $object_type) { // check if taxonomy is registered for this custom type if ($object_type == $post_type->rewrite['slug']) { // get category objects $terms = get_categories(array('type' => $object_type, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0)); // make rules foreach ($terms as $term) { $rules[$object_type . '/' . $term->slug . '/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug; } } } } } // merge with global rules $wp_rewrite->rules = $rules + $wp_rewrite->rules; } add_filter('generate_rewrite_rules', 'taxonomy_slug_rewrite'); ```
175,728
<p>I can log into <a href="http://localhost/wp/wp-admin/" rel="nofollow">http://localhost/wp/wp-admin/</a> fine, but logging into <a href="http://localhost/wp/wp-admin/network/" rel="nofollow">http://localhost/wp/wp-admin/network/</a> produces a network redirect loop (ERR_TOO_MANY_REDIRECTS). The site also loads just fine even when logged in.</p> <p>How can I find out what is causing this? Wordpress 4.1 installed into subdirectory 'wp', then converted to multisite. There is only one site in the network so far.</p> <p><strong>update:</strong> This seems very relevant: <a href="https://wordpress.org/support/topic/network-site-redirect-loop-solution" rel="nofollow">https://wordpress.org/support/topic/network-site-redirect-loop-solution</a></p> <ul> <li>A work-around is to remove the check to see if <code>$current_blog-&gt;path</code> matches <code>$current_site-&gt;path</code>.</li> </ul> <hr> <p><strong>I have tried clearing cookies and adding this code to wp-config:</strong></p> <pre><code>define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); </code></pre> <p><strong>My .htaccess</strong> (unmodified from WordPress multisite setup):</p> <pre><code>RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) wp/$2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ wp/$2 [L] RewriteRule . index.php [L] </code></pre>
[ { "answer_id": 175753, "author": "Arshad Hussain", "author_id": 45086, "author_profile": "https://wordpress.stackexchange.com/users/45086", "pm_score": 1, "selected": false, "text": "<p>In your wp-config.php, you should overwrite the given server-variables that cause the problem by adding this below your database-configuration in wp-config:</p>\n\n<pre><code>if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {\n$list = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);\n$_SERVER['REMOTE_ADDR'] = $list[0];\n}\n$_SERVER[ 'SERVER_ADDR' ] = DOMAIN_CURRENT_SITE;\n$_SERVER[ 'REMOTE_ADDR' ] = DOMAIN_CURRENT_SITE;\n$_SERVER[ 'HTTP_HOST' ] = DOMAIN_CURRENT_SITE;\n</code></pre>\n\n<p>You need to set your multisite define('DOMAIN_CURRENT_SITE', 'www.betterplace.org'); above this, of course.</p>\n" }, { "answer_id": 241010, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": false, "text": "<p>Problem is here: in htaccess, instead of this:</p>\n\n<pre><code>RewriteBase /\n</code></pre>\n\n<p>you should have</p>\n\n<pre><code>RewriteBase /wp/\n</code></pre>\n\n<p>in <code>wp-config.php</code>, there should be:</p>\n\n<pre><code>define( 'WP_ALLOW_MULTISITE', true );\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false); //or true, depends on your chosen way\ndefine('DOMAIN_CURRENT_SITE', 'localhost');\ndefine('PATH_CURRENT_SITE', '/wp/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n" }, { "answer_id": 338473, "author": "Andrew", "author_id": 168541, "author_profile": "https://wordpress.stackexchange.com/users/168541", "pm_score": 1, "selected": false, "text": "<p>There's another possible cause of the loop when trying to access: </p>\n\n<pre><code>/wp-admin/network/\n</code></pre>\n\n<p>There's a redirect triggered at the bottom of: </p>\n\n<pre><code>/wp-admin/network/admin.php\n</code></pre>\n\n<p>This checks that the current blog and current website have the same path and domain values, if they don't then the redirect occurs.</p>\n\n<p>Double check that the path specified in the <strong>wp_blogs</strong> table is the same as the path set on the current site.</p>\n\n<p>These values can end up out of sync, especially when installing the applications inside a directory, eg. /blog/</p>\n" }, { "answer_id": 359768, "author": "Shahzaib Chadhar", "author_id": 183408, "author_profile": "https://wordpress.stackexchange.com/users/183408", "pm_score": 0, "selected": false, "text": "<p>If you are using Cloudflare, from SSL/TLS tab of your Cloudflare account, select Full encryption. It will solve the issue.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7n4Pt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7n4Pt.png\" alt=\"SSL TO FULL\"></a></p>\n" }, { "answer_id": 365809, "author": "shadow.mal", "author_id": 157386, "author_profile": "https://wordpress.stackexchange.com/users/157386", "pm_score": 2, "selected": false, "text": "<p>I also had the same redirect problem when trying to access wp-admin/network. Performing below changes fixed it.</p>\n\n<p>1). In <code>wp-config.php</code> file, added <code>www.website.com</code> rather than just <code>website.com</code> \n<code>define('DOMAIN_CURRENT_SITE', 'www.website.com');</code></p>\n\n<p>2). use phpmyadmin --> <code>wp_blogs</code> table\nAdd <code>www.</code> to the domain value</p>\n\n<p>Basically, both site name and blog name have to be exactly the same.</p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 377489, "author": "Naren Rawat", "author_id": 196931, "author_profile": "https://wordpress.stackexchange.com/users/196931", "pm_score": 0, "selected": false, "text": "<pre><code>define('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false);\ndefine('DOMAIN_CURRENT_SITE', '**https://hotgossips.in**');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\ndefine( 'DISALLOW_FILE_EDIT', false );\n</code></pre>\n<p><strong>Just put your full address in website url whether it's from www or https or https://www</strong></p>\n<p>After searching for a day i found my solution. This works for me.Hope it will work for you as well!!</p>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66079/" ]
I can log into <http://localhost/wp/wp-admin/> fine, but logging into <http://localhost/wp/wp-admin/network/> produces a network redirect loop (ERR\_TOO\_MANY\_REDIRECTS). The site also loads just fine even when logged in. How can I find out what is causing this? Wordpress 4.1 installed into subdirectory 'wp', then converted to multisite. There is only one site in the network so far. **update:** This seems very relevant: <https://wordpress.org/support/topic/network-site-redirect-loop-solution> * A work-around is to remove the check to see if `$current_blog->path` matches `$current_site->path`. --- **I have tried clearing cookies and adding this code to wp-config:** ``` define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); ``` **My .htaccess** (unmodified from WordPress multisite setup): ``` RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) wp/$2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ wp/$2 [L] RewriteRule . index.php [L] ```
Problem is here: in htaccess, instead of this: ``` RewriteBase / ``` you should have ``` RewriteBase /wp/ ``` in `wp-config.php`, there should be: ``` define( 'WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); //or true, depends on your chosen way define('DOMAIN_CURRENT_SITE', 'localhost'); define('PATH_CURRENT_SITE', '/wp/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); ```
175,729
<p>I'm trying to disable a checkbox depending on the state of another checkbox.</p> <pre><code>&lt;form action="options.php" method="post" id="form_submission"&gt; &lt;table&gt; &lt;tr&gt; &lt;td width="200px"&gt; &lt;label for="first_option"&gt;&lt;?php _e('First Option:', 'my_plugin'); ?&gt;&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" name="first_option_show" value="show" &lt;?php echo (get_option('first_option_show')=="show" ? 'checked' : '');?&gt;&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" name="first_option_required" value="required" &lt;?php echo (get_option('first_option_required')=="required" ? 'checked' : '');?&gt;&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type="submit" name="submit" value="Save Settings"&gt; &lt;/form&gt; </code></pre> <p>So what I want in the script above, when the "first_option_show" is NOT checked I need the "first_option_required" to be disabled (whatever state the state of the "first_option_required" is check or unchecked, I don't clear the data in the DB).</p> <p>I need this to run On Load of the page too, because as you can see the state of the "checkbox" come from the options.</p> <p>I know it's probably an easy one, but I cannot get my head around it.</p> <p>I was used to work with Javascript and make check of different values, but now that I work with PHP and html, I can't get it to work.</p> <p>Just to make sure I give more information, the following will be in the Admin Area, it's for a plugin development, this is for a field in a different form, one option says if the field will be "showing" in the page form and the other one if the field will be required, which is why, if the field is not showing I want to disable the option if the "required" field.</p> <p>Thanks in Advance!</p>
[ { "answer_id": 175737, "author": "Alexey", "author_id": 7314, "author_profile": "https://wordpress.stackexchange.com/users/7314", "pm_score": 0, "selected": false, "text": "<p>The state of checkbox you can know only with JavaScript.\nIn jQuery it could be look like this:</p>\n\n<pre><code>if($(\"input[name=first_option_show]\").not(\":checked\")){\n $(\"input[name=first_option_required]\").attr(\"disabled\",true);\n}\n</code></pre>\n" }, { "answer_id": 175779, "author": "David Gard", "author_id": 10097, "author_profile": "https://wordpress.stackexchange.com/users/10097", "pm_score": 1, "selected": false, "text": "<p>This may be a little overkill for you needs, but I use a bulked up version of this to great effect on my site.</p>\n\n<p>This script will - </p>\n\n<ul>\n<li><p>Check what state the <code>first_option_required</code> option shold be in on page load (and set)</p></li>\n<li><p>Change the state of the <code>first_option_required</code> button upon changes to the <code>first_option_show</code> option. This is managed via an event hadler that will capture changes to the <code>first_option_show</code> option</p></li>\n</ul>\n\n<p>Double check the input names are correct for your needs and then paste the code in to any JS file that is accessible by the page for which you reqire this functionality.</p>\n\n<p><strong>Note</strong> - If you don't already have a JS file that is included and require help enquing on, let us know.</p>\n\n<pre><code>jQuery(function($){\n\n /**\n * Once the document is ready, initialise the 'checkResponses' object\n */\n $(document).ready(function(){\n checkResponses.init();\n });\n\n /**\n * Monitor the change is state to user responses in my form\n */\n checkResponses = {\n\n /**\n * Psuedo constructor\n */\n init : function(){\n this.create_events();\n this.maybe_disable_first_option_required();\n }, // init\n\n /**\n * Create events required for monitoring\n */\n create_events : function(){\n\n var t = this; // This object\n\n $('input[name=first_option_show]').on('change', function(){\n t.maybe_disable_first_option_required();\n });\n\n }, // create_events\n\n /**\n * Check to see if the 'first_option_required' options should be disabled or not\n */\n maybe_disable_first_option_required : function(){\n\n if($('input[name=first_option_show]').is(':checked')){\n alert('Removing...');\n $('input[name=first_option_required]').removeAttr('disabled');\n } else {\n alert('Adding...');\n $('input[name=first_option_required]').attr('disabled', true);\n }\n\n } // maybe_disable_first_option_required\n\n }\n\n});\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66412/" ]
I'm trying to disable a checkbox depending on the state of another checkbox. ``` <form action="options.php" method="post" id="form_submission"> <table> <tr> <td width="200px"> <label for="first_option"><?php _e('First Option:', 'my_plugin'); ?></label> </td> <td> <input type="checkbox" name="first_option_show" value="show" <?php echo (get_option('first_option_show')=="show" ? 'checked' : '');?>> </td> <td> <input type="checkbox" name="first_option_required" value="required" <?php echo (get_option('first_option_required')=="required" ? 'checked' : '');?>> </td> </tr> </table> <input type="submit" name="submit" value="Save Settings"> </form> ``` So what I want in the script above, when the "first\_option\_show" is NOT checked I need the "first\_option\_required" to be disabled (whatever state the state of the "first\_option\_required" is check or unchecked, I don't clear the data in the DB). I need this to run On Load of the page too, because as you can see the state of the "checkbox" come from the options. I know it's probably an easy one, but I cannot get my head around it. I was used to work with Javascript and make check of different values, but now that I work with PHP and html, I can't get it to work. Just to make sure I give more information, the following will be in the Admin Area, it's for a plugin development, this is for a field in a different form, one option says if the field will be "showing" in the page form and the other one if the field will be required, which is why, if the field is not showing I want to disable the option if the "required" field. Thanks in Advance!
This may be a little overkill for you needs, but I use a bulked up version of this to great effect on my site. This script will - * Check what state the `first_option_required` option shold be in on page load (and set) * Change the state of the `first_option_required` button upon changes to the `first_option_show` option. This is managed via an event hadler that will capture changes to the `first_option_show` option Double check the input names are correct for your needs and then paste the code in to any JS file that is accessible by the page for which you reqire this functionality. **Note** - If you don't already have a JS file that is included and require help enquing on, let us know. ``` jQuery(function($){ /** * Once the document is ready, initialise the 'checkResponses' object */ $(document).ready(function(){ checkResponses.init(); }); /** * Monitor the change is state to user responses in my form */ checkResponses = { /** * Psuedo constructor */ init : function(){ this.create_events(); this.maybe_disable_first_option_required(); }, // init /** * Create events required for monitoring */ create_events : function(){ var t = this; // This object $('input[name=first_option_show]').on('change', function(){ t.maybe_disable_first_option_required(); }); }, // create_events /** * Check to see if the 'first_option_required' options should be disabled or not */ maybe_disable_first_option_required : function(){ if($('input[name=first_option_show]').is(':checked')){ alert('Removing...'); $('input[name=first_option_required]').removeAttr('disabled'); } else { alert('Adding...'); $('input[name=first_option_required]').attr('disabled', true); } } // maybe_disable_first_option_required } }); ```
175,771
<p>I'm not sure if this is possible - but checking before re-writing the template.</p> <p>I've extended wp_query to allow for a geocode/location search to be performed. This is working in itself and returning posts in a nearest to search point first order.</p> <p>In the query generated now by wp_query it's calculating the distance in miles away from the search point and returning this <code>AS distance</code>.</p> <p>My colleague who's built the results template has used ACF - so is looping through the list using:</p> <pre><code>&lt;?php while ( have_posts() ) : the_post(); ?&gt; </code></pre> <p>This 'distance' value is not being returned when using the usual ACF method of <code>&lt;?php echo the_field('distance'); ?&gt;</code> which makes sense as it's not an ACF or post field, but rather calculated in the wp_query...</p> <p>Is there a good way of accessing values from the query, but not ACF fields, inside this ACF loop - or am I better rewriting to manually look through the query results without the ACF methods?</p>
[ { "answer_id": 175737, "author": "Alexey", "author_id": 7314, "author_profile": "https://wordpress.stackexchange.com/users/7314", "pm_score": 0, "selected": false, "text": "<p>The state of checkbox you can know only with JavaScript.\nIn jQuery it could be look like this:</p>\n\n<pre><code>if($(\"input[name=first_option_show]\").not(\":checked\")){\n $(\"input[name=first_option_required]\").attr(\"disabled\",true);\n}\n</code></pre>\n" }, { "answer_id": 175779, "author": "David Gard", "author_id": 10097, "author_profile": "https://wordpress.stackexchange.com/users/10097", "pm_score": 1, "selected": false, "text": "<p>This may be a little overkill for you needs, but I use a bulked up version of this to great effect on my site.</p>\n\n<p>This script will - </p>\n\n<ul>\n<li><p>Check what state the <code>first_option_required</code> option shold be in on page load (and set)</p></li>\n<li><p>Change the state of the <code>first_option_required</code> button upon changes to the <code>first_option_show</code> option. This is managed via an event hadler that will capture changes to the <code>first_option_show</code> option</p></li>\n</ul>\n\n<p>Double check the input names are correct for your needs and then paste the code in to any JS file that is accessible by the page for which you reqire this functionality.</p>\n\n<p><strong>Note</strong> - If you don't already have a JS file that is included and require help enquing on, let us know.</p>\n\n<pre><code>jQuery(function($){\n\n /**\n * Once the document is ready, initialise the 'checkResponses' object\n */\n $(document).ready(function(){\n checkResponses.init();\n });\n\n /**\n * Monitor the change is state to user responses in my form\n */\n checkResponses = {\n\n /**\n * Psuedo constructor\n */\n init : function(){\n this.create_events();\n this.maybe_disable_first_option_required();\n }, // init\n\n /**\n * Create events required for monitoring\n */\n create_events : function(){\n\n var t = this; // This object\n\n $('input[name=first_option_show]').on('change', function(){\n t.maybe_disable_first_option_required();\n });\n\n }, // create_events\n\n /**\n * Check to see if the 'first_option_required' options should be disabled or not\n */\n maybe_disable_first_option_required : function(){\n\n if($('input[name=first_option_show]').is(':checked')){\n alert('Removing...');\n $('input[name=first_option_required]').removeAttr('disabled');\n } else {\n alert('Adding...');\n $('input[name=first_option_required]').attr('disabled', true);\n }\n\n } // maybe_disable_first_option_required\n\n }\n\n});\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175771", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66428/" ]
I'm not sure if this is possible - but checking before re-writing the template. I've extended wp\_query to allow for a geocode/location search to be performed. This is working in itself and returning posts in a nearest to search point first order. In the query generated now by wp\_query it's calculating the distance in miles away from the search point and returning this `AS distance`. My colleague who's built the results template has used ACF - so is looping through the list using: ``` <?php while ( have_posts() ) : the_post(); ?> ``` This 'distance' value is not being returned when using the usual ACF method of `<?php echo the_field('distance'); ?>` which makes sense as it's not an ACF or post field, but rather calculated in the wp\_query... Is there a good way of accessing values from the query, but not ACF fields, inside this ACF loop - or am I better rewriting to manually look through the query results without the ACF methods?
This may be a little overkill for you needs, but I use a bulked up version of this to great effect on my site. This script will - * Check what state the `first_option_required` option shold be in on page load (and set) * Change the state of the `first_option_required` button upon changes to the `first_option_show` option. This is managed via an event hadler that will capture changes to the `first_option_show` option Double check the input names are correct for your needs and then paste the code in to any JS file that is accessible by the page for which you reqire this functionality. **Note** - If you don't already have a JS file that is included and require help enquing on, let us know. ``` jQuery(function($){ /** * Once the document is ready, initialise the 'checkResponses' object */ $(document).ready(function(){ checkResponses.init(); }); /** * Monitor the change is state to user responses in my form */ checkResponses = { /** * Psuedo constructor */ init : function(){ this.create_events(); this.maybe_disable_first_option_required(); }, // init /** * Create events required for monitoring */ create_events : function(){ var t = this; // This object $('input[name=first_option_show]').on('change', function(){ t.maybe_disable_first_option_required(); }); }, // create_events /** * Check to see if the 'first_option_required' options should be disabled or not */ maybe_disable_first_option_required : function(){ if($('input[name=first_option_show]').is(':checked')){ alert('Removing...'); $('input[name=first_option_required]').removeAttr('disabled'); } else { alert('Adding...'); $('input[name=first_option_required]').attr('disabled', true); } } // maybe_disable_first_option_required } }); ```
175,782
<p>I set the content and the wordpress directory of wordpress like described <a href="http://codex.wordpress.org/Editing_wp-config.php" rel="nofollow">in the codex</a>:</p> <pre><code>define('WP_SITEURL', 'https://' . $_SERVER['SERVER_NAME'] . '/wordpress'); define('WP_CONTENT_DIR', dirname(__FILE__) . '/content'); </code></pre> <p>Now what I want to do is set an individual upload directory for every user, like this:</p> <pre><code>wpinstance.org/content/uploads/user-name/here-goes-the-file.jpg </code></pre> <p>I already tried a lot using</p> <pre><code>define( 'UPLOADS', dirname(__FILE__) . '/content/uploads'.$current_user-&gt;user_name.'/'); </code></pre> <p>as well as many combinations without <code>dirname()</code> and so on. It all turned out to take the files up to <code>wordpress/…something</code> and leaving the user name part empty. So how can I achieve this? Any ideas?</p>
[ { "answer_id": 176022, "author": "mcnesium", "author_id": 22572, "author_profile": "https://wordpress.stackexchange.com/users/22572", "pm_score": 4, "selected": true, "text": "<p>With credits to <a href=\"/users/4209/petermolnar\">petermolnar</a> via <code>irc://freenode.net/wordpress</code> I can answer my own question. The key is to set an <code>upload-dir</code> filter in the theme's <code>functions.php</code>:</p>\n\n<pre><code>function per_user_upload_dir( $original ){\n // use the original array for initial setup\n $modified = $original;\n // set our own replacements\n if ( is_user_logged_in() ) {\n $current_user = wp_get_current_user();\n $subdir = $current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n" }, { "answer_id": 325565, "author": "Shohag Malik", "author_id": 159002, "author_profile": "https://wordpress.stackexchange.com/users/159002", "pm_score": 0, "selected": false, "text": "<pre><code>function per_user_upload_dir( $original ){\n // use the original array for initial setup\n $modified = $original;\n // set our own replacements\n if ( is_user_logged_in() ) {\n $current_user = wp_get_current_user();\n $subdir = $current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n\n<p>it's worked for me... but is it possible to make another subfolder for all users, like uploads/users/ ? i want to keep all users content into users folder under the upload directory</p>\n" }, { "answer_id": 400352, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 0, "selected": false, "text": "<p>Nice solution. The uploads folder might get a bit cluttered if many users are uploading. Easy fix is to change:</p>\n<pre><code>$subdir = $current_user-&gt;user_login;\n</code></pre>\n<p>to</p>\n<pre><code>$subdir = 'user_docs/'.$current_user-&gt;user_login;\n</code></pre>\n<p>The modified example below also only does this for a specific role (instructor)</p>\n<pre><code>function per_user_upload_dir( $original ){\n $modified = $original;\n if ( is_user_logged_in() &amp;&amp; current_user_can('instructor') ) {\n $current_user = wp_get_current_user();\n $subdir = 'user_docs/'.$current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175782", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22572/" ]
I set the content and the wordpress directory of wordpress like described [in the codex](http://codex.wordpress.org/Editing_wp-config.php): ``` define('WP_SITEURL', 'https://' . $_SERVER['SERVER_NAME'] . '/wordpress'); define('WP_CONTENT_DIR', dirname(__FILE__) . '/content'); ``` Now what I want to do is set an individual upload directory for every user, like this: ``` wpinstance.org/content/uploads/user-name/here-goes-the-file.jpg ``` I already tried a lot using ``` define( 'UPLOADS', dirname(__FILE__) . '/content/uploads'.$current_user->user_name.'/'); ``` as well as many combinations without `dirname()` and so on. It all turned out to take the files up to `wordpress/…something` and leaving the user name part empty. So how can I achieve this? Any ideas?
With credits to [petermolnar](/users/4209/petermolnar) via `irc://freenode.net/wordpress` I can answer my own question. The key is to set an `upload-dir` filter in the theme's `functions.php`: ``` function per_user_upload_dir( $original ){ // use the original array for initial setup $modified = $original; // set our own replacements if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $subdir = $current_user->user_login; $modified['subdir'] = $subdir; $modified['url'] = $original['baseurl'] . '/' . $subdir; $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir; } return $modified; } add_filter( 'upload_dir', 'per_user_upload_dir'); ```
175,785
<p>I need create a file (any type: json, php, csv, txt) when I create or update a post from WPadmin. The format structure would be:</p> <p>ID, "operation to execute" (new post, update post, delete post), title, field2, field3</p> <p>Thanks! martin</p>
[ { "answer_id": 176022, "author": "mcnesium", "author_id": 22572, "author_profile": "https://wordpress.stackexchange.com/users/22572", "pm_score": 4, "selected": true, "text": "<p>With credits to <a href=\"/users/4209/petermolnar\">petermolnar</a> via <code>irc://freenode.net/wordpress</code> I can answer my own question. The key is to set an <code>upload-dir</code> filter in the theme's <code>functions.php</code>:</p>\n\n<pre><code>function per_user_upload_dir( $original ){\n // use the original array for initial setup\n $modified = $original;\n // set our own replacements\n if ( is_user_logged_in() ) {\n $current_user = wp_get_current_user();\n $subdir = $current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n" }, { "answer_id": 325565, "author": "Shohag Malik", "author_id": 159002, "author_profile": "https://wordpress.stackexchange.com/users/159002", "pm_score": 0, "selected": false, "text": "<pre><code>function per_user_upload_dir( $original ){\n // use the original array for initial setup\n $modified = $original;\n // set our own replacements\n if ( is_user_logged_in() ) {\n $current_user = wp_get_current_user();\n $subdir = $current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n\n<p>it's worked for me... but is it possible to make another subfolder for all users, like uploads/users/ ? i want to keep all users content into users folder under the upload directory</p>\n" }, { "answer_id": 400352, "author": "Twinpictures Info", "author_id": 214066, "author_profile": "https://wordpress.stackexchange.com/users/214066", "pm_score": 0, "selected": false, "text": "<p>Nice solution. The uploads folder might get a bit cluttered if many users are uploading. Easy fix is to change:</p>\n<pre><code>$subdir = $current_user-&gt;user_login;\n</code></pre>\n<p>to</p>\n<pre><code>$subdir = 'user_docs/'.$current_user-&gt;user_login;\n</code></pre>\n<p>The modified example below also only does this for a specific role (instructor)</p>\n<pre><code>function per_user_upload_dir( $original ){\n $modified = $original;\n if ( is_user_logged_in() &amp;&amp; current_user_can('instructor') ) {\n $current_user = wp_get_current_user();\n $subdir = 'user_docs/'.$current_user-&gt;user_login;\n $modified['subdir'] = $subdir;\n $modified['url'] = $original['baseurl'] . '/' . $subdir;\n $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir;\n }\n return $modified;\n}\nadd_filter( 'upload_dir', 'per_user_upload_dir');\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47361/" ]
I need create a file (any type: json, php, csv, txt) when I create or update a post from WPadmin. The format structure would be: ID, "operation to execute" (new post, update post, delete post), title, field2, field3 Thanks! martin
With credits to [petermolnar](/users/4209/petermolnar) via `irc://freenode.net/wordpress` I can answer my own question. The key is to set an `upload-dir` filter in the theme's `functions.php`: ``` function per_user_upload_dir( $original ){ // use the original array for initial setup $modified = $original; // set our own replacements if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $subdir = $current_user->user_login; $modified['subdir'] = $subdir; $modified['url'] = $original['baseurl'] . '/' . $subdir; $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir; } return $modified; } add_filter( 'upload_dir', 'per_user_upload_dir'); ```
175,793
<p>The goal is to grab the first video (embed or shortcode) from the post. So we need to check post content if it has embedded videos ( supported by WP ) or [video] shortcodes. Multiple videos and embeds could exist in the single post. If found any - return the very first of them, not depending on order of given patterns to match, but on order they have been inserted into the post. </p> <p>Here is my progress so far...</p> <p>This one returns first [video] shortcode. Is there a way to make it look for not only video shortcodes, but for embeds also?</p> <pre><code>function theme_self_hosted_videos() { global $post; $pattern = get_shortcode_regex(); if ( preg_match_all( '/'. $pattern .'/s', $post-&gt;post_content, $matches ) &amp;&amp; array_key_exists( 2, $matches ) &amp;&amp; in_array( 'video', $matches[2] ) ) { $videos = $matches[0]; $i = 0; foreach ($videos as $video ) { if($i == 0) { echo do_shortcode($video); } $i++; } } return false; } add_action( 'wp', 'theme_self_hosted_videos' ); </code></pre> <p>Here's my current progress of a function to return first video embed from the post. Not working as expected, though. Obviously depends on $pattern_array order and maybe on the patterns themselves...</p> <pre><code>function theme_oembed_videos() { global $post; // Here is a sample array of patterns for supported video embeds from wp-includes/class-wp-embed.php $pattern_array = array( '#https://youtu\.be/.*#i', '#https://(www\.)?youtube\.com/playlist.*#i', '#https://(www\.)?youtube\.com/watch.*#i', '#http://(www\.)?youtube\.com/watch.*#i', '#http://(www\.)?youtube\.com/playlist.*#i', '#http://youtu\.be/.*#i', '#https?://wordpress.tv/.*#i', '#https?://(.+\.)?vimeo\.com/.*#i' ); foreach ($pattern_array as $pattern) { if (preg_match_all($pattern, $post-&gt;post_content, $matches)) { return wp_oembed_get( $matches[0] ); } return false; } } </code></pre>
[ { "answer_id": 175795, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": false, "text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/functions/get_media_embedded_in_content/\" rel=\"noreferrer\"><code>get_media_embedded_in_content()</code></a> function for both shortcode and embedded media (it looks for these HTML tags: audio, video, object, embed, or iframe), just be sure to use content with applied filters and shortcode executed.</p>\n\n<p>For example:</p>\n\n<pre><code>$post_id = 125;\n$post = get_post($post_id);\n\n//Get the content, apply filters and execute shortcodes\n$content = apply_filters( 'the_content', $post-&gt;post_content );\n$embeds = get_media_embedded_in_content( $content );\n\n//$embeds is an array and each item is the HTML of an embedded media.\n//The first item of the array is the first embedded media in the content\n$fist_embedded = $embeds[0];\n</code></pre>\n\n<p>Addapting te above code to a function similar to yours:</p>\n\n<pre><code>function get_first_embed_media($post_id) {\n\n $post = get_post($post_id);\n $content = do_shortcode( apply_filters( 'the_content', $post-&gt;post_content ) );\n $embeds = get_media_embedded_in_content( $content );\n\n if( !empty($embeds) ) {\n //return first embed\n return $embeds[0];\n\n } else {\n //No embeds found\n return false;\n }\n\n}\n</code></pre>\n\n<p>To limit videos only you could do something like this:</p>\n\n<pre><code>function get_first_embed_media($post_id) {\n\n $post = get_post($post_id);\n $content = do_shortcode( apply_filters( 'the_content', $post-&gt;post_content ) );\n $embeds = get_media_embedded_in_content( $content );\n\n if( !empty($embeds) ) {\n //check what is the first embed containg video tag, youtube or vimeo\n foreach( $embeds as $embed ) {\n if( strpos( $embed, 'video' ) || strpos( $embed, 'youtube' ) || strpos( $embed, 'vimeo' ) ) {\n return $embed;\n }\n }\n\n } else {\n //No video embedded found\n return false;\n }\n\n}\n</code></pre>\n\n<p><strong>Note:</strong> <a href=\"https://core.trac.wordpress.org/ticket/26675\" rel=\"noreferrer\">There was a bug in <code>get_media_embedded_in_content()</code> that made this answer not working as expected</a> bellow WP 4.2.</p>\n" }, { "answer_id": 175844, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 3, "selected": true, "text": "<p>You could try mashing all the patterns together in one big regexp or and then doing a simple line by line parse of the content:</p>\n\n<pre><code>function theme_oembed_videos() {\n\n global $post;\n\n if ( $post &amp;&amp; $post-&gt;post_content ) {\n\n global $shortcode_tags;\n // Make a copy of global shortcode tags - we'll temporarily overwrite it.\n $theme_shortcode_tags = $shortcode_tags;\n\n // The shortcodes we're interested in.\n $shortcode_tags = array(\n 'video' =&gt; $theme_shortcode_tags['video'],\n 'embed' =&gt; $theme_shortcode_tags['embed']\n );\n // Get the absurd shortcode regexp.\n $video_regex = '#' . get_shortcode_regex() . '#i';\n\n // Restore global shortcode tags.\n $shortcode_tags = $theme_shortcode_tags;\n\n $pattern_array = array( $video_regex );\n\n // Get the patterns from the embed object.\n if ( ! function_exists( '_wp_oembed_get_object' ) ) {\n include ABSPATH . WPINC . '/class-oembed.php';\n }\n $oembed = _wp_oembed_get_object();\n $pattern_array = array_merge( $pattern_array, array_keys( $oembed-&gt;providers ) );\n\n // Or all the patterns together.\n $pattern = '#(' . array_reduce( $pattern_array, function ( $carry, $item ) {\n if ( strpos( $item, '#' ) === 0 ) {\n // Assuming '#...#i' regexps.\n $item = substr( $item, 1, -2 );\n } else {\n // Assuming glob patterns.\n $item = str_replace( '*', '(.+)', $item );\n }\n return $carry ? $carry . ')|(' . $item : $item;\n } ) . ')#is';\n\n // Simplistic parse of content line by line.\n $lines = explode( \"\\n\", $post-&gt;post_content );\n foreach ( $lines as $line ) {\n $line = trim( $line );\n if ( preg_match( $pattern, $line, $matches ) ) {\n if ( strpos( $matches[0], '[' ) === 0 ) {\n $ret = do_shortcode( $matches[0] );\n } else {\n $ret = wp_oembed_get( $matches[0] );\n }\n return $ret;\n }\n }\n }\n}\n</code></pre>\n\n<p>Also you might want to use transients for the embeds - see <a href=\"https://wordpress.stackexchange.com/a/175427/57034\">this answer</a> I gave.</p>\n" }, { "answer_id": 405253, "author": "Antony Gibbs", "author_id": 93359, "author_profile": "https://wordpress.stackexchange.com/users/93359", "pm_score": 0, "selected": false, "text": "<p>Based on @cybmeta answer, improved it a little bit and though I would share</p>\n<pre class=\"lang-php prettyprint-override\"><code>function get_first_embed_media($post_id, $regex_filter = null)\n{\n $post = get_post($post_id);\n $content = do_shortcode(apply_filters('the_content', $post-&gt;post_content));\n $embeds = get_media_embedded_in_content($content);\n\n if (!empty($embeds)) {\n // Loop\n foreach ($embeds as $embed) {\n if (\n $regex_filter == null ||\n preg_match($regex_filter, $embed)\n ) {\n return $embed;\n }\n }\n }\n \n // No matching embedded found\n return false;\n}\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>$first_video = get_first_embed_media(1234, '/video|youtube|vimeo/')\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31277/" ]
The goal is to grab the first video (embed or shortcode) from the post. So we need to check post content if it has embedded videos ( supported by WP ) or [video] shortcodes. Multiple videos and embeds could exist in the single post. If found any - return the very first of them, not depending on order of given patterns to match, but on order they have been inserted into the post. Here is my progress so far... This one returns first [video] shortcode. Is there a way to make it look for not only video shortcodes, but for embeds also? ``` function theme_self_hosted_videos() { global $post; $pattern = get_shortcode_regex(); if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) && array_key_exists( 2, $matches ) && in_array( 'video', $matches[2] ) ) { $videos = $matches[0]; $i = 0; foreach ($videos as $video ) { if($i == 0) { echo do_shortcode($video); } $i++; } } return false; } add_action( 'wp', 'theme_self_hosted_videos' ); ``` Here's my current progress of a function to return first video embed from the post. Not working as expected, though. Obviously depends on $pattern\_array order and maybe on the patterns themselves... ``` function theme_oembed_videos() { global $post; // Here is a sample array of patterns for supported video embeds from wp-includes/class-wp-embed.php $pattern_array = array( '#https://youtu\.be/.*#i', '#https://(www\.)?youtube\.com/playlist.*#i', '#https://(www\.)?youtube\.com/watch.*#i', '#http://(www\.)?youtube\.com/watch.*#i', '#http://(www\.)?youtube\.com/playlist.*#i', '#http://youtu\.be/.*#i', '#https?://wordpress.tv/.*#i', '#https?://(.+\.)?vimeo\.com/.*#i' ); foreach ($pattern_array as $pattern) { if (preg_match_all($pattern, $post->post_content, $matches)) { return wp_oembed_get( $matches[0] ); } return false; } } ```
You could try mashing all the patterns together in one big regexp or and then doing a simple line by line parse of the content: ``` function theme_oembed_videos() { global $post; if ( $post && $post->post_content ) { global $shortcode_tags; // Make a copy of global shortcode tags - we'll temporarily overwrite it. $theme_shortcode_tags = $shortcode_tags; // The shortcodes we're interested in. $shortcode_tags = array( 'video' => $theme_shortcode_tags['video'], 'embed' => $theme_shortcode_tags['embed'] ); // Get the absurd shortcode regexp. $video_regex = '#' . get_shortcode_regex() . '#i'; // Restore global shortcode tags. $shortcode_tags = $theme_shortcode_tags; $pattern_array = array( $video_regex ); // Get the patterns from the embed object. if ( ! function_exists( '_wp_oembed_get_object' ) ) { include ABSPATH . WPINC . '/class-oembed.php'; } $oembed = _wp_oembed_get_object(); $pattern_array = array_merge( $pattern_array, array_keys( $oembed->providers ) ); // Or all the patterns together. $pattern = '#(' . array_reduce( $pattern_array, function ( $carry, $item ) { if ( strpos( $item, '#' ) === 0 ) { // Assuming '#...#i' regexps. $item = substr( $item, 1, -2 ); } else { // Assuming glob patterns. $item = str_replace( '*', '(.+)', $item ); } return $carry ? $carry . ')|(' . $item : $item; } ) . ')#is'; // Simplistic parse of content line by line. $lines = explode( "\n", $post->post_content ); foreach ( $lines as $line ) { $line = trim( $line ); if ( preg_match( $pattern, $line, $matches ) ) { if ( strpos( $matches[0], '[' ) === 0 ) { $ret = do_shortcode( $matches[0] ); } else { $ret = wp_oembed_get( $matches[0] ); } return $ret; } } } } ``` Also you might want to use transients for the embeds - see [this answer](https://wordpress.stackexchange.com/a/175427/57034) I gave.
175,806
<p>We are managing the sales, subscriptions and customer profiles/accounts to our products via WP 4.1. The subscriptions are to products on a separate server with .NET. After a customer makes a purchase on the WP side, we'd like to push the customer account details (i.e. user name, password, etc.) to the .NET application and these credentials will be used to log into the .NET app. The challenge that I'm running into is how to duplicate on the .NET side the same hash method used in WP. I know that WP uses PHPass (<a href="http://www.openwall.com/phpass/" rel="nofollow">http://www.openwall.com/phpass/</a>) to hash the passwords, but there isn't a library available for .NET.</p> <p>A couple of questions:</p> <ol> <li><p>Is there an "easy" solution to this, to being able to duplicate the hash method on the .NET side?</p></li> <li><p>Is SECURE_AUTH_SALT the salt used for generating the password hash? We have SSL enabled.</p></li> </ol> <p>One possible solution could be to "degrade" the hash method on the WP side to just a simple MD5 hash using a salt, a method I could then easily duplicate on the .NET side and accomplished as described here <a href="https://wordpress.stackexchange.com/questions/90373/how-can-i-change-the-default-wordpress-password-hashing-system-to-something-cust">How can I change the default wordpress password hashing system to something custom?</a> Thoughts on this?</p>
[ { "answer_id": 194526, "author": "maxkoryukov", "author_id": 76217, "author_profile": "https://wordpress.stackexchange.com/users/76217", "pm_score": 2, "selected": false, "text": "<p>Here is the library: <a href=\"http://www.zer7.com/software/cryptsharp\" rel=\"nofollow\">http://www.zer7.com/software/cryptsharp</a></p>\n\n<p>And this is \"howtouse\":</p>\n\n<pre><code> public override bool ValidateUser(string name, string password)\n {\n if (string.IsNullOrWhiteSpace(name))\n return false;\n if (string.IsNullOrWhiteSpace(password))\n return false;\n\n // this is just fetching the hash from the WP-database using BLToolkit. You can use any other way to get the hash from db ;)\n UserData ud = null;\n using (Db db = new Db())\n {\n db.SetCommand(@\"SELECT id, user_pass FROM wp_users WHERE user_login=@user_login AND user_status=0\",\n db.Parameter(\"user_login\", name)\n );\n\n ud = db.ExecuteObject&lt;UserData&gt;();\n\n }\n\n if (null == ud)\n return false;\n // !!!! HERE IS CHECKING !!!\n // LIB USAGE:\n return CryptSharp.PhpassCrypter.CheckPassword(password, ud.user_pass);\n }\n</code></pre>\n\n<p>This code is a part of custom MembershipProvider.</p>\n" }, { "answer_id": 194876, "author": "skjoshi", "author_id": 36813, "author_profile": "https://wordpress.stackexchange.com/users/36813", "pm_score": 1, "selected": false, "text": "<p>I have been also in similar condition as OP and I have been using solution in the reference provided by @AndrewBartel. This solution is targeted at phpBB.</p>\n\n<p>I am explaining the format for the hashed password (<a href=\"https://pythonhosted.org/passlib/lib/passlib.hash.phpass.html#format\" rel=\"nofollow\">Taken from here</a>):</p>\n\n<blockquote>\n <p>An example hash (of password) is <code>$P$8ohUJ.1sdFw09/bMaAQPTGDNi2BIUt1</code>. A phpass portable hash string has the format <code>$P$RoundsSaltChecksum</code>, where:</p>\n \n <ul>\n <li><p><code>$P$</code> is the prefix used to identify phpass hashes, following the Modular Crypt Format.\n rounds is a single character encoding a 6-bit integer representing the number of rounds used. This is logarithmic, the real number of rounds is 2^rounds. (in the example, rounds is encoded as 8, or 2**13 iterations).</p></li>\n <li><p>salt is eight characters drawn from <code>[./0-9A-Za-z]</code>, providing a 48-bit salt (<code>ohUJ.1sd</code> in the example).</p></li>\n <li><p>checksum is 22 characters drawn from the same set, encoding the 128-bit checksum (<code>Fw09/bMaAQPTGDNi2BIUt1</code> in the example).</p></li>\n </ul>\n</blockquote>\n\n<p>As mentioned in the note sections:</p>\n\n<blockquote>\n <p>Note that phpBB3 databases uses the alternate prefix $H$, both\n prefixes are recognized by this implementation, and the checksums are\n the same.</p>\n</blockquote>\n\n<p>So, the prefix doesn't affect the checksum of the hash. The changes made by @pdaddy are only changing the prefixes to match the prefix used by Wordpress (same as used in PhPass). Just a point to note here is Wordpress also supports both of the prefixes as can be seen in the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-phpass.php#L129\" rel=\"nofollow\">code here</a>. So, if you want to support both phpBB and Wordpress prefixes, you can change the third line in <code>hashCryptPrivate</code> function as </p>\n\n<pre><code>if ((!genSalt.StartsWith(\"$P$\")) &amp;&amp; (!genSalt.StartsWith(\"$H$\"))) return output;\n</code></pre>\n\n<p>Now, the <code>phpbbCheckHash</code> function should be able to match passwords from both Wordpress and phpBB hashes.</p>\n" }, { "answer_id": 222544, "author": "Fütemire", "author_id": 91580, "author_profile": "https://wordpress.stackexchange.com/users/91580", "pm_score": 0, "selected": false, "text": "<p>For VB.Net users, simply converting the CSharp code to VB with a converter won't work. I believe it has something to do with the difference in the way the RightShift <strong>>></strong> operators work in CSharp compared to VB but I'm not 100% on that. I just know it doesn't work.\nSo.....\nWhat I did was create a CSharp class library that I reference in my VB project.</p>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66482/" ]
We are managing the sales, subscriptions and customer profiles/accounts to our products via WP 4.1. The subscriptions are to products on a separate server with .NET. After a customer makes a purchase on the WP side, we'd like to push the customer account details (i.e. user name, password, etc.) to the .NET application and these credentials will be used to log into the .NET app. The challenge that I'm running into is how to duplicate on the .NET side the same hash method used in WP. I know that WP uses PHPass (<http://www.openwall.com/phpass/>) to hash the passwords, but there isn't a library available for .NET. A couple of questions: 1. Is there an "easy" solution to this, to being able to duplicate the hash method on the .NET side? 2. Is SECURE\_AUTH\_SALT the salt used for generating the password hash? We have SSL enabled. One possible solution could be to "degrade" the hash method on the WP side to just a simple MD5 hash using a salt, a method I could then easily duplicate on the .NET side and accomplished as described here [How can I change the default wordpress password hashing system to something custom?](https://wordpress.stackexchange.com/questions/90373/how-can-i-change-the-default-wordpress-password-hashing-system-to-something-cust) Thoughts on this?
Here is the library: <http://www.zer7.com/software/cryptsharp> And this is "howtouse": ``` public override bool ValidateUser(string name, string password) { if (string.IsNullOrWhiteSpace(name)) return false; if (string.IsNullOrWhiteSpace(password)) return false; // this is just fetching the hash from the WP-database using BLToolkit. You can use any other way to get the hash from db ;) UserData ud = null; using (Db db = new Db()) { db.SetCommand(@"SELECT id, user_pass FROM wp_users WHERE user_login=@user_login AND user_status=0", db.Parameter("user_login", name) ); ud = db.ExecuteObject<UserData>(); } if (null == ud) return false; // !!!! HERE IS CHECKING !!! // LIB USAGE: return CryptSharp.PhpassCrypter.CheckPassword(password, ud.user_pass); } ``` This code is a part of custom MembershipProvider.
175,811
<p>I am trying to allow my editors and admins to click to "Edit Author" as they would "Edit Post" or "Edit [Custom Post Type]" from the admin bar when they are on a page like /authors/jdoe</p> <p>(Note: I do <code>$wp_rewrite-&gt;author_base = 'people'</code> so that my addresses are /people/jdoe ... not sure if that creates any potential issues.)</p> <p>I tried to do this through functions but later read that functions.php is processed too early to get the current template or any variables or IDs from the page content. </p> <pre><code>function add_author_edit_link( $wp_admin_bar ) { if ( is_page_template('author.php') ) { $args = array( 'id' =&gt; 'author-edit', 'title' =&gt; __( 'Edit Person' ), 'href' =&gt; '/wp-admin/user-edit.php?user_id=' . $user-&gt;ID ); $wp_admin_bar-&gt;add_node($args); } // if is_page_template author } add_action( 'admin_bar_menu', 'add_author_edit_link', 500 ); </code></pre> <p>Not sure how to approach this but will appreciate any thoughts. </p> <p>I guess I could try to put it into the page content for certain roles only, but is there no easier way to add something like it to the admin bar? </p>
[ { "answer_id": 175813, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You could try this modification of your code:</p>\n\n<pre><code>function add_author_edit_link( $wp_admin_bar )\n{\n if ( is_author() &amp;&amp; current_user_can( 'add_users' ) )\n {\n $args = array(\n 'id' =&gt; 'author-edit',\n 'title' =&gt; __( 'Edit Author' ),\n 'href' =&gt; admin_url( sprintf( \n 'user-edit.php?user_id=%d',\n get_queried_object_id() \n ) )\n );\n $wp_admin_bar-&gt;add_node($args);\n } \n}\n\nadd_action( 'admin_bar_menu', 'add_author_edit_link', 99 );\n</code></pre>\n\n<p>where we use the <code>get_queried_object_id()</code> function to get the author id.</p>\n\n<p>Notice that you can use the <a href=\"http://codex.wordpress.org/Function_Reference/admin_url\" rel=\"nofollow\"><code>admin_url()</code></a> to get the url to the backend.</p>\n\n<p>I use <a href=\"http://codex.wordpress.org/Function_Reference/is_author\" rel=\"nofollow\"><code>is_author()</code></a> here instead of <code>is_page_template( 'author.php' )</code>.</p>\n\n<p>This <em>Edit Author</em> link might not be relevant for users that can't modify other users, so I added the <code>current_user_can( 'add_users' )</code> check. I couldn't find the <code>edit_users</code> <em>capability</em> so I used <code>add_users</code> instead.</p>\n" }, { "answer_id": 175816, "author": "Ariful Islam", "author_id": 20831, "author_profile": "https://wordpress.stackexchange.com/users/20831", "pm_score": 1, "selected": false, "text": "<p>You might try this: </p>\n\n<pre><code>function add_author_edit_link( $wp_admin_bar ) {\n if ( is_author() &amp;&amp; current_user_can( 'add_users' )) {\n $currentUserID = get_current_user_id();\n $args = array(\n 'id' =&gt; 'author-edit',\n 'title' =&gt; __( 'Edit Person' ),\n 'href' =&gt; '/wp-admin/user-edit.php?user_id=' . $currentUserID\n );\n $wp_admin_bar-&gt;add_node($args);\n }\n}\nadd_action( 'admin_bar_menu', 'add_author_edit_link', 500 );\n</code></pre>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66490/" ]
I am trying to allow my editors and admins to click to "Edit Author" as they would "Edit Post" or "Edit [Custom Post Type]" from the admin bar when they are on a page like /authors/jdoe (Note: I do `$wp_rewrite->author_base = 'people'` so that my addresses are /people/jdoe ... not sure if that creates any potential issues.) I tried to do this through functions but later read that functions.php is processed too early to get the current template or any variables or IDs from the page content. ``` function add_author_edit_link( $wp_admin_bar ) { if ( is_page_template('author.php') ) { $args = array( 'id' => 'author-edit', 'title' => __( 'Edit Person' ), 'href' => '/wp-admin/user-edit.php?user_id=' . $user->ID ); $wp_admin_bar->add_node($args); } // if is_page_template author } add_action( 'admin_bar_menu', 'add_author_edit_link', 500 ); ``` Not sure how to approach this but will appreciate any thoughts. I guess I could try to put it into the page content for certain roles only, but is there no easier way to add something like it to the admin bar?
You could try this modification of your code: ``` function add_author_edit_link( $wp_admin_bar ) { if ( is_author() && current_user_can( 'add_users' ) ) { $args = array( 'id' => 'author-edit', 'title' => __( 'Edit Author' ), 'href' => admin_url( sprintf( 'user-edit.php?user_id=%d', get_queried_object_id() ) ) ); $wp_admin_bar->add_node($args); } } add_action( 'admin_bar_menu', 'add_author_edit_link', 99 ); ``` where we use the `get_queried_object_id()` function to get the author id. Notice that you can use the [`admin_url()`](http://codex.wordpress.org/Function_Reference/admin_url) to get the url to the backend. I use [`is_author()`](http://codex.wordpress.org/Function_Reference/is_author) here instead of `is_page_template( 'author.php' )`. This *Edit Author* link might not be relevant for users that can't modify other users, so I added the `current_user_can( 'add_users' )` check. I couldn't find the `edit_users` *capability* so I used `add_users` instead.
175,818
<p>I have used the <a href="http://www.advancedcustomfields.com" rel="nofollow noreferrer">Advanced Custom Fields</a> plugin to create all the data elements for a company leadership directory page and management bio pages.</p> <p>On the site blog, management will not be posting articles themselves, but it should appear as if they have. I think this practice is referred to as "guest authors" - authors that don't have user accounts in the WordPress site where the content is posted on their behalf by site admins.</p> <p>What I'd like to happen is this:</p> <ol> <li>When a guest author is selected for the post (an <a href="http://www.advancedcustomfields.com/resources/post-object/" rel="nofollow noreferrer">ACF Custom Post Object</a>), output their name. The name should link to the archive page www.example.com/author/john-doe.</li> <li>When a quest author is not selected, default to the site admin's author info.</li> <li>I do NOT want to create ghost user accounts to post as guest authors. (As mentioned, these guest authors have already been defined in detail as part of the team leadership post type in combination with ACF.)</li> </ol> <p>I'm relatively new to WordPress theme development and have been Googling for a way to achieve this. These two posts are the closest I could find to my situation but do not solve what I'm trying to do:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/110355/guest-author-how-can-i-use-custom-fields-to-create-guest-author-link">Guest Author - How can I use custom fields to create guest author link?</a></li> <li><a href="https://wordpress.stackexchange.com/questions/110501/guest-author-how-to-modify-my-custom-function-code-if-the-guest-author-url-wil">Guest Author - How to modify my custom function code if the guest author URL will follow a particular pattern/format?</a></li> </ul> <p>Is this a common practice? If so, can someone direct me to more information? I'd greatly appreciate it!</p> <h1>UPDATE</h1> <p>I’m kinda getting there. So far I’ve managed to write a custom author posts link if a guest author exists.</p> <p>The resulting URL for a post author and guest author now have matching formats …</p> <p>post author ex: www(dot)example.com/author/john-doe guest author ex: www(dot)example.com/author/jane-doe</p> <p>Now I just need to figure out how to hijack the author archive page to display posts from the post author OR the guest author.</p> <p>FUNCTIONS.PHP CODE:</p> <pre><code>add_filter( 'the_author_posts_link', 'custom_author_posts_link' ); function custom_author_posts_link($url) { `global $post; $post_object = get_field('post_author'); if ( $post_object ) { `// GUEST AUTHOR EXISTS - override post object to grab relevant guest author info global $post; $post = $post_object; setup_postdata( $post ); $guest_author_slug = $post-&gt;post_name; $guest_author_name = get_field('team_member_name'); $guest_author_posts_link = site_url() . '/author/' . $guest_author_slug; $guest_url = sprintf( '&lt;a href="%1$s" title="%2$s" rel="author"&gt;%3$s&lt;/a&gt;', esc_url( $guest_author_posts_link ), esc_attr( sprintf( __( 'Posts by %s' ), $guest_author_name ) ), $guest_author_name ); $guest_url = $link; wp_reset_postdata(); // We're done here. Return to main $post object ` } return $url; ` } </code></pre> <h1>UPDATE 2</h1> <p>I've reworked things a bit. Instead of 'hijacking' the author archive page, I've modified the "the_author_posts_link" filter to point to a custom post type, when it's appropriate to do so. Now each of my three author types has an endpoint where I can display their bio and activity.</p> <p>The blog posts use Advanced Custom Fields which have a select pulling in post objects from the two relevant post types, Team Leadership and Guest Contributors.</p> <pre><code>add_filter( 'the_author_posts_link', 'custom_author_posts_link' ); function custom_author_posts_link($url) { global $post; // Check if a post author is defined in the post_author post object. If none is defined, override will not occur and default post author will display $post_object = get_field('post_author'); if ( $post_object ) { // Post author exists. Override post object to grab relevant guest author info. global $post; $post = $post_object; setup_postdata( $post ); $author_type = get_field('author_type'); $author_slug = $post-&gt;post_name; $author_name = get_field('author_name'); // Use the post author type to determine the author link if ( strtolower($author_type) == 'guest contributor' ){ $author_posts_link = site_url() . '/guest-contributor/' . $author_slug; } else { $author_posts_link = site_url() . '/leadership-team/' . $author_slug; } // Format the link to return. This is based off the default filter (See WordPress: https://core.trac. wordpress.org/browser/tags/4.1/src/wp-includes/author-template.php) $guest_url = sprintf( '&lt;a href="%1$s" tit le="%2$s" rel="author"&gt;%3$s&lt;/a&gt;', esc_url( $author_po sts_link ), esc_attr( sprintf( __( 'Posts by %s' ), $author_name ) ), $author_name ); $url = $guest_url; wp_reset_postdata(); // We're done here, return to main $post object } return $url; } </code></pre>
[ { "answer_id": 176219, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>If you want something to behave like a \"normal\" wordpress author then the best thing to do is to create a \"dummy\" account for it, and if you really want disable the possibility to login to it.\nFor any other solution that mimics the functionality in other ways you first need to <strong>fully</strong> understand the functionality you are trying to mimic, and by your own words \"I'm relatively new to WordPress theme development\".... </p>\n" }, { "answer_id": 227719, "author": "user2961664", "author_id": 94611, "author_profile": "https://wordpress.stackexchange.com/users/94611", "pm_score": 1, "selected": false, "text": "<p>You could have saved yourself a ton of work and just used the Co-Authors Plus plugin. It has a guest author function. You do have to set them up, but there is no account/password for them, and they can have author pages. (I am not affiliated with them, just use it on several sites.) </p>\n" } ]
2015/01/23
[ "https://wordpress.stackexchange.com/questions/175818", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66492/" ]
I have used the [Advanced Custom Fields](http://www.advancedcustomfields.com) plugin to create all the data elements for a company leadership directory page and management bio pages. On the site blog, management will not be posting articles themselves, but it should appear as if they have. I think this practice is referred to as "guest authors" - authors that don't have user accounts in the WordPress site where the content is posted on their behalf by site admins. What I'd like to happen is this: 1. When a guest author is selected for the post (an [ACF Custom Post Object](http://www.advancedcustomfields.com/resources/post-object/)), output their name. The name should link to the archive page www.example.com/author/john-doe. 2. When a quest author is not selected, default to the site admin's author info. 3. I do NOT want to create ghost user accounts to post as guest authors. (As mentioned, these guest authors have already been defined in detail as part of the team leadership post type in combination with ACF.) I'm relatively new to WordPress theme development and have been Googling for a way to achieve this. These two posts are the closest I could find to my situation but do not solve what I'm trying to do: * [Guest Author - How can I use custom fields to create guest author link?](https://wordpress.stackexchange.com/questions/110355/guest-author-how-can-i-use-custom-fields-to-create-guest-author-link) * [Guest Author - How to modify my custom function code if the guest author URL will follow a particular pattern/format?](https://wordpress.stackexchange.com/questions/110501/guest-author-how-to-modify-my-custom-function-code-if-the-guest-author-url-wil) Is this a common practice? If so, can someone direct me to more information? I'd greatly appreciate it! UPDATE ====== I’m kinda getting there. So far I’ve managed to write a custom author posts link if a guest author exists. The resulting URL for a post author and guest author now have matching formats … post author ex: www(dot)example.com/author/john-doe guest author ex: www(dot)example.com/author/jane-doe Now I just need to figure out how to hijack the author archive page to display posts from the post author OR the guest author. FUNCTIONS.PHP CODE: ``` add_filter( 'the_author_posts_link', 'custom_author_posts_link' ); function custom_author_posts_link($url) { `global $post; $post_object = get_field('post_author'); if ( $post_object ) { `// GUEST AUTHOR EXISTS - override post object to grab relevant guest author info global $post; $post = $post_object; setup_postdata( $post ); $guest_author_slug = $post->post_name; $guest_author_name = get_field('team_member_name'); $guest_author_posts_link = site_url() . '/author/' . $guest_author_slug; $guest_url = sprintf( '<a href="%1$s" title="%2$s" rel="author">%3$s</a>', esc_url( $guest_author_posts_link ), esc_attr( sprintf( __( 'Posts by %s' ), $guest_author_name ) ), $guest_author_name ); $guest_url = $link; wp_reset_postdata(); // We're done here. Return to main $post object ` } return $url; ` } ``` UPDATE 2 ======== I've reworked things a bit. Instead of 'hijacking' the author archive page, I've modified the "the\_author\_posts\_link" filter to point to a custom post type, when it's appropriate to do so. Now each of my three author types has an endpoint where I can display their bio and activity. The blog posts use Advanced Custom Fields which have a select pulling in post objects from the two relevant post types, Team Leadership and Guest Contributors. ``` add_filter( 'the_author_posts_link', 'custom_author_posts_link' ); function custom_author_posts_link($url) { global $post; // Check if a post author is defined in the post_author post object. If none is defined, override will not occur and default post author will display $post_object = get_field('post_author'); if ( $post_object ) { // Post author exists. Override post object to grab relevant guest author info. global $post; $post = $post_object; setup_postdata( $post ); $author_type = get_field('author_type'); $author_slug = $post->post_name; $author_name = get_field('author_name'); // Use the post author type to determine the author link if ( strtolower($author_type) == 'guest contributor' ){ $author_posts_link = site_url() . '/guest-contributor/' . $author_slug; } else { $author_posts_link = site_url() . '/leadership-team/' . $author_slug; } // Format the link to return. This is based off the default filter (See WordPress: https://core.trac. wordpress.org/browser/tags/4.1/src/wp-includes/author-template.php) $guest_url = sprintf( '<a href="%1$s" tit le="%2$s" rel="author">%3$s</a>', esc_url( $author_po sts_link ), esc_attr( sprintf( __( 'Posts by %s' ), $author_name ) ), $author_name ); $url = $guest_url; wp_reset_postdata(); // We're done here, return to main $post object } return $url; } ```
You could have saved yourself a ton of work and just used the Co-Authors Plus plugin. It has a guest author function. You do have to set them up, but there is no account/password for them, and they can have author pages. (I am not affiliated with them, just use it on several sites.)
175,843
<p>I have a custom post type that have a meta_key <code>custom_meta_sponsored</code> that owns alphabetical values. "X" means post doesn't sponsored. I want to show the archive page in custom order, sponsored first in random order.</p> <p>I use <code>pre_get_posts</code> hook, but it doesn't work as I expected:</p> <pre><code>function custom_loops($query) { if ( is_post_type_archive('my_post_type') ){ $query-&gt;set( 'posts_per_page', 40); $query-&gt;set( 'meta_key', 'custom_meta_sponsored'); $query-&gt;set( 'orderby', 'meta_value rand'); //$query-&gt;set( 'order', 'DESC'); } remove_action( 'pre_get_posts', 'custom_loops' ); } add_action('pre_get_posts', 'custom_loops'); </code></pre> <p>In the result sponsored posts display first and nearly random. I mean sponsored posts in randon by a kind of date order. Newly created posts are always display first. I would like to display sponsored post fully random regardless of creation date. Any idea?</p>
[ { "answer_id": 175853, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 1, "selected": false, "text": "<p>You could use the <code>'posts_orderby'</code> filter:</p>\n\n<pre><code>function custom_loops($query) {\n if ( is_post_type_archive('my_post_type') ){\n $query-&gt;set( 'posts_per_page', 40);\n $query-&gt;set( 'meta_key', 'custom_meta_sponsored');\n $query-&gt;set( 'orderby', 'custom_meta_sponsored');\n $query-&gt;set( 'order', 'DESC');\n add_filter( 'posts_orderby', function ( $orderby, $query ) {\n if ( $query-&gt;get( 'orderby' ) != 'custom_meta_sponsored' ) return $orderby;\n global $wpdb;\n $orderby = $wpdb-&gt;prepare(\n 'CASE WHEN ' . $wpdb-&gt;postmeta . '.meta_value != %s THEN CONCAT(%s, RAND()) ELSE '\n . $wpdb-&gt;posts . '.post_date END ' . $query-&gt;get( 'order' )\n , 'X', 'z'\n );\n return $orderby;\n }, 10, 2 );\n }\n remove_action( 'pre_get_posts', 'custom_loops' );\n}\nadd_action('pre_get_posts', 'custom_loops');\n</code></pre>\n" }, { "answer_id": 178324, "author": "Attila", "author_id": 9909, "author_profile": "https://wordpress.stackexchange.com/users/9909", "pm_score": 0, "selected": false, "text": "<p>Finally I created two loops. With a <code>foreach</code> I go through the main query results <code>$wp_query-&gt;posts</code> and reordering posts.</p>\n\n<p>Thank you.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9909/" ]
I have a custom post type that have a meta\_key `custom_meta_sponsored` that owns alphabetical values. "X" means post doesn't sponsored. I want to show the archive page in custom order, sponsored first in random order. I use `pre_get_posts` hook, but it doesn't work as I expected: ``` function custom_loops($query) { if ( is_post_type_archive('my_post_type') ){ $query->set( 'posts_per_page', 40); $query->set( 'meta_key', 'custom_meta_sponsored'); $query->set( 'orderby', 'meta_value rand'); //$query->set( 'order', 'DESC'); } remove_action( 'pre_get_posts', 'custom_loops' ); } add_action('pre_get_posts', 'custom_loops'); ``` In the result sponsored posts display first and nearly random. I mean sponsored posts in randon by a kind of date order. Newly created posts are always display first. I would like to display sponsored post fully random regardless of creation date. Any idea?
You could use the `'posts_orderby'` filter: ``` function custom_loops($query) { if ( is_post_type_archive('my_post_type') ){ $query->set( 'posts_per_page', 40); $query->set( 'meta_key', 'custom_meta_sponsored'); $query->set( 'orderby', 'custom_meta_sponsored'); $query->set( 'order', 'DESC'); add_filter( 'posts_orderby', function ( $orderby, $query ) { if ( $query->get( 'orderby' ) != 'custom_meta_sponsored' ) return $orderby; global $wpdb; $orderby = $wpdb->prepare( 'CASE WHEN ' . $wpdb->postmeta . '.meta_value != %s THEN CONCAT(%s, RAND()) ELSE ' . $wpdb->posts . '.post_date END ' . $query->get( 'order' ) , 'X', 'z' ); return $orderby; }, 10, 2 ); } remove_action( 'pre_get_posts', 'custom_loops' ); } add_action('pre_get_posts', 'custom_loops'); ```
175,851
<p>Seriously, I lost my whole day with this... Either I completely missed the point... Or I really cannot find the proper information on the internet... </p> <p>Everywhere I find they say to load jQuery in the following way, in my main file of my plugin I do the following</p> <p>This is the wp_enqueue_scripts (with an S) to load the scripts</p> <pre><code>add_action('wp_enqueue_scripts', 'myplugin_load_jquery'); </code></pre> <p>Then you need the function that calls for jQuery (wp_enqueue_script no S for this one).</p> <pre><code>function myplugin_load_jquery(){ wp_enqueue_script('jquery'); }; </code></pre> <p>What am I missing,</p> <p>After doing that, I'm trying to use the following, and it always gives me the message "Call to undefined function jQuery()"</p> <pre><code>jQuery(document).ready(function(){ //Do anything... }); </code></pre> <p>Can anyone finally tell me how to do that properly? In a clear manner? Or point me somewhere with proper and clear information?</p> <p>Do I absolutely need to put my scripts inside a .JS file? Or I can run it from the same file?</p> <p>... Working now... Doing more tests</p>
[ { "answer_id": 175855, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": -1, "selected": false, "text": "<p>You need to make sure jQuery has been loaded, so output your code in a late action, eg for front end you could use <code>'wp_print_footer_scripts'</code> with a large priority:</p>\n\n<pre><code>add_action( 'wp_print_footer_scripts', function () {\n ?&gt;\n &lt;script&gt;\n jQuery(document).ready(function(){\n //Do anything...\n });\n &lt;/script&gt;\n &lt;?php\n}, 50 );\n</code></pre>\n\n<p>Similarly for admin <code>'admin_print_footer_scripts'</code>.</p>\n" }, { "answer_id": 175856, "author": "Daniyal Ahmed", "author_id": 66517, "author_profile": "https://wordpress.stackexchange.com/users/66517", "pm_score": -1, "selected": false, "text": "<p>Simply follow these steps, in my case my plugin name is awesome social icons. </p>\n\n<pre><code> // Step - 1\n&lt;?php\n function register_awesome_social_submenu_page()\n {\n add_submenu_page('options-general.php', 'Awesome Social', 'Awesome Social', 'manage_options', 'awesome-social', 'awesome_social_callback');\n }\n ?&gt;\n // Step - 2\n&lt;?php\nadd_action('admin_menu', 'register_awesome_social_submenu_page');\n?&gt;\n // Step - 3\n\n&lt;?php \nfunction awesome_social_callback()\n{\n wp_enqueue_script('jquery');\n wp_enqueue_script('jquery-form');\n?&gt;\n&lt;script&gt;\n$j=jQuery.noConflict();\n\n $j(document).ready(function(){\n\n// Do what you want :)\n});\n&lt;/script&gt;\n\n&lt;?php\n\n }\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 175874, "author": "paul", "author_id": 1000, "author_profile": "https://wordpress.stackexchange.com/users/1000", "pm_score": 2, "selected": false, "text": "<p>You don't have to specifically enqueue jQuery, as you're probably using jQuery in your custom script. You can do:</p>\n\n<pre><code>wp_enqueue_script( 'my-script', plugin_url( 'js/my-script.js', __FILE__ ), array('jquery') );\n\njQuery(document).ready(function($){\n //Do anything...\n});\n</code></pre>\n\n<p>Notice the $ passed as an arg to the callback, it will make jQuery accessible to your function scope.</p>\n" }, { "answer_id": 175909, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": true, "text": "<p>You need specify jquery as a dependency of your custom script, setting the 3rd parameter of <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script()</a> to <code>array('jquery')</code>, like this:</p>\n\n<pre><code>wp_enqueue_script(\n 'yourCustomScript',\n plugins_url('js/yourCustomScript.js', __FILE__),\n array('jquery'),\n '1.0.0',\n false\n);\n</code></pre>\n\n<p><em>Change the path to point to your custom-script file</em></p>\n\n<p>As to your <strong>last question</strong>, the answer is affirmative. You need a .js file. Basically WP needs to know what scripts are loading in a page to make sure dependencies are loading first and none gets loaded twice.</p>\n\n<p>Also keep in mind that your usual <code>$()</code> alias will not work unless you wrap your code in:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n // Inside of this function, $() will work as an alias for jQuery()\n // and other libraries also using $ will not be accessible under this shortcut\n});\n</code></pre>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers\" rel=\"nofollow\">Refference</a>.</p>\n\n<p>Here's a testing example that should work from inside a custom plugin:</p>\n\n<h3>jquery-test.js:</h3>\n\n<pre><code>jQuery(document).ready(function($) {\n $('&lt;a/&gt;', {\n id: 'foo',\n href: 'https://www.google.com/webhp?q=jquery+mistakes+you+are+probably+making',\n title: 'bar',\n rel: 'external',\n text: 'jQuery\\'s dead! Long live jQuery!',\n style: '' +\n 'position: fixed;' +\n 'top: 120px; ' +\n 'left: 0; ' +\n 'padding: 10px 20px; ' +\n 'background-color: #369; ' +\n 'color: white; ' +\n 'z-index: 9999;' +\n 'border-radius: 0 6px 6px 0'\n })\n .prependTo('body');\n});\n</code></pre>\n\n<p>Put this file in your plugin's <code>/js</code> folder.\nIn your plugin's main file, add this php:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'testing_jquery');\nfunction testing_jquery() {\n if ( ! is_admin()) \n wp_enqueue_script(\n 'testing-jquery',\n plugins_url('js/testing-jquery.js', __FILE__ ),\n ['jquery'],\n true\n );\n}\n</code></pre>\n\n<p>Make sure it's not inside any other function or class. </p>\n\n<p>If you're not adding this via a plugin, but a theme, place the <code>testing-jquery.js</code> file in the theme's <code>/js</code> folder and replace <code>plugins_url('js/testing-jquery.js', __FILE__ ),</code> with <code>get_stylesheet_directory_uri() . '/js/testing-jquery.js',</code></p>\n\n<p>This should add a blue link to a google search for common mistakes when using jQuery to every frontend page of your website.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175851", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66412/" ]
Seriously, I lost my whole day with this... Either I completely missed the point... Or I really cannot find the proper information on the internet... Everywhere I find they say to load jQuery in the following way, in my main file of my plugin I do the following This is the wp\_enqueue\_scripts (with an S) to load the scripts ``` add_action('wp_enqueue_scripts', 'myplugin_load_jquery'); ``` Then you need the function that calls for jQuery (wp\_enqueue\_script no S for this one). ``` function myplugin_load_jquery(){ wp_enqueue_script('jquery'); }; ``` What am I missing, After doing that, I'm trying to use the following, and it always gives me the message "Call to undefined function jQuery()" ``` jQuery(document).ready(function(){ //Do anything... }); ``` Can anyone finally tell me how to do that properly? In a clear manner? Or point me somewhere with proper and clear information? Do I absolutely need to put my scripts inside a .JS file? Or I can run it from the same file? ... Working now... Doing more tests
You need specify jquery as a dependency of your custom script, setting the 3rd parameter of [wp\_enqueue\_script()](http://codex.wordpress.org/Function_Reference/wp_enqueue_script) to `array('jquery')`, like this: ``` wp_enqueue_script( 'yourCustomScript', plugins_url('js/yourCustomScript.js', __FILE__), array('jquery'), '1.0.0', false ); ``` *Change the path to point to your custom-script file* As to your **last question**, the answer is affirmative. You need a .js file. Basically WP needs to know what scripts are loading in a page to make sure dependencies are loading first and none gets loaded twice. Also keep in mind that your usual `$()` alias will not work unless you wrap your code in: ``` jQuery(document).ready(function($) { // Inside of this function, $() will work as an alias for jQuery() // and other libraries also using $ will not be accessible under this shortcut }); ``` [Refference](http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers). Here's a testing example that should work from inside a custom plugin: ### jquery-test.js: ``` jQuery(document).ready(function($) { $('<a/>', { id: 'foo', href: 'https://www.google.com/webhp?q=jquery+mistakes+you+are+probably+making', title: 'bar', rel: 'external', text: 'jQuery\'s dead! Long live jQuery!', style: '' + 'position: fixed;' + 'top: 120px; ' + 'left: 0; ' + 'padding: 10px 20px; ' + 'background-color: #369; ' + 'color: white; ' + 'z-index: 9999;' + 'border-radius: 0 6px 6px 0' }) .prependTo('body'); }); ``` Put this file in your plugin's `/js` folder. In your plugin's main file, add this php: ``` add_action('wp_enqueue_scripts', 'testing_jquery'); function testing_jquery() { if ( ! is_admin()) wp_enqueue_script( 'testing-jquery', plugins_url('js/testing-jquery.js', __FILE__ ), ['jquery'], true ); } ``` Make sure it's not inside any other function or class. If you're not adding this via a plugin, but a theme, place the `testing-jquery.js` file in the theme's `/js` folder and replace `plugins_url('js/testing-jquery.js', __FILE__ ),` with `get_stylesheet_directory_uri() . '/js/testing-jquery.js',` This should add a blue link to a google search for common mistakes when using jQuery to every frontend page of your website.
175,867
<p>I came across <a href="http://blog.g-design.net/post/60019471157/managing-and-deploying-wordpress-with-git" rel="nofollow">this site</a> and I was wondering why WordPress isn't using this as default:</p> <pre><code>define('WP_SITEURL', 'http://' . $_SERVER['SERVER_NAME']); define('WP_HOME', 'http://' . $_SERVER['SERVER_NAME']); </code></pre> <p>So nobody has to change this values when changing the domain. Is there any reason or disadvantages of using this?</p>
[ { "answer_id": 175868, "author": "karpstrucking", "author_id": 55214, "author_profile": "https://wordpress.stackexchange.com/users/55214", "pm_score": 1, "selected": false, "text": "<p>With these constants defined, your WP site will work both with and without the preceding www. (as well as on any other URLs that correctly resolve to the site, like hosting-provided staging URLs, etc), which search engines will penalize as duplicate content.</p>\n" }, { "answer_id": 412057, "author": "Abu Nabil", "author_id": 228270, "author_profile": "https://wordpress.stackexchange.com/users/228270", "pm_score": 0, "selected": false, "text": "<p>There are a few reasons why WordPress does not use <code>$_SERVER['SERVER_NAME']</code> as the default value for <code>WP_SITEURL</code> and <code>WP_HOME</code>.</p>\n<p>Firstly, <code>$_SERVER['SERVER_NAME']</code> only returns the hostname of the server, not the full URL of the WordPress site. For example, if your WordPress site is installed in a subdirectory (e.g. <code>http://example.com/blog</code>), <code>$_SERVER['SERVER_NAME']</code> will only return <code>example.com</code>, not the full URL of the site. In this case, using <code>$_SERVER['SERVER_NAME']</code> as the default value for <code>WP_SITEURL</code> and <code>WP_HOME</code> would cause the URLs of your site to be incorrect.</p>\n<p>Secondly, using <code>$_SERVER['SERVER_NAME']</code> as the default value for <code>WP_SITEURL</code> and <code>WP_HOME</code> can cause problems if your site is accessed through multiple hostnames or aliases (e.g. if you have multiple domains or subdomains pointing to the same WordPress installation). In this case, using <code>$_SERVER['SERVER_NAME']</code> as the default value would cause WordPress to use only one of the hostnames or aliases, which may not be the one you want to use as the primary URL for your site.</p>\n<p>For these reasons, WordPress does not use <code>$_SERVER['SERVER_NAME']</code> as the default value for <code>WP_SITEURL</code> and <code>WP_HOME</code>. Instead, it uses the default values of <code>http://localhost</code> for <code>WP_SITEURL</code> and <code>http://localhost/wp</code> for <code>WP_HOME</code>, which can be changed by setting the values of these constants in the <code>wp-config.php</code> file. This allows you to specify the correct URLs for your site, regardless of whether it is installed in a subdirectory, accessed through multiple hostnames or aliases, or hosted on a server with a different hostname.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65855/" ]
I came across [this site](http://blog.g-design.net/post/60019471157/managing-and-deploying-wordpress-with-git) and I was wondering why WordPress isn't using this as default: ``` define('WP_SITEURL', 'http://' . $_SERVER['SERVER_NAME']); define('WP_HOME', 'http://' . $_SERVER['SERVER_NAME']); ``` So nobody has to change this values when changing the domain. Is there any reason or disadvantages of using this?
With these constants defined, your WP site will work both with and without the preceding www. (as well as on any other URLs that correctly resolve to the site, like hosting-provided staging URLs, etc), which search engines will penalize as duplicate content.
175,878
<p>I discovered that I have 29,000 cron jobs in my WordPress database from deactivated and deleted plugins. I have tried a number of optimizer plugins but the huge number of cron jobs means I can't delete them using plugins.</p> <p>I also tried this in my functions.php without success:</p> <pre><code>add_action("init", "clear_crons_left"); function clear_crons_left() { wp_clear_scheduled_hook("cron_name"); } </code></pre> <p>Is there any SQL command I can use in phpmyadmin to search by cron hook and remove them? </p>
[ { "answer_id": 175880, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 3, "selected": false, "text": "<p>Try </p>\n\n<pre><code>SELECT * FROM `wp_options` WHERE option_name = 'cron'\n</code></pre>\n\n<p>If you find it you might try:</p>\n\n<ul>\n<li>In SQL: <code>UPDATE wp_options SET option_value = '' WHERE option_name = 'cron'</code></li>\n<li>In wordpress: <code>update_option('cron', '');</code></li>\n</ul>\n\n<p>You might need to either delete the cron option or set the value to an empty serialized array. </p>\n\n<p>Using update_option would be safer as I'm not certain as to whether the value should be a serialized empty array or an empty string. You could check in wp-includes/options.php though ... but using update_option will handle it properly without worrying about the database.</p>\n" }, { "answer_id": 176678, "author": "Pádraig Ó Beirn", "author_id": 66530, "author_profile": "https://wordpress.stackexchange.com/users/66530", "pm_score": 5, "selected": true, "text": "<p>Thanks Privateer for the prompt reply and advice.</p>\n\n<p>I found a way around it before I saw your answer. Here is a step-by-step method for deleting thousands of old cron jobs and may be of use to someone else.</p>\n\n<p>I logged on to phpMyAdmin. I clicked on my database and then the 'search' tab. I typed in 'cron' then selected 'all tables' and clicked 'Go'. I scrolled down the search results list to my wp_options table. I clicked 'Browse'. At the top of the list was option_name 'cron'. I clicked 'Edit' then waited for the page to load. I clicked on the box that showed the list of cron jobs. The cron list was so long that it took about 80 seconds for my cursor to respond. I then used Ctrl-A on the keyboard to select all before hitting the delete button. It took about 2 minutes before my browser completed the deletion (chrome timed-out so I tried Firefox which worked).</p>\n\n<p>After another couple of minutes the cron jobs for my current active plugins re-populated the list. There were 9 cron jobs (down from over 29,000!). Six years of duplicate cron jobs from badly coded plugins, some of which I just installed for a day to try out. Also hundreds from common plugins such as Wordfence, BackupBuddy, Nextgen Gallery, and AutoOptimizer - all of which I had uninstalled in the past. My site now loads like it's been turbo-charged. The admin area is much quicker. Admin timeout errors have disappeared. I had spent so much time on optimising my website trying to decrease the load time. I even moved hosts and upgraded my hosting plans. Nothing increased the speed of my site like deleting all the outdated cron jobs. Mobile download time decreased from 20 seconds to 6 seconds. Desktop download time decreased from about 12 to 4 seconds. </p>\n\n<p>In my search for a solution I found very little information on the effect of cron jobs on website performance. Many said it made little difference and for a small number of cron jobs that's true. But years into the life of a WordPress site I wonder how many are bloated with hundreds if not thousands of old cron jobs from deleted plugins. Instead of asking users to check their php memory limit I would suggest that developers first ask users to check the number of cron jobs in wp_options when problem-solving fatal memory errors. You may be surprised/shocked at what you find! :-) </p>\n" }, { "answer_id": 205127, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 3, "selected": false, "text": "<p>An even simpler solution is to call <code>delete_option( 'cron' );</code> once in some plugin. All automatically added cron jobs will get added again on the next visit/request of your site.</p>\n\n<p>As a one case (mu) plugin that only runs whenever you activate it:</p>\n\n<pre><code>&lt;?php\n/** Plugin Name: Clean Cron */\nregister_activation_hook( __FILE__, function()\n{\n delete_option( 'cron' );\n} );\n</code></pre>\n" }, { "answer_id": 235423, "author": "Indivision Dev", "author_id": 100705, "author_profile": "https://wordpress.stackexchange.com/users/100705", "pm_score": 2, "selected": false, "text": "<p>In case someone wanted to clear a specific cron name (say 'CRON_NAME'), this solution worked for me:</p>\n\n<pre><code> $crons = _get_cron_array();\n //echo \"Found total \".count($crons).\"&lt;br /&gt;\";\n //Keep only the ones that don't match the cron name\n $updated = array_filter($crons, function($v){return !array_key_exists(\"CRON_NAME\",$v);});\n //echo \"Reduced to \".count($updated).\"&lt;br /&gt;\"; \n _set_cron_array($updated);\n</code></pre>\n" }, { "answer_id": 252142, "author": "Preetinder Singh", "author_id": 110727, "author_profile": "https://wordpress.stackexchange.com/users/110727", "pm_score": 2, "selected": false, "text": "<p>I had an year full of pending cron jobs, about 5 Mb data for this single database entry. Deleted the cron jobs from the database. Disabled cron jobs in wp-config.php</p>\n\n<p>Set up a manual cron job in cpanel. Now my site is literally flying. I had been upgrading servers, buying more CPU/RAM, but all was a waste of money and time.</p>\n\n<p>To delete all pending cron jobs run this query in phpmyadmin>Run query:</p>\n\n<pre><code>UPDATE wp_options SET option_value = '' WHERE option_name = 'cron'\n</code></pre>\n\n<p>Thanks a lot Pádraig Ó Beirn.</p>\n" }, { "answer_id": 255832, "author": "Paul Wenzel", "author_id": 14356, "author_profile": "https://wordpress.stackexchange.com/users/14356", "pm_score": 4, "selected": false, "text": "<p>Wordpress cron events can also be cleared from the command line, using <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">WP-CLI</a>:</p>\n\n<pre><code>wp cron event list\nwp cron event delete your_example_event\n</code></pre>\n\n<p>More details in the <a href=\"https://wp-cli.org/commands/cron/event/delete/\" rel=\"noreferrer\">wp-cli docs</a>.</p>\n" }, { "answer_id": 269171, "author": "Rebecca", "author_id": 118084, "author_profile": "https://wordpress.stackexchange.com/users/118084", "pm_score": 0, "selected": false, "text": "<p>If you clear your cron tasks this way and you use UpdraftPlus, you will need to re-save your settings in order to regenerate the cron tasks. Until you do this, your automated backups will not run (but manual backups will).</p>\n\n<p>The settings will still be there, and you don't need to edit anything. Just go to [UpdraftPlus top menu]->Settings, and the scroll down to the bottom and click \"Save Changes\". </p>\n" }, { "answer_id": 307124, "author": "Sitezilla", "author_id": 143362, "author_profile": "https://wordpress.stackexchange.com/users/143362", "pm_score": 0, "selected": false, "text": "<p>I got here because of the huge amount of <code>sm_ping</code> cronjobs in <code>wp_options</code>. If that is your problem, you could try the following : </p>\n\n<p>Put this in functions.php (child theme) if you don't have access to phpmyadmin, especially if your site is bloated with ping cronjobs (sm_ping) : </p>\n\n<pre><code>if (isset($_GET['doing_wp_cron'])) {\nremove_action('do_pings', 'do_all_pings');\nwp_clear_scheduled_hook('do_pings');\n}\n</code></pre>\n" }, { "answer_id": 320061, "author": "David F. Carr", "author_id": 108454, "author_profile": "https://wordpress.stackexchange.com/users/108454", "pm_score": 2, "selected": false, "text": "<p>I ran into a similar issue, where because of one of my own coding errors, thousands of copies of one particular cron job had been added to a site. The wp_clear_scheduled_hook function appeared to time out and fail. I got around it with a script that unset all instances of the cron function within the array and then adds the filtered array as the new cron option in the options table. See below.</p>\n\n<p>In this way, I avoided blowing away the desirable cron jobs previously added to the site.</p>\n\n<p>This could be modified as a function that takes an array of handles to eliminate or an array of handles to be preserved.</p>\n\n<pre><code>$crons = _get_cron_array();\n $hook = 'tj_flush_w3tc_cache';\n foreach ( $crons as $timestamp =&gt; $cron ) {\n if ( isset( $cron[ $hook ] ) ) {\n unset($cron[$hook]);\n }\n if(!empty($cron))\n $newcron[$timestamp] = $cron; \n }\n update_option('cron',$newcron);\n</code></pre>\n" }, { "answer_id": 330074, "author": "Windy", "author_id": 162124, "author_profile": "https://wordpress.stackexchange.com/users/162124", "pm_score": 1, "selected": false, "text": "<p>I have a way very simple to delete all cron events.\nBefore, you need to DISABLE WP Cron in wp-config\nThen, you install Plugin WP Control\nThen, Move to Tool menu > Cron events > Click chose all > Delete all of them.\nCould you try it.\nThanks.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66530/" ]
I discovered that I have 29,000 cron jobs in my WordPress database from deactivated and deleted plugins. I have tried a number of optimizer plugins but the huge number of cron jobs means I can't delete them using plugins. I also tried this in my functions.php without success: ``` add_action("init", "clear_crons_left"); function clear_crons_left() { wp_clear_scheduled_hook("cron_name"); } ``` Is there any SQL command I can use in phpmyadmin to search by cron hook and remove them?
Thanks Privateer for the prompt reply and advice. I found a way around it before I saw your answer. Here is a step-by-step method for deleting thousands of old cron jobs and may be of use to someone else. I logged on to phpMyAdmin. I clicked on my database and then the 'search' tab. I typed in 'cron' then selected 'all tables' and clicked 'Go'. I scrolled down the search results list to my wp\_options table. I clicked 'Browse'. At the top of the list was option\_name 'cron'. I clicked 'Edit' then waited for the page to load. I clicked on the box that showed the list of cron jobs. The cron list was so long that it took about 80 seconds for my cursor to respond. I then used Ctrl-A on the keyboard to select all before hitting the delete button. It took about 2 minutes before my browser completed the deletion (chrome timed-out so I tried Firefox which worked). After another couple of minutes the cron jobs for my current active plugins re-populated the list. There were 9 cron jobs (down from over 29,000!). Six years of duplicate cron jobs from badly coded plugins, some of which I just installed for a day to try out. Also hundreds from common plugins such as Wordfence, BackupBuddy, Nextgen Gallery, and AutoOptimizer - all of which I had uninstalled in the past. My site now loads like it's been turbo-charged. The admin area is much quicker. Admin timeout errors have disappeared. I had spent so much time on optimising my website trying to decrease the load time. I even moved hosts and upgraded my hosting plans. Nothing increased the speed of my site like deleting all the outdated cron jobs. Mobile download time decreased from 20 seconds to 6 seconds. Desktop download time decreased from about 12 to 4 seconds. In my search for a solution I found very little information on the effect of cron jobs on website performance. Many said it made little difference and for a small number of cron jobs that's true. But years into the life of a WordPress site I wonder how many are bloated with hundreds if not thousands of old cron jobs from deleted plugins. Instead of asking users to check their php memory limit I would suggest that developers first ask users to check the number of cron jobs in wp\_options when problem-solving fatal memory errors. You may be surprised/shocked at what you find! :-)
175,881
<p>I'm stuck on loading page content by id (through a plugin). What I have is the following:</p> <pre><code>&lt;?php $my_query = new WP_Query('page_id=39'); ?&gt; &lt;?php while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>Instead of entering the id "39" though, it needs to come from $user_set_value</p> <p>I'm able to echo the id like this: </p> <pre><code>&lt;?php global $wp_query; $postid = $wp_query-&gt;post-&gt;ID; echo get_post_meta($postid, 'user_set_value', true); wp_reset_query(); ?&gt; </code></pre> <p>..but how could I go about echoing $user_set_value into the first snippet so it would get the id on the fly?</p> <p>Many thanks!</p>
[ { "answer_id": 175880, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 3, "selected": false, "text": "<p>Try </p>\n\n<pre><code>SELECT * FROM `wp_options` WHERE option_name = 'cron'\n</code></pre>\n\n<p>If you find it you might try:</p>\n\n<ul>\n<li>In SQL: <code>UPDATE wp_options SET option_value = '' WHERE option_name = 'cron'</code></li>\n<li>In wordpress: <code>update_option('cron', '');</code></li>\n</ul>\n\n<p>You might need to either delete the cron option or set the value to an empty serialized array. </p>\n\n<p>Using update_option would be safer as I'm not certain as to whether the value should be a serialized empty array or an empty string. You could check in wp-includes/options.php though ... but using update_option will handle it properly without worrying about the database.</p>\n" }, { "answer_id": 176678, "author": "Pádraig Ó Beirn", "author_id": 66530, "author_profile": "https://wordpress.stackexchange.com/users/66530", "pm_score": 5, "selected": true, "text": "<p>Thanks Privateer for the prompt reply and advice.</p>\n\n<p>I found a way around it before I saw your answer. Here is a step-by-step method for deleting thousands of old cron jobs and may be of use to someone else.</p>\n\n<p>I logged on to phpMyAdmin. I clicked on my database and then the 'search' tab. I typed in 'cron' then selected 'all tables' and clicked 'Go'. I scrolled down the search results list to my wp_options table. I clicked 'Browse'. At the top of the list was option_name 'cron'. I clicked 'Edit' then waited for the page to load. I clicked on the box that showed the list of cron jobs. The cron list was so long that it took about 80 seconds for my cursor to respond. I then used Ctrl-A on the keyboard to select all before hitting the delete button. It took about 2 minutes before my browser completed the deletion (chrome timed-out so I tried Firefox which worked).</p>\n\n<p>After another couple of minutes the cron jobs for my current active plugins re-populated the list. There were 9 cron jobs (down from over 29,000!). Six years of duplicate cron jobs from badly coded plugins, some of which I just installed for a day to try out. Also hundreds from common plugins such as Wordfence, BackupBuddy, Nextgen Gallery, and AutoOptimizer - all of which I had uninstalled in the past. My site now loads like it's been turbo-charged. The admin area is much quicker. Admin timeout errors have disappeared. I had spent so much time on optimising my website trying to decrease the load time. I even moved hosts and upgraded my hosting plans. Nothing increased the speed of my site like deleting all the outdated cron jobs. Mobile download time decreased from 20 seconds to 6 seconds. Desktop download time decreased from about 12 to 4 seconds. </p>\n\n<p>In my search for a solution I found very little information on the effect of cron jobs on website performance. Many said it made little difference and for a small number of cron jobs that's true. But years into the life of a WordPress site I wonder how many are bloated with hundreds if not thousands of old cron jobs from deleted plugins. Instead of asking users to check their php memory limit I would suggest that developers first ask users to check the number of cron jobs in wp_options when problem-solving fatal memory errors. You may be surprised/shocked at what you find! :-) </p>\n" }, { "answer_id": 205127, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 3, "selected": false, "text": "<p>An even simpler solution is to call <code>delete_option( 'cron' );</code> once in some plugin. All automatically added cron jobs will get added again on the next visit/request of your site.</p>\n\n<p>As a one case (mu) plugin that only runs whenever you activate it:</p>\n\n<pre><code>&lt;?php\n/** Plugin Name: Clean Cron */\nregister_activation_hook( __FILE__, function()\n{\n delete_option( 'cron' );\n} );\n</code></pre>\n" }, { "answer_id": 235423, "author": "Indivision Dev", "author_id": 100705, "author_profile": "https://wordpress.stackexchange.com/users/100705", "pm_score": 2, "selected": false, "text": "<p>In case someone wanted to clear a specific cron name (say 'CRON_NAME'), this solution worked for me:</p>\n\n<pre><code> $crons = _get_cron_array();\n //echo \"Found total \".count($crons).\"&lt;br /&gt;\";\n //Keep only the ones that don't match the cron name\n $updated = array_filter($crons, function($v){return !array_key_exists(\"CRON_NAME\",$v);});\n //echo \"Reduced to \".count($updated).\"&lt;br /&gt;\"; \n _set_cron_array($updated);\n</code></pre>\n" }, { "answer_id": 252142, "author": "Preetinder Singh", "author_id": 110727, "author_profile": "https://wordpress.stackexchange.com/users/110727", "pm_score": 2, "selected": false, "text": "<p>I had an year full of pending cron jobs, about 5 Mb data for this single database entry. Deleted the cron jobs from the database. Disabled cron jobs in wp-config.php</p>\n\n<p>Set up a manual cron job in cpanel. Now my site is literally flying. I had been upgrading servers, buying more CPU/RAM, but all was a waste of money and time.</p>\n\n<p>To delete all pending cron jobs run this query in phpmyadmin>Run query:</p>\n\n<pre><code>UPDATE wp_options SET option_value = '' WHERE option_name = 'cron'\n</code></pre>\n\n<p>Thanks a lot Pádraig Ó Beirn.</p>\n" }, { "answer_id": 255832, "author": "Paul Wenzel", "author_id": 14356, "author_profile": "https://wordpress.stackexchange.com/users/14356", "pm_score": 4, "selected": false, "text": "<p>Wordpress cron events can also be cleared from the command line, using <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">WP-CLI</a>:</p>\n\n<pre><code>wp cron event list\nwp cron event delete your_example_event\n</code></pre>\n\n<p>More details in the <a href=\"https://wp-cli.org/commands/cron/event/delete/\" rel=\"noreferrer\">wp-cli docs</a>.</p>\n" }, { "answer_id": 269171, "author": "Rebecca", "author_id": 118084, "author_profile": "https://wordpress.stackexchange.com/users/118084", "pm_score": 0, "selected": false, "text": "<p>If you clear your cron tasks this way and you use UpdraftPlus, you will need to re-save your settings in order to regenerate the cron tasks. Until you do this, your automated backups will not run (but manual backups will).</p>\n\n<p>The settings will still be there, and you don't need to edit anything. Just go to [UpdraftPlus top menu]->Settings, and the scroll down to the bottom and click \"Save Changes\". </p>\n" }, { "answer_id": 307124, "author": "Sitezilla", "author_id": 143362, "author_profile": "https://wordpress.stackexchange.com/users/143362", "pm_score": 0, "selected": false, "text": "<p>I got here because of the huge amount of <code>sm_ping</code> cronjobs in <code>wp_options</code>. If that is your problem, you could try the following : </p>\n\n<p>Put this in functions.php (child theme) if you don't have access to phpmyadmin, especially if your site is bloated with ping cronjobs (sm_ping) : </p>\n\n<pre><code>if (isset($_GET['doing_wp_cron'])) {\nremove_action('do_pings', 'do_all_pings');\nwp_clear_scheduled_hook('do_pings');\n}\n</code></pre>\n" }, { "answer_id": 320061, "author": "David F. Carr", "author_id": 108454, "author_profile": "https://wordpress.stackexchange.com/users/108454", "pm_score": 2, "selected": false, "text": "<p>I ran into a similar issue, where because of one of my own coding errors, thousands of copies of one particular cron job had been added to a site. The wp_clear_scheduled_hook function appeared to time out and fail. I got around it with a script that unset all instances of the cron function within the array and then adds the filtered array as the new cron option in the options table. See below.</p>\n\n<p>In this way, I avoided blowing away the desirable cron jobs previously added to the site.</p>\n\n<p>This could be modified as a function that takes an array of handles to eliminate or an array of handles to be preserved.</p>\n\n<pre><code>$crons = _get_cron_array();\n $hook = 'tj_flush_w3tc_cache';\n foreach ( $crons as $timestamp =&gt; $cron ) {\n if ( isset( $cron[ $hook ] ) ) {\n unset($cron[$hook]);\n }\n if(!empty($cron))\n $newcron[$timestamp] = $cron; \n }\n update_option('cron',$newcron);\n</code></pre>\n" }, { "answer_id": 330074, "author": "Windy", "author_id": 162124, "author_profile": "https://wordpress.stackexchange.com/users/162124", "pm_score": 1, "selected": false, "text": "<p>I have a way very simple to delete all cron events.\nBefore, you need to DISABLE WP Cron in wp-config\nThen, you install Plugin WP Control\nThen, Move to Tool menu > Cron events > Click chose all > Delete all of them.\nCould you try it.\nThanks.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66531/" ]
I'm stuck on loading page content by id (through a plugin). What I have is the following: ``` <?php $my_query = new WP_Query('page_id=39'); ?> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> ``` Instead of entering the id "39" though, it needs to come from $user\_set\_value I'm able to echo the id like this: ``` <?php global $wp_query; $postid = $wp_query->post->ID; echo get_post_meta($postid, 'user_set_value', true); wp_reset_query(); ?> ``` ..but how could I go about echoing $user\_set\_value into the first snippet so it would get the id on the fly? Many thanks!
Thanks Privateer for the prompt reply and advice. I found a way around it before I saw your answer. Here is a step-by-step method for deleting thousands of old cron jobs and may be of use to someone else. I logged on to phpMyAdmin. I clicked on my database and then the 'search' tab. I typed in 'cron' then selected 'all tables' and clicked 'Go'. I scrolled down the search results list to my wp\_options table. I clicked 'Browse'. At the top of the list was option\_name 'cron'. I clicked 'Edit' then waited for the page to load. I clicked on the box that showed the list of cron jobs. The cron list was so long that it took about 80 seconds for my cursor to respond. I then used Ctrl-A on the keyboard to select all before hitting the delete button. It took about 2 minutes before my browser completed the deletion (chrome timed-out so I tried Firefox which worked). After another couple of minutes the cron jobs for my current active plugins re-populated the list. There were 9 cron jobs (down from over 29,000!). Six years of duplicate cron jobs from badly coded plugins, some of which I just installed for a day to try out. Also hundreds from common plugins such as Wordfence, BackupBuddy, Nextgen Gallery, and AutoOptimizer - all of which I had uninstalled in the past. My site now loads like it's been turbo-charged. The admin area is much quicker. Admin timeout errors have disappeared. I had spent so much time on optimising my website trying to decrease the load time. I even moved hosts and upgraded my hosting plans. Nothing increased the speed of my site like deleting all the outdated cron jobs. Mobile download time decreased from 20 seconds to 6 seconds. Desktop download time decreased from about 12 to 4 seconds. In my search for a solution I found very little information on the effect of cron jobs on website performance. Many said it made little difference and for a small number of cron jobs that's true. But years into the life of a WordPress site I wonder how many are bloated with hundreds if not thousands of old cron jobs from deleted plugins. Instead of asking users to check their php memory limit I would suggest that developers first ask users to check the number of cron jobs in wp\_options when problem-solving fatal memory errors. You may be surprised/shocked at what you find! :-)
175,883
<p>I have a simple custom query driven by <code>get_posts</code>:</p> <pre><code>&lt;ul&gt; &lt;?php $args = array('post_type' =&gt; 'event', 'numberposts' =&gt; 6 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); echo '&lt;li&gt;&lt;a href="' . get_permalink() . '"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/li&gt;'; endforeach; wp_reset_postdata(); ?&gt; &lt;/ul&gt; </code></pre> <p>However, there's a need to access this custom loop's query object - the one which is accessible by default if you do custom loops using <code>new WP_Query</code> method. (This is needed to get connected posts of other CPTs, mechanism driven by the excellent <a href="https://github.com/scribu/wp-posts-to-posts/wiki/each_connected" rel="nofollow">Posts2Posts</a> plugin's <code>each_connected</code>.) Is it possible to get to the query object from <code>get_posts</code>? Or the only way to do this is to remake the loop in the <code>new WP_Query</code> style?</p>
[ { "answer_id": 175888, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 0, "selected": false, "text": "<p><del>Yes, I think the only way is</del> (See \nAndrei Gheorghiu's answer) If you choose to remake the loop, the slightly tricky bit is to make the <code>$args</code> array the same as <code>get_posts()</code>'s defaults:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'event', 'posts_per_page' =&gt; 6,\n 'post_status' =&gt; 'publish', // If post_type 'attachment' then 'post_status' =&gt; 'inherit'\n 'orderby' =&gt; 'date', 'order' =&gt; 'DESC',\n 'suppress_filters' =&gt; true,\n 'ignore_sticky_posts' =&gt; true, 'no_found_rows' =&gt; true,\n);\n$query = new WP_Query;\n$myposts = $query-&gt;query( $args );\n</code></pre>\n" }, { "answer_id": 175902, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": true, "text": "<p>You can filter any WP query using <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts()</code></a>. The (sometimes) tricky part is that it is run against all queries of WP so you need to pinpoint your query using WP conditionals (<code>is_admin()</code>, <code>is_page()</code>, <code>is_archive()</code>, etc... ). </p>\n\n<p>You'll find a few useful examples on that page, too.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17702/" ]
I have a simple custom query driven by `get_posts`: ``` <ul> <?php $args = array('post_type' => 'event', 'numberposts' => 6 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; endforeach; wp_reset_postdata(); ?> </ul> ``` However, there's a need to access this custom loop's query object - the one which is accessible by default if you do custom loops using `new WP_Query` method. (This is needed to get connected posts of other CPTs, mechanism driven by the excellent [Posts2Posts](https://github.com/scribu/wp-posts-to-posts/wiki/each_connected) plugin's `each_connected`.) Is it possible to get to the query object from `get_posts`? Or the only way to do this is to remake the loop in the `new WP_Query` style?
You can filter any WP query using [`pre_get_posts()`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). The (sometimes) tricky part is that it is run against all queries of WP so you need to pinpoint your query using WP conditionals (`is_admin()`, `is_page()`, `is_archive()`, etc... ). You'll find a few useful examples on that page, too.
175,884
<p>In my child theme's <code>archive.php</code>, I have the following code for displaying the title of my archive pages:</p> <pre><code>&lt;?php the_archive_title( '&lt;h1 class=&quot;page-title&quot;&gt;', '&lt;/h1&gt;' ); ?&gt; </code></pre> <p>But that displays my titles as &quot;Category: <em>Category Title</em>&quot; instead of simply the title without the prepended &quot;Category: &quot;.</p> <p>My first instinct was to override <code>get_the_archive_title()</code> from <code>wp-includes/general-template</code>. But from what I've read, apparently I'm not supposed to ever alter wordpress core stuff, even with overrides from a child theme.</p> <p>So what is the best-practice way to control the output of <code>the_archive_title()</code>?</p>
[ { "answer_id": 175900, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 3, "selected": false, "text": "<p>You could use </p>\n\n<pre><code>echo '&lt;h1 class=\"page-title\"&gt;' . single_cat_title( '', false ) . '&lt;/h1&gt;';\n</code></pre>\n" }, { "answer_id": 175903, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 7, "selected": true, "text": "<p>If you look at <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\">the source code of <code>get_the_archive_title()</code></a>, you will see that there is a filter supplied, called <code>get_the_archive_title</code>, through which you can filter the output from the function.</p>\n\n<p>You can use the following to change the output on a category page</p>\n\n<pre><code>add_filter( 'get_the_archive_title', function ( $title ) {\n\n if( is_category() ) {\n\n $title = single_cat_title( '', false );\n\n }\n\n return $title;\n\n});\n</code></pre>\n" }, { "answer_id": 192547, "author": "rhysclay", "author_id": 75204, "author_profile": "https://wordpress.stackexchange.com/users/75204", "pm_score": 3, "selected": false, "text": "<p>Another option is:</p>\n\n<pre><code>&lt;?php echo str_replace('Brand: ','',get_the_archive_title()); ?&gt;\n</code></pre>\n\n<p>Replace Brand: with whatever text you are wanting to get rid of. </p>\n\n<p>Its worth looking into the difference between get_the_archive_title() and the_archive_title()\nthe_archive_title() returns an array\nget_the_archive_title() returns a string</p>\n" }, { "answer_id": 203884, "author": "Quinn Comendant", "author_id": 68917, "author_profile": "https://wordpress.stackexchange.com/users/68917", "pm_score": 5, "selected": false, "text": "<p>The accepted answer works to remove the <code>Category:</code> prefix from category archive titles, but not other taxonomy or post types. To exclude other prefixes, there are two options:</p>\n\n<ol>\n<li><p>Rebuild the title for all the variants used in the original <code>get_the_archive_title()</code> function:</p>\n\n<pre><code>// Return an alternate title, without prefix, for every type used in the get_the_archive_title().\nadd_filter('get_the_archive_title', function ($title) {\n if ( is_category() ) {\n $title = single_cat_title( '', false );\n } elseif ( is_tag() ) {\n $title = single_tag_title( '', false );\n } elseif ( is_author() ) {\n $title = '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;';\n } elseif ( is_year() ) {\n $title = get_the_date( _x( 'Y', 'yearly archives date format' ) );\n } elseif ( is_month() ) {\n $title = get_the_date( _x( 'F Y', 'monthly archives date format' ) );\n } elseif ( is_day() ) {\n $title = get_the_date( _x( 'F j, Y', 'daily archives date format' ) );\n } elseif ( is_tax( 'post_format' ) ) {\n if ( is_tax( 'post_format', 'post-format-aside' ) ) {\n $title = _x( 'Asides', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) {\n $title = _x( 'Galleries', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-image' ) ) {\n $title = _x( 'Images', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-video' ) ) {\n $title = _x( 'Videos', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-quote' ) ) {\n $title = _x( 'Quotes', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-link' ) ) {\n $title = _x( 'Links', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-status' ) ) {\n $title = _x( 'Statuses', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-audio' ) ) {\n $title = _x( 'Audio', 'post format archive title' );\n } elseif ( is_tax( 'post_format', 'post-format-chat' ) ) {\n $title = _x( 'Chats', 'post format archive title' );\n }\n } elseif ( is_post_type_archive() ) {\n $title = post_type_archive_title( '', false );\n } elseif ( is_tax() ) {\n $title = single_term_title( '', false );\n } else {\n $title = __( 'Archives' );\n }\n return $title;\n});\n</code></pre></li>\n<li><p>Or, simply strip anything that looks like a title prefix (which may alter actual titles which contain a word followed by the colon character):</p>\n\n<pre><code>// Simply remove anything that looks like an archive title prefix (\"Archive:\", \"Foo:\", \"Bar:\").\nadd_filter('get_the_archive_title', function ($title) {\n return preg_replace('/^\\w+: /', '', $title);\n});\n</code></pre></li>\n</ol>\n" }, { "answer_id": 292354, "author": "Dan Knauss", "author_id": 57078, "author_profile": "https://wordpress.stackexchange.com/users/57078", "pm_score": 2, "selected": false, "text": "<p>Ben Gillbanks <a href=\"https://www.binarymoon.co.uk/2017/02/hide-archive-title-prefix-wordpress/\" rel=\"nofollow noreferrer\">has a nice solution</a> that handles all post types and taxonomies:</p>\n\n<pre><code>function hap_hide_the_archive_title( $title ) {\n// Skip if the site isn't LTR, this is visual, not functional.\n// Should try to work out an elegant solution that works for both directions.\nif ( is_rtl() ) {\n return $title;\n}\n// Split the title into parts so we can wrap them with spans.\n$title_parts = explode( ': ', $title, 2 );\n// Glue it back together again.\nif ( ! empty( $title_parts[1] ) ) {\n $title = wp_kses(\n $title_parts[1],\n array(\n 'span' =&gt; array(\n 'class' =&gt; array(),\n ),\n )\n );\n $title = '&lt;span class=\"screen-reader-text\"&gt;' . esc_html( $title_parts[0] ) . ': &lt;/span&gt;' . $title;\n}\nreturn $title;\n}\nadd_filter( 'get_the_archive_title', 'hap_hide_the_archive_title' );\n</code></pre>\n" }, { "answer_id": 301055, "author": "Mark Williams", "author_id": 25301, "author_profile": "https://wordpress.stackexchange.com/users/25301", "pm_score": 0, "selected": false, "text": "<p>You can use <code>post_type_archive_title()</code> to get the title of an archive without the \"Archives:\" text.</p>\n" }, { "answer_id": 408962, "author": "Fanky", "author_id": 89973, "author_profile": "https://wordpress.stackexchange.com/users/89973", "pm_score": 0, "selected": false, "text": "<p>Use this instead <code>the_archive_title()</code>. Works with CPTs and custom taxonomies.</p>\n<pre><code>&lt;?php\n$term = $wp_query-&gt;get_queried_object();\n$term_title = $term-&gt;label //works with CPTs (Books)\n?? $term-&gt;name //works with custom taxonomy terms (gets Small in size/small)\n?? &quot;untitled&quot;;\n?&gt;\n&lt;h1&gt;&lt;?php echo $term_title; ?&gt;&lt;/h1&gt;\n</code></pre>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175884", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66533/" ]
In my child theme's `archive.php`, I have the following code for displaying the title of my archive pages: ``` <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); ?> ``` But that displays my titles as "Category: *Category Title*" instead of simply the title without the prepended "Category: ". My first instinct was to override `get_the_archive_title()` from `wp-includes/general-template`. But from what I've read, apparently I'm not supposed to ever alter wordpress core stuff, even with overrides from a child theme. So what is the best-practice way to control the output of `the_archive_title()`?
If you look at [the source code of `get_the_archive_title()`](https://developer.wordpress.org/reference/functions/get_the_archive_title/), you will see that there is a filter supplied, called `get_the_archive_title`, through which you can filter the output from the function. You can use the following to change the output on a category page ``` add_filter( 'get_the_archive_title', function ( $title ) { if( is_category() ) { $title = single_cat_title( '', false ); } return $title; }); ```
175,890
<p>I would like to have a few pages which can be reached by anyone who knows the URL, but which are not listed on the WordPress menu. I would like those pages to have a name rather than a number, but I don't see a way to do any of these things.</p> <p>That is, I can create a page named "Special" and not include it in the menu, but I cannot go to</p> <p>mysite.net/Special</p> <p>only to </p> <p>mysite.net/?page_id=561</p> <p>I also want to keep the /?page_id=561 navigation, because this is an established site with a lot of links set up to use that style of URL. I just want a few specific pages to have nice names that will resolve.</p> <p>Does WordPress have such a feature? Should I try to get IIS to direct /Special to /?page_id=561 ?</p> <p>Hmm. In choosing tags for this question, I found "url-rewriting" and <a href="http://codex.wordpress.org/Rewrite_API/add_rewrite_rule" rel="nofollow">http://codex.wordpress.org/Rewrite_API/add_rewrite_rule</a> - it looks like I could add </p> <pre><code>function custom_rewrite_basic() { add_rewrite_rule('mysite.net/Special', 'mysite.net/Special'); } add_action('init', 'custom_rewrite_basic'); </code></pre> <p>To "functions.php" - the one I see is in my theme (twentytwelve) folder... so would I just insert this in there?</p>
[ { "answer_id": 175892, "author": "OnethingSimple", "author_id": 66538, "author_profile": "https://wordpress.stackexchange.com/users/66538", "pm_score": 2, "selected": true, "text": "<p>If you tried to create a static file and then load it like a normal file, you may have had trouble because a WP page as we call it, is actually not actually 1 file, but rather a lot of files that tell Wordpress how to put together information queried from the database based on the query that is used in the URL. Most modern WP installs use pretty-links which don't have users see that query \"?page_id=561\" because it make urls easier to read and more semantic. (Before doing what I list below, I'm pretty sure that if you switch to permalinks, your old query links should still work because permalinks change pretty-links down into queries behind the scenes.)</p>\n\n<p>If you are absolutely positive that you don't want to make the switch to pretty-links, then you could load Wordpress on your own through a static file. To do this we first need to require the wp-blog-header.php file that is located in the WP root directory. So to test this out you can save a file into the root directory, name it secret-page.php and put in the following lines. After you should be able to access it at mysite.com/secret-page.php ( provided mysite.com is your wordpress install directory. It could possible be a different directory then the root folder of your website. Look for the folder with wp-config.php inside it.</p>\n\n<pre><code>&lt;?php\nrequire( 'wp-blog-header.php' );\ndefine('WP_USE_THEMES', true);\n\nget_header();\nwp_head();\n?&gt;\n &lt;div id=\"main\"&gt;\n</code></pre>\n\n<p>Normally I would not put a file in the root directory, but you also don't want to put that file in your theme folder and have the url be www.mysite.com/wp-content/themes/secret_page.php ( unless you want to make a rewrite rule redirecting the url yoursite.com/secret-page.php to yoursite.com/wp-content/themes//secret-page.php ). If you do that, just change the require line above to require('../../../wp-blog-header'); if you use a typical theme folder. For every folder above the root folder you place the file, you will have to put a set of \"../\" before the file name, which just means \"go back one folder\"</p>\n\n<p>To explain what the file above did, it ran the wp-blog-header.php file which started Wordpress for you, then the second line told Wordpress we wanted to use themes. This way we can get the same look as your site regardless if this file is in the theme folder or not, we will have access to your regularly used theme because WP has it saved as an option in the Database.</p>\n\n<p>Next, the get_header(); line went to your theme and began to print out your websites page, and after that, wp_head() runs all the Wordpress head actions. If you are a developer, you can continue on from here alone. If not, but you can handle your own, then goto your theme folder and copy code from index.php or page.php ( whichever page you most want to imitate ). Check out this codex page, <a href=\"http://codex.wordpress.org/Template_Tags\" rel=\"nofollow\">http://codex.wordpress.org/Template_Tags</a> - it will explain how template tags work, that will help you to add the same functionality your sites pages usually have to this new page, which is unlisted and only available to people who know the URL. You don't have to use the '' - that is actually just to demonstrate that is where you should begin your html. I hope this helped.</p>\n" }, { "answer_id": 175898, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>All you need is to enable permalinks.</p>\n\n<p>I strongly recommend switching to permalinks: <em>/%postname%/</em></p>\n\n<p><strong>The old links will still work.</strong> (In fact, every single permalink type is just an alias for the default one: <em>?p=%post_id%</em> ).</p>\n\n<p>Being able to give people easier to remember links to pages is a secondary reason. The main one should be boosting page rankings in search engines. </p>\n\n<p>Google places pages that have the searched keyword in the URL higher. It's a fact.</p>\n\n<p>As for not showing page in menus, just disable the \"Add new pages to this menu\" checkbox in Dashboard > Appearance > Menus. And add/remove any pages/posts to/from the menu while at it.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66537/" ]
I would like to have a few pages which can be reached by anyone who knows the URL, but which are not listed on the WordPress menu. I would like those pages to have a name rather than a number, but I don't see a way to do any of these things. That is, I can create a page named "Special" and not include it in the menu, but I cannot go to mysite.net/Special only to mysite.net/?page\_id=561 I also want to keep the /?page\_id=561 navigation, because this is an established site with a lot of links set up to use that style of URL. I just want a few specific pages to have nice names that will resolve. Does WordPress have such a feature? Should I try to get IIS to direct /Special to /?page\_id=561 ? Hmm. In choosing tags for this question, I found "url-rewriting" and <http://codex.wordpress.org/Rewrite_API/add_rewrite_rule> - it looks like I could add ``` function custom_rewrite_basic() { add_rewrite_rule('mysite.net/Special', 'mysite.net/Special'); } add_action('init', 'custom_rewrite_basic'); ``` To "functions.php" - the one I see is in my theme (twentytwelve) folder... so would I just insert this in there?
If you tried to create a static file and then load it like a normal file, you may have had trouble because a WP page as we call it, is actually not actually 1 file, but rather a lot of files that tell Wordpress how to put together information queried from the database based on the query that is used in the URL. Most modern WP installs use pretty-links which don't have users see that query "?page\_id=561" because it make urls easier to read and more semantic. (Before doing what I list below, I'm pretty sure that if you switch to permalinks, your old query links should still work because permalinks change pretty-links down into queries behind the scenes.) If you are absolutely positive that you don't want to make the switch to pretty-links, then you could load Wordpress on your own through a static file. To do this we first need to require the wp-blog-header.php file that is located in the WP root directory. So to test this out you can save a file into the root directory, name it secret-page.php and put in the following lines. After you should be able to access it at mysite.com/secret-page.php ( provided mysite.com is your wordpress install directory. It could possible be a different directory then the root folder of your website. Look for the folder with wp-config.php inside it. ``` <?php require( 'wp-blog-header.php' ); define('WP_USE_THEMES', true); get_header(); wp_head(); ?> <div id="main"> ``` Normally I would not put a file in the root directory, but you also don't want to put that file in your theme folder and have the url be www.mysite.com/wp-content/themes/secret\_page.php ( unless you want to make a rewrite rule redirecting the url yoursite.com/secret-page.php to yoursite.com/wp-content/themes//secret-page.php ). If you do that, just change the require line above to require('../../../wp-blog-header'); if you use a typical theme folder. For every folder above the root folder you place the file, you will have to put a set of "../" before the file name, which just means "go back one folder" To explain what the file above did, it ran the wp-blog-header.php file which started Wordpress for you, then the second line told Wordpress we wanted to use themes. This way we can get the same look as your site regardless if this file is in the theme folder or not, we will have access to your regularly used theme because WP has it saved as an option in the Database. Next, the get\_header(); line went to your theme and began to print out your websites page, and after that, wp\_head() runs all the Wordpress head actions. If you are a developer, you can continue on from here alone. If not, but you can handle your own, then goto your theme folder and copy code from index.php or page.php ( whichever page you most want to imitate ). Check out this codex page, <http://codex.wordpress.org/Template_Tags> - it will explain how template tags work, that will help you to add the same functionality your sites pages usually have to this new page, which is unlisted and only available to people who know the URL. You don't have to use the '' - that is actually just to demonstrate that is where you should begin your html. I hope this helped.
175,893
<p>I'm still quite new to Wordpress - after a pointer or two.</p> <p>I've created a archive page for a custom post type of 'property'. This is set-up, working from an admin point of view, and I have a listing/index page showing the content created using a template I've themed called 'archive-property.php'.</p> <p>While this archive template shows a listing page of these posts, I also need a separate view which shows the same posts plotted on a google map.</p> <p>I'm quite familiar with setting up google maps - but wondering how I route a URL to this template in wordpress?</p> <p>So the ideal aim is that the /property/ carries on serving content using the archive-property.php template.</p> <p>Then there would be a /property/map/ page which would need to load from a different template file - something like archive-property-map.php...</p> <p>How do I tell wordpress that a request for this 2nd URL should use that template?</p>
[ { "answer_id": 175892, "author": "OnethingSimple", "author_id": 66538, "author_profile": "https://wordpress.stackexchange.com/users/66538", "pm_score": 2, "selected": true, "text": "<p>If you tried to create a static file and then load it like a normal file, you may have had trouble because a WP page as we call it, is actually not actually 1 file, but rather a lot of files that tell Wordpress how to put together information queried from the database based on the query that is used in the URL. Most modern WP installs use pretty-links which don't have users see that query \"?page_id=561\" because it make urls easier to read and more semantic. (Before doing what I list below, I'm pretty sure that if you switch to permalinks, your old query links should still work because permalinks change pretty-links down into queries behind the scenes.)</p>\n\n<p>If you are absolutely positive that you don't want to make the switch to pretty-links, then you could load Wordpress on your own through a static file. To do this we first need to require the wp-blog-header.php file that is located in the WP root directory. So to test this out you can save a file into the root directory, name it secret-page.php and put in the following lines. After you should be able to access it at mysite.com/secret-page.php ( provided mysite.com is your wordpress install directory. It could possible be a different directory then the root folder of your website. Look for the folder with wp-config.php inside it.</p>\n\n<pre><code>&lt;?php\nrequire( 'wp-blog-header.php' );\ndefine('WP_USE_THEMES', true);\n\nget_header();\nwp_head();\n?&gt;\n &lt;div id=\"main\"&gt;\n</code></pre>\n\n<p>Normally I would not put a file in the root directory, but you also don't want to put that file in your theme folder and have the url be www.mysite.com/wp-content/themes/secret_page.php ( unless you want to make a rewrite rule redirecting the url yoursite.com/secret-page.php to yoursite.com/wp-content/themes//secret-page.php ). If you do that, just change the require line above to require('../../../wp-blog-header'); if you use a typical theme folder. For every folder above the root folder you place the file, you will have to put a set of \"../\" before the file name, which just means \"go back one folder\"</p>\n\n<p>To explain what the file above did, it ran the wp-blog-header.php file which started Wordpress for you, then the second line told Wordpress we wanted to use themes. This way we can get the same look as your site regardless if this file is in the theme folder or not, we will have access to your regularly used theme because WP has it saved as an option in the Database.</p>\n\n<p>Next, the get_header(); line went to your theme and began to print out your websites page, and after that, wp_head() runs all the Wordpress head actions. If you are a developer, you can continue on from here alone. If not, but you can handle your own, then goto your theme folder and copy code from index.php or page.php ( whichever page you most want to imitate ). Check out this codex page, <a href=\"http://codex.wordpress.org/Template_Tags\" rel=\"nofollow\">http://codex.wordpress.org/Template_Tags</a> - it will explain how template tags work, that will help you to add the same functionality your sites pages usually have to this new page, which is unlisted and only available to people who know the URL. You don't have to use the '' - that is actually just to demonstrate that is where you should begin your html. I hope this helped.</p>\n" }, { "answer_id": 175898, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>All you need is to enable permalinks.</p>\n\n<p>I strongly recommend switching to permalinks: <em>/%postname%/</em></p>\n\n<p><strong>The old links will still work.</strong> (In fact, every single permalink type is just an alias for the default one: <em>?p=%post_id%</em> ).</p>\n\n<p>Being able to give people easier to remember links to pages is a secondary reason. The main one should be boosting page rankings in search engines. </p>\n\n<p>Google places pages that have the searched keyword in the URL higher. It's a fact.</p>\n\n<p>As for not showing page in menus, just disable the \"Add new pages to this menu\" checkbox in Dashboard > Appearance > Menus. And add/remove any pages/posts to/from the menu while at it.</p>\n" } ]
2015/01/24
[ "https://wordpress.stackexchange.com/questions/175893", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66428/" ]
I'm still quite new to Wordpress - after a pointer or two. I've created a archive page for a custom post type of 'property'. This is set-up, working from an admin point of view, and I have a listing/index page showing the content created using a template I've themed called 'archive-property.php'. While this archive template shows a listing page of these posts, I also need a separate view which shows the same posts plotted on a google map. I'm quite familiar with setting up google maps - but wondering how I route a URL to this template in wordpress? So the ideal aim is that the /property/ carries on serving content using the archive-property.php template. Then there would be a /property/map/ page which would need to load from a different template file - something like archive-property-map.php... How do I tell wordpress that a request for this 2nd URL should use that template?
If you tried to create a static file and then load it like a normal file, you may have had trouble because a WP page as we call it, is actually not actually 1 file, but rather a lot of files that tell Wordpress how to put together information queried from the database based on the query that is used in the URL. Most modern WP installs use pretty-links which don't have users see that query "?page\_id=561" because it make urls easier to read and more semantic. (Before doing what I list below, I'm pretty sure that if you switch to permalinks, your old query links should still work because permalinks change pretty-links down into queries behind the scenes.) If you are absolutely positive that you don't want to make the switch to pretty-links, then you could load Wordpress on your own through a static file. To do this we first need to require the wp-blog-header.php file that is located in the WP root directory. So to test this out you can save a file into the root directory, name it secret-page.php and put in the following lines. After you should be able to access it at mysite.com/secret-page.php ( provided mysite.com is your wordpress install directory. It could possible be a different directory then the root folder of your website. Look for the folder with wp-config.php inside it. ``` <?php require( 'wp-blog-header.php' ); define('WP_USE_THEMES', true); get_header(); wp_head(); ?> <div id="main"> ``` Normally I would not put a file in the root directory, but you also don't want to put that file in your theme folder and have the url be www.mysite.com/wp-content/themes/secret\_page.php ( unless you want to make a rewrite rule redirecting the url yoursite.com/secret-page.php to yoursite.com/wp-content/themes//secret-page.php ). If you do that, just change the require line above to require('../../../wp-blog-header'); if you use a typical theme folder. For every folder above the root folder you place the file, you will have to put a set of "../" before the file name, which just means "go back one folder" To explain what the file above did, it ran the wp-blog-header.php file which started Wordpress for you, then the second line told Wordpress we wanted to use themes. This way we can get the same look as your site regardless if this file is in the theme folder or not, we will have access to your regularly used theme because WP has it saved as an option in the Database. Next, the get\_header(); line went to your theme and began to print out your websites page, and after that, wp\_head() runs all the Wordpress head actions. If you are a developer, you can continue on from here alone. If not, but you can handle your own, then goto your theme folder and copy code from index.php or page.php ( whichever page you most want to imitate ). Check out this codex page, <http://codex.wordpress.org/Template_Tags> - it will explain how template tags work, that will help you to add the same functionality your sites pages usually have to this new page, which is unlisted and only available to people who know the URL. You don't have to use the '' - that is actually just to demonstrate that is where you should begin your html. I hope this helped.
175,917
<p>I'm trying to get all arguments for function <code>get_the_author_meta()</code> or <code>the_author_meta()</code> because I have custom profile fields such as "parent name" and so, not only the normal arguments which is in <a href="http://codex.wordpress.org/Function_Reference/the_author_meta" rel="nofollow">Function_Reference/the_author_meta</a></p> <p>I tried php <code>func_get_args()</code> but I can't make it work</p> <p>any suggestions ?</p>
[ { "answer_id": 175925, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>I think you are confusing function arguments with author (user) meta fields. To get all user meta fields you can use <a href=\"http://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\"><code>get_user_meta()</code></a> with empty <code>$key</code> parameter. For example, for user with ID 45:</p>\n\n<pre><code>$user_meta = get_user_meta( 45 );\n</code></pre>\n\n<p><code>$user_meta</code> will be an array with all meta fields for the user with ID = 45.</p>\n" }, { "answer_id": 175930, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 1, "selected": false, "text": "<p>The user meta, including the custom ones, are saved in the <code>wp_usermeta</code> table. You can get all user properties and meta keys using <a href=\"http://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow\">get_userdata( $userid )</a>, an alias of <code>get_user_by( 'id' )</code> , which returns a WP_User object or false on failure (the user with that ID does not exist).</p>\n\n<p>Furthermore, you can determine if a certain meta key or property is set for a certain user using <code>__isset($key)</code>. You can access a meta key or property using <code>__get($key)</code>;</p>\n\n<p>For example, you can make a shortcode to display user properties and/or meta keys with</p>\n\n<pre><code>add_shortcode('get-user-property', 'get_user_property');\nfunction get_user_property( $atts ) {\n $atts = shortcode_atts( array(\n 'user' =&gt; get_current_user_id(),\n 'key' =&gt; 'display_name',\n ), $atts, 'get-user-property');\n $ud = get_userdata($atts['user']);\n return $ud ? \n ($ud-&gt;__isset($atts['key']) ?\n $ud-&gt;__get($atts['key']) :\n (isset($ud-&gt;{$atts['key']}) ? \n $ud-&gt;{$atts['key']} : \n '[not set]'\n )\n ) : \n '[user does not exist]';\n}\n</code></pre>\n\n<p>Now you can get any user property/meta-key using <code>[get-user-property user=\"%id%\" key=\"%field_name%\"]</code> anywhere you have shortcodes enabled. If the prop is not set for a user, it will return <code>[not set]</code>, or <code>[user does not exist]</code> if you got the wrong ID. </p>\n\n<p>If run without any arguments, it will return the display_name of the current user.</p>\n" } ]
2015/01/25
[ "https://wordpress.stackexchange.com/questions/175917", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37854/" ]
I'm trying to get all arguments for function `get_the_author_meta()` or `the_author_meta()` because I have custom profile fields such as "parent name" and so, not only the normal arguments which is in [Function\_Reference/the\_author\_meta](http://codex.wordpress.org/Function_Reference/the_author_meta) I tried php `func_get_args()` but I can't make it work any suggestions ?
I think you are confusing function arguments with author (user) meta fields. To get all user meta fields you can use [`get_user_meta()`](http://codex.wordpress.org/Function_Reference/get_user_meta) with empty `$key` parameter. For example, for user with ID 45: ``` $user_meta = get_user_meta( 45 ); ``` `$user_meta` will be an array with all meta fields for the user with ID = 45.