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
212,241
<p>I am using <a href="http://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/" rel="nofollow noreferrer">this code</a> to search products from a wordpress/woocommerce website.<br> My requirment is URL will be like "<a href="http://localhost/wp/?s=D34&amp;post_type=product" rel="nofollow noreferrer">http://localhost/wp/?s=D34&amp;post_type=product</a>" While <code>s=D34</code> is search string. </p> <p>When user will search for a string. Data will be searched from All default fields+ product's <code>custom filed</code>. The below code work fine with <a href="http://localhost/wp/?s=D34" rel="nofollow noreferrer">http://localhost/wp/?s=D34</a> but when <code>&amp;post_type=product</code> is concatenated with url then it say <a href="https://i.stack.imgur.com/2AbCv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2AbCv.png" alt="enter image description here"></a></p> <p><strong>Code is given below</strong></p> <pre><code>function cf_search_where( $where ) { global $pagenow, $wpdb; if ( is_search() ) { $where = preg_replace("/\(\s*".$wpdb-&gt;posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/", "(".$wpdb-&gt;posts.".post_title LIKE $1) OR (".$wpdb-&gt;postmeta.".meta_value LIKE $1)", $where ); $where .= " AND ($wpdb-&gt;posts.post_type = 'product') "; } return $where; } add_filter( 'posts_where', 'cf_search_where' ); </code></pre> <p><strong>This is to prevent distinct values</strong></p> <pre><code> function cf_search_distinct( $where ) { global $wpdb; if ( is_search() ) { return "DISTINCT"; //to prevent duplicates } return $where; } add_filter( 'posts_distinct', 'cf_search_distinct' ); </code></pre> <p>So What modification is required?</p> <p><code>URL</code> <a href="http://localhost/wp/?orderby=price&amp;post_type=product" rel="nofollow noreferrer">http://localhost/wp/?orderby=price&amp;post_type=product</a> work fine </p> <p>but what is wrong with <a href="http://localhost/wp/?s=D34&amp;post_type=product" rel="nofollow noreferrer">http://localhost/wp/?s=D34&amp;post_type=product</a></p> <p>Wordpress version is sixteen and 4.4. Woocommerce Plugin is installed</p> <p>In both cases Query is </p> <p><strong>Case 1:</strong> <a href="http://localhost/wp/?s=D34&amp;post_type=product" rel="nofollow noreferrer">http://localhost/wp/?s=D34&amp;post_type=product</a></p> <p><strong>Case 2:</strong> <a href="http://localhost/wp/?s=D34" rel="nofollow noreferrer">http://localhost/wp/?s=D34</a></p> <pre><code>AND wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish') AND (((wp_posts.post_title LIKE '%D34%') OR (wp_postmeta.meta_value LIKE '%D34%') OR (wp_posts.post_content LIKE '%D34%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment', 'product') AND (wp_posts.post_status = 'publish') AND (wp_posts.post_type = 'product') </code></pre>
[ { "answer_id": 212242, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 0, "selected": false, "text": "<p>try this</p>\n\n<pre><code>function cf_search_where( $where ) {\n global $pagenow, $wpdb;\n\n // a little debugging will help you..\n //print_r ($where);\n //die();\n\n if ( is_search() ) {\n\n $where = preg_replace(\"/\\(\\s*\".$wpdb-&gt;posts.\".post_title\\s+LIKE\\s*(\\'[^\\']+\\')\\s*\\)/\",\n \"(\".$wpdb-&gt;posts.\".post_title LIKE $1) OR (\".$wpdb-&gt;postmeta.\".meta_value LIKE $1)\", $where );\n $where .= \" AND ($wpdb-&gt;posts.post_type = 'product') \";\n }\n\n return $where;\n}\nadd_filter( 'posts_where', 'cf_search_where' );\n</code></pre>\n" }, { "answer_id": 212294, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>If I understand you, what you are doing is wildly complicated. All you should need is a simple <code>pre_get_posts</code> filter:</p>\n\n<pre><code>add_filter( 'pre_get_posts', 'modified_pre_get_posts' ); \nfunction modified_pre_get_posts( $query ) { \n if ( $query-&gt;is_search() ) { \n $query-&gt;set( 'post_type', 'product' ); \n } \n return $query; \n}\n</code></pre>\n\n<p>Plus your filter that adds <code>DISTINCT</code>.</p>\n\n<p><code>post_type</code> is a <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\">query parameter rolled into Core</a>. Passing an URL such as <code>localhost/wp/?s=D34&amp;post_type=product</code> should by default limit your queries to the single named post type. You shouldn't have to do anything special to make that work. Your filter may in fact be causing trouble.</p>\n" }, { "answer_id": 212340, "author": "Saichon Wongbua", "author_id": 85558, "author_profile": "https://wordpress.stackexchange.com/users/85558", "pm_score": 0, "selected": false, "text": "<p>You just add hidden input type by put these code below to your searchform.php</p>\n\n<pre><code>&lt;input type=\"hidden\" value=\"post\" name=\"product\" id=\"product\" /&gt;\n</code></pre>\n" } ]
2015/12/18
[ "https://wordpress.stackexchange.com/questions/212241", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85511/" ]
I am using [this code](http://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/) to search products from a wordpress/woocommerce website. My requirment is URL will be like "<http://localhost/wp/?s=D34&post_type=product>" While `s=D34` is search string. When user will search for a string. Data will be searched from All default fields+ product's `custom filed`. The below code work fine with <http://localhost/wp/?s=D34> but when `&post_type=product` is concatenated with url then it say [![enter image description here](https://i.stack.imgur.com/2AbCv.png)](https://i.stack.imgur.com/2AbCv.png) **Code is given below** ``` function cf_search_where( $where ) { global $pagenow, $wpdb; if ( is_search() ) { $where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/", "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where ); $where .= " AND ($wpdb->posts.post_type = 'product') "; } return $where; } add_filter( 'posts_where', 'cf_search_where' ); ``` **This is to prevent distinct values** ``` function cf_search_distinct( $where ) { global $wpdb; if ( is_search() ) { return "DISTINCT"; //to prevent duplicates } return $where; } add_filter( 'posts_distinct', 'cf_search_distinct' ); ``` So What modification is required? `URL` <http://localhost/wp/?orderby=price&post_type=product> work fine but what is wrong with <http://localhost/wp/?s=D34&post_type=product> Wordpress version is sixteen and 4.4. Woocommerce Plugin is installed In both cases Query is **Case 1:** <http://localhost/wp/?s=D34&post_type=product> **Case 2:** <http://localhost/wp/?s=D34> ``` AND wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish') AND (((wp_posts.post_title LIKE '%D34%') OR (wp_postmeta.meta_value LIKE '%D34%') OR (wp_posts.post_content LIKE '%D34%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment', 'product') AND (wp_posts.post_status = 'publish') AND (wp_posts.post_type = 'product') ```
If I understand you, what you are doing is wildly complicated. All you should need is a simple `pre_get_posts` filter: ``` add_filter( 'pre_get_posts', 'modified_pre_get_posts' ); function modified_pre_get_posts( $query ) { if ( $query->is_search() ) { $query->set( 'post_type', 'product' ); } return $query; } ``` Plus your filter that adds `DISTINCT`. `post_type` is a [query parameter rolled into Core](https://codex.wordpress.org/WordPress_Query_Vars). Passing an URL such as `localhost/wp/?s=D34&post_type=product` should by default limit your queries to the single named post type. You shouldn't have to do anything special to make that work. Your filter may in fact be causing trouble.
212,266
<p>i know how i can print a single script with wp_dequeue_script and wp_enqueue_script to the footer:</p> <pre><code>function dequeue_my_scripts() { wp_dequeue_script('dgx_donate_paypalstd_script'); } add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 ); function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script'); } add_action( 'wp_footer', 'enqueue_scripts_to_footer' ); </code></pre> <p>But how can i print a couple of scripts to the footer. Is there a posibility to use enumeration for example:</p> <pre><code>function dequeue_my_scripts() { wp_dequeue_script('dgx_donate_paypalstd_script','next-handle-script', 'next-handle-script'.....); } add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 ); function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script','next-handle-script', 'next-handle-script'.....); } add_action( 'wp_footer', 'enqueue_scripts_to_footer' ); </code></pre> <p>Or is there another possibility??</p>
[ { "answer_id": 212268, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 0, "selected": false, "text": "<p>Right out of the codex: the fifth argument to the wp_enqueue_script function call is a boolean to tell it whether or not to put the script in the footer:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_enqueue_script</a></p>\n" }, { "answer_id": 212274, "author": "Omar Tariq", "author_id": 36718, "author_profile": "https://wordpress.stackexchange.com/users/36718", "pm_score": 3, "selected": true, "text": "<p>Like this:-</p>\n\n<pre><code>function dequeue_my_scripts() {\n wp_dequeue_script('dgx_donate_paypalstd_script');\n wp_dequeue_script('next-handle-script');\n wp_dequeue_script('next-handle-script-2');\n /* and so on*/\n}\nadd_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 );\n\nfunction enqueue_scripts_to_footer() {\n wp_enqueue_script('dgx_donate_paypalstd_script');\n wp_enqueue_script('next-handle-script');\n wp_enqueue_script('next-handle-script-2');\n /* and so on */\n}\nadd_action( 'wp_footer', 'enqueue_scripts_to_footer' );\n</code></pre>\n\n<p>What's wrong in this implementation?</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I would also like to notify you that this is the correct implementation of what you are trying to achieve:-</p>\n\n<pre><code>function enqueue_scripts_to_footer() {\n wp_enqueue_script('dgx_donate_paypalstd_script', false, array(), false, true);\n wp_enqueue_script('next-handle-script', false, array(), false, true);\n wp_enqueue_script('next-handle-script-2', false, array(), false, true);\n /* and so on */\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_scripts_to_footer' );\n</code></pre>\n" } ]
2015/12/18
[ "https://wordpress.stackexchange.com/questions/212266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i know how i can print a single script with wp\_dequeue\_script and wp\_enqueue\_script to the footer: ``` function dequeue_my_scripts() { wp_dequeue_script('dgx_donate_paypalstd_script'); } add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 ); function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script'); } add_action( 'wp_footer', 'enqueue_scripts_to_footer' ); ``` But how can i print a couple of scripts to the footer. Is there a posibility to use enumeration for example: ``` function dequeue_my_scripts() { wp_dequeue_script('dgx_donate_paypalstd_script','next-handle-script', 'next-handle-script'.....); } add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 ); function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script','next-handle-script', 'next-handle-script'.....); } add_action( 'wp_footer', 'enqueue_scripts_to_footer' ); ``` Or is there another possibility??
Like this:- ``` function dequeue_my_scripts() { wp_dequeue_script('dgx_donate_paypalstd_script'); wp_dequeue_script('next-handle-script'); wp_dequeue_script('next-handle-script-2'); /* and so on*/ } add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 ); function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script'); wp_enqueue_script('next-handle-script'); wp_enqueue_script('next-handle-script-2'); /* and so on */ } add_action( 'wp_footer', 'enqueue_scripts_to_footer' ); ``` What's wrong in this implementation? **EDIT:** I would also like to notify you that this is the correct implementation of what you are trying to achieve:- ``` function enqueue_scripts_to_footer() { wp_enqueue_script('dgx_donate_paypalstd_script', false, array(), false, true); wp_enqueue_script('next-handle-script', false, array(), false, true); wp_enqueue_script('next-handle-script-2', false, array(), false, true); /* and so on */ } add_action( 'wp_enqueue_scripts', 'enqueue_scripts_to_footer' ); ```
212,309
<p>I have created a small search tool that unless you know the EXACT code, you will not be taken to the post. For example, if I enter "OI812" it will take me to a custom post type that is ../CPT/OI812.</p> <p>The CPT is not part of the regular search and I've removed anything with that slug from a canonical redirect. Unless they use my small search tool and enter the code exactly, it will not take them to the page.</p> <p>So far, so good. However, I would like to have a uniquely generated URL every time they access the page. E.G. ../CPT/HASHorSOMETHINGcrazyANDrandom. This would make sharing the URL useless unless they visit the page and enter the code into the search tool.</p> <p>I'm curious how one would go about this? I've searched around but the search terms for something like this seems to be a little ubiquitous. Any help appreciated.</p>
[ { "answer_id": 212316, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">add_rewrite_rule</a> or <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add_rewrite_endpoint</a> to capture the <code>HASHorSOMETHINGcrazyANDrandom</code>. </p>\n\n<p><a href=\"http://hashids.org/php/\" rel=\"nofollow\">Hashids</a> could also help you generate a hash that you could read back later.</p>\n\n<pre><code>$hashids = new Hashids\\Hashids('this is my salt');\n\n$post_id = 1;\n$request_id = 2;\n$random = 3;\n\n$crazy_id = $hashids-&gt;encode($post_id, $request_id, $random);\n\n$numbers = $hashids-&gt;decode($crazy_id);\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #1</strong></p>\n\n<p>This creates two endpoints:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/CPT/\" rel=\"nofollow\">http://example.com/CPT/</a>{CODE}/{HASH}</p>\n \n <p><a href=\"http://example.com/CPT/\" rel=\"nofollow\">http://example.com/CPT/</a>{CODE}/</p>\n</blockquote>\n\n<p>In either case a new hash will be generated with a new link everytime. Because I'm using <code>wp_hash_password</code> I loop until a password doesn't contain <code>/</code> so it won't break the URL. I'm sure there are better ways but... it works for this test. The plain password is based on the <code>SERVER_NAME</code> + <code>{CODE}</code> which was taken from the first param.</p>\n\n<p>Each hash URL is unique but always validates if used with the correct code.</p>\n\n<hr>\n\n<pre><code>if( ! class_exists('HashPoint')):\n\n class HashPoint {\n\n const ENDPOINT_NAME = 'CPT'; // endpoint to capture\n const ENDPOINT_QUERY_NAME = '__cpt'; // turns to param\n\n // WordPress hooks\n public function init() {\n add_filter('query_vars', array($this, 'add_query_vars'), 0);\n add_action('parse_request', array($this, 'sniff_requests'), 0);\n add_action('init', array($this, 'add_endpoint'), 0);\n }\n\n // Add public query vars\n public function add_query_vars($vars) {\n $vars[] = static::ENDPOINT_QUERY_NAME;\n $vars[] = 'code';\n $vars[] = 'hash';\n\n return $vars;\n }\n\n // Add API Endpoint\n public function add_endpoint() {\n add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&amp;code=$matches[1]&amp;hash=$matches[2]', 'top');\n add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&amp;code=$matches[1]', 'top');\n\n flush_rewrite_rules(false); //// &lt;---------- REMOVE THIS WHEN DONE\n }\n\n // Sniff Requests\n public function sniff_requests($wp_query) {\n global $wp;\n\n if(isset($wp-&gt;query_vars[ static::ENDPOINT_QUERY_NAME ])) {\n $this-&gt;handle_request(); // handle it\n }\n }\n\n // Handle Requests\n protected function handle_request() {\n // Control the template used\n\n add_filter('template_include', function($original_template) {\n\n // global $wp_query;\n // var_dump ( $wp_query-&gt;query_vars );\n\n // var_dump($original_template);\n\n return get_template_directory() . '/crazy-hash.php';\n });\n }\n }\n\n $hashEP = new HashPoint();\n $hashEP-&gt;init();\n\nendif; // HashPoint\n</code></pre>\n\n<p><strong>CRAZY HASH TEMPLATE</strong></p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Crazy Hash\n */\nget_header();\n\nglobal $wp_query;\n$code = $wp_query-&gt;query_vars[ 'code' ];\n$hash = empty($wp_query-&gt;query_vars[ 'hash' ]) ? 'NONE' : $wp_query-&gt;query_vars[ 'hash' ];\n$hash = urldecode($hash);\n\necho 'Code : ' . $code;\necho '&lt;br /&gt;';\necho 'Hash : ' . $hash;\necho '&lt;br /&gt;';\necho '&lt;br /&gt;';\n\nrequire_once(ABSPATH . 'wp-includes/class-phpass.php');\n$wp_hasher = new PasswordHash(8, true);\n\n$plain = $_SERVER[ 'SERVER_NAME' ] . '-' . $code;\n$hash_mash = wp_hash_password($plain);\n\n// make sure we don't have any `/` to break the url\nwhile(strpos($hash_mash, '/')) {\n $hash_mash = wp_hash_password($plain);\n}\n\necho 'Valid?&lt;br /&gt;';\n\nif($wp_hasher-&gt;CheckPassword($plain, $hash)) {\n echo \"YES, Matched&lt;br /&gt;&lt;br /&gt;\";\n}\nelse {\n echo \"No, BAD HASH!!!&lt;br /&gt;&lt;br /&gt;\";\n}\n\n$url = get_home_url(NULL, 'CPT/' . $code . '/' . urlencode($hash_mash));\n\necho \"Try this Hash : &lt;a href=\\\"$url\\\"&gt;$hash_mash&lt;/a&gt;\";\necho '&lt;br /&gt;&lt;br /&gt;';\n\n// ... more ...\n\nget_footer();\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #2 | LIFETIME NONCE</strong></p>\n\n<p>For @birgire - To make a lifetime nonce wouldn't you just need to remove the <code>wp_nonce_tick()</code> from <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/pluggable.php#L1880\" rel=\"nofollow\">wp_create_nonce</a>?</p>\n\n<pre><code>function wp_create_lifetime_nonce($action = - 1) {\n $user = wp_get_current_user();\n $uid = (int) $user-&gt;ID;\n if( ! $uid) { \n $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action);\n }\n\n $token = wp_get_session_token();\n $i = 0;//wp_nonce_tick(); -- time is not a factor anymore\n\n return substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10);\n}\n\nfunction wp_verify_lifetime_nonce($nonce, $action = - 1) {\n $nonce = (string) $nonce;\n $user = wp_get_current_user();\n $uid = (int) $user-&gt;ID;\n if( ! $uid) {\n $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action);\n }\n\n if(empty($nonce)) {\n return false;\n }\n\n $token = wp_get_session_token();\n $i = 0; //wp_nonce_tick(); -- time is not a factor anymore\n\n // Nonce generated anytime ago\n $expected = substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10);\n if(hash_equals($expected, $nonce)) {\n return 1;\n }\n\n do_action('wp_verify_lifetime_nonce_failed', $nonce, $action, $user, $token);\n\n // Invalid nonce\n return false;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>$code = 'OI812';\n\n$lifetime_nonce = wp_create_lifetime_nonce($code);\n$nonce = wp_create_nonce($code);\n\necho \"&lt;pre&gt;\";\nprint_r(\n array(\n $code,\n $lifetime_nonce,\n $nonce,\n ! wp_verify_nonce($nonce, $code) ? 'FAILED' : 'WORKED',\n ! wp_verify_lifetime_nonce($lifetime_nonce, $code) ? 'FAILED' : 'WORKED',\n ));\necho \"&lt;/pre&gt;\";\n</code></pre>\n" }, { "answer_id": 212322, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 3, "selected": false, "text": "<p>You could use a partial implementation of <a href=\"http://jwt.io/\" rel=\"noreferrer\">JWTs</a> to pass a unique token including identifying information and the requested post ID (or slug) as the endpoint, and check the identifying info upon validation.</p>\n\n<p>URLs containing a unique token can be <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"noreferrer\">rewritten</a> to pass the token as a specific variable. A <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query\" rel=\"noreferrer\"><code>'parse_query'</code> action hook</a> can then check for the presence of the token variable, and replace the query with one that will return the proper post if the token is valid - or an error if it isn't.</p>\n\n<p>In this manner, only the visitor issued the token could use it to access the post (unless someone else both acquires the token and spoofs the original visitor's IP - this could be further secured with a cookie or session ID of some sort). Forging tokens is impossible without your secret.</p>\n\n<pre><code>$secret = '{insert randomly generated string here}';\n$custom_post_type = 'my_cpt';\n$unique_url_base = 'cpt';\n\nadd_action( 'init', 'wpse_212309_rewrite_unique_token_url' );\n\n/**\n * Adds a rewrite rule to forward URLs in the format /cpt/{unique token} to\n * index.php?post_type=my_cpt&amp;unique_token={unique token}. Supersedes WordPress\n * rewrites for the endpoint.\n **/\nfunction wpse_212309_rewrite_unique_token_url(){\n add_rewrite_rule(\n trailingslashit( $unique_url_base ) . '([^\\.]*.[^\\.]*)$',\n 'index.php?post_type=' . $custom_post_type . '&amp;unique_token=$matches[1]',\n 'top'\n );\n}\n\nadd_action( 'parse_query', 'wpse_212309_decode_unique_token_query' );\n\n/**\n * Replaces queries for the 'my_cpt' post-type containing a unique token with\n * the appropriate 'my_cpt' post if the token is valid (i.e., passed to the\n * server from the client IP to which it was assigned).\n **/\nfunction wpse_212309_decode_unique_token_query( $wp ) {\n if( is_admin() )\n return;\n\n if( isset( $wp-&gt;query_vars[ 'p' ] ) || $custom_post_type != $wp-&gt;query_vars[ 'post_type' ] || empty( $_GET[ 'unique_token' ] ) )\n return;\n\n $post_id = wpse_212309_get_post_id_from_unique_slug( $_GET[ 'unique_token' ] );\n\n if( ! $post_id ) {\n $wp-&gt;set_404();\n status_header( 404 );\n return;\n }\n\n $wp-&gt;parse_request( 'p=' . $post_id );\n}\n\n/**\n * Encodes data into a URL-friendly JWT-esque token including IP information\n * for the requesting party, as well as an optional expiration timestamp.\n **/\nfunction wpse_212309_encode_token( $payload, $expiration = null ) { \n $payload[ 'aud' ] = hash( 'md5', $_SERVER[ 'REMOTE_ADDR' ] . $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] );\n $payload[ 'iss' ] = time();\n\n if( isset( $expiration ) )\n $payload[ 'exp' ] = $expiration;\n\n $payload = base64_encode( json_encode( $payload ) );\n $hash = hash( 'md5', $payload . $secret );\n\n return urlencode( $payload . '.' . $hash );\n}\n\n/**\n * Decodes a token generated by 'wpse_212309_encode_token()', returning the\n * payload if the token is both unaltered and sent by the original client IP\n * or false otherwise.\n **/\nfunction wpse_212309_decode_token( $token ) {\n if( empty( $token ) || -1 === strpos( $token, '.' ) )\n return false;\n\n $token = urldecode( $token );\n $token = explode( '.', $token );\n $hash = $token[1];\n $payload = $token[0];\n\n // If the payload or the hash is missing, the token's invalid.\n if( empty( $payload ) || empty( $hash ) )\n return false;\n\n $hash_check = hash( 'md5', $payload . $secret );\n\n // Has the payload and/or hash been modified since the token was issued?\n if( $hash_check !== $hash )\n return false;\n\n $payload = base64_decode( $payload );\n\n if( ! $payload )\n return false;\n\n $payload = json_decode( $payload, true );\n\n if( ! $payload )\n return false;\n\n $audience_check = hash( 'md5', $_SERVER[ 'REMOTE_ADDR' ] . $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] );\n\n // Was this token passed to the server by the IP that it was issued to?\n if( $audience_check != $payload[ 'aud' ] )\n return false;\n\n // Does the payload have an expiration date - if so, has it expired?\n if( ! empty( $payload[ 'exp' ] ) &amp;&amp; $payload[ 'exp' ] &gt; time() )\n return false;\n\n // Token validated - return the payload as legitimate data.\n return $payload;\n}\n\n/**\n * Produces a token associating a post ID with a particular client, suitable\n * for inclusion in a URL. Optionally takes a \"time to live\" argument, in\n * in seconds, before the token should expire.\n **/\nfunction wpse_212309_generate_unique_slug( $post_id, $ttl = null ) {\n $expiration = null;\n\n if( $ttl )\n $expiration = time() + $ttl * 1000;\n\n return wpse_212309_encode_token( array( 'pid' =&gt; $post_id ), $expiration );\n}\n\n/**\n * Returns a post ID from a token if the token was in fact issued to the \n * requesting client IP, or false otherwise.\n **/\nfunction wpse_212309_get_post_id_from_unique_slug( $token ) {\n $payload = wpse_212309_decode_token( $token );\n\n if( ! $payload )\n return false;\n\n return $payload[ 'pid' ];\n}\n</code></pre>\n\n<p>How you actually send visitors to the unique URLs containing a token depends on your application (i.e. how you set up your \"search tool\"), but using the implementation above you can retrieve a visitor-unique slug for a post ID like this:</p>\n\n<pre><code>// A slug that only works for the visitor it was issued to:\n$unique_slug = wpse_212309_generate_unique_slug( $post_id );\n\n// OR, for one that additionally expires in an hour:\n$unique_slug = wpse_212309_generate_unique_slug( $post_id, 3600 )\n</code></pre>\n" }, { "answer_id": 212419, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<p>An alternative simple solution.</p>\n\n<h1><em>Creative</em> uses of Nonces</h1>\n\n<p>WordPress has internal system to generate unique hash that can be then verified: <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow\">nonces</a>. Normally nonces are used to prevent <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\" rel=\"nofollow\">CSRF attacks</a>, but considering that <em>out-of-the-box</em> a WP nonce:</p>\n\n<ul>\n<li>is an hash</li>\n<li>may be verified</li>\n<li>is valid only for a limited frame of time</li>\n<li>is coupled to a specific user</li>\n</ul>\n\n<p>It fits quite well all your needs.</p>\n\n<h1>No rewrite rules</h1>\n\n<p>I'll be honest: I don't like WordPress rewrite API. Rules are stored in database, they need to be \"flushed\" before being used, and the API itself is far from ideal.</p>\n\n<p>In cases like this, I would just go a bit low-level, and use the <a href=\"https://developer.wordpress.org/reference/hooks/do_parse_request/\" rel=\"nofollow\"><code>'do_parse_request'</code></a> filter hook to check the secret url and set proper vars if needed.</p>\n\n<h1>The url format</h1>\n\n<p>For the code below I'll assume a link like:</p>\n\n<p><code>home_url( '/s/'. $post_id . '|' . wp_create_nonce('my-cpt'.$post_id) )</code></p>\n\n<p>This makes use of nonces so it is unique per-user and even the same user can use it for a limited amount of time, by default 1 day, but it can be changed using <a href=\"https://developer.wordpress.org/reference/hooks/nonce_life/\" rel=\"nofollow\"><code>'nonce_life'</code></a> filter.</p>\n\n<p>It will look like this <code>https://example.com/s/MTUy|ab5f9370de</code>.</p>\n\n<h1>Decript url and send to post</h1>\n\n<p>With <code>'do_parse_request'</code> filter, we can intercept the request for an url like the one above before is parsed by WordPres, and we can prevent WordPress to further process the url.</p>\n\n<pre><code>is_admin() or add_filter('do_parse_request', function($do, $wp) {\n\n // quick way to get current url\n $url = trim(esc_url_raw(add_query_arg(array())), '/');\n // check if WP has some subfolder in home url\n $path = trim(parse_url(home_url(), PHP_URL_PATH), '/');\n $path and $path .= '/';\n\n // this is not one of ours secret urls, just do nothing\n if (strpos($url, $path.'s/') !== 0) {\n return $do;\n\n // extract post id and nonce from url\n $sectretUrl = explode('|', preg_replace('~^'.$path.'s/~', '', $url), 2);\n $id = (int) base64_decode(urldecode($sectretUrl[0])) ;\n $nonce = empty($sectretUrl[1]) ? false : $sectretUrl[1];\n\n // verify nonce, if not valid let WordPress continue the flow\n // that very likely ends on a 404\n if (!$id || !$nonce || ! wp_verify_nonce($nonce, 'my-cpt'.$id)) {\n return $do;\n\n // everything ok, let's set query var and tell WP don't parse request\n $wp-&gt;query_vars = array('p' =&gt; $id);\n $wp-&gt;is_secret_ok = $id;\n return false;\n\n}, PHP_INT_MAX, 2);\n</code></pre>\n\n<p>That's it, it works. All with a single code snippet of just 15 lines of code (excluding comments). Not even need to flush rewrite rules.</p>\n\n<p>But you still have a problem.</p>\n\n<h1>Disabling standard access</h1>\n\n<p>If you look at the secret url example I wrote above, <code>https://example.com/s/MTUy|ab5f9370de</code>, it's quite easy to understand that first part is something base64-encoded.</p>\n\n<p>If someone tries to decode it, will find the post id. And using an url like <code>\"http://example.com?p={$decoded_id}\"</code> that person will be able to view the post.</p>\n\n<p>Moreover, I guess that the title of the post is visible. If you use the slug that WordPress autogenerates, using an url like <code>\"http://example.com?p={$guessed_slug}\"</code> your post will be visible again.</p>\n\n<p>This means you need to prevent access to standard url for the CPT post. Maybe only allow privileged users, like administrators and editors.</p>\n\n<pre><code>add_action('template_redirect', function() {\n // when not our CPT or user is privileged, do nothing\n if (! is_singular('my-cpt') || current_user_can('edit_others_posts')) {\n return;\n }\n global $wp;\n // if this is from \"standard\" url, exit with error\n if (! isset($wp-&gt;is_secret_ok) || $wp-&gt;is_secret_ok !== (int) get_queried_object_id()) {\n wp_die('Not allowed.');\n }\n // prevent canonical redirect that will ends in a 404 request\n add_filter('redirect_canonical', '__return_false');\n}, -1);\n</code></pre>\n\n<p>To prevent access to users that comes from \"standard\" url, I used a variable <code>$wp-&gt;is_secret_ok</code> that I set in the previous code snippet, when the hashed url is verified.</p>\n\n<h1>Creating the secret CPT link</h1>\n\n<p>The url that we need is a bit complex, so we may want to create a function that builds it, taking as param the post ID.</p>\n\n<p>It is also possible to use that function to filter the permalink and let WordPress automatically output the \"secret\" url when you just call <code>the_permalink()</code>.</p>\n\n<p>Something like this:</p>\n\n<pre><code>function my_cpt_secret_url($postId) {\n $id = urlencode(base64_encode((string)$postId));\n\n return home_url('/s/'.$id.'|'.wp_create_nonce('my-cpt'.$postId));\n}\n\nis_admin() or add_filter('post_type_link', function($link, $post) {\n if ($post-&gt;post_type === 'my-cpt') {\n return my_cpt_secret_url($post-&gt;ID)\n return $link;\n}, 30, 2);\n</code></pre>\n" } ]
2015/12/18
[ "https://wordpress.stackexchange.com/questions/212309", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64488/" ]
I have created a small search tool that unless you know the EXACT code, you will not be taken to the post. For example, if I enter "OI812" it will take me to a custom post type that is ../CPT/OI812. The CPT is not part of the regular search and I've removed anything with that slug from a canonical redirect. Unless they use my small search tool and enter the code exactly, it will not take them to the page. So far, so good. However, I would like to have a uniquely generated URL every time they access the page. E.G. ../CPT/HASHorSOMETHINGcrazyANDrandom. This would make sharing the URL useless unless they visit the page and enter the code into the search tool. I'm curious how one would go about this? I've searched around but the search terms for something like this seems to be a little ubiquitous. Any help appreciated.
Use [add\_rewrite\_rule](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule) or [add\_rewrite\_endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint) to capture the `HASHorSOMETHINGcrazyANDrandom`. [Hashids](http://hashids.org/php/) could also help you generate a hash that you could read back later. ``` $hashids = new Hashids\Hashids('this is my salt'); $post_id = 1; $request_id = 2; $random = 3; $crazy_id = $hashids->encode($post_id, $request_id, $random); $numbers = $hashids->decode($crazy_id); ``` --- **UPDATE #1** This creates two endpoints: > > <http://example.com/CPT/>{CODE}/{HASH} > > > <http://example.com/CPT/>{CODE}/ > > > In either case a new hash will be generated with a new link everytime. Because I'm using `wp_hash_password` I loop until a password doesn't contain `/` so it won't break the URL. I'm sure there are better ways but... it works for this test. The plain password is based on the `SERVER_NAME` + `{CODE}` which was taken from the first param. Each hash URL is unique but always validates if used with the correct code. --- ``` if( ! class_exists('HashPoint')): class HashPoint { const ENDPOINT_NAME = 'CPT'; // endpoint to capture const ENDPOINT_QUERY_NAME = '__cpt'; // turns to param // WordPress hooks public function init() { add_filter('query_vars', array($this, 'add_query_vars'), 0); add_action('parse_request', array($this, 'sniff_requests'), 0); add_action('init', array($this, 'add_endpoint'), 0); } // Add public query vars public function add_query_vars($vars) { $vars[] = static::ENDPOINT_QUERY_NAME; $vars[] = 'code'; $vars[] = 'hash'; return $vars; } // Add API Endpoint public function add_endpoint() { add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&code=$matches[1]&hash=$matches[2]', 'top'); add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&code=$matches[1]', 'top'); flush_rewrite_rules(false); //// <---------- REMOVE THIS WHEN DONE } // Sniff Requests public function sniff_requests($wp_query) { global $wp; if(isset($wp->query_vars[ static::ENDPOINT_QUERY_NAME ])) { $this->handle_request(); // handle it } } // Handle Requests protected function handle_request() { // Control the template used add_filter('template_include', function($original_template) { // global $wp_query; // var_dump ( $wp_query->query_vars ); // var_dump($original_template); return get_template_directory() . '/crazy-hash.php'; }); } } $hashEP = new HashPoint(); $hashEP->init(); endif; // HashPoint ``` **CRAZY HASH TEMPLATE** ``` <?php /** * Template Name: Crazy Hash */ get_header(); global $wp_query; $code = $wp_query->query_vars[ 'code' ]; $hash = empty($wp_query->query_vars[ 'hash' ]) ? 'NONE' : $wp_query->query_vars[ 'hash' ]; $hash = urldecode($hash); echo 'Code : ' . $code; echo '<br />'; echo 'Hash : ' . $hash; echo '<br />'; echo '<br />'; require_once(ABSPATH . 'wp-includes/class-phpass.php'); $wp_hasher = new PasswordHash(8, true); $plain = $_SERVER[ 'SERVER_NAME' ] . '-' . $code; $hash_mash = wp_hash_password($plain); // make sure we don't have any `/` to break the url while(strpos($hash_mash, '/')) { $hash_mash = wp_hash_password($plain); } echo 'Valid?<br />'; if($wp_hasher->CheckPassword($plain, $hash)) { echo "YES, Matched<br /><br />"; } else { echo "No, BAD HASH!!!<br /><br />"; } $url = get_home_url(NULL, 'CPT/' . $code . '/' . urlencode($hash_mash)); echo "Try this Hash : <a href=\"$url\">$hash_mash</a>"; echo '<br /><br />'; // ... more ... get_footer(); ``` --- **UPDATE #2 | LIFETIME NONCE** For @birgire - To make a lifetime nonce wouldn't you just need to remove the `wp_nonce_tick()` from [wp\_create\_nonce](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/pluggable.php#L1880)? ``` function wp_create_lifetime_nonce($action = - 1) { $user = wp_get_current_user(); $uid = (int) $user->ID; if( ! $uid) { $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action); } $token = wp_get_session_token(); $i = 0;//wp_nonce_tick(); -- time is not a factor anymore return substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10); } function wp_verify_lifetime_nonce($nonce, $action = - 1) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user->ID; if( ! $uid) { $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action); } if(empty($nonce)) { return false; } $token = wp_get_session_token(); $i = 0; //wp_nonce_tick(); -- time is not a factor anymore // Nonce generated anytime ago $expected = substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10); if(hash_equals($expected, $nonce)) { return 1; } do_action('wp_verify_lifetime_nonce_failed', $nonce, $action, $user, $token); // Invalid nonce return false; } ``` --- ``` $code = 'OI812'; $lifetime_nonce = wp_create_lifetime_nonce($code); $nonce = wp_create_nonce($code); echo "<pre>"; print_r( array( $code, $lifetime_nonce, $nonce, ! wp_verify_nonce($nonce, $code) ? 'FAILED' : 'WORKED', ! wp_verify_lifetime_nonce($lifetime_nonce, $code) ? 'FAILED' : 'WORKED', )); echo "</pre>"; ```
212,325
<p>Assuming you write a plugin and hook into <a href="https://developer.wordpress.org/plugins/the-basics/activation-deactivation-hooks/" rel="nofollow noreferrer">activation / deactivation</a> to <a href="https://codex.wordpress.org/Function_Reference/register_post_type" rel="nofollow noreferrer">register_post_type</a> is that good enough? Or do you need to do it every <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/init" rel="nofollow noreferrer">init</a>?</p> <p>I'm looking for perf boosts and I want to reduce unnecessary calls.</p> <p><a href="https://generatewp.com/post-type/" rel="nofollow noreferrer">GenerateWP</a> uses <code>add_action( 'init', 'custom_post_type', 0 );</code> so that might be as early as I might want to register it.</p> <p><strong>FINDINGS</strong></p> <ul> <li><p><a href="https://wordpress.stackexchange.com/a/212326/84219">@s-ha-dum</a>: </p> <blockquote> <p><code>register_post_type</code> needs to be called on every page load</p> <p>The <code>post</code> data itself is kept in the database, but the registration tells the PHP what to do with it.</p> </blockquote></li> <li><p><a href="https://wordpress.stackexchange.com/a/212327/84219">@pieter-goosen</a>: </p> <blockquote> <p>Build in types are actually registered twice on every page load (due to localization that is only available on <code>init</code>)</p> </blockquote></li> </ul>
[ { "answer_id": 212316, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">add_rewrite_rule</a> or <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add_rewrite_endpoint</a> to capture the <code>HASHorSOMETHINGcrazyANDrandom</code>. </p>\n\n<p><a href=\"http://hashids.org/php/\" rel=\"nofollow\">Hashids</a> could also help you generate a hash that you could read back later.</p>\n\n<pre><code>$hashids = new Hashids\\Hashids('this is my salt');\n\n$post_id = 1;\n$request_id = 2;\n$random = 3;\n\n$crazy_id = $hashids-&gt;encode($post_id, $request_id, $random);\n\n$numbers = $hashids-&gt;decode($crazy_id);\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #1</strong></p>\n\n<p>This creates two endpoints:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/CPT/\" rel=\"nofollow\">http://example.com/CPT/</a>{CODE}/{HASH}</p>\n \n <p><a href=\"http://example.com/CPT/\" rel=\"nofollow\">http://example.com/CPT/</a>{CODE}/</p>\n</blockquote>\n\n<p>In either case a new hash will be generated with a new link everytime. Because I'm using <code>wp_hash_password</code> I loop until a password doesn't contain <code>/</code> so it won't break the URL. I'm sure there are better ways but... it works for this test. The plain password is based on the <code>SERVER_NAME</code> + <code>{CODE}</code> which was taken from the first param.</p>\n\n<p>Each hash URL is unique but always validates if used with the correct code.</p>\n\n<hr>\n\n<pre><code>if( ! class_exists('HashPoint')):\n\n class HashPoint {\n\n const ENDPOINT_NAME = 'CPT'; // endpoint to capture\n const ENDPOINT_QUERY_NAME = '__cpt'; // turns to param\n\n // WordPress hooks\n public function init() {\n add_filter('query_vars', array($this, 'add_query_vars'), 0);\n add_action('parse_request', array($this, 'sniff_requests'), 0);\n add_action('init', array($this, 'add_endpoint'), 0);\n }\n\n // Add public query vars\n public function add_query_vars($vars) {\n $vars[] = static::ENDPOINT_QUERY_NAME;\n $vars[] = 'code';\n $vars[] = 'hash';\n\n return $vars;\n }\n\n // Add API Endpoint\n public function add_endpoint() {\n add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&amp;code=$matches[1]&amp;hash=$matches[2]', 'top');\n add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&amp;code=$matches[1]', 'top');\n\n flush_rewrite_rules(false); //// &lt;---------- REMOVE THIS WHEN DONE\n }\n\n // Sniff Requests\n public function sniff_requests($wp_query) {\n global $wp;\n\n if(isset($wp-&gt;query_vars[ static::ENDPOINT_QUERY_NAME ])) {\n $this-&gt;handle_request(); // handle it\n }\n }\n\n // Handle Requests\n protected function handle_request() {\n // Control the template used\n\n add_filter('template_include', function($original_template) {\n\n // global $wp_query;\n // var_dump ( $wp_query-&gt;query_vars );\n\n // var_dump($original_template);\n\n return get_template_directory() . '/crazy-hash.php';\n });\n }\n }\n\n $hashEP = new HashPoint();\n $hashEP-&gt;init();\n\nendif; // HashPoint\n</code></pre>\n\n<p><strong>CRAZY HASH TEMPLATE</strong></p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Crazy Hash\n */\nget_header();\n\nglobal $wp_query;\n$code = $wp_query-&gt;query_vars[ 'code' ];\n$hash = empty($wp_query-&gt;query_vars[ 'hash' ]) ? 'NONE' : $wp_query-&gt;query_vars[ 'hash' ];\n$hash = urldecode($hash);\n\necho 'Code : ' . $code;\necho '&lt;br /&gt;';\necho 'Hash : ' . $hash;\necho '&lt;br /&gt;';\necho '&lt;br /&gt;';\n\nrequire_once(ABSPATH . 'wp-includes/class-phpass.php');\n$wp_hasher = new PasswordHash(8, true);\n\n$plain = $_SERVER[ 'SERVER_NAME' ] . '-' . $code;\n$hash_mash = wp_hash_password($plain);\n\n// make sure we don't have any `/` to break the url\nwhile(strpos($hash_mash, '/')) {\n $hash_mash = wp_hash_password($plain);\n}\n\necho 'Valid?&lt;br /&gt;';\n\nif($wp_hasher-&gt;CheckPassword($plain, $hash)) {\n echo \"YES, Matched&lt;br /&gt;&lt;br /&gt;\";\n}\nelse {\n echo \"No, BAD HASH!!!&lt;br /&gt;&lt;br /&gt;\";\n}\n\n$url = get_home_url(NULL, 'CPT/' . $code . '/' . urlencode($hash_mash));\n\necho \"Try this Hash : &lt;a href=\\\"$url\\\"&gt;$hash_mash&lt;/a&gt;\";\necho '&lt;br /&gt;&lt;br /&gt;';\n\n// ... more ...\n\nget_footer();\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE #2 | LIFETIME NONCE</strong></p>\n\n<p>For @birgire - To make a lifetime nonce wouldn't you just need to remove the <code>wp_nonce_tick()</code> from <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/pluggable.php#L1880\" rel=\"nofollow\">wp_create_nonce</a>?</p>\n\n<pre><code>function wp_create_lifetime_nonce($action = - 1) {\n $user = wp_get_current_user();\n $uid = (int) $user-&gt;ID;\n if( ! $uid) { \n $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action);\n }\n\n $token = wp_get_session_token();\n $i = 0;//wp_nonce_tick(); -- time is not a factor anymore\n\n return substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10);\n}\n\nfunction wp_verify_lifetime_nonce($nonce, $action = - 1) {\n $nonce = (string) $nonce;\n $user = wp_get_current_user();\n $uid = (int) $user-&gt;ID;\n if( ! $uid) {\n $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action);\n }\n\n if(empty($nonce)) {\n return false;\n }\n\n $token = wp_get_session_token();\n $i = 0; //wp_nonce_tick(); -- time is not a factor anymore\n\n // Nonce generated anytime ago\n $expected = substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10);\n if(hash_equals($expected, $nonce)) {\n return 1;\n }\n\n do_action('wp_verify_lifetime_nonce_failed', $nonce, $action, $user, $token);\n\n // Invalid nonce\n return false;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>$code = 'OI812';\n\n$lifetime_nonce = wp_create_lifetime_nonce($code);\n$nonce = wp_create_nonce($code);\n\necho \"&lt;pre&gt;\";\nprint_r(\n array(\n $code,\n $lifetime_nonce,\n $nonce,\n ! wp_verify_nonce($nonce, $code) ? 'FAILED' : 'WORKED',\n ! wp_verify_lifetime_nonce($lifetime_nonce, $code) ? 'FAILED' : 'WORKED',\n ));\necho \"&lt;/pre&gt;\";\n</code></pre>\n" }, { "answer_id": 212322, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 3, "selected": false, "text": "<p>You could use a partial implementation of <a href=\"http://jwt.io/\" rel=\"noreferrer\">JWTs</a> to pass a unique token including identifying information and the requested post ID (or slug) as the endpoint, and check the identifying info upon validation.</p>\n\n<p>URLs containing a unique token can be <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"noreferrer\">rewritten</a> to pass the token as a specific variable. A <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query\" rel=\"noreferrer\"><code>'parse_query'</code> action hook</a> can then check for the presence of the token variable, and replace the query with one that will return the proper post if the token is valid - or an error if it isn't.</p>\n\n<p>In this manner, only the visitor issued the token could use it to access the post (unless someone else both acquires the token and spoofs the original visitor's IP - this could be further secured with a cookie or session ID of some sort). Forging tokens is impossible without your secret.</p>\n\n<pre><code>$secret = '{insert randomly generated string here}';\n$custom_post_type = 'my_cpt';\n$unique_url_base = 'cpt';\n\nadd_action( 'init', 'wpse_212309_rewrite_unique_token_url' );\n\n/**\n * Adds a rewrite rule to forward URLs in the format /cpt/{unique token} to\n * index.php?post_type=my_cpt&amp;unique_token={unique token}. Supersedes WordPress\n * rewrites for the endpoint.\n **/\nfunction wpse_212309_rewrite_unique_token_url(){\n add_rewrite_rule(\n trailingslashit( $unique_url_base ) . '([^\\.]*.[^\\.]*)$',\n 'index.php?post_type=' . $custom_post_type . '&amp;unique_token=$matches[1]',\n 'top'\n );\n}\n\nadd_action( 'parse_query', 'wpse_212309_decode_unique_token_query' );\n\n/**\n * Replaces queries for the 'my_cpt' post-type containing a unique token with\n * the appropriate 'my_cpt' post if the token is valid (i.e., passed to the\n * server from the client IP to which it was assigned).\n **/\nfunction wpse_212309_decode_unique_token_query( $wp ) {\n if( is_admin() )\n return;\n\n if( isset( $wp-&gt;query_vars[ 'p' ] ) || $custom_post_type != $wp-&gt;query_vars[ 'post_type' ] || empty( $_GET[ 'unique_token' ] ) )\n return;\n\n $post_id = wpse_212309_get_post_id_from_unique_slug( $_GET[ 'unique_token' ] );\n\n if( ! $post_id ) {\n $wp-&gt;set_404();\n status_header( 404 );\n return;\n }\n\n $wp-&gt;parse_request( 'p=' . $post_id );\n}\n\n/**\n * Encodes data into a URL-friendly JWT-esque token including IP information\n * for the requesting party, as well as an optional expiration timestamp.\n **/\nfunction wpse_212309_encode_token( $payload, $expiration = null ) { \n $payload[ 'aud' ] = hash( 'md5', $_SERVER[ 'REMOTE_ADDR' ] . $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] );\n $payload[ 'iss' ] = time();\n\n if( isset( $expiration ) )\n $payload[ 'exp' ] = $expiration;\n\n $payload = base64_encode( json_encode( $payload ) );\n $hash = hash( 'md5', $payload . $secret );\n\n return urlencode( $payload . '.' . $hash );\n}\n\n/**\n * Decodes a token generated by 'wpse_212309_encode_token()', returning the\n * payload if the token is both unaltered and sent by the original client IP\n * or false otherwise.\n **/\nfunction wpse_212309_decode_token( $token ) {\n if( empty( $token ) || -1 === strpos( $token, '.' ) )\n return false;\n\n $token = urldecode( $token );\n $token = explode( '.', $token );\n $hash = $token[1];\n $payload = $token[0];\n\n // If the payload or the hash is missing, the token's invalid.\n if( empty( $payload ) || empty( $hash ) )\n return false;\n\n $hash_check = hash( 'md5', $payload . $secret );\n\n // Has the payload and/or hash been modified since the token was issued?\n if( $hash_check !== $hash )\n return false;\n\n $payload = base64_decode( $payload );\n\n if( ! $payload )\n return false;\n\n $payload = json_decode( $payload, true );\n\n if( ! $payload )\n return false;\n\n $audience_check = hash( 'md5', $_SERVER[ 'REMOTE_ADDR' ] . $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] );\n\n // Was this token passed to the server by the IP that it was issued to?\n if( $audience_check != $payload[ 'aud' ] )\n return false;\n\n // Does the payload have an expiration date - if so, has it expired?\n if( ! empty( $payload[ 'exp' ] ) &amp;&amp; $payload[ 'exp' ] &gt; time() )\n return false;\n\n // Token validated - return the payload as legitimate data.\n return $payload;\n}\n\n/**\n * Produces a token associating a post ID with a particular client, suitable\n * for inclusion in a URL. Optionally takes a \"time to live\" argument, in\n * in seconds, before the token should expire.\n **/\nfunction wpse_212309_generate_unique_slug( $post_id, $ttl = null ) {\n $expiration = null;\n\n if( $ttl )\n $expiration = time() + $ttl * 1000;\n\n return wpse_212309_encode_token( array( 'pid' =&gt; $post_id ), $expiration );\n}\n\n/**\n * Returns a post ID from a token if the token was in fact issued to the \n * requesting client IP, or false otherwise.\n **/\nfunction wpse_212309_get_post_id_from_unique_slug( $token ) {\n $payload = wpse_212309_decode_token( $token );\n\n if( ! $payload )\n return false;\n\n return $payload[ 'pid' ];\n}\n</code></pre>\n\n<p>How you actually send visitors to the unique URLs containing a token depends on your application (i.e. how you set up your \"search tool\"), but using the implementation above you can retrieve a visitor-unique slug for a post ID like this:</p>\n\n<pre><code>// A slug that only works for the visitor it was issued to:\n$unique_slug = wpse_212309_generate_unique_slug( $post_id );\n\n// OR, for one that additionally expires in an hour:\n$unique_slug = wpse_212309_generate_unique_slug( $post_id, 3600 )\n</code></pre>\n" }, { "answer_id": 212419, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<p>An alternative simple solution.</p>\n\n<h1><em>Creative</em> uses of Nonces</h1>\n\n<p>WordPress has internal system to generate unique hash that can be then verified: <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow\">nonces</a>. Normally nonces are used to prevent <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\" rel=\"nofollow\">CSRF attacks</a>, but considering that <em>out-of-the-box</em> a WP nonce:</p>\n\n<ul>\n<li>is an hash</li>\n<li>may be verified</li>\n<li>is valid only for a limited frame of time</li>\n<li>is coupled to a specific user</li>\n</ul>\n\n<p>It fits quite well all your needs.</p>\n\n<h1>No rewrite rules</h1>\n\n<p>I'll be honest: I don't like WordPress rewrite API. Rules are stored in database, they need to be \"flushed\" before being used, and the API itself is far from ideal.</p>\n\n<p>In cases like this, I would just go a bit low-level, and use the <a href=\"https://developer.wordpress.org/reference/hooks/do_parse_request/\" rel=\"nofollow\"><code>'do_parse_request'</code></a> filter hook to check the secret url and set proper vars if needed.</p>\n\n<h1>The url format</h1>\n\n<p>For the code below I'll assume a link like:</p>\n\n<p><code>home_url( '/s/'. $post_id . '|' . wp_create_nonce('my-cpt'.$post_id) )</code></p>\n\n<p>This makes use of nonces so it is unique per-user and even the same user can use it for a limited amount of time, by default 1 day, but it can be changed using <a href=\"https://developer.wordpress.org/reference/hooks/nonce_life/\" rel=\"nofollow\"><code>'nonce_life'</code></a> filter.</p>\n\n<p>It will look like this <code>https://example.com/s/MTUy|ab5f9370de</code>.</p>\n\n<h1>Decript url and send to post</h1>\n\n<p>With <code>'do_parse_request'</code> filter, we can intercept the request for an url like the one above before is parsed by WordPres, and we can prevent WordPress to further process the url.</p>\n\n<pre><code>is_admin() or add_filter('do_parse_request', function($do, $wp) {\n\n // quick way to get current url\n $url = trim(esc_url_raw(add_query_arg(array())), '/');\n // check if WP has some subfolder in home url\n $path = trim(parse_url(home_url(), PHP_URL_PATH), '/');\n $path and $path .= '/';\n\n // this is not one of ours secret urls, just do nothing\n if (strpos($url, $path.'s/') !== 0) {\n return $do;\n\n // extract post id and nonce from url\n $sectretUrl = explode('|', preg_replace('~^'.$path.'s/~', '', $url), 2);\n $id = (int) base64_decode(urldecode($sectretUrl[0])) ;\n $nonce = empty($sectretUrl[1]) ? false : $sectretUrl[1];\n\n // verify nonce, if not valid let WordPress continue the flow\n // that very likely ends on a 404\n if (!$id || !$nonce || ! wp_verify_nonce($nonce, 'my-cpt'.$id)) {\n return $do;\n\n // everything ok, let's set query var and tell WP don't parse request\n $wp-&gt;query_vars = array('p' =&gt; $id);\n $wp-&gt;is_secret_ok = $id;\n return false;\n\n}, PHP_INT_MAX, 2);\n</code></pre>\n\n<p>That's it, it works. All with a single code snippet of just 15 lines of code (excluding comments). Not even need to flush rewrite rules.</p>\n\n<p>But you still have a problem.</p>\n\n<h1>Disabling standard access</h1>\n\n<p>If you look at the secret url example I wrote above, <code>https://example.com/s/MTUy|ab5f9370de</code>, it's quite easy to understand that first part is something base64-encoded.</p>\n\n<p>If someone tries to decode it, will find the post id. And using an url like <code>\"http://example.com?p={$decoded_id}\"</code> that person will be able to view the post.</p>\n\n<p>Moreover, I guess that the title of the post is visible. If you use the slug that WordPress autogenerates, using an url like <code>\"http://example.com?p={$guessed_slug}\"</code> your post will be visible again.</p>\n\n<p>This means you need to prevent access to standard url for the CPT post. Maybe only allow privileged users, like administrators and editors.</p>\n\n<pre><code>add_action('template_redirect', function() {\n // when not our CPT or user is privileged, do nothing\n if (! is_singular('my-cpt') || current_user_can('edit_others_posts')) {\n return;\n }\n global $wp;\n // if this is from \"standard\" url, exit with error\n if (! isset($wp-&gt;is_secret_ok) || $wp-&gt;is_secret_ok !== (int) get_queried_object_id()) {\n wp_die('Not allowed.');\n }\n // prevent canonical redirect that will ends in a 404 request\n add_filter('redirect_canonical', '__return_false');\n}, -1);\n</code></pre>\n\n<p>To prevent access to users that comes from \"standard\" url, I used a variable <code>$wp-&gt;is_secret_ok</code> that I set in the previous code snippet, when the hashed url is verified.</p>\n\n<h1>Creating the secret CPT link</h1>\n\n<p>The url that we need is a bit complex, so we may want to create a function that builds it, taking as param the post ID.</p>\n\n<p>It is also possible to use that function to filter the permalink and let WordPress automatically output the \"secret\" url when you just call <code>the_permalink()</code>.</p>\n\n<p>Something like this:</p>\n\n<pre><code>function my_cpt_secret_url($postId) {\n $id = urlencode(base64_encode((string)$postId));\n\n return home_url('/s/'.$id.'|'.wp_create_nonce('my-cpt'.$postId));\n}\n\nis_admin() or add_filter('post_type_link', function($link, $post) {\n if ($post-&gt;post_type === 'my-cpt') {\n return my_cpt_secret_url($post-&gt;ID)\n return $link;\n}, 30, 2);\n</code></pre>\n" } ]
2015/12/18
[ "https://wordpress.stackexchange.com/questions/212325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84219/" ]
Assuming you write a plugin and hook into [activation / deactivation](https://developer.wordpress.org/plugins/the-basics/activation-deactivation-hooks/) to [register\_post\_type](https://codex.wordpress.org/Function_Reference/register_post_type) is that good enough? Or do you need to do it every [init](https://codex.wordpress.org/Plugin_API/Action_Reference/init)? I'm looking for perf boosts and I want to reduce unnecessary calls. [GenerateWP](https://generatewp.com/post-type/) uses `add_action( 'init', 'custom_post_type', 0 );` so that might be as early as I might want to register it. **FINDINGS** * [@s-ha-dum](https://wordpress.stackexchange.com/a/212326/84219): > > `register_post_type` needs to be called on every page load > > > The `post` data itself is kept in the database, but the registration tells the PHP what to do with it. > > > * [@pieter-goosen](https://wordpress.stackexchange.com/a/212327/84219): > > Build in types are actually registered twice on every page load (due to localization that is only available on `init`) > > >
Use [add\_rewrite\_rule](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule) or [add\_rewrite\_endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint) to capture the `HASHorSOMETHINGcrazyANDrandom`. [Hashids](http://hashids.org/php/) could also help you generate a hash that you could read back later. ``` $hashids = new Hashids\Hashids('this is my salt'); $post_id = 1; $request_id = 2; $random = 3; $crazy_id = $hashids->encode($post_id, $request_id, $random); $numbers = $hashids->decode($crazy_id); ``` --- **UPDATE #1** This creates two endpoints: > > <http://example.com/CPT/>{CODE}/{HASH} > > > <http://example.com/CPT/>{CODE}/ > > > In either case a new hash will be generated with a new link everytime. Because I'm using `wp_hash_password` I loop until a password doesn't contain `/` so it won't break the URL. I'm sure there are better ways but... it works for this test. The plain password is based on the `SERVER_NAME` + `{CODE}` which was taken from the first param. Each hash URL is unique but always validates if used with the correct code. --- ``` if( ! class_exists('HashPoint')): class HashPoint { const ENDPOINT_NAME = 'CPT'; // endpoint to capture const ENDPOINT_QUERY_NAME = '__cpt'; // turns to param // WordPress hooks public function init() { add_filter('query_vars', array($this, 'add_query_vars'), 0); add_action('parse_request', array($this, 'sniff_requests'), 0); add_action('init', array($this, 'add_endpoint'), 0); } // Add public query vars public function add_query_vars($vars) { $vars[] = static::ENDPOINT_QUERY_NAME; $vars[] = 'code'; $vars[] = 'hash'; return $vars; } // Add API Endpoint public function add_endpoint() { add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&code=$matches[1]&hash=$matches[2]', 'top'); add_rewrite_rule('^' . static::ENDPOINT_NAME . '/([^/]*)/?', 'index.php?' . static::ENDPOINT_QUERY_NAME . '=1&code=$matches[1]', 'top'); flush_rewrite_rules(false); //// <---------- REMOVE THIS WHEN DONE } // Sniff Requests public function sniff_requests($wp_query) { global $wp; if(isset($wp->query_vars[ static::ENDPOINT_QUERY_NAME ])) { $this->handle_request(); // handle it } } // Handle Requests protected function handle_request() { // Control the template used add_filter('template_include', function($original_template) { // global $wp_query; // var_dump ( $wp_query->query_vars ); // var_dump($original_template); return get_template_directory() . '/crazy-hash.php'; }); } } $hashEP = new HashPoint(); $hashEP->init(); endif; // HashPoint ``` **CRAZY HASH TEMPLATE** ``` <?php /** * Template Name: Crazy Hash */ get_header(); global $wp_query; $code = $wp_query->query_vars[ 'code' ]; $hash = empty($wp_query->query_vars[ 'hash' ]) ? 'NONE' : $wp_query->query_vars[ 'hash' ]; $hash = urldecode($hash); echo 'Code : ' . $code; echo '<br />'; echo 'Hash : ' . $hash; echo '<br />'; echo '<br />'; require_once(ABSPATH . 'wp-includes/class-phpass.php'); $wp_hasher = new PasswordHash(8, true); $plain = $_SERVER[ 'SERVER_NAME' ] . '-' . $code; $hash_mash = wp_hash_password($plain); // make sure we don't have any `/` to break the url while(strpos($hash_mash, '/')) { $hash_mash = wp_hash_password($plain); } echo 'Valid?<br />'; if($wp_hasher->CheckPassword($plain, $hash)) { echo "YES, Matched<br /><br />"; } else { echo "No, BAD HASH!!!<br /><br />"; } $url = get_home_url(NULL, 'CPT/' . $code . '/' . urlencode($hash_mash)); echo "Try this Hash : <a href=\"$url\">$hash_mash</a>"; echo '<br /><br />'; // ... more ... get_footer(); ``` --- **UPDATE #2 | LIFETIME NONCE** For @birgire - To make a lifetime nonce wouldn't you just need to remove the `wp_nonce_tick()` from [wp\_create\_nonce](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/pluggable.php#L1880)? ``` function wp_create_lifetime_nonce($action = - 1) { $user = wp_get_current_user(); $uid = (int) $user->ID; if( ! $uid) { $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action); } $token = wp_get_session_token(); $i = 0;//wp_nonce_tick(); -- time is not a factor anymore return substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10); } function wp_verify_lifetime_nonce($nonce, $action = - 1) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user->ID; if( ! $uid) { $uid = apply_filters('lifetime_nonce_user_logged_out', $uid, $action); } if(empty($nonce)) { return false; } $token = wp_get_session_token(); $i = 0; //wp_nonce_tick(); -- time is not a factor anymore // Nonce generated anytime ago $expected = substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), - 12, 10); if(hash_equals($expected, $nonce)) { return 1; } do_action('wp_verify_lifetime_nonce_failed', $nonce, $action, $user, $token); // Invalid nonce return false; } ``` --- ``` $code = 'OI812'; $lifetime_nonce = wp_create_lifetime_nonce($code); $nonce = wp_create_nonce($code); echo "<pre>"; print_r( array( $code, $lifetime_nonce, $nonce, ! wp_verify_nonce($nonce, $code) ? 'FAILED' : 'WORKED', ! wp_verify_lifetime_nonce($lifetime_nonce, $code) ? 'FAILED' : 'WORKED', )); echo "</pre>"; ```
212,345
<p>I have put the below code in <strong>functions.php</strong>. (It's used to hide some options from client.) But the problem is, after adding these codes, images are not uploading, can't even even uploaded photos from library or while creating a new post. Someone pls help</p> <pre><code>echo '&lt;style&gt; #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles,#toplevel_page_vc-general, #menu-settings,#toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts,#menu-appearance, #wp-admin-bar-snap-post, .error { display:none; } &lt;/style&gt;'; </code></pre>
[ { "answer_id": 212353, "author": "Omar Tariq", "author_id": 36718, "author_profile": "https://wordpress.stackexchange.com/users/36718", "pm_score": 1, "selected": false, "text": "<p>Replace your code with this code:-</p>\n\n<pre><code>add_action('wp_footer', 'myCssCode', PHP_INT_MAX);\nfunction myCssCode() {\n ?&gt;\n &lt;style&gt; \n #toplevel_page_wpcf7, \n #wp-admin-bar-wp-logo,\n #screen-meta-links,\n #menu-tools,\n #wp-admin-bar-wpseo-menu,\n #footer-upgrade,\n #toplevel_page_wpfront-user-role-editor-all-roles,\n #toplevel_page_vc-general,\n #menu-settings,\n #toplevel_page_wpseo_dashboard,\n #toplevel_page_revslider,\n #toplevel_page_themepunch-google-fonts,\n #menu-appearance,\n #wp-admin-bar-snap-post,\n .error\n {\n display:none;\n }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 212357, "author": "Gijo Varghese", "author_id": 85428, "author_profile": "https://wordpress.stackexchange.com/users/85428", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php \nadd_action( 'admin_head', 'admin_css' );\n function admin_css(){ ?&gt;\n &lt;style&gt; \n #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles,#toplevel_page_vc-general, #menu-settings,#toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts,#menu-appearance, #wp-admin-bar-snap-post, .error\n {\n display:none;\n }\n &lt;/style&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>this one worked</p>\n" } ]
2015/12/19
[ "https://wordpress.stackexchange.com/questions/212345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85428/" ]
I have put the below code in **functions.php**. (It's used to hide some options from client.) But the problem is, after adding these codes, images are not uploading, can't even even uploaded photos from library or while creating a new post. Someone pls help ``` echo '<style> #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles,#toplevel_page_vc-general, #menu-settings,#toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts,#menu-appearance, #wp-admin-bar-snap-post, .error { display:none; } </style>'; ```
Replace your code with this code:- ``` add_action('wp_footer', 'myCssCode', PHP_INT_MAX); function myCssCode() { ?> <style> #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles, #toplevel_page_vc-general, #menu-settings, #toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts, #menu-appearance, #wp-admin-bar-snap-post, .error { display:none; } </style> <?php } ```
212,346
<p>My problem is simple, I just don't want user to shop unless and until user is not logged in. I also want to show specific message "Please Log In First" instead of price or add to cart button on the single product page.</p> <p>I can hide price and add to cart functionality by using...</p> <pre><code>if (!is_user_logged_in()) { //Remove single product add to cart remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30); //Remove single product price remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10); //Remove loop add to cart remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart'); //Remove loop price remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10); } </code></pre> <p>How can I show message "Please log in first" on single product page instead of add to cart button?</p>
[ { "answer_id": 212353, "author": "Omar Tariq", "author_id": 36718, "author_profile": "https://wordpress.stackexchange.com/users/36718", "pm_score": 1, "selected": false, "text": "<p>Replace your code with this code:-</p>\n\n<pre><code>add_action('wp_footer', 'myCssCode', PHP_INT_MAX);\nfunction myCssCode() {\n ?&gt;\n &lt;style&gt; \n #toplevel_page_wpcf7, \n #wp-admin-bar-wp-logo,\n #screen-meta-links,\n #menu-tools,\n #wp-admin-bar-wpseo-menu,\n #footer-upgrade,\n #toplevel_page_wpfront-user-role-editor-all-roles,\n #toplevel_page_vc-general,\n #menu-settings,\n #toplevel_page_wpseo_dashboard,\n #toplevel_page_revslider,\n #toplevel_page_themepunch-google-fonts,\n #menu-appearance,\n #wp-admin-bar-snap-post,\n .error\n {\n display:none;\n }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 212357, "author": "Gijo Varghese", "author_id": 85428, "author_profile": "https://wordpress.stackexchange.com/users/85428", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php \nadd_action( 'admin_head', 'admin_css' );\n function admin_css(){ ?&gt;\n &lt;style&gt; \n #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles,#toplevel_page_vc-general, #menu-settings,#toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts,#menu-appearance, #wp-admin-bar-snap-post, .error\n {\n display:none;\n }\n &lt;/style&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>this one worked</p>\n" } ]
2015/12/19
[ "https://wordpress.stackexchange.com/questions/212346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85583/" ]
My problem is simple, I just don't want user to shop unless and until user is not logged in. I also want to show specific message "Please Log In First" instead of price or add to cart button on the single product page. I can hide price and add to cart functionality by using... ``` if (!is_user_logged_in()) { //Remove single product add to cart remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30); //Remove single product price remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10); //Remove loop add to cart remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart'); //Remove loop price remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10); } ``` How can I show message "Please log in first" on single product page instead of add to cart button?
Replace your code with this code:- ``` add_action('wp_footer', 'myCssCode', PHP_INT_MAX); function myCssCode() { ?> <style> #toplevel_page_wpcf7, #wp-admin-bar-wp-logo, #screen-meta-links, #menu-tools, #wp-admin-bar-wpseo-menu, #footer-upgrade, #toplevel_page_wpfront-user-role-editor-all-roles, #toplevel_page_vc-general, #menu-settings, #toplevel_page_wpseo_dashboard, #toplevel_page_revslider, #toplevel_page_themepunch-google-fonts, #menu-appearance, #wp-admin-bar-snap-post, .error { display:none; } </style> <?php } ```
212,348
<p>I am looking for an option where a custom meta value will be saved when user uploads an attachment.</p> <p>Lets say I need a meta key _example_meta_key and want to save meta value of this as ex087659bh <em>(It will be a randomly generated number, I can take care of this.)</em></p> <p>The problem is, I can't seem to find any filters to add custom meta value on upload. </p> <p>There are some tutorials which shows the way to add fields in media edit form but I need this to be executed at the time of file upload.</p>
[ { "answer_id": 212351, "author": "Omar Tariq", "author_id": 36718, "author_profile": "https://wordpress.stackexchange.com/users/36718", "pm_score": -1, "selected": false, "text": "<p>As @jgraup pointed out. You can use the filter <code>wp_handle_upload</code>. The final code will look like something what is pasted below. You might want to use only one of the two hooks or maybe both of them.</p>\n\n<pre><code>add_filter('wp_handle_upload_prefilter', 'startOfWpHandleUpload', 10, 2 );\n\nfunction startOfWpHandleUpload( $file ) {\n\n /* Here you can access the following properties of the uploaded file\n * before it is processed by the wp_handle_upload function. \n */\n\n /* Name of the uploaded file. */\n $file['name'];\n /* MIME Type of the uploaded file. */\n $file['type'];\n /* Temporary location of the stored file. */\n $file['tmp_name'];\n /* \"0\" for no errror. Don't know what is for error. */\n $file['error'];\n /* size in bytes of the uploaded file. */\n $file['size'];\n\n return $file;\n}\n\nadd_filter('wp_handle_upload', 'endOfWpHandleUpload', 10, 2 );\n\nfunction endOfWpHandleUpload( $file, $type ) {\n\n /* Here you can access the following properties of the uploaded file\n * before it is processed by the wp_handle_upload function.\n */\n\n /* Absolute path of the file on the filesystem of the operating system. */\n $file['file'];\n /* Public accessible URL of the file over the Internet. */\n $file['url'];\n /* MIME type of the file. */\n $file['type'];\n\n return $file;\n}\n</code></pre>\n" }, { "answer_id": 212391, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Use <code>added_post_meta</code> and <code>update_post_meta</code> with the <code>$post_id</code>. For extended properties see this <a href=\"https://wordpress.stackexchange.com/a/212390/84219\">post</a> and <a href=\"https://wordpress.stackexchange.com/a/1065/84219\">this</a> for more image functions.</p>\n\n<pre><code>add_action('added_post_meta', 'wpse_20151218_after_post_meta', 10, 4);\n\nfunction wpse_20151218_after_post_meta($meta_id, $post_id, $meta_key, $meta_value) {\n\n // _wp_attachment_metadata added\n if($meta_key === '_wp_attachment_metadata') {\n\n // Add Custom Field\n update_post_meta($post_id, '_example_meta_key', 'ex087659bh');\n\n // _wp_attached_file\n // _wp_attachment_metadata (serialized)\n // _wp_attachment_image_alt\n // _example_meta_key\n\n $attachment_meta = get_post_meta($post_id);\n }\n}\n</code></pre>\n" } ]
2015/12/19
[ "https://wordpress.stackexchange.com/questions/212348", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85582/" ]
I am looking for an option where a custom meta value will be saved when user uploads an attachment. Lets say I need a meta key \_example\_meta\_key and want to save meta value of this as ex087659bh *(It will be a randomly generated number, I can take care of this.)* The problem is, I can't seem to find any filters to add custom meta value on upload. There are some tutorials which shows the way to add fields in media edit form but I need this to be executed at the time of file upload.
Use `added_post_meta` and `update_post_meta` with the `$post_id`. For extended properties see this [post](https://wordpress.stackexchange.com/a/212390/84219) and [this](https://wordpress.stackexchange.com/a/1065/84219) for more image functions. ``` add_action('added_post_meta', 'wpse_20151218_after_post_meta', 10, 4); function wpse_20151218_after_post_meta($meta_id, $post_id, $meta_key, $meta_value) { // _wp_attachment_metadata added if($meta_key === '_wp_attachment_metadata') { // Add Custom Field update_post_meta($post_id, '_example_meta_key', 'ex087659bh'); // _wp_attached_file // _wp_attachment_metadata (serialized) // _wp_attachment_image_alt // _example_meta_key $attachment_meta = get_post_meta($post_id); } } ```
212,375
<p>I need a code snippet to load css (extra style sheet?) when a author is logged in. This is for a custom dashboard and post "page".</p> <p><a href="https://i.stack.imgur.com/pW6fb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pW6fb.jpg" alt="enter image description here"></a></p> <p>The screenshot is what i mean by post page. I want to hide stuf by css for only authors. Things within the red circles are things i want to hide.</p>
[ { "answer_id": 212376, "author": "Alexey", "author_id": 7314, "author_profile": "https://wordpress.stackexchange.com/users/7314", "pm_score": 0, "selected": false, "text": "<p>Get current user ID and compare it with post author ID. If they are equal then load extra style sheet.</p>\n\n<p>To get current user ID use\n<code>$user_ID = get_current_user_id();</code></p>\n\n<p>To get post author ID use\n<code>$author_ID = get_the_author();</code></p>\n\n<p>The best practice to load style sheet is to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\">wp_enqueue_style()</a> function.</p>\n" }, { "answer_id": 212395, "author": "Omar Tariq", "author_id": 36718, "author_profile": "https://wordpress.stackexchange.com/users/36718", "pm_score": 1, "selected": false, "text": "<p>Change <code>$url</code> according to your requirements. In the current state the <code>$url</code> links to a stylesheet <code>custom-style.css</code> located in your current active theme's subdirectory <code>admin</code>. I tested this code and it is working fine. Enjoy :-)</p>\n\n<pre><code>/**\n * This function registers and enqueues styles on front-end if\n * logged-in user has a role 'author'.\n */\nfunction customStylesheetForAuthorsOnly() {\n\n /* Unique slug for the specific resource. */\n $handle = 'unique-css-stylesheet-handle';\n\n /* URL of the stylesheet (resource). */\n $url = get_template_directory_uri() . '/admin/custom-style.css';\n\n /* Array containing the handles of all the dependencies. */\n $dependencies = array();\n\n wp_register_style($handle, $url, $dependencies);\n\n global $current_user;\n get_currentuserinfo();\n\n /* Check if current user has 'author' in his roles */\n if(in_array('author', $current_user-&gt;roles) === true) {\n wp_enqueue_style($handle);\n }\n\n}\nadd_action('admin_enqueue_scripts', 'customStylesheetForAuthorsOnly');\n</code></pre>\n" }, { "answer_id": 212402, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>If a user is not logged in then <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_head\" rel=\"nofollow\">admin_head</a> probably won't run. So let's just check their <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">capabilities</a>.</p>\n\n<pre><code>function my_custom_admin_head() {\n if ( ! current_user_can( 'have-fun' )) :\n ?&gt;&lt;style&gt;\n #welcome-panel{display: none !important;}\n #wp-content-editor-tools{display: none !important;}\n &lt;/style&gt;\n &lt;?php endif; // cant' have-fun\n}\nadd_action( 'admin_head', 'my_custom_admin_head' );\n</code></pre>\n" } ]
2015/12/19
[ "https://wordpress.stackexchange.com/questions/212375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57885/" ]
I need a code snippet to load css (extra style sheet?) when a author is logged in. This is for a custom dashboard and post "page". [![enter image description here](https://i.stack.imgur.com/pW6fb.jpg)](https://i.stack.imgur.com/pW6fb.jpg) The screenshot is what i mean by post page. I want to hide stuf by css for only authors. Things within the red circles are things i want to hide.
If a user is not logged in then [admin\_head](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_head) probably won't run. So let's just check their [capabilities](https://codex.wordpress.org/Roles_and_Capabilities). ``` function my_custom_admin_head() { if ( ! current_user_can( 'have-fun' )) : ?><style> #welcome-panel{display: none !important;} #wp-content-editor-tools{display: none !important;} </style> <?php endif; // cant' have-fun } add_action( 'admin_head', 'my_custom_admin_head' ); ```
212,417
<pre><code>&lt;?php global $post; $post_slug=$post-&gt;post_name; ?&gt; </code></pre> <p>This code is used after <code>&lt;head&gt;</code> and before <code>&lt;body&gt;</code> and is supposed to get current page's slug. It works great, however it will get the <em>slug of first blog post</em> when on <em>"general"</em> blog page. </p> <p>Example:</p> <ul> <li>Blog url: <code>www.my-site.com/blog/ -&gt;</code> slug in admin area is set to <code>blog</code></li> <li>Blog post url: <code>www.my-site.com/post-1/ -&gt;</code> slug in admin area is set to <code>post-1</code></li> </ul> <p>Code echoes <code>post-1</code> for both. <strong>Any ideas?</strong></p>
[ { "answer_id": 212421, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow\">get_queried_object</a> Retrieve the currently-queried object. </p>\n</blockquote>\n\n<pre><code> $queried_object = get_queried_object();\n\n var_dump( $queried_object ); \n</code></pre>\n\n<hr>\n\n<ul>\n<li>if you're on a single post, it will return the post object</li>\n<li>if you're on a page, it will return the page object</li>\n<li>if you're on an archive page, it will return the post type object</li>\n<li>if you're on a category archive, it will return the category object</li>\n<li>if you're on an author archive, it will return the author object</li>\n<li>etc.</li>\n</ul>\n" }, { "answer_id": 212424, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": true, "text": "<blockquote>\n <p>This code is used after <code>&lt;head&gt;</code> and before <code>&lt;body&gt;</code> and is supposed to\n get current page's slug. It works great, however it will get the slug\n of first blog post when on \"general\" blog page.</p>\n</blockquote>\n\n<p><code>$post</code> is going to be set to the first post in the Loop when the page loads. On \"page\" pages with only one post in the Loop that is going to be the page data you expect. On archive pages it will be the first post in the set of posts on the page. This is what appears to be happening. You can't trust <code>$post</code> explicitly like that-- that is, without understanding exactly when it is set to what. (Most loops, even secondary ones, will alter this variable as well)</p>\n\n<p>To get the page data itself you need <code>get_queried_object()</code> but be careful with that too as it will be different on various types of pages-- sometimes a post object, sometimes a user object, sometimes <code>null</code>.</p>\n" }, { "answer_id": 216133, "author": "Zarko Jovic", "author_id": 47318, "author_profile": "https://wordpress.stackexchange.com/users/47318", "pm_score": 0, "selected": false, "text": "<pre><code>global $wp_query;\n$post_id = $wp_query-&gt;post-&gt;ID\n\n$post = get_post( $post_id );\n$slug = $post-&gt;post_name;\n\necho $slug;\n</code></pre>\n\n<p>This should be the best solution in case you have to ask for it from a secondary loop, and if you getting the wrong slug with only the global $post variable.</p>\n" } ]
2015/12/20
[ "https://wordpress.stackexchange.com/questions/212417", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
``` <?php global $post; $post_slug=$post->post_name; ?> ``` This code is used after `<head>` and before `<body>` and is supposed to get current page's slug. It works great, however it will get the *slug of first blog post* when on *"general"* blog page. Example: * Blog url: `www.my-site.com/blog/ ->` slug in admin area is set to `blog` * Blog post url: `www.my-site.com/post-1/ ->` slug in admin area is set to `post-1` Code echoes `post-1` for both. **Any ideas?**
> > This code is used after `<head>` and before `<body>` and is supposed to > get current page's slug. It works great, however it will get the slug > of first blog post when on "general" blog page. > > > `$post` is going to be set to the first post in the Loop when the page loads. On "page" pages with only one post in the Loop that is going to be the page data you expect. On archive pages it will be the first post in the set of posts on the page. This is what appears to be happening. You can't trust `$post` explicitly like that-- that is, without understanding exactly when it is set to what. (Most loops, even secondary ones, will alter this variable as well) To get the page data itself you need `get_queried_object()` but be careful with that too as it will be different on various types of pages-- sometimes a post object, sometimes a user object, sometimes `null`.
212,418
<p>I have <code>index.php</code> with a pagination. The permalink settings is plain permalinks.</p> <p>I have a correct pagination view when I open a page <code>/?paged=2</code> but if I open just <code>index.php</code> I have all posts without pagination. There is my <code>index.php</code>:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $posts_per_page = get_option('posts_per_page'); $args = array('post__in' =&gt; get_option( 'sticky_posts' ),'posts_per_page' =&gt; $posts_per_page, 'paged' =&gt; $paged); $the_query = new WP_Query( $args); if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;div class="section"&gt; &lt;div class="container"&gt; &lt;div class="wrap-content"&gt; &lt;div class="pg-block list"&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;aside class="wrap-aside hid-xs"&gt; &lt;div class="block-inner"&gt; &lt;?php dynamic_sidebar('sidebar-1');?&gt; &lt;/div&gt; &lt;/aside&gt; &lt;/div&gt; &lt;div class="wrap-content"&gt; &lt;?php //number of pages for pagination $total_pages = $the_query-&gt;found_posts / $posts_per_page; if ($the_query-&gt;found_posts % $posts_per_page != 0) $total_pages++; $args_nav = array( 'show_all' =&gt; false, 'end_size' =&gt; 2, 'mid_size' =&gt; 2, 'prev_next' =&gt; True, 'prev_text' =&gt; '', 'next_text' =&gt; '', 'total' =&gt; $total_pages, 'add_args' =&gt; False, 'add_fragment' =&gt; '', 'screen_reader_text' =&gt; ' ' ); the_posts_pagination($args_nav); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e( 'Posts not found' ); ?&gt;&lt;/p&gt; &lt;?php endif; get_footer();?&gt; </code></pre> <p>PS: I just edit my code like that but nothing was changed. The first page displays all posts without pagination</p> <pre><code>&lt;?php if ( have_posts() ) : ?&gt; &lt;div class="section"&gt; &lt;div class="container"&gt; &lt;div class="wrap-content"&gt; &lt;div class="pg-block list"&gt; &lt;?php while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 214900, "author": "franz", "author_id": 87029, "author_profile": "https://wordpress.stackexchange.com/users/87029", "pm_score": 0, "selected": false, "text": "<p>Add this two lines to your theme's function.php file and everything will get back to work:</p>\n\n<pre><code>add_filter(‘redirect_canonical’,’custom_disable_redirect_canonical’);\n\nfunction custom_disable_redirect_canonical($redirect_url) {if (is_paged() &amp;&amp; is_singular()) $redirect_url = false; return $redirect_url; }\n</code></pre>\n" }, { "answer_id": 312366, "author": "Varsha Dhadge", "author_id": 122253, "author_profile": "https://wordpress.stackexchange.com/users/122253", "pm_score": 1, "selected": false, "text": "<p>Adding ignore sticky line inside array should solve the issue :)</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; '6',\n 'ignore_sticky_posts' =&gt; 1,//this is the one :)\n 'paged' =&gt; $paged, \n);\n</code></pre>\n" } ]
2015/12/20
[ "https://wordpress.stackexchange.com/questions/212418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81470/" ]
I have `index.php` with a pagination. The permalink settings is plain permalinks. I have a correct pagination view when I open a page `/?paged=2` but if I open just `index.php` I have all posts without pagination. There is my `index.php`: ``` <?php get_header(); ?> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $posts_per_page = get_option('posts_per_page'); $args = array('post__in' => get_option( 'sticky_posts' ),'posts_per_page' => $posts_per_page, 'paged' => $paged); $the_query = new WP_Query( $args); if ( $the_query->have_posts() ) : ?> <div class="section"> <div class="container"> <div class="wrap-content"> <div class="pg-block list"> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?> </div> <?php wp_reset_postdata(); ?> <aside class="wrap-aside hid-xs"> <div class="block-inner"> <?php dynamic_sidebar('sidebar-1');?> </div> </aside> </div> <div class="wrap-content"> <?php //number of pages for pagination $total_pages = $the_query->found_posts / $posts_per_page; if ($the_query->found_posts % $posts_per_page != 0) $total_pages++; $args_nav = array( 'show_all' => false, 'end_size' => 2, 'mid_size' => 2, 'prev_next' => True, 'prev_text' => '', 'next_text' => '', 'total' => $total_pages, 'add_args' => False, 'add_fragment' => '', 'screen_reader_text' => ' ' ); the_posts_pagination($args_nav); ?> </div> </div> </div> <?php else : ?> <p><?php _e( 'Posts not found' ); ?></p> <?php endif; get_footer();?> ``` PS: I just edit my code like that but nothing was changed. The first page displays all posts without pagination ``` <?php if ( have_posts() ) : ?> <div class="section"> <div class="container"> <div class="wrap-content"> <div class="pg-block list"> <?php while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?> </div> <?php wp_reset_postdata(); ?> ```
Adding ignore sticky line inside array should solve the issue :) ``` $args = array( 'post_type' => 'post', 'posts_per_page' => '6', 'ignore_sticky_posts' => 1,//this is the one :) 'paged' => $paged, ); ```
212,423
<p>I need get all comments of a post including of the meta value.. for eg. i need all comments fields + a meta value.</p> <p>i tried the following code to get but.. its not working</p> <pre><code>$args = array( 'status' =&gt; 'approve', 'type' =&gt; 'comment', 'post_id' =&gt; '99', 'post_type' =&gt; 'product', //'count' =&gt; true, 'meta_query' =&gt; array( array( 'key' =&gt; 'comment_rating_avg_key', 'compare' =&gt; 'EXISTS', ), ), ); $comments_query = new WP_Comment_Query; $comments = $comments_query-&gt;query( $args ); var_dump($comments); </code></pre> <p>Do i need to write a custom query to get it ? or it can be done using default WP functions ?</p>
[ { "answer_id": 212450, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"nofollow\"><code>WP_Comment_Query</code></a> doesn't pull comment meta. You can search by comment meta but the query doesn't return that data. You could easily check this yourself by looking at the Codex.</p>\n\n<p>You need to loop over the results and run <a href=\"https://codex.wordpress.org/Function_Reference/get_comment_meta\" rel=\"nofollow\"><code>get_comment_meta()</code></a>, or essentially do the same via a filter on <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/class-wp-comment-query.php#L438\" rel=\"nofollow\"><code>the_comments</code></a>. </p>\n\n<p>It is also possible to add to the data returned by <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/class-wp-comment-query.php#L810\" rel=\"nofollow\">filtering the \"fields\" clauses</a>:</p>\n\n<pre><code>function add_cmeta_wpse_212423($clauses){\n // var_dump($clauses);\n global $wpdb;\n $meta = \"(SELECT meta_value\n FROM {$wpdb-&gt;commentmeta} \n WHERE (\n comment_id = comment_ID\n AND meta_key = 'test_comment_meta')\n ) as test_comment_meta\";\n $clauses['fields'] .= ', '.$meta;\n return $clauses;\n}\nadd_filter('comments_clauses','add_cmeta_wpse_212423');\n</code></pre>\n\n<p>I created a subquery. You could create a <code>JOIN</code> as well.</p>\n" }, { "answer_id": 411195, "author": "Ali Emadzadeh", "author_id": 214181, "author_profile": "https://wordpress.stackexchange.com/users/214181", "pm_score": 0, "selected": false, "text": "<p>I needed to get comments count with buyer suggestion meta value in my recent woocommerce theme (buyer suggestion done with acf plugin).\nto get the count of amount of all comments with buyer suggestion, below code worked for me. (sorry for my english, its not my native)</p>\n<pre><code>$args = array(\n 'post_id' =&gt; get_the_ID(),\n 'count' =&gt; true,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'viuna-shop-comment-suggest-buying-product',\n 'value' =&gt; 'i-suggest',\n ),\n ),\n);\n\n// The Comment Query\n$comment_query = get_comments($args);\n</code></pre>\n<p>If <code>'count' =&gt; true</code>, it returns only the comments number, if you want the list of comments, remove it.</p>\n" } ]
2015/12/20
[ "https://wordpress.stackexchange.com/questions/212423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18746/" ]
I need get all comments of a post including of the meta value.. for eg. i need all comments fields + a meta value. i tried the following code to get but.. its not working ``` $args = array( 'status' => 'approve', 'type' => 'comment', 'post_id' => '99', 'post_type' => 'product', //'count' => true, 'meta_query' => array( array( 'key' => 'comment_rating_avg_key', 'compare' => 'EXISTS', ), ), ); $comments_query = new WP_Comment_Query; $comments = $comments_query->query( $args ); var_dump($comments); ``` Do i need to write a custom query to get it ? or it can be done using default WP functions ?
[`WP_Comment_Query`](https://codex.wordpress.org/Class_Reference/WP_Comment_Query) doesn't pull comment meta. You can search by comment meta but the query doesn't return that data. You could easily check this yourself by looking at the Codex. You need to loop over the results and run [`get_comment_meta()`](https://codex.wordpress.org/Function_Reference/get_comment_meta), or essentially do the same via a filter on [`the_comments`](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/class-wp-comment-query.php#L438). It is also possible to add to the data returned by [filtering the "fields" clauses](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/class-wp-comment-query.php#L810): ``` function add_cmeta_wpse_212423($clauses){ // var_dump($clauses); global $wpdb; $meta = "(SELECT meta_value FROM {$wpdb->commentmeta} WHERE ( comment_id = comment_ID AND meta_key = 'test_comment_meta') ) as test_comment_meta"; $clauses['fields'] .= ', '.$meta; return $clauses; } add_filter('comments_clauses','add_cmeta_wpse_212423'); ``` I created a subquery. You could create a `JOIN` as well.
212,425
<p>My site is enerating some code for older/newer posts on the category page, but when you click "older" the link does not work. it is generating /blog/page/2 from /blog/</p> <ol> <li><p>Tried a few plugins (WPnavi, Category pagination fix, and a few others that were the first and 2nd rated under "pagination" search) but it didn't work</p></li> <li><p>Tried a bunch of the codes I found on wordpress.org </p></li> <li><p>Only one post category, not a custom post.</p></li> </ol> <p>But nothing seems to be working...</p> <p>Here is the code</p> <pre><code>&lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;A href="&lt;?php the_permalink() ?&gt;" class="noborder"&gt;&lt;?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt; "rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;section class="entry-content"&gt; &lt;?php $content = get_the_content(); $content = strip_tags($content); echo substr($content, 0, 250); ?&gt;... &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;" class="button"&gt;Full Post&lt;/a&gt; &lt;?php endwhile; endif; ?&gt; &lt;/article&gt; &lt;nav&gt; &lt;div class="6u"&gt;&lt;?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class="button"&gt;&amp;larr; Older Posts&lt;/span&gt;' ) ) ?&gt; &lt;div class="6u"&gt;&lt;?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class="button"&gt;&amp;rarr; &lt;/span&gt;' ) ) ?&gt;&lt;/div&gt; &lt;/nav&gt; </code></pre>
[ { "answer_id": 212428, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>Try this code, not much different from your's but with proper nesting. Let me know if that works.</p>\n\n<pre><code>&lt;?php if ( have_posts() ) :\n while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" class=\"noborder\"&gt;&lt;?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?&gt;&lt;/a&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title_attribute(); ?&gt;\" rel=\"bookmark\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n\n &lt;section class=\"entry-content\"&gt;\n &lt;?php $content = get_the_content();\n $content = strip_tags($content);\n echo substr($content, 0, 250) . '...';\n ?&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"Permanent Link to &lt;?php the_title_attribute(); ?&gt;\" class=\"button\"&gt;Full Post&lt;/a&gt;\n &lt;/section&gt;\n\n &lt;/article&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;nav&gt;\n &lt;div class=\"6u\"&gt;&lt;?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class=\"button\"&gt;&amp;larr; Older Posts&lt;/span&gt;' ) ) ?&gt;\n &lt;div class=\"6u\"&gt;&lt;?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class=\"button\"&gt;&amp;rarr; &lt;/span&gt;' ) ) ?&gt;&lt;/div&gt;\n &lt;/nav&gt; \n\n&lt;?php else : ?&gt;\n\n &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 212442, "author": "Cdunn", "author_id": 85626, "author_profile": "https://wordpress.stackexchange.com/users/85626", "pm_score": 0, "selected": false, "text": "<p>Found this to fix my problem, hope it helps someone:</p>\n\n<pre><code> add_action('init','yoursite_init');\nfunction yoursite_init() {\n global $wp_rewrite;\n //add rewrite rule.\n add_rewrite_rule(\"author/([^/]+)/page/?([0-9]{1,})/?$\",'index.php?author_name=$matches[1]&amp;paged=$matches[2]','top');\n add_rewrite_rule(\"(.+?)/page/?([0-9]{1,})/?$\",'index.php?category_name=$matches[1]&amp;paged=$matches[2]','top');\n $wp_rewrite-&gt;flush_rules(false);\n}\n</code></pre>\n" } ]
2015/12/20
[ "https://wordpress.stackexchange.com/questions/212425", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85626/" ]
My site is enerating some code for older/newer posts on the category page, but when you click "older" the link does not work. it is generating /blog/page/2 from /blog/ 1. Tried a few plugins (WPnavi, Category pagination fix, and a few others that were the first and 2nd rated under "pagination" search) but it didn't work 2. Tried a bunch of the codes I found on wordpress.org 3. Only one post category, not a custom post. But nothing seems to be working... Here is the code ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <A href="<?php the_permalink() ?>" class="noborder"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?></a></div> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?> "rel="bookmark"><?php the_title(); ?></a> <section class="entry-content"> <?php $content = get_the_content(); $content = strip_tags($content); echo substr($content, 0, 250); ?>... <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>" class="button">Full Post</a> <?php endwhile; endif; ?> </article> <nav> <div class="6u"><?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&larr; Older Posts</span>' ) ) ?> <div class="6u"><?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&rarr; </span>' ) ) ?></div> </nav> ```
Try this code, not much different from your's but with proper nesting. Let me know if that works. ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <a href="<?php the_permalink() ?>" class="noborder"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?></a> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title(); ?></a> <section class="entry-content"> <?php $content = get_the_content(); $content = strip_tags($content); echo substr($content, 0, 250) . '...'; ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>" class="button">Full Post</a> </section> </article> <?php endwhile; ?> <nav> <div class="6u"><?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&larr; Older Posts</span>' ) ) ?> <div class="6u"><?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&rarr; </span>' ) ) ?></div> </nav> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ```
212,461
<p>I am trying to have 2 php functions automatically inserted in every post for my CPT. The problem I am having is that even though I've found a way to add text, Im not sure how to add the php functions cause with the code I have it adds it as regular text to the post.</p> <p>This is what I have in my functions file ---</p> <pre><code> add_filter( 'default_content', 'my_editor_content', 10, 2 ); function my_editor_content( $content, $post ) { switch( $post-&gt;post_type ) { case 'property': $content = "&lt;div&gt;"; $content . "&lt;?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) { MRP_Multi_Rating_API::display_rating_result( array( 'rating_item_ids' =&gt; 2, 'show_count' =&gt; false, 'result_type' =&gt; 'value_rt', 'no_rating_results_text' =&gt; 'Not Rated' ) ); } ?&gt;&lt;?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) { MRP_Multi_Rating_API::display_rating_result( array( 'rating_item_ids' =&gt; 5, 'show_count' =&gt; false, 'result_type' =&gt; 'overall_rt', 'no_rating_results_text' =&gt; 'Not Rated' ) ); } ?&gt;"; $content = "&lt;/div&gt;"; break; default: $content = "your default content"; break; } return $content; } </code></pre> <p>How can I fix this so my functions work and is it possible to make it add to every post not just the new ones created?</p> <p>Thanks</p>
[ { "answer_id": 212428, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>Try this code, not much different from your's but with proper nesting. Let me know if that works.</p>\n\n<pre><code>&lt;?php if ( have_posts() ) :\n while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" class=\"noborder\"&gt;&lt;?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?&gt;&lt;/a&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title_attribute(); ?&gt;\" rel=\"bookmark\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n\n &lt;section class=\"entry-content\"&gt;\n &lt;?php $content = get_the_content();\n $content = strip_tags($content);\n echo substr($content, 0, 250) . '...';\n ?&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"Permanent Link to &lt;?php the_title_attribute(); ?&gt;\" class=\"button\"&gt;Full Post&lt;/a&gt;\n &lt;/section&gt;\n\n &lt;/article&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;nav&gt;\n &lt;div class=\"6u\"&gt;&lt;?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class=\"button\"&gt;&amp;larr; Older Posts&lt;/span&gt;' ) ) ?&gt;\n &lt;div class=\"6u\"&gt;&lt;?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '&lt;span class=\"button\"&gt;&amp;rarr; &lt;/span&gt;' ) ) ?&gt;&lt;/div&gt;\n &lt;/nav&gt; \n\n&lt;?php else : ?&gt;\n\n &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 212442, "author": "Cdunn", "author_id": 85626, "author_profile": "https://wordpress.stackexchange.com/users/85626", "pm_score": 0, "selected": false, "text": "<p>Found this to fix my problem, hope it helps someone:</p>\n\n<pre><code> add_action('init','yoursite_init');\nfunction yoursite_init() {\n global $wp_rewrite;\n //add rewrite rule.\n add_rewrite_rule(\"author/([^/]+)/page/?([0-9]{1,})/?$\",'index.php?author_name=$matches[1]&amp;paged=$matches[2]','top');\n add_rewrite_rule(\"(.+?)/page/?([0-9]{1,})/?$\",'index.php?category_name=$matches[1]&amp;paged=$matches[2]','top');\n $wp_rewrite-&gt;flush_rules(false);\n}\n</code></pre>\n" } ]
2015/12/20
[ "https://wordpress.stackexchange.com/questions/212461", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
I am trying to have 2 php functions automatically inserted in every post for my CPT. The problem I am having is that even though I've found a way to add text, Im not sure how to add the php functions cause with the code I have it adds it as regular text to the post. This is what I have in my functions file --- ``` add_filter( 'default_content', 'my_editor_content', 10, 2 ); function my_editor_content( $content, $post ) { switch( $post->post_type ) { case 'property': $content = "<div>"; $content . "<?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) { MRP_Multi_Rating_API::display_rating_result( array( 'rating_item_ids' => 2, 'show_count' => false, 'result_type' => 'value_rt', 'no_rating_results_text' => 'Not Rated' ) ); } ?><?php if ( class_exists( 'MRP_Multi_Rating_API' ) ) { MRP_Multi_Rating_API::display_rating_result( array( 'rating_item_ids' => 5, 'show_count' => false, 'result_type' => 'overall_rt', 'no_rating_results_text' => 'Not Rated' ) ); } ?>"; $content = "</div>"; break; default: $content = "your default content"; break; } return $content; } ``` How can I fix this so my functions work and is it possible to make it add to every post not just the new ones created? Thanks
Try this code, not much different from your's but with proper nesting. Let me know if that works. ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <a href="<?php the_permalink() ?>" class="noborder"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?></a> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title(); ?></a> <section class="entry-content"> <?php $content = get_the_content(); $content = strip_tags($content); echo substr($content, 0, 250) . '...'; ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>" class="button">Full Post</a> </section> </article> <?php endwhile; ?> <nav> <div class="6u"><?php next_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&larr; Older Posts</span>' ) ) ?> <div class="6u"><?php previous_posts_link(sprintf( __( '%s', 'blankslate' ), '<span class="button">&rarr; </span>' ) ) ?></div> </nav> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ```
212,487
<p>I have a taxonomy called <code>portfolio_cat</code> with its categories.So now I need to create a slider with that categories as a title and their post items. How I can do that? What loop do I need to have so that I could put in a slider categories with their posts?</p> <p>I dont know how to customize this loop to fit in</p> <pre><code>&lt;?php $query = new WP_Query( array('post_type' =&gt; 'portfolio', 'posts_per_page' =&gt; 7, 'order' =&gt; ASC ) ); while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; </code></pre>
[ { "answer_id": 212491, "author": "Peyman Mohamadpour", "author_id": 75020, "author_profile": "https://wordpress.stackexchange.com/users/75020", "pm_score": 2, "selected": false, "text": "<p>You may do this:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'portfolio'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'portfolio_cat',\n 'field' =&gt; 'name',\n 'terms' =&gt; array('cat1', 'cat2', 'cat3'))\n )\n )\n);\n$wp_query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 212496, "author": "Ana DEV", "author_id": 77773, "author_profile": "https://wordpress.stackexchange.com/users/77773", "pm_score": 1, "selected": false, "text": "<p>Here is the working example</p>\n\n<pre><code>&lt;?php\n$member_group_terms = get_terms( 'member_group' );\n ?&gt;\nThen, loop through each one, running a new query each time:\n\n&lt;?php\n foreach ( $member_group_terms as $member_group_term ) {\n $member_group_query = new WP_Query( array(\n 'post_type' =&gt; 'member',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'member_group',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( $member_group_term-&gt;slug ),\n 'operator' =&gt; 'IN'\n )\n )\n) );\n?&gt;\n&lt;h2&gt;&lt;?php echo $member_group_term-&gt;name; ?&gt;&lt;/h2&gt;\n&lt;ul&gt;\n&lt;?php\nif ( $member_group_query-&gt;have_posts() ) : while ( $member_group_query-&gt;have_posts() ) : $member_group_query-&gt;the_post(); ?&gt;\n &lt;li&gt;&lt;?php echo the_title(); ?&gt;&lt;/li&gt;\n&lt;?php endwhile; endif; ?&gt;\n&lt;/ul&gt;\n&lt;?php\n// Reset things, for good measure\n$member_group_query = null;\nwp_reset_postdata();\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 212518, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I'm not going to discuss implementation of a slider, that is too broad. There are a couple of tutorials around which you can look at on how to implement simple sliders</p>\n\n<p>The real issue here is the query itself. Sorting a query by the terms a post belongs to is quite heavy operations, and if not done correctly (<em>no offense, as you have done in your answer</em>), it can be really really expensive. The overly-used method of getting all terms and then looping through them and running a query for each term can have you stuck at an operation making 100 db calls, and that is only on a small site with only a few terms and posts. Very large sites can pack the meat on db calls which can see your SEO rating stuck at minus and page load times deep in the red.</p>\n\n<p>I have done a <a href=\"https://wordpress.stackexchange.com/search?tab=newest&amp;q=usort%20user%3A31545\">few posts on this specific subject</a>, so I actually wanted to mark this as duplicate, but I feel that this needs a fresh look with a different approach.</p>\n\n<p>What I have done in the passed is to do everything (<em>query all the posts, then sort the result and displaying them</em>) in one single operation. This complete query result was then stored in a transient. The setback here is that we store a tremendous amount of serialized data in the transient which again is not really what transients should do.</p>\n\n<p>What I will do here is to build a dynamic sorting script which will do all the hard work and will store only post ID's in a transient (<em>this will take care of not having to store huge amounts of serialized data which can be slow</em>). We will then use the sorted post ID's from the transient to get our posts that we will need. Because posts are saved in a cache, we do not hit the db hard to get our desired posts, we simply query and return the posts from the cache if they are already there</p>\n\n<h2>FEW IMPORTANT NOTES:</h2>\n\n<ul>\n<li><p>Although I have tested the code, it is not fully tested. On my install there are no obvious bugs at this stage. You should however test this fully with debug turned on on a local test install before moving this to production</p></li>\n<li><p>For what it is worth, the code need at least PHP5.4, but you are already on at least PHP5.6, or even better, PHP7 ;-)</p></li>\n<li><p>There are a few <code>orderby</code> parameters that is not excepted by the code. You can extend it if needed. Check the post search I have linked to. I have done a lot of different stuff with <code>usort()</code></p></li>\n<li><p>The code uses the first term returned by <code>get_the_terms</code>, so posts with multiple terms might be sorted incorrectly due to the first term being used</p></li>\n</ul>\n\n<h2>THE SORTING SCRIPTS:</h2>\n\n<p>What we will do is, we will get all the posts according to our needs, but we will only return the post object properties we need to save resources. We will then use <code>usort()</code> to sort the posts according to terms. Instead of creating something static that you will need to alter when needed, we will make this dynamic so you can reuse it as much as you like by only changing the values of the parameters passed</p>\n\n<pre><code>/**\n * Function to return an ordered list of post id's according to the terms they belong to.\n *\n * This function accepts four parameters\n * @param (string) $taxonomy The taxonomy to get posts and terms from\n * @param (array) $args An array of arguments valid in 'WP_Query'\n * @param (array) $term_args An array of arguments valid with 'get_terms'\n * @param (array) $sort An array of parameters used to sort posts in 'usort()'\n * @return $ids\n */\nfunction get_sorted_query_results( \n $taxonomy = 'category', \n $args = [], \n $term_args = [], \n $sort = [] \n) {\n /** \n * To avoid unexpected ordering, we will avoid any odering that is not done by a WP_Post\n * property. If we incounter any ordering outside that, we would simply return false and\n * stop execution\n */\n $avoid_this_ordering = [\n 'none', \n 'type', \n 'rand', \n 'comment_count', \n 'meta_value', \n 'meta_value_num', \n 'post__in'\n ];\n if ( isset( $args['orderby'] ) ) {\n if ( in_array( $args['orderby'], $avoid_this_ordering ) )\n return null;\n }\n\n // Validate and sanitize the taxonomy name\n if ( 'category' !== $taxonomy\n &amp;&amp; 'post_tag' !== $taxonomy\n ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n if ( !taxonomy_exists( $taxonomy ) )\n return null;\n }\n\n // Now that we have run important test, set the transient\n\n // Set a transient to store the post ID's. Excellent for performance\n $transient_name = 'pobt_' . md5( $taxonomy . json_encode( array_merge( $args, $term_args, $sort ) ) );\n if ( false === ( $ids = get_transient ( $transient_name ) ) ) {\n\n // Set up a variable to hold an array of post id and id that should not be duplicated \n // Set our query defaults\n $defaults = [\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date'\n ];\n /**\n * If tax_query isn't explicitely set, we will set a default tax_query to ensure we only get posts\n * from the specific taxonomy. Avoid adding and using category and tag parameters\n */\n if ( !isset( $args['tax_query'] ) ) { \n // Add 'fields'=&gt;'ids' to $term_args to get only term ids\n $term_args['fields'] = 'ids';\n $terms = get_terms( $taxonomy, $term_args );\n if ( $terms ) { // No need to check for WP_Error because we already now the taxonomy exist\n $defaults['tax_query'] = [\n [\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $terms\n ]\n ];\n } else {\n // To avoid unexpected output, return null\n return null;\n }\n }\n // Merge the defaults wih the incoming $args\n $query_args = $defaults;\n if ( $args )\n $query_args = wp_parse_args( $args, $defaults );\n\n // Make sure that 'fields' is always set to 'all' and cannot be overridden\n $query_args['fields'] = 'all';\n // Always allow filters to modify get_posts()\n $query_args['suppress_filters'] = false;\n\n /**\n * Create two separate arrays:\n * - one to hold numeric values like dates and ID's \n * one with lettering strings like names and slugs. \n * \n * This will ensure very reliable sorting and also we\n * will use this to get only specific post fields\n */\n $orderby_num_array = [\n 'date' =&gt; 'post_date', \n 'modified' =&gt; 'post_modified', \n 'ID' =&gt; 'ID', \n 'menu_order' =&gt; 'menu_order',\n 'parent' =&gt; 'post_parent',\n 'author' =&gt; 'post_author'\n ];\n $orderby_letter_array = [\n 'title' =&gt; 'post_title',\n 'name' =&gt; 'post_name',\n ];\n // Merge the two arrays to use the combine array in our filter_has_var\n $orderby_comb_array = array_merge( $orderby_num_array, $orderby_letter_array );\n\n //Now we will filter get_posts to just return the post fields we need\n add_filter( 'posts_fields', function ( $fields ) \n use ( \n $query_args, \n $orderby_comb_array \n )\n {\n global $wpdb;\n\n remove_filter( current_filter(), __FUNCTION__ );\n\n // If $query_args['orderby'] is ID, just get ids\n if ( 'ID' === $query_args['orderby'] ) { \n $fields = \"$wpdb-&gt;posts.ID\";\n } else { \n $extra_field = $orderby_comb_array[$query_args['orderby']];\n $fields = \"$wpdb-&gt;posts.ID, $wpdb-&gt;posts.$extra_field\";\n }\n\n return $fields;\n });\n\n // Now we can query our desired posts\n $q = get_posts( $query_args );\n\n if ( !$q ) \n return null;\n\n /**\n * We must now set defaults to sort by. 'order' will the order in which terms should be sorted\n * 'orderby' by defualt will be the value used to sort posts by in the query. This will be used\n * when a post has the same term as another post, then posts should be sorted by this value\n */\n $sort_defaults = [\n 'order' =&gt; 'ASC', // This will sort terms from a-z\n 'orderby' =&gt; $query_args['orderby'] // Use the default query order\n ];\n\n // Merge the defaults and incoming args\n $sorting_args = $sort_defaults;\n if ( $sort )\n $sorting_args = wp_parse_args( $sort, $sort_defaults );\n\n /**\n * Now we can loop through the posts and sort them with usort()\n *\n * There is a bug in usort causing the following error:\n * usort(): Array was modified by the user comparison function\n * @see https://bugs.php.net/bug.php?id=50688\n * The only workaround is to suppress the error reporting\n * by using the @ sign before usort in versions before PHP7\n *\n * This bug have been fixed in PHP 7, so you can remove @ in you're on PHP 7\n */\n @usort( $q, function ( $a, $b ) \n use ( \n $taxonomy, \n $sorting_args, \n $orderby_num_array, \n $orderby_letter_array \n )\n { \n\n /**\n * Get the respective terms from the posts. We will use the first\n * term's name. We can safely dereference the array as we already\n * made sure that we get posts that has terms from the selected taxonomy\n */\n $post_terms_a = get_the_terms( $a, $taxonomy )[0]-&gt;name;\n $post_terms_b = get_the_terms( $b, $taxonomy )[0]-&gt;name;\n\n // First sort by terms\n if ( $post_terms_a !== $post_terms_b ) {\n if ( 'ASC' === $sorting_args['order'] ) {\n return strcasecmp( $post_terms_a, $post_terms_b );\n } else { \n return strcasecmp( $post_terms_b, $post_terms_a );\n }\n }\n\n /**\n * If we reached this point, terms are the same, we need to sort the posts by \n * $query_args['orderby']\n */\n if ( in_array( $sorting_args['orderby'], $orderby_num_array ) ) {\n if ( 'ASC' === $sorting_args['order'] ) {\n return $a-&gt;$orderby_num_array[$sorting_args['orderby']] &lt; $b-&gt;$orderby_num_array[$sorting_args['orderby']];\n } else { \n return $a-&gt;$orderby_num_array[$sorting_args['orderby']] &gt; $b-&gt;$orderby_num_array[$sorting_args['orderby']];\n }\n } elseif ( in_array( $sorting_args['orderby'], $orderby_letter_array ) ) { \n if ( 'ASC' === $sorting_args['order'] ) {\n return strcasecmp( \n $a-&gt;$orderby_num_array[$sorting_args['orderby']], \n $b-&gt;$orderby_num_array[$sorting_args['orderby']] \n );\n } else { \n return strcasecmp( \n $b-&gt;$orderby_num_array[$sorting_args['orderby']], \n $a-&gt;$orderby_num_array[$sorting_args['orderby']] \n );\n }\n }\n });\n\n // Get all the post id's from the posts\n $ids = wp_list_pluck( $q, 'ID' );\n\n set_transient( $transient_name, $ids, 30*DAY_IN_SECONDS ); \n }\n return $ids;\n}\n</code></pre>\n\n<p>I have commented the code to make it easy to follow. A few notes on the parameters though</p>\n\n<ul>\n<li><p><code>$taxonomy</code>. This is the taxonomy to get terms and posts from</p></li>\n<li><p><code>$args</code>. An array of any valid argument that is acceptable in <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a>. There are a few defaults set, </p>\n\n<pre><code>$defaults = [\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date'\n];\n</code></pre>\n\n<p>so you can use this parameter to set any extras like 'post_type' and a <code>tax_query</code> if you need more specific posts</p></li>\n<li><p><code>$term_args</code>. An array of parameters valid with <code>get_terms</code>. This is used to get more spefic terms from $taxonomy. </p></li>\n<li><p><code>$sort</code> An array of arguments used to determine the sort order in <code>usort()</code>. Valid arguments are <code>order</code> and <code>orderby</code></p></li>\n</ul>\n\n<p>Remember, if you do not need to set a parameter and you need to set one adjacent, pass an empty array, except for <code>$taxonomy</code> which must be set to a valid taxonomy</p>\n\n<h2>EXAMPLE</h2>\n\n<pre><code>$taxonomy = 'my_taxonomy';\n$args = [\n 'post_type' =&gt; 'my_post_type'\n];\n$term_args = [];\n$sort = [\n 'order' =&gt; 'DESC'\n];\n$q = get_sorted_query_results( $taxonomy, $args, $term_args, $sort );\n</code></pre>\n\n<p>This, on my install runs 3 db queries in +/- 0.002 seconds.</p>\n\n<p>We have save all the relevant sorted post ID's in a transient which expires every 30 days. We need to flush it as well when we publish a new post, update, delete or undelete a post. Very generically, you can make use of the <code>transition_post_status</code> hook to flush the transient on the above cases</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_pobt_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_pobt_%')\" );\n});\n</code></pre>\n\n<p>There are quite a <a href=\"https://wordpress.stackexchange.com/search?q=transition_post_status\">lot of examples on site with specific uses</a> to target specific post status changes. You also have the post object available, so you can target specific post types, authors, etc</p>\n\n<p>Now that you have an array of sorted id's you can now query complete posts. Here we would use the <code>post__in</code> parameter and as <code>orderby</code> value to return the desired posts already sorted</p>\n\n<p>From the above example, we would do</p>\n\n<pre><code>if ( $q ) { // Very important check to avoid undesired results if $q is empty\n $query_args = [\n 'post__in' =&gt; $q,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'post__in',\n // Any other parameters\n ];\n $query = new WP_Query( $query_args );\n // Run your loop, see code below\n}\n</code></pre>\n\n<p>All we need to do now is to display the terms names as headings. This is quite simple, compare the current post term with the previous post's term, if they do not match, display term name, otherwise, display nothing</p>\n\n<pre><code>if ( $query-&gt;have_posts() ) {\n // Define variable to hold previous post term name\n $term_string = '';\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // Get the post terms. Use the first term's name\n $term_name = get_the_terms( get_the_ID(), 'TAXONOMY_NAME_HERE' )[0]-&gt;name;\n // Display the taxonomy name if previous and current post term name don't match\n if ( $term_string != $term_name )\n echo '&lt;h2&gt;' . $term_name . '&lt;/h2&gt;'; // Add styling and tags to suite your needs\n\n // Update the $term_string variable\n $term_string = $term_name;\n\n // REST OF YOUR LOOP\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>Here is the complete query as I have run it on my install</p>\n\n<pre><code>$taxonomy = 'category';\n$args = [\n 'post_type' =&gt; 'post'\n];\n$term_args = [];\n$sort = [\n 'order' =&gt; 'DESC'\n];\n$q = get_sorted_query_results( $taxonomy, $args, $term_args, $sort );\n\nif ( $q ) { // Very important check to avoid undesired results if $q is empty\n $query_args = [\n 'posts_per_page' =&gt; count( $q ),\n 'post__in' =&gt; $q,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'post__in',\n // Any other parameters\n ];\n $query = new WP_Query( $query_args );\n\n if ( $query-&gt;have_posts() ) {\n // Define variable to hold previous post term name\n $term_string = '';\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // Get the post terms. Use the first term's name\n $term_name = get_the_terms( get_the_ID(), 'category' )[0]-&gt;name;\n // Display the taxonomy name if previous and current post term name don't match\n if ( $term_string != $term_name )\n echo '&lt;h2&gt;' . $term_name . '&lt;/h2&gt;'; // Add styling and tags to suite your needs\n\n // Update the $term_string variable\n $term_string = $term_name;\n\n // REST OF YOUR LOOP\n the_title();\n\n }\n wp_reset_postdata();\n }\n}\n</code></pre>\n\n<p>On test with 21 posts and 6 categories, the whole operation cost me 7 queries in 0.1 seconds</p>\n\n<p>With the overly-used easy method</p>\n\n<pre><code>$terms= get_terms( 'category' );\nforeach ( $terms as $term ) {\n echo $term-&gt;name;\n $args = [\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; 'category',\n 'terms' =&gt; $term-&gt;term_id,\n ]\n ],\n ];\n $query = new WP_Query( $args );\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n\n the_title();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>I got <strong>32</strong> queries in 0.2 seconds. That is 25 queries (<em>5times more</em>) more, and that is only on 6 categories and 21 posts.</p>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212487", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77773/" ]
I have a taxonomy called `portfolio_cat` with its categories.So now I need to create a slider with that categories as a title and their post items. How I can do that? What loop do I need to have so that I could put in a slider categories with their posts? I dont know how to customize this loop to fit in ``` <?php $query = new WP_Query( array('post_type' => 'portfolio', 'posts_per_page' => 7, 'order' => ASC ) ); while ( $query->have_posts() ) : $query->the_post(); ?> ```
I'm not going to discuss implementation of a slider, that is too broad. There are a couple of tutorials around which you can look at on how to implement simple sliders The real issue here is the query itself. Sorting a query by the terms a post belongs to is quite heavy operations, and if not done correctly (*no offense, as you have done in your answer*), it can be really really expensive. The overly-used method of getting all terms and then looping through them and running a query for each term can have you stuck at an operation making 100 db calls, and that is only on a small site with only a few terms and posts. Very large sites can pack the meat on db calls which can see your SEO rating stuck at minus and page load times deep in the red. I have done a [few posts on this specific subject](https://wordpress.stackexchange.com/search?tab=newest&q=usort%20user%3A31545), so I actually wanted to mark this as duplicate, but I feel that this needs a fresh look with a different approach. What I have done in the passed is to do everything (*query all the posts, then sort the result and displaying them*) in one single operation. This complete query result was then stored in a transient. The setback here is that we store a tremendous amount of serialized data in the transient which again is not really what transients should do. What I will do here is to build a dynamic sorting script which will do all the hard work and will store only post ID's in a transient (*this will take care of not having to store huge amounts of serialized data which can be slow*). We will then use the sorted post ID's from the transient to get our posts that we will need. Because posts are saved in a cache, we do not hit the db hard to get our desired posts, we simply query and return the posts from the cache if they are already there FEW IMPORTANT NOTES: -------------------- * Although I have tested the code, it is not fully tested. On my install there are no obvious bugs at this stage. You should however test this fully with debug turned on on a local test install before moving this to production * For what it is worth, the code need at least PHP5.4, but you are already on at least PHP5.6, or even better, PHP7 ;-) * There are a few `orderby` parameters that is not excepted by the code. You can extend it if needed. Check the post search I have linked to. I have done a lot of different stuff with `usort()` * The code uses the first term returned by `get_the_terms`, so posts with multiple terms might be sorted incorrectly due to the first term being used THE SORTING SCRIPTS: -------------------- What we will do is, we will get all the posts according to our needs, but we will only return the post object properties we need to save resources. We will then use `usort()` to sort the posts according to terms. Instead of creating something static that you will need to alter when needed, we will make this dynamic so you can reuse it as much as you like by only changing the values of the parameters passed ``` /** * Function to return an ordered list of post id's according to the terms they belong to. * * This function accepts four parameters * @param (string) $taxonomy The taxonomy to get posts and terms from * @param (array) $args An array of arguments valid in 'WP_Query' * @param (array) $term_args An array of arguments valid with 'get_terms' * @param (array) $sort An array of parameters used to sort posts in 'usort()' * @return $ids */ function get_sorted_query_results( $taxonomy = 'category', $args = [], $term_args = [], $sort = [] ) { /** * To avoid unexpected ordering, we will avoid any odering that is not done by a WP_Post * property. If we incounter any ordering outside that, we would simply return false and * stop execution */ $avoid_this_ordering = [ 'none', 'type', 'rand', 'comment_count', 'meta_value', 'meta_value_num', 'post__in' ]; if ( isset( $args['orderby'] ) ) { if ( in_array( $args['orderby'], $avoid_this_ordering ) ) return null; } // Validate and sanitize the taxonomy name if ( 'category' !== $taxonomy && 'post_tag' !== $taxonomy ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING ); if ( !taxonomy_exists( $taxonomy ) ) return null; } // Now that we have run important test, set the transient // Set a transient to store the post ID's. Excellent for performance $transient_name = 'pobt_' . md5( $taxonomy . json_encode( array_merge( $args, $term_args, $sort ) ) ); if ( false === ( $ids = get_transient ( $transient_name ) ) ) { // Set up a variable to hold an array of post id and id that should not be duplicated // Set our query defaults $defaults = [ 'posts_per_page' => -1, 'order' => 'DESC', 'orderby' => 'date' ]; /** * If tax_query isn't explicitely set, we will set a default tax_query to ensure we only get posts * from the specific taxonomy. Avoid adding and using category and tag parameters */ if ( !isset( $args['tax_query'] ) ) { // Add 'fields'=>'ids' to $term_args to get only term ids $term_args['fields'] = 'ids'; $terms = get_terms( $taxonomy, $term_args ); if ( $terms ) { // No need to check for WP_Error because we already now the taxonomy exist $defaults['tax_query'] = [ [ 'taxonomy' => $taxonomy, 'terms' => $terms ] ]; } else { // To avoid unexpected output, return null return null; } } // Merge the defaults wih the incoming $args $query_args = $defaults; if ( $args ) $query_args = wp_parse_args( $args, $defaults ); // Make sure that 'fields' is always set to 'all' and cannot be overridden $query_args['fields'] = 'all'; // Always allow filters to modify get_posts() $query_args['suppress_filters'] = false; /** * Create two separate arrays: * - one to hold numeric values like dates and ID's * one with lettering strings like names and slugs. * * This will ensure very reliable sorting and also we * will use this to get only specific post fields */ $orderby_num_array = [ 'date' => 'post_date', 'modified' => 'post_modified', 'ID' => 'ID', 'menu_order' => 'menu_order', 'parent' => 'post_parent', 'author' => 'post_author' ]; $orderby_letter_array = [ 'title' => 'post_title', 'name' => 'post_name', ]; // Merge the two arrays to use the combine array in our filter_has_var $orderby_comb_array = array_merge( $orderby_num_array, $orderby_letter_array ); //Now we will filter get_posts to just return the post fields we need add_filter( 'posts_fields', function ( $fields ) use ( $query_args, $orderby_comb_array ) { global $wpdb; remove_filter( current_filter(), __FUNCTION__ ); // If $query_args['orderby'] is ID, just get ids if ( 'ID' === $query_args['orderby'] ) { $fields = "$wpdb->posts.ID"; } else { $extra_field = $orderby_comb_array[$query_args['orderby']]; $fields = "$wpdb->posts.ID, $wpdb->posts.$extra_field"; } return $fields; }); // Now we can query our desired posts $q = get_posts( $query_args ); if ( !$q ) return null; /** * We must now set defaults to sort by. 'order' will the order in which terms should be sorted * 'orderby' by defualt will be the value used to sort posts by in the query. This will be used * when a post has the same term as another post, then posts should be sorted by this value */ $sort_defaults = [ 'order' => 'ASC', // This will sort terms from a-z 'orderby' => $query_args['orderby'] // Use the default query order ]; // Merge the defaults and incoming args $sorting_args = $sort_defaults; if ( $sort ) $sorting_args = wp_parse_args( $sort, $sort_defaults ); /** * Now we can loop through the posts and sort them with usort() * * There is a bug in usort causing the following error: * usort(): Array was modified by the user comparison function * @see https://bugs.php.net/bug.php?id=50688 * The only workaround is to suppress the error reporting * by using the @ sign before usort in versions before PHP7 * * This bug have been fixed in PHP 7, so you can remove @ in you're on PHP 7 */ @usort( $q, function ( $a, $b ) use ( $taxonomy, $sorting_args, $orderby_num_array, $orderby_letter_array ) { /** * Get the respective terms from the posts. We will use the first * term's name. We can safely dereference the array as we already * made sure that we get posts that has terms from the selected taxonomy */ $post_terms_a = get_the_terms( $a, $taxonomy )[0]->name; $post_terms_b = get_the_terms( $b, $taxonomy )[0]->name; // First sort by terms if ( $post_terms_a !== $post_terms_b ) { if ( 'ASC' === $sorting_args['order'] ) { return strcasecmp( $post_terms_a, $post_terms_b ); } else { return strcasecmp( $post_terms_b, $post_terms_a ); } } /** * If we reached this point, terms are the same, we need to sort the posts by * $query_args['orderby'] */ if ( in_array( $sorting_args['orderby'], $orderby_num_array ) ) { if ( 'ASC' === $sorting_args['order'] ) { return $a->$orderby_num_array[$sorting_args['orderby']] < $b->$orderby_num_array[$sorting_args['orderby']]; } else { return $a->$orderby_num_array[$sorting_args['orderby']] > $b->$orderby_num_array[$sorting_args['orderby']]; } } elseif ( in_array( $sorting_args['orderby'], $orderby_letter_array ) ) { if ( 'ASC' === $sorting_args['order'] ) { return strcasecmp( $a->$orderby_num_array[$sorting_args['orderby']], $b->$orderby_num_array[$sorting_args['orderby']] ); } else { return strcasecmp( $b->$orderby_num_array[$sorting_args['orderby']], $a->$orderby_num_array[$sorting_args['orderby']] ); } } }); // Get all the post id's from the posts $ids = wp_list_pluck( $q, 'ID' ); set_transient( $transient_name, $ids, 30*DAY_IN_SECONDS ); } return $ids; } ``` I have commented the code to make it easy to follow. A few notes on the parameters though * `$taxonomy`. This is the taxonomy to get terms and posts from * `$args`. An array of any valid argument that is acceptable in [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query). There are a few defaults set, ``` $defaults = [ 'posts_per_page' => -1, 'order' => 'DESC', 'orderby' => 'date' ]; ``` so you can use this parameter to set any extras like 'post\_type' and a `tax_query` if you need more specific posts * `$term_args`. An array of parameters valid with `get_terms`. This is used to get more spefic terms from $taxonomy. * `$sort` An array of arguments used to determine the sort order in `usort()`. Valid arguments are `order` and `orderby` Remember, if you do not need to set a parameter and you need to set one adjacent, pass an empty array, except for `$taxonomy` which must be set to a valid taxonomy EXAMPLE ------- ``` $taxonomy = 'my_taxonomy'; $args = [ 'post_type' => 'my_post_type' ]; $term_args = []; $sort = [ 'order' => 'DESC' ]; $q = get_sorted_query_results( $taxonomy, $args, $term_args, $sort ); ``` This, on my install runs 3 db queries in +/- 0.002 seconds. We have save all the relevant sorted post ID's in a transient which expires every 30 days. We need to flush it as well when we publish a new post, update, delete or undelete a post. Very generically, you can make use of the `transition_post_status` hook to flush the transient on the above cases ``` add_action( 'transition_post_status', function () { global $wpdb; $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_pobt_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_pobt_%')" ); }); ``` There are quite a [lot of examples on site with specific uses](https://wordpress.stackexchange.com/search?q=transition_post_status) to target specific post status changes. You also have the post object available, so you can target specific post types, authors, etc Now that you have an array of sorted id's you can now query complete posts. Here we would use the `post__in` parameter and as `orderby` value to return the desired posts already sorted From the above example, we would do ``` if ( $q ) { // Very important check to avoid undesired results if $q is empty $query_args = [ 'post__in' => $q, 'order' => 'ASC', 'orderby' => 'post__in', // Any other parameters ]; $query = new WP_Query( $query_args ); // Run your loop, see code below } ``` All we need to do now is to display the terms names as headings. This is quite simple, compare the current post term with the previous post's term, if they do not match, display term name, otherwise, display nothing ``` if ( $query->have_posts() ) { // Define variable to hold previous post term name $term_string = ''; while ( $query->have_posts() ) { $query->the_post(); // Get the post terms. Use the first term's name $term_name = get_the_terms( get_the_ID(), 'TAXONOMY_NAME_HERE' )[0]->name; // Display the taxonomy name if previous and current post term name don't match if ( $term_string != $term_name ) echo '<h2>' . $term_name . '</h2>'; // Add styling and tags to suite your needs // Update the $term_string variable $term_string = $term_name; // REST OF YOUR LOOP } wp_reset_postdata(); } ``` Here is the complete query as I have run it on my install ``` $taxonomy = 'category'; $args = [ 'post_type' => 'post' ]; $term_args = []; $sort = [ 'order' => 'DESC' ]; $q = get_sorted_query_results( $taxonomy, $args, $term_args, $sort ); if ( $q ) { // Very important check to avoid undesired results if $q is empty $query_args = [ 'posts_per_page' => count( $q ), 'post__in' => $q, 'order' => 'ASC', 'orderby' => 'post__in', // Any other parameters ]; $query = new WP_Query( $query_args ); if ( $query->have_posts() ) { // Define variable to hold previous post term name $term_string = ''; while ( $query->have_posts() ) { $query->the_post(); // Get the post terms. Use the first term's name $term_name = get_the_terms( get_the_ID(), 'category' )[0]->name; // Display the taxonomy name if previous and current post term name don't match if ( $term_string != $term_name ) echo '<h2>' . $term_name . '</h2>'; // Add styling and tags to suite your needs // Update the $term_string variable $term_string = $term_name; // REST OF YOUR LOOP the_title(); } wp_reset_postdata(); } } ``` On test with 21 posts and 6 categories, the whole operation cost me 7 queries in 0.1 seconds With the overly-used easy method ``` $terms= get_terms( 'category' ); foreach ( $terms as $term ) { echo $term->name; $args = [ 'tax_query' => [ [ 'taxonomy' => 'category', 'terms' => $term->term_id, ] ], ]; $query = new WP_Query( $args ); while ( $query->have_posts() ) { $query->the_post(); the_title(); } wp_reset_postdata(); } ``` I got **32** queries in 0.2 seconds. That is 25 queries (*5times more*) more, and that is only on 6 categories and 21 posts.
212,490
<p>I recently had a system crash and had to reinstall WordPress with my backup files.</p> <p>In the JavaScript log I began throwing errors pertaining to the domain and realized I was still using the remote servers URL. So, I read the <em>Changing the Site URL</em> article in the WP Codex and added the following two lines to my <code>config.php</code> file:</p> <pre><code>define('WP_SITEURL','http://localhost:3000'); define('WP_HOME','http://localhost:3000'); </code></pre> <p>If I go to <em>localhost:3000</em> in my browser, it goes instead to <em>localhost</em> and loads the Apache server <em>It works!</em> page. However, I am using PHPs built in server. So please don't drag Apache into this.</p> <p>I do have the ability to go to <em>localhost:3000/wp-admin</em> and login with admin credentials, however when I try to click any of the admin links, I get a 404 not found:</p> <blockquote> <p>The requested resource <em>resource name</em> was not found on this server.</p> </blockquote> <p>Everything was working before the system crash, and I'm fairly confident I started the PHP server in the appropriate directory. Will someone viewing this both tell me how to fix this error, but also more importantly, explain <strong>why</strong> I can't visit my local version of the site? </p> <p>Any assistance will be much appreciated. Thanks.</p>
[ { "answer_id": 212494, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 0, "selected": false, "text": "<p>You can go to your database and check for wp-option table.\nIn that if you will try changing the siteurl and home, I think this will help you out.</p>\n" }, { "answer_id": 212508, "author": "ehmad11", "author_id": 36929, "author_profile": "https://wordpress.stackexchange.com/users/36929", "pm_score": 0, "selected": false, "text": "<p>dump database from remote server open .sql file in a text editor find and replace remote urls to localhost then import the database in localhost</p>\n\n<p>as birgire suggests: this idea is not good for some databases with serialized arrays so i suggest this tool which i have tested and found helpful:</p>\n\n<p><a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n" }, { "answer_id": 212536, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Instead of renaming, set up your local web server to handle requests to that domain and modify your local hosts file to associate the domain with ip 127.0.0.1.</p>\n\n<p>Especially when debugging hard to find bugs you will want your enviroment to be as similar to the one of the live site.</p>\n\n<p>(I can do it in a not very modern version of WAMP and therefor I assume you can do it with all similar web servers)</p>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212490", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85662/" ]
I recently had a system crash and had to reinstall WordPress with my backup files. In the JavaScript log I began throwing errors pertaining to the domain and realized I was still using the remote servers URL. So, I read the *Changing the Site URL* article in the WP Codex and added the following two lines to my `config.php` file: ``` define('WP_SITEURL','http://localhost:3000'); define('WP_HOME','http://localhost:3000'); ``` If I go to *localhost:3000* in my browser, it goes instead to *localhost* and loads the Apache server *It works!* page. However, I am using PHPs built in server. So please don't drag Apache into this. I do have the ability to go to *localhost:3000/wp-admin* and login with admin credentials, however when I try to click any of the admin links, I get a 404 not found: > > The requested resource *resource name* was not found on this server. > > > Everything was working before the system crash, and I'm fairly confident I started the PHP server in the appropriate directory. Will someone viewing this both tell me how to fix this error, but also more importantly, explain **why** I can't visit my local version of the site? Any assistance will be much appreciated. Thanks.
Instead of renaming, set up your local web server to handle requests to that domain and modify your local hosts file to associate the domain with ip 127.0.0.1. Especially when debugging hard to find bugs you will want your enviroment to be as similar to the one of the live site. (I can do it in a not very modern version of WAMP and therefor I assume you can do it with all similar web servers)
212,515
<p>I've added a custom field in comment by using </p> <pre><code>function comment_label($fields){ unset( $fields['url'] ); $fields['rate'] = '&lt;p class="comment_form_rate" id="rate_recipe"&gt; &lt;span class="star_rating"&gt; &lt;input class="star star-5" id="star-5" type="radio" name="rate" value="5"/&gt; &lt;label class="star star-5" for="star-5"&gt;&lt;/label&gt; &lt;input class="star star-4" id="star-4" type="radio" name="rate" value="4"/&gt; &lt;label class="star star-4" for="star-4"&gt;&lt;/label&gt; &lt;input class="star star-3" id="star-3" type="radio" name="rate" value="3"/&gt; &lt;label class="star star-3" for="star-3"&gt;&lt;/label&gt; &lt;input class="star star-2" id="star-2" type="radio" name="rate" value="2"/&gt; &lt;label class="star star-2" for="star-2"&gt;&lt;/label&gt; &lt;input class="star star-1" id="star-1" type="radio" name="rate" value="1"/&gt; &lt;label class="star star-1" for="star-1"&gt;&lt;/label&gt; &lt;/span&gt; &lt;/p&gt;'; return $fields; } </code></pre> <p>which work as intended if you are going to post a comment with an unlogged status.</p> <p>But as soon as you login this field goes away, leaving just with the textarea input of comment and the desired <code>title_reply</code>, even if you don't log as admin but as normal user. This is my <code>comments.php</code> file.</p> <pre><code>&lt;?php if ( post_password_required() ): ?&gt; &lt;p class="nopassword"&gt;&lt;?php _e( 'Questo articolo è protetto da password. Inserisci la password per visualizzare i commenti.', 'wtd' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;div id="comments" class="comments-area"&gt; &lt;?php if ( have_comments() ) : ?&gt; &lt;h2 class="comments-title"&gt; &lt;?php printf( _nx( 'Un commento su &amp;ldquo;%2$s&amp;rdquo;', '%1$s commenti su &amp;ldquo;%2$s&amp;rdquo;', get_comments_number(), 'comments title', 'wtd' ), number_format_i18n( get_comments_number() ), '&lt;span&gt;' . get_the_title() . '&lt;/span&gt;' ); ?&gt; &lt;/h2&gt; &lt;ol class="commentlist"&gt; &lt;?php wp_list_comments( array( 'callback' =&gt; 'wtd_comment', 'style' =&gt; 'p', 'type' =&gt; 'comment', 'per_page' =&gt; 8 ) ); ?&gt; &lt;/ol&gt;&lt;!-- .commentlist --&gt; &lt;?php if ( get_comment_pages_count() &gt; 1 &amp;&amp; get_option( 'page_comments' ) ) : // navigazione dei commenti ?&gt; &lt;nav id="comment-nav-below" class="navigation" role="navigation"&gt; &lt;h1 class="assistive-text section-heading"&gt;&lt;?php _e( 'Paginazione commenti', 'wtd' ); ?&gt;&lt;/h1&gt; &lt;div class="nav-previous"&gt;&lt;?php previous_comments_link( __( '&amp;larr; Commenti Precedenti', 'wtd' ) ); ?&gt;&lt;/div&gt; &lt;div class="nav-next"&gt;&lt;?php next_comments_link( __( 'Nuovi commenti &amp;rarr;', 'wtd' ) ); ?&gt;&lt;/div&gt; &lt;/nav&gt; &lt;?php endif; // check for comment navigation ?&gt; &lt;?php /* If there are no comments and comments are closed, let's leave a note. * But we only want the note on posts and pages that had comments in the first place. */ if ( ! comments_open() &amp;&amp; get_comments_number() ) : ?&gt; &lt;p class="nocomments"&gt;&lt;?php _e( 'I commenti sono chiusi' , 'wtd' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php endif; // have_comments() ?&gt; &lt;?php //argomenti da stampare in front-end $argz = array( 'class_form' =&gt; 'form-control', 'comment_notes_before' =&gt; __('il tuo feedback è importante per noi!','wtd'), 'label_submit' =&gt; __('Commenta','wtd'), 'comment_fields' =&gt; '', 'title_reply' =&gt; __('Valuta questa ricetta','wtd'), ); comment_form($argz); ?&gt; &lt;/div&gt;&lt;!-- #comments .comments-area --&gt; </code></pre> <p>Am I missing something?</p>
[ { "answer_id": 212526, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I fully understand your question, but to add some HTML (just <em>over</em> or <em>under</em> the submit field) that is visible to both <em>logged-in</em> and <em>logged-out</em> users, you can try the following:</p>\n\n<pre><code>add_filter( 'comment_form_submit_field', function( $submit_field )\n{\n //-----------------------------------\n // Adjust the prepend to your needs\n //-----------------------------------\n $prepend = '&lt;p&gt; Prepend some HTML &lt;/p&gt;';\n\n //-----------------------------------\n // Adjust the append to your needs\n //-----------------------------------\n $append = '&lt;p&gt; Append some HTML &lt;/p&gt;';\n\n return $prepend . $submit_field . $append;\n} );\n</code></pre>\n\n<p>Other workarounds are possible, like the <code>comment_form</code> action.</p>\n\n<p>There are some comment-form filters that are only available to <em>logged-out</em> users, like the</p>\n\n<ul>\n<li><code>comment_form_before_fields</code></li>\n<li><code>comment_form_field_{$name}</code></li>\n<li><code>comment_form_after_fields</code></li>\n</ul>\n\n<p>So most likely you're trying to hook into those filters - but you haven't mentioned what filters you're using.</p>\n" }, { "answer_id": 212713, "author": "Valex", "author_id": 84319, "author_profile": "https://wordpress.stackexchange.com/users/84319", "pm_score": 0, "selected": false, "text": "<p>I Have managed it this way,using an action hook as you said because my filter is for non logged users only.</p>\n\n<pre><code>function comment_custom(){\n\n ?&gt;&lt;p class=\"comment_form_rate\" id=\"rate_recipe\"&gt;&lt;label&gt;Vota la ricetta&lt;/label&gt;&lt;br/&gt;\n &lt;span class=\"star_rating\"&gt;\n\n&lt;input class=\"star star-5\" id=\"star-5\" type=\"radio\" name=\"rate\" value=\"5\"/&gt;\n&lt;label class=\"star star-5\" for=\"star-5\"&gt;&lt;/label&gt;\n&lt;input class=\"star star-4\" id=\"star-4\" type=\"radio\" name=\"rate\" value=\"4\"/&gt;\n&lt;label class=\"star star-4\" for=\"star-4\"&gt;&lt;/label&gt;\n&lt;input class=\"star star-3\" id=\"star-3\" type=\"radio\" name=\"rate\" value=\"3\"/&gt;\n&lt;label class=\"star star-3\" for=\"star-3\"&gt;&lt;/label&gt;\n&lt;input class=\"star star-2\" id=\"star-2\" type=\"radio\" name=\"rate\" value=\"2\"/&gt;\n&lt;label class=\"star star-2\" for=\"star-2\"&gt;&lt;/label&gt;\n&lt;input class=\"star star-1\" id=\"star-1\" type=\"radio\" name=\"rate\" value=\"1\"/&gt;\n&lt;label class=\"star star-1\" for=\"star-1\"&gt;&lt;/label&gt; &lt;/span&gt;\n &lt;/p&gt;\n</code></pre>\n\n<p>\n\n<pre><code>}\n\n //Those filter makes my \"\"custom comment field\"\" both logged and unlogged \n add_action('comment_form_after_fields','comment_custom');\n add_action('comment_form_logged_in_after','comment_custom');\n</code></pre>\n" }, { "answer_id": 290903, "author": "Bibek Shahi Newa", "author_id": 134745, "author_profile": "https://wordpress.stackexchange.com/users/134745", "pm_score": 0, "selected": false, "text": "<p>You have probably done </p>\n\n<pre><code>$defaults['comment_notes_before'] = __( '' ); \n$defaults['submit_button'] = __( '' ); \n$defaults['comment_field'] = __( '' ); \n$defaults['title_reply'] = __( 'Leave your Reply' ); \n$defaults['label_submit'] = __( 'Submit Comment', 'custom' ); \n</code></pre>\n\n<p>For custom comment form </p>\n\n<p>Now what happens is Wordpress will display default comment form for logged in users which you have initialized to blank thus nothing is display.</p>\n\n<p>Solution Is that We need to change $default parameters of comment form since wordpress will display default form with only comment fields.\nWe can do that by using condition </p>\n\n<pre><code>if (!is_user_logged_in()) { \n//custom form \n} \nelse{ \n//make changes in default comment form \n} \n</code></pre>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84319/" ]
I've added a custom field in comment by using ``` function comment_label($fields){ unset( $fields['url'] ); $fields['rate'] = '<p class="comment_form_rate" id="rate_recipe"> <span class="star_rating"> <input class="star star-5" id="star-5" type="radio" name="rate" value="5"/> <label class="star star-5" for="star-5"></label> <input class="star star-4" id="star-4" type="radio" name="rate" value="4"/> <label class="star star-4" for="star-4"></label> <input class="star star-3" id="star-3" type="radio" name="rate" value="3"/> <label class="star star-3" for="star-3"></label> <input class="star star-2" id="star-2" type="radio" name="rate" value="2"/> <label class="star star-2" for="star-2"></label> <input class="star star-1" id="star-1" type="radio" name="rate" value="1"/> <label class="star star-1" for="star-1"></label> </span> </p>'; return $fields; } ``` which work as intended if you are going to post a comment with an unlogged status. But as soon as you login this field goes away, leaving just with the textarea input of comment and the desired `title_reply`, even if you don't log as admin but as normal user. This is my `comments.php` file. ``` <?php if ( post_password_required() ): ?> <p class="nopassword"><?php _e( 'Questo articolo è protetto da password. Inserisci la password per visualizzare i commenti.', 'wtd' ); ?></p> <?php endif; ?> <div id="comments" class="comments-area"> <?php if ( have_comments() ) : ?> <h2 class="comments-title"> <?php printf( _nx( 'Un commento su &ldquo;%2$s&rdquo;', '%1$s commenti su &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'wtd' ), number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' ); ?> </h2> <ol class="commentlist"> <?php wp_list_comments( array( 'callback' => 'wtd_comment', 'style' => 'p', 'type' => 'comment', 'per_page' => 8 ) ); ?> </ol><!-- .commentlist --> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // navigazione dei commenti ?> <nav id="comment-nav-below" class="navigation" role="navigation"> <h1 class="assistive-text section-heading"><?php _e( 'Paginazione commenti', 'wtd' ); ?></h1> <div class="nav-previous"><?php previous_comments_link( __( '&larr; Commenti Precedenti', 'wtd' ) ); ?></div> <div class="nav-next"><?php next_comments_link( __( 'Nuovi commenti &rarr;', 'wtd' ) ); ?></div> </nav> <?php endif; // check for comment navigation ?> <?php /* If there are no comments and comments are closed, let's leave a note. * But we only want the note on posts and pages that had comments in the first place. */ if ( ! comments_open() && get_comments_number() ) : ?> <p class="nocomments"><?php _e( 'I commenti sono chiusi' , 'wtd' ); ?></p> <?php endif; ?> <?php endif; // have_comments() ?> <?php //argomenti da stampare in front-end $argz = array( 'class_form' => 'form-control', 'comment_notes_before' => __('il tuo feedback è importante per noi!','wtd'), 'label_submit' => __('Commenta','wtd'), 'comment_fields' => '', 'title_reply' => __('Valuta questa ricetta','wtd'), ); comment_form($argz); ?> </div><!-- #comments .comments-area --> ``` Am I missing something?
I'm not sure I fully understand your question, but to add some HTML (just *over* or *under* the submit field) that is visible to both *logged-in* and *logged-out* users, you can try the following: ``` add_filter( 'comment_form_submit_field', function( $submit_field ) { //----------------------------------- // Adjust the prepend to your needs //----------------------------------- $prepend = '<p> Prepend some HTML </p>'; //----------------------------------- // Adjust the append to your needs //----------------------------------- $append = '<p> Append some HTML </p>'; return $prepend . $submit_field . $append; } ); ``` Other workarounds are possible, like the `comment_form` action. There are some comment-form filters that are only available to *logged-out* users, like the * `comment_form_before_fields` * `comment_form_field_{$name}` * `comment_form_after_fields` So most likely you're trying to hook into those filters - but you haven't mentioned what filters you're using.
212,519
<p>I've used Advanced Custom Fields to create custom fields for Competition name, answers etc. I've made a custom post type for competitions as shown on the image and I used Wordpress functions.php to create the columns from my custom fields values. </p> <p>I'm trying to get a "Filter by"-dropdown box with the competitions different names/labels like shown below, but I can only find solutions using taxonomies, which I rather not use <strong>if possible</strong> because I've only used custom fields for everything else.</p> <p>Is it possible to make a custom "Filter by" dropdown using only custom fields?</p> <p><a href="https://i.stack.imgur.com/2qP4Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2qP4Y.png" alt="Wordpress filter by"></a></p>
[ { "answer_id": 212527, "author": "David Gard", "author_id": 10097, "author_profile": "https://wordpress.stackexchange.com/users/10097", "pm_score": 4, "selected": false, "text": "<p>The <strong>restrict_manage_posts</strong> action triggers the <code>add_extra_tablenav()</code> function, which is how you add additional dropdowns to your desired List Table.</p>\n<p>In the example below, we first ensure that the <strong>Post Type</strong> is correct, and then we grab all DB values stored against the <code>competition_name</code> key in the <code>postmeta</code> table (you must change the key name as required). The query is fairly basic and only checks to see if the <strong>Competition</strong> is published, takes only unique values (you don't want duplication in the dropdown) and then orders them alphabetically.</p>\n<p>Next we check for results (no point outputting the dropdown for nothing), and then construct the options (including a defualt to show all). Finally the dropdown is output.</p>\n<p>As stated in my comment, this isn't the end of the story though; you'll need some logic to tell the List Table to only show your desired results when the filter is active, but I'll leave you to have a look at that and then start another question if you require further assistance. <em><strong>Hint</strong> - check out the file <code>/wp-admin/includes/class-wp-posts-list-table.php</code>, and it's parent <code>.../wp-class-list-table.php</code></em></p>\n<pre><code>/**\n * Add extra dropdowns to the List Tables\n *\n * @param required string $post_type The Post Type that is being displayed\n */\nadd_action('restrict_manage_posts', 'add_extra_tablenav');\nfunction add_extra_tablenav($post_type){\n \n global $wpdb;\n \n /** Ensure this is the correct Post Type*/\n if($post_type !== 'competition')\n return;\n \n /** Grab the results from the DB */\n $query = $wpdb-&gt;prepare('\n SELECT DISTINCT pm.meta_value FROM %1$s pm\n LEFT JOIN %2$s p ON p.ID = pm.post_id\n WHERE pm.meta_key = &quot;%3$s&quot; \n AND p.post_status = &quot;%4$s&quot; \n AND p.post_type = &quot;%5$s&quot;\n ORDER BY &quot;%6$s&quot;',\n $wpdb-&gt;postmeta,\n $wpdb-&gt;posts,\n 'competition_name', // Your meta key - change as required\n 'publish', // Post status - change as required\n $post_type,\n 'competition_name'\n );\n $results = $wpdb-&gt;get_col($query);\n \n /** Ensure there are options to show */\n if(empty($results))\n return;\n\n // get selected option if there is one selected\n if (isset( $_GET['competition-name'] ) &amp;&amp; $_GET['competition-name'] != '') {\n $selectedName = $_GET['competition-name'];\n } else {\n $selectedName = -1;\n }\n \n /** Grab all of the options that should be shown */\n $options[] = sprintf('&lt;option value=&quot;-1&quot;&gt;%1$s&lt;/option&gt;', __('All Competitions', 'your-text-domain'));\n foreach($results as $result) :\n if ($result == $selectedName) {\n $options[] = sprintf('&lt;option value=&quot;%1$s&quot; selected&gt;%2$s&lt;/option&gt;', esc_attr($result), $result);\n } else {\n $options[] = sprintf('&lt;option value=&quot;%1$s&quot;&gt;%2$s&lt;/option&gt;', esc_attr($result), $result);\n }\n endforeach;\n\n /** Output the dropdown menu */\n echo '&lt;select class=&quot;&quot; id=&quot;competition-name&quot; name=&quot;competition-name&quot;&gt;';\n echo join(&quot;\\n&quot;, $options);\n echo '&lt;/select&gt;';\n\n}\n</code></pre>\n" }, { "answer_id": 212528, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 5, "selected": true, "text": "<p>And for displaying result for Filter then try this code</p>\n<pre><code>add_filter( 'parse_query', 'prefix_parse_filter' );\nfunction prefix_parse_filter($query) {\n global $pagenow;\n $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';\n \n if ( is_admin() &amp;&amp; \n 'competition' == $current_page &amp;&amp;\n 'edit.php' == $pagenow &amp;&amp; \n isset( $_GET['competition-name'] ) &amp;&amp; \n $_GET['competition-name'] != '' ) {\n \n $competition_name = $_GET['competition-name'];\n $query-&gt;query_vars['meta_key'] = 'competition_name';\n $query-&gt;query_vars['meta_value'] = $competition_name;\n $query-&gt;query_vars['meta_compare'] = '=';\n }\n}\n</code></pre>\n<p>Change the meta key and meta value as required.\nI have taken &quot;competition name as meta_key and &quot;competition-name&quot; as select drop down name.</p>\n" }, { "answer_id": 333909, "author": "Ellis Benus Web Developer", "author_id": 141220, "author_profile": "https://wordpress.stackexchange.com/users/141220", "pm_score": 0, "selected": false, "text": "<p>If this isn't working for anyone, my solution was needing to add the Column I was trying to filter by to the list of Sortable columns for my custom post type.</p>\n\n<pre><code>// Make Custom Post Type Custom Columns Sortable\nfunction cpt_custom_columns_sortable( $columns ) {\n\n // Add our columns to $columns array\n $columns['item_number'] = 'item_number';\n $columns['coat_school'] = 'coat_school'; \n\n return $columns;\n} add_filter( 'manage_edit-your-custom-post-type-slug_sortable_columns', 'cpt_custom_columns_sortable' );\n</code></pre>\n" }, { "answer_id": 360567, "author": "anthony peruzzo", "author_id": 184198, "author_profile": "https://wordpress.stackexchange.com/users/184198", "pm_score": 0, "selected": false, "text": "<p>Replace the query below to correct the wpdb:prepare error:</p>\n\n<pre><code>$query = $wpdb-&gt;prepare('\n SELECT DISTINCT pm.meta_value FROM %1$s pm\n LEFT JOIN %2$s p ON p.ID = pm.post_id\n WHERE pm.meta_key = \"%3$s\" \n AND p.post_status = \"%4$s\" \n AND p.post_type = \"%5$s\"\n ORDER BY \"%3$s\"',\n $wpdb-&gt;postmeta,\n $wpdb-&gt;posts,\n 'competition_name', // Your meta key - change as required\n 'publish', // Post status - change as required\n $post_type,\n 'competition_name' //this is needed a second time to define \"%3$s\" in ORDER BY\n );\n</code></pre>\n" }, { "answer_id": 370602, "author": "Ejaz UL Haq", "author_id": 178714, "author_profile": "https://wordpress.stackexchange.com/users/178714", "pm_score": 0, "selected": false, "text": "<p>I ave faced the same issue when I was trying to filter custom-post-type with custom-field<br>\nbut I have resolved this issue in the following steps. <br>\nConverted custom-field name from <code>writer</code> to <code>_writer</code> <br>\nand then I have updated following code inside <code>callback function</code> of <code>parse_query</code> hook that I can add custom-field meta_query like <br></p>\n<pre><code>$query-&gt;set( 'meta_query', array(\n array(\n 'key' =&gt; '_writer',\n 'compare' =&gt; '=',\n 'value' =&gt; $_GET['_writer'],\n 'type' =&gt; 'numeric',\n )\n) ); \n</code></pre>\n<p><strong>This Above Solution</strong> Worked for me.<br>\n<strong>Documentation</strong> <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_posts/</a> <br>\n<strong>Helpful Links</strong> <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571</a> <br>\n<a href=\"https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that\">https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that</a></p>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212519", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85674/" ]
I've used Advanced Custom Fields to create custom fields for Competition name, answers etc. I've made a custom post type for competitions as shown on the image and I used Wordpress functions.php to create the columns from my custom fields values. I'm trying to get a "Filter by"-dropdown box with the competitions different names/labels like shown below, but I can only find solutions using taxonomies, which I rather not use **if possible** because I've only used custom fields for everything else. Is it possible to make a custom "Filter by" dropdown using only custom fields? [![Wordpress filter by](https://i.stack.imgur.com/2qP4Y.png)](https://i.stack.imgur.com/2qP4Y.png)
And for displaying result for Filter then try this code ``` add_filter( 'parse_query', 'prefix_parse_filter' ); function prefix_parse_filter($query) { global $pagenow; $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( is_admin() && 'competition' == $current_page && 'edit.php' == $pagenow && isset( $_GET['competition-name'] ) && $_GET['competition-name'] != '' ) { $competition_name = $_GET['competition-name']; $query->query_vars['meta_key'] = 'competition_name'; $query->query_vars['meta_value'] = $competition_name; $query->query_vars['meta_compare'] = '='; } } ``` Change the meta key and meta value as required. I have taken "competition name as meta\_key and "competition-name" as select drop down name.
212,553
<p>Hello there for a custom post type "organizations" I have about 5000 posts which have to be shown in a list with link within one page.</p> <p>However WP_Query just crashes (without PHP timeout just after 4 seconds on the server). Is this a WordPress problem? If so, why do they limit it? Or is it definitly a server problem?</p> <pre><code>$q = new WP_Query(array('post_type' =&gt; 'organization','posts_per_page' =&gt; 9999)); </code></pre>
[ { "answer_id": 212568, "author": "andrewdcato", "author_id": 55012, "author_profile": "https://wordpress.stackexchange.com/users/55012", "pm_score": 1, "selected": false, "text": "<p>You're probably hitting your DB server's memory limits whenever you're running the query. </p>\n\n<p>Why are you trying to show 5k results on one page? That seems like a really suboptimal idea from a UX standpoint to me.</p>\n" }, { "answer_id": 212589, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": true, "text": "<p>Querying this many posts is dangerous and you can ( and do ) take the site down. If you absolutely have to do this, you need to adjust your query to be more performant.</p>\n\n<p>If you're just needing the link then add <code>'fields' =&gt; 'ids'</code> to your params - this will only return the post ID and not the whole Post object. You can then use the ID to get the permalink, title etc.</p>\n\n<p>If you're not going to paginate, then use <code>'no_found_rows' =&gt; true</code> this will stop WordPress from running expensive SQL CALC queries to get the total number of posts that the query retrieves.</p>\n\n<p>You should 100% cache the results of this query using the <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow\">Transient API</a> this will allow you to return cached HTML instead of rebuilding this query every time someone hits the page.</p>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
Hello there for a custom post type "organizations" I have about 5000 posts which have to be shown in a list with link within one page. However WP\_Query just crashes (without PHP timeout just after 4 seconds on the server). Is this a WordPress problem? If so, why do they limit it? Or is it definitly a server problem? ``` $q = new WP_Query(array('post_type' => 'organization','posts_per_page' => 9999)); ```
Querying this many posts is dangerous and you can ( and do ) take the site down. If you absolutely have to do this, you need to adjust your query to be more performant. If you're just needing the link then add `'fields' => 'ids'` to your params - this will only return the post ID and not the whole Post object. You can then use the ID to get the permalink, title etc. If you're not going to paginate, then use `'no_found_rows' => true` this will stop WordPress from running expensive SQL CALC queries to get the total number of posts that the query retrieves. You should 100% cache the results of this query using the [Transient API](https://codex.wordpress.org/Transients_API) this will allow you to return cached HTML instead of rebuilding this query every time someone hits the page.
212,561
<p>I have 3 headers (header.php, header2.php, and header3.php). I want to always display header.php at the top. Below header.php, I want a second header to display depending on what category the post is. If the post is Grizzly Bears, I want header2. If the post is Peace Pipes, I want header3.</p> <p>I understand displaying 2 headers with: </p> <pre><code>&lt;?php get_header(); get_header(header2); ?&gt; </code></pre> <p>But how can I make the second header dependent on if a category is tagged (or tag is added, to make this question complete)? </p> <p><strong>EDIT:</strong> <em>Due to the help of jgraup and karpstrucking, I see this question is not complete:</em></p> <p>Using ...</p> <pre><code>if ( has_category( 'Grizzly Bears' ) ) { get_header( 'header2' ); } else if ( has_category( 'Peace Pipes' ) ) { get_header( 'header3' ); } </code></pre> <p>... works only if the has_category is the child-most category. I would like to apply the condition to the parent-most category. This code fails for this. For example, I check parent category 'Grizzly Bears' and child category 'Grizzly Bears Fishing' and I can't use the code for 'Grizzly Bears'.</p> <p>Thanks, JM</p>
[ { "answer_id": 212562, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>For all <a href=\"https://codex.wordpress.org/Category_Templates\" rel=\"nofollow\">categories</a> (<a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_categories\" rel=\"nofollow\">wp_get_post_categories</a>)</p>\n\n<blockquote>\n <p>The function wp_get_post_categories() retrieve a list of categories for a post.</p>\n</blockquote>\n\n<pre><code>get_header('header');\n</code></pre>\n\n<p>Conditional based on <a href=\"https://codex.wordpress.org/Function_Reference/has_category\" rel=\"nofollow\">has_category</a></p>\n\n<blockquote>\n <p>Check if the current post has any of the given categories. The given categories are checked against the post's categories' term_ids, names and slugs. Categories given as integers will only be checked against the post's categories' term_ids.</p>\n</blockquote>\n\n<pre><code>if(has_category('bears', $post)) {\n get_header('header2');\n}\nelse if(has_category('pipes', $post)) {\n get_header('header3');\n}\n</code></pre>\n" }, { "answer_id": 212563, "author": "karpstrucking", "author_id": 55214, "author_profile": "https://wordpress.stackexchange.com/users/55214", "pm_score": 1, "selected": false, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Function_Reference/has_category\" rel=\"nofollow\">has_category()</a> function for this:</p>\n\n<pre><code>if ( has_category( 'Grizzly Bears' ) ) {\n get_header( 'header2' );\n} else if ( has_category( 'Peace Pipes' ) ) {\n get_header( 'header3' );\n}\n</code></pre>\n\n<p>You can add the <a href=\"https://codex.wordpress.org/Function_Reference/has_tag\" rel=\"nofollow\">has_tag</a> function as well. Both accept an array of term IDs, names or slugs if you want to check multiples at once.</p>\n\n<p>Edit: changed <code>in_category</code> to <code>has_category</code> for consistency and potential future deprecation</p>\n" }, { "answer_id": 212590, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<h1>EDIT from COMMENTS</h1>\n\n<blockquote>\n <p>All I want to do, in this case, is display a header(header)2 -IF-a post has a certain category checked. I might have \"Grizzly bears\" only, or might have both \"Grizzly bears\" and its child \"Grizzly bears fishing,\" or I might have another child \"Grizzly bears eating\" but as long as that \"Grizzly bears\" category is checked, I want the -THEN- statement to happen. </p>\n</blockquote>\n\n<p>We can still use the same function that we have created in the <strong>ORIGINAL ANSWER</strong>, but we will aplly it a bit different. We will need to get the categories the post belongs to and then check if <em>Grizzly bears</em> are among them</p>\n\n<pre><code>$parent_cat = 1, //Pass the ID, this will ID for 'Grizzly bears' \n$descendants = get_term_descendants( $parent_cat );\n$post_terms = get_the_category( get_the_ID() );\n$ids = wp_list_pluck( $post_terms, 'term_id' );\nif ( $decendants &amp;&amp; !in_array( $parent_cat, $ids ) ) {\n if ( has_category( $decendants ) ) {\n // Post belongs to parent cat descendants but not parent cat\n }\n} elseif ( in_array( $parent_cat, $ids ) ) {\n // Post belongs to the parent category\n} else {\n // Post does not belong to parent cat or any of its decendants\n}\n</code></pre>\n\n<h1>ORIGINAL ANSWER</h1>\n\n<p>Your question is a bit hard to understand, but I will answer to how I read it. </p>\n\n<p>If you need to apply a certain header to each to the top level term and all of its descendants, you can write your function using <code>get_terms()</code> to return all descendants from the given top level parent</p>\n\n<p>FEW NOTES BEFORE CODE:</p>\n\n<ul>\n<li><p>The code is untested and might be buggy. Be sure to test this locally first with debug turned on</p></li>\n<li><p>The code requires at least PHP 5.4</p></li>\n<li><p>It can be quite verbose as we need to do a lot of work to get all the descendants from a top level term. Note, I have explained this, but for performance, make sure that you pass the ID rather than slug to the function, and do not use names</p></li>\n</ul>\n\n<h2>CODE</h2>\n\n<pre><code>function get_term_descendants( $term = '', $taxonomy = 'category' )\n{\n // First make sure we have a term set, if not, return false\n if ( !$term )\n return false;\n\n // Validate and sanitize taxonomy\n if ( 'category' !== $taxonomy ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n // Make sure the taxonomy is valid\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n // Make sure our taxonomy is hierarchical\n if ( !is_taxonomy_hierarchical( $taxonomy ) )\n return false;\n }\n\n // OK, we have a term and the taxonomy is valid, now we need to validate and sanitize the term\n if ( is_numeric( $term ) ) {\n $term = filter_var( $term, FILTER_VAILDATE_INT );\n } else {\n $term_filtered = filter_var( $term, FILTER_SANITIZE_STRING );\n $term_object = get_term_by( 'slug', $term_filtered, $taxonomy );\n $term = filter_var( $term_object-&gt;term_id, FILTER_VAILDATE_INT );\n }\n\n // Everything is sanitized and validated, lets get the term descendants ids\n $term_descendants = get_terms( $taxonomy, ['child_of' =&gt; $term, 'fields' =&gt; 'ids'] );\n\n // Check if we have terms\n if ( !$term_descendants )\n return false;\n\n // We have made it, return the descendants\n return $descendants;\n}\n</code></pre>\n\n<p>Our function <code>get_term_descendants()</code> will now either hold an array of descendant term ID's of the term passed to the function or will return false if the passed term dont have descendants</p>\n\n<p>We can now use our function and pass the returned array of ids directly to <code>has_category()</code></p>\n\n<p><strong>NOTE:</strong> You can either pass the parent term ID or slug to the function. Do not use names as hierarchical terms can have duplicate names accross different hierarchies. Also note, passing the slug to the function is a bit more expensive because we will use <code>get_term_by()</code> to get the term ID from the slug. For performance, try to always pass the ID</p>\n\n<pre><code>$parent_cat = 1, //Pass the ID, can pass the slug, but reread the note above\n$descendants = get_term_descendants( $parent_cat );\nif ( $decendants ) {\n $term_array = array_merge( $parent_cat, $descendants );\n} else {\n $term_array = $parent_cat;\n}\n// Now we can check if the post belongs to the parent cat or one of his descendants\nif ( has_category( $term_array, $post ) ) {\n // Post belongs to parent cat or one of his descendants\n} else {\n // Post does not belong to the parent or any of his descendants\n}\n</code></pre>\n" } ]
2015/12/21
[ "https://wordpress.stackexchange.com/questions/212561", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73570/" ]
I have 3 headers (header.php, header2.php, and header3.php). I want to always display header.php at the top. Below header.php, I want a second header to display depending on what category the post is. If the post is Grizzly Bears, I want header2. If the post is Peace Pipes, I want header3. I understand displaying 2 headers with: ``` <?php get_header(); get_header(header2); ?> ``` But how can I make the second header dependent on if a category is tagged (or tag is added, to make this question complete)? **EDIT:** *Due to the help of jgraup and karpstrucking, I see this question is not complete:* Using ... ``` if ( has_category( 'Grizzly Bears' ) ) { get_header( 'header2' ); } else if ( has_category( 'Peace Pipes' ) ) { get_header( 'header3' ); } ``` ... works only if the has\_category is the child-most category. I would like to apply the condition to the parent-most category. This code fails for this. For example, I check parent category 'Grizzly Bears' and child category 'Grizzly Bears Fishing' and I can't use the code for 'Grizzly Bears'. Thanks, JM
You can use the [has\_category()](https://codex.wordpress.org/Function_Reference/has_category) function for this: ``` if ( has_category( 'Grizzly Bears' ) ) { get_header( 'header2' ); } else if ( has_category( 'Peace Pipes' ) ) { get_header( 'header3' ); } ``` You can add the [has\_tag](https://codex.wordpress.org/Function_Reference/has_tag) function as well. Both accept an array of term IDs, names or slugs if you want to check multiples at once. Edit: changed `in_category` to `has_category` for consistency and potential future deprecation
212,588
<p>Reading <a href="https://wordpress.stackexchange.com/q/23169/22728">Kaiser's query and Scribu's answer</a> I'm now in an ocean of no shore. I made a custom taxonomy, where I want to show the terms as per their hierarchy, like below:</p> <pre><code>Level 0 -- Level 1 --- Level 2 ---- Level 3 --- Level 2 ---- Level 3 ---- Level 3 -- Level 1 --- Level 2 </code></pre> <p>But I failed using <code>orderby =&gt; 'term_group'</code> in both <code>get_categories()</code> and <code>get_terms()</code>. Using <code>term_group</code> what I got is:</p> <pre><code>Level 0 -- Level 1 -- Level 1 --- Level 2 --- Level 2 --- Level 2 ---- Level 3 ---- Level 3 ---- Level 3 </code></pre> <p>I've checked the data, all the hierarchies are perfect, but they are not visibly working on the front-end in my code. But the following code's working when I's entering terms by my hand one by one:</p> <pre><code>$all_terms = get_categories( array( 'taxonomy' =&gt; 'my_tax', 'show_count' =&gt; true, 'hide_empty' =&gt; false, 'orderby' =&gt; 'term_group', ) ); </code></pre> <p>But when I used an automated script, entering/migrating data, so that the level 0 enters first, then the level 1 and so on, the same code is not working. So I guess, the orderby was actually working on the IDs (and yes, actually it is).</p> <p>How can I display the taxonomy terms the way they are hierarchical?</p>
[ { "answer_id": 212592, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p><code>term_group</code> seemed to have never been fully developed together with the <code>alias_of</code> parameter. What the exact indended use is (<em>or was</em>), I cannot say for sure. I would just rather avoid the use of those two parameters.</p>\n\n<p>Regarding your issue of creating a hierarchical tree, <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow\"><code>wp_list_categories()</code></a> immediately jumps to mind (<em>remember this works for custom taxonomies as well</em>). You can either use <code>wp_list_categories()</code> as-is and manipulate the output through the parameters availble, or you can look at <a href=\"https://developer.wordpress.org/reference/functions/walk_category_tree/\" rel=\"nofollow\"><code>walk_category_tree()</code></a> which <code>wp_list_categories()</code> uses to build its tree. <code>walk_category_tree()</code> also use the <a href=\"https://developer.wordpress.org/reference/classes/walker_category/\" rel=\"nofollow\"><code>Walker_Category</code> class</a>, so you can use this to exact fine tune what you need</p>\n\n<p>There is also the option of writing your own recursive function to create your tree</p>\n" }, { "answer_id": 213478, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 1, "selected": true, "text": "<p>I solved it using simple PHP, and with the help of my colleague Mr. Afzal. My existing query was:</p>\n\n<pre><code>$all_terms = get_categories( array(\n 'taxonomy' =&gt; 'my_tax',\n 'show_count' =&gt; true,\n 'hide_empty' =&gt; false,\n 'orderby' =&gt; 'term_group', //bogus :p\n ) );\n</code></pre>\n\n<p>Instead of my existing query, I made it a <code>$wpdb</code> query for a better control:</p>\n\n<pre><code>global $wpdb;\n$tax_query = $wpdb-&gt;get_results(\"SELECT t.*, tt.* FROM $wpdb-&gt;terms AS t\n INNER JOIN $wpdb-&gt;term_taxonomy AS tt ON t.term_id = tt.term_id\n WHERE tt.taxonomy IN ('my_tax')\n ORDER BY tt.parent, t.name ASC\n \", ARRAY_A);\n</code></pre>\n\n<p>So that we now have <em>alphabetically</em> sorted array with some valuable information that I need for further proceedings:</p>\n\n<ul>\n<li><code>term_id</code></li>\n<li><code>parent</code></li>\n</ul>\n\n<h3>Hierarchical Arrays</h3>\n\n<p>I made my tree-generating function using <a href=\"https://stackoverflow.com/a/10332361/1743124\">this SO thread</a>, it's a recursive function:</p>\n\n<pre><code>function create_tax_tree( &amp;$list, $parent ) {\n $taxTree = array();\n foreach( $parent as $ind =&gt; $val ) {\n if( isset($list[$val['term_id']]) ) {\n $val['children'] = create_tax_tree( $list, $list[$val['term_id']] );\n }\n $taxTree[] = $val;\n }\n return $taxTree;\n}\n</code></pre>\n\n<p>And this function will make me an array with exact parent-child relationship. After my db Query, I did the following now:</p>\n\n<pre><code>if (count( $tax_query ) &gt; 0) :\n\n //Making my tree array\n $taxs = array();\n foreach( $tax_query as $tax ) {\n $taxs[ $tax['parent'] ][] = $tax;\n }\n //that's my tree in array or arrays\n $tax_tree = create_tax_tree( $taxs, $taxs[0] );\n\nelse :\n\n _e('No term found', 'textdomain');\n\nendif;\n</code></pre>\n\n<p>Now my tree is in <code>$tax_tree</code> variable. If I <code>var_dump($tax_tree)</code>, it's an array of arrays, which is full of exact parent-child relations.</p>\n\n<h3>Final results</h3>\n\n<p>To get the final result, we need another recursive function, and here PHP5 provides a <a href=\"http://php.net/manual/en/spl.iterators.php\" rel=\"nofollow noreferrer\">nice bunch of classes</a>, learned from <a href=\"https://stackoverflow.com/a/5524267\">this SO thread</a>. I'm using two of them in the following way:</p>\n\n<pre><code>$tax_iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator( $tax_tree ));\n\nforeach( $tax_iterator as $key =&gt; $value ) {\n $depth = get_tax_depth( $term_id, true ); //custom-made function\n if( 'term_id' === $key )\n $term_id = (int) $value; //having the term_id for further use\n\n if( 'name' === $key ) {\n echo '&lt;p&gt;';\n $pad = str_repeat('---', $depth * 3); //for visual hierarchy\n echo $pad .' '. $value; //the name of the tax term\n echo '&lt;/p&gt;';\n }\n}\n</code></pre>\n\n<p>And the output is:</p>\n\n<pre><code>Level 0\n-- Level 1\n--- Level 2\n---- Level 3\n--- Level 2\n---- Level 3\n---- Level 3\n-- Level 1\n--- Level 2\n</code></pre>\n\n<p>:)</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212588", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
Reading [Kaiser's query and Scribu's answer](https://wordpress.stackexchange.com/q/23169/22728) I'm now in an ocean of no shore. I made a custom taxonomy, where I want to show the terms as per their hierarchy, like below: ``` Level 0 -- Level 1 --- Level 2 ---- Level 3 --- Level 2 ---- Level 3 ---- Level 3 -- Level 1 --- Level 2 ``` But I failed using `orderby => 'term_group'` in both `get_categories()` and `get_terms()`. Using `term_group` what I got is: ``` Level 0 -- Level 1 -- Level 1 --- Level 2 --- Level 2 --- Level 2 ---- Level 3 ---- Level 3 ---- Level 3 ``` I've checked the data, all the hierarchies are perfect, but they are not visibly working on the front-end in my code. But the following code's working when I's entering terms by my hand one by one: ``` $all_terms = get_categories( array( 'taxonomy' => 'my_tax', 'show_count' => true, 'hide_empty' => false, 'orderby' => 'term_group', ) ); ``` But when I used an automated script, entering/migrating data, so that the level 0 enters first, then the level 1 and so on, the same code is not working. So I guess, the orderby was actually working on the IDs (and yes, actually it is). How can I display the taxonomy terms the way they are hierarchical?
I solved it using simple PHP, and with the help of my colleague Mr. Afzal. My existing query was: ``` $all_terms = get_categories( array( 'taxonomy' => 'my_tax', 'show_count' => true, 'hide_empty' => false, 'orderby' => 'term_group', //bogus :p ) ); ``` Instead of my existing query, I made it a `$wpdb` query for a better control: ``` global $wpdb; $tax_query = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('my_tax') ORDER BY tt.parent, t.name ASC ", ARRAY_A); ``` So that we now have *alphabetically* sorted array with some valuable information that I need for further proceedings: * `term_id` * `parent` ### Hierarchical Arrays I made my tree-generating function using [this SO thread](https://stackoverflow.com/a/10332361/1743124), it's a recursive function: ``` function create_tax_tree( &$list, $parent ) { $taxTree = array(); foreach( $parent as $ind => $val ) { if( isset($list[$val['term_id']]) ) { $val['children'] = create_tax_tree( $list, $list[$val['term_id']] ); } $taxTree[] = $val; } return $taxTree; } ``` And this function will make me an array with exact parent-child relationship. After my db Query, I did the following now: ``` if (count( $tax_query ) > 0) : //Making my tree array $taxs = array(); foreach( $tax_query as $tax ) { $taxs[ $tax['parent'] ][] = $tax; } //that's my tree in array or arrays $tax_tree = create_tax_tree( $taxs, $taxs[0] ); else : _e('No term found', 'textdomain'); endif; ``` Now my tree is in `$tax_tree` variable. If I `var_dump($tax_tree)`, it's an array of arrays, which is full of exact parent-child relations. ### Final results To get the final result, we need another recursive function, and here PHP5 provides a [nice bunch of classes](http://php.net/manual/en/spl.iterators.php), learned from [this SO thread](https://stackoverflow.com/a/5524267). I'm using two of them in the following way: ``` $tax_iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator( $tax_tree )); foreach( $tax_iterator as $key => $value ) { $depth = get_tax_depth( $term_id, true ); //custom-made function if( 'term_id' === $key ) $term_id = (int) $value; //having the term_id for further use if( 'name' === $key ) { echo '<p>'; $pad = str_repeat('---', $depth * 3); //for visual hierarchy echo $pad .' '. $value; //the name of the tax term echo '</p>'; } } ``` And the output is: ``` Level 0 -- Level 1 --- Level 2 ---- Level 3 --- Level 2 ---- Level 3 ---- Level 3 -- Level 1 --- Level 2 ``` :)
212,597
<p>My text editor in Theme Options doesn't have font color option. How can I add that? I've searched around the web, but no luck. On regular pages and posts I can see the font color option.</p> <p>I'm using Options framework. Here's the code snippet:</p> <pre><code>$options[] = array( 'name' =&gt; __('Main text block', 'options_check'), 'id' =&gt; 'main_text_editor', 'type' =&gt; 'editor', 'settings' =&gt; $wp_editor_settings ); </code></pre>
[ { "answer_id": 212624, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>I think you mean the font color inside the TinyMCE editor. The <code>wp_editor()</code> function have the settings parameter, there you reference to an var like ``.</p>\n\n<p>This parameter need a array and this array can use a lot of parameters. The follow example demonstrate this and the <a href=\"http://codex.wordpress.org/Function_Reference/wp_editor#Arguments\" rel=\"nofollow\">codex</a> have also a documentation.</p>\n\n<pre><code>$settings = array(\n 'wpautop' =&gt; true,\n 'media_buttons' =&gt; false,\n 'textarea_name' =&gt; 'test-editor',\n 'textarea_rows' =&gt; get_option('default_post_edit_rows', 10),\n 'tabindex' =&gt; '',\n 'editor_css' =&gt; '',\n 'editor_class' =&gt; '',\n 'teeny' =&gt; true,\n 'dfw' =&gt; true,\n 'tinymce' =&gt; array(\n 'theme_advanced_buttons1' =&gt; 'bold,italic,underline' \n ),\n 'quicktags' =&gt; false\n);\nwp_editor( 'Text in editor', 'test-editor', $settings );\n</code></pre>\n\n<p>The argument inside the array <code>tinymce</code> accept also a array with different parameters to customize the editor bar.</p>\n\n<p>The follow buttons was in default defined for the 'teeny' buttons, the PressThis bar, different from the default editor:</p>\n\n<pre><code>'teeny_mce_buttons',\narray( \n 'bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', \n 'numlist', 'alignleft', 'aligncenter', 'alignright', 'undo', \n 'redo', 'link', 'unlink', 'fullscreen'\n)\n</code></pre>\n\n<p>Also is the second row possibel:</p>\n\n<pre><code>'mce_buttons_2'\narray( \n 'formatselect', 'underline', 'alignjustify', 'forecolor', 'pastetext',\n 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo'\n)\n</code></pre>\n\n<h2>Default WP Editor Settings</h2>\n\n<pre><code> $set = wp_parse_args( $settings, array(\n 'wpautop' =&gt; true,\n 'media_buttons' =&gt; true,\n 'default_editor' =&gt; '',\n 'drag_drop_upload' =&gt; false,\n 'textarea_name' =&gt; $editor_id,\n 'textarea_rows' =&gt; 20,\n 'tabindex' =&gt; '',\n 'tabfocus_elements' =&gt; ':prev,:next',\n 'editor_css' =&gt; '',\n 'editor_class' =&gt; '',\n 'teeny' =&gt; false,\n 'dfw' =&gt; false,\n '_content_editor_dfw' =&gt; false,\n 'tinymce' =&gt; true,\n 'quicktags' =&gt; true\n ) );\n</code></pre>\n\n<h2>Custom plugins in the TinyMCE editor</h2>\n\n<p>You can also add custom plugins for the TinyMCE in this settings array, like the follow example.</p>\n\n<pre><code>'tinymce' =&gt; array( \n 'plugins' =&gt; 'fullscreen, wordpress, wplink, textcolor'\n)\n</code></pre>\n" }, { "answer_id": 212626, "author": "theo", "author_id": 85213, "author_profile": "https://wordpress.stackexchange.com/users/85213", "pm_score": 3, "selected": true, "text": "<p>In theme options, I had to define wp_editor_settings. So, just in options.php, I used:</p>\n\n<pre><code>//WP_editor settigs\n $wp_editor_settings = array(\n 'wpautop' =&gt; true, // Default\n 'textarea_rows' =&gt; 15,\n 'tinymce' =&gt; array( \n 'plugins' =&gt; 'fullscreen,wordpress,wplink, textcolor'\n ));\n</code></pre>\n\n<p>Basically, I'm adding tinymce plugin.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85213/" ]
My text editor in Theme Options doesn't have font color option. How can I add that? I've searched around the web, but no luck. On regular pages and posts I can see the font color option. I'm using Options framework. Here's the code snippet: ``` $options[] = array( 'name' => __('Main text block', 'options_check'), 'id' => 'main_text_editor', 'type' => 'editor', 'settings' => $wp_editor_settings ); ```
In theme options, I had to define wp\_editor\_settings. So, just in options.php, I used: ``` //WP_editor settigs $wp_editor_settings = array( 'wpautop' => true, // Default 'textarea_rows' => 15, 'tinymce' => array( 'plugins' => 'fullscreen,wordpress,wplink, textcolor' )); ``` Basically, I'm adding tinymce plugin.
212,616
<p>i search about it on google but didn't find any thing. I want to remove my wordpress wp_posts table's unused columns, to save my database storage... </p> <p>I know if table column is empty it will not effect on my space, but maintained table can be increase my website performance!!!, currently <code>23 columns</code> in my wp_posts table...</p> <p>I have <code>1,200,000 Rows</code> in my wp_posts table with size: <code>1.2 GB</code>, and it will increase to <code>30,000,000 Rows</code> in 2 month...</p> <p>There are many fields that are not in my use, so how can i delete them, so it will not effect on my wp project??</p> <p>i am worried about if i delete any column, may be my website will not work on any stage. </p> <p><strong>Columns that i want to delete :</strong> </p> <pre><code>post_date post_date_gmt ping_status post_password to_ping pinged post_content_filtered //more if possible, i will update my posts, but i dont need last modify date. post_modified post_modified_gmt </code></pre> <p><a href="https://i.stack.imgur.com/i8JD6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8JD6.png" alt="enter image description here"></a></p> <p>Thanks in Advance :) </p>
[ { "answer_id": 212620, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>If you change the DB structure than you are effectively not running wordpress any longer, but your fork of it. This is not always a negative thing to do as long as you are aware that once you do it there is no guaranty that any plugin or theme or future wordpress version will work with your DB scheme.</p>\n\n<p><strong>TL;DR</strong></p>\n\n<p>Extremely bad idea.</p>\n" }, { "answer_id": 212621, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>have 1,200,000 Rows in my wp_posts table with size: 1.2 GB, and it will increase to 30,000,000 Rows in 2 month...</p>\n</blockquote>\n\n<p>It is totally insane. I really do not know what the reason for this is, but <strong>30 MILLION</strong> posts are insane. You really need to go and sit down and think about what your are doing and what your goal is, and to be really honest and straight here, you have some gaols very wrong here.</p>\n\n<p>I really do not know if any type of average purchased hosting will ever have enough resources to run a site with a db this overly massive. Do you have your own super server you are running this on?</p>\n\n<p>Simply deleting tables and columns created by WordPress is definitely not an option here, anyways, deleting unused columns and tables will not majorly enhance your performance on the site. IMHO, you might just break some other stuff, which will have you knocking your head against a mountain again.</p>\n\n<h2>SOLUTION</h2>\n\n<p>Rethink your complete plan with your site and stop all insanity ;-)</p>\n" }, { "answer_id": 212625, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>Deleting the columns will not have much effect in terms of table size. But it will <strong>break the regular WordPress queries,</strong> because the SQL write and read queries are referencing these columns. If they are absent, the SQL will be invalid and you get just a MySQL error, not the results.</p>\n\n<p>1.2 GB is not that much. A normal InnoDB table can hold <a href=\"http://dev.mysql.com/doc/refman/5.5/en/innodb-restrictions.html\" rel=\"nofollow\">up to 64 TB</a>:</p>\n\n<blockquote>\n <p>The maximum tablespace size is four billion database pages (64TB). This is also the maximum size for a table.</p>\n</blockquote>\n\n<p>Your <em>indexes</em> might be a problem. Here is a good explanation for how to analyze them: <a href=\"http://aadant.com/blog/2014/02/04/how-to-calculate-a-specific-innodb-index-size/\" rel=\"nofollow\">How to calculate a specific InnoDB index size?</a></p>\n\n<p>You might want turn off index creation during import, or alter the existing one completely.</p>\n\n<p>Another option is <a href=\"https://dev.mysql.com/doc/refman/5.7/en/partitioning-overview.html\" rel=\"nofollow\">partitioning</a>, using multiple physical tables that look logical like just one. Not sure how WordPress can deal with that, because there are some <a href=\"https://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations.html\" rel=\"nofollow\">limitations</a>.</p>\n\n<p>Or consider using a completely separate table for your data. Pulling these into the regular queries is not that hard. There are many filters to change database queries, you will probably find one that fits your needs.</p>\n" }, { "answer_id": 212627, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>In addition to what everyone else has mentioned, your intentions are flawed - if you're trying to save space, this is not the way to go about it.</p>\n\n<ul>\n<li><code>post_date</code> - 8 bytes</li>\n<li><code>post_date_gmt</code> - 8 bytes</li>\n<li><code>ping_status</code> - 8 bytes (at most - <code>open</code>, <code>closed</code> or <code>inherit</code>)</li>\n<li><code>post_modified</code> - 8 bytes</li>\n<li><code>post_modified_gmt</code> - 8 bytes</li>\n</ul>\n\n<p>The other fields mentioned are likely to be 0 bytes (switch off pings in Settings > Discussion).</p>\n\n<blockquote>\n <p>40 bytes per row * 1.2m rows = ~40MB = ~3.5% of 1.2GB</p>\n</blockquote>\n\n<p>In other words, your savings are so trivial it's simply not worth the effort of implementing (which would be a pain to say the least).</p>\n\n<p>If you want that many posts in one install, better hosting is the answer.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85716/" ]
i search about it on google but didn't find any thing. I want to remove my wordpress wp\_posts table's unused columns, to save my database storage... I know if table column is empty it will not effect on my space, but maintained table can be increase my website performance!!!, currently `23 columns` in my wp\_posts table... I have `1,200,000 Rows` in my wp\_posts table with size: `1.2 GB`, and it will increase to `30,000,000 Rows` in 2 month... There are many fields that are not in my use, so how can i delete them, so it will not effect on my wp project?? i am worried about if i delete any column, may be my website will not work on any stage. **Columns that i want to delete :** ``` post_date post_date_gmt ping_status post_password to_ping pinged post_content_filtered //more if possible, i will update my posts, but i dont need last modify date. post_modified post_modified_gmt ``` [![enter image description here](https://i.stack.imgur.com/i8JD6.png)](https://i.stack.imgur.com/i8JD6.png) Thanks in Advance :)
If you change the DB structure than you are effectively not running wordpress any longer, but your fork of it. This is not always a negative thing to do as long as you are aware that once you do it there is no guaranty that any plugin or theme or future wordpress version will work with your DB scheme. **TL;DR** Extremely bad idea.
212,629
<p>One of the functions I'm using in my plugin is polluting the global scope with a name that could collide with another function (used in another plugin). So, I guess I should deprecate it. But how should I go about that?</p> <pre><code>function foo() { echo 'bar'; } </code></pre> <p>I'm aware of <code>_deprecate_function()</code> but would be grateful for an example showing all the steps I should take in order to remove the function from my plugin's core.</p> <p>Ref: <a href="https://developer.wordpress.org/reference/functions/_deprecated_function/">https://developer.wordpress.org/reference/functions/_deprecated_function/</a></p>
[ { "answer_id": 212630, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You create a new plugin and advice your users to migrate to it as the current one is EOL.</p>\n\n<p>There is nothing more annoying than plugin and theme authors changing their public APIs and try to treat it as \"just another small upgrade\". There is no reason to break sites because of a problem your users are actually not being affected by.</p>\n" }, { "answer_id": 212631, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": false, "text": "<p>Deprecation does not always equal being removed, it usually means that the item is marked for EVENTUAL removal from the API. Is this a method that will be called externally - as in by other plugins or developers? If this method is only ever used by the plugin internally, you can probably safely remove replace it with a better name function.</p>\n\n<p>If not, I'd create the better named function and have the badly named one call it with a <code>__doing_it_wrong</code> call - read about it in the <a href=\"https://developer.wordpress.org/reference/functions/_doing_it_wrong/\">codex</a> This will give other developers time to update their references to the method and you can safely remove the method in a later version.</p>\n\n<pre><code>function badly_named() {\n\n __doing_it_wrong( 'badly_named', 'This method has been deprecated in favor of better_named_function' );\n\n /**\n * Call the better named method\n */\n better_named_function();\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 212634, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>In addition to the answer by @Welcher:</p>\n\n<p>There are some good \"<em>graveyard</em>\" examples in the core, where \"<em><a href=\"https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/deprecated.php#L11-L13\">functions come to die</a></em>\".</p>\n\n<p>You could use them as guidelines, e.g. regarding the documentation.</p>\n\n<p>Here's one such example for the <code>permalink_link()</code> under the <a href=\"https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/deprecated.php#L835-L845\"><code>wp-includes/deprecated.php</code></a> </p>\n\n<pre><code>/**\n * Print the permalink of the current post in the loop.\n *\n * @since 0.71\n * @deprecated 1.2.0 Use the_permalink()\n * @see the_permalink()\n */\nfunction permalink_link() {\n _deprecated_function( __FUNCTION__, '1.2', 'the_permalink()' );\n the_permalink();\n}\n</code></pre>\n\n<p>Here's the inline documentation for the <a href=\"https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/functions.php#L3532\"><code>_deprecated_function</code></a> function that explains the input arguments:</p>\n\n<pre><code>/**\n * Mark a function as deprecated and inform when it has been used.\n *\n * There is a hook deprecated_function_run that will be called that can be used\n * to get the backtrace up to what file and function called the deprecated\n * function.\n *\n * The current behavior is to trigger a user error if WP_DEBUG is true.\n *\n * This function is to be used in every function that is deprecated.\n *\n * @since 2.5.0\n * @access private\n *\n * @param string $function The function that was called.\n * @param string $version The version of WordPress that deprecated the function.\n * @param string $replacement Optional. The function that should have been called. \n * Default null.\n */\n</code></pre>\n" }, { "answer_id": 272463, "author": "alexg", "author_id": 17616, "author_profile": "https://wordpress.stackexchange.com/users/17616", "pm_score": 2, "selected": false, "text": "<p>I would suggest something like:</p>\n\n<pre><code>/**\n * @deprecated Please use good_function_name() instead\n * @since x.y.z Marked deprecated in favor of good_function_name()\n * @see good_function_name()\n */\nfunction bad_function_name() {\n trigger_error(\n 'The ' . __FUNCTION__ . ' function is deprecated. ' .\n 'Please use good_function_name() instead.',\n defined( 'E_USER_DEPRECATED' ) ? E_USER_DEPRECATED : E_USER_WARNING\n );\n\n return good_function_name();\n}\n</code></pre>\n\n<p>This has the effect of showing a deprecation warning in the logs along with a stack trace. Naturally this will only work if logging is enabled in WordPress.</p>\n\n<p>The ternary operator is there because the E_USER_DEPRECATED constant was only introduced in PHP 5.3.0. In older versions we can fall back to a simple user warning instead.</p>\n\n<p>From the <a href=\"http://php.net/manual/en/errorfunc.constants.php\" rel=\"nofollow noreferrer\">PHP manual on error constants</a>:</p>\n\n<blockquote>\n <p><strong>E_DEPRECATED</strong> Run-time notices. Enable this to receive warnings about code that will not work in future versions. </p>\n</blockquote>\n\n<p>The reason I do not like to use <a href=\"https://developer.wordpress.org/reference/functions/_doing_it_wrong/\" rel=\"nofollow noreferrer\">_doing_it_wrong</a> or <a href=\"https://developer.wordpress.org/reference/functions/_deprecated_function/\" rel=\"nofollow noreferrer\">__deprecated_function</a> is that these functions are intended only for WordPress core. From the code reference on those functions:</p>\n\n<blockquote>\n <p>This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.</p>\n</blockquote>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
One of the functions I'm using in my plugin is polluting the global scope with a name that could collide with another function (used in another plugin). So, I guess I should deprecate it. But how should I go about that? ``` function foo() { echo 'bar'; } ``` I'm aware of `_deprecate_function()` but would be grateful for an example showing all the steps I should take in order to remove the function from my plugin's core. Ref: <https://developer.wordpress.org/reference/functions/_deprecated_function/>
In addition to the answer by @Welcher: There are some good "*graveyard*" examples in the core, where "*[functions come to die](https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/deprecated.php#L11-L13)*". You could use them as guidelines, e.g. regarding the documentation. Here's one such example for the `permalink_link()` under the [`wp-includes/deprecated.php`](https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/deprecated.php#L835-L845) ``` /** * Print the permalink of the current post in the loop. * * @since 0.71 * @deprecated 1.2.0 Use the_permalink() * @see the_permalink() */ function permalink_link() { _deprecated_function( __FUNCTION__, '1.2', 'the_permalink()' ); the_permalink(); } ``` Here's the inline documentation for the [`_deprecated_function`](https://github.com/WordPress/WordPress/blob/c1976fff71ad8f56ffe1e22facb9668ea6b5082b/wp-includes/functions.php#L3532) function that explains the input arguments: ``` /** * Mark a function as deprecated and inform when it has been used. * * There is a hook deprecated_function_run that will be called that can be used * to get the backtrace up to what file and function called the deprecated * function. * * The current behavior is to trigger a user error if WP_DEBUG is true. * * This function is to be used in every function that is deprecated. * * @since 2.5.0 * @access private * * @param string $function The function that was called. * @param string $version The version of WordPress that deprecated the function. * @param string $replacement Optional. The function that should have been called. * Default null. */ ```
212,645
<p>I've created the following custom post type: </p> <pre><code>/** * Register hire custom post type */ function hire() { $labels = array( 'name' =&gt; _x( 'Hire Products', 'Post Type General Name', 'fire' ), 'singular_name' =&gt; _x( 'Hire Product', 'Post Type Singular Name', 'fire' ), 'menu_name' =&gt; __( 'Hire Products', 'fire' ), 'name_admin_bar' =&gt; __( 'Hire Products', 'fire' ), 'archives' =&gt; __( 'Item Archives', 'fire' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'fire' ), 'all_items' =&gt; __( 'All Items', 'fire' ), 'add_new_item' =&gt; __( 'Add New Item', 'fire' ), 'add_new' =&gt; __( 'Add New', 'fire' ), 'new_item' =&gt; __( 'New Item', 'fire' ), 'edit_item' =&gt; __( 'Edit Item', 'fire' ), 'update_item' =&gt; __( 'Update Item', 'fire' ), 'view_item' =&gt; __( 'View Item', 'fire' ), 'search_items' =&gt; __( 'Search Item', 'fire' ), 'not_found' =&gt; __( 'Not found', 'fire' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'fire' ), 'featured_image' =&gt; __( 'Featured Image', 'fire' ), 'set_featured_image' =&gt; __( 'Set featured image', 'fire' ), 'remove_featured_image' =&gt; __( 'Remove featured image', 'fire' ), 'use_featured_image' =&gt; __( 'Use as featured image', 'fire' ), 'insert_into_item' =&gt; __( 'Insert into item', 'fire' ), 'uploaded_to_this_item' =&gt; __( 'Uploaded to this item', 'fire' ), 'items_list' =&gt; __( 'Items list', 'fire' ), 'items_list_navigation' =&gt; __( 'Items list navigation', 'fire' ), 'filter_items_list' =&gt; __( 'Filter items list', 'fire' ), ); $args = array( 'label' =&gt; __( 'Hire Product', 'fire' ), 'description' =&gt; __( 'Custom post type for hire products.', 'fire' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'page-attributes', ), 'taxonomies' =&gt; array('hire_taxonomies'), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'capability_type' =&gt; 'page', ); register_post_type( 'hire', $args ); } add_action( 'init', 'hire', 0 ); </code></pre> <p>I've also created the following code to enable taxonomies for my custom post type: </p> <pre><code>/** * Hire taxonomies */ function hire_taxonomies() { $labels = array( 'name' =&gt; _x( 'Categories', 'Taxonomy General Name', 'fire' ), 'singular_name' =&gt; _x( 'Category', 'Taxonomy Singular Name', 'fire' ), 'menu_name' =&gt; __( 'Categories', 'fire' ), 'all_items' =&gt; __( 'All Items', 'fire' ), 'parent_item' =&gt; __( 'Parent Item', 'fire' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'fire' ), 'new_item_name' =&gt; __( 'New Item Name', 'fire' ), 'add_new_item' =&gt; __( 'Add New Item', 'fire' ), 'edit_item' =&gt; __( 'Edit Item', 'fire' ), 'update_item' =&gt; __( 'Update Item', 'fire' ), 'view_item' =&gt; __( 'View Item', 'fire' ), 'separate_items_with_commas' =&gt; __( 'Separate items with commas', 'fire' ), 'add_or_remove_items' =&gt; __( 'Add or remove items', 'fire' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'fire' ), 'popular_items' =&gt; __( 'Popular Items', 'fire' ), 'search_items' =&gt; __( 'Search Items', 'fire' ), 'not_found' =&gt; __( 'Not Found', 'fire' ), 'no_terms' =&gt; __( 'No items', 'fire' ), 'items_list' =&gt; __( 'Items list', 'fire' ), 'items_list_navigation' =&gt; __( 'Items list navigation', 'fire' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, ); register_taxonomy( 'hire_taxonomies', array( 'hire' ), $args ); } add_action( 'init', 'hire_taxonomies', 0 ); </code></pre> <p>When I go to WP admin, the "Categories" tab appears under my custom post type. I've created some categories for that custom post type, but they don't show up when I go to wrote a post under that custom post type. </p> <p>What am I missing here? </p>
[ { "answer_id": 212646, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": true, "text": "<p>In your second code block change </p>\n\n<pre><code>'hierarchical' =&gt; false,\n</code></pre>\n\n<p>to </p>\n\n<pre><code>'hierarchical' =&gt; true,\n</code></pre>\n\n<p>This should solve your problem :)</p>\n" }, { "answer_id": 407304, "author": "Arunjith R S", "author_id": 113890, "author_profile": "https://wordpress.stackexchange.com/users/113890", "pm_score": 0, "selected": false, "text": "<p>You can add it like this,</p>\n<pre><code>add_action( 'init', array('className', 'add_taxonomy'), '' );\n</code></pre>\n<p>sometimes if you forgot to add empty strings <code>''</code> inside <code>add_action</code> at the end, it will not show up on the menu.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37548/" ]
I've created the following custom post type: ``` /** * Register hire custom post type */ function hire() { $labels = array( 'name' => _x( 'Hire Products', 'Post Type General Name', 'fire' ), 'singular_name' => _x( 'Hire Product', 'Post Type Singular Name', 'fire' ), 'menu_name' => __( 'Hire Products', 'fire' ), 'name_admin_bar' => __( 'Hire Products', 'fire' ), 'archives' => __( 'Item Archives', 'fire' ), 'parent_item_colon' => __( 'Parent Item:', 'fire' ), 'all_items' => __( 'All Items', 'fire' ), 'add_new_item' => __( 'Add New Item', 'fire' ), 'add_new' => __( 'Add New', 'fire' ), 'new_item' => __( 'New Item', 'fire' ), 'edit_item' => __( 'Edit Item', 'fire' ), 'update_item' => __( 'Update Item', 'fire' ), 'view_item' => __( 'View Item', 'fire' ), 'search_items' => __( 'Search Item', 'fire' ), 'not_found' => __( 'Not found', 'fire' ), 'not_found_in_trash' => __( 'Not found in Trash', 'fire' ), 'featured_image' => __( 'Featured Image', 'fire' ), 'set_featured_image' => __( 'Set featured image', 'fire' ), 'remove_featured_image' => __( 'Remove featured image', 'fire' ), 'use_featured_image' => __( 'Use as featured image', 'fire' ), 'insert_into_item' => __( 'Insert into item', 'fire' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'fire' ), 'items_list' => __( 'Items list', 'fire' ), 'items_list_navigation' => __( 'Items list navigation', 'fire' ), 'filter_items_list' => __( 'Filter items list', 'fire' ), ); $args = array( 'label' => __( 'Hire Product', 'fire' ), 'description' => __( 'Custom post type for hire products.', 'fire' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'page-attributes', ), 'taxonomies' => array('hire_taxonomies'), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'hire', $args ); } add_action( 'init', 'hire', 0 ); ``` I've also created the following code to enable taxonomies for my custom post type: ``` /** * Hire taxonomies */ function hire_taxonomies() { $labels = array( 'name' => _x( 'Categories', 'Taxonomy General Name', 'fire' ), 'singular_name' => _x( 'Category', 'Taxonomy Singular Name', 'fire' ), 'menu_name' => __( 'Categories', 'fire' ), 'all_items' => __( 'All Items', 'fire' ), 'parent_item' => __( 'Parent Item', 'fire' ), 'parent_item_colon' => __( 'Parent Item:', 'fire' ), 'new_item_name' => __( 'New Item Name', 'fire' ), 'add_new_item' => __( 'Add New Item', 'fire' ), 'edit_item' => __( 'Edit Item', 'fire' ), 'update_item' => __( 'Update Item', 'fire' ), 'view_item' => __( 'View Item', 'fire' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'fire' ), 'add_or_remove_items' => __( 'Add or remove items', 'fire' ), 'choose_from_most_used' => __( 'Choose from the most used', 'fire' ), 'popular_items' => __( 'Popular Items', 'fire' ), 'search_items' => __( 'Search Items', 'fire' ), 'not_found' => __( 'Not Found', 'fire' ), 'no_terms' => __( 'No items', 'fire' ), 'items_list' => __( 'Items list', 'fire' ), 'items_list_navigation' => __( 'Items list navigation', 'fire' ), ); $args = array( 'labels' => $labels, 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'hire_taxonomies', array( 'hire' ), $args ); } add_action( 'init', 'hire_taxonomies', 0 ); ``` When I go to WP admin, the "Categories" tab appears under my custom post type. I've created some categories for that custom post type, but they don't show up when I go to wrote a post under that custom post type. What am I missing here?
In your second code block change ``` 'hierarchical' => false, ``` to ``` 'hierarchical' => true, ``` This should solve your problem :)
212,653
<p>I am creating a navigation with bootstrap in a custom WP theme. I have managed to get this result:</p> <pre><code>&lt;li id="menu-item-27" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-27"&gt;...&lt;/li&gt; </code></pre> <p>However I have already styled my navigation before transforming it to WP navigation like this:</p> <pre><code>&lt;li class="" id="nava"&gt;&lt;a href="--&gt;&lt;?php //echo get_option('home');?&gt;&lt;!--/"&gt;Home&lt;/a&gt;&lt;/li&gt; </code></pre> <p>I want to replace id="menu-item-27" with id="nava".</p> <p>Any help is much appreciated!</p>
[ { "answer_id": 212657, "author": "Henry Lynx", "author_id": 85632, "author_profile": "https://wordpress.stackexchange.com/users/85632", "pm_score": 0, "selected": false, "text": "<p>Thank you @birgire I edited the walker class like this:</p>\n\n<pre><code>From: \n$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args );\nTo:\n$id = apply_filters( 'nav_menu_item_id', 'nava', $item, $args );\n</code></pre>\n" }, { "answer_id": 212664, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>You could use the <code>nav_menu_item_id</code> filter like this:</p>\n\n<pre><code>add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )\n{\n if( 'menu-item-27' === $menu_id )\n $menu_id = 'nava';\n\n return $menu_id;\n}, 10, 4 );\n</code></pre>\n\n<p>but I this is \"unstable\" regarding the menu ID, if you delete and re-insert menu items. You might also want to target a specific menu location.</p>\n\n<p>A common method, that I like for it's flexibility, is to check for a specific CSS classes, that we can set within the navigational UI in the backend.</p>\n\n<p>Here's an example where we check for the <code>set-id-nava</code> class. If it is set, then we override the CSS id with <code>nava</code>:</p>\n\n<pre><code>add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )\n{\n if( in_array( 'set-id-nava', (array) $item-&gt;classes ) )\n $menu_id = 'nava';\n\n return $menu_id;\n}, 10, 4 );\n</code></pre>\n\n<p>We could also make this more dynamically and check for <code>set-id-???</code>.</p>\n\n<p>We could even add an extra input field to set CSS id's for each menu item. But that would require more work.</p>\n\n<p>If you don't want the <code>set-id-nava</code> as a CSS class, then you could remove it, e.g. via the <code>nav_menu_css_class</code> filter.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85632/" ]
I am creating a navigation with bootstrap in a custom WP theme. I have managed to get this result: ``` <li id="menu-item-27" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-27">...</li> ``` However I have already styled my navigation before transforming it to WP navigation like this: ``` <li class="" id="nava"><a href="--><?php //echo get_option('home');?><!--/">Home</a></li> ``` I want to replace id="menu-item-27" with id="nava". Any help is much appreciated!
You could use the `nav_menu_item_id` filter like this: ``` add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth ) { if( 'menu-item-27' === $menu_id ) $menu_id = 'nava'; return $menu_id; }, 10, 4 ); ``` but I this is "unstable" regarding the menu ID, if you delete and re-insert menu items. You might also want to target a specific menu location. A common method, that I like for it's flexibility, is to check for a specific CSS classes, that we can set within the navigational UI in the backend. Here's an example where we check for the `set-id-nava` class. If it is set, then we override the CSS id with `nava`: ``` add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth ) { if( in_array( 'set-id-nava', (array) $item->classes ) ) $menu_id = 'nava'; return $menu_id; }, 10, 4 ); ``` We could also make this more dynamically and check for `set-id-???`. We could even add an extra input field to set CSS id's for each menu item. But that would require more work. If you don't want the `set-id-nava` as a CSS class, then you could remove it, e.g. via the `nav_menu_css_class` filter.
212,662
<p>How to add Space between sidebar and footer widget in word press theme.In bottom of our <a href="http://www.urdustatus.com" rel="nofollow">Site</a>, I added footer and how can i increase space between sidebar and footer.Its very close and touching the each other. You can see in bottom of home page.</p>
[ { "answer_id": 212657, "author": "Henry Lynx", "author_id": 85632, "author_profile": "https://wordpress.stackexchange.com/users/85632", "pm_score": 0, "selected": false, "text": "<p>Thank you @birgire I edited the walker class like this:</p>\n\n<pre><code>From: \n$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args );\nTo:\n$id = apply_filters( 'nav_menu_item_id', 'nava', $item, $args );\n</code></pre>\n" }, { "answer_id": 212664, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>You could use the <code>nav_menu_item_id</code> filter like this:</p>\n\n<pre><code>add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )\n{\n if( 'menu-item-27' === $menu_id )\n $menu_id = 'nava';\n\n return $menu_id;\n}, 10, 4 );\n</code></pre>\n\n<p>but I this is \"unstable\" regarding the menu ID, if you delete and re-insert menu items. You might also want to target a specific menu location.</p>\n\n<p>A common method, that I like for it's flexibility, is to check for a specific CSS classes, that we can set within the navigational UI in the backend.</p>\n\n<p>Here's an example where we check for the <code>set-id-nava</code> class. If it is set, then we override the CSS id with <code>nava</code>:</p>\n\n<pre><code>add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )\n{\n if( in_array( 'set-id-nava', (array) $item-&gt;classes ) )\n $menu_id = 'nava';\n\n return $menu_id;\n}, 10, 4 );\n</code></pre>\n\n<p>We could also make this more dynamically and check for <code>set-id-???</code>.</p>\n\n<p>We could even add an extra input field to set CSS id's for each menu item. But that would require more work.</p>\n\n<p>If you don't want the <code>set-id-nava</code> as a CSS class, then you could remove it, e.g. via the <code>nav_menu_css_class</code> filter.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83804/" ]
How to add Space between sidebar and footer widget in word press theme.In bottom of our [Site](http://www.urdustatus.com), I added footer and how can i increase space between sidebar and footer.Its very close and touching the each other. You can see in bottom of home page.
You could use the `nav_menu_item_id` filter like this: ``` add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth ) { if( 'menu-item-27' === $menu_id ) $menu_id = 'nava'; return $menu_id; }, 10, 4 ); ``` but I this is "unstable" regarding the menu ID, if you delete and re-insert menu items. You might also want to target a specific menu location. A common method, that I like for it's flexibility, is to check for a specific CSS classes, that we can set within the navigational UI in the backend. Here's an example where we check for the `set-id-nava` class. If it is set, then we override the CSS id with `nava`: ``` add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth ) { if( in_array( 'set-id-nava', (array) $item->classes ) ) $menu_id = 'nava'; return $menu_id; }, 10, 4 ); ``` We could also make this more dynamically and check for `set-id-???`. We could even add an extra input field to set CSS id's for each menu item. But that would require more work. If you don't want the `set-id-nava` as a CSS class, then you could remove it, e.g. via the `nav_menu_css_class` filter.
212,671
<p>The following error may occur if a previous registration remains pending with a conflicting email address.</p> <blockquote> <p>That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.</p> </blockquote> <p>The related username error looks like the following.</p> <blockquote> <p>That username is currently reserved but may be available in a couple of days.</p> </blockquote>
[ { "answer_id": 212672, "author": "here", "author_id": 28978, "author_profile": "https://wordpress.stackexchange.com/users/28978", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Login as WordPress administrator</li>\n<li>Navigate to add a new user</li>\n<li>Check box to bypass email confirmation</li>\n<li>Add the user with a different email address</li>\n<li>Edit the user's email address to the desired result</li>\n</ol>\n\n<p>For the similar username error, see <a href=\"https://wordpress.stackexchange.com/questions/160633/how-can-i-un-reserve-a-pending-username-registration\">How can I un-reserve a pending username registration?</a></p>\n\n<p>The timeout period is 2 days following a conflict, and trac tickets to clarify this process currently exist <a href=\"https://core.trac.wordpress.org/ticket/31127\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://core.trac.wordpress.org/ticket/31127\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 265512, "author": "Marty", "author_id": 118801, "author_profile": "https://wordpress.stackexchange.com/users/118801", "pm_score": 3, "selected": false, "text": "<p>When I add a new user with a different email address, I get the error message: That username is currently reserved but may be available in a couple of days.</p>\n<p>For me, I removed the row from the database in the table wp_signups where user_login equaled the username. Essentially:</p>\n<pre><code>delete from wp_signups where user_login = 'abc';\n</code></pre>\n<p>Then I was able to re-add the user.</p>\n<p>Edit suggestion by @aubreypwd:\nAdditionally, admins (network admins only in an MU or network install) have the option to add users without sending an email. If you check that option, it avoids this process.</p>\n" }, { "answer_id": 265518, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>To work around the \"that email address has already been used\" error, we can create a plugin that effectively bypasses the check. The plugin will work in three parts, utilizing three different hooks.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/pre_user_login/\" rel=\"nofollow noreferrer\"><code>pre_user_login</code></a> filters a username after it has been sanitized. We'll use this hook to grab the user, of particular interest is the email.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/pre_user_email/\" rel=\"nofollow noreferrer\"><code>pre_user_email</code></a> filters a user’s email before the user is created or updated. We'll use this hook to modify the email to some random characters.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/user_register/\" rel=\"nofollow noreferrer\"><code>user_register</code></a> fires immediately after a new user is registered. We'll use this hook to manually update the user email after the user is registered.</p>\n\n<pre><code>add_filter( 'pre_user_email', [ new wpse_212671(), 'pre_user_login' ] );\nclass wpse_212671 {\n protected $user;\n public function pre_user_login( $user ) {\n $this-&gt;user = $user;\n if( isset( $user[ 'ID' ] ) || ! get_user_by( 'email', $user[ 'user_email' ] ) {\n return $user;\n }\n add_filter( 'pre_user_email', [ $this, 'pre_user_email' ] );\n add_action( 'user_register', [ $this, 'user_register' ] );\n }\n public function pre_user_email( $email ) {\n return $this-&gt;generate_random_string();\n }\n public function user_register( $user_id ) {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'users';\n $wpdb-&gt;query( $wpdb-&gt;prepare(\n \"UPDATE %s \n SET user_email = %s\n WHERE user_login = %s\", \n $table,\n $this-&gt;user[ 'user_email' ], \n $this-&gt;user[ 'user_login' ]\n ) );\n }\n //* Code slightly modified from http://stackoverflow.com/a/13212994/6077935\n protected function generate_random_string( $length = 40 ) {\n return substr( str_shuffle( str_repeat( \n $x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\n ceil( $length / strlen( $x ) )\n ) ), 1, $length );\n }\n}\n</code></pre>\n" }, { "answer_id": 311481, "author": "jeffmcneill", "author_id": 20624, "author_profile": "https://wordpress.stackexchange.com/users/20624", "pm_score": 0, "selected": false, "text": "<p>There is a useful plugin called \"User Activation Keys\" which adds a menu item to the Network Users interface:</p>\n\n<p><a href=\"https://wordpress.org/plugins/user-activation-keys/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/user-activation-keys/</a></p>\n\n<p>This allows for editing/deleting/approving user activation requests and subsequently reserved email addresses/usernames.</p>\n" }, { "answer_id": 406483, "author": "jalefkowit", "author_id": 1782, "author_profile": "https://wordpress.stackexchange.com/users/1782", "pm_score": 1, "selected": false, "text": "<p>If you're comfortable working directly in MySQL and would rather not write code or install a plugin just for this task, you can fix this issue pretty simply.</p>\n<p>Inside your site's MySQL database, there will be a table named <code>{ $wpdb-&gt;prefix }_signups</code>, where <code>$wpdb-&gt;prefix</code> is whatever prefix you have configured WP to use for its database datables. (By default, that is <code>wp_</code>.)</p>\n<p>Query that table by the email address that's locked up to find the signup record for it:</p>\n<p><code>SELECT * FROM {$wpdb-&gt;prefix}_signups WHERE user_email = '{ email address }';</code></p>\n<p>That should bring back the record of the signup attempt for that email address. Then just DELETE that record from the table, and you're done.</p>\n" } ]
2015/12/22
[ "https://wordpress.stackexchange.com/questions/212671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28978/" ]
The following error may occur if a previous registration remains pending with a conflicting email address. > > That email address has already been used. Please check your inbox for > an activation email. It will become available in a couple of days if > you do nothing. > > > The related username error looks like the following. > > That username is currently reserved but may be available in a couple of days. > > >
When I add a new user with a different email address, I get the error message: That username is currently reserved but may be available in a couple of days. For me, I removed the row from the database in the table wp\_signups where user\_login equaled the username. Essentially: ``` delete from wp_signups where user_login = 'abc'; ``` Then I was able to re-add the user. Edit suggestion by @aubreypwd: Additionally, admins (network admins only in an MU or network install) have the option to add users without sending an email. If you check that option, it avoids this process.
212,696
<p>I have a website hosted on ASP.NET server and using wordpress to build my site. I've extended its functionalities using PHP code. At which directory do I store secure files such as (passwords and certificate.pem)?</p> <p>My server has the following structure:</p> <pre><code>-/ -/mywebsite.com -/data -/logs -/wwwroot -/wp-admin -/wp-content -/wp-includes </code></pre> <p>I understand that ASP.NET has a file called web.config file that is secure and stored at <code>wwwroot</code>. What's something equivalent using PHP? It is also my understanding that Wordpress stored database password in wp-config.php located at <code>wwwroot</code> so I assume <code>wwwroot</code> is a secure directory?</p> <p>I'm using a shared host btw.</p> <p>Thanks.</p>
[ { "answer_id": 212672, "author": "here", "author_id": 28978, "author_profile": "https://wordpress.stackexchange.com/users/28978", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Login as WordPress administrator</li>\n<li>Navigate to add a new user</li>\n<li>Check box to bypass email confirmation</li>\n<li>Add the user with a different email address</li>\n<li>Edit the user's email address to the desired result</li>\n</ol>\n\n<p>For the similar username error, see <a href=\"https://wordpress.stackexchange.com/questions/160633/how-can-i-un-reserve-a-pending-username-registration\">How can I un-reserve a pending username registration?</a></p>\n\n<p>The timeout period is 2 days following a conflict, and trac tickets to clarify this process currently exist <a href=\"https://core.trac.wordpress.org/ticket/31127\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://core.trac.wordpress.org/ticket/31127\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 265512, "author": "Marty", "author_id": 118801, "author_profile": "https://wordpress.stackexchange.com/users/118801", "pm_score": 3, "selected": false, "text": "<p>When I add a new user with a different email address, I get the error message: That username is currently reserved but may be available in a couple of days.</p>\n<p>For me, I removed the row from the database in the table wp_signups where user_login equaled the username. Essentially:</p>\n<pre><code>delete from wp_signups where user_login = 'abc';\n</code></pre>\n<p>Then I was able to re-add the user.</p>\n<p>Edit suggestion by @aubreypwd:\nAdditionally, admins (network admins only in an MU or network install) have the option to add users without sending an email. If you check that option, it avoids this process.</p>\n" }, { "answer_id": 265518, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>To work around the \"that email address has already been used\" error, we can create a plugin that effectively bypasses the check. The plugin will work in three parts, utilizing three different hooks.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/pre_user_login/\" rel=\"nofollow noreferrer\"><code>pre_user_login</code></a> filters a username after it has been sanitized. We'll use this hook to grab the user, of particular interest is the email.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/pre_user_email/\" rel=\"nofollow noreferrer\"><code>pre_user_email</code></a> filters a user’s email before the user is created or updated. We'll use this hook to modify the email to some random characters.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/user_register/\" rel=\"nofollow noreferrer\"><code>user_register</code></a> fires immediately after a new user is registered. We'll use this hook to manually update the user email after the user is registered.</p>\n\n<pre><code>add_filter( 'pre_user_email', [ new wpse_212671(), 'pre_user_login' ] );\nclass wpse_212671 {\n protected $user;\n public function pre_user_login( $user ) {\n $this-&gt;user = $user;\n if( isset( $user[ 'ID' ] ) || ! get_user_by( 'email', $user[ 'user_email' ] ) {\n return $user;\n }\n add_filter( 'pre_user_email', [ $this, 'pre_user_email' ] );\n add_action( 'user_register', [ $this, 'user_register' ] );\n }\n public function pre_user_email( $email ) {\n return $this-&gt;generate_random_string();\n }\n public function user_register( $user_id ) {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'users';\n $wpdb-&gt;query( $wpdb-&gt;prepare(\n \"UPDATE %s \n SET user_email = %s\n WHERE user_login = %s\", \n $table,\n $this-&gt;user[ 'user_email' ], \n $this-&gt;user[ 'user_login' ]\n ) );\n }\n //* Code slightly modified from http://stackoverflow.com/a/13212994/6077935\n protected function generate_random_string( $length = 40 ) {\n return substr( str_shuffle( str_repeat( \n $x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\n ceil( $length / strlen( $x ) )\n ) ), 1, $length );\n }\n}\n</code></pre>\n" }, { "answer_id": 311481, "author": "jeffmcneill", "author_id": 20624, "author_profile": "https://wordpress.stackexchange.com/users/20624", "pm_score": 0, "selected": false, "text": "<p>There is a useful plugin called \"User Activation Keys\" which adds a menu item to the Network Users interface:</p>\n\n<p><a href=\"https://wordpress.org/plugins/user-activation-keys/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/user-activation-keys/</a></p>\n\n<p>This allows for editing/deleting/approving user activation requests and subsequently reserved email addresses/usernames.</p>\n" }, { "answer_id": 406483, "author": "jalefkowit", "author_id": 1782, "author_profile": "https://wordpress.stackexchange.com/users/1782", "pm_score": 1, "selected": false, "text": "<p>If you're comfortable working directly in MySQL and would rather not write code or install a plugin just for this task, you can fix this issue pretty simply.</p>\n<p>Inside your site's MySQL database, there will be a table named <code>{ $wpdb-&gt;prefix }_signups</code>, where <code>$wpdb-&gt;prefix</code> is whatever prefix you have configured WP to use for its database datables. (By default, that is <code>wp_</code>.)</p>\n<p>Query that table by the email address that's locked up to find the signup record for it:</p>\n<p><code>SELECT * FROM {$wpdb-&gt;prefix}_signups WHERE user_email = '{ email address }';</code></p>\n<p>That should bring back the record of the signup attempt for that email address. Then just DELETE that record from the table, and you're done.</p>\n" } ]
2015/12/23
[ "https://wordpress.stackexchange.com/questions/212696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76324/" ]
I have a website hosted on ASP.NET server and using wordpress to build my site. I've extended its functionalities using PHP code. At which directory do I store secure files such as (passwords and certificate.pem)? My server has the following structure: ``` -/ -/mywebsite.com -/data -/logs -/wwwroot -/wp-admin -/wp-content -/wp-includes ``` I understand that ASP.NET has a file called web.config file that is secure and stored at `wwwroot`. What's something equivalent using PHP? It is also my understanding that Wordpress stored database password in wp-config.php located at `wwwroot` so I assume `wwwroot` is a secure directory? I'm using a shared host btw. Thanks.
When I add a new user with a different email address, I get the error message: That username is currently reserved but may be available in a couple of days. For me, I removed the row from the database in the table wp\_signups where user\_login equaled the username. Essentially: ``` delete from wp_signups where user_login = 'abc'; ``` Then I was able to re-add the user. Edit suggestion by @aubreypwd: Additionally, admins (network admins only in an MU or network install) have the option to add users without sending an email. If you check that option, it avoids this process.
212,721
<p>I'm trying that :</p> <pre><code>&lt;?php $phone = get_user_meta($current_user-&gt;ID,'phone_number',true); echo $phone; ?&gt; </code></pre> <p>But it's not working</p>
[ { "answer_id": 212723, "author": "Mohamed Rihan", "author_id": 85768, "author_profile": "https://wordpress.stackexchange.com/users/85768", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;?php\n // number 9 will be user ID\n $all_meta_for_user = get_user_meta( 9 );\n print_r( $all_meta_for_user );\n\n// find the key that you want\nArray ( \n [first_name] =&gt; Array ( [0] =&gt; Tom ) \n [last_name] =&gt; Array ( [0] =&gt; Auger) \n [nickname] =&gt; Array ( [0] =&gt; tomauger ) \n [description] =&gt; etc.... \n)\n\n// store it in a variable \n$last_name = $all_meta_for_user['last_name'][0];\n\n// display it \necho $last_name;\n</code></pre>\n" }, { "answer_id": 212731, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 2, "selected": false, "text": "<p>If you are not looping all users and only want to get current user <code>phone_number</code> meta then you can try the below.</p>\n\n<pre><code>$current_user_id = get_current_user_id();\n$phone = get_user_meta($current_user_id,'phone_number',true);\necho $phone;\n</code></pre>\n\n<p><strong>NOTE</strong>: This will work only for logged in user. </p>\n\n<p>Also Check <code>phone_number</code> meta_key. By default wordpress doesn't have such meta key I guess.</p>\n" }, { "answer_id": 212760, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>WordPress has a shortcut for getting the current user ID, which it sounds like you need-- <a href=\"https://codex.wordpress.org/Function_Reference/get_current_user_id\" rel=\"nofollow\"><code>get_current_user_id()</code></a>. Using that you should be able to get the information you need. The following is a proof of concept block of code that will check for the return values of the functions and apply some conditional logic in case you need to:</p>\n\n<pre><code>$uid = get_current_user_id();\nif (!empty($uid)) {\n $phone = get_user_meta($uid,'phone_number',true); \n if (!empty($phone)) {\n echo $phone;\n } else {\n echo 'User does not have a phone number stored in the database';\n }\n} else {\n echo 'User is not logged in';\n}\n</code></pre>\n" }, { "answer_id": 212799, "author": "Vincent Roye", "author_id": 74388, "author_profile": "https://wordpress.stackexchange.com/users/74388", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php $phone = get_user_meta($current_user-&gt;ID,'phone',true); echo $phone;?&gt;\n</code></pre>\n\n<p>it was \"phone\" and not \"phone_number\"</p>\n" }, { "answer_id": 357764, "author": "Ravi Raj", "author_id": 182065, "author_profile": "https://wordpress.stackexchange.com/users/182065", "pm_score": 0, "selected": false, "text": "<pre><code>$phone = get_user_meta($user_id, 'billing_phone', true);\necho $phone;\n</code></pre>\n" } ]
2015/12/23
[ "https://wordpress.stackexchange.com/questions/212721", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74388/" ]
I'm trying that : ``` <?php $phone = get_user_meta($current_user->ID,'phone_number',true); echo $phone; ?> ``` But it's not working
``` <?php // number 9 will be user ID $all_meta_for_user = get_user_meta( 9 ); print_r( $all_meta_for_user ); // find the key that you want Array ( [first_name] => Array ( [0] => Tom ) [last_name] => Array ( [0] => Auger) [nickname] => Array ( [0] => tomauger ) [description] => etc.... ) // store it in a variable $last_name = $all_meta_for_user['last_name'][0]; // display it echo $last_name; ```
212,727
<p>I have a function in functions.php which automatically generates a page. It doesn't check to see if there is already a page with the same title at the moment.</p> <p>The function is started with:</p> <pre><code>add_action( 'after_setup_theme', 'add_pages' ); </code></pre> <p><strong>edit</strong>: I only want this to run <strong>once</strong> every page load. I think it is the same thing if I would use</p> <p><code>add_action( 'init', 'add_pages' );</code></p> <p>Here is the code in the add pages function:</p> <pre><code>function add_pages() { $content = "text content"; $page = array( 'post_title' =&gt; 'A unique title?', 'post_content' =&gt; $content, 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_type' =&gt; 'page', 'post_parent' =&gt; 0 ); // Add page $insert_id = wp_insert_post( $page ); } </code></pre> <p>When I reload the "posts" page in wordpress admin, two new pages are created. When I reload again, four new pages are created. When I reload again, a whole bunch of pages are created. I was wondering if there is an explanation for this?</p> <p><strong>edit:</strong> If I change the <strong>post_title</strong> and reload, only one page is created. But if I reload again, two pages are created. But after that, it behaves irrationally, sometimes there are consistently two pages created on each page load , but sometimes a large number of pages are created.</p> <p>I intend to check if the page title already exists, but I wanted to understand this behaviour anyway.</p>
[ { "answer_id": 212729, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p><code>after_setup_theme</code> is not the hook you are looking for - you want <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow\"><code>after_switch_theme</code></a> - this hook will only run once, when your theme is initally activated.</p>\n" }, { "answer_id": 212732, "author": "Pardeep Nadha", "author_id": 85783, "author_profile": "https://wordpress.stackexchange.com/users/85783", "pm_score": 2, "selected": false, "text": "<p>Below is the code, it will not create page if title already exists:</p>\n\n<pre><code>function add_pages() {\n $content = \"text content\";\n $postTitle = 'A unique title?';\n global $wpdb;\n\n $query = $wpdb-&gt;prepare(\n 'SELECT ID FROM ' . $wpdb-&gt;posts . '\n WHERE post_title = %s\n AND post_type = \\'page\\'',\n $postTitle\n );\n $wpdb-&gt;query( $query );\n\n if ( $wpdb-&gt;num_rows ) {\n // Title already exists\n } else {\n $page = array(\n 'post_title' =&gt; 'A unique title?',\n 'post_content' =&gt; $content,\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_type' =&gt; 'page',\n 'post_parent' =&gt; 0 \n );\n\n // Add page\n $insert_id = wp_insert_post( $page );\n }\n}\n</code></pre>\n" } ]
2015/12/23
[ "https://wordpress.stackexchange.com/questions/212727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82394/" ]
I have a function in functions.php which automatically generates a page. It doesn't check to see if there is already a page with the same title at the moment. The function is started with: ``` add_action( 'after_setup_theme', 'add_pages' ); ``` **edit**: I only want this to run **once** every page load. I think it is the same thing if I would use `add_action( 'init', 'add_pages' );` Here is the code in the add pages function: ``` function add_pages() { $content = "text content"; $page = array( 'post_title' => 'A unique title?', 'post_content' => $content, 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'page', 'post_parent' => 0 ); // Add page $insert_id = wp_insert_post( $page ); } ``` When I reload the "posts" page in wordpress admin, two new pages are created. When I reload again, four new pages are created. When I reload again, a whole bunch of pages are created. I was wondering if there is an explanation for this? **edit:** If I change the **post\_title** and reload, only one page is created. But if I reload again, two pages are created. But after that, it behaves irrationally, sometimes there are consistently two pages created on each page load , but sometimes a large number of pages are created. I intend to check if the page title already exists, but I wanted to understand this behaviour anyway.
`after_setup_theme` is not the hook you are looking for - you want [`after_switch_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme) - this hook will only run once, when your theme is initally activated.
212,744
<p>I have <code>archive-page.php</code>, where my custom posts are displayed. I want to put a link on my image, <code>&lt;a href="" alt=""&gt;&lt;img src="" alt=""&gt;&lt;/a&gt;</code>, which leads to <code>single-page.php</code> for that particular post or product. How can I do that? </p> <p>I have tried this:</p> <pre><code>&lt;a href= "&lt;?php get_the_permalink ();?&gt;" alt=""&gt;&lt;img src="" alt=""&gt;&lt;/a&gt; </code></pre> <p>but it does not work. I don't know what to put in <code>functions.php</code> and in those pages: <code>archive-page.php</code> and <code>single-page.php</code> </p>
[ { "answer_id": 212758, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_permalink/\" rel=\"nofollow\"><code>get_the_permalink()</code></a> doesn't <code>echo</code> anything. It just returns a string so that you can further manipulate it. </p>\n\n<p>You need <a href=\"https://developer.wordpress.org/reference/functions/the_permalink/\" rel=\"nofollow\"><code>the_permalink()</code></a> instead, which will <code>echo</code> the link. </p>\n\n<p>The difference used to be clear in the Codex but now, in the much inferior, \"developer\" code reference toward which WordPress is migrating it is not so clear.</p>\n" }, { "answer_id": 330902, "author": "Qaisar Feroz", "author_id": 161501, "author_profile": "https://wordpress.stackexchange.com/users/161501", "pm_score": 0, "selected": false, "text": "<p>As explained by <strong><a href=\"https://wordpress.stackexchange.com/a/212758/161501\">this answer</a></strong>, </p>\n\n<pre><code>&lt;a href= \"&lt;?php get_the_permalink ();?&gt;\" alt=\"\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>&lt;a href= \"&lt;?php echo get_the_permalink ();?&gt;\" alt=\"\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>&lt;a href= \"&lt;?php the_permalink ();?&gt;\" alt=\"\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/a&gt;\n</code></pre>\n" } ]
2015/12/23
[ "https://wordpress.stackexchange.com/questions/212744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85790/" ]
I have `archive-page.php`, where my custom posts are displayed. I want to put a link on my image, `<a href="" alt=""><img src="" alt=""></a>`, which leads to `single-page.php` for that particular post or product. How can I do that? I have tried this: ``` <a href= "<?php get_the_permalink ();?>" alt=""><img src="" alt=""></a> ``` but it does not work. I don't know what to put in `functions.php` and in those pages: `archive-page.php` and `single-page.php`
[`get_the_permalink()`](https://developer.wordpress.org/reference/functions/get_the_permalink/) doesn't `echo` anything. It just returns a string so that you can further manipulate it. You need [`the_permalink()`](https://developer.wordpress.org/reference/functions/the_permalink/) instead, which will `echo` the link. The difference used to be clear in the Codex but now, in the much inferior, "developer" code reference toward which WordPress is migrating it is not so clear.
212,784
<p>I'm using a security plugin that keep sending me emails:</p> <p>"A lockdown event has occurred due to too many failed login attempts or invalid username: Username: Admin IP Address: 195.154.243.31</p> <p>IP Range: 195.154.243.*</p> <p>Log into your site's WordPress administration panel to see the duration of the lockout or to unlock the user."</p> <p>I tried to block the access to wp-admin folder and create htaccess file with this code:</p> <pre><code>order deny,allow deny from all allow from &lt;my ip&gt; </code></pre> <p>also in the root htaccess i added :</p> <pre><code>&lt;Files ~ "(wp-login.php|wp-signup.php)"&gt; Order Deny,Allow Deny from all Allow from &lt;my ip&gt; &lt;/Files&gt; </code></pre> <p>how does the attacker/bot try to login?</p>
[ { "answer_id": 212810, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": false, "text": "<p>Under <strong>Custom Base</strong> where you have used <code>/shop/%product_cat%</code> needs to be replaced with <code>/shop/%product-category%</code> Please see screenshot below: </p>\n\n<p><a href=\"https://i.stack.imgur.com/6v9bL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6v9bL.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 267068, "author": "i_a", "author_id": 65793, "author_profile": "https://wordpress.stackexchange.com/users/65793", "pm_score": 1, "selected": false, "text": "<p>Turns out you don't need to use %product-category% as this does create an issue with the permalinks, that variable name is left in the links, and not the actual product category.</p>\n\n<p>Just leave <strong>Category base</strong> blank, that is what seems to have been causing the 404 error conflict. With the settings below, all is working:</p>\n\n<p>example.com/store/ => Shop page listing products</p>\n\n<p>example.com/store/category-name/ => Category page listing products from a category</p>\n\n<p>example.com/store/category-name/product-name/ => Product page showing product details</p>\n\n<p><a href=\"https://i.stack.imgur.com/S1M5u.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S1M5u.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2015/12/23
[ "https://wordpress.stackexchange.com/questions/212784", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41168/" ]
I'm using a security plugin that keep sending me emails: "A lockdown event has occurred due to too many failed login attempts or invalid username: Username: Admin IP Address: 195.154.243.31 IP Range: 195.154.243.\* Log into your site's WordPress administration panel to see the duration of the lockout or to unlock the user." I tried to block the access to wp-admin folder and create htaccess file with this code: ``` order deny,allow deny from all allow from <my ip> ``` also in the root htaccess i added : ``` <Files ~ "(wp-login.php|wp-signup.php)"> Order Deny,Allow Deny from all Allow from <my ip> </Files> ``` how does the attacker/bot try to login?
Under **Custom Base** where you have used `/shop/%product_cat%` needs to be replaced with `/shop/%product-category%` Please see screenshot below: [![enter image description here](https://i.stack.imgur.com/6v9bL.png)](https://i.stack.imgur.com/6v9bL.png)
212,808
<p>I need to display on a page the list of emails of the users who already posted once on my site. </p> <p>I have this snippet of code:</p> <pre><code>global $wpdb; $min_posts = 1; $author_ids = $wpdb-&gt;get_col("SELECT `post_author` FROM (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb-&gt;posts} WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats` WHERE `count` &gt;= {$min_posts} ORDER BY `count` DESC;"); </code></pre> <p>But I have two issues: how can I choose to display it on a particular page (I usually add snippets to functions.php) and how can I get the emails instead of the iDs ? </p> <p>I probably have to use <code>get_the_author_meta( 'user_email' )</code> but I don't know how to implement it here. </p> <p>Thanks for your time and help</p>
[ { "answer_id": 212811, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 2, "selected": false, "text": "<p>If your query is correct and returns list of <code>user_id</code> then you can run the below</p>\n\n<pre><code>foreach($user_id_array as $user_id){\n echo get_the_author_meta( 'user_email', $user_id );\n echo \"&lt;br&gt;\";//to print in new line for each user mail\n}\n</code></pre>\n\n<p>You can use the above in page template or in any templating hook. For example you can print this in <code>wp_head</code>,<code>wp_footer</code> etc</p>\n\n<p>Let us do this in an empty page. Let us assume the <code>page_id</code> is <code>8</code> then the following filter will do the trick</p>\n\n<pre><code>function print_selected_umail($content){\n\n//check if we are in required page(8), so that we can add the selected user mail\nif(is_page(8)){\n //queried result\n foreach($user_id_array as $user_id){\n $content .= get_the_author_meta( 'user_email', $user_id );\n $content .= \"&lt;br&gt;\";//to print in new line for each user mail\n }\n }\nreturn $content;\n}\nadd_filter('the_content','print_selected_umail');\n</code></pre>\n" }, { "answer_id": 212813, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>You can place following code in your functions.php file &amp; use the shortcode <code>[myblogwriters min_posts=\"1\"]</code> anywhere in the page/post content and can also change the min_posts value :)</p>\n\n<pre><code>function show_min_one_post_writers($atts){\n\n global $wpdb;\n\n $attrs = shortcode_atts( array(\n 'min_posts' =&gt; ''\n ), $atts );\n\n $min_posts = $attrs['min_posts'];\n\n $authors = $wpdb-&gt;get_col(\"SELECT `post_author` FROM\n (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb-&gt;posts}\n WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats`\n WHERE `count` &gt;= {$min_posts} ORDER BY `count` DESC;\");\n\n $my_blog_writers = \"\";\n\n if ( empty ($authors) ) {\n return \"&lt;p&gt;No one has contirbuted any post yet!&lt;/p&gt;\";\n } else {\n foreach ($authors as $author_id) {\n $my_writer = get_userdata($author_id);\n $my_blog_writers .= \"&lt;p&gt;\".$my_writer-&gt;first_name .\" \".$my_writer-&gt;last_name .\" : \". $my_writer-&gt;user_email.\"&lt;/p&gt;\";\n }\n return $my_blog_writers;\n } \n}\nadd_shortcode( 'myblogwriters', 'show_min_one_post_writers' );\n</code></pre>\n" } ]
2015/12/24
[ "https://wordpress.stackexchange.com/questions/212808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68671/" ]
I need to display on a page the list of emails of the users who already posted once on my site. I have this snippet of code: ``` global $wpdb; $min_posts = 1; $author_ids = $wpdb->get_col("SELECT `post_author` FROM (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb->posts} WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats` WHERE `count` >= {$min_posts} ORDER BY `count` DESC;"); ``` But I have two issues: how can I choose to display it on a particular page (I usually add snippets to functions.php) and how can I get the emails instead of the iDs ? I probably have to use `get_the_author_meta( 'user_email' )` but I don't know how to implement it here. Thanks for your time and help
You can place following code in your functions.php file & use the shortcode `[myblogwriters min_posts="1"]` anywhere in the page/post content and can also change the min\_posts value :) ``` function show_min_one_post_writers($atts){ global $wpdb; $attrs = shortcode_atts( array( 'min_posts' => '' ), $atts ); $min_posts = $attrs['min_posts']; $authors = $wpdb->get_col("SELECT `post_author` FROM (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb->posts} WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats` WHERE `count` >= {$min_posts} ORDER BY `count` DESC;"); $my_blog_writers = ""; if ( empty ($authors) ) { return "<p>No one has contirbuted any post yet!</p>"; } else { foreach ($authors as $author_id) { $my_writer = get_userdata($author_id); $my_blog_writers .= "<p>".$my_writer->first_name ." ".$my_writer->last_name ." : ". $my_writer->user_email."</p>"; } return $my_blog_writers; } } add_shortcode( 'myblogwriters', 'show_min_one_post_writers' ); ```
212,812
<p>I am currently creating a post programmatically, with the <code>wp_insert_post</code> function but am having some difficulties when adding two variables into the content part of the array. I would like to add <code>$_POST['poll-description']</code> as well as the code I am currently using <code>'[poll id=' . $latest_pollid . ']'</code> to be the post content.</p> <p>Is there any way I can use both of these in the following code?</p> <pre><code>$post_id = wp_insert_post( array( 'comment_status' =&gt; 'open', 'ping_status' =&gt; 'closed', 'post_author' =&gt; $current_user-&gt;ID, 'post_name' =&gt; $slug, 'post_title' =&gt; $pollq_question, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'post', 'post_content' =&gt; '[poll id=' . $latest_pollid . ']' ) ); </code></pre> <p>Would this work?</p> <pre><code>`post_content' =&gt; $_POST['poll-description'] '[poll id=' . $latest_pollid . ']'` </code></pre>
[ { "answer_id": 212811, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 2, "selected": false, "text": "<p>If your query is correct and returns list of <code>user_id</code> then you can run the below</p>\n\n<pre><code>foreach($user_id_array as $user_id){\n echo get_the_author_meta( 'user_email', $user_id );\n echo \"&lt;br&gt;\";//to print in new line for each user mail\n}\n</code></pre>\n\n<p>You can use the above in page template or in any templating hook. For example you can print this in <code>wp_head</code>,<code>wp_footer</code> etc</p>\n\n<p>Let us do this in an empty page. Let us assume the <code>page_id</code> is <code>8</code> then the following filter will do the trick</p>\n\n<pre><code>function print_selected_umail($content){\n\n//check if we are in required page(8), so that we can add the selected user mail\nif(is_page(8)){\n //queried result\n foreach($user_id_array as $user_id){\n $content .= get_the_author_meta( 'user_email', $user_id );\n $content .= \"&lt;br&gt;\";//to print in new line for each user mail\n }\n }\nreturn $content;\n}\nadd_filter('the_content','print_selected_umail');\n</code></pre>\n" }, { "answer_id": 212813, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>You can place following code in your functions.php file &amp; use the shortcode <code>[myblogwriters min_posts=\"1\"]</code> anywhere in the page/post content and can also change the min_posts value :)</p>\n\n<pre><code>function show_min_one_post_writers($atts){\n\n global $wpdb;\n\n $attrs = shortcode_atts( array(\n 'min_posts' =&gt; ''\n ), $atts );\n\n $min_posts = $attrs['min_posts'];\n\n $authors = $wpdb-&gt;get_col(\"SELECT `post_author` FROM\n (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb-&gt;posts}\n WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats`\n WHERE `count` &gt;= {$min_posts} ORDER BY `count` DESC;\");\n\n $my_blog_writers = \"\";\n\n if ( empty ($authors) ) {\n return \"&lt;p&gt;No one has contirbuted any post yet!&lt;/p&gt;\";\n } else {\n foreach ($authors as $author_id) {\n $my_writer = get_userdata($author_id);\n $my_blog_writers .= \"&lt;p&gt;\".$my_writer-&gt;first_name .\" \".$my_writer-&gt;last_name .\" : \". $my_writer-&gt;user_email.\"&lt;/p&gt;\";\n }\n return $my_blog_writers;\n } \n}\nadd_shortcode( 'myblogwriters', 'show_min_one_post_writers' );\n</code></pre>\n" } ]
2015/12/24
[ "https://wordpress.stackexchange.com/questions/212812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84655/" ]
I am currently creating a post programmatically, with the `wp_insert_post` function but am having some difficulties when adding two variables into the content part of the array. I would like to add `$_POST['poll-description']` as well as the code I am currently using `'[poll id=' . $latest_pollid . ']'` to be the post content. Is there any way I can use both of these in the following code? ``` $post_id = wp_insert_post( array( 'comment_status' => 'open', 'ping_status' => 'closed', 'post_author' => $current_user->ID, 'post_name' => $slug, 'post_title' => $pollq_question, 'post_status' => 'publish', 'post_type' => 'post', 'post_content' => '[poll id=' . $latest_pollid . ']' ) ); ``` Would this work? ``` `post_content' => $_POST['poll-description'] '[poll id=' . $latest_pollid . ']'` ```
You can place following code in your functions.php file & use the shortcode `[myblogwriters min_posts="1"]` anywhere in the page/post content and can also change the min\_posts value :) ``` function show_min_one_post_writers($atts){ global $wpdb; $attrs = shortcode_atts( array( 'min_posts' => '' ), $atts ); $min_posts = $attrs['min_posts']; $authors = $wpdb->get_col("SELECT `post_author` FROM (SELECT `post_author`, COUNT(*) AS `count` FROM {$wpdb->posts} WHERE `post_status`='publish' GROUP BY `post_author`) AS `stats` WHERE `count` >= {$min_posts} ORDER BY `count` DESC;"); $my_blog_writers = ""; if ( empty ($authors) ) { return "<p>No one has contirbuted any post yet!</p>"; } else { foreach ($authors as $author_id) { $my_writer = get_userdata($author_id); $my_blog_writers .= "<p>".$my_writer->first_name ." ".$my_writer->last_name ." : ". $my_writer->user_email."</p>"; } return $my_blog_writers; } } add_shortcode( 'myblogwriters', 'show_min_one_post_writers' ); ```
212,833
<p>I understand that each page is assigned its own class such as .page-id-22 &amp; I can use that to assign a background image to it using the stylesheet but I've seen a theme that adds a control to the admin section of the page itself, which is what I'd like to accomplish. </p> <p>Basically, the user would be able to click &amp; upload an image to an individual page, as needed, without the need to edit the stylesheet. </p> <p>Would it be similar to some ideas posited in <a href="https://wordpress.org/support/topic/post-body-backgroundcss-controlled-via-admin" rel="nofollow noreferrer">this dated discussion</a>?</p> <p>This question is different from <a href="https://wordpress.stackexchange.com/questions/204327/create-a-full-width-responsive-header-image-per-page">this discussion</a> because it's not just the header &amp; this is something that needs to be part of the theme which doesn't make use of a plugin.</p>
[ { "answer_id": 212834, "author": "Arsalan", "author_id": 85844, "author_profile": "https://wordpress.stackexchange.com/users/85844", "pm_score": 1, "selected": false, "text": "<p>It can be done with a custom field and the CSS should be changed to <code>.php</code> file:</p>\n\n<pre><code>$image = get_post_meta( $post-&gt;ID, \"ImagePathFromCustomField\", true );\nif ( $image != '' ) { \n ?&gt;\n &lt;style type=\"text/css\"&gt;\n .bg-image { \n background-image: url(&lt;?php echo $image; ?&gt;); \n background-repeat: repeat; \n }\n &lt;/style&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 212836, "author": "apsolut", "author_id": 51004, "author_profile": "https://wordpress.stackexchange.com/users/51004", "pm_score": 0, "selected": false, "text": "<p>The easiest way would be to use custom fields, lets say ACF (Advanced Custom Fields) \n *even free version from WordPress.org </p>\n\n<ol>\n<li><p>Lets say we are using ACF, you need to Create field group: <a href=\"http://www.advancedcustomfields.com/resources/creating-a-field-group/\" rel=\"nofollow noreferrer\">Follow this Link</a>, and go to Custom Fields > Add New</p></li>\n<li><p>Fields, Create field, Add Field Label and Field Name (YOUR_FIELD_NAME) after that select Field Type: Image (when you select this type of field, you will get option to display it as URL</p></li>\n<li><p>Select location (Page or Posts) - where to show that Field you created:<a href=\"https://i.stack.imgur.com/Clymw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Clymw.png\" alt=\"ACF Choose Location\"></a></p></li>\n<li><p>Now we have Image Field button on every page in backend lets jump to frontend display</p></li>\n<li><p>Decide where you want to display that image (code), it can be page.php,footer.php,header.php (or anything you need), open that file and you need to paste <code>&lt;img src=\"&lt;?php the_field('YOUR_FIELD_NAME'); ?&gt;\" /&gt;</code> there.</p></li>\n<li><p>More advanced things are, you can use if/else to display image and jquery for that background, <code>&lt;?php if( get_field('YOUR_FIELD_NAME') ): ?&gt;\n &lt;img src=\"&lt;?php the_field('YOUR_FIELD_NAME'); ?&gt;\" /&gt;\n &lt;script&gt;Your Script here&lt;/script&gt;<br>\n&lt;?php endif; ?&gt;</code></p></li>\n<li><p>Best way would be to insert your script file in footer, so it loads after jQuery and other parts and only when there is image the same code as <strong>6</strong> but containing only script code..</p></li>\n</ol>\n\n<p>INFO: section <strong>3</strong> will give you backend option to show Image Field when you create new or edit old Page</p>\n" }, { "answer_id": 212850, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Check out the <a href=\"https://github.com/ericandrewlewis/wp-custom-css-per-post\" rel=\"nofollow\">Custom CSS Per Post Plugin</a> on GitHub to see how to use a meta box with the customizer. There is also a Gist: <a href=\"https://gist.github.com/ericandrewlewis/5d51ba515cd96f4e089c\" rel=\"nofollow\">Custom CSS in WordPress, editable in the Customizer</a> where you could just replace the CSS portion with a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Image_Control\" rel=\"nofollow\">WP_Customize_Image_Control</a>.</p>\n" } ]
2015/12/24
[ "https://wordpress.stackexchange.com/questions/212833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76434/" ]
I understand that each page is assigned its own class such as .page-id-22 & I can use that to assign a background image to it using the stylesheet but I've seen a theme that adds a control to the admin section of the page itself, which is what I'd like to accomplish. Basically, the user would be able to click & upload an image to an individual page, as needed, without the need to edit the stylesheet. Would it be similar to some ideas posited in [this dated discussion](https://wordpress.org/support/topic/post-body-backgroundcss-controlled-via-admin)? This question is different from [this discussion](https://wordpress.stackexchange.com/questions/204327/create-a-full-width-responsive-header-image-per-page) because it's not just the header & this is something that needs to be part of the theme which doesn't make use of a plugin.
It can be done with a custom field and the CSS should be changed to `.php` file: ``` $image = get_post_meta( $post->ID, "ImagePathFromCustomField", true ); if ( $image != '' ) { ?> <style type="text/css"> .bg-image { background-image: url(<?php echo $image; ?>); background-repeat: repeat; } </style> <?php } ```
212,845
<p>I'm looking to add some client-side (JavaScript) events to the post edit screen of wp-admin (<code>post.php?action=edit</code>). I wish to fire events when the user selects a new featured image and a different event when they remove the featured image.</p> <p>So far I've been able to find <a href="https://wordpress.stackexchange.com/questions/175790/run-script-after-clicking-set-featured-image-in-media">this wordpress.se answer</a>, which has allowed me to hook into the <em>"on featured image set"</em> event, however I'm at a loss as to how to hook into the <em>"on featued image removed"</em> event, as it pertains to the client. </p> <p>I've dug into <code>wp.media.featuredImage.frame().states._events</code> a little bit using Chrome's WebInspector, but there doesn't seem to be an event registered that quite matches what I'm looking for...</p> <p><a href="https://i.stack.imgur.com/dyett.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dyett.png" alt="wp.media.featuredImage.frame().states._events"></a></p> <p>The only one that jumps out at me as a potential candidate is the <code>content:render:edit-image</code> event, but it doesn't fire during either of the events I'm trying to listen for!</p> <p>Does anyone know of a way to do this?</p>
[ { "answer_id": 213192, "author": "Jordan Foreman", "author_id": 7222, "author_profile": "https://wordpress.stackexchange.com/users/7222", "pm_score": 3, "selected": true, "text": "<p>So I was able to achieve what I wanted, albeit in a bit of a roundabout way. I'll share my solution here in case anyone stumbles across this post looking to do something similar.</p>\n\n<p>Rather than adding an event listener to some unset event (that doesn't exist) on the object returned by <code>wp.media.featuredImage.frame()</code>, I instead added my own onclick event listener to the <code>#remove-post-thumbnail</code> link element. This feels a little hacky to me, since its not <em>directly</em> tied to the unset of a featured image, however since there's no prompt to verify removal, the user interaction is fairly seemless.</p>\n\n<p>There is a caveat with this solution, however - there is already an <code>onclick</code> event bound to that link, so you need to avoid overriding that, or else you won't be able to actually remove the featured image. Originally I tried capturing that default onclick event and then calling it from within my own event that overrides it, like so:</p>\n\n<p><strong>DO NOT DO THIS</strong></p>\n\n<pre><code>var ogCallback = document.getElementById('remove-post-thumbnail').onclick;\ndocument.getElementById('remove-post-thumbnail').onclick = function(e) {\n // My code - do some things\n // ...\n ogCallback(e);\n}\n</code></pre>\n\n<p>But this made WordPress a little buggy when removing the featured image, likely due to some JavaScript scoping that I wasn't taking into account. Because I'm also leveraging jQuery (this is a judgment-free zone, right?) I was able to use jQuery's event binding system instead, and avoid overriding the default behaviour, allowing my custom code to run in tandem with WordPress' featured image removal logic:</p>\n\n<p><strong>DO THIS</strong></p>\n\n<pre><code>$(document).on('click', '#remove-post-thumbnail', function(){\n // Do stuff. Don't let your dreams be dreams\n});\n</code></pre>\n" }, { "answer_id": 395776, "author": "Léo Muniz", "author_id": 164153, "author_profile": "https://wordpress.stackexchange.com/users/164153", "pm_score": 0, "selected": false, "text": "<p>The solution above from Jordan Foreman makes sense and I first tried exactly the same thing, but it did not work for me.</p>\n<p>In fact, in the WordPress <strong>media-editor.js</strong> core file there is a <code>return false</code> on the <code>#remove-post-thumbnail</code> click event that I think it's being called before the <code>document</code> click and that could be preventing it to be triggered.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {\n event.preventDefault();\n // Stop propagation to prevent thickbox from activating.\n event.stopPropagation();\n\n wp.media.featuredImage.frame().open();\n}).on( 'click', '#remove-post-thumbnail', function() {\n wp.media.featuredImage.remove();\n return false; // this line cancels the click and prevents other click events.\n});\n</code></pre>\n<p>So, to trigger an event when removing a featured image, I attached the click event directly to the <code>#postimagediv</code> (the Featured Image meta box itself) and it worked.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$( '#postimagediv' ).on('click', '#remove-post-thumbnail', function(){\n // Do stuff. Don't let your dreams be dreams\n});\n</code></pre>\n" } ]
2015/12/24
[ "https://wordpress.stackexchange.com/questions/212845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7222/" ]
I'm looking to add some client-side (JavaScript) events to the post edit screen of wp-admin (`post.php?action=edit`). I wish to fire events when the user selects a new featured image and a different event when they remove the featured image. So far I've been able to find [this wordpress.se answer](https://wordpress.stackexchange.com/questions/175790/run-script-after-clicking-set-featured-image-in-media), which has allowed me to hook into the *"on featured image set"* event, however I'm at a loss as to how to hook into the *"on featued image removed"* event, as it pertains to the client. I've dug into `wp.media.featuredImage.frame().states._events` a little bit using Chrome's WebInspector, but there doesn't seem to be an event registered that quite matches what I'm looking for... [![wp.media.featuredImage.frame().states._events](https://i.stack.imgur.com/dyett.png)](https://i.stack.imgur.com/dyett.png) The only one that jumps out at me as a potential candidate is the `content:render:edit-image` event, but it doesn't fire during either of the events I'm trying to listen for! Does anyone know of a way to do this?
So I was able to achieve what I wanted, albeit in a bit of a roundabout way. I'll share my solution here in case anyone stumbles across this post looking to do something similar. Rather than adding an event listener to some unset event (that doesn't exist) on the object returned by `wp.media.featuredImage.frame()`, I instead added my own onclick event listener to the `#remove-post-thumbnail` link element. This feels a little hacky to me, since its not *directly* tied to the unset of a featured image, however since there's no prompt to verify removal, the user interaction is fairly seemless. There is a caveat with this solution, however - there is already an `onclick` event bound to that link, so you need to avoid overriding that, or else you won't be able to actually remove the featured image. Originally I tried capturing that default onclick event and then calling it from within my own event that overrides it, like so: **DO NOT DO THIS** ``` var ogCallback = document.getElementById('remove-post-thumbnail').onclick; document.getElementById('remove-post-thumbnail').onclick = function(e) { // My code - do some things // ... ogCallback(e); } ``` But this made WordPress a little buggy when removing the featured image, likely due to some JavaScript scoping that I wasn't taking into account. Because I'm also leveraging jQuery (this is a judgment-free zone, right?) I was able to use jQuery's event binding system instead, and avoid overriding the default behaviour, allowing my custom code to run in tandem with WordPress' featured image removal logic: **DO THIS** ``` $(document).on('click', '#remove-post-thumbnail', function(){ // Do stuff. Don't let your dreams be dreams }); ```
212,911
<p>Don't ask why. Image below pretty much ask what I'm looking to achieve:</p> <p><img src="https://s19.postimg.org/g73zya4ab/how_to_remove_link_to_existing_content.png" alt="screenshot"></p>
[ { "answer_id": 212919, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Place this code in your functions.php file</p>\n\n<pre><code>add_action( 'admin_print_scripts-post.php', 'wpse22643_overwrite_wplinks' );\nadd_action( 'admin_print_scripts-post-new.php', 'wpse22643_overwrite_wplinks' );\n\nfunction wpse22643_overwrite_wplinks( $hook ) {\n\n // register is important, that other plugins will change or deactivate this\n wp_register_script(\n 'overwrite-wplinks', \n get_stylesheet_directory_uri() . '/js/overwrite-wplinks.js',\n array( 'jquery' ),\n '',\n TRUE\n );\n wp_enqueue_script( 'overwrite-wplinks' );\n}\n</code></pre>\n\n<p>Double check the path to the js file you want to include above (<strong>/js/overwrite-wplinks.js</strong>). Then place the following code in the above mentioned js file.</p>\n\n<pre><code>( function( $ ) {\n\n if ( typeof wpLink == 'undefined' )\n return;\n\n wpLink.setDefaultValues = function () { \n\n $('#link-selector p:nth-child(2).howto').css('display','none');\n\n };\n\n} )( jQuery );\n</code></pre>\n" }, { "answer_id": 212922, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>We could hook into the <code>after_wp_tiny_mce</code> with some CSS to hide it, if the <code>wplink</code> editor plugin is loaded. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] ) \n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' ) \n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" }, { "answer_id": 232476, "author": "Mani", "author_id": 98462, "author_profile": "https://wordpress.stackexchange.com/users/98462", "pm_score": 0, "selected": false, "text": "<p>I found this code some ones blog but it worked for me , Solved my problem </p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] )\n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' )\n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" } ]
2015/12/26
[ "https://wordpress.stackexchange.com/questions/212911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81346/" ]
Don't ask why. Image below pretty much ask what I'm looking to achieve: ![screenshot](https://s19.postimg.org/g73zya4ab/how_to_remove_link_to_existing_content.png)
We could hook into the `after_wp_tiny_mce` with some CSS to hide it, if the `wplink` editor plugin is loaded. **Example:** ``` add_action( 'after_wp_tiny_mce', function( $settings ) { // Check for the 'wplink' editor plugin if( isset( $settings['content']['plugins'] ) && false !== strpos( $settings['content']['plugins'], 'wplink' ) ) echo '<style> #link-selector > .howto, #link-selector > #search-panel { display:none; } </style>'; } ); ```
212,949
<p>I have an issue I can't solve. When my website loads it seems to be grabbing an old version of our customized CSS and using that to override all our new CSS. But that old version no longer exists. I have no idea where it's coming from.</p> <p>If you look at our page source here: <a href="http://view-source:http://www.universaltheosophy.com/" rel="nofollow">view-source:http://www.universaltheosophy.com/</a> then scroll down and you'll see a bunch of css code, some of which I have no idea where it's coming from. After this:</p> <pre><code>/*---------------------------------- * end review ----------------------------------*/ </code></pre> <p>You'll see stuff like this:</p> <pre><code>#navigation .inner { width: 1250px !important; } </code></pre> <p>I have no idea how to find out where this code is coming from. It's not in any of the CSS files under our theme's directory. I also tried turning off and disabling "wp supercache" after deleting the whole cache, thinking maybe the css was cached somewhere, but that did nothing. I've done a "string search" through the whole wordpress directory and can't find this css code anywhere!</p> <p>The thing is, this css code <em>was</em> part of an old version of our customized CSS. We have a file called "custom-overrides-2.css" that is added to our theme's css files, which provides certain overrides. There was a previous version "custom-overrides-1.css", which I think contained the above css, but it's long since been deleted.</p> <p>How can I find out where this code is coming from, and how do I get rid of it? It's completely f*ing up our mobile display, since our mobile "responsive.css" is being overridden by it.</p> <p>Any help would be very much appreciated.</p>
[ { "answer_id": 212919, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Place this code in your functions.php file</p>\n\n<pre><code>add_action( 'admin_print_scripts-post.php', 'wpse22643_overwrite_wplinks' );\nadd_action( 'admin_print_scripts-post-new.php', 'wpse22643_overwrite_wplinks' );\n\nfunction wpse22643_overwrite_wplinks( $hook ) {\n\n // register is important, that other plugins will change or deactivate this\n wp_register_script(\n 'overwrite-wplinks', \n get_stylesheet_directory_uri() . '/js/overwrite-wplinks.js',\n array( 'jquery' ),\n '',\n TRUE\n );\n wp_enqueue_script( 'overwrite-wplinks' );\n}\n</code></pre>\n\n<p>Double check the path to the js file you want to include above (<strong>/js/overwrite-wplinks.js</strong>). Then place the following code in the above mentioned js file.</p>\n\n<pre><code>( function( $ ) {\n\n if ( typeof wpLink == 'undefined' )\n return;\n\n wpLink.setDefaultValues = function () { \n\n $('#link-selector p:nth-child(2).howto').css('display','none');\n\n };\n\n} )( jQuery );\n</code></pre>\n" }, { "answer_id": 212922, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>We could hook into the <code>after_wp_tiny_mce</code> with some CSS to hide it, if the <code>wplink</code> editor plugin is loaded. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] ) \n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' ) \n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" }, { "answer_id": 232476, "author": "Mani", "author_id": 98462, "author_profile": "https://wordpress.stackexchange.com/users/98462", "pm_score": 0, "selected": false, "text": "<p>I found this code some ones blog but it worked for me , Solved my problem </p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] )\n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' )\n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" } ]
2015/12/26
[ "https://wordpress.stackexchange.com/questions/212949", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73388/" ]
I have an issue I can't solve. When my website loads it seems to be grabbing an old version of our customized CSS and using that to override all our new CSS. But that old version no longer exists. I have no idea where it's coming from. If you look at our page source here: [view-source:http://www.universaltheosophy.com/](http://view-source:http://www.universaltheosophy.com/) then scroll down and you'll see a bunch of css code, some of which I have no idea where it's coming from. After this: ``` /*---------------------------------- * end review ----------------------------------*/ ``` You'll see stuff like this: ``` #navigation .inner { width: 1250px !important; } ``` I have no idea how to find out where this code is coming from. It's not in any of the CSS files under our theme's directory. I also tried turning off and disabling "wp supercache" after deleting the whole cache, thinking maybe the css was cached somewhere, but that did nothing. I've done a "string search" through the whole wordpress directory and can't find this css code anywhere! The thing is, this css code *was* part of an old version of our customized CSS. We have a file called "custom-overrides-2.css" that is added to our theme's css files, which provides certain overrides. There was a previous version "custom-overrides-1.css", which I think contained the above css, but it's long since been deleted. How can I find out where this code is coming from, and how do I get rid of it? It's completely f\*ing up our mobile display, since our mobile "responsive.css" is being overridden by it. Any help would be very much appreciated.
We could hook into the `after_wp_tiny_mce` with some CSS to hide it, if the `wplink` editor plugin is loaded. **Example:** ``` add_action( 'after_wp_tiny_mce', function( $settings ) { // Check for the 'wplink' editor plugin if( isset( $settings['content']['plugins'] ) && false !== strpos( $settings['content']['plugins'], 'wplink' ) ) echo '<style> #link-selector > .howto, #link-selector > #search-panel { display:none; } </style>'; } ); ```
212,951
<p>I have WordPress site 1 on domain1.com.</p> <p>I copied WordPress site 1 to WordPress site 2 on domain2.com (database and files).</p> <p>Both WordPress sites have their independent database names/usernames/passwords and separate FTP credentials/directories.</p> <p>Both WordPress sites are on the same server (localhost).</p> <p>When I delete a plugin/theme from WordPress site 2, that plugin/theme also gets deleted from WordPress site 1 (and vice versa)! Likewise, when I install a new plugin/theme on one of the sites, it also gets installed on the other site!</p> <p>However, if I activate a plugin/theme on one site, it does not get activated on the other site. Also, if I add/delete a post/page/media file from one site, it does not get added/deleted to the other site.</p> <p>Does anyone have any idea what is going on? I made sure there are no references in database 2 to database 1, and I even hardcoded the siteurl into wp-config.php</p> <pre><code>define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST']); </code></pre> <p>I'm still having this problem after three hours of deleting the database/files and re-uploading them. I even tried creating WordPress site 2 on entirely different FTP directories with new credentials (and likewise a new database and credentials) to no avail!</p> <p>EDIT:</p> <p>It gets even crazier. I completely deleted WordPress site 2's database and all files. I then did a completely NEW WordPress install, and when I click on Plugins, I see all the plugins that are on WordPress site 1 (likewise for themes)! The problem somehow still exists! Now I am completely stumped.</p> <p>I'm on an Ubuntu server running Nginx.</p>
[ { "answer_id": 212919, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Place this code in your functions.php file</p>\n\n<pre><code>add_action( 'admin_print_scripts-post.php', 'wpse22643_overwrite_wplinks' );\nadd_action( 'admin_print_scripts-post-new.php', 'wpse22643_overwrite_wplinks' );\n\nfunction wpse22643_overwrite_wplinks( $hook ) {\n\n // register is important, that other plugins will change or deactivate this\n wp_register_script(\n 'overwrite-wplinks', \n get_stylesheet_directory_uri() . '/js/overwrite-wplinks.js',\n array( 'jquery' ),\n '',\n TRUE\n );\n wp_enqueue_script( 'overwrite-wplinks' );\n}\n</code></pre>\n\n<p>Double check the path to the js file you want to include above (<strong>/js/overwrite-wplinks.js</strong>). Then place the following code in the above mentioned js file.</p>\n\n<pre><code>( function( $ ) {\n\n if ( typeof wpLink == 'undefined' )\n return;\n\n wpLink.setDefaultValues = function () { \n\n $('#link-selector p:nth-child(2).howto').css('display','none');\n\n };\n\n} )( jQuery );\n</code></pre>\n" }, { "answer_id": 212922, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>We could hook into the <code>after_wp_tiny_mce</code> with some CSS to hide it, if the <code>wplink</code> editor plugin is loaded. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] ) \n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' ) \n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" }, { "answer_id": 232476, "author": "Mani", "author_id": 98462, "author_profile": "https://wordpress.stackexchange.com/users/98462", "pm_score": 0, "selected": false, "text": "<p>I found this code some ones blog but it worked for me , Solved my problem </p>\n\n<pre><code>add_action( 'after_wp_tiny_mce', function( $settings )\n{\n // Check for the 'wplink' editor plugin\n if( isset( $settings['content']['plugins'] )\n &amp;&amp; false !== strpos( $settings['content']['plugins'], 'wplink' )\n )\n echo '&lt;style&gt;\n #link-selector &gt; .howto, #link-selector &gt; #search-panel { display:none; }\n &lt;/style&gt;';\n} );\n</code></pre>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212951", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20223/" ]
I have WordPress site 1 on domain1.com. I copied WordPress site 1 to WordPress site 2 on domain2.com (database and files). Both WordPress sites have their independent database names/usernames/passwords and separate FTP credentials/directories. Both WordPress sites are on the same server (localhost). When I delete a plugin/theme from WordPress site 2, that plugin/theme also gets deleted from WordPress site 1 (and vice versa)! Likewise, when I install a new plugin/theme on one of the sites, it also gets installed on the other site! However, if I activate a plugin/theme on one site, it does not get activated on the other site. Also, if I add/delete a post/page/media file from one site, it does not get added/deleted to the other site. Does anyone have any idea what is going on? I made sure there are no references in database 2 to database 1, and I even hardcoded the siteurl into wp-config.php ``` define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST']); ``` I'm still having this problem after three hours of deleting the database/files and re-uploading them. I even tried creating WordPress site 2 on entirely different FTP directories with new credentials (and likewise a new database and credentials) to no avail! EDIT: It gets even crazier. I completely deleted WordPress site 2's database and all files. I then did a completely NEW WordPress install, and when I click on Plugins, I see all the plugins that are on WordPress site 1 (likewise for themes)! The problem somehow still exists! Now I am completely stumped. I'm on an Ubuntu server running Nginx.
We could hook into the `after_wp_tiny_mce` with some CSS to hide it, if the `wplink` editor plugin is loaded. **Example:** ``` add_action( 'after_wp_tiny_mce', function( $settings ) { // Check for the 'wplink' editor plugin if( isset( $settings['content']['plugins'] ) && false !== strpos( $settings['content']['plugins'], 'wplink' ) ) echo '<style> #link-selector > .howto, #link-selector > #search-panel { display:none; } </style>'; } ); ```
212,953
<p>I have a custom post meta box that I want to put in the right sidebar. When I set the priority to <code>high</code> it appears in the number 1 spot in sidebar above everything. If I set to <code>core</code> it appear at the bottom of right sidebar.</p> <p>My desired position is in the number 2 spot in the right sidebar. Right below the publish metabox.</p> <p>Is this possibble? </p>
[ { "answer_id": 212969, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": false, "text": "<p>Still if its something like client requirement then below is somewhat <strong>hack</strong> sort of solution. Add this code to your <code>add_meta_box()</code> function. For the sake of understanding, below I have provided complete function but you will need to use selective code :-) Do let me know how it goes.</p>\n\n<pre><code>function myplugin_add_meta_box() {\n\n $screens = array( 'post', 'page' );\n\n foreach ( $screens as $screen ) {\n\n add_meta_box(\n 'testdiv',\n __( 'My Post Section Title', 'myplugin_textdomain' ),\n 'myplugin_meta_box_callback',\n $screen,\n 'side'\n );\n }\n /* Get the user details to find user id for whom this order should be shown. Ideally, I believe it will be admin user. Make sure you change the email id*/\n $user = get_user_by( 'email', '[email protected]' ); \n $order = get_user_option(\"meta-box-order_post\", $user-&gt;ID);\n\n $current_order = array(); \n $current_order = explode(\",\",$order['side']);\n\n for($i=0 ; $i &lt;= count ($current_order) ; $i++){\n $temp = $current_order[$i];\n if ( $current_order[$i] == 'testdiv' &amp;&amp; $i != 1) {\n $current_order[$i] = $current_order[1]; \n $current_order[1] = $temp; \n }\n }\n\n $order['side'] = implode(\",\",$current_order);\n\n update_user_option($user-&gt;ID, \"meta-box-order_page\", $order, true);\n update_user_option($user-&gt;ID, \"meta-box-order_post\", $order, true);\n\n}\nadd_action( 'add_meta_boxes', 'myplugin_add_meta_box', 2 );\n</code></pre>\n" }, { "answer_id": 342375, "author": "Anthony Eden", "author_id": 171483, "author_profile": "https://wordpress.stackexchange.com/users/171483", "pm_score": 0, "selected": false, "text": "<p>After some experimentation, I have come up with this method which may be a tad more robust:</p>\n\n<pre><code>add_action('add_meta_boxes', function () {\n $screens = array('post', 'page');\n\n foreach ($screens as $screen) {\n add_meta_box(\"metabox_name\", \"Meta Box Title\", \"my_metabox_callback\", $screen, \"side\", \"high\");\n\n // Force the box to display below the 'Publish' metabox\n $user = wp_get_current_user(); \n $order = get_user_option(\"meta-box-order_\".$screen, $user-&gt;ID);\n\n if(strpos($order['side'], \"metabox_name\") !== false) {\n $order = str_replace('metabox_name,', '', $order['side']);\n }\n\n if(strpos($order['side'], \"submitdiv\") === false) {\n $order['side'] = 'submitdiv,' . $order['side'];\n }\n\n if(substr($order['side'], -1) == \",\") {\n $order['side'] = substr($order['side'], 0, -1);\n }\n\n $current_order = array(); \n $current_order = explode(\",\", $order['side']);\n\n // Add this metabox to the order array\n $key = array_search('submitdiv', $current_order, true);\n\n if($key !== false) {\n $new_order = array_merge(\n array_slice($current_order, 0, $key+1),\n array(\"metabox_name\")\n );\n\n if(count($current_order) &gt; $key) {\n $new_order = array_merge(\n $new_order,\n array_slice($current_order, $key+1)\n );\n }\n\n $order['side'] = implode(\",\", $new_order);\n\n update_user_option($user-&gt;ID, \"meta-box-order_\".$screen, $order, true);\n }\n }\n});\n</code></pre>\n\n<p>This doesn't feel very elegant to me, but it does work in a variety of situations where the earlier answer fails (e.g. new users).</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8668/" ]
I have a custom post meta box that I want to put in the right sidebar. When I set the priority to `high` it appears in the number 1 spot in sidebar above everything. If I set to `core` it appear at the bottom of right sidebar. My desired position is in the number 2 spot in the right sidebar. Right below the publish metabox. Is this possibble?
Still if its something like client requirement then below is somewhat **hack** sort of solution. Add this code to your `add_meta_box()` function. For the sake of understanding, below I have provided complete function but you will need to use selective code :-) Do let me know how it goes. ``` function myplugin_add_meta_box() { $screens = array( 'post', 'page' ); foreach ( $screens as $screen ) { add_meta_box( 'testdiv', __( 'My Post Section Title', 'myplugin_textdomain' ), 'myplugin_meta_box_callback', $screen, 'side' ); } /* Get the user details to find user id for whom this order should be shown. Ideally, I believe it will be admin user. Make sure you change the email id*/ $user = get_user_by( 'email', '[email protected]' ); $order = get_user_option("meta-box-order_post", $user->ID); $current_order = array(); $current_order = explode(",",$order['side']); for($i=0 ; $i <= count ($current_order) ; $i++){ $temp = $current_order[$i]; if ( $current_order[$i] == 'testdiv' && $i != 1) { $current_order[$i] = $current_order[1]; $current_order[1] = $temp; } } $order['side'] = implode(",",$current_order); update_user_option($user->ID, "meta-box-order_page", $order, true); update_user_option($user->ID, "meta-box-order_post", $order, true); } add_action( 'add_meta_boxes', 'myplugin_add_meta_box', 2 ); ```
212,978
<p>I am following <a href="http://www.wpbeginner.com/wp-tutorials/how-to-install-and-setup-wordpress-multisite-network/" rel="noreferrer">This tutorial</a> to Create a Network of WordPress Sites . After adding</p> <pre><code>/* Multisite */ define( 'WP_ALLOW_MULTISITE', true ); </code></pre> <p>to my <code>wp-config.php</code> file and when I start to configure multisite network I got this error</p> <pre><code>ERROR: You cannot install a network of sites with your server address. You cannot use port numbers such as :8080 </code></pre> <p>I try to change</p> <pre><code> Listen 0.0.0.0:8080 Listen [::0]:8080 </code></pre> <p>to</p> <pre><code> Listen 0.0.0.0:80 Listen [::0]:80 </code></pre> <p>from <code>httpd.conf</code> of Apache but due to this wamp server remains orange . How to solve this .I am a new to WordPress Any help would be highly appreciated .</p>
[ { "answer_id": 212988, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>You can't use port 8080. I have no idea why as that is a fairly common port for a web server. However, <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L121\" rel=\"noreferrer\">you can't</a>:</p>\n\n<pre><code>121 if ( ( false !== $has_ports &amp;&amp; ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) {\n122 echo '&lt;div class=\"error\"&gt;&lt;p&gt;&lt;strong&gt;' . __( 'ERROR:') . '&lt;/strong&gt; ' . __( 'You cannot install a network of sites with your server address.' ) . '&lt;/p&gt;&lt;/div&gt;';\n123 echo '&lt;p&gt;' . sprintf(\n124 /* translators: %s: port number */\n125 __( 'You cannot use port numbers such as %s.' ),\n126 '&lt;code&gt;' . $has_ports . '&lt;/code&gt;'\n127 ) . '&lt;/p&gt;';\n128 echo '&lt;a href=\"' . esc_url( admin_url() ) . '\"&gt;' . __( 'Return to Dashboard' ) . '&lt;/a&gt;';\n129 echo '&lt;/div&gt;';\n130 include( ABSPATH . 'wp-admin/admin-footer.php' );\n131 die();\n132 }\n</code></pre>\n\n<p>Notice <code>! in_array( $has_ports, array( ':80', ':443' ) )</code>. Those ports are hard-coded. There are no filters you can use to alter them, not even in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L80\" rel=\"noreferrer\"><code>get_clean_basename()</code></a> (and I am afraid to guess at what horrors you'd create if you could alter what that returns). </p>\n\n<p>Alter your server to use port 443 or port 80 instead. </p>\n" }, { "answer_id": 213001, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p><strong>Warning: This is just a test for dev installs and not production sites</strong></p>\n\n<p>I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than <code>:80</code> and <code>:443</code>, e.g. <code>:8080</code>. </p>\n\n<p>I only found this <a href=\"http://benohead.com/wordpress-running-multisite-different-port/\" rel=\"noreferrer\">blog post</a> by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions.</p>\n\n<p>Here's a <em>must-use</em> plugin <code>/wp-content/mu-plugins/wpse-ms-on-different-port.php</code> where we try to avoid core modifications:</p>\n\n<pre><code>&lt;?php \n/**\n * Test for multisite support on a different port than :80 and :443 (e.g. :8080)\n *\n * Here we assume that the 'siteurl' and 'home' options contain the :8080 port\n *\n * WARNING: Not suited for production sites!\n */\n\n/**\n * Get around the problem with wpmu_create_blog() where sanitize_user() \n * strips out the semicolon (:) in the $domain string\n * This means created sites with hostnames of \n * e.g. example.tld8080 instead of example.tld:8080\n */\nadd_filter( 'sanitize_user', function( $username, $raw_username, $strict )\n{\n // Edit the port to your needs\n $port = 8080;\n\n if( $strict // wpmu_create_blog uses strict mode\n &amp;&amp; is_multisite() // multisite check\n &amp;&amp; $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port \n &amp;&amp; false === strpos( $username, ':' . $port ) // stripped domain is without correct port\n )\n $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080\n\n return $username;\n}, 1, 3 );\n\n/**\n * Temporarly change the port (e.g. :8080 ) to :80 to get around \n * the core restriction in the network.php page.\n */\nadd_action( 'load-network.php', function()\n{\n add_filter( 'option_active_plugins', function( $value )\n {\n add_filter( 'option_siteurl', function( $value )\n {\n // Edit the port to your needs\n $port = 8080;\n\n // Network step 2\n if( is_multisite() || network_domain_check() )\n return $value;\n\n // Network step 1\n static $count = 0;\n if( 0 === $count++ )\n $value = str_replace( ':' . $port, ':80', $value );\n return $value;\n } );\n return $value;\n } );\n} );\n</code></pre>\n\n<p>I just tested this on my dev install, but this might need more checks of course ;-)</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84928/" ]
I am following [This tutorial](http://www.wpbeginner.com/wp-tutorials/how-to-install-and-setup-wordpress-multisite-network/) to Create a Network of WordPress Sites . After adding ``` /* Multisite */ define( 'WP_ALLOW_MULTISITE', true ); ``` to my `wp-config.php` file and when I start to configure multisite network I got this error ``` ERROR: You cannot install a network of sites with your server address. You cannot use port numbers such as :8080 ``` I try to change ``` Listen 0.0.0.0:8080 Listen [::0]:8080 ``` to ``` Listen 0.0.0.0:80 Listen [::0]:80 ``` from `httpd.conf` of Apache but due to this wamp server remains orange . How to solve this .I am a new to WordPress Any help would be highly appreciated .
**Warning: This is just a test for dev installs and not production sites** I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than `:80` and `:443`, e.g. `:8080`. I only found this [blog post](http://benohead.com/wordpress-running-multisite-different-port/) by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions. Here's a *must-use* plugin `/wp-content/mu-plugins/wpse-ms-on-different-port.php` where we try to avoid core modifications: ``` <?php /** * Test for multisite support on a different port than :80 and :443 (e.g. :8080) * * Here we assume that the 'siteurl' and 'home' options contain the :8080 port * * WARNING: Not suited for production sites! */ /** * Get around the problem with wpmu_create_blog() where sanitize_user() * strips out the semicolon (:) in the $domain string * This means created sites with hostnames of * e.g. example.tld8080 instead of example.tld:8080 */ add_filter( 'sanitize_user', function( $username, $raw_username, $strict ) { // Edit the port to your needs $port = 8080; if( $strict // wpmu_create_blog uses strict mode && is_multisite() // multisite check && $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port && false === strpos( $username, ':' . $port ) // stripped domain is without correct port ) $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080 return $username; }, 1, 3 ); /** * Temporarly change the port (e.g. :8080 ) to :80 to get around * the core restriction in the network.php page. */ add_action( 'load-network.php', function() { add_filter( 'option_active_plugins', function( $value ) { add_filter( 'option_siteurl', function( $value ) { // Edit the port to your needs $port = 8080; // Network step 2 if( is_multisite() || network_domain_check() ) return $value; // Network step 1 static $count = 0; if( 0 === $count++ ) $value = str_replace( ':' . $port, ':80', $value ); return $value; } ); return $value; } ); } ); ``` I just tested this on my dev install, but this might need more checks of course ;-)
212,979
<p>I'm developing a plugin, and, each time a user uploads an image in the media library, I'd like to modify metadata of this image. I have tried with the hook "wp_handle_upload_prefilter" but it seems this method doesn't work.</p>
[ { "answer_id": 212988, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>You can't use port 8080. I have no idea why as that is a fairly common port for a web server. However, <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L121\" rel=\"noreferrer\">you can't</a>:</p>\n\n<pre><code>121 if ( ( false !== $has_ports &amp;&amp; ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) {\n122 echo '&lt;div class=\"error\"&gt;&lt;p&gt;&lt;strong&gt;' . __( 'ERROR:') . '&lt;/strong&gt; ' . __( 'You cannot install a network of sites with your server address.' ) . '&lt;/p&gt;&lt;/div&gt;';\n123 echo '&lt;p&gt;' . sprintf(\n124 /* translators: %s: port number */\n125 __( 'You cannot use port numbers such as %s.' ),\n126 '&lt;code&gt;' . $has_ports . '&lt;/code&gt;'\n127 ) . '&lt;/p&gt;';\n128 echo '&lt;a href=\"' . esc_url( admin_url() ) . '\"&gt;' . __( 'Return to Dashboard' ) . '&lt;/a&gt;';\n129 echo '&lt;/div&gt;';\n130 include( ABSPATH . 'wp-admin/admin-footer.php' );\n131 die();\n132 }\n</code></pre>\n\n<p>Notice <code>! in_array( $has_ports, array( ':80', ':443' ) )</code>. Those ports are hard-coded. There are no filters you can use to alter them, not even in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L80\" rel=\"noreferrer\"><code>get_clean_basename()</code></a> (and I am afraid to guess at what horrors you'd create if you could alter what that returns). </p>\n\n<p>Alter your server to use port 443 or port 80 instead. </p>\n" }, { "answer_id": 213001, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p><strong>Warning: This is just a test for dev installs and not production sites</strong></p>\n\n<p>I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than <code>:80</code> and <code>:443</code>, e.g. <code>:8080</code>. </p>\n\n<p>I only found this <a href=\"http://benohead.com/wordpress-running-multisite-different-port/\" rel=\"noreferrer\">blog post</a> by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions.</p>\n\n<p>Here's a <em>must-use</em> plugin <code>/wp-content/mu-plugins/wpse-ms-on-different-port.php</code> where we try to avoid core modifications:</p>\n\n<pre><code>&lt;?php \n/**\n * Test for multisite support on a different port than :80 and :443 (e.g. :8080)\n *\n * Here we assume that the 'siteurl' and 'home' options contain the :8080 port\n *\n * WARNING: Not suited for production sites!\n */\n\n/**\n * Get around the problem with wpmu_create_blog() where sanitize_user() \n * strips out the semicolon (:) in the $domain string\n * This means created sites with hostnames of \n * e.g. example.tld8080 instead of example.tld:8080\n */\nadd_filter( 'sanitize_user', function( $username, $raw_username, $strict )\n{\n // Edit the port to your needs\n $port = 8080;\n\n if( $strict // wpmu_create_blog uses strict mode\n &amp;&amp; is_multisite() // multisite check\n &amp;&amp; $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port \n &amp;&amp; false === strpos( $username, ':' . $port ) // stripped domain is without correct port\n )\n $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080\n\n return $username;\n}, 1, 3 );\n\n/**\n * Temporarly change the port (e.g. :8080 ) to :80 to get around \n * the core restriction in the network.php page.\n */\nadd_action( 'load-network.php', function()\n{\n add_filter( 'option_active_plugins', function( $value )\n {\n add_filter( 'option_siteurl', function( $value )\n {\n // Edit the port to your needs\n $port = 8080;\n\n // Network step 2\n if( is_multisite() || network_domain_check() )\n return $value;\n\n // Network step 1\n static $count = 0;\n if( 0 === $count++ )\n $value = str_replace( ':' . $port, ':80', $value );\n return $value;\n } );\n return $value;\n } );\n} );\n</code></pre>\n\n<p>I just tested this on my dev install, but this might need more checks of course ;-)</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85931/" ]
I'm developing a plugin, and, each time a user uploads an image in the media library, I'd like to modify metadata of this image. I have tried with the hook "wp\_handle\_upload\_prefilter" but it seems this method doesn't work.
**Warning: This is just a test for dev installs and not production sites** I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than `:80` and `:443`, e.g. `:8080`. I only found this [blog post](http://benohead.com/wordpress-running-multisite-different-port/) by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions. Here's a *must-use* plugin `/wp-content/mu-plugins/wpse-ms-on-different-port.php` where we try to avoid core modifications: ``` <?php /** * Test for multisite support on a different port than :80 and :443 (e.g. :8080) * * Here we assume that the 'siteurl' and 'home' options contain the :8080 port * * WARNING: Not suited for production sites! */ /** * Get around the problem with wpmu_create_blog() where sanitize_user() * strips out the semicolon (:) in the $domain string * This means created sites with hostnames of * e.g. example.tld8080 instead of example.tld:8080 */ add_filter( 'sanitize_user', function( $username, $raw_username, $strict ) { // Edit the port to your needs $port = 8080; if( $strict // wpmu_create_blog uses strict mode && is_multisite() // multisite check && $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port && false === strpos( $username, ':' . $port ) // stripped domain is without correct port ) $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080 return $username; }, 1, 3 ); /** * Temporarly change the port (e.g. :8080 ) to :80 to get around * the core restriction in the network.php page. */ add_action( 'load-network.php', function() { add_filter( 'option_active_plugins', function( $value ) { add_filter( 'option_siteurl', function( $value ) { // Edit the port to your needs $port = 8080; // Network step 2 if( is_multisite() || network_domain_check() ) return $value; // Network step 1 static $count = 0; if( 0 === $count++ ) $value = str_replace( ':' . $port, ':80', $value ); return $value; } ); return $value; } ); } ); ``` I just tested this on my dev install, but this might need more checks of course ;-)
212,989
<p>I develop my custom widget with setting where I can set up custom color for the widget. I use this code to initialize <code>wpColorPicker</code> instead of default text input in <code>form()</code> method of Widget class:</p> <pre><code>jQuery(document).ready(function($){ $('#&lt;?php echo $this-&gt;get_field_id( 'bg_color_1' ); ?&gt;').wpColorPicker(); }); </code></pre> <p>All works great but if you are trying change the color in Theme Customizer after changing value nothing happens: the Save button still not active and site page not refreshing with the new color.</p> <p>Previously trying for triggering <code>change</code> event, but not working:</p> <pre><code>$('#&lt;?php echo $this-&gt;get_field_id( 'bg_color_1' ); ?&gt;').wpColorPicker({ change: function(event, ui) { $('#&lt;?php echo $this-&gt;get_field_id( 'bg_color_1' ); ?&gt;').change(); } }); </code></pre> <p>How to reload the page preview (trigger the event when value inside my input have been changed)?</p>
[ { "answer_id": 212988, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>You can't use port 8080. I have no idea why as that is a fairly common port for a web server. However, <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L121\" rel=\"noreferrer\">you can't</a>:</p>\n\n<pre><code>121 if ( ( false !== $has_ports &amp;&amp; ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) {\n122 echo '&lt;div class=\"error\"&gt;&lt;p&gt;&lt;strong&gt;' . __( 'ERROR:') . '&lt;/strong&gt; ' . __( 'You cannot install a network of sites with your server address.' ) . '&lt;/p&gt;&lt;/div&gt;';\n123 echo '&lt;p&gt;' . sprintf(\n124 /* translators: %s: port number */\n125 __( 'You cannot use port numbers such as %s.' ),\n126 '&lt;code&gt;' . $has_ports . '&lt;/code&gt;'\n127 ) . '&lt;/p&gt;';\n128 echo '&lt;a href=\"' . esc_url( admin_url() ) . '\"&gt;' . __( 'Return to Dashboard' ) . '&lt;/a&gt;';\n129 echo '&lt;/div&gt;';\n130 include( ABSPATH . 'wp-admin/admin-footer.php' );\n131 die();\n132 }\n</code></pre>\n\n<p>Notice <code>! in_array( $has_ports, array( ':80', ':443' ) )</code>. Those ports are hard-coded. There are no filters you can use to alter them, not even in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L80\" rel=\"noreferrer\"><code>get_clean_basename()</code></a> (and I am afraid to guess at what horrors you'd create if you could alter what that returns). </p>\n\n<p>Alter your server to use port 443 or port 80 instead. </p>\n" }, { "answer_id": 213001, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p><strong>Warning: This is just a test for dev installs and not production sites</strong></p>\n\n<p>I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than <code>:80</code> and <code>:443</code>, e.g. <code>:8080</code>. </p>\n\n<p>I only found this <a href=\"http://benohead.com/wordpress-running-multisite-different-port/\" rel=\"noreferrer\">blog post</a> by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions.</p>\n\n<p>Here's a <em>must-use</em> plugin <code>/wp-content/mu-plugins/wpse-ms-on-different-port.php</code> where we try to avoid core modifications:</p>\n\n<pre><code>&lt;?php \n/**\n * Test for multisite support on a different port than :80 and :443 (e.g. :8080)\n *\n * Here we assume that the 'siteurl' and 'home' options contain the :8080 port\n *\n * WARNING: Not suited for production sites!\n */\n\n/**\n * Get around the problem with wpmu_create_blog() where sanitize_user() \n * strips out the semicolon (:) in the $domain string\n * This means created sites with hostnames of \n * e.g. example.tld8080 instead of example.tld:8080\n */\nadd_filter( 'sanitize_user', function( $username, $raw_username, $strict )\n{\n // Edit the port to your needs\n $port = 8080;\n\n if( $strict // wpmu_create_blog uses strict mode\n &amp;&amp; is_multisite() // multisite check\n &amp;&amp; $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port \n &amp;&amp; false === strpos( $username, ':' . $port ) // stripped domain is without correct port\n )\n $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080\n\n return $username;\n}, 1, 3 );\n\n/**\n * Temporarly change the port (e.g. :8080 ) to :80 to get around \n * the core restriction in the network.php page.\n */\nadd_action( 'load-network.php', function()\n{\n add_filter( 'option_active_plugins', function( $value )\n {\n add_filter( 'option_siteurl', function( $value )\n {\n // Edit the port to your needs\n $port = 8080;\n\n // Network step 2\n if( is_multisite() || network_domain_check() )\n return $value;\n\n // Network step 1\n static $count = 0;\n if( 0 === $count++ )\n $value = str_replace( ':' . $port, ':80', $value );\n return $value;\n } );\n return $value;\n } );\n} );\n</code></pre>\n\n<p>I just tested this on my dev install, but this might need more checks of course ;-)</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/46077/" ]
I develop my custom widget with setting where I can set up custom color for the widget. I use this code to initialize `wpColorPicker` instead of default text input in `form()` method of Widget class: ``` jQuery(document).ready(function($){ $('#<?php echo $this->get_field_id( 'bg_color_1' ); ?>').wpColorPicker(); }); ``` All works great but if you are trying change the color in Theme Customizer after changing value nothing happens: the Save button still not active and site page not refreshing with the new color. Previously trying for triggering `change` event, but not working: ``` $('#<?php echo $this->get_field_id( 'bg_color_1' ); ?>').wpColorPicker({ change: function(event, ui) { $('#<?php echo $this->get_field_id( 'bg_color_1' ); ?>').change(); } }); ``` How to reload the page preview (trigger the event when value inside my input have been changed)?
**Warning: This is just a test for dev installs and not production sites** I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than `:80` and `:443`, e.g. `:8080`. I only found this [blog post](http://benohead.com/wordpress-running-multisite-different-port/) by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions. Here's a *must-use* plugin `/wp-content/mu-plugins/wpse-ms-on-different-port.php` where we try to avoid core modifications: ``` <?php /** * Test for multisite support on a different port than :80 and :443 (e.g. :8080) * * Here we assume that the 'siteurl' and 'home' options contain the :8080 port * * WARNING: Not suited for production sites! */ /** * Get around the problem with wpmu_create_blog() where sanitize_user() * strips out the semicolon (:) in the $domain string * This means created sites with hostnames of * e.g. example.tld8080 instead of example.tld:8080 */ add_filter( 'sanitize_user', function( $username, $raw_username, $strict ) { // Edit the port to your needs $port = 8080; if( $strict // wpmu_create_blog uses strict mode && is_multisite() // multisite check && $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port && false === strpos( $username, ':' . $port ) // stripped domain is without correct port ) $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080 return $username; }, 1, 3 ); /** * Temporarly change the port (e.g. :8080 ) to :80 to get around * the core restriction in the network.php page. */ add_action( 'load-network.php', function() { add_filter( 'option_active_plugins', function( $value ) { add_filter( 'option_siteurl', function( $value ) { // Edit the port to your needs $port = 8080; // Network step 2 if( is_multisite() || network_domain_check() ) return $value; // Network step 1 static $count = 0; if( 0 === $count++ ) $value = str_replace( ':' . $port, ':80', $value ); return $value; } ); return $value; } ); } ); ``` I just tested this on my dev install, but this might need more checks of course ;-)
212,996
<p>On attachment page I would like to display all images belonging to the parent post, so there should a thumbnail gallery. Using... </p> <pre><code>$parent = get_post_field( 'post_parent', get_the_ID() ); $gallery = get_post_gallery( $parent, false ); </code></pre> <p>...gives this which is kinda weird to use. Why are ids seperatated from src? How do I even get ID of that thumbnail to get the permalink? Even If I get this working by some complicated core, it feels dirty. Isn't there a better solution?</p> <pre><code>array (size=3) 'columns' =&gt; string '4' (length=1) 'ids' =&gt; string '8844,8853,8498,8845,8846,8847,8848,8849,8852,8854,8843,8851,8855,8499,9672,9673' (length=79) 'src' =&gt; array (size=16) 0 =&gt; string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-251-200x200.jpg' (length=80) 1 =&gt; string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-33-200x200.jpg' (length=79) 2 =&gt; string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-13-200x200.jpg' (length=79) 3 =&gt; string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-26-200x200.jpg' (length=79) </code></pre> <p>I need something like this</p> <pre><code>&lt;?php foreach($gallery as $img) : ?&gt; &lt;a href="&lt;?php echo get_permalink($img-&gt;ID); ?&gt;"&gt; &lt;img src="&lt;?php echo $img-&gt;src ?&gt;" alt=" -&lt;?php echo $img-&gt;title " /&gt; &lt;/a&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>There is also <code>get_post_gallery_images()</code> but it returns only thumbnail urls</p>
[ { "answer_id": 212988, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": false, "text": "<p>You can't use port 8080. I have no idea why as that is a fairly common port for a web server. However, <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L121\" rel=\"noreferrer\">you can't</a>:</p>\n\n<pre><code>121 if ( ( false !== $has_ports &amp;&amp; ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) {\n122 echo '&lt;div class=\"error\"&gt;&lt;p&gt;&lt;strong&gt;' . __( 'ERROR:') . '&lt;/strong&gt; ' . __( 'You cannot install a network of sites with your server address.' ) . '&lt;/p&gt;&lt;/div&gt;';\n123 echo '&lt;p&gt;' . sprintf(\n124 /* translators: %s: port number */\n125 __( 'You cannot use port numbers such as %s.' ),\n126 '&lt;code&gt;' . $has_ports . '&lt;/code&gt;'\n127 ) . '&lt;/p&gt;';\n128 echo '&lt;a href=\"' . esc_url( admin_url() ) . '\"&gt;' . __( 'Return to Dashboard' ) . '&lt;/a&gt;';\n129 echo '&lt;/div&gt;';\n130 include( ABSPATH . 'wp-admin/admin-footer.php' );\n131 die();\n132 }\n</code></pre>\n\n<p>Notice <code>! in_array( $has_ports, array( ':80', ':443' ) )</code>. Those ports are hard-coded. There are no filters you can use to alter them, not even in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/includes/network.php#L80\" rel=\"noreferrer\"><code>get_clean_basename()</code></a> (and I am afraid to guess at what horrors you'd create if you could alter what that returns). </p>\n\n<p>Alter your server to use port 443 or port 80 instead. </p>\n" }, { "answer_id": 213001, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p><strong>Warning: This is just a test for dev installs and not production sites</strong></p>\n\n<p>I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than <code>:80</code> and <code>:443</code>, e.g. <code>:8080</code>. </p>\n\n<p>I only found this <a href=\"http://benohead.com/wordpress-running-multisite-different-port/\" rel=\"noreferrer\">blog post</a> by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions.</p>\n\n<p>Here's a <em>must-use</em> plugin <code>/wp-content/mu-plugins/wpse-ms-on-different-port.php</code> where we try to avoid core modifications:</p>\n\n<pre><code>&lt;?php \n/**\n * Test for multisite support on a different port than :80 and :443 (e.g. :8080)\n *\n * Here we assume that the 'siteurl' and 'home' options contain the :8080 port\n *\n * WARNING: Not suited for production sites!\n */\n\n/**\n * Get around the problem with wpmu_create_blog() where sanitize_user() \n * strips out the semicolon (:) in the $domain string\n * This means created sites with hostnames of \n * e.g. example.tld8080 instead of example.tld:8080\n */\nadd_filter( 'sanitize_user', function( $username, $raw_username, $strict )\n{\n // Edit the port to your needs\n $port = 8080;\n\n if( $strict // wpmu_create_blog uses strict mode\n &amp;&amp; is_multisite() // multisite check\n &amp;&amp; $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port \n &amp;&amp; false === strpos( $username, ':' . $port ) // stripped domain is without correct port\n )\n $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080\n\n return $username;\n}, 1, 3 );\n\n/**\n * Temporarly change the port (e.g. :8080 ) to :80 to get around \n * the core restriction in the network.php page.\n */\nadd_action( 'load-network.php', function()\n{\n add_filter( 'option_active_plugins', function( $value )\n {\n add_filter( 'option_siteurl', function( $value )\n {\n // Edit the port to your needs\n $port = 8080;\n\n // Network step 2\n if( is_multisite() || network_domain_check() )\n return $value;\n\n // Network step 1\n static $count = 0;\n if( 0 === $count++ )\n $value = str_replace( ':' . $port, ':80', $value );\n return $value;\n } );\n return $value;\n } );\n} );\n</code></pre>\n\n<p>I just tested this on my dev install, but this might need more checks of course ;-)</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/212996", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85935/" ]
On attachment page I would like to display all images belonging to the parent post, so there should a thumbnail gallery. Using... ``` $parent = get_post_field( 'post_parent', get_the_ID() ); $gallery = get_post_gallery( $parent, false ); ``` ...gives this which is kinda weird to use. Why are ids seperatated from src? How do I even get ID of that thumbnail to get the permalink? Even If I get this working by some complicated core, it feels dirty. Isn't there a better solution? ``` array (size=3) 'columns' => string '4' (length=1) 'ids' => string '8844,8853,8498,8845,8846,8847,8848,8849,8852,8854,8843,8851,8855,8499,9672,9673' (length=79) 'src' => array (size=16) 0 => string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-251-200x200.jpg' (length=80) 1 => string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-33-200x200.jpg' (length=79) 2 => string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-13-200x200.jpg' (length=79) 3 => string 'http://localhost/biljke/wp-content/uploads/2015/05/uljana-repica-26-200x200.jpg' (length=79) ``` I need something like this ``` <?php foreach($gallery as $img) : ?> <a href="<?php echo get_permalink($img->ID); ?>"> <img src="<?php echo $img->src ?>" alt=" -<?php echo $img->title " /> </a> <?php endforeach; ?> ``` There is also `get_post_gallery_images()` but it returns only thumbnail urls
**Warning: This is just a test for dev installs and not production sites** I was curious to see if there was a workaround, for those who want to develope multisites on their dev installs but on different ports than `:80` and `:443`, e.g. `:8080`. I only found this [blog post](http://benohead.com/wordpress-running-multisite-different-port/) by Henri Benoit. There he gives examples how to modify the 3.9.1 core, to get around the core restrictions. Here's a *must-use* plugin `/wp-content/mu-plugins/wpse-ms-on-different-port.php` where we try to avoid core modifications: ``` <?php /** * Test for multisite support on a different port than :80 and :443 (e.g. :8080) * * Here we assume that the 'siteurl' and 'home' options contain the :8080 port * * WARNING: Not suited for production sites! */ /** * Get around the problem with wpmu_create_blog() where sanitize_user() * strips out the semicolon (:) in the $domain string * This means created sites with hostnames of * e.g. example.tld8080 instead of example.tld:8080 */ add_filter( 'sanitize_user', function( $username, $raw_username, $strict ) { // Edit the port to your needs $port = 8080; if( $strict // wpmu_create_blog uses strict mode && is_multisite() // multisite check && $port == parse_url( $raw_username, PHP_URL_PORT ) // raw domain has port && false === strpos( $username, ':' . $port ) // stripped domain is without correct port ) $username = str_replace( $port, ':' . $port, $username ); // replace e.g. example.tld8080 to example.tld:8080 return $username; }, 1, 3 ); /** * Temporarly change the port (e.g. :8080 ) to :80 to get around * the core restriction in the network.php page. */ add_action( 'load-network.php', function() { add_filter( 'option_active_plugins', function( $value ) { add_filter( 'option_siteurl', function( $value ) { // Edit the port to your needs $port = 8080; // Network step 2 if( is_multisite() || network_domain_check() ) return $value; // Network step 1 static $count = 0; if( 0 === $count++ ) $value = str_replace( ':' . $port, ':80', $value ); return $value; } ); return $value; } ); } ); ``` I just tested this on my dev install, but this might need more checks of course ;-)
213,006
<p>I am trying to use the WordPress Rest Api with authentication to get more data from the API. I have installed the Oauth plugin, rest-api plugin, and gotten API credentials from WP-CLI.</p> <p>I have figured out how to access data without authorization. This works:</p> <pre><code>// set our end point $domain = "http://localhost/wp-api"; $endpoint = $domain."/wp-json/wp/v2/posts/"; $curl = curl_init($endpoint); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_URL =&gt; $endpoint, ]); $response = curl_exec($curl); $decoderesponse = json_decode($response, true); ?&gt; &lt;pre&gt; &lt;?php print_r($decoderesponse); ?&gt; &lt;/pre&gt; </code></pre> <p>But I can't figure out how to authenticate with credentials. Here is my attempt. I am not sure if "key" and "secret" are correct.</p> <pre><code>// Oauth credentials from wp-cli $ID = "4"; $Key = "l8XZD9lX89kb"; $Secret = "UUbcc8vjUkGjuDyvK1gRTts9sZp2N8k9tbIQaGjZ6SNOyR4d"; // set our end point $domain = "http://localhost/wp-api"; $endpoint = $domain."/wp-json/wp/v2/posts/1/revisions"; $headers[] = "key=$Key"; $headers[] = "secret=$Secret"; $curl = curl_init($endpoint); curl_setopt_array($curl, [ CURLOPT_HTTPHEADER =&gt; $headers, CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_URL =&gt; $endpoint, ]); $response = curl_exec($curl); $decoderesponse = json_decode($response, true); ?&gt; &lt;pre&gt; &lt;?php print_r($decoderesponse); ?&gt; &lt;/pre&gt; </code></pre> <p>The output is</p> <pre><code>Array ( [code] =&gt; rest_cannot_read [message] =&gt; Sorry, you cannot view revisions of this post. [data] =&gt; Array ( [status] =&gt; 401 ) ) </code></pre> <p>How can I get this to work? Thank you.</p>
[ { "answer_id": 223789, "author": "juz", "author_id": 68207, "author_profile": "https://wordpress.stackexchange.com/users/68207", "pm_score": 0, "selected": false, "text": "<p>Update: From what I've read, you need to do multiple curls to get the access_token, which you then use to do the query</p>\n\n<ul>\n<li>Temporary Credentials Acquisition: The client gets a set of temporary credentials from the server. </li>\n<li>Authorization: The user \"authorizes\" the request token to access their account. </li>\n<li>Token Exchange: The client exchanges the short-lived temporary credentials for a long-lived token.</li>\n</ul>\n\n<p><a href=\"http://oauth1.wp-api.org/docs/basics/Auth-Flow.html\" rel=\"nofollow\">oauth1 server flow</a></p>\n" }, { "answer_id": 239873, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 4, "selected": false, "text": "<p>Let's go step by step here. Looks like you're trying to use OAuth just for authentication, <strong><em>but before you can do so you need to get the Access Token</em></strong> which will be used to authenticate when you make your API calls. </p>\n\n<p>Because this is using OAuth version 1, in order to obtain the <strong>Access Token</strong> you must do the following:</p>\n\n<ol>\n<li>First, setup an application, make a call to the site to obtain the <strong>Request Token</strong> (temp credentials) using the Client ID and Secret for the application</li>\n<li>Second, make a call to the site to Authorize the application with the <strong>Request Token</strong> from first step (user-facing, see below).</li>\n<li>Third, after authorization has been completed, you then make a call to the site to obtain the <strong>Access Token</strong> (now that application has been authorized)</li>\n</ol>\n\n<p>I recommend using Postman for the first few steps, because they only need to be completed once. Postman will also handle generating the <code>timestamp</code>, <code>nonce</code> and <code>oauth signature</code>, so if you're not using an OAuth library, then you should absolutely use Postman. Once you have your <strong>Access Token</strong> you can make the calls via CURL without any libraries.</p>\n\n<p><a href=\"https://www.getpostman.com/\" rel=\"noreferrer\">https://www.getpostman.com/</a></p>\n\n<h2>First Step (setup application)</h2>\n\n<p>Install WP OAuth 1 plugin, activate, then goto menu item under <strong><em>Users > Applications</em></strong>. Add new application, fill out name and description. For callback either the URL to redirect the user to (after authorizing), or <code>oop</code> for Out-of-Band flow which will redirect to an internal page which displays the verifier token (instead of redirecting).</p>\n\n<p><a href=\"https://github.com/WP-API/OAuth1/blob/master/docs/basics/Registering.md\" rel=\"noreferrer\">https://github.com/WP-API/OAuth1/blob/master/docs/basics/Registering.md</a></p>\n\n<p>To proceed to the second step a call needs to be made to your site, using the <strong>Client ID</strong> and <strong>Client Secret</strong> from the created application, to get temporary credentials (Request Token).</p>\n\n<p>Open up Postman, create a new call to <code>http://website.com/oauth1/request</code>, click on the Authorization tab, select OAuth 1.0 from dropdown, enter in the Client Key, Client Secret, set signature method to <code>HMAC-SHA1</code>, enable add params to header, <strong>encode oauth signature</strong>, then click <strong>Update Request</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/DjI4J.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DjI4J.png\" alt=\"Postman OAuth1 Request\"></a></p>\n\n<p>Postman will auto generate the signature, nonce, and timestamp for you, and add them to the header (you can view under Headers tab).</p>\n\n<p>Click Send and you should get a response that includes <code>oauth_token</code> and <code>oauth_token_secret</code>:\n<a href=\"https://i.stack.imgur.com/Paf61.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Paf61.png\" alt=\"Postman OAuth1 Request Response\"></a></p>\n\n<p>These values will be used in the next step to authorize the application under your WordPress user account.</p>\n\n<h2>Second Step (authorize application)</h2>\n\n<p>Authorization step only needs to be completed once, this step is user-facing, and the one that everyone is familiar with. This step is required because you're using OAuth1, and the application needs to be associated with a WordPress user account. Think of when a site allows you to login with Facebook ... they direct you to Facebook where you login and click \"Authorize\" ... this needs to be done, just through your WordPress site.</p>\n\n<p>I recommend using your Web Browser for this step, as you can easily just set the variables in URL, and this provides the \"Authorize\" page to authorize the application.</p>\n\n<p>Open your web browser and type in the URL to your site, like this:\n<code>http://website.com/oauth1/authorize</code></p>\n\n<p>Now add on to this URL, <code>oauth_consumer_key</code> (Client ID), <code>oauth_token</code> and <code>oauth_token_secret</code> (from previous step). In my example this is the full URL:</p>\n\n<pre><code>http://website.com/oauth1/authorize?oauth_consumer_key=TUPFNj1ZTd8u&amp;oauth_token=J98cN81p01aqSdFd9rjkHZWI&amp;oauth_token_secret=RkrMhw8YzXQljyh99BrNHmP7phryUvZgVObpmJtos3QExG1O\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/p752F.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/p752F.png\" alt=\"OAuth1 Authorize Application\"></a></p>\n\n<p>Once you click on Authorize, you will get another screen with the verification token. In my example this is the verification token returned <code>E0JnxjjYxc32fMr2AF0uWsZm</code></p>\n\n<h2>Third Step (get access token)</h2>\n\n<p>Now that we have authorized the application, we need to make one last call to get the Authorization Token which will be used to make all your API calls. Just like the first step i'm going to use Postman (because signature is required to be HMAC-SHA1), and it makes it 100x easier to complete these steps.</p>\n\n<p>Open up Postman again, and change the URL to <code>http://website.com/oauth1/access</code></p>\n\n<p>Make sure to add the Token, and Token Secret (values from the first step), then click on <strong>Params</strong> to show the boxes below the URL. On the left type in <strong>oauth_verifier</strong> and on the right, enter the code from the second step, the <strong>Verification Token</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/6WoIt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6WoIt.png\" alt=\"Postman OAuth1 Access Step\"></a></p>\n\n<p>Make sure to click Update Request, then click Send, and you should get a response back with <code>oauth_token</code> and <code>oauth_token_secret</code> ... this is what you need to make your API calls with! Discard the original ones from step 1, save these ones in your code or somewhere else safe.</p>\n\n<p><a href=\"https://i.stack.imgur.com/k1dRI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/k1dRI.png\" alt=\"Postman OAuth1 Access Response\"></a></p>\n\n<p>You can then make an API call to your site, setting the headers with the returned token, and token secret.</p>\n\n<p>You can pass this multiple ways, via Authorization header, in GET parameters, or POST (if encoded as application/x-www-form-urlencoded). Keep in mind you MUST pass the signature, timestamp, and nonce. I didn't realize how long this reply would take me, so i'll update this tomorrow with example on doing that with your code.</p>\n\n<p>I strongly recommend installing Rest API log so you can view log of API calls, and see what was sent, returned, etc. This will help with debugging tremendously.</p>\n\n<p><a href=\"https://github.com/petenelson/wp-rest-api-log\" rel=\"noreferrer\">https://github.com/petenelson/wp-rest-api-log</a></p>\n" }, { "answer_id": 239967, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>Adding this as another answer to give you help to figure out how to do this. Basically as mentioned in my comments if you're going to use OAuth1 you MUST associate it with a user account, no way around that.</p>\n\n<p>First you need to use CURL to login to the site with a username password for WordPress, store the cookie so you can use it in your CURL call to OAuth (make sure to update your CURL call to include the cookie):</p>\n\n<p><a href=\"https://stackoverflow.com/questions/724107/wordpress-autologin-using-curl-or-fsockopen-in-php\">https://stackoverflow.com/questions/724107/wordpress-autologin-using-curl-or-fsockopen-in-php</a></p>\n\n<p>Then make the call to OAuth using CURL with the Client ID and Client Secret, to obtain the temporary oauth token and secret (Request Token)</p>\n\n<p>To make this call (and the call to obtain access token), you need to setup your CURL call correctly. See end of this answer for code and references.</p>\n\n<p>After you obtain the temporary oauth token and secret (Request Token), make a CURL POST call to this URL of your site:</p>\n\n<p><code>http://website.com/oauth1/authorize</code></p>\n\n<p>You will then need to pull all the values from the returned HTML for the authorization page, and then submit your own POST to the form action URL.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/35363815/how-to-get-a-value-input-from-html-returned-of-curl\">https://stackoverflow.com/questions/35363815/how-to-get-a-value-input-from-html-returned-of-curl</a></p>\n\n<p>Specifically these need to be included in your POST data to complete the \"authorization\" POSTing to <code>http://domain.com/wp-login.php?action=oauth1_authorize</code></p>\n\n<ul>\n<li><p><code>_wpnonce</code> -- This is the nonce value for the form to be submitted,\nthis MUST be pulled from the HTML input and submitted with your POST</p>\n\n<p><code>consumer</code> -- This is a hidden input in the HTML (this is reference to a Post ID so you must pull it from the HTML input</p>\n\n<p><code>oauth_token</code> -- This is a hidden input in the HTML (but you should\nalso already have this)</p>\n\n<p><code>wp-submit</code> -- This needs to be set to the value <code>authorize</code></p></li>\n</ul>\n\n<p>Here's example HTML generated for the authentication page:</p>\n\n<pre><code>&lt;form name=\"oauth1_authorize_form\" id=\"oauth1_authorize_form\" action=\"http://website.com/wp-login.php?action=oauth1_authorize\" method=\"post\"&gt;\n\n &lt;h2 class=\"login-title\"&gt;Connect My Auth&lt;/h2&gt;\n\n &lt;div class=\"login-info\"&gt;\n &lt;p&gt;Howdy &lt;strong&gt;admin&lt;/strong&gt;,&lt;br/&gt; \"My OAuth Demo\" would like to connect to Example Site.&lt;/p&gt;\n\n &lt;/div&gt;\n\n &lt;input type=\"hidden\" name=\"consumer\" value=\"5428\" /&gt;&lt;input type=\"hidden\" name=\"oauth_token\" value=\"i1scugFXyPENniCP4kABKtGb\" /&gt;&lt;input type=\"hidden\" id=\"_wpnonce\" name=\"_wpnonce\" value=\"ca9b267b4f\" /&gt;&lt;input type=\"hidden\" name=\"_wp_http_referer\" value=\"/wp-login.php?action=oauth1_authorize&amp;amp;oauth_consumer_key=TUPFNj1ZTd8u&amp;amp;oauth_token=i1scugFXyPENniCP4kABKtGb&amp;amp;oauth_token_secret=gzqW47pHG0tilFm9WT7lUgLoqN2YqS6tFFjUEiQoMgcmG2ic\" /&gt; &lt;p class=\"submit\"&gt;\n &lt;button type=\"submit\" name=\"wp-submit\" value=\"authorize\" class=\"button button-primary button-large\"&gt;Authorize&lt;/button&gt;\n &lt;button type=\"submit\" name=\"wp-submit\" value=\"cancel\" class=\"button button-large\"&gt;Cancel&lt;/button&gt;\n &lt;/p&gt;\n\n&lt;/form&gt;\n</code></pre>\n\n<p>After you make the POST with all those values/data, this is the HTML that will be returned with the authorization code (so you need to pull the value from inside the <code>&lt;code&gt;</code> block:</p>\n\n<pre><code>&lt;div id=\"login\"&gt;\n &lt;h1&gt;&lt;a href=\"https://wordpress.org/\" title=\"Powered by WordPress\" tabindex=\"-1\"&gt;Example Site&lt;/a&gt;&lt;/h1&gt;\n &lt;p&gt;Your verification token is &lt;code&gt;yGOYFpyawe8iZmmcizqVIw3f&lt;/code&gt;&lt;/p&gt; &lt;p id=\"backtoblog\"&gt;&lt;a href=\"http://website.com/\"&gt;&amp;larr; Back to Example Site&lt;/a&gt;&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Once you have the verification token, you can then make a call to <code>/oauth1/access</code> using the verification token, oauth token, and oauth token secret. The verification token needs to be put in the POST data as <code>oauth_verifier</code></p>\n\n<p>That will return your new and permanent Access Token, and VOILA!</p>\n\n<h2>Example CURL Code</h2>\n\n<p>Below is example code to make the CURL call, the most important part being how the <code>oauth_signature</code> is generated:</p>\n\n<p><a href=\"https://oauth1.wp-api.org/docs/basics/Signing.html\" rel=\"nofollow noreferrer\">https://oauth1.wp-api.org/docs/basics/Signing.html</a></p>\n\n<pre><code>function buildBaseString($baseURI, $method, $params){\n $r = array();\n ksort($params);\n foreach($params as $key=&gt;$value){\n $r[] = \"$key=\" . rawurlencode($value);\n }\n\n return $method.\"&amp;\" . rawurlencode($baseURI) . '&amp;' . rawurlencode(implode('&amp;', $r));\n}\n\nfunction buildAuthorizationHeader($oauth){\n $r = 'Authorization: OAuth ';\n $values = array();\n foreach($oauth as $key=&gt;$value)\n $values[] = \"$key=\\\"\" . rawurlencode($value) . \"\\\"\";\n\n $r .= implode(', ', $values);\n return $r;\n}\n\n// Add request, authorize, etc to end of URL based on what call you're making\n$url = \"http://domain.com/oauth/\";\n\n$consumer_key = \"CLIENT ID HERE\";\n$consumer_secret = \"CLIENT SECRET HERE\";\n\n$oauth = array( 'oauth_consumer_key' =&gt; $consumer_key,\n 'oauth_nonce' =&gt; time(),\n 'oauth_signature_method' =&gt; 'HMAC-SHA1',\n 'oauth_callback' =&gt; 'oob',\n 'oauth_timestamp' =&gt; time(),\n 'oauth_version' =&gt; '1.0');\n\n$base_info = buildBaseString($url, 'GET', $oauth);\n$composite_key = rawurlencode($consumer_secret) . '&amp;' . rawurlencode($oauth_access_token_secret);\n$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));\n$oauth['oauth_signature'] = $oauth_signature;\n\n\n$header = array(buildAuthorizationHeader($oauth), 'Expect:');\n$options = array( CURLOPT_HTTPHEADER =&gt; $header,\n CURLOPT_HEADER =&gt; false,\n CURLOPT_URL =&gt; $url,\n CURLOPT_RETURNTRANSFER =&gt; true,\n CURLOPT_SSL_VERIFYPEER =&gt; false);\n\n$feed = curl_init();\ncurl_setopt_array($feed, $options);\n$json = curl_exec($feed);\ncurl_close($feed);\n\n$return_data = json_decode($json);\n\nprint_r($return_data);\n</code></pre>\n\n<p>This site tells exactly how to encode the OAuth signature, and how to send using CURL (i recommend reading the entire page):\n<a href=\"https://hannah.wf/twitter-oauth-simple-curl-requests-for-your-own-data/\" rel=\"nofollow noreferrer\">https://hannah.wf/twitter-oauth-simple-curl-requests-for-your-own-data/</a></p>\n\n<p>More resource on generating OAuth1 signature:\n<a href=\"https://stackoverflow.com/questions/24613277/oauth-signature-generation-using-hmac-sha1\">https://stackoverflow.com/questions/24613277/oauth-signature-generation-using-hmac-sha1</a></p>\n\n<p>Other Resources:\n<a href=\"http://collaboradev.com/2011/04/01/twitter-oauth-php-tutorial/\" rel=\"nofollow noreferrer\">http://collaboradev.com/2011/04/01/twitter-oauth-php-tutorial/</a></p>\n" }, { "answer_id": 239977, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>I know I'm coming into this a bit late, but can you use wp_remote_get and _post?</p>\n\n<p>I'm pulling and posting content with my wordpress install using them:</p>\n\n<p>THis is the general idea from the wordpress codex: </p>\n\n<pre><code>$response = wp_remote_post( $url, array(\n 'body' =&gt; $data,\n 'httpversion' =&gt; '1.0',\n 'sslverify' =&gt; false,\n 'headers' =&gt; array(\n 'Authorization' =&gt; 'Basic ' . base64_encode( $username . ':' . $password ),\n ),\n) );\n</code></pre>\n\n<p>Here is a more specific example:</p>\n\n<pre><code>$url='http://WWW.EXAMPLE HERE.';\n$response = wp_remote_post( $url, array(\n 'method' =&gt; 'POST',\n 'timeout' =&gt; 45,\n 'redirection' =&gt; 5,\n 'httpversion' =&gt; '1.0', //needed to get a response\n 'blocking' =&gt; true,\n 'headers' =&gt; array('Authorization' =&gt; 'Basic ' . base64_encode( 'MY TOKENID' . ':' . '' )),\n 'body' =&gt; $body // in array\n 'cookies' =&gt; array()\n )\n);\n\nif ( is_wp_error( $response ) ) {\n $error_message = $response-&gt;get_error_message();\n echo \"Something went wrong: $error_message\";\n} else {\n // echo 'Response:&lt;pre&gt;';\n // print_r( $response );\n // echo '&lt;/pre&gt;'; \n$responseBody = json_decode($response['body'],true);\necho $responseBody['message'];\n\n }\n }\n}\n</code></pre>\n\n<p>The trick is encoding the username and pw. Now often time depending on the API username and pw will either be blank or will be your tokens.</p>\n\n<p>so for instance in my specific example above, the headers were</p>\n\n<pre><code>'headers' =&gt; array('Authorization' =&gt; 'Basic ' . base64_encode( 'MYTOKENID' . ':' . '' ))\n</code></pre>\n\n<p>and i left pw blank. That's up to the API system you're using though.</p>\n" } ]
2015/12/27
[ "https://wordpress.stackexchange.com/questions/213006", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49017/" ]
I am trying to use the WordPress Rest Api with authentication to get more data from the API. I have installed the Oauth plugin, rest-api plugin, and gotten API credentials from WP-CLI. I have figured out how to access data without authorization. This works: ``` // set our end point $domain = "http://localhost/wp-api"; $endpoint = $domain."/wp-json/wp/v2/posts/"; $curl = curl_init($endpoint); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $endpoint, ]); $response = curl_exec($curl); $decoderesponse = json_decode($response, true); ?> <pre> <?php print_r($decoderesponse); ?> </pre> ``` But I can't figure out how to authenticate with credentials. Here is my attempt. I am not sure if "key" and "secret" are correct. ``` // Oauth credentials from wp-cli $ID = "4"; $Key = "l8XZD9lX89kb"; $Secret = "UUbcc8vjUkGjuDyvK1gRTts9sZp2N8k9tbIQaGjZ6SNOyR4d"; // set our end point $domain = "http://localhost/wp-api"; $endpoint = $domain."/wp-json/wp/v2/posts/1/revisions"; $headers[] = "key=$Key"; $headers[] = "secret=$Secret"; $curl = curl_init($endpoint); curl_setopt_array($curl, [ CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $endpoint, ]); $response = curl_exec($curl); $decoderesponse = json_decode($response, true); ?> <pre> <?php print_r($decoderesponse); ?> </pre> ``` The output is ``` Array ( [code] => rest_cannot_read [message] => Sorry, you cannot view revisions of this post. [data] => Array ( [status] => 401 ) ) ``` How can I get this to work? Thank you.
Let's go step by step here. Looks like you're trying to use OAuth just for authentication, ***but before you can do so you need to get the Access Token*** which will be used to authenticate when you make your API calls. Because this is using OAuth version 1, in order to obtain the **Access Token** you must do the following: 1. First, setup an application, make a call to the site to obtain the **Request Token** (temp credentials) using the Client ID and Secret for the application 2. Second, make a call to the site to Authorize the application with the **Request Token** from first step (user-facing, see below). 3. Third, after authorization has been completed, you then make a call to the site to obtain the **Access Token** (now that application has been authorized) I recommend using Postman for the first few steps, because they only need to be completed once. Postman will also handle generating the `timestamp`, `nonce` and `oauth signature`, so if you're not using an OAuth library, then you should absolutely use Postman. Once you have your **Access Token** you can make the calls via CURL without any libraries. <https://www.getpostman.com/> First Step (setup application) ------------------------------ Install WP OAuth 1 plugin, activate, then goto menu item under ***Users > Applications***. Add new application, fill out name and description. For callback either the URL to redirect the user to (after authorizing), or `oop` for Out-of-Band flow which will redirect to an internal page which displays the verifier token (instead of redirecting). <https://github.com/WP-API/OAuth1/blob/master/docs/basics/Registering.md> To proceed to the second step a call needs to be made to your site, using the **Client ID** and **Client Secret** from the created application, to get temporary credentials (Request Token). Open up Postman, create a new call to `http://website.com/oauth1/request`, click on the Authorization tab, select OAuth 1.0 from dropdown, enter in the Client Key, Client Secret, set signature method to `HMAC-SHA1`, enable add params to header, **encode oauth signature**, then click **Update Request** [![Postman OAuth1 Request](https://i.stack.imgur.com/DjI4J.png)](https://i.stack.imgur.com/DjI4J.png) Postman will auto generate the signature, nonce, and timestamp for you, and add them to the header (you can view under Headers tab). Click Send and you should get a response that includes `oauth_token` and `oauth_token_secret`: [![Postman OAuth1 Request Response](https://i.stack.imgur.com/Paf61.png)](https://i.stack.imgur.com/Paf61.png) These values will be used in the next step to authorize the application under your WordPress user account. Second Step (authorize application) ----------------------------------- Authorization step only needs to be completed once, this step is user-facing, and the one that everyone is familiar with. This step is required because you're using OAuth1, and the application needs to be associated with a WordPress user account. Think of when a site allows you to login with Facebook ... they direct you to Facebook where you login and click "Authorize" ... this needs to be done, just through your WordPress site. I recommend using your Web Browser for this step, as you can easily just set the variables in URL, and this provides the "Authorize" page to authorize the application. Open your web browser and type in the URL to your site, like this: `http://website.com/oauth1/authorize` Now add on to this URL, `oauth_consumer_key` (Client ID), `oauth_token` and `oauth_token_secret` (from previous step). In my example this is the full URL: ``` http://website.com/oauth1/authorize?oauth_consumer_key=TUPFNj1ZTd8u&oauth_token=J98cN81p01aqSdFd9rjkHZWI&oauth_token_secret=RkrMhw8YzXQljyh99BrNHmP7phryUvZgVObpmJtos3QExG1O ``` [![OAuth1 Authorize Application](https://i.stack.imgur.com/p752F.png)](https://i.stack.imgur.com/p752F.png) Once you click on Authorize, you will get another screen with the verification token. In my example this is the verification token returned `E0JnxjjYxc32fMr2AF0uWsZm` Third Step (get access token) ----------------------------- Now that we have authorized the application, we need to make one last call to get the Authorization Token which will be used to make all your API calls. Just like the first step i'm going to use Postman (because signature is required to be HMAC-SHA1), and it makes it 100x easier to complete these steps. Open up Postman again, and change the URL to `http://website.com/oauth1/access` Make sure to add the Token, and Token Secret (values from the first step), then click on **Params** to show the boxes below the URL. On the left type in **oauth\_verifier** and on the right, enter the code from the second step, the **Verification Token** [![Postman OAuth1 Access Step](https://i.stack.imgur.com/6WoIt.png)](https://i.stack.imgur.com/6WoIt.png) Make sure to click Update Request, then click Send, and you should get a response back with `oauth_token` and `oauth_token_secret` ... this is what you need to make your API calls with! Discard the original ones from step 1, save these ones in your code or somewhere else safe. [![Postman OAuth1 Access Response](https://i.stack.imgur.com/k1dRI.png)](https://i.stack.imgur.com/k1dRI.png) You can then make an API call to your site, setting the headers with the returned token, and token secret. You can pass this multiple ways, via Authorization header, in GET parameters, or POST (if encoded as application/x-www-form-urlencoded). Keep in mind you MUST pass the signature, timestamp, and nonce. I didn't realize how long this reply would take me, so i'll update this tomorrow with example on doing that with your code. I strongly recommend installing Rest API log so you can view log of API calls, and see what was sent, returned, etc. This will help with debugging tremendously. <https://github.com/petenelson/wp-rest-api-log>
213,016
<p>I want to serve a specific Wordpress page for multiple urls. Basically I want to point all the urls in a specific format to a known page:</p> <pre><code>/some-prefix-* =&gt; /target-page </code></pre> <p>And accessing <code>/some-prefix-and-here-something</code> it should load <code>/target-page</code>.</p> <p>How to do this?</p> <p>Note I do <em>not</em> want to redirect the user but to be able to serve an existing page to multiple urls.</p> <p>The <code>.htaccess</code> looks like this:</p> <pre><code># BEGIN s2Member GZIP exclusions RewriteEngine On RewriteRule ^prefix-*$ some/path/to/directory-$1 [NC,L] &lt;IfModule rewrite_module&gt; RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} (^|\?|&amp;)s2member_file_download\=.+ [OR] RewriteCond %{QUERY_STRING} (^|\?|&amp;)no-gzip\=1 RewriteRule .* - [E=no-gzip:1] &lt;/IfModule&gt; # END s2Member GZIP exclusions # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress DirectoryIndex index.php index.html </code></pre> <p>I thought by adding <code>RewriteEngine On RewriteRule ^prefix-*$ some/path/to/directory-$1 [NC,L]</code> will serve <code>/prefix-*</code> from <code>some/path/to/directory-$1</code>. For example: when accessing <code>example.com/prefix-foo</code> should be the same with <code>example.com/some/path/to/directory-foo</code> (which resolves to <code>example.com/some/path/to/directory-foo/index.html</code>).</p> <p>Also, if there is already a Wordpress page with the name <code>prefix-bar</code>, <code>/prefix-bar</code> should <em>not</em> load <code>example.com/some/path/to/directory-bar/index.html</code>.</p>
[ { "answer_id": 213017, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Create a hook to init and wp_redirect when the current post's slug starts with your prefix.</p>\n\n<pre><code>function wp_init() {\n\n global $post;\n $slug = $post-&gt;post_name;\n $prefix = 'foobar';\n if (substr($slug, 0 strlen($prefix))==$prefix) {\n wp_redirect(123); // your page id\n }\n\n}\nadd_action('init', 'wp_init');\n</code></pre>\n" }, { "answer_id": 213322, "author": "Rahil Wazir", "author_id": 36349, "author_profile": "https://wordpress.stackexchange.com/users/36349", "pm_score": 5, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\"><code>template_include</code></a>, but before you hook to this filter you must do the following steps:</p>\n\n<ol>\n<li><p>Create page template. e.g: <code>page-target.php</code></p>\n\n<pre><code>&lt;?php\n/**\n * Template Name: Page Target\n */\n...\n</code></pre></li>\n<li><p>Manually query the contents of <code>target-page</code> on <code>page-target.php</code> template, because the global <code>$post</code> will be referencing to your <code>some-prefix-*</code> page.</p></li>\n<li>(Optional): Edit and apply page template <code>Page Target</code> to your <code>/target-page</code> from the Page Attributes</li>\n</ol>\n\n<p>Then add the following to your <code>functions.php</code> file</p>\n\n<pre><code>add_filter('template_include', function($template) {\n global $post;\n\n $prefix = 'some-prefix-'; // Your prefix\n $prefixExist = strpos($post-&gt;post_name, $prefix) !== false;\n\n if ($prefixExist) {\n return locate_template('page-target.php'); //Your template\n }\n\n return $template;\n});\n</code></pre>\n\n<p>Above filter will override the template with <code>page-target.php</code> if condition met, otherwise default</p>\n\n<h3>Edit:</h3>\n\n<p>I think I have found a better way to resolve this using <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\"><code>add_rewrite_rule</code></a></p>\n\n<pre><code>function custom_rewrite_basic() {\n $page_id = 123; //Your serve page id\n add_rewrite_rule('^some-prefix-.*', 'index.php?page_id=' . $page_id, 'top');\n}\nadd_action('init', 'custom_rewrite_basic');\n</code></pre>\n\n<blockquote>\n <p><strong>IMPORTANT:</strong> Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes.</p>\n</blockquote>\n" }, { "answer_id": 213326, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p><strong>Note</strong> that <em>search engines</em> might not like multiple paths to the same content!</p>\n\n<p>Here I assume you want e.g.:</p>\n\n<pre><code>example.tld/some/path/to/painting-orange\nexample.tld/painting-blue\nexample.tld/painting-red\nexample.tld/painting-yellow\n</code></pre>\n\n<p>to behave like it was this page:</p>\n\n<pre><code>example.tld/paintings\n</code></pre>\n\n<p>but not so for paths like: </p>\n\n<pre><code>example.tld/painting-white/painting-brown/large\nexample.tld/painting-brown/small\n</code></pre>\n\n<p>The rule here is to match the prefix on the left side of <code>basename( $path )</code>.</p>\n\n<p>Here's a little hack with the <code>request</code> filter, to check if the current page name is correctly prefixed:</p>\n\n<pre><code>&lt;?php\n/** \n * Plugin Name: Wildcard Pages\n */\nadd_filter( 'request', function( $qv )\n{\n // Edit to your needs\n $prefix = 'painting-';\n $target = 'paintings';\n\n // Check if the current page name is prefixed\n if( isset( $qv['pagename'] )\n &amp;&amp; $prefix === substr( basename( $qv['pagename'] ), 0, strlen( $prefix ) ) \n )\n $qv['pagename'] = $target;\n\n return $qv;\n} );\n</code></pre>\n\n<p>Modify this to your needs. Then create the plugin file <code>/wp-content/plugins/wpse-wildcard-pages/wpse-wildcard-pages.php</code> file and activate the plugin from the backend.</p>\n\n<p>We could also add a check with <a href=\"http://codex.wordpress.org/Function_Reference/get_page_by_path\" rel=\"nofollow\"><code>get_page_by_path()</code></a> on the target page, just to make sure it exists. We might also want to restrict this to certain post types.</p>\n" } ]
2015/12/28
[ "https://wordpress.stackexchange.com/questions/213016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44849/" ]
I want to serve a specific Wordpress page for multiple urls. Basically I want to point all the urls in a specific format to a known page: ``` /some-prefix-* => /target-page ``` And accessing `/some-prefix-and-here-something` it should load `/target-page`. How to do this? Note I do *not* want to redirect the user but to be able to serve an existing page to multiple urls. The `.htaccess` looks like this: ``` # BEGIN s2Member GZIP exclusions RewriteEngine On RewriteRule ^prefix-*$ some/path/to/directory-$1 [NC,L] <IfModule rewrite_module> RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} (^|\?|&)s2member_file_download\=.+ [OR] RewriteCond %{QUERY_STRING} (^|\?|&)no-gzip\=1 RewriteRule .* - [E=no-gzip:1] </IfModule> # END s2Member GZIP exclusions # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress DirectoryIndex index.php index.html ``` I thought by adding `RewriteEngine On RewriteRule ^prefix-*$ some/path/to/directory-$1 [NC,L]` will serve `/prefix-*` from `some/path/to/directory-$1`. For example: when accessing `example.com/prefix-foo` should be the same with `example.com/some/path/to/directory-foo` (which resolves to `example.com/some/path/to/directory-foo/index.html`). Also, if there is already a Wordpress page with the name `prefix-bar`, `/prefix-bar` should *not* load `example.com/some/path/to/directory-bar/index.html`.
You can use [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include), but before you hook to this filter you must do the following steps: 1. Create page template. e.g: `page-target.php` ``` <?php /** * Template Name: Page Target */ ... ``` 2. Manually query the contents of `target-page` on `page-target.php` template, because the global `$post` will be referencing to your `some-prefix-*` page. 3. (Optional): Edit and apply page template `Page Target` to your `/target-page` from the Page Attributes Then add the following to your `functions.php` file ``` add_filter('template_include', function($template) { global $post; $prefix = 'some-prefix-'; // Your prefix $prefixExist = strpos($post->post_name, $prefix) !== false; if ($prefixExist) { return locate_template('page-target.php'); //Your template } return $template; }); ``` Above filter will override the template with `page-target.php` if condition met, otherwise default ### Edit: I think I have found a better way to resolve this using [`add_rewrite_rule`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule) ``` function custom_rewrite_basic() { $page_id = 123; //Your serve page id add_rewrite_rule('^some-prefix-.*', 'index.php?page_id=' . $page_id, 'top'); } add_action('init', 'custom_rewrite_basic'); ``` > > **IMPORTANT:** Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes. > > >
213,043
<p>How to determine if the current file is loaded in a plugin or in a theme? A boolean PHP function.</p>
[ { "answer_id": 213044, "author": "Andrei Surdu", "author_id": 31111, "author_profile": "https://wordpress.stackexchange.com/users/31111", "pm_score": -1, "selected": true, "text": "<p><strong>1. The function:</strong></p>\n\n<pre><code>function wp543_is_plugin(){\n return strpos( str_replace(\"\\\\\", \"/\", plugin_dir_path( $file ) ) , str_replace(\"\\\\\", \"/\", WP_PLUGIN_DIR) ) !== false;\n}\n</code></pre>\n\n<p><strong>2. Call the function:</strong></p>\n\n<pre><code>wp543_is_plugin();\n</code></pre>\n\n<p>Calling this function will return <code>true</code> if the current file is loaded in a plugin and <code>false</code> if it is loaded in a theme.</p>\n\n<p><strong>Edit:</strong> Since this answer has received many downvotes I've found the solution that should fix my previous mistake. <em>And I intentionally solved it with just one line of code.</em> :)</p>\n\n<p>How this function works now:</p>\n\n<ol>\n<li>Replaces all backslashes wit forward slashes.</li>\n<li><code>plugin_dir_path( __FILE__ )</code> will always return the full path to current file. No matter if thatfile is within a plugin or theme. </li>\n<li><code>WP_PLUGIN_DIR</code> will always return the plugins path, so we just check if that path is found in <code>plugin_dir_path( __FILE__ )</code></li>\n<li>If it is found than the current file is within a plugin and return <code>true</code> otherwise <code>false</code>.</li>\n</ol>\n" }, { "answer_id": 213054, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": -1, "selected": false, "text": "<p>Interesting question.</p>\n\n<p>The content directory and the plugins directory can be altered but I don't believe you can alter the \"themes\" portion of the <code>wp-content</code> directory, so:</p>\n\n<pre><code>function theme_or_plugin_wpse_213043($path) {\n $path = str_replace('\\\\','/',$path);\n $path = explode('/',$path);\n return in_array('themes',$path);\n}\nvar_dump(theme_or_plugin_wpse_213043(__FILE__));\n</code></pre>\n\n<p>The function will <code>return</code> <code>true</code> for theme files and <code>false</code> otherwise-- this inlcudes plugins and mu-plugins.</p>\n\n<p>I am also fairly certain that if you need this function you are doing something else incorrectly-- probably using the wrong methods to get the theme/plugin paths or URLs.</p>\n" }, { "answer_id": 213213, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<h2>EDIT</h2>\n\n<p>Talking to @s_ha_dum, there are issues between operating system with the paths, Windows uses backslashes, so we need to compensate for them</p>\n\n<p>Because OP needs a boolean returned, we need a function to return either true or false, so we can either write two separate functions to cover both bases or just choose one and go with it. This method has its drawbacks though as it does not cover for files loaded outside the plugins and theme folders</p>\n\n<p>Lets look at a conditional that would return true if a file is loaded from a theme</p>\n\n<pre><code>function is_file_in_theme( $file_path = __FILE__ )\n{\n // Get the them root folder\n $root = get_theme_root(); \n // Change all '\\' to '/' to compensate for localhosts\n $root = str_replace( '\\\\', '/', $root ); // This will output E:\\xampp\\htdocs\\wordpress\\wp-content\\themes\n\n // Make sure we do that to $file_path as well\n $file_path = str_replace( '\\\\', '/', $file_path ); \n\n // We can now look for $root in $file_path and either return true or false\n $bool = stripos( $file_path, $root );\n if ( false === $bool )\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>We can alternatively do the same for plugins</p>\n\n<pre><code>function is_file_in_plugin( $file_path = __FILE__ )\n{\n // Get the plugin root folder\n $root = WP_PLUGIN_DIR; \n // Change all '\\' to '/' to compensate for localhosts\n $root = str_replace( '\\\\', '/', $root ); \n\n // Make sure we do that to $file_path as well\n $file_path = str_replace( '\\\\', '/', $file_path ); \n\n // We can now look for $root in $file_path and either return true or false\n $bool = stripos( $file_path, $root );\n if ( false === $bool )\n return false;\n\n return true;\n}\n</code></pre>\n" } ]
2015/12/28
[ "https://wordpress.stackexchange.com/questions/213043", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31111/" ]
How to determine if the current file is loaded in a plugin or in a theme? A boolean PHP function.
**1. The function:** ``` function wp543_is_plugin(){ return strpos( str_replace("\\", "/", plugin_dir_path( $file ) ) , str_replace("\\", "/", WP_PLUGIN_DIR) ) !== false; } ``` **2. Call the function:** ``` wp543_is_plugin(); ``` Calling this function will return `true` if the current file is loaded in a plugin and `false` if it is loaded in a theme. **Edit:** Since this answer has received many downvotes I've found the solution that should fix my previous mistake. *And I intentionally solved it with just one line of code.* :) How this function works now: 1. Replaces all backslashes wit forward slashes. 2. `plugin_dir_path( __FILE__ )` will always return the full path to current file. No matter if thatfile is within a plugin or theme. 3. `WP_PLUGIN_DIR` will always return the plugins path, so we just check if that path is found in `plugin_dir_path( __FILE__ )` 4. If it is found than the current file is within a plugin and return `true` otherwise `false`.
213,186
<p>I just started to work with Wordpress (Theme Development) and due to awesome functions like bloginfo('description') and others my static homepage looks a lot like a regular site, but editable with the Wordpress Dashboard.</p> <p>But now, I want to put more information on my homepage which I can edit through the dashboard. I guess this is really basic Wordpress and that a simple Wordpress function or MySQL-query should be enough, but I can't seem to find it. </p> <p>This is my code right now: </p> <pre><code> &lt;div class="fp-container"&gt; &lt;div class="fp-border"&gt; &lt;h1 class="fp-description"&gt;&lt;?php bloginfo('description'); ?&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div class="fp-text"&gt; &lt;p&gt;&lt;?php bloginfo('description'); ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>As you can see, between the '&lt; p>' and '&lt; /p>' I call the description for the second time, how can I call another string that can be entered through the Dashboard?</p> <p>I've asked this question on stackoverflow.com, and the only answer I got was that I should use the_content(), but that only works once, and I will need multiple text boxes on my frontpage. How can I do this?</p> <p>Rik</p>
[ { "answer_id": 213044, "author": "Andrei Surdu", "author_id": 31111, "author_profile": "https://wordpress.stackexchange.com/users/31111", "pm_score": -1, "selected": true, "text": "<p><strong>1. The function:</strong></p>\n\n<pre><code>function wp543_is_plugin(){\n return strpos( str_replace(\"\\\\\", \"/\", plugin_dir_path( $file ) ) , str_replace(\"\\\\\", \"/\", WP_PLUGIN_DIR) ) !== false;\n}\n</code></pre>\n\n<p><strong>2. Call the function:</strong></p>\n\n<pre><code>wp543_is_plugin();\n</code></pre>\n\n<p>Calling this function will return <code>true</code> if the current file is loaded in a plugin and <code>false</code> if it is loaded in a theme.</p>\n\n<p><strong>Edit:</strong> Since this answer has received many downvotes I've found the solution that should fix my previous mistake. <em>And I intentionally solved it with just one line of code.</em> :)</p>\n\n<p>How this function works now:</p>\n\n<ol>\n<li>Replaces all backslashes wit forward slashes.</li>\n<li><code>plugin_dir_path( __FILE__ )</code> will always return the full path to current file. No matter if thatfile is within a plugin or theme. </li>\n<li><code>WP_PLUGIN_DIR</code> will always return the plugins path, so we just check if that path is found in <code>plugin_dir_path( __FILE__ )</code></li>\n<li>If it is found than the current file is within a plugin and return <code>true</code> otherwise <code>false</code>.</li>\n</ol>\n" }, { "answer_id": 213054, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": -1, "selected": false, "text": "<p>Interesting question.</p>\n\n<p>The content directory and the plugins directory can be altered but I don't believe you can alter the \"themes\" portion of the <code>wp-content</code> directory, so:</p>\n\n<pre><code>function theme_or_plugin_wpse_213043($path) {\n $path = str_replace('\\\\','/',$path);\n $path = explode('/',$path);\n return in_array('themes',$path);\n}\nvar_dump(theme_or_plugin_wpse_213043(__FILE__));\n</code></pre>\n\n<p>The function will <code>return</code> <code>true</code> for theme files and <code>false</code> otherwise-- this inlcudes plugins and mu-plugins.</p>\n\n<p>I am also fairly certain that if you need this function you are doing something else incorrectly-- probably using the wrong methods to get the theme/plugin paths or URLs.</p>\n" }, { "answer_id": 213213, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<h2>EDIT</h2>\n\n<p>Talking to @s_ha_dum, there are issues between operating system with the paths, Windows uses backslashes, so we need to compensate for them</p>\n\n<p>Because OP needs a boolean returned, we need a function to return either true or false, so we can either write two separate functions to cover both bases or just choose one and go with it. This method has its drawbacks though as it does not cover for files loaded outside the plugins and theme folders</p>\n\n<p>Lets look at a conditional that would return true if a file is loaded from a theme</p>\n\n<pre><code>function is_file_in_theme( $file_path = __FILE__ )\n{\n // Get the them root folder\n $root = get_theme_root(); \n // Change all '\\' to '/' to compensate for localhosts\n $root = str_replace( '\\\\', '/', $root ); // This will output E:\\xampp\\htdocs\\wordpress\\wp-content\\themes\n\n // Make sure we do that to $file_path as well\n $file_path = str_replace( '\\\\', '/', $file_path ); \n\n // We can now look for $root in $file_path and either return true or false\n $bool = stripos( $file_path, $root );\n if ( false === $bool )\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>We can alternatively do the same for plugins</p>\n\n<pre><code>function is_file_in_plugin( $file_path = __FILE__ )\n{\n // Get the plugin root folder\n $root = WP_PLUGIN_DIR; \n // Change all '\\' to '/' to compensate for localhosts\n $root = str_replace( '\\\\', '/', $root ); \n\n // Make sure we do that to $file_path as well\n $file_path = str_replace( '\\\\', '/', $file_path ); \n\n // We can now look for $root in $file_path and either return true or false\n $bool = stripos( $file_path, $root );\n if ( false === $bool )\n return false;\n\n return true;\n}\n</code></pre>\n" } ]
2015/12/29
[ "https://wordpress.stackexchange.com/questions/213186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86005/" ]
I just started to work with Wordpress (Theme Development) and due to awesome functions like bloginfo('description') and others my static homepage looks a lot like a regular site, but editable with the Wordpress Dashboard. But now, I want to put more information on my homepage which I can edit through the dashboard. I guess this is really basic Wordpress and that a simple Wordpress function or MySQL-query should be enough, but I can't seem to find it. This is my code right now: ``` <div class="fp-container"> <div class="fp-border"> <h1 class="fp-description"><?php bloginfo('description'); ?></h1> </div> <div class="fp-text"> <p><?php bloginfo('description'); ?></p> </div> ``` As you can see, between the '< p>' and '< /p>' I call the description for the second time, how can I call another string that can be entered through the Dashboard? I've asked this question on stackoverflow.com, and the only answer I got was that I should use the\_content(), but that only works once, and I will need multiple text boxes on my frontpage. How can I do this? Rik
**1. The function:** ``` function wp543_is_plugin(){ return strpos( str_replace("\\", "/", plugin_dir_path( $file ) ) , str_replace("\\", "/", WP_PLUGIN_DIR) ) !== false; } ``` **2. Call the function:** ``` wp543_is_plugin(); ``` Calling this function will return `true` if the current file is loaded in a plugin and `false` if it is loaded in a theme. **Edit:** Since this answer has received many downvotes I've found the solution that should fix my previous mistake. *And I intentionally solved it with just one line of code.* :) How this function works now: 1. Replaces all backslashes wit forward slashes. 2. `plugin_dir_path( __FILE__ )` will always return the full path to current file. No matter if thatfile is within a plugin or theme. 3. `WP_PLUGIN_DIR` will always return the plugins path, so we just check if that path is found in `plugin_dir_path( __FILE__ )` 4. If it is found than the current file is within a plugin and return `true` otherwise `false`.
213,191
<p>Code in my funcitons.php</p> <pre><code>function custom_thumbs() { add_image_size( 'cover-size', 1600, 450, true ); } add_action( 'after_setup_theme', 'custom_thumbs' ); </code></pre> <p>Usage:</p> <p><code>echo the_post_thumbnail($post-&gt;ID,'cover-size');</code></p> <p>but this is the result:</p> <pre><code>&lt;img width="3648" height="2736" src="http://localhost/sonru/wp-content/uploads/2015/12/DSC04656.jpg" class="attachment-9 size-9 wp-post-image" alt="DSC04656" cover-size="" srcset="http://localhost/sonru/wp-content/uploads/2015/12/DSC04656-300x225.jpg 300w, http://localhost/sonru/wp-content/uploads/2015/12/DSC04656-600x450.jpg 600w" sizes="(max-width: 3648px) 100vw, 3648px"&gt; </code></pre> <p>What Am I missing here?</p> <p>-Edit-</p> <p>I'm already regenerating thumbnails using the <code>regenerate thunbnails</code> plugin</p>
[ { "answer_id": 213194, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>You may need to regenerate your images. There are plugins to accomplish this or re-upload your image and see if the size doesn't take affect. It won't happen automatically to existing files. </p>\n\n<p>First, check your uploads directory to see if the files exists that way you know they are being generated. Then try another function to output the results.</p>\n\n<p>What do you end up with when you use:</p>\n\n<pre><code>$attachment_id = get_post_thumbnail_id( $post-&gt;ID ); \n$img_src = wp_get_attachment_image_url( $attachment_id, 'cover-size' ); \n$img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'cover-size' );\n</code></pre>\n\n<p>Also if may be handy to output your meta data for that attachment - specifically to see the <code>size</code> information:</p>\n\n<pre><code>print_r ( wp_get_attachment_metadata( $attachment_id) );\n</code></pre>\n\n<p>The above <code>wp_get_attachment_image_srcset</code> requires WordPress 4.4 and you can find more information about <a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/\" rel=\"nofollow\">Responsive Images in WordPress 4.4</a>.</p>\n\n<p>Assuming the files exist:</p>\n\n<ul>\n<li><p><a href=\"https://codex.wordpress.org/Function_Reference/the_post_thumbnail\" rel=\"nofollow\">the_post_thumbnail</a> <code>( $size, $attr )</code></p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\">get_the_post_thumbnail</a> <code>( int|WP_Post $post = null, string|array $size = 'post-thumbnail', string|array $attr = '' )</code></p></li>\n</ul>\n\n<p>Are you in a Loop or outside of it? </p>\n\n<p>If you're inside try <code>the_post_thumbnail ('cover-size');</code> </p>\n\n<p>otherwise <code>echo get_the_post_thumbnail ($post,'cover-size');</code></p>\n" }, { "answer_id": 213202, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You are using the wrong function:</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow\"><code>the_post_thumbnail()</code></a> does not accept the post ID as value, but the image size.</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\"><code>get_the_post_thumbnail()</code></a> is what you need and maybe trying to use. The first parameter accept the post ID and the second parameter accepts the image size to use as in your question</p></li>\n</ul>\n\n<h2>SOLUTION</h2>\n\n<p>Swap <code>the_post_thumbnail()</code> with <code>get_the_post_thumbnail()</code></p>\n\n<h2>EDIT</h2>\n\n<p>Just a note, make sure that you add your new image size after you have added support for thumbnails. Also, you would want to add a new post thumbnail size with <a href=\"https://codex.wordpress.org/Function_Reference/set_post_thumbnail_size\" rel=\"nofollow\"><code>set_post_thumbnail_size()</code></a></p>\n" } ]
2015/12/29
[ "https://wordpress.stackexchange.com/questions/213191", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3435/" ]
Code in my funcitons.php ``` function custom_thumbs() { add_image_size( 'cover-size', 1600, 450, true ); } add_action( 'after_setup_theme', 'custom_thumbs' ); ``` Usage: `echo the_post_thumbnail($post->ID,'cover-size');` but this is the result: ``` <img width="3648" height="2736" src="http://localhost/sonru/wp-content/uploads/2015/12/DSC04656.jpg" class="attachment-9 size-9 wp-post-image" alt="DSC04656" cover-size="" srcset="http://localhost/sonru/wp-content/uploads/2015/12/DSC04656-300x225.jpg 300w, http://localhost/sonru/wp-content/uploads/2015/12/DSC04656-600x450.jpg 600w" sizes="(max-width: 3648px) 100vw, 3648px"> ``` What Am I missing here? -Edit- I'm already regenerating thumbnails using the `regenerate thunbnails` plugin
You may need to regenerate your images. There are plugins to accomplish this or re-upload your image and see if the size doesn't take affect. It won't happen automatically to existing files. First, check your uploads directory to see if the files exists that way you know they are being generated. Then try another function to output the results. What do you end up with when you use: ``` $attachment_id = get_post_thumbnail_id( $post->ID ); $img_src = wp_get_attachment_image_url( $attachment_id, 'cover-size' ); $img_srcset = wp_get_attachment_image_srcset( $attachment_id, 'cover-size' ); ``` Also if may be handy to output your meta data for that attachment - specifically to see the `size` information: ``` print_r ( wp_get_attachment_metadata( $attachment_id) ); ``` The above `wp_get_attachment_image_srcset` requires WordPress 4.4 and you can find more information about [Responsive Images in WordPress 4.4](https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/). Assuming the files exist: * [the\_post\_thumbnail](https://codex.wordpress.org/Function_Reference/the_post_thumbnail) `( $size, $attr )` * [get\_the\_post\_thumbnail](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) `( int|WP_Post $post = null, string|array $size = 'post-thumbnail', string|array $attr = '' )` Are you in a Loop or outside of it? If you're inside try `the_post_thumbnail ('cover-size');` otherwise `echo get_the_post_thumbnail ($post,'cover-size');`
213,219
<p>I have a filter for the Gallery Shortcode where I grab IDs for images used in a post and using the IDs I grab their meta data. Now I need a way to use the <code>$copyright</code> variable in a filter for grabbing <code>post_content</code> so I can echo the content of that variable.</p> <p>Is there a way to reuse a variable in different filter or maybe there is a better way for what I am trying to accomplish?</p> <pre><code>function wpse_get_full_size_gallery_images( $gallery, $post, $galleries ) { $ids = explode( ',', $galleries['include'] ); $copyright = array(); foreach( $ids as $id ) $copyright[] = get_post_meta( $id, 'wiki_copyright', true ); return $gallery; } add_filter( 'shortcode_atts_gallery', 'wpse_get_full_size_gallery_images', 10, 3 ); function my_the_content_filter( $content ) { //pass here the copyright array and append it at the end $content .= $copyright; return $content; } add_filter( 'the_content', 'my_the_content_filter', 20 ); </code></pre>
[ { "answer_id": 213223, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 4, "selected": true, "text": "<p>This is probably a good case for a global variable. Just make sure it is set to an array before you add to it and also when to attempt to output the content. Convert the array to a string before adding to content.</p>\n\n<p>Also, make sure the meta data exists before adding to the array -- that way you're not adding empty copyright values.</p>\n\n<p><strong>GLOBAL VERSION</strong></p>\n\n<pre><code>function wpse_get_full_size_gallery_images($gallery, $post, $galleries) {\n\n // reference the global variable\n global $copyright;\n\n // make sure it's set\n if( ! isset($copyright)) $copyright = array();\n\n // grab the IDS\n $ids = explode(',', $galleries[ 'include' ]);\n\n foreach($ids as $id) {\n // get the possible meta\n $meta = get_post_meta($id, 'wiki_copyright', true);\n\n // add them to the copyright array \n // make sure to only add if it exists\n if( !empty($meta)) $copyright[] = $meta;\n }\n\n return $gallery;\n}\n\nadd_filter('shortcode_atts_gallery', 'wpse_get_full_size_gallery_images', 10, 3);\n\nfunction my_the_content_filter($content) {\n\n // reference the global variable\n global $copyright;\n\n // add copyright array converted to string if we have content\n if( ! empty($copyright)) $content .= implode(',', $copyright);\n\n return $content;\n}\n\nadd_filter('the_content', 'my_the_content_filter', 20);\n</code></pre>\n\n<p><strong>STATIC VERSION</strong></p>\n\n<p>If you don't like to use globals, <em>for whatever reason</em>, then consider a <a href=\"http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static\" rel=\"nofollow noreferrer\">static</a> as an alternate <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">variable scope</a> in PHP.</p>\n\n<blockquote>\n <p>Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.</p>\n</blockquote>\n\n<p>Since the persistent variable is tied to a single function scope we'll need to create the function outside any loops then reuse it for adding values in addition to retrieving those values. </p>\n\n<p><em>If you pass a new value; <strong>add it</strong>. If you don't pass a value; <strong>get all values</strong>.</em></p>\n\n<pre><code>if( ! function_exists('copyrights')) {\n function copyrights($value = '') {\n\n // only this function has access to $_copyrights\n static $_copyrights;\n\n // expressions can't be assigned as defaults\n // but we still want to initialize the value\n if( ! isset($_copyrights)) {\n $_copyrights = array();\n }\n\n // if we're passing new values then add them\n if( ! empty($value)) {\n $_copyrights[] = $value;\n\n return true; // success\n }\n else {\n // otherwise return uniques\n $unique_list = array_unique($_copyrights);\n\n // convert to string before they leave\n return implode(\", \", $unique_list);\n }\n }\n}\n\nadd_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) {\n $ids = explode(',', $galleries[ 'include' ]);\n foreach($ids as $id) \n if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true)))\n copyrights($meta);\n\n return $gallery;\n}, 10, 3);\n\nadd_filter('the_content', function($content) {\n return $content . copyrights();\n}, 20);\n</code></pre>\n\n<p>TESTING</p>\n\n<pre><code>copyrights ( 123 );\ncopyrights ( 223 );\ncopyrights ( 333 );\ncopyrights ( 123 );\ncopyrights ( 111 );\ncopyrights ( 111 );\ncopyrights ( 111 );\n\necho ( copyrights() ); // 123, 223, 333, 111\n</code></pre>\n\n<p><strong>SINGLETON VERSION</strong></p>\n\n<p>I actually never use globals because a <a href=\"http://www.phptherightway.com/pages/Design-Patterns.html#singleton\" rel=\"nofollow noreferrer\">Singleton Pattern</a> is my preferred method.</p>\n\n<p>The idea is that you put all your methods on an instance of a class but only access it through a static method. By doing so, the class ensures there is only ever one single instance created.</p>\n\n<pre><code>if( ! class_exists('Copyrights')) {\n class Copyrights {\n\n private $copyrights;\n private static $instance;\n\n // PRIVATE CONSTRUCTOR\n\n private function __construct() {\n\n // initialize the array\n $this-&gt;copyrights = array();\n }\n\n // STATIC SINGLETON\n\n public static function getInstance() {\n if(is_null(self::$instance)) {\n self::$instance = new self();\n }\n\n return self::$instance;\n }\n\n // PUBLIC METHODS\n\n public function toString() {\n $unique_list = array_unique($this-&gt;copyrights);\n\n return implode(\", \", $unique_list);\n }\n\n public function add($value = '') {\n if( ! empty($value)) {\n $this-&gt;copyrights[] = $value;\n }\n }\n }\n}\n\nadd_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) {\n\n $ids = explode(',', $galleries[ 'include' ]);\n\n foreach($ids as $id)\n if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true))) \n Copyrights::getInstance()-&gt;add($meta);\n\n return $gallery;\n}, 10, 3);\n\nadd_filter('the_content', function($content) {\n return $content . Copyrights::getInstance()-&gt;toString();\n}, 20);\n</code></pre>\n\n<p>TESTING</p>\n\n<pre><code>Copyrights::getInstance()-&gt;add ( 123 );\nCopyrights::getInstance()-&gt;add ( 223 );\nCopyrights::getInstance()-&gt;add ( 333 );\nCopyrights::getInstance()-&gt;add ( 123 );\nCopyrights::getInstance()-&gt;add ( 111 );\nCopyrights::getInstance()-&gt;add ( 111 );\nCopyrights::getInstance()-&gt;add ( 111 );\n\necho Copyrights::getInstance()-&gt;toString(); // 123, 223, 333, 111\n</code></pre>\n\n<p><strong>SINGLETON PER POST VERSION</strong></p>\n\n<p>Maybe the <em>single</em> most important aspect that has been overlooked in the debate of <code>global</code> vs. <code>the sky is falling</code> is the solution above (<em>and alternates proposed</em>) only cater to a single post. If you wanted to add your copyrights in a loop you would be screwed because all posts would be added to a single array.</p>\n\n<p>With the singleton class, adding a per ID singleton is cake and arguably the best possible <em>option</em>.</p>\n\n<pre><code>if( ! class_exists('Copyrights')) {\n class Copyrights {\n\n private static $instance;\n private $copyrights;\n public $post_id;\n\n // PRIVATE CONSTRUCTOR\n\n private function __construct($post_id) {\n\n // save the id\n $this-&gt;post_id = $post_id;\n\n // initialize the array\n $this-&gt;copyrights = array();\n }\n\n // SINGLETON\n\n public static function getInstance($post_id = 'NO ID') {\n if(is_null(self::$instance)) self::$instance = array();\n if(is_null(self::$instance[ $post_id ])) {\n self::$instance[ $post_id ] = new self($post_id);\n }\n\n return self::$instance[ $post_id ];\n }\n\n // PUBLIC METHODS\n\n public function toString() {\n $unique_list = array_unique($this-&gt;copyrights);\n\n return implode(\", \", $unique_list);\n }\n\n public function add($value = '') {\n if( ! empty($value)) {\n $this-&gt;copyrights[] = $value;\n }\n }\n }\n}\n\nadd_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) {\n\n $ids = explode(',', $galleries[ 'include' ]);\n\n foreach($ids as $id)\n if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true)))\n Copyrights::getInstance($post-&gt;ID)-&gt;add($meta);\n\n return $gallery;\n}, 10, 3);\n\nadd_filter('the_content', function($content) {\n global $post;\n return $content . Copyrights::getInstance($post-&gt;ID)-&gt;toString();\n}, 20);\n</code></pre>\n\n<p>TESTING</p>\n\n<p>As you can see, having the the <em>option</em> to use <code>ID</code> as a key keeps things flexible.</p>\n\n<pre><code>Copyrights::getInstance( 1 )-&gt;add ( 123 );\nCopyrights::getInstance( 1 )-&gt;add ( 223 );\nCopyrights::getInstance( 2 )-&gt;add ( 333 );\nCopyrights::getInstance( 2 )-&gt;add ( 123 );\nCopyrights::getInstance( 2 )-&gt;add ( 111 );\nCopyrights::getInstance( 2 )-&gt;add ( 111 );\nCopyrights::getInstance( 2 )-&gt;add ( 111 );\nCopyrights::getInstance()-&gt;add ( 111 );\nCopyrights::getInstance()-&gt;add ( 444 );\nCopyrights::getInstance()-&gt;add ( 555 );\nCopyrights::getInstance()-&gt;add ( 888 );\n\necho Copyrights::getInstance( 1 )-&gt;toString(); // 123, 223\necho Copyrights::getInstance( 2 )-&gt;toString(); // 333, 123, 111\necho Copyrights::getInstance()-&gt;toString(); // 111, 444, 555, 888\n</code></pre>\n\n<p>At the point that someone thinks it's a good idea to store a temporary value in the <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow noreferrer\">database</a> because they don't understand PHP then it's a good time to rethink the problem.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I <a href=\"https://wordpress.stackexchange.com/a/213223/84219\">solved</a> the question using a <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">global</a> variable but rethinking the issue you can do away with a lot of complexities by justing using <a href=\"https://codex.wordpress.org/Function_Reference/the_content\" rel=\"nofollow noreferrer\">the content</a> filter hook alone -- which keeps the issue localized.</p>\n\n<p>In this case, when <code>the_content</code> runs, we check for <a href=\"https://codex.wordpress.org/Function_Reference/get_post_galleries\" rel=\"nofollow noreferrer\">all galleries</a> and output only the <a href=\"http://php.net/manual/en/function.array-filter.php\" rel=\"nofollow noreferrer\">relevant data</a>.</p>\n\n<blockquote>\n <p>No need for globals, statics, singletons, options or extra functions.</p>\n \n <p>Best of all, this will work in a loop without complication.</p>\n</blockquote>\n\n<pre><code>add_filter('the_content', 'add_copyright_to_content');\n\nfunction add_copyright_to_content($content) {\n\n // pull all galleries from the post\n $galleries = get_post_galleries(get_post(), false);\n\n // no gallery? then let's get out of here\n if(empty($galleries)) return $content;\n\n $all = '';\n\n // gather all ids\n foreach($galleries as $gallery) $all .= $gallery[ 'ids' ] . ',';\n\n // convert them to an array with unique ids\n $all = array_unique(array_filter(explode(',', $all)));\n\n // replace id for copyright info on the image meta\n foreach($all as $key =&gt; $id) $all [ $key ] = get_post_meta($id, 'wiki_copyright', true);\n\n // return non-empty values to the end of the content\n return $content . implode(', ', array_filter($all));\n}\n</code></pre>\n" }, { "answer_id": 213263, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>...maybe there is a better way for what I am trying to accomplish?</p>\n</blockquote>\n\n<p>There are always extra options to take into consideration. Globalizing a variable is certainly not one of them and you should avoid doing that. Globalizing is an easy way out to solve any issue, but believe me you'll spend days debugging an issue which does not give you any debugging errors when something breaks your global. </p>\n\n<p>WordPress alreay made a huge mess with globals. Just go through questions and answers on this site and check how many are using the globals <code>$wp_query</code>, <code>$posts</code> and <code>$post</code> as local variables.</p>\n\n<p>I personally use <code>$copyright</code> as a variable to hold date info. If we globalize <code>$copyright</code> with a string of id's as in your case, either my variable is going to break the global or the global is going to break my variable. Worst is, I would not get any debug errors and I would not know where my values are changed. So never ever globalize variables, IMHO, it is really bad practice as there are many other options</p>\n\n<p>A quick option that comes to mind is storing your data with the Options API. It is easy and does not require huge overheads as options are cached, and they are save to use.</p>\n\n<p>Lets try the following: (<strong><em>NOTE:</strong> All code is untested so make sure to test this on local install first. The code also requires PHP5.4+</em>)</p>\n\n<pre><code>add_filter( 'shortcode_atts_gallery', function ( $gallery, $post, $galleries ) \n{ \n // Get all the ids\n $ids = $galleries['include'];\n // Instead of overloading the shortcode, lets just save the id's for later use\n if ( !$ids ) // Always make sure we have values\n return $gallery;\n\n // Add our ids in an option\n $option = get_option( 'custom_copyright_ids' );\n if ( false !== $option // Make sure that the option does not yet exist\n || $option !== $ids // We only want the update if $id's change\n ) {\n // Lets update or add our option\n update_option( 'custom_copyright_ids', $ids );\n }\n\n return $gallery;\n}, 10, 3 );\n</code></pre>\n\n<p>We can nowcreate a \"global\" function which we can carry around and use (<strong><em>safely</em></strong>) where we want to use it. (<em>The function below is static, you can make it dynamic</em>)</p>\n\n<pre><code>function get_global_copyright_ids()\n{\n $output = '';\n\n // Get our ids\n $ids = get_option( 'custom_copyright_ids' );\n\n // Make sure we have a value for $option, either return an empty string\n if ( false === $ids )\n return $output;\n\n // We have ids, lets continue\n // We expect $ids to be an array, so lets turn the string into an array\n $ids = explode( ',', trim( $ids ) );\n\n foreach ( $ids as $id ) {\n // Get our post meta\n $meta = get_post_meta( $id, 'wiki_copyright', true );\n if ( !$meta )\n continue;\n // We have meta, add it to our $output string. Add any markup here\n $output .= $meta\n } // endforeach $ids\n\n // Return our string of post meta\n return $output;\n}\n</code></pre>\n\n<p>We can now use <code>get_global_copyright_ids()</code> anywhere where we want to</p>\n\n<pre><code>add_filter( 'the_content', function ( $content )\n{\n // Get our content to add from our \"global\" function\n $extra = '';\n if ( function_exists( 'get_global_copyright_ids' ) ) {\n $extra = get_global_copyright_ids();\n }\n\n if ( !$extra )\n return $content;\n\n // Append $extra to $content\n return $content . $extra;\n}):\n</code></pre>\n\n<p>And there you have a much better and safer system which is really easy to debug and best of all <strong>YOU KEPT THE GLOBAL SCOPE CLEAN!!!</strong></p>\n" } ]
2015/12/29
[ "https://wordpress.stackexchange.com/questions/213219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85935/" ]
I have a filter for the Gallery Shortcode where I grab IDs for images used in a post and using the IDs I grab their meta data. Now I need a way to use the `$copyright` variable in a filter for grabbing `post_content` so I can echo the content of that variable. Is there a way to reuse a variable in different filter or maybe there is a better way for what I am trying to accomplish? ``` function wpse_get_full_size_gallery_images( $gallery, $post, $galleries ) { $ids = explode( ',', $galleries['include'] ); $copyright = array(); foreach( $ids as $id ) $copyright[] = get_post_meta( $id, 'wiki_copyright', true ); return $gallery; } add_filter( 'shortcode_atts_gallery', 'wpse_get_full_size_gallery_images', 10, 3 ); function my_the_content_filter( $content ) { //pass here the copyright array and append it at the end $content .= $copyright; return $content; } add_filter( 'the_content', 'my_the_content_filter', 20 ); ```
This is probably a good case for a global variable. Just make sure it is set to an array before you add to it and also when to attempt to output the content. Convert the array to a string before adding to content. Also, make sure the meta data exists before adding to the array -- that way you're not adding empty copyright values. **GLOBAL VERSION** ``` function wpse_get_full_size_gallery_images($gallery, $post, $galleries) { // reference the global variable global $copyright; // make sure it's set if( ! isset($copyright)) $copyright = array(); // grab the IDS $ids = explode(',', $galleries[ 'include' ]); foreach($ids as $id) { // get the possible meta $meta = get_post_meta($id, 'wiki_copyright', true); // add them to the copyright array // make sure to only add if it exists if( !empty($meta)) $copyright[] = $meta; } return $gallery; } add_filter('shortcode_atts_gallery', 'wpse_get_full_size_gallery_images', 10, 3); function my_the_content_filter($content) { // reference the global variable global $copyright; // add copyright array converted to string if we have content if( ! empty($copyright)) $content .= implode(',', $copyright); return $content; } add_filter('the_content', 'my_the_content_filter', 20); ``` **STATIC VERSION** If you don't like to use globals, *for whatever reason*, then consider a [static](http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static) as an alternate [variable scope](http://php.net/manual/en/language.variables.scope.php) in PHP. > > Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. > > > Since the persistent variable is tied to a single function scope we'll need to create the function outside any loops then reuse it for adding values in addition to retrieving those values. *If you pass a new value; **add it**. If you don't pass a value; **get all values**.* ``` if( ! function_exists('copyrights')) { function copyrights($value = '') { // only this function has access to $_copyrights static $_copyrights; // expressions can't be assigned as defaults // but we still want to initialize the value if( ! isset($_copyrights)) { $_copyrights = array(); } // if we're passing new values then add them if( ! empty($value)) { $_copyrights[] = $value; return true; // success } else { // otherwise return uniques $unique_list = array_unique($_copyrights); // convert to string before they leave return implode(", ", $unique_list); } } } add_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) { $ids = explode(',', $galleries[ 'include' ]); foreach($ids as $id) if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true))) copyrights($meta); return $gallery; }, 10, 3); add_filter('the_content', function($content) { return $content . copyrights(); }, 20); ``` TESTING ``` copyrights ( 123 ); copyrights ( 223 ); copyrights ( 333 ); copyrights ( 123 ); copyrights ( 111 ); copyrights ( 111 ); copyrights ( 111 ); echo ( copyrights() ); // 123, 223, 333, 111 ``` **SINGLETON VERSION** I actually never use globals because a [Singleton Pattern](http://www.phptherightway.com/pages/Design-Patterns.html#singleton) is my preferred method. The idea is that you put all your methods on an instance of a class but only access it through a static method. By doing so, the class ensures there is only ever one single instance created. ``` if( ! class_exists('Copyrights')) { class Copyrights { private $copyrights; private static $instance; // PRIVATE CONSTRUCTOR private function __construct() { // initialize the array $this->copyrights = array(); } // STATIC SINGLETON public static function getInstance() { if(is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } // PUBLIC METHODS public function toString() { $unique_list = array_unique($this->copyrights); return implode(", ", $unique_list); } public function add($value = '') { if( ! empty($value)) { $this->copyrights[] = $value; } } } } add_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) { $ids = explode(',', $galleries[ 'include' ]); foreach($ids as $id) if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true))) Copyrights::getInstance()->add($meta); return $gallery; }, 10, 3); add_filter('the_content', function($content) { return $content . Copyrights::getInstance()->toString(); }, 20); ``` TESTING ``` Copyrights::getInstance()->add ( 123 ); Copyrights::getInstance()->add ( 223 ); Copyrights::getInstance()->add ( 333 ); Copyrights::getInstance()->add ( 123 ); Copyrights::getInstance()->add ( 111 ); Copyrights::getInstance()->add ( 111 ); Copyrights::getInstance()->add ( 111 ); echo Copyrights::getInstance()->toString(); // 123, 223, 333, 111 ``` **SINGLETON PER POST VERSION** Maybe the *single* most important aspect that has been overlooked in the debate of `global` vs. `the sky is falling` is the solution above (*and alternates proposed*) only cater to a single post. If you wanted to add your copyrights in a loop you would be screwed because all posts would be added to a single array. With the singleton class, adding a per ID singleton is cake and arguably the best possible *option*. ``` if( ! class_exists('Copyrights')) { class Copyrights { private static $instance; private $copyrights; public $post_id; // PRIVATE CONSTRUCTOR private function __construct($post_id) { // save the id $this->post_id = $post_id; // initialize the array $this->copyrights = array(); } // SINGLETON public static function getInstance($post_id = 'NO ID') { if(is_null(self::$instance)) self::$instance = array(); if(is_null(self::$instance[ $post_id ])) { self::$instance[ $post_id ] = new self($post_id); } return self::$instance[ $post_id ]; } // PUBLIC METHODS public function toString() { $unique_list = array_unique($this->copyrights); return implode(", ", $unique_list); } public function add($value = '') { if( ! empty($value)) { $this->copyrights[] = $value; } } } } add_filter('shortcode_atts_gallery', function($gallery, $post, $galleries) { $ids = explode(',', $galleries[ 'include' ]); foreach($ids as $id) if( ! empty($meta = get_post_meta($id, 'wiki_copyright', true))) Copyrights::getInstance($post->ID)->add($meta); return $gallery; }, 10, 3); add_filter('the_content', function($content) { global $post; return $content . Copyrights::getInstance($post->ID)->toString(); }, 20); ``` TESTING As you can see, having the the *option* to use `ID` as a key keeps things flexible. ``` Copyrights::getInstance( 1 )->add ( 123 ); Copyrights::getInstance( 1 )->add ( 223 ); Copyrights::getInstance( 2 )->add ( 333 ); Copyrights::getInstance( 2 )->add ( 123 ); Copyrights::getInstance( 2 )->add ( 111 ); Copyrights::getInstance( 2 )->add ( 111 ); Copyrights::getInstance( 2 )->add ( 111 ); Copyrights::getInstance()->add ( 111 ); Copyrights::getInstance()->add ( 444 ); Copyrights::getInstance()->add ( 555 ); Copyrights::getInstance()->add ( 888 ); echo Copyrights::getInstance( 1 )->toString(); // 123, 223 echo Copyrights::getInstance( 2 )->toString(); // 333, 123, 111 echo Copyrights::getInstance()->toString(); // 111, 444, 555, 888 ``` At the point that someone thinks it's a good idea to store a temporary value in the [database](https://codex.wordpress.org/Options_API) because they don't understand PHP then it's a good time to rethink the problem. --- **UPDATE** I [solved](https://wordpress.stackexchange.com/a/213223/84219) the question using a [global](http://php.net/manual/en/language.variables.scope.php) variable but rethinking the issue you can do away with a lot of complexities by justing using [the content](https://codex.wordpress.org/Function_Reference/the_content) filter hook alone -- which keeps the issue localized. In this case, when `the_content` runs, we check for [all galleries](https://codex.wordpress.org/Function_Reference/get_post_galleries) and output only the [relevant data](http://php.net/manual/en/function.array-filter.php). > > No need for globals, statics, singletons, options or extra functions. > > > Best of all, this will work in a loop without complication. > > > ``` add_filter('the_content', 'add_copyright_to_content'); function add_copyright_to_content($content) { // pull all galleries from the post $galleries = get_post_galleries(get_post(), false); // no gallery? then let's get out of here if(empty($galleries)) return $content; $all = ''; // gather all ids foreach($galleries as $gallery) $all .= $gallery[ 'ids' ] . ','; // convert them to an array with unique ids $all = array_unique(array_filter(explode(',', $all))); // replace id for copyright info on the image meta foreach($all as $key => $id) $all [ $key ] = get_post_meta($id, 'wiki_copyright', true); // return non-empty values to the end of the content return $content . implode(', ', array_filter($all)); } ```
213,224
<p>Unfortunately, <code>the_posts_navigation()</code> function is not working for me. When I click on 'Older Posts' it's showing '404 page I don't know why my code is not working. </p> <p>Here is the code -</p> <pre><code>&lt;div class="row"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;div class="col-md-3 thumbnailu"&gt; &lt;a class="thmb" href="&lt;?php echo get_post_meta ($post-&gt;ID, 'link_name', true); ?&gt;" target="_blank"&gt; &lt;?php the_post_thumbnail( 'website-image-size', array( 'class' =&gt; 'img-responsive' ) ); ?&gt; &lt;p class="caption"&gt;&lt;?php the_title(); ?&gt;&lt;br&gt; by &lt;?php echo get_post_meta ($post-&gt;ID, 'author_name', true); ?&gt; &lt;/p&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php the_posts_navigation(array( 'prev_text' =&gt; 'Older Posts', 'next_text' =&gt; 'Newer Posts', 'screen_reader_text' =&gt; ' ', )); ?&gt; </code></pre> <p></p> <p>It's showing the same error even I use the <code>previous_posts_link()</code> function. </p>
[ { "answer_id": 213225, "author": "Aniket Bhawkar", "author_id": 85953, "author_profile": "https://wordpress.stackexchange.com/users/85953", "pm_score": 1, "selected": false, "text": "<p>This function uses <code>get_the_posts_pagination()</code> which uses the GLOBAL <code>$wp_query</code> to setup the <code>paginate_links()</code> function, so I believe that doesn't work for <code>get_posts</code>.</p>\n\n<p>Try use the function <code>paginate_links()</code> by itself or the function <code>posts_nav_link()</code></p>\n" }, { "answer_id": 279239, "author": "sagar", "author_id": 97598, "author_profile": "https://wordpress.stackexchange.com/users/97598", "pm_score": -1, "selected": false, "text": "<p>Place <code>the_posts_navigation</code>inside while loop hopefully it works!!</p>\n" } ]
2015/12/29
[ "https://wordpress.stackexchange.com/questions/213224", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81042/" ]
Unfortunately, `the_posts_navigation()` function is not working for me. When I click on 'Older Posts' it's showing '404 page I don't know why my code is not working. Here is the code - ``` <div class="row"> <?php while ( have_posts() ) : the_post(); ?> <div class="col-md-3 thumbnailu"> <a class="thmb" href="<?php echo get_post_meta ($post->ID, 'link_name', true); ?>" target="_blank"> <?php the_post_thumbnail( 'website-image-size', array( 'class' => 'img-responsive' ) ); ?> <p class="caption"><?php the_title(); ?><br> by <?php echo get_post_meta ($post->ID, 'author_name', true); ?> </p> </a> </div> <?php endwhile; ?> <?php the_posts_navigation(array( 'prev_text' => 'Older Posts', 'next_text' => 'Newer Posts', 'screen_reader_text' => ' ', )); ?> ``` It's showing the same error even I use the `previous_posts_link()` function.
This function uses `get_the_posts_pagination()` which uses the GLOBAL `$wp_query` to setup the `paginate_links()` function, so I believe that doesn't work for `get_posts`. Try use the function `paginate_links()` by itself or the function `posts_nav_link()`
213,266
<p>I want to be able to login to wordpress through a customized function, no dashboard etc showing. I just want the user being logged in and then I want to handle stuff like customized forms, update stuff into db etc for a specific logged in user.</p> <p>I thought <code>wp_signon</code>() looked like a good alternative, but it opens up the dashboard menu that I really didn't want it to. Is there a possible way not show dashboard-menu when logged in (basically show nothing, just being logged in with a cookie) as a client? When I log in as adminstrator (through /wp-admin) I want the "normal" functionality with dashboard etc.</p> <p>Is this possible?</p>
[ { "answer_id": 213269, "author": "bestprogrammerintheworld", "author_id": 38848, "author_profile": "https://wordpress.stackexchange.com/users/38848", "pm_score": 0, "selected": false, "text": "<p>I found an answer to this myself... if someone stumbles upon the same issue. I installed a plugin called Admin Menu Editor:\n<a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow\">https://wordpress.org/plugins/admin-menu-editor/</a></p>\n\n<p>...and in the settings for this plugin I set capability level Administrator for Panel and then the client users I set to another role.</p>\n" }, { "answer_id": 325611, "author": "Loren Rosen", "author_id": 158993, "author_profile": "https://wordpress.stackexchange.com/users/158993", "pm_score": 2, "selected": false, "text": "<p>I assume you're referring to the black bar that may run across the top of a web page. That's called the 'Toolbar'. However, an earlier version of it was called the 'Admin Bar', and that name is still used in the code.\nTo never display it, add this to <code>functions.php</code></p>\n\n<pre><code>function my_function_admin_bar(){\n return false;\n}\nadd_filter( 'show_admin_bar' , 'my_function_admin_bar');\n</code></pre>\n\n<p>or to just show the bar for admins</p>\n\n<pre><code>function my_function_admin_bar($content) {\n return ( current_user_can( 'administrator' ) ) ? $content : false;\n}\nadd_filter( 'show_admin_bar' , 'my_function_admin_bar');\n</code></pre>\n\n<p>(Or similarly in a plugin.)</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">the Codex</a>.</p>\n\n<p>(Also, you should be able to use <code>wp_signon()</code> if you wish.) </p>\n" } ]
2015/12/30
[ "https://wordpress.stackexchange.com/questions/213266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38848/" ]
I want to be able to login to wordpress through a customized function, no dashboard etc showing. I just want the user being logged in and then I want to handle stuff like customized forms, update stuff into db etc for a specific logged in user. I thought `wp_signon`() looked like a good alternative, but it opens up the dashboard menu that I really didn't want it to. Is there a possible way not show dashboard-menu when logged in (basically show nothing, just being logged in with a cookie) as a client? When I log in as adminstrator (through /wp-admin) I want the "normal" functionality with dashboard etc. Is this possible?
I assume you're referring to the black bar that may run across the top of a web page. That's called the 'Toolbar'. However, an earlier version of it was called the 'Admin Bar', and that name is still used in the code. To never display it, add this to `functions.php` ``` function my_function_admin_bar(){ return false; } add_filter( 'show_admin_bar' , 'my_function_admin_bar'); ``` or to just show the bar for admins ``` function my_function_admin_bar($content) { return ( current_user_can( 'administrator' ) ) ? $content : false; } add_filter( 'show_admin_bar' , 'my_function_admin_bar'); ``` (Or similarly in a plugin.) See [the Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/show_admin_bar). (Also, you should be able to use `wp_signon()` if you wish.)
213,272
<p>Basically, I have this line of code:</p> <pre><code>&lt;?php echo do_shortcode('[O_U user_name="operator" blocked_message="This page is restricted for guests."] **Content Goes here** [/O_U]'); ?&gt; </code></pre> <p>Now, inside Content Goes here I use regular HTML to create my content. But, now, I need to add some php inside that HTML. </p> <p>Right now, I need to populate the <em>option</em> for <strong>select</strong> tag with MySQL results.</p> <p>I have a php code:</p> <pre><code>&lt;?php $database_name = "rams"; $mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST); $mydb -&gt; show_errors(); //Populate languages $languages = $mydb -&gt; get_results( 'SELECT * FROM language_skills' ); foreach ($languages as $language){ //do some echo of html } ?&gt; </code></pre> <p>How can I achieve a result here? I now, echo waits for a string there. I thought about heredoc and a custom function, but I can't seem to achieve the result.</p> <p><strong>UPDATE:</strong></p> <p>I managed to get my data. It's in an array. How I can show all the array results in above situation? </p> <p>My array goes something like this:</p> <pre><code>&lt;option value="$value"&gt;$content&lt;/option&gt; </code></pre> <p>It shows exactly what I want when I use:</p> <pre><code>[shortcode].$array[index].[/shortcode] </code></pre> <p>How can I add all the indexes? I tried for each but it doesn't work in between shortcodes</p> <p>ANSWER: </p> <p>I used implode to change array to a string and code now works as i want.</p>
[ { "answer_id": 213269, "author": "bestprogrammerintheworld", "author_id": 38848, "author_profile": "https://wordpress.stackexchange.com/users/38848", "pm_score": 0, "selected": false, "text": "<p>I found an answer to this myself... if someone stumbles upon the same issue. I installed a plugin called Admin Menu Editor:\n<a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow\">https://wordpress.org/plugins/admin-menu-editor/</a></p>\n\n<p>...and in the settings for this plugin I set capability level Administrator for Panel and then the client users I set to another role.</p>\n" }, { "answer_id": 325611, "author": "Loren Rosen", "author_id": 158993, "author_profile": "https://wordpress.stackexchange.com/users/158993", "pm_score": 2, "selected": false, "text": "<p>I assume you're referring to the black bar that may run across the top of a web page. That's called the 'Toolbar'. However, an earlier version of it was called the 'Admin Bar', and that name is still used in the code.\nTo never display it, add this to <code>functions.php</code></p>\n\n<pre><code>function my_function_admin_bar(){\n return false;\n}\nadd_filter( 'show_admin_bar' , 'my_function_admin_bar');\n</code></pre>\n\n<p>or to just show the bar for admins</p>\n\n<pre><code>function my_function_admin_bar($content) {\n return ( current_user_can( 'administrator' ) ) ? $content : false;\n}\nadd_filter( 'show_admin_bar' , 'my_function_admin_bar');\n</code></pre>\n\n<p>(Or similarly in a plugin.)</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/show_admin_bar\" rel=\"nofollow noreferrer\">the Codex</a>.</p>\n\n<p>(Also, you should be able to use <code>wp_signon()</code> if you wish.) </p>\n" } ]
2015/12/30
[ "https://wordpress.stackexchange.com/questions/213272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85213/" ]
Basically, I have this line of code: ``` <?php echo do_shortcode('[O_U user_name="operator" blocked_message="This page is restricted for guests."] **Content Goes here** [/O_U]'); ?> ``` Now, inside Content Goes here I use regular HTML to create my content. But, now, I need to add some php inside that HTML. Right now, I need to populate the *option* for **select** tag with MySQL results. I have a php code: ``` <?php $database_name = "rams"; $mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST); $mydb -> show_errors(); //Populate languages $languages = $mydb -> get_results( 'SELECT * FROM language_skills' ); foreach ($languages as $language){ //do some echo of html } ?> ``` How can I achieve a result here? I now, echo waits for a string there. I thought about heredoc and a custom function, but I can't seem to achieve the result. **UPDATE:** I managed to get my data. It's in an array. How I can show all the array results in above situation? My array goes something like this: ``` <option value="$value">$content</option> ``` It shows exactly what I want when I use: ``` [shortcode].$array[index].[/shortcode] ``` How can I add all the indexes? I tried for each but it doesn't work in between shortcodes ANSWER: I used implode to change array to a string and code now works as i want.
I assume you're referring to the black bar that may run across the top of a web page. That's called the 'Toolbar'. However, an earlier version of it was called the 'Admin Bar', and that name is still used in the code. To never display it, add this to `functions.php` ``` function my_function_admin_bar(){ return false; } add_filter( 'show_admin_bar' , 'my_function_admin_bar'); ``` or to just show the bar for admins ``` function my_function_admin_bar($content) { return ( current_user_can( 'administrator' ) ) ? $content : false; } add_filter( 'show_admin_bar' , 'my_function_admin_bar'); ``` (Or similarly in a plugin.) See [the Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/show_admin_bar). (Also, you should be able to use `wp_signon()` if you wish.)
213,280
<p>I am trying to create some custom database table on wordpress plugin activation with php OOP concept. But no database is created after plugin activation. Here is my code</p> <pre><code>class wpe_Main { public function __construct() { register_activation_hook( __FILE__, array($this,'create_wpe_enquiry_table')); } public function create_wpe_enquiry_table(){ global $wpdb; $sql_enquiry = "CREATE TABLE IF NOT EXISTS {$wpdb-&gt;prefix}wpe_enquiry ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `userid` int(11) NOT NULL, `enquiry_type_id` varchar(3) NOT NULL, `contact_email` varchar(200) NOT NULL, `contact_number` varchar(50) NOT NULL, `contact_messenger` varchar(200) NOT NULL, `query_title` varchar(200) NOT NULL, `query_content` text NOT NULL, `attachment1` varchar(200) NOT NULL, `attachment2` varchar(200) NOT NULL, `attachment3` varchar(200) NOT NULL, `user_ip` varchar(50) NOT NULL, `query_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP, `query_udate` DATETIME ON UPDATE CURRENT_TIMESTAMP, `status` varchar(2) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; $sql_enquiry_reply = "CREATE TABLE IF NOT EXISTS {$wpdb-&gt;prefix}wpe_query_reply ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `quiry_id` int(11) NOT NULL, `reply_content` text NOT NULL, `user_ip` varchar(50) NOT NULL, `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP, `reply_udate` DATETIME ON UPDATE CURRENT_TIMESTAMP, `status` varchar(2) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; $sql_enquiry_type = "CREATE TABLE IF NOT EXISTS {$wpdb-&gt;prefix}wpe_query_part ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `part_value` int(11) NOT NULL, `part_name` varchar(200) NOT NULL, `user_ip` varchar(50) NOT NULL, `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql_enquiry ); dbDelta( $sql_enquiry_reply ); dbDelta( $sql_enquiry_type ); } } $wpuf = new wpe_Main(); </code></pre>
[ { "answer_id": 213285, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 2, "selected": true, "text": "<p>Is your class <code>wpe_Main</code> file is the mail file of the plugin?</p>\n\n<p>Because <code>__FILE__</code> should return main plugin file path. So if your <code>wpe_Main</code> class is in a sub directory then the register activation won't work.</p>\n\n<p>If you want you can try like below to avoid <code>__FILE__</code> confusion</p>\n\n<p>Plugin path: <code>wp-content/plugin/sampleplugin/sample.php</code></p>\n\n<p>Then the hook should be like below</p>\n\n<pre><code>register_activation_hook( 'sampleplugin/sample.php', \narray($this,'create_wpe_enquiry_table'));\n</code></pre>\n\n<p><strong>Updated</strong> after comments</p>\n\n<p>If Your class in main plugin file then <strong>for sure</strong> the function is executing on plugin activation. Your table are not creating might be SQL error or typos. So please check the function responsible for creating table. </p>\n\n<p>For simple testing on activation function try the below code </p>\n\n<pre><code>update_option('activation_test','its working');\n</code></pre>\n\n<p>then check the options, you can see that it should been updated or you can even send mail to test.</p>\n\n<p>Testing the activation function is your conviniens. At the end <code>register_activation_hook</code> <strong>will work on OOPS without any problem</strong>. Check <a href=\"https://codex.wordpress.org/Function_Reference/register_activation_hook#Examples\" rel=\"nofollow\">Reference</a></p>\n" }, { "answer_id": 213373, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You're not using the real powers of <code>dbDelta()</code> here, when you use the <code>IF NOT EXISTS</code> clause.</p>\n\n<h2>With the <code>IF NOT EXISTS</code> clause</h2>\n\n<p>When you use the <code>IF NOT EXISTS</code> check in:</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS\n</code></pre>\n\n<p>then <code>dbDelta()</code> will do the following matches:</p>\n\n<pre><code>if ( preg_match( \"|CREATE TABLE ([^ ]*)|\", $qry, $matches ) ) {\n $cqueries[ trim( $matches[1], '`' ) ] = $qry;\n</code></pre>\n\n<p>Here <code>$matches</code> is:</p>\n\n<pre><code>Array\n(\n [0] =&gt; CREATE TABLE IF\n [1] =&gt; IF\n)\n</code></pre>\n\n<p>and </p>\n\n<pre><code>trim( $matches[1], '`' )\n</code></pre>\n\n<p>gives the table name <code>IF</code>.</p>\n\n<p>Then it will try to find it's fields with:</p>\n\n<pre><code>$tablefields = $wpdb-&gt;get_results(\"DESCRIBE {$table};\");\n</code></pre>\n\n<p>or <code>DESCRIBE IF</code> that will (hopefully) not give any results. Thus <code>dbDelta()</code> will only try to run the raw creation query but skip any possible future updates to the table structure.</p>\n\n<h2>Without the <code>IF NOT EXISTS</code> clause</h2>\n\n<p>If you remove the <code>IF NOT EXISTS</code> part, then the first runtime, for e.g. the <code>wp_wpe_query_part</code> table, will be</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS wp_wpe_query_part (\n `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n `part_value` int(11) NOT NULL,\n `part_name` varchar(200) NOT NULL,\n `user_ip` varchar(50) NOT NULL,\n `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8\n</code></pre>\n\n<p>and for the second runtime, when the table already exists, we will get these queries:</p>\n\n<pre><code>DESCRIBE wp_wpe_query_part;\n\nSHOW INDEX FROM wp_wpe_query_part;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN id `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN part_value `part_value` int(11) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN part_name `part_name` varchar(200) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN user_ip `user_ip` varchar(50) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN reply_cdate `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP;\n</code></pre>\n\n<p>If we later make some changes to the table structure, it will then modify the current table accordingly.</p>\n" } ]
2015/12/30
[ "https://wordpress.stackexchange.com/questions/213280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86047/" ]
I am trying to create some custom database table on wordpress plugin activation with php OOP concept. But no database is created after plugin activation. Here is my code ``` class wpe_Main { public function __construct() { register_activation_hook( __FILE__, array($this,'create_wpe_enquiry_table')); } public function create_wpe_enquiry_table(){ global $wpdb; $sql_enquiry = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wpe_enquiry ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `userid` int(11) NOT NULL, `enquiry_type_id` varchar(3) NOT NULL, `contact_email` varchar(200) NOT NULL, `contact_number` varchar(50) NOT NULL, `contact_messenger` varchar(200) NOT NULL, `query_title` varchar(200) NOT NULL, `query_content` text NOT NULL, `attachment1` varchar(200) NOT NULL, `attachment2` varchar(200) NOT NULL, `attachment3` varchar(200) NOT NULL, `user_ip` varchar(50) NOT NULL, `query_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP, `query_udate` DATETIME ON UPDATE CURRENT_TIMESTAMP, `status` varchar(2) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; $sql_enquiry_reply = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wpe_query_reply ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `quiry_id` int(11) NOT NULL, `reply_content` text NOT NULL, `user_ip` varchar(50) NOT NULL, `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP, `reply_udate` DATETIME ON UPDATE CURRENT_TIMESTAMP, `status` varchar(2) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; $sql_enquiry_type = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}wpe_query_part ( `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `part_value` int(11) NOT NULL, `part_name` varchar(200) NOT NULL, `user_ip` varchar(50) NOT NULL, `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql_enquiry ); dbDelta( $sql_enquiry_reply ); dbDelta( $sql_enquiry_type ); } } $wpuf = new wpe_Main(); ```
Is your class `wpe_Main` file is the mail file of the plugin? Because `__FILE__` should return main plugin file path. So if your `wpe_Main` class is in a sub directory then the register activation won't work. If you want you can try like below to avoid `__FILE__` confusion Plugin path: `wp-content/plugin/sampleplugin/sample.php` Then the hook should be like below ``` register_activation_hook( 'sampleplugin/sample.php', array($this,'create_wpe_enquiry_table')); ``` **Updated** after comments If Your class in main plugin file then **for sure** the function is executing on plugin activation. Your table are not creating might be SQL error or typos. So please check the function responsible for creating table. For simple testing on activation function try the below code ``` update_option('activation_test','its working'); ``` then check the options, you can see that it should been updated or you can even send mail to test. Testing the activation function is your conviniens. At the end `register_activation_hook` **will work on OOPS without any problem**. Check [Reference](https://codex.wordpress.org/Function_Reference/register_activation_hook#Examples)
213,300
<p>I'm writing a WP CLI command which creates and updates taxonomies using <code>wp_insert_term</code>. Actions on my custom taxonomies are not accepted since they don't show up as registered.</p> <p>The wp-cli included <a href="https://github.com/wp-cli/wp-cli/blob/2ad47776f13cac8cf14c3ba669036b378f879cf1/php/commands/term.php" rel="nofollow">Term_Command</a> itself uses <code>wp_insert_term</code> and allows actions on default taxonomies but errors on custom taxonomies.</p> <p>Various searches suggest custom taxonomies aren't registered until <code>init</code>. Is there a way to run <code>init</code> inside wp-cli so custom taxonomies can be manipulated? Anyone got any other ideas?</p>
[ { "answer_id": 213285, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 2, "selected": true, "text": "<p>Is your class <code>wpe_Main</code> file is the mail file of the plugin?</p>\n\n<p>Because <code>__FILE__</code> should return main plugin file path. So if your <code>wpe_Main</code> class is in a sub directory then the register activation won't work.</p>\n\n<p>If you want you can try like below to avoid <code>__FILE__</code> confusion</p>\n\n<p>Plugin path: <code>wp-content/plugin/sampleplugin/sample.php</code></p>\n\n<p>Then the hook should be like below</p>\n\n<pre><code>register_activation_hook( 'sampleplugin/sample.php', \narray($this,'create_wpe_enquiry_table'));\n</code></pre>\n\n<p><strong>Updated</strong> after comments</p>\n\n<p>If Your class in main plugin file then <strong>for sure</strong> the function is executing on plugin activation. Your table are not creating might be SQL error or typos. So please check the function responsible for creating table. </p>\n\n<p>For simple testing on activation function try the below code </p>\n\n<pre><code>update_option('activation_test','its working');\n</code></pre>\n\n<p>then check the options, you can see that it should been updated or you can even send mail to test.</p>\n\n<p>Testing the activation function is your conviniens. At the end <code>register_activation_hook</code> <strong>will work on OOPS without any problem</strong>. Check <a href=\"https://codex.wordpress.org/Function_Reference/register_activation_hook#Examples\" rel=\"nofollow\">Reference</a></p>\n" }, { "answer_id": 213373, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You're not using the real powers of <code>dbDelta()</code> here, when you use the <code>IF NOT EXISTS</code> clause.</p>\n\n<h2>With the <code>IF NOT EXISTS</code> clause</h2>\n\n<p>When you use the <code>IF NOT EXISTS</code> check in:</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS\n</code></pre>\n\n<p>then <code>dbDelta()</code> will do the following matches:</p>\n\n<pre><code>if ( preg_match( \"|CREATE TABLE ([^ ]*)|\", $qry, $matches ) ) {\n $cqueries[ trim( $matches[1], '`' ) ] = $qry;\n</code></pre>\n\n<p>Here <code>$matches</code> is:</p>\n\n<pre><code>Array\n(\n [0] =&gt; CREATE TABLE IF\n [1] =&gt; IF\n)\n</code></pre>\n\n<p>and </p>\n\n<pre><code>trim( $matches[1], '`' )\n</code></pre>\n\n<p>gives the table name <code>IF</code>.</p>\n\n<p>Then it will try to find it's fields with:</p>\n\n<pre><code>$tablefields = $wpdb-&gt;get_results(\"DESCRIBE {$table};\");\n</code></pre>\n\n<p>or <code>DESCRIBE IF</code> that will (hopefully) not give any results. Thus <code>dbDelta()</code> will only try to run the raw creation query but skip any possible future updates to the table structure.</p>\n\n<h2>Without the <code>IF NOT EXISTS</code> clause</h2>\n\n<p>If you remove the <code>IF NOT EXISTS</code> part, then the first runtime, for e.g. the <code>wp_wpe_query_part</code> table, will be</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS wp_wpe_query_part (\n `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n `part_value` int(11) NOT NULL,\n `part_name` varchar(200) NOT NULL,\n `user_ip` varchar(50) NOT NULL,\n `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8\n</code></pre>\n\n<p>and for the second runtime, when the table already exists, we will get these queries:</p>\n\n<pre><code>DESCRIBE wp_wpe_query_part;\n\nSHOW INDEX FROM wp_wpe_query_part;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN id `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN part_value `part_value` int(11) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN part_name `part_name` varchar(200) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN user_ip `user_ip` varchar(50) NOT NULL;\n\nALTER TABLE wp_wpe_query_partCHANGE COLUMN reply_cdate `reply_cdate` DATETIME DEFAULT CURRENT_TIMESTAMP;\n</code></pre>\n\n<p>If we later make some changes to the table structure, it will then modify the current table accordingly.</p>\n" } ]
2015/12/30
[ "https://wordpress.stackexchange.com/questions/213300", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/737/" ]
I'm writing a WP CLI command which creates and updates taxonomies using `wp_insert_term`. Actions on my custom taxonomies are not accepted since they don't show up as registered. The wp-cli included [Term\_Command](https://github.com/wp-cli/wp-cli/blob/2ad47776f13cac8cf14c3ba669036b378f879cf1/php/commands/term.php) itself uses `wp_insert_term` and allows actions on default taxonomies but errors on custom taxonomies. Various searches suggest custom taxonomies aren't registered until `init`. Is there a way to run `init` inside wp-cli so custom taxonomies can be manipulated? Anyone got any other ideas?
Is your class `wpe_Main` file is the mail file of the plugin? Because `__FILE__` should return main plugin file path. So if your `wpe_Main` class is in a sub directory then the register activation won't work. If you want you can try like below to avoid `__FILE__` confusion Plugin path: `wp-content/plugin/sampleplugin/sample.php` Then the hook should be like below ``` register_activation_hook( 'sampleplugin/sample.php', array($this,'create_wpe_enquiry_table')); ``` **Updated** after comments If Your class in main plugin file then **for sure** the function is executing on plugin activation. Your table are not creating might be SQL error or typos. So please check the function responsible for creating table. For simple testing on activation function try the below code ``` update_option('activation_test','its working'); ``` then check the options, you can see that it should been updated or you can even send mail to test. Testing the activation function is your conviniens. At the end `register_activation_hook` **will work on OOPS without any problem**. Check [Reference](https://codex.wordpress.org/Function_Reference/register_activation_hook#Examples)
213,324
<p>I have a Wordpress menu that I am using as a Hamburger menu for smaller mobile devices. Since there really isn't a "hover" event for touch devices, I have changed the main menu items to show their corresponding sub menus on "click" (or "touch"). The problem is that I can't make the main menu items clickable. Also, I don't see an option in "wp_nav_menu" to show the top level item on the submenu. That is how I would be inclined to use it. I need a workaround or something like that.</p>
[ { "answer_id": 213327, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 1, "selected": false, "text": "<p>You could solve this with other nasty hacks but here's <em>kind of</em> WordPress way:</p>\n\n<p><strong>In your <code>header.php</code></strong></p>\n\n<pre><code>&lt;?php\n// User is not using mobile\nif( ! wp_is_mobile() ) {\n\n wp_nav_menu(); // Your \"original menu\" \n}\n// User is using mobile\nelse if( wp_is_mobile() ) {\n\n wp_nav_menu(); // Your another menu that only has top level items\n}\n?&gt;\n</code></pre>\n\n<p>Keep in mind that <code>wp_is_mobile()</code> also considers tablets as mobile devices and you should always carefully think this through because if PC window is resized to small / narrow -> it obviously doesn't count it as mobile.</p>\n\n<p><strong>And jQuery to disable your click event:</strong></p>\n\n<pre><code>var isMobile = false;\n\n// Check if user is using mobile device\nif (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {\n\n isMobile = true;\n}\n\nif( ! isMobile ) {\n\n // Your usual click event\n}\n</code></pre>\n" }, { "answer_id": 213328, "author": "The Hawk", "author_id": 85560, "author_profile": "https://wordpress.stackexchange.com/users/85560", "pm_score": 0, "selected": false, "text": "<p>This works well. The second click goes to the page...</p>\n\n<pre><code>$(\".smallNavigation &gt; ul &gt; li &gt; a\").click(function (e) {\n\n $(\"ul.sub-menu\").hide();\n $(\"ul.sub-menu\", $(this).parent(\"li\")).show();\n\n e.preventDefault();\n $(this).unbind(e);\n\n})\n</code></pre>\n" } ]
2015/12/30
[ "https://wordpress.stackexchange.com/questions/213324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85560/" ]
I have a Wordpress menu that I am using as a Hamburger menu for smaller mobile devices. Since there really isn't a "hover" event for touch devices, I have changed the main menu items to show their corresponding sub menus on "click" (or "touch"). The problem is that I can't make the main menu items clickable. Also, I don't see an option in "wp\_nav\_menu" to show the top level item on the submenu. That is how I would be inclined to use it. I need a workaround or something like that.
You could solve this with other nasty hacks but here's *kind of* WordPress way: **In your `header.php`** ``` <?php // User is not using mobile if( ! wp_is_mobile() ) { wp_nav_menu(); // Your "original menu" } // User is using mobile else if( wp_is_mobile() ) { wp_nav_menu(); // Your another menu that only has top level items } ?> ``` Keep in mind that `wp_is_mobile()` also considers tablets as mobile devices and you should always carefully think this through because if PC window is resized to small / narrow -> it obviously doesn't count it as mobile. **And jQuery to disable your click event:** ``` var isMobile = false; // Check if user is using mobile device if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { isMobile = true; } if( ! isMobile ) { // Your usual click event } ```
213,342
<p>I have tried below script to load jQuery UI Autocomplete in theme. But it doesn't load their related scripts. How should I call it to work.</p> <pre><code>wp_enqueue_script('jquery-ui-autocomplete'); </code></pre> <p>I think below scripts are jQuery UI related scripts for autocomplete but it's doesn't load.</p> <pre><code>&lt;script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.core.min.js?ver=1.10.2'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.widget.min.js?ver=1.10.2'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.position.min.js?ver=1.10.2'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.menu.min.js?ver=1.10.2'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.autocomplete.min.js?ver=1.10.2'&gt;&lt;/script&gt; </code></pre>
[ { "answer_id": 213327, "author": "N00b", "author_id": 80903, "author_profile": "https://wordpress.stackexchange.com/users/80903", "pm_score": 1, "selected": false, "text": "<p>You could solve this with other nasty hacks but here's <em>kind of</em> WordPress way:</p>\n\n<p><strong>In your <code>header.php</code></strong></p>\n\n<pre><code>&lt;?php\n// User is not using mobile\nif( ! wp_is_mobile() ) {\n\n wp_nav_menu(); // Your \"original menu\" \n}\n// User is using mobile\nelse if( wp_is_mobile() ) {\n\n wp_nav_menu(); // Your another menu that only has top level items\n}\n?&gt;\n</code></pre>\n\n<p>Keep in mind that <code>wp_is_mobile()</code> also considers tablets as mobile devices and you should always carefully think this through because if PC window is resized to small / narrow -> it obviously doesn't count it as mobile.</p>\n\n<p><strong>And jQuery to disable your click event:</strong></p>\n\n<pre><code>var isMobile = false;\n\n// Check if user is using mobile device\nif (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {\n\n isMobile = true;\n}\n\nif( ! isMobile ) {\n\n // Your usual click event\n}\n</code></pre>\n" }, { "answer_id": 213328, "author": "The Hawk", "author_id": 85560, "author_profile": "https://wordpress.stackexchange.com/users/85560", "pm_score": 0, "selected": false, "text": "<p>This works well. The second click goes to the page...</p>\n\n<pre><code>$(\".smallNavigation &gt; ul &gt; li &gt; a\").click(function (e) {\n\n $(\"ul.sub-menu\").hide();\n $(\"ul.sub-menu\", $(this).parent(\"li\")).show();\n\n e.preventDefault();\n $(this).unbind(e);\n\n})\n</code></pre>\n" } ]
2015/12/31
[ "https://wordpress.stackexchange.com/questions/213342", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85145/" ]
I have tried below script to load jQuery UI Autocomplete in theme. But it doesn't load their related scripts. How should I call it to work. ``` wp_enqueue_script('jquery-ui-autocomplete'); ``` I think below scripts are jQuery UI related scripts for autocomplete but it's doesn't load. ``` <script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.core.min.js?ver=1.10.2'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.widget.min.js?ver=1.10.2'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.position.min.js?ver=1.10.2'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.menu.min.js?ver=1.10.2'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-includes/js/jquery/ui/jquery.ui.autocomplete.min.js?ver=1.10.2'></script> ```
You could solve this with other nasty hacks but here's *kind of* WordPress way: **In your `header.php`** ``` <?php // User is not using mobile if( ! wp_is_mobile() ) { wp_nav_menu(); // Your "original menu" } // User is using mobile else if( wp_is_mobile() ) { wp_nav_menu(); // Your another menu that only has top level items } ?> ``` Keep in mind that `wp_is_mobile()` also considers tablets as mobile devices and you should always carefully think this through because if PC window is resized to small / narrow -> it obviously doesn't count it as mobile. **And jQuery to disable your click event:** ``` var isMobile = false; // Check if user is using mobile device if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { isMobile = true; } if( ! isMobile ) { // Your usual click event } ```
213,354
<p>I'm trying to update the Advanced Custom Fields meta value associated with a custom taxonomy term</p> <pre><code>$term_status = wp_update_term( $rate_id, 'rate', $term_data ); $term_id = $term_status['term_taxonomy_id']; update_field( 'field_56829855eebc9',$rate_daily,$term_id ); </code></pre> <p>However, I'm not getting the field updated. I have tried the field name instead of the field key too.</p>
[ { "answer_id": 213358, "author": "Seen Dru", "author_id": 85739, "author_profile": "https://wordpress.stackexchange.com/users/85739", "pm_score": 4, "selected": true, "text": "<p>I figured it out somehow.. </p>\n\n<p>Syntax of <code>update_field()</code>:</p>\n\n<p><code>update_field($field_key, $value, $post_id)</code></p>\n\n<p>MY MISTAKE:\nI was using the wrong parameter for the <code>$post_id</code> which i thought was the Term Id of the custom taxonomy term.</p>\n\n<p>CORRECT USAGE: rather than using term id (<code>$term_id</code> in my question), one should use a string with the taxonomy preppended to the $term_id </p>\n\n<p>ie <code>$post_id</code> = <code>$taxonomy.'_'.$term_id</code></p>\n\n<p>for eg: if your custom taxonomy is <code>foo</code> and the term id is <code>123</code></p>\n\n<p>then : <code>$post_id = foo_123</code></p>\n\n<p>Hope this is helpful for someone.</p>\n\n<p>This is the first time I'm asking/answering a question here. </p>\n" }, { "answer_id": 268802, "author": "Grayaa Hammed", "author_id": 120904, "author_profile": "https://wordpress.stackexchange.com/users/120904", "pm_score": 0, "selected": false, "text": "<p>Only this worked for me:</p>\n\n<pre><code>update_term_meta($term_id, $field['name'], $value);\n</code></pre>\n\n<p>In my case i have an \"author\" taxonomy with a custom field called \"institution\", so i did:</p>\n\n<pre><code>$my_author_taxonomy = get_term_by( \"name\", $author_taxonomy_name, 'author' ); \nupdate_term_meta($my_author_taxonomy-&gt;term_id, \"institution\", $Institution);\n</code></pre>\n\n<p>I hope it will help someone :)</p>\n" }, { "answer_id": 305144, "author": "That Brazilian Guy", "author_id": 22510, "author_profile": "https://wordpress.stackexchange.com/users/22510", "pm_score": 0, "selected": false, "text": "<p>I had success using <a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\">wp_set_object_terms</a>, as suggested by the <a href=\"https://support.advancedcustomfields.com/forums/topic/update_field-for-taxonomy-field-type/\" rel=\"nofollow noreferrer\">official ACF support</a>.</p>\n" } ]
2015/12/31
[ "https://wordpress.stackexchange.com/questions/213354", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85739/" ]
I'm trying to update the Advanced Custom Fields meta value associated with a custom taxonomy term ``` $term_status = wp_update_term( $rate_id, 'rate', $term_data ); $term_id = $term_status['term_taxonomy_id']; update_field( 'field_56829855eebc9',$rate_daily,$term_id ); ``` However, I'm not getting the field updated. I have tried the field name instead of the field key too.
I figured it out somehow.. Syntax of `update_field()`: `update_field($field_key, $value, $post_id)` MY MISTAKE: I was using the wrong parameter for the `$post_id` which i thought was the Term Id of the custom taxonomy term. CORRECT USAGE: rather than using term id (`$term_id` in my question), one should use a string with the taxonomy preppended to the $term\_id ie `$post_id` = `$taxonomy.'_'.$term_id` for eg: if your custom taxonomy is `foo` and the term id is `123` then : `$post_id = foo_123` Hope this is helpful for someone. This is the first time I'm asking/answering a question here.
213,367
<p>I use the conditonal function <strong>is_singular($my_post_type)</strong> inside my plugin and it is very convenient. The problem is that is doesn't work backend.</p> <p>Is there an alternative that works frontend &amp; backend ? Thanks !</p>
[ { "answer_id": 213376, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p>No. There is no equivalent to <code>is_singular()</code> for backend pages, possible because there are no equivalents to \"singuler\" pages on the backend. You don't say what you want to achieve here, but I'd guess you probably want to exploit the <code>admin_head-$hook_suffix</code> hooks that fire in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-admin/admin-header.php\" rel=\"nofollow\"><code>admin-header.php</code></a></p>\n\n<pre><code>122 /**\n123 * Fires in head section for a specific admin page.\n124 *\n125 * The dynamic portion of the hook, `$hook_suffix`, refers to the hook suffix\n126 * for the admin page.\n127 *\n128 * @since 2.1.0\n129 */\n130 do_action( \"admin_head-$hook_suffix\" );\n</code></pre>\n" }, { "answer_id": 213381, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 1, "selected": false, "text": "<p>If you conditionally want to load any scripts for your post type then following may be useful.</p>\n\n<pre><code>function my_enqueue($hook) {\n\n global $current_screen;\n\n /* Check if the post being added/edited is a Custom Post Type which you want */\n\n if ( ( 'post.php' == $hook || 'post-new.php' == $hook ) &amp;&amp; 'hire' == $current_screen-&gt;post_type )\n\n wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . '/js/myscript.js' );\n}\nadd_action( 'admin_enqueue_scripts', 'my_enqueue' );\n</code></pre>\n" }, { "answer_id": 289346, "author": "gordie", "author_id": 70449, "author_profile": "https://wordpress.stackexchange.com/users/70449", "pm_score": 3, "selected": false, "text": "<p>Here's what I use now:</p>\n\n<pre><code>function custom_singular_backend(){\n $screen = get_current_screen();\n\n if ( ( $screen-&gt;base == 'post' ) &amp;&amp; ( $screen-&gt;post_type == POSTTYPE ) ){\n //...\n }\n}\nadd_action( 'current_screen','custom_singular_backend');\n</code></pre>\n" } ]
2015/12/31
[ "https://wordpress.stackexchange.com/questions/213367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70449/" ]
I use the conditonal function **is\_singular($my\_post\_type)** inside my plugin and it is very convenient. The problem is that is doesn't work backend. Is there an alternative that works frontend & backend ? Thanks !
Here's what I use now: ``` function custom_singular_backend(){ $screen = get_current_screen(); if ( ( $screen->base == 'post' ) && ( $screen->post_type == POSTTYPE ) ){ //... } } add_action( 'current_screen','custom_singular_backend'); ```
213,369
<p>I have a post type called 'Writers' and another post type called 'Documents'.</p> <p>I use the Relationship field in Advanced Custom Fields to link a list of Writers (post objects) to a Document. This means that the field is basically an array containing multiple writers (some contain only one).</p> <p>I have a template in my theme where I display additional information for each Writer inside their individual posts. I would like to display a list of documents they have contributed to (i.e. Posts containing the writer's name in the relationship field).</p> <p>I have tried the following query but it doesn't work:</p> <pre><code>$item = 0; $writerName = get_the_title(); $my_contributions = new WP_Query( array( 'post_type' =&gt; 'documents', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'doc_contributors', 'meta_value' =&gt; $writerName, 'meta_compare' =&gt; 'LIKE' ) ); if( $my_contributions-&gt;have_posts() ) : while( $my_contributions-&gt;have_posts() ) : $my_contributions-&gt;the_post(); $item++; ?&gt; &lt;div class="list-line margint10 clearfix"&gt; &lt;?php echo esc_attr( $item ) . ". " ?&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php get_the_title( $my_contributions-&gt;ID ); ?&gt;&lt;/a&gt; &lt;br /&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_query(); </code></pre>
[ { "answer_id": 213375, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 5, "selected": true, "text": "<p>I am updating my complete answer based on your clarification in the comment below. I hope this helps:</p>\n\n<pre><code>&lt;div class=\"entry-content\"&gt;\n\n &lt;h2&gt;Documents written by this writer&lt;/h2&gt;\n &lt;?php \n /*\n * Query posts for a relationship value.\n * This method uses the meta_query LIKE to match the string \"123\" to the database value a:1:{i:0;s:3:\"123\";} (serialized array)\n */\n\n $documents = get_posts(array(\n 'post_type' =&gt; 'document',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'writer', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n )\n ));\n\n ?&gt;\n &lt;?php if( $documents ): ?&gt;\n &lt;ul&gt;\n &lt;?php foreach( $documents as $document ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo get_permalink( $document-&gt;ID ); ?&gt;\"&gt;\n &lt;?php echo get_the_title( $document-&gt;ID ); ?&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;?php endif; ?&gt;\n\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 377097, "author": "Australianreindeer", "author_id": 195626, "author_profile": "https://wordpress.stackexchange.com/users/195626", "pm_score": 0, "selected": false, "text": "<p>If someone has problems with displaying more than 5 results, here's a small tweak.</p>\n<pre><code>$documents = get_posts(array(\n 'post_type' =&gt; 'document',\n 'posts_per_page' =&gt; -1, //add this line\n</code></pre>\n" } ]
2015/12/31
[ "https://wordpress.stackexchange.com/questions/213369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86102/" ]
I have a post type called 'Writers' and another post type called 'Documents'. I use the Relationship field in Advanced Custom Fields to link a list of Writers (post objects) to a Document. This means that the field is basically an array containing multiple writers (some contain only one). I have a template in my theme where I display additional information for each Writer inside their individual posts. I would like to display a list of documents they have contributed to (i.e. Posts containing the writer's name in the relationship field). I have tried the following query but it doesn't work: ``` $item = 0; $writerName = get_the_title(); $my_contributions = new WP_Query( array( 'post_type' => 'documents', 'posts_per_page' => -1, 'meta_key' => 'doc_contributors', 'meta_value' => $writerName, 'meta_compare' => 'LIKE' ) ); if( $my_contributions->have_posts() ) : while( $my_contributions->have_posts() ) : $my_contributions->the_post(); $item++; ?> <div class="list-line margint10 clearfix"> <?php echo esc_attr( $item ) . ". " ?><a href="<?php the_permalink(); ?>"><?php get_the_title( $my_contributions->ID ); ?></a> <br /> </div> <?php endwhile; endif; wp_reset_query(); ```
I am updating my complete answer based on your clarification in the comment below. I hope this helps: ``` <div class="entry-content"> <h2>Documents written by this writer</h2> <?php /* * Query posts for a relationship value. * This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array) */ $documents = get_posts(array( 'post_type' => 'document', 'meta_query' => array( array( 'key' => 'writer', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) ) )); ?> <?php if( $documents ): ?> <ul> <?php foreach( $documents as $document ): ?> <li> <a href="<?php echo get_permalink( $document->ID ); ?>"> <?php echo get_the_title( $document->ID ); ?> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> </div> ```
213,390
<p>I am letting users upload avatars which are stored within the uploads folder inside the avatars subfolder which I created. </p> <p>The problem is that avatars are now listed in the media library among other uploaded images.</p> <p>How can I prevent that? </p> <p>I was looking for a filter to filter out what is being displayed but couldn't find one. I wouldn't mind the avatars folder being outside the uploads folder if it has to.</p>
[ { "answer_id": 213375, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 5, "selected": true, "text": "<p>I am updating my complete answer based on your clarification in the comment below. I hope this helps:</p>\n\n<pre><code>&lt;div class=\"entry-content\"&gt;\n\n &lt;h2&gt;Documents written by this writer&lt;/h2&gt;\n &lt;?php \n /*\n * Query posts for a relationship value.\n * This method uses the meta_query LIKE to match the string \"123\" to the database value a:1:{i:0;s:3:\"123\";} (serialized array)\n */\n\n $documents = get_posts(array(\n 'post_type' =&gt; 'document',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'writer', // name of custom field\n 'value' =&gt; '\"' . get_the_ID() . '\"', // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' =&gt; 'LIKE'\n )\n )\n ));\n\n ?&gt;\n &lt;?php if( $documents ): ?&gt;\n &lt;ul&gt;\n &lt;?php foreach( $documents as $document ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo get_permalink( $document-&gt;ID ); ?&gt;\"&gt;\n &lt;?php echo get_the_title( $document-&gt;ID ); ?&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;?php endif; ?&gt;\n\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 377097, "author": "Australianreindeer", "author_id": 195626, "author_profile": "https://wordpress.stackexchange.com/users/195626", "pm_score": 0, "selected": false, "text": "<p>If someone has problems with displaying more than 5 results, here's a small tweak.</p>\n<pre><code>$documents = get_posts(array(\n 'post_type' =&gt; 'document',\n 'posts_per_page' =&gt; -1, //add this line\n</code></pre>\n" } ]
2015/12/31
[ "https://wordpress.stackexchange.com/questions/213390", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86115/" ]
I am letting users upload avatars which are stored within the uploads folder inside the avatars subfolder which I created. The problem is that avatars are now listed in the media library among other uploaded images. How can I prevent that? I was looking for a filter to filter out what is being displayed but couldn't find one. I wouldn't mind the avatars folder being outside the uploads folder if it has to.
I am updating my complete answer based on your clarification in the comment below. I hope this helps: ``` <div class="entry-content"> <h2>Documents written by this writer</h2> <?php /* * Query posts for a relationship value. * This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array) */ $documents = get_posts(array( 'post_type' => 'document', 'meta_query' => array( array( 'key' => 'writer', // name of custom field 'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 'compare' => 'LIKE' ) ) )); ?> <?php if( $documents ): ?> <ul> <?php foreach( $documents as $document ): ?> <li> <a href="<?php echo get_permalink( $document->ID ); ?>"> <?php echo get_the_title( $document->ID ); ?> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> </div> ```
213,408
<p>Today is 2016-01-01 in my console.</p> <pre><code>date Fri Jan 1 14:24:04 CST 2016 </code></pre> <p>Now I write an article attached a photo which is taken today and publish it today. I found that the URL of the photo was displayed as:</p> <pre><code>&lt;a href="http://hwy.local/wp/wp-content/uploads/2015/02/scan.png"&gt; &lt;img src="http://hwy.local/wp/wp-content/uploads/2015/02/scan-169x300.png" alt="scan" width="169" height="300" class="alignnone size-medium wp-image-2098" /&gt; &lt;/a&gt; </code></pre> <p>Why not <code>src="http://hwy.local/wp/wp-content/uploads/2016/01/scan-169x300.png"</code>?</p> <ol> <li>The photo was taken today. </li> <li>I upload it today. </li> <li>The date on my OS is 2016-01-01.</li> </ol> <p>Why is <code>uploads/2015/02/scan-169x300.png</code> in <code>src</code> not <code>uploads/2016/01/scan-169x300.png</code> in the <code>src</code>? </p>
[ { "answer_id": 214348, "author": "Ray Mitchell", "author_id": 2709, "author_profile": "https://wordpress.stackexchange.com/users/2709", "pm_score": 4, "selected": false, "text": "<p>What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015?</p>\n\n<p><a href=\"https://core.trac.wordpress.org/ticket/10752\">https://core.trac.wordpress.org/ticket/10752</a></p>\n" }, { "answer_id": 214349, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If uploaded to some content entity like e.g. post, page or custom post type, WordPress does arrange the attachments uploads by creation date of that entity - and not according to the upload, creation date of the attachment. That might just be the case for you, because otherwise I can't think of a reasonable, related to default behavior, explanation for what you are describing. If that isn't the case, then you have to check for interferences by plug-ins or the theme.</p>\n" }, { "answer_id": 214374, "author": "Syed Priom", "author_id": 48577, "author_profile": "https://wordpress.stackexchange.com/users/48577", "pm_score": 3, "selected": false, "text": "<p>About the assigned folders for uploaded photos -</p>\n\n<ol>\n<li><p>If a photo is uploaded within a post/page, it will be in the folder corresponding to the date of the post/page e.g. if post date is June 2015, uploaded photos will be in /uploads/2015/06 folder.</p></li>\n<li><p>If a photo is uploaded directly in the media library (not within any post/page), it will be in the folder corresponding to upload date e.g. if we upload a photo to library on January 2016, it will be in /uploads/2016/01 folder.</p></li>\n<li><p>We can derive that the date of the photo being taken is not relevant. In the above two cases, it doesn't really matter which date the photo was actually taken.</p></li>\n</ol>\n" } ]
2016/01/01
[ "https://wordpress.stackexchange.com/questions/213408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70405/" ]
Today is 2016-01-01 in my console. ``` date Fri Jan 1 14:24:04 CST 2016 ``` Now I write an article attached a photo which is taken today and publish it today. I found that the URL of the photo was displayed as: ``` <a href="http://hwy.local/wp/wp-content/uploads/2015/02/scan.png"> <img src="http://hwy.local/wp/wp-content/uploads/2015/02/scan-169x300.png" alt="scan" width="169" height="300" class="alignnone size-medium wp-image-2098" /> </a> ``` Why not `src="http://hwy.local/wp/wp-content/uploads/2016/01/scan-169x300.png"`? 1. The photo was taken today. 2. I upload it today. 3. The date on my OS is 2016-01-01. Why is `uploads/2015/02/scan-169x300.png` in `src` not `uploads/2016/01/scan-169x300.png` in the `src`?
What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015? <https://core.trac.wordpress.org/ticket/10752>
213,425
<p>For example, this works:</p> <pre><code>'default' =&gt; '#ffffff' </code></pre> <p>But this does not:</p> <pre><code>$white = '#ffffff'; 'default' =&gt; $white </code></pre> <p>How can I pass variables to key/value pairs?</p> <p>Here is a more complete example for some context:</p> <pre><code>$white = '#ffffff'; $transport = 'refresh'; $wp_customize-&gt;add_setting('mytheme_text_color', array( 'default' =&gt; $white, 'transport' =&gt; $transport )); </code></pre> <p>In reply to jgraup:</p> <p>This code works:</p> <pre><code>$wp_customize-&gt;add_setting('themeone_primary_nav_background_color', array( 'default' =&gt; '#181818', 'transport' =&gt; 'refresh' )); </code></pre> <p>This code doesn't:</p> <pre><code>$args = array('default' =&gt; '#181818', 'transport' =&gt; 'refresh'); $wp_customize-&gt;add_setting('themeone_primary_nav_background_color', $args); </code></pre> <p>When I customize my page colors in the admin section, I should see a "default" color button. In the former code, I see this button. In the latter code, I do not.</p> <p>I have uploaded the file to my google drive if anyone wants to take a look: <a href="https://drive.google.com/open?id=0B01XHUEqiziEcW14WE5NN0VYYlE" rel="nofollow">https://drive.google.com/open?id=0B01XHUEqiziEcW14WE5NN0VYYlE</a></p> <p>And here is a picture of the problem with example output: <a href="https://drive.google.com/file/d/0B01XHUEqiziEUDVyZWFRWGZ0SkE/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B01XHUEqiziEUDVyZWFRWGZ0SkE/view?usp=sharing</a></p>
[ { "answer_id": 214348, "author": "Ray Mitchell", "author_id": 2709, "author_profile": "https://wordpress.stackexchange.com/users/2709", "pm_score": 4, "selected": false, "text": "<p>What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015?</p>\n\n<p><a href=\"https://core.trac.wordpress.org/ticket/10752\">https://core.trac.wordpress.org/ticket/10752</a></p>\n" }, { "answer_id": 214349, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If uploaded to some content entity like e.g. post, page or custom post type, WordPress does arrange the attachments uploads by creation date of that entity - and not according to the upload, creation date of the attachment. That might just be the case for you, because otherwise I can't think of a reasonable, related to default behavior, explanation for what you are describing. If that isn't the case, then you have to check for interferences by plug-ins or the theme.</p>\n" }, { "answer_id": 214374, "author": "Syed Priom", "author_id": 48577, "author_profile": "https://wordpress.stackexchange.com/users/48577", "pm_score": 3, "selected": false, "text": "<p>About the assigned folders for uploaded photos -</p>\n\n<ol>\n<li><p>If a photo is uploaded within a post/page, it will be in the folder corresponding to the date of the post/page e.g. if post date is June 2015, uploaded photos will be in /uploads/2015/06 folder.</p></li>\n<li><p>If a photo is uploaded directly in the media library (not within any post/page), it will be in the folder corresponding to upload date e.g. if we upload a photo to library on January 2016, it will be in /uploads/2016/01 folder.</p></li>\n<li><p>We can derive that the date of the photo being taken is not relevant. In the above two cases, it doesn't really matter which date the photo was actually taken.</p></li>\n</ol>\n" } ]
2016/01/01
[ "https://wordpress.stackexchange.com/questions/213425", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86088/" ]
For example, this works: ``` 'default' => '#ffffff' ``` But this does not: ``` $white = '#ffffff'; 'default' => $white ``` How can I pass variables to key/value pairs? Here is a more complete example for some context: ``` $white = '#ffffff'; $transport = 'refresh'; $wp_customize->add_setting('mytheme_text_color', array( 'default' => $white, 'transport' => $transport )); ``` In reply to jgraup: This code works: ``` $wp_customize->add_setting('themeone_primary_nav_background_color', array( 'default' => '#181818', 'transport' => 'refresh' )); ``` This code doesn't: ``` $args = array('default' => '#181818', 'transport' => 'refresh'); $wp_customize->add_setting('themeone_primary_nav_background_color', $args); ``` When I customize my page colors in the admin section, I should see a "default" color button. In the former code, I see this button. In the latter code, I do not. I have uploaded the file to my google drive if anyone wants to take a look: <https://drive.google.com/open?id=0B01XHUEqiziEcW14WE5NN0VYYlE> And here is a picture of the problem with example output: <https://drive.google.com/file/d/0B01XHUEqiziEUDVyZWFRWGZ0SkE/view?usp=sharing>
What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015? <https://core.trac.wordpress.org/ticket/10752>
213,438
<p>I can't figure out why this script wont load on site. Am I missing something?</p> <pre><code>function ajax_follow_enqueue_scripts() { wp_register_script('follow', plugins_url('the-follow.js', __FILE__)); wp_enqueue_script('follow'); wp_localize_script( 'the_follow', 'postfollow', array('ajax_url' =&gt; admin_url( 'admin-ajax.php' ))); } add_action( 'wp_enqueue_scripts', 'ajax_follow_enqueue_scripts' ); </code></pre>
[ { "answer_id": 214348, "author": "Ray Mitchell", "author_id": 2709, "author_profile": "https://wordpress.stackexchange.com/users/2709", "pm_score": 4, "selected": false, "text": "<p>What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015?</p>\n\n<p><a href=\"https://core.trac.wordpress.org/ticket/10752\">https://core.trac.wordpress.org/ticket/10752</a></p>\n" }, { "answer_id": 214349, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>If uploaded to some content entity like e.g. post, page or custom post type, WordPress does arrange the attachments uploads by creation date of that entity - and not according to the upload, creation date of the attachment. That might just be the case for you, because otherwise I can't think of a reasonable, related to default behavior, explanation for what you are describing. If that isn't the case, then you have to check for interferences by plug-ins or the theme.</p>\n" }, { "answer_id": 214374, "author": "Syed Priom", "author_id": 48577, "author_profile": "https://wordpress.stackexchange.com/users/48577", "pm_score": 3, "selected": false, "text": "<p>About the assigned folders for uploaded photos -</p>\n\n<ol>\n<li><p>If a photo is uploaded within a post/page, it will be in the folder corresponding to the date of the post/page e.g. if post date is June 2015, uploaded photos will be in /uploads/2015/06 folder.</p></li>\n<li><p>If a photo is uploaded directly in the media library (not within any post/page), it will be in the folder corresponding to upload date e.g. if we upload a photo to library on January 2016, it will be in /uploads/2016/01 folder.</p></li>\n<li><p>We can derive that the date of the photo being taken is not relevant. In the above two cases, it doesn't really matter which date the photo was actually taken.</p></li>\n</ol>\n" } ]
2016/01/01
[ "https://wordpress.stackexchange.com/questions/213438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78840/" ]
I can't figure out why this script wont load on site. Am I missing something? ``` function ajax_follow_enqueue_scripts() { wp_register_script('follow', plugins_url('the-follow.js', __FILE__)); wp_enqueue_script('follow'); wp_localize_script( 'the_follow', 'postfollow', array('ajax_url' => admin_url( 'admin-ajax.php' ))); } add_action( 'wp_enqueue_scripts', 'ajax_follow_enqueue_scripts' ); ```
What date was/is the post published? Media uploads are added to the folder when the post/page was published, not the upload date. Was the post originally published in Feb 2015? <https://core.trac.wordpress.org/ticket/10752>
213,453
<p>There may be several aspects to my question but I feel in essence it's easy: how do you make sure changes to a child theme <code>style.css</code> are properly propagated across caches?</p> <p>I read in a few places that WP should/would be placing the WP version in <code>nnn</code> when the resource is fetched as <code>http://host/wp-content/themes/theme-child/style.css?ver=nnn</code>. In my installation at <a href="http://frightanic.com/" rel="noreferrer">http://frightanic.com/</a> I see that the <em>parent theme</em> version is used instead. I have W3 Total Cache and a CDN in place but even if they're disabled a resource like <code>wp-content/themes/frightanic/style.css?ver=3.0.7</code> is requested. <code>3.0.7</code> is the version of the <a href="https://wordpress.org/themes/decode/" rel="noreferrer">Decode</a> parent theme.</p> <p>But be that as it may, if I update my child theme CSS without updating either WP or the parent theme at the same time how can I bust it from caches?</p>
[ { "answer_id": 213483, "author": "Marcel Stör", "author_id": 30783, "author_profile": "https://wordpress.stackexchange.com/users/30783", "pm_score": 5, "selected": true, "text": "<p>@dalbaeb's comment eventually lead to insightful discussions and a feasible solution. Thanks a lot!</p>\n\n<p>I believe the reason my child theme CSS was loaded using <code>'ver=&lt;parent-theme-version&gt;</code> was because I had followed the <a href=\"http://codex.wordpress.org/Child_Themes\" rel=\"noreferrer\">WP Codex on child themes</a> 1:1. My <code>functions.php</code> contained this:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'theme_enqueue_styles');\nfunction theme_enqueue_styles() {\n wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');\n}\n</code></pre>\n\n<p>The code I ended up using was first mentioned in <a href=\"https://wordpress.stackexchange.com/a/182023/30783\">https://wordpress.stackexchange.com/a/182023/30783</a> but numerous sites on the Internet copy-pasted it (without giving proper credit).</p>\n\n<pre><code>// Making sure your child theme has an independent version and can bust caches: https://wordpress.stackexchange.com/a/182023/30783\n// Filter get_stylesheet_uri() to return the parent theme's stylesheet\nadd_filter('stylesheet_uri', 'use_parent_theme_stylesheet');\n// Enqueue this theme's scripts and styles (after parent theme)\nadd_action('wp_enqueue_scripts', 'my_theme_styles', 20);\n\nfunction use_parent_theme_stylesheet()\n{\n // Use the parent theme's stylesheet\n return get_template_directory_uri() . '/style.css';\n}\n\nfunction my_theme_styles()\n{\n $themeVersion = wp_get_theme()-&gt;get('Version');\n\n // Enqueue our style.css with our own version\n wp_enqueue_style('child-theme-style', get_stylesheet_directory_uri() . '/style.css',\n array(), $themeVersion);\n}\n</code></pre>\n\n<p><strong>Update 2017-01-26</strong></p>\n\n<p>The current WP Theme handbook now contains a proper fix:: <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet\" rel=\"noreferrer\">https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet</a></p>\n" }, { "answer_id": 241132, "author": "jcdarocha", "author_id": 63019, "author_profile": "https://wordpress.stackexchange.com/users/63019", "pm_score": 1, "selected": false, "text": "<p>This works well when you add directly in your header.php and refresh the cache everytime you update your css file:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?&gt;\" type=\"text/css\" media=\"screen\" /&gt;\n</code></pre>\n\n<p>It displays: style.css?324932684 where the number is the time when the file was edited</p>\n" }, { "answer_id": 250090, "author": "Joshua Coolman", "author_id": 109471, "author_profile": "https://wordpress.stackexchange.com/users/109471", "pm_score": 0, "selected": false, "text": "<p>This may work as well. Using the php rand function:</p>\n\n<pre><code>function theme_enqueue_styles() {\n\n $parent_style = 'parent-style';\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css?'.rand(),\n array( $parent_style )\n );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n</code></pre>\n" }, { "answer_id": 373618, "author": "user1676224", "author_id": 28228, "author_profile": "https://wordpress.stackexchange.com/users/28228", "pm_score": 0, "selected": false, "text": "<p>WordPress now covers this with a function.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n wp_enqueue_style( 'child-style', get_stylesheet_uri(),\n array( 'parenthandle' ), \n wp_get_theme()-&gt;get('Version') // this only works if you have Version in the style header\n );\n}\n</code></pre>\n<p>Uses the <code>Version: 1.0.0</code> in your actual stylesheet <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet\" rel=\"nofollow noreferrer\">Enque Stylesheet with revision</a></p>\n" } ]
2016/01/01
[ "https://wordpress.stackexchange.com/questions/213453", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30783/" ]
There may be several aspects to my question but I feel in essence it's easy: how do you make sure changes to a child theme `style.css` are properly propagated across caches? I read in a few places that WP should/would be placing the WP version in `nnn` when the resource is fetched as `http://host/wp-content/themes/theme-child/style.css?ver=nnn`. In my installation at <http://frightanic.com/> I see that the *parent theme* version is used instead. I have W3 Total Cache and a CDN in place but even if they're disabled a resource like `wp-content/themes/frightanic/style.css?ver=3.0.7` is requested. `3.0.7` is the version of the [Decode](https://wordpress.org/themes/decode/) parent theme. But be that as it may, if I update my child theme CSS without updating either WP or the parent theme at the same time how can I bust it from caches?
@dalbaeb's comment eventually lead to insightful discussions and a feasible solution. Thanks a lot! I believe the reason my child theme CSS was loaded using `'ver=<parent-theme-version>` was because I had followed the [WP Codex on child themes](http://codex.wordpress.org/Child_Themes) 1:1. My `functions.php` contained this: ``` add_action('wp_enqueue_scripts', 'theme_enqueue_styles'); function theme_enqueue_styles() { wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'); } ``` The code I ended up using was first mentioned in <https://wordpress.stackexchange.com/a/182023/30783> but numerous sites on the Internet copy-pasted it (without giving proper credit). ``` // Making sure your child theme has an independent version and can bust caches: https://wordpress.stackexchange.com/a/182023/30783 // Filter get_stylesheet_uri() to return the parent theme's stylesheet add_filter('stylesheet_uri', 'use_parent_theme_stylesheet'); // Enqueue this theme's scripts and styles (after parent theme) add_action('wp_enqueue_scripts', 'my_theme_styles', 20); function use_parent_theme_stylesheet() { // Use the parent theme's stylesheet return get_template_directory_uri() . '/style.css'; } function my_theme_styles() { $themeVersion = wp_get_theme()->get('Version'); // Enqueue our style.css with our own version wp_enqueue_style('child-theme-style', get_stylesheet_directory_uri() . '/style.css', array(), $themeVersion); } ``` **Update 2017-01-26** The current WP Theme handbook now contains a proper fix:: <https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet>
213,459
<p>What is the advantage of explicitly including a composer.json file in my plugin if potential users of my plugin can already get it as a package through WPackagist?</p>
[ { "answer_id": 213469, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>The <code>composer.json</code> file usually contains extra information that are not available in the <code>readme.txt</code> file. So it could simply serve as a <em>readme</em> file for the dependencies of your plugin. </p>\n\n<p>Since <em>Composer</em> is in the toolbox of many developers, it could help them to better understand how your plugin is bolted together. </p>\n\n<p>For e.g. abondoned .org plugins, it would be handy to have that file available for someone that would like to fork it, update it and extend it.</p>\n\n<p>If we want to register our plugin on <em>packagist.org</em>, then we would of course need it.</p>\n" }, { "answer_id": 213755, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<h1>TL;DR</h1>\n\n<p>If you want to support Composer, adding a <code>composer.json</code> is better then just let WPackagist create a package for you.</p>\n\n<p>There are several reasons, no one is <em>really</em> important, but considering that to create a <code>composer.json</code> does not require much effort, it probably worth it.</p>\n\n<h1><code>composer.json</code> Benefits</h1>\n\n<p>Below a non-exhaustive list of benefits of using <code>composer.json</code>.</p>\n\n<h2>Developer friendly</h2>\n\n<p>When you require a package, Composer looks into <em>repositories</em> to find that specific package. Packagist and WPackagist are 2 repositories.</p>\n\n<p>The difference is that Packagist is always parsed by Composer, while WPackagist have to be manually added to the project <code>composer.json</code>.</p>\n\n<p>To require a plugin on Packagist you need a single line in <code>composer.json</code>:</p>\n\n<pre><code>\"require\": {\n \"your-name/your-plugin-name\":\"1.*\",\n}\n</code></pre>\n\n<p>To require a plugin on WPackagist you need to also configure repositories:</p>\n\n<pre><code>\"repositories\":[\n {\n \"type\":\"composer\",\n \"url\":\"http://wpackagist.org\"\n }\n],\n\"require\": {\n \"your-name/your-plugin-name\":\"1.*\",\n}\n</code></pre>\n\n<p>This is also relevant when using command line, see</p>\n\n<pre><code>composer create-project your-name/your-plugin-name\n</code></pre>\n\n<p>VS</p>\n\n<pre><code>composer create-project wpackagist-plugin/your-plugin-name --repository-url=http://wpackagist.org\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>When a project contains more repositories, Composer pings <strong>all of them</strong> to find information about packages.</p>\n\n<p>So adding WPackagist repository, slows down installation. Also consider that all the servers can be down, for any reson. It happen to much bigger companies than the one behind WPackagist, so every repository you add, it is an additional possible point of failure. </p>\n\n<h2>Configuration</h2>\n\n<p>On of the advantages of having a <code>composer.json</code> is that you can configure the way Composer will fetch your plugin.</p>\n\n<p>For example, you can use configure the package name in the <a href=\"https://getcomposer.org/doc/04-schema.md#name\"><code>name</code></a> property, instead of letting WPackagist create the package name for you.</p>\n\n<p>Moreover there are a lot of configuration that can be done in <code>composer.json</code>, just some few examples:</p>\n\n<ul>\n<li>you can use the <a href=\"https://getcomposer.org/doc/articles/aliases.md#branch-alias\"><code>branch-alias</code></a> setting to improve the compatibility of development version of the plugin</li>\n<li>even if you have no dependencies, you can use the <a href=\"https://getcomposer.org/doc/04-schema.md#require\"><code>require</code></a> setting to set a minimum PHP version,</li>\n<li>the <a href=\"https://getcomposer.org/doc/04-schema.md#conflict\"><code>conflict</code></a> setting let you explicit inform about conflicting packages...</li>\n</ul>\n\n<p>and so on.</p>\n\n<h2>Ownership awareness</h2>\n\n<p>When you require a plugin from WPackagist the \"vendor\" part of the package name is always <code>wpackagist-plugin</code>.</p>\n\n<p>So people will require you plugin like:</p>\n\n<pre><code>\"require\": {\n \"wpackagist-plugin/your-plugin-name\":\"1.*\",\n}\n</code></pre>\n\n<p>If you put the plugin on packagist, you can use your own vendor prefix, and I think is better for marketing:</p>\n\n<pre><code>\"require\": {\n \"your-name/your-plugin-name\":\"1.*\",\n}\n</code></pre>\n\n<h2>Autoload</h2>\n\n<p>Composer provide autoload for packages. If you decide to use Composer, you can benefit of it. However, considering that you are shipping your plugin to official repo you need to take into account that the majority of your user will probably install your plugin not using Composer. It means that you have to possibilities:</p>\n\n<ul>\n<li>ship the \"vendor\" folder (that contains the autoload) insider your plugin folder in the official repo</li>\n<li>make use of a custom autoloader or a manual loading mechanism in case the plugin is used without Composer.</li>\n</ul>\n\n<p>The second possibility is mentioned only because your plugin has no dependencies handled by Composer, otherwise ship vendor folder is the only possibility to make your plugin work without Composer, but is not issue-free: when different plugins are installed with embedded vendor folder there is the possibility of version conflicts if different plugins ships different version of same package.</p>\n\n<h2>Explicit Composer support</h2>\n\n<p>By adding <code>composer.json</code> you make people know that you explicitly support Composer. For example, when I search for a plugin, to find a <code>composer.json</code> in the plugin folder is a big plus for me, as I tend to don't use plugins that don't do that.</p>\n\n<p>Moreover, there are tools that target plugin explictly supporting Composer.</p>\n\n<p>For example, I have a script that prevents automatic updates for plugin / themes that have a <code>composer.json</code>.</p>\n" } ]
2016/01/02
[ "https://wordpress.stackexchange.com/questions/213459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
What is the advantage of explicitly including a composer.json file in my plugin if potential users of my plugin can already get it as a package through WPackagist?
TL;DR ===== If you want to support Composer, adding a `composer.json` is better then just let WPackagist create a package for you. There are several reasons, no one is *really* important, but considering that to create a `composer.json` does not require much effort, it probably worth it. `composer.json` Benefits ======================== Below a non-exhaustive list of benefits of using `composer.json`. Developer friendly ------------------ When you require a package, Composer looks into *repositories* to find that specific package. Packagist and WPackagist are 2 repositories. The difference is that Packagist is always parsed by Composer, while WPackagist have to be manually added to the project `composer.json`. To require a plugin on Packagist you need a single line in `composer.json`: ``` "require": { "your-name/your-plugin-name":"1.*", } ``` To require a plugin on WPackagist you need to also configure repositories: ``` "repositories":[ { "type":"composer", "url":"http://wpackagist.org" } ], "require": { "your-name/your-plugin-name":"1.*", } ``` This is also relevant when using command line, see ``` composer create-project your-name/your-plugin-name ``` VS ``` composer create-project wpackagist-plugin/your-plugin-name --repository-url=http://wpackagist.org ``` Performance ----------- When a project contains more repositories, Composer pings **all of them** to find information about packages. So adding WPackagist repository, slows down installation. Also consider that all the servers can be down, for any reson. It happen to much bigger companies than the one behind WPackagist, so every repository you add, it is an additional possible point of failure. Configuration ------------- On of the advantages of having a `composer.json` is that you can configure the way Composer will fetch your plugin. For example, you can use configure the package name in the [`name`](https://getcomposer.org/doc/04-schema.md#name) property, instead of letting WPackagist create the package name for you. Moreover there are a lot of configuration that can be done in `composer.json`, just some few examples: * you can use the [`branch-alias`](https://getcomposer.org/doc/articles/aliases.md#branch-alias) setting to improve the compatibility of development version of the plugin * even if you have no dependencies, you can use the [`require`](https://getcomposer.org/doc/04-schema.md#require) setting to set a minimum PHP version, * the [`conflict`](https://getcomposer.org/doc/04-schema.md#conflict) setting let you explicit inform about conflicting packages... and so on. Ownership awareness ------------------- When you require a plugin from WPackagist the "vendor" part of the package name is always `wpackagist-plugin`. So people will require you plugin like: ``` "require": { "wpackagist-plugin/your-plugin-name":"1.*", } ``` If you put the plugin on packagist, you can use your own vendor prefix, and I think is better for marketing: ``` "require": { "your-name/your-plugin-name":"1.*", } ``` Autoload -------- Composer provide autoload for packages. If you decide to use Composer, you can benefit of it. However, considering that you are shipping your plugin to official repo you need to take into account that the majority of your user will probably install your plugin not using Composer. It means that you have to possibilities: * ship the "vendor" folder (that contains the autoload) insider your plugin folder in the official repo * make use of a custom autoloader or a manual loading mechanism in case the plugin is used without Composer. The second possibility is mentioned only because your plugin has no dependencies handled by Composer, otherwise ship vendor folder is the only possibility to make your plugin work without Composer, but is not issue-free: when different plugins are installed with embedded vendor folder there is the possibility of version conflicts if different plugins ships different version of same package. Explicit Composer support ------------------------- By adding `composer.json` you make people know that you explicitly support Composer. For example, when I search for a plugin, to find a `composer.json` in the plugin folder is a big plus for me, as I tend to don't use plugins that don't do that. Moreover, there are tools that target plugin explictly supporting Composer. For example, I have a script that prevents automatic updates for plugin / themes that have a `composer.json`.
213,480
<p>I offer downloadable products with woocommerce and each product is allowed to have multiple files.</p> <p>I would like to display the file types/formats on the product page so users know what each product contains. Please see the image below.</p> <p><a href="https://i.stack.imgur.com/PB2aw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PB2aw.png" alt="enter image description here"></a></p> <p>One idea I have thought of is to get the names of the attached files, and then somehow print only the last four characters of each one. But I cannot figure out how to write a function that would make it work.</p>
[ { "answer_id": 213486, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>Place the following code in your <code>meta.php</code> template file immediately after the lines where it prints the categories and tags. Please note, the standard practice is that you shall copy the <code>meta.php</code> template file to your theme folder. So to override <code>meta.php</code>, copy: <strong>woocommerce/templates/single-product/meta.php</strong> from plugin folder to <strong>yourtheme/woocommerce/templates/single-product/meta.php</strong></p>\n\n<pre><code>&lt;?php\n\nglobal $product;\n\n$downloads = $product-&gt;get_files();\n\nforeach( $downloads as $key =&gt; $each_download ) {\n $info = pathinfo($each_download[\"file\"]);\n $ext = $info['extension'];\n $formats .= $ext . \", \";\n}\n\necho '&lt;p&gt; Formats: '. $formats .'&lt;/p&gt;';\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 367332, "author": "Serhio Ramus", "author_id": 188653, "author_profile": "https://wordpress.stackexchange.com/users/188653", "pm_score": -1, "selected": false, "text": "<p>How do that too for the File Size? I have a Woo for Digital Products.. But anyone codes not worked for OutPut File Size.. But File format work good.</p>\n\n<p>The code in this thread works great! But only for the file extension, I asked if there is the same code for outputting the size of the file added to the Woo product (as a virtual, downloadable)? I try use all codes from forums where is WP filesize (file size output) but not worked nothing</p>\n\n<p><strong>UPDATE</strong></p>\n\n\n\n<p>that work but needed past ID = 8677 (Manual ..) how do that, get a attached file id (Auto to per Product)?</p>\n" } ]
2016/01/02
[ "https://wordpress.stackexchange.com/questions/213480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86102/" ]
I offer downloadable products with woocommerce and each product is allowed to have multiple files. I would like to display the file types/formats on the product page so users know what each product contains. Please see the image below. [![enter image description here](https://i.stack.imgur.com/PB2aw.png)](https://i.stack.imgur.com/PB2aw.png) One idea I have thought of is to get the names of the attached files, and then somehow print only the last four characters of each one. But I cannot figure out how to write a function that would make it work.
Place the following code in your `meta.php` template file immediately after the lines where it prints the categories and tags. Please note, the standard practice is that you shall copy the `meta.php` template file to your theme folder. So to override `meta.php`, copy: **woocommerce/templates/single-product/meta.php** from plugin folder to **yourtheme/woocommerce/templates/single-product/meta.php** ``` <?php global $product; $downloads = $product->get_files(); foreach( $downloads as $key => $each_download ) { $info = pathinfo($each_download["file"]); $ext = $info['extension']; $formats .= $ext . ", "; } echo '<p> Formats: '. $formats .'</p>'; ?> ```
213,482
<p>I have a <code>&lt;form&gt;</code> with about 20 inputs (mostly <code>select</code> and <code>number</code>) which each is an argument in <code>WP_Query</code> if filled.</p> <p>I learned today that I could use transients to <em>store</em> results which seems like a good opportunity to ease the blow on server, after all: this is rather complicated query.</p> <p>My plan is:</p> <ul> <li>User fills inputs - his/her choice: which, what or if</li> <li>Generate string from filled inputs <em>a.k.a</em> <code>value-1=value&amp;value-2=250000</code></li> <li>Check if transient with the key of that <code>string</code> already exists</li> <li>If exists - show results from transient</li> <li>If doesn't exist - new <code>WP_Query</code></li> <li>Set transient with key being that <code>string</code></li> </ul> <p>I understand that this is a long shot because there are quite a few <code>inputs</code> (especially number <code>inputs</code> - what are the odds, right?) but if I have high traffic, Im sure some patterns will occur.. Especially most popular choises like leaving everything as is, filling only first <code>input</code> <em>etc</em>.</p> <hr> <p><strong>Question:</strong> </p> <p>Would the <em>"extra load"</em> of transient checking and the space required in database outweight the possible resorce gain from transients? </p> <p>This seems like a very good plan to me but I've been wrong before for few times.. If content is dynamic, I could set transition time for 1 hour for example. Would that work as it does in my head?</p> <hr>
[ { "answer_id": 213493, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>what are the odds, right?</p>\n</blockquote>\n\n<p>The odds make the project pretty pointless, actually. </p>\n\n<p>If you have twenty inputs, each with certainly more than 2 options per input you will very easily get in to the millions of possibilities. </p>\n\n<p>Even at 2 per input you'd need to save a few hundred result sets so you'd have a tremendous number of queries anyway. You can's save the same result set forever (which is implied in the fact you seem to know you need \"transients\") because you'd missing new posts so you have to have your results expire fairly often which would mean that you'd need new queries to replace them. </p>\n\n<blockquote>\n <p>Would the \"extra load\" of transient checking and the space required in\n database outweight the possible resorce gain from transients?</p>\n</blockquote>\n\n<p>Given the number of queries that you'd necessarily have to run the transient checking is necessarily going to be unnecessary overhead-- that that will never pay off in any significant way. Likewise with the transient saving. You have, in my opinion, database reads and writes that will virtually never prove useful. </p>\n\n<p>As for the space, you could have hundreds or millions of key/values the database, which in my estimation are going to be virtually useless. On the low end, any typical hosting environment should be able to handle the storage but on the high end you may end up running out of space. </p>\n\n<p>Also, think of how you would save the results. If you save IDs only you still need to run a query to get the rest of the data. If you save the whole query your space requirements go up by orders of magnitude. </p>\n\n<p>The only way I see this working out in your favor is if you have truly staggering volume-- on the order of this site, for example. And I seriously doubt that is going to be the case. </p>\n" }, { "answer_id": 213554, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I have read quite a few of your posts and it seems like your queries are really complex which either slows the page or simply crashes it.</p>\n\n<p>Transients are definitely an option to store the results of such labor intensive queries. As @s_ha_dum mentioned, you'll need to look into what you will be saving.</p>\n\n<blockquote>\n <p>Would the \"extra load\" of transient checking and the space required in database outweight the possible resorce gain from transients?</p>\n</blockquote>\n\n<p>You need to remember that transients are quite expensive to create, so that is something that you would not want to do every hour like you have said. A transient should be created with expiry times that would make them useful, like set the deletion time to something like days or month.</p>\n\n<p>Once created, checking and getting data from a transients simply means 2 db calls in less than 0.002 seconds, so you definitely gain quite a lot on really expensive operations.</p>\n\n<p>Space should never be an issue in the db as you would only want to store post ID's and not the complete object. We want to store as little data in our transient as possible. It is going to mean that you would need to run a second query to get the post objects, but this query will be much leaner. The big score here would be that the first expensive query is dealt with and eliminated. The first query should also be much leaner because we would query id's only.</p>\n\n<p>You can and must in situations where input data is dynamic, use the input data to create a dynamic transient name. You need to remember, a transient's name can only be 45 characters long. A name longer than 45 characters make that the transient is not created, and every page load tries to create a transient. As I said, transients are expensive to create and you do not want to create a transient on every page load as this will add even more load on an already overloaded query. I always pass my input data to <code>md5()</code> (<em>which generate a 32 character key</em>) to create a unique hashed key and then have a transient name like <code>some_name_{md5()_result}</code>. Just remember to convert arrays with <code>json_encode()</code> first and then use that result to pass to <code>md5()</code>. You can look into some of <a href=\"https://wordpress.stackexchange.com/search?q=md5%20user%3Ame\">these posts</a> to see examples using <code>md5()</code>.</p>\n\n<p>What might be an issue here is the amount of transients you are going to create. If you have a possible 1 million dynamic input combinations, you are going to create 1 million transients which can have effects when you delete the transients. This can again cause an issue with crashing the back end. </p>\n\n<p>If the input is dynamic, you are going to save empty values as well for queries where no posts are returned, so you would need to take that into consideration. </p>\n\n<p>What really is also a big factor here is, what is the possibility of two or ten or hundred users using the same exact input values in a week. I mean, there are no usefulness in creating a transient if only one or two people are ever going to use the same exact input values. As I said, creating transients are expensive, so you would not want to unnecessarily create a transient just for one or two people</p>\n\n<p>At the end of day, you will need to take this info and decide how useful or useless a transient would be and then act on that.</p>\n\n<p>Here is just an idea if you wish to have transients</p>\n\n<pre><code>// Here is your string of inputs\n$args = 'value-1=value&amp;value-2=250000';\n// Create a unique hashed key from the arguments\n$key = md5( $args );\n//$key = md5( json_encode( $args ) ); // If $args is an array\n// Set the transient name\n$transient_name = 'custom_input_' . $key;\n\nif ( false === ( $query = get_transient( $transient_name ) ) ) {\n $query = get_posts( $args . '&amp;fields=ids' ) // Only get post ids. Alter if $args is an array\n\n // Set the transient only if we have results\n if ( $query )\n set_transient( \n $transient_name, // Transient name\n $query, // What should be saved\n 7 * DAY_IN_SECONDS // Lifespan of transient is 7 days\n );\n}\n\n// Now run the second query to get the full objects. Just add 'post_type' if this is not 'post' posts\nif ( $query ) {\n $args = [\n 'post__in' =&gt; $query,\n 'posts_per_page' =&gt; count( $query ),\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'post_in'\n ];\n $q = new WP_Query( $args );\n var_dump( $q );\n}\n</code></pre>\n\n<p>We can then just flush all transients when we publish a new post, deletes it, undelete or update a post</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_custom_input_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_custom_input_%')\" );\n});\n</code></pre>\n" } ]
2016/01/02
[ "https://wordpress.stackexchange.com/questions/213482", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
I have a `<form>` with about 20 inputs (mostly `select` and `number`) which each is an argument in `WP_Query` if filled. I learned today that I could use transients to *store* results which seems like a good opportunity to ease the blow on server, after all: this is rather complicated query. My plan is: * User fills inputs - his/her choice: which, what or if * Generate string from filled inputs *a.k.a* `value-1=value&value-2=250000` * Check if transient with the key of that `string` already exists * If exists - show results from transient * If doesn't exist - new `WP_Query` * Set transient with key being that `string` I understand that this is a long shot because there are quite a few `inputs` (especially number `inputs` - what are the odds, right?) but if I have high traffic, Im sure some patterns will occur.. Especially most popular choises like leaving everything as is, filling only first `input` *etc*. --- **Question:** Would the *"extra load"* of transient checking and the space required in database outweight the possible resorce gain from transients? This seems like a very good plan to me but I've been wrong before for few times.. If content is dynamic, I could set transition time for 1 hour for example. Would that work as it does in my head? ---
I have read quite a few of your posts and it seems like your queries are really complex which either slows the page or simply crashes it. Transients are definitely an option to store the results of such labor intensive queries. As @s\_ha\_dum mentioned, you'll need to look into what you will be saving. > > Would the "extra load" of transient checking and the space required in database outweight the possible resorce gain from transients? > > > You need to remember that transients are quite expensive to create, so that is something that you would not want to do every hour like you have said. A transient should be created with expiry times that would make them useful, like set the deletion time to something like days or month. Once created, checking and getting data from a transients simply means 2 db calls in less than 0.002 seconds, so you definitely gain quite a lot on really expensive operations. Space should never be an issue in the db as you would only want to store post ID's and not the complete object. We want to store as little data in our transient as possible. It is going to mean that you would need to run a second query to get the post objects, but this query will be much leaner. The big score here would be that the first expensive query is dealt with and eliminated. The first query should also be much leaner because we would query id's only. You can and must in situations where input data is dynamic, use the input data to create a dynamic transient name. You need to remember, a transient's name can only be 45 characters long. A name longer than 45 characters make that the transient is not created, and every page load tries to create a transient. As I said, transients are expensive to create and you do not want to create a transient on every page load as this will add even more load on an already overloaded query. I always pass my input data to `md5()` (*which generate a 32 character key*) to create a unique hashed key and then have a transient name like `some_name_{md5()_result}`. Just remember to convert arrays with `json_encode()` first and then use that result to pass to `md5()`. You can look into some of [these posts](https://wordpress.stackexchange.com/search?q=md5%20user%3Ame) to see examples using `md5()`. What might be an issue here is the amount of transients you are going to create. If you have a possible 1 million dynamic input combinations, you are going to create 1 million transients which can have effects when you delete the transients. This can again cause an issue with crashing the back end. If the input is dynamic, you are going to save empty values as well for queries where no posts are returned, so you would need to take that into consideration. What really is also a big factor here is, what is the possibility of two or ten or hundred users using the same exact input values in a week. I mean, there are no usefulness in creating a transient if only one or two people are ever going to use the same exact input values. As I said, creating transients are expensive, so you would not want to unnecessarily create a transient just for one or two people At the end of day, you will need to take this info and decide how useful or useless a transient would be and then act on that. Here is just an idea if you wish to have transients ``` // Here is your string of inputs $args = 'value-1=value&value-2=250000'; // Create a unique hashed key from the arguments $key = md5( $args ); //$key = md5( json_encode( $args ) ); // If $args is an array // Set the transient name $transient_name = 'custom_input_' . $key; if ( false === ( $query = get_transient( $transient_name ) ) ) { $query = get_posts( $args . '&fields=ids' ) // Only get post ids. Alter if $args is an array // Set the transient only if we have results if ( $query ) set_transient( $transient_name, // Transient name $query, // What should be saved 7 * DAY_IN_SECONDS // Lifespan of transient is 7 days ); } // Now run the second query to get the full objects. Just add 'post_type' if this is not 'post' posts if ( $query ) { $args = [ 'post__in' => $query, 'posts_per_page' => count( $query ), 'order' => 'ASC', 'orderby' => 'post_in' ]; $q = new WP_Query( $args ); var_dump( $q ); } ``` We can then just flush all transients when we publish a new post, deletes it, undelete or update a post ``` add_action( 'transition_post_status', function () { global $wpdb; $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_custom_input_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_custom_input_%')" ); }); ```
213,508
<p>This might be a very silly question but I am losing my hair over this.. So basically, I have the following line of code"</p> <pre><code> 'Default' =&gt; '&lt;img src="' . THEMEROOT . '/admin/images/default.png" width="120" height="80" alt="&lt;?php _e( 'Default', 'my_theme' ); ?&gt;"/&gt;', </code></pre> <p>The problem I am having is the alt text is printing like this:</p> <pre><code>&lt;?php _e( 'Default', 'my_theme' ); ?&gt; </code></pre> <p>instead of just the "Default" word.. It is a conflict between double and single quotes, but I can't figure out how to fix it. What am I doing wrong here?(please be gentle, I am a new in these things :))</p>
[ { "answer_id": 233020, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>The <code>edit_others_posts</code> capability should allow users to set the author of a post.</p>\n\n<p>At first glance you might reply that you don't want your authors to be able to edit one another's posts. The difference in ability is very subtle though: writing a post and then assigning it to another user isn't much different from being able to write or edit that other user's posts.</p>\n" }, { "answer_id": 299686, "author": "Anoop G", "author_id": 141055, "author_profile": "https://wordpress.stackexchange.com/users/141055", "pm_score": -1, "selected": false, "text": "<pre><code>function add_theme_caps() {\n $role = get_role( 'author' );\n $role-&gt;add_cap( 'edit_others_posts' );\n}\nadd_action( 'admin_init', 'add_theme_caps');\n</code></pre>\n" } ]
2016/01/02
[ "https://wordpress.stackexchange.com/questions/213508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82982/" ]
This might be a very silly question but I am losing my hair over this.. So basically, I have the following line of code" ``` 'Default' => '<img src="' . THEMEROOT . '/admin/images/default.png" width="120" height="80" alt="<?php _e( 'Default', 'my_theme' ); ?>"/>', ``` The problem I am having is the alt text is printing like this: ``` <?php _e( 'Default', 'my_theme' ); ?> ``` instead of just the "Default" word.. It is a conflict between double and single quotes, but I can't figure out how to fix it. What am I doing wrong here?(please be gentle, I am a new in these things :))
The `edit_others_posts` capability should allow users to set the author of a post. At first glance you might reply that you don't want your authors to be able to edit one another's posts. The difference in ability is very subtle though: writing a post and then assigning it to another user isn't much different from being able to write or edit that other user's posts.
213,535
<p>I have googled for this and, did not find any solution.</p> <p>I am trying to add Birth date (datepicker) field in woocommerce registration page.</p> <p>The registration form has been created as per guidance posted <a href="https://support.woothemes.com/hc/en-us/articles/203182373-How-to-add-custom-fields-in-user-registration-on-the-My-Account-page" rel="nofollow">here</a></p> <p>I am using datepicker script available <a href="http://glad.github.io/glDatePicker/" rel="nofollow">here</a></p> <p>According to DatePicker documentation we have to add below code in order to make it work.</p> <pre><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="glDatePicker.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(window).load(function() { $('input').glDatePicker(); }); &lt;/script&gt; </code></pre> <p>Problem is all other fields in the form start displaying calendar. This is because the javascript adds calendar to all the 'input' fields of the form.</p> <p>How to solve this???</p> <p>Code in functions.php ....</p> <pre><code>&lt;p class="form-row form-row-wide"&gt; &lt;label for="reg_billing_birthdate"&gt;&lt;?php _e( 'Birth Date', 'woocommerce' ); ?&gt; &lt;span class="required"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type="text" class="input-text" name="billing_birthdate" id="reg_billing_birthdate" gldp-id="mydate" value="&lt;?php if ( ! empty( $_POST['billing_birthdate'] ) ) esc_attr_e( $_POST['billing_birthdate'] ); ?&gt;" /&gt; &lt;/p&gt; </code></pre>
[ { "answer_id": 213536, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 1, "selected": false, "text": "<p>Don't include jquery from any other source, it will create conflict. Bcoz jQuery is pre bundled in wordpress by default.</p>\n\n<p>For your question, add an <code>id</code> or <code>class</code> to the input element then add the datepicker based on the class. For example</p>\n\n<pre><code>&lt;input type=\"text\" class=\"da_test\" value=\"\" &gt;\n\n&lt;script type=\"text/javascript\"&gt;\n $(window).load(function()\n {\n $('.da_test').glDatePicker();\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>This will avoid datepicker to appear in every input element. </p>\n" }, { "answer_id": 213538, "author": "kpmrpar", "author_id": 86147, "author_profile": "https://wordpress.stackexchange.com/users/86147", "pm_score": 0, "selected": false, "text": "<p>Below changes worked....</p>\n\n<pre><code>&lt;script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"glDatePicker.min.js\"&gt;&lt;/script&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n$(window).load(function()\n{\n $('#reg_billing_birthdate').glDatePicker();\n});\n&lt;/script&gt;\n</code></pre>\n" } ]
2016/01/03
[ "https://wordpress.stackexchange.com/questions/213535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86147/" ]
I have googled for this and, did not find any solution. I am trying to add Birth date (datepicker) field in woocommerce registration page. The registration form has been created as per guidance posted [here](https://support.woothemes.com/hc/en-us/articles/203182373-How-to-add-custom-fields-in-user-registration-on-the-My-Account-page) I am using datepicker script available [here](http://glad.github.io/glDatePicker/) According to DatePicker documentation we have to add below code in order to make it work. ``` <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="glDatePicker.min.js"></script> <script type="text/javascript"> $(window).load(function() { $('input').glDatePicker(); }); </script> ``` Problem is all other fields in the form start displaying calendar. This is because the javascript adds calendar to all the 'input' fields of the form. How to solve this??? Code in functions.php .... ``` <p class="form-row form-row-wide"> <label for="reg_billing_birthdate"><?php _e( 'Birth Date', 'woocommerce' ); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="billing_birthdate" id="reg_billing_birthdate" gldp-id="mydate" value="<?php if ( ! empty( $_POST['billing_birthdate'] ) ) esc_attr_e( $_POST['billing_birthdate'] ); ?>" /> </p> ```
Don't include jquery from any other source, it will create conflict. Bcoz jQuery is pre bundled in wordpress by default. For your question, add an `id` or `class` to the input element then add the datepicker based on the class. For example ``` <input type="text" class="da_test" value="" > <script type="text/javascript"> $(window).load(function() { $('.da_test').glDatePicker(); }); </script> ``` This will avoid datepicker to appear in every input element.
213,563
<p>I'm trying to load a message after successful login on the front end.</p> <p>I have the script that works as a function,</p> <pre><code>function myscript() { ?&gt; &lt;script type="text/javascript"&gt; $( document ).ready(function() { $('&lt;div class="item login"&gt;Success! You\'re now signed in.&lt;/div&gt;').appendTo('.pop-notice').delay(6000).queue(function() { $(this).remove(); }); }); &lt;/script&gt; &lt;?php } </code></pre> <p>Which I then try to load into the footer on login_redirect. </p> <pre><code>function my_login_redirect() { add_action( 'wp_footer', 'myscript' ); } add_filter( 'login_redirect', 'my_login_redirect', 10, 3 ); </code></pre> <p>But it just doesn't work. Not sure what hook I'm really supposed to be using though. </p> <p>Website is <a href="http://dev.podcamptoronto.com/" rel="nofollow">http://dev.podcamptoronto.com/</a> Using a social media account login system, 'wordpress social login'. But it uses the native login function itself, so I don't think it's interfering. </p>
[ { "answer_id": 213566, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p><code>login_redirect</code> is a filter, so technically what you are doing is an abuse of the hook but more importantly, <code>login_redirect</code> runs before a <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-login.php#L826\" rel=\"nofollow\"><strong><em>redirect</em></strong></a> which results in a new page load. HTTP and PHP in that context is stateless meaning that code doesn't populate through a page load.</p>\n\n<p>What you are going to have to do is pass an argument through the URL...</p>\n\n<pre><code>function my_login_redirect($redirect) {\n return esc_url(add_query_arg('lgn',true,$request));\n}\nadd_filter('login_redirect','my_login_redirect',10);\n</code></pre>\n\n<p>Then use that variable to trigger your message either via PHP directly or with your JavaSAcript.</p>\n" }, { "answer_id": 213570, "author": "Zain Sohail", "author_id": 45826, "author_profile": "https://wordpress.stackexchange.com/users/45826", "pm_score": 2, "selected": true, "text": "<p>There could be many approaches to this. Mine is given below ..</p>\n\n<ol>\n<li><p>First you store the time on which the user was logged in so that you can display the successfull login popup for X number of minutes ..</p>\n\n<pre><code>function store_login_time($user_login, $user) {\n $userID = $user-&gt;ID;\n update_user_meta( $userID, '_login_time_', time() );\n}\nadd_action('wp_login', 'store_login_time', 10, 2);\n</code></pre></li>\n<li><p>Then you use this code to display the code on the front page of the website for X number of minutes ( 1 minute in my sample ) using <code>wp_head</code> action ..</p>\n\n<pre><code>function myscript() {\n\n $to_time = time();\n $from_time = get_user_meta( get_current_user_id(), '_login_time_', true ); \n\n $diff = round(abs($to_time - $from_time) / 60,2);\n\n // This will run till 1 minute after logging in ..\n // For Seconds use 0.1 to 0.9\n if ( is_front_page() &amp;&amp; $diff &lt; \"1\" ){\n\n ?&gt; \n &lt;script type=\"text/javascript\"&gt;\n $( document ).ready(function() {\n $('&lt;div class=\"item login\"&gt;Success! You\\'re now signed in.&lt;/div&gt;').appendTo('.pop-notice').delay(6000).queue(function() { $(this).remove(); });\n });\n &lt;/script&gt;\n &lt;?php\n\n }\n}\nadd_action('wp_head', 'myscript');\n</code></pre></li>\n</ol>\n\n<p>You can add further options for user roles as per you needs.</p>\n" } ]
2016/01/03
[ "https://wordpress.stackexchange.com/questions/213563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5302/" ]
I'm trying to load a message after successful login on the front end. I have the script that works as a function, ``` function myscript() { ?> <script type="text/javascript"> $( document ).ready(function() { $('<div class="item login">Success! You\'re now signed in.</div>').appendTo('.pop-notice').delay(6000).queue(function() { $(this).remove(); }); }); </script> <?php } ``` Which I then try to load into the footer on login\_redirect. ``` function my_login_redirect() { add_action( 'wp_footer', 'myscript' ); } add_filter( 'login_redirect', 'my_login_redirect', 10, 3 ); ``` But it just doesn't work. Not sure what hook I'm really supposed to be using though. Website is <http://dev.podcamptoronto.com/> Using a social media account login system, 'wordpress social login'. But it uses the native login function itself, so I don't think it's interfering.
There could be many approaches to this. Mine is given below .. 1. First you store the time on which the user was logged in so that you can display the successfull login popup for X number of minutes .. ``` function store_login_time($user_login, $user) { $userID = $user->ID; update_user_meta( $userID, '_login_time_', time() ); } add_action('wp_login', 'store_login_time', 10, 2); ``` 2. Then you use this code to display the code on the front page of the website for X number of minutes ( 1 minute in my sample ) using `wp_head` action .. ``` function myscript() { $to_time = time(); $from_time = get_user_meta( get_current_user_id(), '_login_time_', true ); $diff = round(abs($to_time - $from_time) / 60,2); // This will run till 1 minute after logging in .. // For Seconds use 0.1 to 0.9 if ( is_front_page() && $diff < "1" ){ ?> <script type="text/javascript"> $( document ).ready(function() { $('<div class="item login">Success! You\'re now signed in.</div>').appendTo('.pop-notice').delay(6000).queue(function() { $(this).remove(); }); }); </script> <?php } } add_action('wp_head', 'myscript'); ``` You can add further options for user roles as per you needs.
213,572
<p>I'm trying to make a mu-plugin dedicated to make OpenGraph tags for my website, since the current plugin in WP directory arent updated for ages.</p> <p>But i ran with several headaches trying to get post or page data, something i never tried before.</p> <p>Using this piece of code:</p> <pre><code>&lt;?php /* Plugin Name: Open Graph! Description: Adiciona tags Open Graph (Facebook) para o site. Author: ChronoMania Team Version: 1.0 Author URI: http://chronomania.com.br */ function pegarConteudoPost() { if (is_single()) { $texto = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id)); if empty($texto) { $texto = wp_trim_words($post-&gt;post_content); } if empty($texto) { $texto = get_bloginfo('description'); } } elseif (is_page()) { $texto = wp_trim_words($page-&gt;post_content); } else { $texto = get_bloginfo('description'); } return $texto; } function pegaURLAtual() { $link = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; return $link; } function montaOpenGraph() { echo '&lt;meta property="og:title" content="' . wp_title("", false) . '"&gt;'; echo '&lt;meta property="og:site_name" content="' . get_bloginfo('name') . '"&gt;'; echo '&lt;meta property="og:url" content="' . pegaURLAtual() . '"&gt;'; echo '&lt;meta property="og:description" content="' . pegarConteudoPost() . '"&gt;'; echo '&lt;meta property="og:image" content="' . get_template_directory_uri() . '/img/social/ogp_logo.png"&gt;'; echo '&lt;meta property="og:type" content="article"&gt;'; } // Registrando funções add_action('wp_head', 'montaOpenGraph'); ?&gt; </code></pre> <p>It gives me error 500. So i managed to trace the error to the function pegarConteudoPost().</p> <p>As i stated before, i dont have much experience with php (so the jury rig code) and never need to work with data outside the loop, so i dig some code from google and put there, with no results.</p> <p>Any ideas to how can i make this work?</p>
[ { "answer_id": 213573, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You're using non-existent variables in your function, <code>$post_id</code>, <code>$post</code>, <code>$page</code>.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow\"><code>get_queried_object</code></a> to get data from the current page.</p>\n\n<pre><code>if( is_single() || is_page() ){\n $this_page = get_queried_object();\n $excerpt = get_post_field( 'post_excerpt', $this_page-&gt;ID );\n}\n</code></pre>\n" }, { "answer_id": 213594, "author": "Vico", "author_id": 71362, "author_profile": "https://wordpress.stackexchange.com/users/71362", "pm_score": 1, "selected": true, "text": "<p>After several headaches i managed to solve the issue based on Milo's answer.\nBut i need to add a check if the excerpt returned empty, and if it return empty i need to trim the entire content string to get the desired data.</p>\n\n<p>Final code:</p>\n\n<pre><code>function pegarConteudoPost()\n{\n if( is_single() || is_page() )\n {\n $this_page = get_queried_object();\n $excerpt = get_post_field( 'post_excerpt', $this_page-&gt;ID );\n\n if ($excerpt === '')\n {\n $excerpt = wp_trim_words(get_post_field( 'post_content', $this_page-&gt;ID ), 55);\n }\n\n $texto = $excerpt;\n }\n else\n {\n $texto = get_bloginfo('description');\n }\n return $texto;\n}\n</code></pre>\n" } ]
2016/01/03
[ "https://wordpress.stackexchange.com/questions/213572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71362/" ]
I'm trying to make a mu-plugin dedicated to make OpenGraph tags for my website, since the current plugin in WP directory arent updated for ages. But i ran with several headaches trying to get post or page data, something i never tried before. Using this piece of code: ``` <?php /* Plugin Name: Open Graph! Description: Adiciona tags Open Graph (Facebook) para o site. Author: ChronoMania Team Version: 1.0 Author URI: http://chronomania.com.br */ function pegarConteudoPost() { if (is_single()) { $texto = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id)); if empty($texto) { $texto = wp_trim_words($post->post_content); } if empty($texto) { $texto = get_bloginfo('description'); } } elseif (is_page()) { $texto = wp_trim_words($page->post_content); } else { $texto = get_bloginfo('description'); } return $texto; } function pegaURLAtual() { $link = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; return $link; } function montaOpenGraph() { echo '<meta property="og:title" content="' . wp_title("", false) . '">'; echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '">'; echo '<meta property="og:url" content="' . pegaURLAtual() . '">'; echo '<meta property="og:description" content="' . pegarConteudoPost() . '">'; echo '<meta property="og:image" content="' . get_template_directory_uri() . '/img/social/ogp_logo.png">'; echo '<meta property="og:type" content="article">'; } // Registrando funções add_action('wp_head', 'montaOpenGraph'); ?> ``` It gives me error 500. So i managed to trace the error to the function pegarConteudoPost(). As i stated before, i dont have much experience with php (so the jury rig code) and never need to work with data outside the loop, so i dig some code from google and put there, with no results. Any ideas to how can i make this work?
After several headaches i managed to solve the issue based on Milo's answer. But i need to add a check if the excerpt returned empty, and if it return empty i need to trim the entire content string to get the desired data. Final code: ``` function pegarConteudoPost() { if( is_single() || is_page() ) { $this_page = get_queried_object(); $excerpt = get_post_field( 'post_excerpt', $this_page->ID ); if ($excerpt === '') { $excerpt = wp_trim_words(get_post_field( 'post_content', $this_page->ID ), 55); } $texto = $excerpt; } else { $texto = get_bloginfo('description'); } return $texto; } ```
213,576
<h2>The Problem</h2> <p>WP appears to remove the value of my query variable before it gets used to filter the list of users.</p> <h2>My Code</h2> <p>This function adds a custom column to my Users table on <code>/wp-admin/users.php</code>:</p> <pre><code>function add_course_section_to_user_meta( $columns ) { $columns['course_section'] = 'Section'; return $columns; } add_filter( 'manage_users_columns', 'add_course_section_to_user_meta' ); </code></pre> <p>This function tells WP how to fill values in the column:</p> <pre><code>function manage_users_course_section( $val, $col, $uid ) { if ( 'course_section' === $col ) return get_the_author_meta( 'course_section', $uid ); } add_filter( 'manage_users_custom_column', 'manage_users_course_section' ); </code></pre> <p>This adds a dropdown and <code>Filter</code> button above the Users table:</p> <pre><code>function add_course_section_filter() { echo '&lt;select name="course_section" style="float:none;"&gt;'; echo '&lt;option value=""&gt;Course Section...&lt;/option&gt;'; for ( $i = 1; $i &lt;= 3; ++$i ) { if ( $i == $_GET[ 'course_section' ] ) { echo '&lt;option value="'.$i.'" selected="selected"&gt;Section '.$i.'&lt;/option&gt;'; } else { echo '&lt;option value="'.$i.'"&gt;Section '.$i.'&lt;/option&gt;'; } } echo '&lt;input id="post-query-submit" type="submit" class="button" value="Filter" name=""&gt;'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); </code></pre> <p>This function alters the user query to add my <code>meta_query</code>:</p> <pre><code>function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() &amp;&amp; 'users.php' == $pagenow &amp;&amp; isset( $_GET[ 'course_section' ] ) &amp;&amp; !empty( $_GET[ 'course_section' ] ) ) { $section = $_GET[ 'course_section' ]; $meta_query = array( array( 'key' =&gt; 'course_section', 'value' =&gt; $section ) ); $query-&gt;set( 'meta_key', 'course_section' ); $query-&gt;set( 'meta_query', $meta_query ); } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); </code></pre> <h2>Other Information</h2> <p>It creates my dropdown correctly. When I select a course section and click <code>Filter</code> the page refreshes and <code>course_section</code> shows up in the URL, but it has no value associated with it. If I check the HTTP requests, it shows that it gets submitted with the correct variable value, but then there's a <code>302 Redirect</code> that seems to strip out the value I selected.</p> <p>If I submit the <code>course_section</code> variable by typing it directly into the URL, the filter works as expected.</p> <p>My code is roughly based on <a href="http://www.davemccourt.com/wp-user-filtering/" rel="noreferrer">this code from Dave Court</a>.</p> <p>I also tried whitelisting my query var using this code, but with no luck:</p> <pre><code>function add_course_section_query_var( $qvars ) { $qvars[] = 'course_section'; return $qvars; } add_filter( 'query_vars', 'add_course_section_query_var' ); </code></pre> <p>I'm using WP 4.4. Any ideas why my filter is not working?</p>
[ { "answer_id": 213582, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 2, "selected": false, "text": "<p>I tested your code in both Wordpress 4.4 and in Wordpress 4.3.1. With version 4.4, I encounter exactly the same issue as you. However, your code works correctly in version 4.3.1! </p>\n\n<p>I think this is a Wordpress bug. I don't know if it's been reported yet. I think the reason behind the bug might be that the submit button is sending the query vars twice. If you look at the query vars, you will see that course_section is listed twice, once with the correct value and once empty. </p>\n\n<h1>Edit: This is the JavaScript Solution</h1>\n\n<p>Simply add this to your theme’s functions.php file and change the NAME_OF_YOUR_INPUT_FIELD to the name of your input field! Since WordPress automatically loads jQuery on the admin side, you do not have to enqueue any scripts. This snippet of code simply adds a change listener to the dropdown inputs and then automatically updates the other dropdown to match the same value. <a href=\"http://www.linsoftware.com/using-the-restrict_manage_users-action-hook-in-wordpress-4-4/\" rel=\"nofollow\">More explanation here.</a></p>\n\n<pre><code>add_action( 'in_admin_footer', function() {\n?&gt;\n&lt;script type=\"text/javascript\"&gt;\n var el = jQuery(\"[name='NAME_OF_YOUR_INPUT_FIELD']\");\n el.change(function() {\n el.val(jQuery(this).val());\n });\n&lt;/script&gt;\n&lt;?php\n} );\n</code></pre>\n\n<p>Hope this helps! </p>\n" }, { "answer_id": 213587, "author": "morphatic", "author_id": 9800, "author_profile": "https://wordpress.stackexchange.com/users/9800", "pm_score": 5, "selected": true, "text": "<h2>UPDATE 2018-06-28</h2>\n\n<p>While the code below mostly works fine, here is a rewrite of the code for WP >=4.6.0 (using PHP 7):</p>\n\n<pre><code>function add_course_section_filter( $which ) {\n\n // create sprintf templates for &lt;select&gt; and &lt;option&gt;s\n $st = '&lt;select name=\"course_section_%s\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;%s&lt;/option&gt;%s&lt;/select&gt;';\n $ot = '&lt;option value=\"%s\" %s&gt;Section %s&lt;/option&gt;';\n\n // determine which filter button was clicked, if any and set section\n $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) );\n $section = $_GET[ 'course_section_' . $button ] ?? -1;\n\n // generate &lt;option&gt; and &lt;select&gt; code\n $options = implode( '', array_map( function($i) use ( $ot, $section ) {\n return sprintf( $ot, $i, selected( $i, $section, false ), $i );\n }, range( 1, 3 ) ));\n $select = sprintf( $st, $which, __( 'Course Section...' ), $options );\n\n // output &lt;select&gt; and submit button\n echo $select;\n submit_button(__( 'Filter' ), null, $which, false);\n}\nadd_action('restrict_manage_users', 'add_course_section_filter');\n\nfunction filter_users_by_course_section($query)\n{\n global $pagenow;\n if (is_admin() &amp;&amp; 'users.php' == $pagenow) {\n $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) );\n if ($section = $_GET[ 'course_section_' . $button ]) {\n $meta_query = [['key' =&gt; 'courses','value' =&gt; $section, 'compare' =&gt; 'LIKE']];\n $query-&gt;set('meta_key', 'courses');\n $query-&gt;set('meta_query', $meta_query);\n }\n }\n}\nadd_filter('pre_get_users', 'filter_users_by_course_section');\n</code></pre>\n\n<p>I incorporated several ideas from @birgire and @cale_b who also offers solutions below that are worth reading. Specifically, I:</p>\n\n<ol>\n<li>Used the <code>$which</code> variable that was added in <code>v4.6.0</code></li>\n<li>Used best practice for i18n by using translatable strings, e.g. <code>__( 'Filter' )</code></li>\n<li>Exchanged loops for the (more fashionable?) <code>array_map()</code>, <code>array_filter()</code>, and <code>range()</code></li>\n<li>Used <code>sprintf()</code> for generating the markup templates</li>\n<li>Used the square bracket array notation instead of <code>array()</code></li>\n</ol>\n\n<p>Lastly, I discovered a bug in my earlier solutions. Those solutions always favor the TOP <code>&lt;select&gt;</code> over the BOTTOM <code>&lt;select&gt;</code>. So if you selected a filter option from the top dropdown, and then subsequently select one from the bottom dropdown, the filter will still only use whatever value was up top (if it's not blank). This new version corrects that bug.</p>\n\n<h2>UPDATE 2018-02-14</h2>\n\n<p>This <a href=\"https://core.trac.wordpress.org/ticket/35307\" rel=\"noreferrer\">issue has been patched since WP 4.6.0</a> and the <a href=\"https://developer.wordpress.org/reference/hooks/restrict_manage_users/\" rel=\"noreferrer\">changes are documented in the official docs</a>. The solution below still works, though.</p>\n\n<h2>What Caused the Problem (WP &lt;4.6.0)</h2>\n\n<p>The problem was that the <code>restrict_manage_users</code> action gets called twice: once ABOVE the Users table, and once BELOW it. This means that TWO <code>select</code> dropdowns get created with the <strong>same name</strong>. When the <code>Filter</code> button is clicked, whatever value is in the second <code>select</code> element (i.e. the one BELOW the table) overrides the value in the first one, i.e. the one ABOVE the table.</p>\n\n<p>In case you want to dive into the WP source, the <code>restrict_manage_users</code> action is triggered from within <a href=\"https://developer.wordpress.org/reference/classes/wp_users_list_table/extra_tablenav/\" rel=\"noreferrer\"><code>WP_Users_List_Table::extra_tablenav($which)</code></a>, which is the function that creates the native dropdown to change a user's role. That function has the help of the <code>$which</code> variable that tells it whether it is creating the <code>select</code> above or below the form, and allows it to give the two dropdowns different <code>name</code> attributes. Unfortunately, the <code>$which</code> variable doesn't get passed to the <code>restrict_manage_users</code> action, so we have to come up with another way to differentiate our own custom elements.</p>\n\n<p>One way to do this, as <a href=\"/a/213582/9800\">@Linnea suggests</a>, would be to add some JavaScript to catch the <code>Filter</code> click and sync up the values of the two dropdowns. I chose a PHP-only solution that I'll describe now.</p>\n\n<h2>How to Fix It</h2>\n\n<p>You can take advantage of the ability to turn HTML inputs into arrays of values, and then filter the array to get rid of any undefined values. Here's the code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function add_course_section_filter() {\n if ( isset( $_GET[ 'course_section' ]) ) {\n $section = $_GET[ 'course_section' ];\n $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ];\n } else {\n $section = -1;\n }\n echo ' &lt;select name=\"course_section[]\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;Course Section...&lt;/option&gt;';\n for ( $i = 1; $i &lt;= 3; ++$i ) {\n $selected = $i == $section ? ' selected=\"selected\"' : '';\n echo '&lt;option value=\"' . $i . '\"' . $selected . '&gt;Section ' . $i . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n echo '&lt;input type=\"submit\" class=\"button\" value=\"Filter\"&gt;';\n }\n add_action( 'restrict_manage_users', 'add_course_section_filter' );\n\n function filter_users_by_course_section( $query ) {\n global $pagenow;\n\n if ( is_admin() &amp;&amp; \n 'users.php' == $pagenow &amp;&amp; \n isset( $_GET[ 'course_section' ] ) &amp;&amp; \n is_array( $_GET[ 'course_section' ] )\n ) {\n $section = $_GET[ 'course_section' ];\n $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ];\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n }\n }\n add_filter( 'pre_get_users', 'filter_users_by_course_section' );\n</code></pre>\n\n<h2>Bonus: PHP 7 Refactor</h2>\n\n<p>Since I'm excited about PHP 7, in case you're running WP on a PHP 7 server, here's a shorter, sexier version using the <a href=\"http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"noreferrer\">null coalescing operator <code>??</code></a>:</p>\n\n<pre><code>function add_course_section_filter() {\n $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? -1;\n echo ' &lt;select name=\"course_section[]\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;Course Section...&lt;/option&gt;';\n for ( $i = 1; $i &lt;= 3; ++$i ) {\n $selected = $i == $section ? ' selected=\"selected\"' : '';\n echo '&lt;option value=\"' . $i . '\"' . $selected . '&gt;Section ' . $i . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n echo '&lt;input type=\"submit\" class=\"button\" value=\"Filter\"&gt;';\n}\nadd_action( 'restrict_manage_users', 'add_course_section_filter' );\n\nfunction filter_users_by_course_section( $query ) {\n global $pagenow;\n\n if ( is_admin() &amp;&amp; 'users.php' == $pagenow) {\n $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? null;\n if ( null !== $section ) {\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n }\n }\n}\nadd_filter( 'pre_get_users', 'filter_users_by_course_section' );\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 213602, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>In the core, the <em>bottom</em> input names are marked with the instance number, e.g. <code>new_role</code> (top) and <code>new_role2</code> (bottom). Here are two approaches for a similar naming convention, namely <code>course_section1</code> (top) and <code>course_section2</code> (bottom):</p>\n\n<h2>Approach #1</h2>\n\n<p>Since the <code>$which</code> variable (<em>top</em>,<em>bottom</em>) doesn't get passed to the <code>restrict_manage_users</code> hook, we could get around that by creating our own version of that hook:</p>\n\n<p>Let's create the action hook <code>wpse_restrict_manage_users</code> that has access to a <code>$which</code> variable:</p>\n\n<pre><code>add_action( 'restrict_manage_users', function() \n{\n static $instance = 0; \n do_action( 'wpse_restrict_manage_users', 1 === ++$instance ? 'top' : 'bottom' );\n\n} );\n</code></pre>\n\n<p>Then we can hook it with:</p>\n\n<pre><code>add_action( 'wpse_restrict_manage_users', function( $which )\n{\n $name = 'top' === $which ? 'course_section1' : 'course_section2';\n\n // your stuff here\n} );\n</code></pre>\n\n<p>where we now have <code>$name</code> as <code>course_section1</code> at the <em>top</em> and <code>course_section2</code> at the <em>bottom</em>.</p>\n\n<h2>Approach #2</h2>\n\n<p>Let's hook into <code>restrict_manage_users</code>, to display dropdowns, with a different name for each instance:</p>\n\n<pre><code>function add_course_section_filter() \n{\n static $instance= 0; \n\n // Dropdown options \n $options = '';\n foreach( range( 1, 3 ) as $rng )\n {\n $options = sprintf( \n '&lt;option value=\"%1$d\" %2$s&gt;Section %1$d&lt;/option&gt;',\n $rng,\n selected( $rng, get_selected_course_section(), 0 )\n );\n }\n\n // Display dropdown with a different name for each instance\n printf( \n '&lt;select name=\"%s\" style=\"float:none;\"&gt;&lt;option value=\"0\"&gt;%s&lt;/option&gt;%s&lt;/select&gt;', \n 'course_section' . ++$instance,\n __( 'Course Section...' ),\n $options \n );\n\n\n // Button\n printf (\n '&lt;input id=\"post-query-submit\" type=\"submit\" class=\"button\" value=\"%s\" name=\"\"&gt;',\n __( 'Filter' )\n );\n}\nadd_action( 'restrict_manage_users', 'add_course_section_filter' );\n</code></pre>\n\n<p>where we used the core function <a href=\"https://codex.wordpress.org/Function_Reference/selected\" rel=\"nofollow\"><code>selected()</code></a> and the helper function:</p>\n\n<pre><code>/**\n * Get the selected course section \n * @return int $course_section\n */\nfunction get_selected_course_section()\n{\n foreach( range( 1, 2) as $rng )\n $course_section = ! empty( $_GET[ 'course_section' . $rng ] )\n ? $_GET[ 'course_section' . $rng ]\n : -1; // default\n\n return (int) $course_section;\n}\n</code></pre>\n\n<p>Then we could also use this when we check for the selected course section in the <code>pre_get_users</code> action callback.</p>\n" }, { "answer_id": 218913, "author": "locomo", "author_id": 42754, "author_profile": "https://wordpress.stackexchange.com/users/42754", "pm_score": 1, "selected": false, "text": "<p>This is a different Javascript solution that may be helpful for some people. In my case I simply removed the 2nd (bottom) select list entirely. I find that I never use the bottom inputs anyway...</p>\n\n<pre><code>add_action( 'in_admin_footer', function() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(\".tablenav.bottom select[name='course_section']\").remove();\n jQuery(\".tablenav.bottom input#post-query-submit\").remove();\n &lt;/script&gt;\n &lt;?php\n} );\n</code></pre>\n" }, { "answer_id": 272419, "author": "random_user_name", "author_id": 11704, "author_profile": "https://wordpress.stackexchange.com/users/11704", "pm_score": 1, "selected": false, "text": "<h1>Non-JavaScript Solution</h1>\n\n<p>Give the select a name that is \"array-style\", like so:</p>\n\n<pre><code>echo '&lt;select name=\"course_section[]\" style=\"float:none;\"&gt;';\n</code></pre>\n\n<p>Then BOTH parameters are passed (from the top and the botom of the table), and now in a known array format.</p>\n\n<p>Then, the value can be used like this in the <code>pre_get_users</code> function:</p>\n\n<pre><code>function filter_users_by_course_section( $query ) {\n global $pagenow;\n\n // if not on users page in admin, get out\n if ( ! is_admin() || 'users.php' != $pagenow ) {\n return;\n } \n\n // if no section selected, get out\n if ( empty( $_GET['course_section'] ) ) {\n return;\n }\n\n // course_section is known to be set now, so load it\n $section = $_GET['course_section'];\n\n // the value is an array, and one of the two select boxes was likely\n // not set to anything, so use array_filter to eliminate empty elements\n $section = array_filter( $section );\n\n // the value is still an array, so get the first value\n $section = reset( $section );\n\n // now the value is a single value, such as 1\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n}\n</code></pre>\n" }, { "answer_id": 293946, "author": "Alpha Elf", "author_id": 136679, "author_profile": "https://wordpress.stackexchange.com/users/136679", "pm_score": 0, "selected": false, "text": "<h2>another solution</h2>\n<p>you can put your filter select box in separate file like <code>user_list_filter.php</code></p>\n<p>and use <code>require_once 'user_list_filter.php'</code> in your action callback function</p>\n<p><code>user_list_filter.php</code> file:</p>\n<pre><code>&lt;select name=&quot;course_section&quot; style=&quot;float:none;&quot;&gt;\n &lt;option value=&quot;&quot;&gt;Course Section...&lt;/option&gt;\n &lt;?php for ( $i = 1; $i &lt;= 3; ++$i ) {\n if ( $i == $_GET[ 'course_section' ] ) { ?&gt;\n &lt;option value=&quot;&lt;?=$i?&gt;&quot; selected=&quot;selected&quot;&gt;Section &lt;?=$i?&gt;&lt;/option&gt;\n &lt;?php } else { ?&gt;\n &lt;option value=&quot;&lt;?=$i?&gt;&quot;&gt;Section &lt;?=$i?&gt;&lt;/option&gt;\n &lt;?php }\n }?&gt;\n&lt;/select&gt;\n&lt;input id=&quot;post-query-submit&quot; type=&quot;submit&quot; class=&quot;button&quot; value=&quot;Filter&quot; name=&quot;&quot;&gt;\n</code></pre>\n<p>and in your action callback:</p>\n<pre><code>function add_course_section_filter() {\n require_once 'user_list_filter.php';\n}\n</code></pre>\n" } ]
2016/01/04
[ "https://wordpress.stackexchange.com/questions/213576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9800/" ]
The Problem ----------- WP appears to remove the value of my query variable before it gets used to filter the list of users. My Code ------- This function adds a custom column to my Users table on `/wp-admin/users.php`: ``` function add_course_section_to_user_meta( $columns ) { $columns['course_section'] = 'Section'; return $columns; } add_filter( 'manage_users_columns', 'add_course_section_to_user_meta' ); ``` This function tells WP how to fill values in the column: ``` function manage_users_course_section( $val, $col, $uid ) { if ( 'course_section' === $col ) return get_the_author_meta( 'course_section', $uid ); } add_filter( 'manage_users_custom_column', 'manage_users_course_section' ); ``` This adds a dropdown and `Filter` button above the Users table: ``` function add_course_section_filter() { echo '<select name="course_section" style="float:none;">'; echo '<option value="">Course Section...</option>'; for ( $i = 1; $i <= 3; ++$i ) { if ( $i == $_GET[ 'course_section' ] ) { echo '<option value="'.$i.'" selected="selected">Section '.$i.'</option>'; } else { echo '<option value="'.$i.'">Section '.$i.'</option>'; } } echo '<input id="post-query-submit" type="submit" class="button" value="Filter" name="">'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); ``` This function alters the user query to add my `meta_query`: ``` function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow && isset( $_GET[ 'course_section' ] ) && !empty( $_GET[ 'course_section' ] ) ) { $section = $_GET[ 'course_section' ]; $meta_query = array( array( 'key' => 'course_section', 'value' => $section ) ); $query->set( 'meta_key', 'course_section' ); $query->set( 'meta_query', $meta_query ); } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); ``` Other Information ----------------- It creates my dropdown correctly. When I select a course section and click `Filter` the page refreshes and `course_section` shows up in the URL, but it has no value associated with it. If I check the HTTP requests, it shows that it gets submitted with the correct variable value, but then there's a `302 Redirect` that seems to strip out the value I selected. If I submit the `course_section` variable by typing it directly into the URL, the filter works as expected. My code is roughly based on [this code from Dave Court](http://www.davemccourt.com/wp-user-filtering/). I also tried whitelisting my query var using this code, but with no luck: ``` function add_course_section_query_var( $qvars ) { $qvars[] = 'course_section'; return $qvars; } add_filter( 'query_vars', 'add_course_section_query_var' ); ``` I'm using WP 4.4. Any ideas why my filter is not working?
UPDATE 2018-06-28 ----------------- While the code below mostly works fine, here is a rewrite of the code for WP >=4.6.0 (using PHP 7): ``` function add_course_section_filter( $which ) { // create sprintf templates for <select> and <option>s $st = '<select name="course_section_%s" style="float:none;"><option value="">%s</option>%s</select>'; $ot = '<option value="%s" %s>Section %s</option>'; // determine which filter button was clicked, if any and set section $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) ); $section = $_GET[ 'course_section_' . $button ] ?? -1; // generate <option> and <select> code $options = implode( '', array_map( function($i) use ( $ot, $section ) { return sprintf( $ot, $i, selected( $i, $section, false ), $i ); }, range( 1, 3 ) )); $select = sprintf( $st, $which, __( 'Course Section...' ), $options ); // output <select> and submit button echo $select; submit_button(__( 'Filter' ), null, $which, false); } add_action('restrict_manage_users', 'add_course_section_filter'); function filter_users_by_course_section($query) { global $pagenow; if (is_admin() && 'users.php' == $pagenow) { $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) ); if ($section = $_GET[ 'course_section_' . $button ]) { $meta_query = [['key' => 'courses','value' => $section, 'compare' => 'LIKE']]; $query->set('meta_key', 'courses'); $query->set('meta_query', $meta_query); } } } add_filter('pre_get_users', 'filter_users_by_course_section'); ``` I incorporated several ideas from @birgire and @cale\_b who also offers solutions below that are worth reading. Specifically, I: 1. Used the `$which` variable that was added in `v4.6.0` 2. Used best practice for i18n by using translatable strings, e.g. `__( 'Filter' )` 3. Exchanged loops for the (more fashionable?) `array_map()`, `array_filter()`, and `range()` 4. Used `sprintf()` for generating the markup templates 5. Used the square bracket array notation instead of `array()` Lastly, I discovered a bug in my earlier solutions. Those solutions always favor the TOP `<select>` over the BOTTOM `<select>`. So if you selected a filter option from the top dropdown, and then subsequently select one from the bottom dropdown, the filter will still only use whatever value was up top (if it's not blank). This new version corrects that bug. UPDATE 2018-02-14 ----------------- This [issue has been patched since WP 4.6.0](https://core.trac.wordpress.org/ticket/35307) and the [changes are documented in the official docs](https://developer.wordpress.org/reference/hooks/restrict_manage_users/). The solution below still works, though. What Caused the Problem (WP <4.6.0) ----------------------------------- The problem was that the `restrict_manage_users` action gets called twice: once ABOVE the Users table, and once BELOW it. This means that TWO `select` dropdowns get created with the **same name**. When the `Filter` button is clicked, whatever value is in the second `select` element (i.e. the one BELOW the table) overrides the value in the first one, i.e. the one ABOVE the table. In case you want to dive into the WP source, the `restrict_manage_users` action is triggered from within [`WP_Users_List_Table::extra_tablenav($which)`](https://developer.wordpress.org/reference/classes/wp_users_list_table/extra_tablenav/), which is the function that creates the native dropdown to change a user's role. That function has the help of the `$which` variable that tells it whether it is creating the `select` above or below the form, and allows it to give the two dropdowns different `name` attributes. Unfortunately, the `$which` variable doesn't get passed to the `restrict_manage_users` action, so we have to come up with another way to differentiate our own custom elements. One way to do this, as [@Linnea suggests](/a/213582/9800), would be to add some JavaScript to catch the `Filter` click and sync up the values of the two dropdowns. I chose a PHP-only solution that I'll describe now. How to Fix It ------------- You can take advantage of the ability to turn HTML inputs into arrays of values, and then filter the array to get rid of any undefined values. Here's the code: ```php function add_course_section_filter() { if ( isset( $_GET[ 'course_section' ]) ) { $section = $_GET[ 'course_section' ]; $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ]; } else { $section = -1; } echo ' <select name="course_section[]" style="float:none;"><option value="">Course Section...</option>'; for ( $i = 1; $i <= 3; ++$i ) { $selected = $i == $section ? ' selected="selected"' : ''; echo '<option value="' . $i . '"' . $selected . '>Section ' . $i . '</option>'; } echo '</select>'; echo '<input type="submit" class="button" value="Filter">'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow && isset( $_GET[ 'course_section' ] ) && is_array( $_GET[ 'course_section' ] ) ) { $section = $_GET[ 'course_section' ]; $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ]; $meta_query = array( array( 'key' => 'course_section', 'value' => $section ) ); $query->set( 'meta_key', 'course_section' ); $query->set( 'meta_query', $meta_query ); } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); ``` Bonus: PHP 7 Refactor --------------------- Since I'm excited about PHP 7, in case you're running WP on a PHP 7 server, here's a shorter, sexier version using the [null coalescing operator `??`](http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op): ``` function add_course_section_filter() { $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? -1; echo ' <select name="course_section[]" style="float:none;"><option value="">Course Section...</option>'; for ( $i = 1; $i <= 3; ++$i ) { $selected = $i == $section ? ' selected="selected"' : ''; echo '<option value="' . $i . '"' . $selected . '>Section ' . $i . '</option>'; } echo '</select>'; echo '<input type="submit" class="button" value="Filter">'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow) { $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? null; if ( null !== $section ) { $meta_query = array( array( 'key' => 'course_section', 'value' => $section ) ); $query->set( 'meta_key', 'course_section' ); $query->set( 'meta_query', $meta_query ); } } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); ``` Enjoy!
213,584
<p>I am working on a website that uses a previously developed image slider plugin. I had it all working in my local environment but once I took it live it kicked the following error anywhere the image slider is located...</p> <pre><code>Warning: Missing argument 2 for wpdb::prepare(), called in /home/content/r/o/b/robertrhuspeak/html/desarch/wp content/plugins/portfolio/fields.php on line 48 and defined in /home/content/r/o/b/robertrhuspeak/html/desarch/wp-includes/wp-db.php on line 1246 </code></pre> <p>The line of code it is referencing looks like this...</p> <pre><code>$fields = $wpdb-&gt;get_results($wpdb-&gt;prepare("SELECT meta_key, meta_value, meta_order IS NULL AS isnull FROM $wpdb-&gt;postmeta WHERE post_id=$postID ORDER BY isnull ASC, ABS(meta_order) ASC, meta_id")); </code></pre> <p>My understanding is that wp-db.php is expecting two arguments and the above code is not written with two arguments.</p> <p>BUT, I frankly have no idea how it should be written. And I have dug hard on the Internet to find something that will explain it to me clearly.</p> <p>Any guidance would be greatly appreciated.</p> <p>Thanks!</p>
[ { "answer_id": 213582, "author": "Linnea Huxford", "author_id": 86210, "author_profile": "https://wordpress.stackexchange.com/users/86210", "pm_score": 2, "selected": false, "text": "<p>I tested your code in both Wordpress 4.4 and in Wordpress 4.3.1. With version 4.4, I encounter exactly the same issue as you. However, your code works correctly in version 4.3.1! </p>\n\n<p>I think this is a Wordpress bug. I don't know if it's been reported yet. I think the reason behind the bug might be that the submit button is sending the query vars twice. If you look at the query vars, you will see that course_section is listed twice, once with the correct value and once empty. </p>\n\n<h1>Edit: This is the JavaScript Solution</h1>\n\n<p>Simply add this to your theme’s functions.php file and change the NAME_OF_YOUR_INPUT_FIELD to the name of your input field! Since WordPress automatically loads jQuery on the admin side, you do not have to enqueue any scripts. This snippet of code simply adds a change listener to the dropdown inputs and then automatically updates the other dropdown to match the same value. <a href=\"http://www.linsoftware.com/using-the-restrict_manage_users-action-hook-in-wordpress-4-4/\" rel=\"nofollow\">More explanation here.</a></p>\n\n<pre><code>add_action( 'in_admin_footer', function() {\n?&gt;\n&lt;script type=\"text/javascript\"&gt;\n var el = jQuery(\"[name='NAME_OF_YOUR_INPUT_FIELD']\");\n el.change(function() {\n el.val(jQuery(this).val());\n });\n&lt;/script&gt;\n&lt;?php\n} );\n</code></pre>\n\n<p>Hope this helps! </p>\n" }, { "answer_id": 213587, "author": "morphatic", "author_id": 9800, "author_profile": "https://wordpress.stackexchange.com/users/9800", "pm_score": 5, "selected": true, "text": "<h2>UPDATE 2018-06-28</h2>\n\n<p>While the code below mostly works fine, here is a rewrite of the code for WP >=4.6.0 (using PHP 7):</p>\n\n<pre><code>function add_course_section_filter( $which ) {\n\n // create sprintf templates for &lt;select&gt; and &lt;option&gt;s\n $st = '&lt;select name=\"course_section_%s\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;%s&lt;/option&gt;%s&lt;/select&gt;';\n $ot = '&lt;option value=\"%s\" %s&gt;Section %s&lt;/option&gt;';\n\n // determine which filter button was clicked, if any and set section\n $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) );\n $section = $_GET[ 'course_section_' . $button ] ?? -1;\n\n // generate &lt;option&gt; and &lt;select&gt; code\n $options = implode( '', array_map( function($i) use ( $ot, $section ) {\n return sprintf( $ot, $i, selected( $i, $section, false ), $i );\n }, range( 1, 3 ) ));\n $select = sprintf( $st, $which, __( 'Course Section...' ), $options );\n\n // output &lt;select&gt; and submit button\n echo $select;\n submit_button(__( 'Filter' ), null, $which, false);\n}\nadd_action('restrict_manage_users', 'add_course_section_filter');\n\nfunction filter_users_by_course_section($query)\n{\n global $pagenow;\n if (is_admin() &amp;&amp; 'users.php' == $pagenow) {\n $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) );\n if ($section = $_GET[ 'course_section_' . $button ]) {\n $meta_query = [['key' =&gt; 'courses','value' =&gt; $section, 'compare' =&gt; 'LIKE']];\n $query-&gt;set('meta_key', 'courses');\n $query-&gt;set('meta_query', $meta_query);\n }\n }\n}\nadd_filter('pre_get_users', 'filter_users_by_course_section');\n</code></pre>\n\n<p>I incorporated several ideas from @birgire and @cale_b who also offers solutions below that are worth reading. Specifically, I:</p>\n\n<ol>\n<li>Used the <code>$which</code> variable that was added in <code>v4.6.0</code></li>\n<li>Used best practice for i18n by using translatable strings, e.g. <code>__( 'Filter' )</code></li>\n<li>Exchanged loops for the (more fashionable?) <code>array_map()</code>, <code>array_filter()</code>, and <code>range()</code></li>\n<li>Used <code>sprintf()</code> for generating the markup templates</li>\n<li>Used the square bracket array notation instead of <code>array()</code></li>\n</ol>\n\n<p>Lastly, I discovered a bug in my earlier solutions. Those solutions always favor the TOP <code>&lt;select&gt;</code> over the BOTTOM <code>&lt;select&gt;</code>. So if you selected a filter option from the top dropdown, and then subsequently select one from the bottom dropdown, the filter will still only use whatever value was up top (if it's not blank). This new version corrects that bug.</p>\n\n<h2>UPDATE 2018-02-14</h2>\n\n<p>This <a href=\"https://core.trac.wordpress.org/ticket/35307\" rel=\"noreferrer\">issue has been patched since WP 4.6.0</a> and the <a href=\"https://developer.wordpress.org/reference/hooks/restrict_manage_users/\" rel=\"noreferrer\">changes are documented in the official docs</a>. The solution below still works, though.</p>\n\n<h2>What Caused the Problem (WP &lt;4.6.0)</h2>\n\n<p>The problem was that the <code>restrict_manage_users</code> action gets called twice: once ABOVE the Users table, and once BELOW it. This means that TWO <code>select</code> dropdowns get created with the <strong>same name</strong>. When the <code>Filter</code> button is clicked, whatever value is in the second <code>select</code> element (i.e. the one BELOW the table) overrides the value in the first one, i.e. the one ABOVE the table.</p>\n\n<p>In case you want to dive into the WP source, the <code>restrict_manage_users</code> action is triggered from within <a href=\"https://developer.wordpress.org/reference/classes/wp_users_list_table/extra_tablenav/\" rel=\"noreferrer\"><code>WP_Users_List_Table::extra_tablenav($which)</code></a>, which is the function that creates the native dropdown to change a user's role. That function has the help of the <code>$which</code> variable that tells it whether it is creating the <code>select</code> above or below the form, and allows it to give the two dropdowns different <code>name</code> attributes. Unfortunately, the <code>$which</code> variable doesn't get passed to the <code>restrict_manage_users</code> action, so we have to come up with another way to differentiate our own custom elements.</p>\n\n<p>One way to do this, as <a href=\"/a/213582/9800\">@Linnea suggests</a>, would be to add some JavaScript to catch the <code>Filter</code> click and sync up the values of the two dropdowns. I chose a PHP-only solution that I'll describe now.</p>\n\n<h2>How to Fix It</h2>\n\n<p>You can take advantage of the ability to turn HTML inputs into arrays of values, and then filter the array to get rid of any undefined values. Here's the code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function add_course_section_filter() {\n if ( isset( $_GET[ 'course_section' ]) ) {\n $section = $_GET[ 'course_section' ];\n $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ];\n } else {\n $section = -1;\n }\n echo ' &lt;select name=\"course_section[]\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;Course Section...&lt;/option&gt;';\n for ( $i = 1; $i &lt;= 3; ++$i ) {\n $selected = $i == $section ? ' selected=\"selected\"' : '';\n echo '&lt;option value=\"' . $i . '\"' . $selected . '&gt;Section ' . $i . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n echo '&lt;input type=\"submit\" class=\"button\" value=\"Filter\"&gt;';\n }\n add_action( 'restrict_manage_users', 'add_course_section_filter' );\n\n function filter_users_by_course_section( $query ) {\n global $pagenow;\n\n if ( is_admin() &amp;&amp; \n 'users.php' == $pagenow &amp;&amp; \n isset( $_GET[ 'course_section' ] ) &amp;&amp; \n is_array( $_GET[ 'course_section' ] )\n ) {\n $section = $_GET[ 'course_section' ];\n $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ];\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n }\n }\n add_filter( 'pre_get_users', 'filter_users_by_course_section' );\n</code></pre>\n\n<h2>Bonus: PHP 7 Refactor</h2>\n\n<p>Since I'm excited about PHP 7, in case you're running WP on a PHP 7 server, here's a shorter, sexier version using the <a href=\"http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"noreferrer\">null coalescing operator <code>??</code></a>:</p>\n\n<pre><code>function add_course_section_filter() {\n $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? -1;\n echo ' &lt;select name=\"course_section[]\" style=\"float:none;\"&gt;&lt;option value=\"\"&gt;Course Section...&lt;/option&gt;';\n for ( $i = 1; $i &lt;= 3; ++$i ) {\n $selected = $i == $section ? ' selected=\"selected\"' : '';\n echo '&lt;option value=\"' . $i . '\"' . $selected . '&gt;Section ' . $i . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n echo '&lt;input type=\"submit\" class=\"button\" value=\"Filter\"&gt;';\n}\nadd_action( 'restrict_manage_users', 'add_course_section_filter' );\n\nfunction filter_users_by_course_section( $query ) {\n global $pagenow;\n\n if ( is_admin() &amp;&amp; 'users.php' == $pagenow) {\n $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? null;\n if ( null !== $section ) {\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n }\n }\n}\nadd_filter( 'pre_get_users', 'filter_users_by_course_section' );\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 213602, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>In the core, the <em>bottom</em> input names are marked with the instance number, e.g. <code>new_role</code> (top) and <code>new_role2</code> (bottom). Here are two approaches for a similar naming convention, namely <code>course_section1</code> (top) and <code>course_section2</code> (bottom):</p>\n\n<h2>Approach #1</h2>\n\n<p>Since the <code>$which</code> variable (<em>top</em>,<em>bottom</em>) doesn't get passed to the <code>restrict_manage_users</code> hook, we could get around that by creating our own version of that hook:</p>\n\n<p>Let's create the action hook <code>wpse_restrict_manage_users</code> that has access to a <code>$which</code> variable:</p>\n\n<pre><code>add_action( 'restrict_manage_users', function() \n{\n static $instance = 0; \n do_action( 'wpse_restrict_manage_users', 1 === ++$instance ? 'top' : 'bottom' );\n\n} );\n</code></pre>\n\n<p>Then we can hook it with:</p>\n\n<pre><code>add_action( 'wpse_restrict_manage_users', function( $which )\n{\n $name = 'top' === $which ? 'course_section1' : 'course_section2';\n\n // your stuff here\n} );\n</code></pre>\n\n<p>where we now have <code>$name</code> as <code>course_section1</code> at the <em>top</em> and <code>course_section2</code> at the <em>bottom</em>.</p>\n\n<h2>Approach #2</h2>\n\n<p>Let's hook into <code>restrict_manage_users</code>, to display dropdowns, with a different name for each instance:</p>\n\n<pre><code>function add_course_section_filter() \n{\n static $instance= 0; \n\n // Dropdown options \n $options = '';\n foreach( range( 1, 3 ) as $rng )\n {\n $options = sprintf( \n '&lt;option value=\"%1$d\" %2$s&gt;Section %1$d&lt;/option&gt;',\n $rng,\n selected( $rng, get_selected_course_section(), 0 )\n );\n }\n\n // Display dropdown with a different name for each instance\n printf( \n '&lt;select name=\"%s\" style=\"float:none;\"&gt;&lt;option value=\"0\"&gt;%s&lt;/option&gt;%s&lt;/select&gt;', \n 'course_section' . ++$instance,\n __( 'Course Section...' ),\n $options \n );\n\n\n // Button\n printf (\n '&lt;input id=\"post-query-submit\" type=\"submit\" class=\"button\" value=\"%s\" name=\"\"&gt;',\n __( 'Filter' )\n );\n}\nadd_action( 'restrict_manage_users', 'add_course_section_filter' );\n</code></pre>\n\n<p>where we used the core function <a href=\"https://codex.wordpress.org/Function_Reference/selected\" rel=\"nofollow\"><code>selected()</code></a> and the helper function:</p>\n\n<pre><code>/**\n * Get the selected course section \n * @return int $course_section\n */\nfunction get_selected_course_section()\n{\n foreach( range( 1, 2) as $rng )\n $course_section = ! empty( $_GET[ 'course_section' . $rng ] )\n ? $_GET[ 'course_section' . $rng ]\n : -1; // default\n\n return (int) $course_section;\n}\n</code></pre>\n\n<p>Then we could also use this when we check for the selected course section in the <code>pre_get_users</code> action callback.</p>\n" }, { "answer_id": 218913, "author": "locomo", "author_id": 42754, "author_profile": "https://wordpress.stackexchange.com/users/42754", "pm_score": 1, "selected": false, "text": "<p>This is a different Javascript solution that may be helpful for some people. In my case I simply removed the 2nd (bottom) select list entirely. I find that I never use the bottom inputs anyway...</p>\n\n<pre><code>add_action( 'in_admin_footer', function() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(\".tablenav.bottom select[name='course_section']\").remove();\n jQuery(\".tablenav.bottom input#post-query-submit\").remove();\n &lt;/script&gt;\n &lt;?php\n} );\n</code></pre>\n" }, { "answer_id": 272419, "author": "random_user_name", "author_id": 11704, "author_profile": "https://wordpress.stackexchange.com/users/11704", "pm_score": 1, "selected": false, "text": "<h1>Non-JavaScript Solution</h1>\n\n<p>Give the select a name that is \"array-style\", like so:</p>\n\n<pre><code>echo '&lt;select name=\"course_section[]\" style=\"float:none;\"&gt;';\n</code></pre>\n\n<p>Then BOTH parameters are passed (from the top and the botom of the table), and now in a known array format.</p>\n\n<p>Then, the value can be used like this in the <code>pre_get_users</code> function:</p>\n\n<pre><code>function filter_users_by_course_section( $query ) {\n global $pagenow;\n\n // if not on users page in admin, get out\n if ( ! is_admin() || 'users.php' != $pagenow ) {\n return;\n } \n\n // if no section selected, get out\n if ( empty( $_GET['course_section'] ) ) {\n return;\n }\n\n // course_section is known to be set now, so load it\n $section = $_GET['course_section'];\n\n // the value is an array, and one of the two select boxes was likely\n // not set to anything, so use array_filter to eliminate empty elements\n $section = array_filter( $section );\n\n // the value is still an array, so get the first value\n $section = reset( $section );\n\n // now the value is a single value, such as 1\n $meta_query = array(\n array(\n 'key' =&gt; 'course_section',\n 'value' =&gt; $section\n )\n );\n\n $query-&gt;set( 'meta_key', 'course_section' );\n $query-&gt;set( 'meta_query', $meta_query );\n}\n</code></pre>\n" }, { "answer_id": 293946, "author": "Alpha Elf", "author_id": 136679, "author_profile": "https://wordpress.stackexchange.com/users/136679", "pm_score": 0, "selected": false, "text": "<h2>another solution</h2>\n<p>you can put your filter select box in separate file like <code>user_list_filter.php</code></p>\n<p>and use <code>require_once 'user_list_filter.php'</code> in your action callback function</p>\n<p><code>user_list_filter.php</code> file:</p>\n<pre><code>&lt;select name=&quot;course_section&quot; style=&quot;float:none;&quot;&gt;\n &lt;option value=&quot;&quot;&gt;Course Section...&lt;/option&gt;\n &lt;?php for ( $i = 1; $i &lt;= 3; ++$i ) {\n if ( $i == $_GET[ 'course_section' ] ) { ?&gt;\n &lt;option value=&quot;&lt;?=$i?&gt;&quot; selected=&quot;selected&quot;&gt;Section &lt;?=$i?&gt;&lt;/option&gt;\n &lt;?php } else { ?&gt;\n &lt;option value=&quot;&lt;?=$i?&gt;&quot;&gt;Section &lt;?=$i?&gt;&lt;/option&gt;\n &lt;?php }\n }?&gt;\n&lt;/select&gt;\n&lt;input id=&quot;post-query-submit&quot; type=&quot;submit&quot; class=&quot;button&quot; value=&quot;Filter&quot; name=&quot;&quot;&gt;\n</code></pre>\n<p>and in your action callback:</p>\n<pre><code>function add_course_section_filter() {\n require_once 'user_list_filter.php';\n}\n</code></pre>\n" } ]
2016/01/04
[ "https://wordpress.stackexchange.com/questions/213584", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67018/" ]
I am working on a website that uses a previously developed image slider plugin. I had it all working in my local environment but once I took it live it kicked the following error anywhere the image slider is located... ``` Warning: Missing argument 2 for wpdb::prepare(), called in /home/content/r/o/b/robertrhuspeak/html/desarch/wp content/plugins/portfolio/fields.php on line 48 and defined in /home/content/r/o/b/robertrhuspeak/html/desarch/wp-includes/wp-db.php on line 1246 ``` The line of code it is referencing looks like this... ``` $fields = $wpdb->get_results($wpdb->prepare("SELECT meta_key, meta_value, meta_order IS NULL AS isnull FROM $wpdb->postmeta WHERE post_id=$postID ORDER BY isnull ASC, ABS(meta_order) ASC, meta_id")); ``` My understanding is that wp-db.php is expecting two arguments and the above code is not written with two arguments. BUT, I frankly have no idea how it should be written. And I have dug hard on the Internet to find something that will explain it to me clearly. Any guidance would be greatly appreciated. Thanks!
UPDATE 2018-06-28 ----------------- While the code below mostly works fine, here is a rewrite of the code for WP >=4.6.0 (using PHP 7): ``` function add_course_section_filter( $which ) { // create sprintf templates for <select> and <option>s $st = '<select name="course_section_%s" style="float:none;"><option value="">%s</option>%s</select>'; $ot = '<option value="%s" %s>Section %s</option>'; // determine which filter button was clicked, if any and set section $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) ); $section = $_GET[ 'course_section_' . $button ] ?? -1; // generate <option> and <select> code $options = implode( '', array_map( function($i) use ( $ot, $section ) { return sprintf( $ot, $i, selected( $i, $section, false ), $i ); }, range( 1, 3 ) )); $select = sprintf( $st, $which, __( 'Course Section...' ), $options ); // output <select> and submit button echo $select; submit_button(__( 'Filter' ), null, $which, false); } add_action('restrict_manage_users', 'add_course_section_filter'); function filter_users_by_course_section($query) { global $pagenow; if (is_admin() && 'users.php' == $pagenow) { $button = key( array_filter( $_GET, function($v) { return __( 'Filter' ) === $v; } ) ); if ($section = $_GET[ 'course_section_' . $button ]) { $meta_query = [['key' => 'courses','value' => $section, 'compare' => 'LIKE']]; $query->set('meta_key', 'courses'); $query->set('meta_query', $meta_query); } } } add_filter('pre_get_users', 'filter_users_by_course_section'); ``` I incorporated several ideas from @birgire and @cale\_b who also offers solutions below that are worth reading. Specifically, I: 1. Used the `$which` variable that was added in `v4.6.0` 2. Used best practice for i18n by using translatable strings, e.g. `__( 'Filter' )` 3. Exchanged loops for the (more fashionable?) `array_map()`, `array_filter()`, and `range()` 4. Used `sprintf()` for generating the markup templates 5. Used the square bracket array notation instead of `array()` Lastly, I discovered a bug in my earlier solutions. Those solutions always favor the TOP `<select>` over the BOTTOM `<select>`. So if you selected a filter option from the top dropdown, and then subsequently select one from the bottom dropdown, the filter will still only use whatever value was up top (if it's not blank). This new version corrects that bug. UPDATE 2018-02-14 ----------------- This [issue has been patched since WP 4.6.0](https://core.trac.wordpress.org/ticket/35307) and the [changes are documented in the official docs](https://developer.wordpress.org/reference/hooks/restrict_manage_users/). The solution below still works, though. What Caused the Problem (WP <4.6.0) ----------------------------------- The problem was that the `restrict_manage_users` action gets called twice: once ABOVE the Users table, and once BELOW it. This means that TWO `select` dropdowns get created with the **same name**. When the `Filter` button is clicked, whatever value is in the second `select` element (i.e. the one BELOW the table) overrides the value in the first one, i.e. the one ABOVE the table. In case you want to dive into the WP source, the `restrict_manage_users` action is triggered from within [`WP_Users_List_Table::extra_tablenav($which)`](https://developer.wordpress.org/reference/classes/wp_users_list_table/extra_tablenav/), which is the function that creates the native dropdown to change a user's role. That function has the help of the `$which` variable that tells it whether it is creating the `select` above or below the form, and allows it to give the two dropdowns different `name` attributes. Unfortunately, the `$which` variable doesn't get passed to the `restrict_manage_users` action, so we have to come up with another way to differentiate our own custom elements. One way to do this, as [@Linnea suggests](/a/213582/9800), would be to add some JavaScript to catch the `Filter` click and sync up the values of the two dropdowns. I chose a PHP-only solution that I'll describe now. How to Fix It ------------- You can take advantage of the ability to turn HTML inputs into arrays of values, and then filter the array to get rid of any undefined values. Here's the code: ```php function add_course_section_filter() { if ( isset( $_GET[ 'course_section' ]) ) { $section = $_GET[ 'course_section' ]; $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ]; } else { $section = -1; } echo ' <select name="course_section[]" style="float:none;"><option value="">Course Section...</option>'; for ( $i = 1; $i <= 3; ++$i ) { $selected = $i == $section ? ' selected="selected"' : ''; echo '<option value="' . $i . '"' . $selected . '>Section ' . $i . '</option>'; } echo '</select>'; echo '<input type="submit" class="button" value="Filter">'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow && isset( $_GET[ 'course_section' ] ) && is_array( $_GET[ 'course_section' ] ) ) { $section = $_GET[ 'course_section' ]; $section = !empty( $section[ 0 ] ) ? $section[ 0 ] : $section[ 1 ]; $meta_query = array( array( 'key' => 'course_section', 'value' => $section ) ); $query->set( 'meta_key', 'course_section' ); $query->set( 'meta_query', $meta_query ); } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); ``` Bonus: PHP 7 Refactor --------------------- Since I'm excited about PHP 7, in case you're running WP on a PHP 7 server, here's a shorter, sexier version using the [null coalescing operator `??`](http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op): ``` function add_course_section_filter() { $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? -1; echo ' <select name="course_section[]" style="float:none;"><option value="">Course Section...</option>'; for ( $i = 1; $i <= 3; ++$i ) { $selected = $i == $section ? ' selected="selected"' : ''; echo '<option value="' . $i . '"' . $selected . '>Section ' . $i . '</option>'; } echo '</select>'; echo '<input type="submit" class="button" value="Filter">'; } add_action( 'restrict_manage_users', 'add_course_section_filter' ); function filter_users_by_course_section( $query ) { global $pagenow; if ( is_admin() && 'users.php' == $pagenow) { $section = $_GET[ 'course_section' ][ 0 ] ?? $_GET[ 'course_section' ][ 1 ] ?? null; if ( null !== $section ) { $meta_query = array( array( 'key' => 'course_section', 'value' => $section ) ); $query->set( 'meta_key', 'course_section' ); $query->set( 'meta_query', $meta_query ); } } } add_filter( 'pre_get_users', 'filter_users_by_course_section' ); ``` Enjoy!
213,612
<p>I am trying to send an email to customer after purchased products and when customer click on the the link provided the email for rating the product it should redirect to customer's account/My account page.<br> I put some code in functions.php to get the WooCommerce My Account URL:</p> <pre><code>$myaccount_page = get_option( 'woocommerce_myaccount_page_id' ); if ( $myaccount_page ) { $myaccount_page_url = get_permalink( $myaccount_page ); } </code></pre> <p>I have customized into <strong>customer-completed-order.php</strong> and put this code</p> <pre><code> &lt;h2&gt; Go to your account page for review &lt;/h2&gt; &lt;a href="http://animax.cf/product/happy-ninja/#reviews"&gt; &lt;img src="http://animax.cf/wp-content/uploads/2015/12/product-reviews.png" alt="Product Rating"&gt; &lt;/a&gt; </code></pre> <p>I want to get woocomerce myaccount url in above code. how should i do this.</p>
[ { "answer_id": 213614, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 6, "selected": true, "text": "<p>You can get the WooCommerce my-account URL as below</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?&gt;\" title=\"&lt;?php _e('My Account',''); ?&gt;\"&gt;&lt;?php _e('My Account',''); ?&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Now you can insert this in completed order mail template too.</p>\n\n<pre><code>&lt;h2&gt; &lt;a href=\"&lt;?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?&gt;\" title=\"&lt;?php _e('My Account',''); ?&gt;\"&gt;Go to your account page for review&lt;/a&gt; &lt;/h2&gt;\n&lt;a href=\"http://animax.cf/product/happy-ninja/#reviews\"&gt;\n &lt;img src=\"http://animax.cf/wp-content/uploads/2015/12/product-reviews.png\" alt=\"Product Rating\"&gt;\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 302926, "author": "user143165", "author_id": 143165, "author_profile": "https://wordpress.stackexchange.com/users/143165", "pm_score": 4, "selected": false, "text": "<p>woocommerce wc_get_page_id function will help you to create WooCommerce pages URLs </p>\n\n<p>Examples of usage:</p>\n\n<p>My Account</p>\n\n<pre><code>&lt;?php echo get_permalink( wc_get_page_id( 'myaccount' ) ); ?&gt;\n</code></pre>\n\n<p>Shop</p>\n\n<pre><code>&lt;?php echo get_permalink( wc_get_page_id( 'shop' ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 327595, "author": "Iulia Cazan", "author_id": 160480, "author_profile": "https://wordpress.stackexchange.com/users/160480", "pm_score": 3, "selected": false, "text": "<p>There is another way to do this using the WooCommerce native endpoints (you can use any of the registered endpoints with WC or third-party plugins that hook into WC):\n<code>&lt;?php echo esc_url( wc_get_account_endpoint_url( 'edit-account' ) ); ?&gt;</code></p>\n\n<p>For dashboard you could use something like this\n<code>&lt;?php echo esc_url( trailingslashit( wc_get_account_endpoint_url( '' ) ) ); ?&gt;</code></p>\n" }, { "answer_id": 342864, "author": "Naved Khan", "author_id": 171847, "author_profile": "https://wordpress.stackexchange.com/users/171847", "pm_score": -1, "selected": false, "text": "<pre><code> &lt;?php \n if ( is_front_page() &amp;&amp; is_home() ) {\n // Default homepage\n echo \"Default homepage\";\n\n } elseif ( is_front_page()){\n\n echo \"Static homepage\";\n // Static homepage\n\n } elseif ( is_home()){\n echo \"Blog page\";\n // Blog page\n\n } elseif ( is_page( 'cart' ) || is_cart()){\n echo \"cart\";\n // Blog page\n\n } elseif (is_single()){\n echo \"is_single\";\n // Blog page\n\n } elseif (is_product_category()){\n echo \"is_product_category\";\n } \n else {\n echo \"Everything else\";\n // Everything else\n }\n ?&gt;\n</code></pre>\n" }, { "answer_id": 368748, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 2, "selected": false, "text": "<p>It returns account page itself without endpoints:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>echo wc_get_account_endpoint_url('dashboard');\n</code></pre>\n" } ]
2016/01/04
[ "https://wordpress.stackexchange.com/questions/213612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86097/" ]
I am trying to send an email to customer after purchased products and when customer click on the the link provided the email for rating the product it should redirect to customer's account/My account page. I put some code in functions.php to get the WooCommerce My Account URL: ``` $myaccount_page = get_option( 'woocommerce_myaccount_page_id' ); if ( $myaccount_page ) { $myaccount_page_url = get_permalink( $myaccount_page ); } ``` I have customized into **customer-completed-order.php** and put this code ``` <h2> Go to your account page for review </h2> <a href="http://animax.cf/product/happy-ninja/#reviews"> <img src="http://animax.cf/wp-content/uploads/2015/12/product-reviews.png" alt="Product Rating"> </a> ``` I want to get woocomerce myaccount url in above code. how should i do this.
You can get the WooCommerce my-account URL as below ``` <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>"><?php _e('My Account',''); ?></a> ``` Now you can insert this in completed order mail template too. ``` <h2> <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>">Go to your account page for review</a> </h2> <a href="http://animax.cf/product/happy-ninja/#reviews"> <img src="http://animax.cf/wp-content/uploads/2015/12/product-reviews.png" alt="Product Rating"> </a> ```
213,621
<p>I need your help, am trying to add class <code>dropdown-submenu</code> to a <code>&lt;li&gt;</code> element which has children. Not sure if I was clear enough, so here is an example:</p> <pre><code> |-Home (Parent Item) |-Services (Parent Item) *class='dropdown'* |-Orthodontics (Child Item) *** class="dropdown-submenu" *** |-Invisalign (Sub Child Item) |-Inman Aligner (Sub Child Item) </code></pre> <p>The HTML format is:</p> <pre><code> &lt;!-- Services --&gt; &lt;li class="dropdown active"&gt; &lt;a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown"&gt; Services &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;!-- Service Orthodontics --&gt; &lt;li class="dropdown-submenu active"&gt; &lt;a href="javascript:void(0);"&gt;Orthodontics&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="invisalign.html"&gt;Invisalign&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="inman_aligner.html"&gt;Inman Aligner&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;!-- End Service Orthodontics --&gt; </code></pre> <p>My walker-class gives all <code>&lt;li&gt;</code> elements which has <code>&lt;ul&gt;</code> class <code>dropdown</code>. It simply look if the element has child and if true it set the class name to <code>dropdown</code>. Here is the code of <code>walker.php</code></p> <pre><code> class Main_Walker_Nav_Menu extends Walker_Nav_Menu { function start_lvl( &amp;$output, $depth ){ //ul $indent = str_repeat("\t",$depth); $submenu = ($depth &gt; 0) ? ' dropdown-menu' : ''; $output .= "\n$indent&lt;ul class=\"dropdown-menu$submenu depth_$depth\"&gt;\n"; } function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ){ //li a span $indent = ( $depth ) ? str_repeat("\t",$depth) : ''; $li_attributes = ''; $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $classes[] = ($args-&gt;walker-&gt;has_children) ? 'dropdown' : ''; $classes[] = ($item-&gt;current || $item-&gt;current_item_anchestor) ? 'active' : ''; $classes[] = 'menu-item-' . $item-&gt;ID; if( $depth &amp;&amp; $args-&gt;walker-&gt;has_children ){ $classes[] = 'dropdown-submenu'; } $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = ' class="' . esc_attr($class_names) . '"'; $id = apply_filters('nav_menu_item_id', 'menu-item-'.$item-&gt;ID, $item, $args); $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '&lt;li' . $id . $value . $class_names . $li_attributes . '&gt;'; $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr($item-&gt;attr_title) . '"' : ''; $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr($item-&gt;target) . '"' : ''; $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr($item-&gt;xfn) . '"' : ''; $attributes .= ! empty( $item-&gt;url ) ? ' href="' . esc_attr($item-&gt;url) . '"' : ''; $attributes .= ( $args-&gt;walker-&gt;has_children ) ? ' class="dropdown-toggle" data-toggle="dropdown"' : ''; $item_output = $args-&gt;before; $item_output .= '&lt;a' . $attributes . '&gt;'; $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after; $item_output .= ( $depth == 0 &amp;&amp; $args-&gt;walker-&gt;has_children ) ? '&lt;/a&gt;' : '&lt;/a&gt;'; $item_output .= $args-&gt;after; $output .= apply_filters ( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 213614, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 6, "selected": true, "text": "<p>You can get the WooCommerce my-account URL as below</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?&gt;\" title=\"&lt;?php _e('My Account',''); ?&gt;\"&gt;&lt;?php _e('My Account',''); ?&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Now you can insert this in completed order mail template too.</p>\n\n<pre><code>&lt;h2&gt; &lt;a href=\"&lt;?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?&gt;\" title=\"&lt;?php _e('My Account',''); ?&gt;\"&gt;Go to your account page for review&lt;/a&gt; &lt;/h2&gt;\n&lt;a href=\"http://animax.cf/product/happy-ninja/#reviews\"&gt;\n &lt;img src=\"http://animax.cf/wp-content/uploads/2015/12/product-reviews.png\" alt=\"Product Rating\"&gt;\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 302926, "author": "user143165", "author_id": 143165, "author_profile": "https://wordpress.stackexchange.com/users/143165", "pm_score": 4, "selected": false, "text": "<p>woocommerce wc_get_page_id function will help you to create WooCommerce pages URLs </p>\n\n<p>Examples of usage:</p>\n\n<p>My Account</p>\n\n<pre><code>&lt;?php echo get_permalink( wc_get_page_id( 'myaccount' ) ); ?&gt;\n</code></pre>\n\n<p>Shop</p>\n\n<pre><code>&lt;?php echo get_permalink( wc_get_page_id( 'shop' ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 327595, "author": "Iulia Cazan", "author_id": 160480, "author_profile": "https://wordpress.stackexchange.com/users/160480", "pm_score": 3, "selected": false, "text": "<p>There is another way to do this using the WooCommerce native endpoints (you can use any of the registered endpoints with WC or third-party plugins that hook into WC):\n<code>&lt;?php echo esc_url( wc_get_account_endpoint_url( 'edit-account' ) ); ?&gt;</code></p>\n\n<p>For dashboard you could use something like this\n<code>&lt;?php echo esc_url( trailingslashit( wc_get_account_endpoint_url( '' ) ) ); ?&gt;</code></p>\n" }, { "answer_id": 342864, "author": "Naved Khan", "author_id": 171847, "author_profile": "https://wordpress.stackexchange.com/users/171847", "pm_score": -1, "selected": false, "text": "<pre><code> &lt;?php \n if ( is_front_page() &amp;&amp; is_home() ) {\n // Default homepage\n echo \"Default homepage\";\n\n } elseif ( is_front_page()){\n\n echo \"Static homepage\";\n // Static homepage\n\n } elseif ( is_home()){\n echo \"Blog page\";\n // Blog page\n\n } elseif ( is_page( 'cart' ) || is_cart()){\n echo \"cart\";\n // Blog page\n\n } elseif (is_single()){\n echo \"is_single\";\n // Blog page\n\n } elseif (is_product_category()){\n echo \"is_product_category\";\n } \n else {\n echo \"Everything else\";\n // Everything else\n }\n ?&gt;\n</code></pre>\n" }, { "answer_id": 368748, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 2, "selected": false, "text": "<p>It returns account page itself without endpoints:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>echo wc_get_account_endpoint_url('dashboard');\n</code></pre>\n" } ]
2016/01/04
[ "https://wordpress.stackexchange.com/questions/213621", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86230/" ]
I need your help, am trying to add class `dropdown-submenu` to a `<li>` element which has children. Not sure if I was clear enough, so here is an example: ``` |-Home (Parent Item) |-Services (Parent Item) *class='dropdown'* |-Orthodontics (Child Item) *** class="dropdown-submenu" *** |-Invisalign (Sub Child Item) |-Inman Aligner (Sub Child Item) ``` The HTML format is: ``` <!-- Services --> <li class="dropdown active"> <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown"> Services </a> <ul class="dropdown-menu"> <!-- Service Orthodontics --> <li class="dropdown-submenu active"> <a href="javascript:void(0);">Orthodontics</a> <ul class="dropdown-menu"> <li><a href="invisalign.html">Invisalign</a></li> <li><a href="inman_aligner.html">Inman Aligner</a></li> </ul> </li> <!-- End Service Orthodontics --> ``` My walker-class gives all `<li>` elements which has `<ul>` class `dropdown`. It simply look if the element has child and if true it set the class name to `dropdown`. Here is the code of `walker.php` ``` class Main_Walker_Nav_Menu extends Walker_Nav_Menu { function start_lvl( &$output, $depth ){ //ul $indent = str_repeat("\t",$depth); $submenu = ($depth > 0) ? ' dropdown-menu' : ''; $output .= "\n$indent<ul class=\"dropdown-menu$submenu depth_$depth\">\n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ){ //li a span $indent = ( $depth ) ? str_repeat("\t",$depth) : ''; $li_attributes = ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = ($args->walker->has_children) ? 'dropdown' : ''; $classes[] = ($item->current || $item->current_item_anchestor) ? 'active' : ''; $classes[] = 'menu-item-' . $item->ID; if( $depth && $args->walker->has_children ){ $classes[] = 'dropdown-submenu'; } $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = ' class="' . esc_attr($class_names) . '"'; $id = apply_filters('nav_menu_item_id', 'menu-item-'.$item->ID, $item, $args); $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names . $li_attributes . '>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr($item->attr_title) . '"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr($item->target) . '"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr($item->xfn) . '"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr($item->url) . '"' : ''; $attributes .= ( $args->walker->has_children ) ? ' class="dropdown-toggle" data-toggle="dropdown"' : ''; $item_output = $args->before; $item_output .= '<a' . $attributes . '>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ( $depth == 0 && $args->walker->has_children ) ? '</a>' : '</a>'; $item_output .= $args->after; $output .= apply_filters ( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } ``` Thanks in advance.
You can get the WooCommerce my-account URL as below ``` <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>"><?php _e('My Account',''); ?></a> ``` Now you can insert this in completed order mail template too. ``` <h2> <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>">Go to your account page for review</a> </h2> <a href="http://animax.cf/product/happy-ninja/#reviews"> <img src="http://animax.cf/wp-content/uploads/2015/12/product-reviews.png" alt="Product Rating"> </a> ```
213,677
<p>Running my own designed custom theme "mdbootstrap" designed by myself. Integrating WooCommerce 2.4.12. and upon testing there is an issue adding variable products to the cart. Basically the add to cart button is hidden and doesn't appear once a variant is selected .</p> <p>If I switch to the TwentyEleven theme, the issue resolves itself.</p> <p>I can force button to show by adding to css</p> <pre><code>.single_variation_wrap{display:block !important;} </code></pre> <p>but even then when I submit "Add to card" page is reloading and when I move to cart page I am getting error: Please choose product options… </p> <p>Variable product: <a href="http://mdb.nomadflow.com/product/ecommerce-homepage-template/" rel="nofollow">http://mdb.nomadflow.com/product/ecommerce-homepage-template/</a></p> <p>Normal products works like a charm: <a href="http://mdb.nomadflow.com/product/blog-homepage-template/" rel="nofollow">http://mdb.nomadflow.com/product/blog-homepage-template/</a></p> <p>You have to be logged in: username: test password: test</p>
[ { "answer_id": 213696, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": 2, "selected": true, "text": "<p>I'm not sure why but you have form tag inside a form tag.. and chrome is making it as one... view source and look for <code>&lt;form class=\"cart\" method=\"post\" enctype='multipart/form-data'&gt;</code> and <code>&lt;form class=\"variations_form cart\" method=\"post\"</code></p>\n\n<p><code>&lt;form class=\"variations_form cart\" method=\"post\"</code> was removed by the browser which is the one needed by woocommerce. </p>\n" }, { "answer_id": 217187, "author": "metatron", "author_id": 88371, "author_profile": "https://wordpress.stackexchange.com/users/88371", "pm_score": 0, "selected": false, "text": "<p>Btw, as for all custom themes designed from scratch: do not forget to include <code>wp_head()</code> and <code>wp_footer()</code> functions as they are needed to let WooCommerce automatically link the necessary JS files. Those JS files are needed to make the WooCommerce do it's thing.</p>\n\n<p>I just ran into this issue coding a theme from scratch and accidently deleting <code>wp_footer()</code>.</p>\n" }, { "answer_id": 227844, "author": "Jason", "author_id": 73096, "author_profile": "https://wordpress.stackexchange.com/users/73096", "pm_score": 1, "selected": false, "text": "<p>I know this thread is older, but I had the same issue and I contacted WooThemes support and they said that…\"We limit the amount of variations we show on the front end for speed. But sometimes you need more than 36 variations, so we offer that filter to override that limitation.\"</p>\n\n<p>So you need to add this code below to your functions.php file and you're good to go. Worked for me. Hope that helps others that have this same issue:</p>\n\n<pre><code>function custom_wc_ajax_variation_threshold( $qty, $product ) {\n return 100;\n}\nadd_filter( 'woocommerce_ajax_variation_threshold', 'custom_wc_ajax_variation_threshold', 100, 2 );\n</code></pre>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77480/" ]
Running my own designed custom theme "mdbootstrap" designed by myself. Integrating WooCommerce 2.4.12. and upon testing there is an issue adding variable products to the cart. Basically the add to cart button is hidden and doesn't appear once a variant is selected . If I switch to the TwentyEleven theme, the issue resolves itself. I can force button to show by adding to css ``` .single_variation_wrap{display:block !important;} ``` but even then when I submit "Add to card" page is reloading and when I move to cart page I am getting error: Please choose product options… Variable product: <http://mdb.nomadflow.com/product/ecommerce-homepage-template/> Normal products works like a charm: <http://mdb.nomadflow.com/product/blog-homepage-template/> You have to be logged in: username: test password: test
I'm not sure why but you have form tag inside a form tag.. and chrome is making it as one... view source and look for `<form class="cart" method="post" enctype='multipart/form-data'>` and `<form class="variations_form cart" method="post"` `<form class="variations_form cart" method="post"` was removed by the browser which is the one needed by woocommerce.
213,701
<p>I read on the WP docs, <a href="https://gist.github.com/wpscholar/4947518" rel="nofollow">which pointed to this gist</a> that the correct way to enqueue styles for IE is by using the <code>$wp_styles</code>. I'm guessing that this would be true then for scripts as well.</p> <h2>Take these examples for instance...</h2> <p><strong>Option One</strong> - Using <code>wp_scripts</code> </p> <pre><code>add_action('wp_print_scripts', function() { global $wp_scripts; wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); $wp_scripts-&gt;add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } ); </code></pre> <p><strong>Option Two</strong> - Use <code>wp_scripts</code> along with <code>is_IE</code> </p> <pre><code>add_action('wp_print_scripts', function() { global $wp_scripts, $is_IE; if($is_IE) { wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); $wp_scripts-&gt;add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } } ); </code></pre> <p><strong>Option Three</strong> - Just echo it in the head :</p> <pre><code>add_action('wp_head', function(){ echo '&lt;!--[if lt IE 9]&gt;&lt;script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"&gt;&lt;/script&gt;&lt;![endif]--&gt;' . "\n"; }); </code></pre> <p><strong>Option Four</strong> - Enqueue it to the head :</p> <pre><code>add_action('wp_print_scripts', function(){ wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); }); </code></pre> <p>The second option. seems cool because it looks a little cleaner on non-IE browsers. But I'm not sure if it actually has any speed advantage or if the check alone slows it down more. Other than that I can't seem to figure out any reason why option one is better than option 3 or 4.</p> <hr> <h2>The reason for this question</h2> <p>I'm using the Genesis framework and <a href="https://gist.github.com/bryanwillis/0892fcec0b32c3ca64f2" rel="nofollow">they include HTML5shiv</a> like the example below which just didn't seem right to me:</p> <pre><code>add_action( 'wp_head', 'genesis_html5_ie_fix' ); /** * Load the html5 shiv for IE8 and below. Can't enqueue with IE conditionals. */ function genesis_html5_ie_fix() { if ( ! genesis_html5() ) return; echo '&lt;!--[if lt IE 9]&gt;&lt;script src="//html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;&lt;![endif]--&gt;' . "\n"; } </code></pre>
[ { "answer_id": 213703, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>And option 5 is to detect on client side what browser it is, and create a script element for your script directly into the dom, like google analytics an FB SDK do.</p>\n\n<p>This has the advantage of doing browser detection in the only place it should be done, the browser, and loading the IE specific scripts only when needed.</p>\n\n<p>In spirit it is very similar to your third option, just more generic.</p>\n\n<p>Sidenote: <code>is_IE</code> like all the other server side browser detection should be avoided as they will break caching.</p>\n" }, { "answer_id": 213748, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<p>Generally speaking, scripts and styles should never be directly printed to page.</p>\n\n<p>Reason is that another plugin or theme might add the same script again, and you get the same script added 2 or more times.</p>\n\n<p>If you enqueue asset the proper way, if other code enqueue the same asset again, it will be added once.</p>\n\n<p>For this reason you should skip options 3 and 4.</p>\n\n<p>Regarding option 2, as <strong>Mark Kaplun</strong> <a href=\"https://wordpress.stackexchange.com/a/213703/35541\">pointed out</a>, it makes use of server-side browser detection, that is never very affordable, and even if it would, don't let you select the version of the browser and in your case it will include the script even in modern IE versions, that don't need it.</p>\n\n<p>So, actually, the option 1 is the best among the ones you proposed.</p>\n\n<p>The only changes I would do:</p>\n\n<ul>\n<li>use <code>'wp_enqueue_scripts'</code> action, instead of <code>'wp_print_scripts'</code></li>\n<li>use <a href=\"https://developer.wordpress.org/reference/functions/wp_scripts/\" rel=\"nofollow noreferrer\"><code>wp_scripts()</code></a> function istead of accessing global</li>\n</ul>\n\n<p>Something like:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', function() {\n wp_enqueue_script(\n 'html5shiv',\n 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js',\n array( 'bootstrap' ),\n '3.7.2',\n false\n );\n wp_scripts()-&gt;add_data( 'html5shiv', 'conditional', 'lt IE 9' );\n} );\n</code></pre>\n\n<p>Doing like that if another plugin enqueue <code>'html5shiv'</code> script again, it will be added just once.</p>\n\n<p>Note that using snippet above, what is print on page is:</p>\n\n<pre><code>&lt;!--[if lt IE 9]&gt;\n&lt;script type='text/javascript' src='https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js'&gt;&lt;/script&gt;\n&lt;![endif]--&gt;\n</code></pre>\n\n<p>This conditional is parsed by the browser (client side), and not server side, so it is affordable and let you add the script only for the IE version you want to target.</p>\n\n<p>If you need to know more about the client platform (OS, screen type and resolution, specific detailed version of browser...) then the only way is to use some javascript to sniff this details and dynamically add the script to DOM (as per <strong>Mark Kaplun</strong> solution), but if knowing the \"browser family\" and major version is enough for you, my suggestion is to use this solution.</p>\n" }, { "answer_id": 214460, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 4, "selected": true, "text": "<p>To extend on <strong>@gmazzap</strong> suggestion on not using globals when you can use <code>wp_scripts()</code>, there is a shortcut for <code>wp_scripts()</code> for adding conditional comments called <code>wp_script_add_data</code> and likewise <code>wp_style_add_data</code> for conditional styles. </p>\n\n<h2>So the correct way to use conditionals as of Wordpress 4.2 is like this:</h2>\n\n<pre><code>/**\n * IE enqueue HTML5shiv with conditionals\n * @link http://tiny.cc/html5shiv\n */\nfunction wpse_213701_enqueue_html5shiv() {\n wp_enqueue_script( 'html5shiv',\n 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js',\n array(),\n false,\n false\n );\n wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );\n}\nadd_action('wp_enqueue_scripts', 'wpse_213701_enqueue_html5shiv');\n</code></pre>\n\n<p>However, the example above is using <em>HTML5shiv</em> which is a unique situation. Since it <strong>has to</strong> be loaded in the head you could do something like this next example if you're worried about a plugin like <a href=\"https://github.com/roots/soil\" rel=\"nofollow noreferrer\">Roots Soil</a> removing all the scripts from the head.</p>\n\n<hr>\n\n<p>Most likely you won't run into a situation like this though. It's a very unstable thing to do since a lot of scripts are required to load in the head. Putting scripts in the footer should be done by setting <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\"><code>$in_footer</code></a> variable to true when enqueuing scripts. So if you do use roots or any cache plugin for that matter don't plan on everything working exactly how you want right out of the box. </p>\n\n<p><em>Here's an ugly example of what you can do:</em></p>\n\n<pre><code>add_action( 'wp_head', 'wpse_213701_check_html5shiv', 1 );\nfunction wpse_213701_check_html5shiv() {\n remove_action( 'wp_head', 'genesis_html5_ie_fix' );\n if ( !has_filter( 'wp_head', 'wp_enqueue_scripts' ) &amp;&amp; !wp_script_is( 'html5shiv', 'done' ) ) {\n add_action('wp_head', 'wpse_213701_echo_html5shiv');\n wp_dequeue_script('html5shiv');\n }\n}\nfunction wpse_213701_echo_html5shiv() {\n echo '&lt;!--[if lt IE 9]&gt;&lt;script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"&gt;&lt;/script&gt;&lt;![endif]--&gt;' . \"\\n\";\n}\n</code></pre>\n\n<hr>\n\n<p>This is overkill though and it still isn't a guarantee that it will work. Over the past 4 years <em>html5shiv</em> has taken on many names which has caused it to be registered / enqueued with several different handles (html5, html5shiv, html5shim, themename-html5shiv, html5-ie-fix, and html5-polyfill just to name a few). Additionally, it's often <a href=\"https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills\" rel=\"nofollow noreferrer\">bundled with modernizr</a>. With that in mind, if you think the above example is ridiculous, you're just as well off adding the script to <code>wp_head</code> in your child theme since a plugins <em>html5shiv</em> handle will most likely named something else.</p>\n\n<h2>Update (Moving scripts to footer with this approach) :</h2>\n\n<p>This sparked some action on <a href=\"https://github.com/roots/soil/issues/33\" rel=\"nofollow noreferrer\">Roots/Soil</a> Github page. Here's probably the best way to do this ( as suggested by <a href=\"https://wordpress.stackexchange.com/users/17937/grappler\">@grappler</a> ) and still move scripts to the footer. A similar approach was posted on <a href=\"https://wordpress.stackexchange.com/users/385/kaiser\"><strong>@kaiser's</strong></a> <a href=\"http://unserkaiser.com/blog/2013/10/08/how-to-move-wordpress-core-javascript-to-the-footer/\" rel=\"nofollow noreferrer\">blog</a> a few years back.</p>\n\n<pre><code>function grappler_move_js_to_footer() \n $scripts = wp_scripts();\n foreach( $scripts-&gt;registered as $script ) {\n if ( 'html5' == $script-&gt;handle ) {\n wp_script_add_data( $script-&gt;handle, 'group', 0 );\n } else {\n wp_script_add_data( $script-&gt;handle, 'group', 1 );\n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'grappler_move_js_to_footer', 99 );\n</code></pre>\n\n<hr>\n\n<p>As for what Mark Kaplan suggested and what <strong><a href=\"https://wordpress.stackexchange.com/a/213822/43806\">toscho mentioned here</a></strong> , <strong>you shouldn't be using option 2's $is_IE method</strong>. Apparently, if the HTTP header Vary: User-Agent doesn't get sent, you will send the wrong output to users behind a cache causing it to break for those users. In regards to browser side detection <a href=\"https://gist.github.com/padolsey/527683\" rel=\"nofollow noreferrer\">here is a long thread of examples</a> on how that might be done. Even client-side detection has it's pitfalls.</p>\n\n<hr>\n\n<p>At the end of the day, maybe the best answer is don't use any of these methods and forget about legacy browsers since <a href=\"https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support\" rel=\"nofollow noreferrer\">Microsoft has dropped support for them as of January 12</a>.</p>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38123/" ]
I read on the WP docs, [which pointed to this gist](https://gist.github.com/wpscholar/4947518) that the correct way to enqueue styles for IE is by using the `$wp_styles`. I'm guessing that this would be true then for scripts as well. Take these examples for instance... ----------------------------------- **Option One** - Using `wp_scripts` ``` add_action('wp_print_scripts', function() { global $wp_scripts; wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); $wp_scripts->add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } ); ``` **Option Two** - Use `wp_scripts` along with `is_IE` ``` add_action('wp_print_scripts', function() { global $wp_scripts, $is_IE; if($is_IE) { wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); $wp_scripts->add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } } ); ``` **Option Three** - Just echo it in the head : ``` add_action('wp_head', function(){ echo '<!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script><![endif]-->' . "\n"; }); ``` **Option Four** - Enqueue it to the head : ``` add_action('wp_print_scripts', function(){ wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array( 'bootstrap' ) ); }); ``` The second option. seems cool because it looks a little cleaner on non-IE browsers. But I'm not sure if it actually has any speed advantage or if the check alone slows it down more. Other than that I can't seem to figure out any reason why option one is better than option 3 or 4. --- The reason for this question ---------------------------- I'm using the Genesis framework and [they include HTML5shiv](https://gist.github.com/bryanwillis/0892fcec0b32c3ca64f2) like the example below which just didn't seem right to me: ``` add_action( 'wp_head', 'genesis_html5_ie_fix' ); /** * Load the html5 shiv for IE8 and below. Can't enqueue with IE conditionals. */ function genesis_html5_ie_fix() { if ( ! genesis_html5() ) return; echo '<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->' . "\n"; } ```
To extend on **@gmazzap** suggestion on not using globals when you can use `wp_scripts()`, there is a shortcut for `wp_scripts()` for adding conditional comments called `wp_script_add_data` and likewise `wp_style_add_data` for conditional styles. So the correct way to use conditionals as of Wordpress 4.2 is like this: ------------------------------------------------------------------------ ``` /** * IE enqueue HTML5shiv with conditionals * @link http://tiny.cc/html5shiv */ function wpse_213701_enqueue_html5shiv() { wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array(), false, false ); wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } add_action('wp_enqueue_scripts', 'wpse_213701_enqueue_html5shiv'); ``` However, the example above is using *HTML5shiv* which is a unique situation. Since it **has to** be loaded in the head you could do something like this next example if you're worried about a plugin like [Roots Soil](https://github.com/roots/soil) removing all the scripts from the head. --- Most likely you won't run into a situation like this though. It's a very unstable thing to do since a lot of scripts are required to load in the head. Putting scripts in the footer should be done by setting [`$in_footer`](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) variable to true when enqueuing scripts. So if you do use roots or any cache plugin for that matter don't plan on everything working exactly how you want right out of the box. *Here's an ugly example of what you can do:* ``` add_action( 'wp_head', 'wpse_213701_check_html5shiv', 1 ); function wpse_213701_check_html5shiv() { remove_action( 'wp_head', 'genesis_html5_ie_fix' ); if ( !has_filter( 'wp_head', 'wp_enqueue_scripts' ) && !wp_script_is( 'html5shiv', 'done' ) ) { add_action('wp_head', 'wpse_213701_echo_html5shiv'); wp_dequeue_script('html5shiv'); } } function wpse_213701_echo_html5shiv() { echo '<!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script><![endif]-->' . "\n"; } ``` --- This is overkill though and it still isn't a guarantee that it will work. Over the past 4 years *html5shiv* has taken on many names which has caused it to be registered / enqueued with several different handles (html5, html5shiv, html5shim, themename-html5shiv, html5-ie-fix, and html5-polyfill just to name a few). Additionally, it's often [bundled with modernizr](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills). With that in mind, if you think the above example is ridiculous, you're just as well off adding the script to `wp_head` in your child theme since a plugins *html5shiv* handle will most likely named something else. Update (Moving scripts to footer with this approach) : ------------------------------------------------------ This sparked some action on [Roots/Soil](https://github.com/roots/soil/issues/33) Github page. Here's probably the best way to do this ( as suggested by [@grappler](https://wordpress.stackexchange.com/users/17937/grappler) ) and still move scripts to the footer. A similar approach was posted on [**@kaiser's**](https://wordpress.stackexchange.com/users/385/kaiser) [blog](http://unserkaiser.com/blog/2013/10/08/how-to-move-wordpress-core-javascript-to-the-footer/) a few years back. ``` function grappler_move_js_to_footer() $scripts = wp_scripts(); foreach( $scripts->registered as $script ) { if ( 'html5' == $script->handle ) { wp_script_add_data( $script->handle, 'group', 0 ); } else { wp_script_add_data( $script->handle, 'group', 1 ); } } } add_action( 'wp_enqueue_scripts', 'grappler_move_js_to_footer', 99 ); ``` --- As for what Mark Kaplan suggested and what **[toscho mentioned here](https://wordpress.stackexchange.com/a/213822/43806)** , **you shouldn't be using option 2's $is\_IE method**. Apparently, if the HTTP header Vary: User-Agent doesn't get sent, you will send the wrong output to users behind a cache causing it to break for those users. In regards to browser side detection [here is a long thread of examples](https://gist.github.com/padolsey/527683) on how that might be done. Even client-side detection has it's pitfalls. --- At the end of the day, maybe the best answer is don't use any of these methods and forget about legacy browsers since [Microsoft has dropped support for them as of January 12](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support).
213,717
<p>On the checkout page, on the Billing Details section, I added two custom fields: Alpha and Beta. During checkout these fields are edited by the user and then saved together with the rest of his address info.</p> <p>On the dashboard, on the "Edit User" page I also added these two custom fields: Alpha and Beta.</p> <p>On the dashboard when I create an order (Woocommerce > Orders > Add Order) I select a customer. His Billing Details are automatically loaded into the "Billing Details" area.</p> <p>Now I have to load also the values of the Alpha and Beta custom fields for that specific customer, into the "Custom Fields" area of the "Add New Order" page.</p> <p>1 - How can I get the ID of that selected customer?</p> <p>2 - Then, having the user ID how can I get the values of his Alpha and Beta fields and display them into the "Custom Fields" area of the "Add New Order" page?</p> <p>The Order is not saved yet!</p> <p>Thank you</p>
[ { "answer_id": 213703, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>And option 5 is to detect on client side what browser it is, and create a script element for your script directly into the dom, like google analytics an FB SDK do.</p>\n\n<p>This has the advantage of doing browser detection in the only place it should be done, the browser, and loading the IE specific scripts only when needed.</p>\n\n<p>In spirit it is very similar to your third option, just more generic.</p>\n\n<p>Sidenote: <code>is_IE</code> like all the other server side browser detection should be avoided as they will break caching.</p>\n" }, { "answer_id": 213748, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": false, "text": "<p>Generally speaking, scripts and styles should never be directly printed to page.</p>\n\n<p>Reason is that another plugin or theme might add the same script again, and you get the same script added 2 or more times.</p>\n\n<p>If you enqueue asset the proper way, if other code enqueue the same asset again, it will be added once.</p>\n\n<p>For this reason you should skip options 3 and 4.</p>\n\n<p>Regarding option 2, as <strong>Mark Kaplun</strong> <a href=\"https://wordpress.stackexchange.com/a/213703/35541\">pointed out</a>, it makes use of server-side browser detection, that is never very affordable, and even if it would, don't let you select the version of the browser and in your case it will include the script even in modern IE versions, that don't need it.</p>\n\n<p>So, actually, the option 1 is the best among the ones you proposed.</p>\n\n<p>The only changes I would do:</p>\n\n<ul>\n<li>use <code>'wp_enqueue_scripts'</code> action, instead of <code>'wp_print_scripts'</code></li>\n<li>use <a href=\"https://developer.wordpress.org/reference/functions/wp_scripts/\" rel=\"nofollow noreferrer\"><code>wp_scripts()</code></a> function istead of accessing global</li>\n</ul>\n\n<p>Something like:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', function() {\n wp_enqueue_script(\n 'html5shiv',\n 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js',\n array( 'bootstrap' ),\n '3.7.2',\n false\n );\n wp_scripts()-&gt;add_data( 'html5shiv', 'conditional', 'lt IE 9' );\n} );\n</code></pre>\n\n<p>Doing like that if another plugin enqueue <code>'html5shiv'</code> script again, it will be added just once.</p>\n\n<p>Note that using snippet above, what is print on page is:</p>\n\n<pre><code>&lt;!--[if lt IE 9]&gt;\n&lt;script type='text/javascript' src='https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js'&gt;&lt;/script&gt;\n&lt;![endif]--&gt;\n</code></pre>\n\n<p>This conditional is parsed by the browser (client side), and not server side, so it is affordable and let you add the script only for the IE version you want to target.</p>\n\n<p>If you need to know more about the client platform (OS, screen type and resolution, specific detailed version of browser...) then the only way is to use some javascript to sniff this details and dynamically add the script to DOM (as per <strong>Mark Kaplun</strong> solution), but if knowing the \"browser family\" and major version is enough for you, my suggestion is to use this solution.</p>\n" }, { "answer_id": 214460, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 4, "selected": true, "text": "<p>To extend on <strong>@gmazzap</strong> suggestion on not using globals when you can use <code>wp_scripts()</code>, there is a shortcut for <code>wp_scripts()</code> for adding conditional comments called <code>wp_script_add_data</code> and likewise <code>wp_style_add_data</code> for conditional styles. </p>\n\n<h2>So the correct way to use conditionals as of Wordpress 4.2 is like this:</h2>\n\n<pre><code>/**\n * IE enqueue HTML5shiv with conditionals\n * @link http://tiny.cc/html5shiv\n */\nfunction wpse_213701_enqueue_html5shiv() {\n wp_enqueue_script( 'html5shiv',\n 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js',\n array(),\n false,\n false\n );\n wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );\n}\nadd_action('wp_enqueue_scripts', 'wpse_213701_enqueue_html5shiv');\n</code></pre>\n\n<p>However, the example above is using <em>HTML5shiv</em> which is a unique situation. Since it <strong>has to</strong> be loaded in the head you could do something like this next example if you're worried about a plugin like <a href=\"https://github.com/roots/soil\" rel=\"nofollow noreferrer\">Roots Soil</a> removing all the scripts from the head.</p>\n\n<hr>\n\n<p>Most likely you won't run into a situation like this though. It's a very unstable thing to do since a lot of scripts are required to load in the head. Putting scripts in the footer should be done by setting <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\"><code>$in_footer</code></a> variable to true when enqueuing scripts. So if you do use roots or any cache plugin for that matter don't plan on everything working exactly how you want right out of the box. </p>\n\n<p><em>Here's an ugly example of what you can do:</em></p>\n\n<pre><code>add_action( 'wp_head', 'wpse_213701_check_html5shiv', 1 );\nfunction wpse_213701_check_html5shiv() {\n remove_action( 'wp_head', 'genesis_html5_ie_fix' );\n if ( !has_filter( 'wp_head', 'wp_enqueue_scripts' ) &amp;&amp; !wp_script_is( 'html5shiv', 'done' ) ) {\n add_action('wp_head', 'wpse_213701_echo_html5shiv');\n wp_dequeue_script('html5shiv');\n }\n}\nfunction wpse_213701_echo_html5shiv() {\n echo '&lt;!--[if lt IE 9]&gt;&lt;script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"&gt;&lt;/script&gt;&lt;![endif]--&gt;' . \"\\n\";\n}\n</code></pre>\n\n<hr>\n\n<p>This is overkill though and it still isn't a guarantee that it will work. Over the past 4 years <em>html5shiv</em> has taken on many names which has caused it to be registered / enqueued with several different handles (html5, html5shiv, html5shim, themename-html5shiv, html5-ie-fix, and html5-polyfill just to name a few). Additionally, it's often <a href=\"https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills\" rel=\"nofollow noreferrer\">bundled with modernizr</a>. With that in mind, if you think the above example is ridiculous, you're just as well off adding the script to <code>wp_head</code> in your child theme since a plugins <em>html5shiv</em> handle will most likely named something else.</p>\n\n<h2>Update (Moving scripts to footer with this approach) :</h2>\n\n<p>This sparked some action on <a href=\"https://github.com/roots/soil/issues/33\" rel=\"nofollow noreferrer\">Roots/Soil</a> Github page. Here's probably the best way to do this ( as suggested by <a href=\"https://wordpress.stackexchange.com/users/17937/grappler\">@grappler</a> ) and still move scripts to the footer. A similar approach was posted on <a href=\"https://wordpress.stackexchange.com/users/385/kaiser\"><strong>@kaiser's</strong></a> <a href=\"http://unserkaiser.com/blog/2013/10/08/how-to-move-wordpress-core-javascript-to-the-footer/\" rel=\"nofollow noreferrer\">blog</a> a few years back.</p>\n\n<pre><code>function grappler_move_js_to_footer() \n $scripts = wp_scripts();\n foreach( $scripts-&gt;registered as $script ) {\n if ( 'html5' == $script-&gt;handle ) {\n wp_script_add_data( $script-&gt;handle, 'group', 0 );\n } else {\n wp_script_add_data( $script-&gt;handle, 'group', 1 );\n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'grappler_move_js_to_footer', 99 );\n</code></pre>\n\n<hr>\n\n<p>As for what Mark Kaplan suggested and what <strong><a href=\"https://wordpress.stackexchange.com/a/213822/43806\">toscho mentioned here</a></strong> , <strong>you shouldn't be using option 2's $is_IE method</strong>. Apparently, if the HTTP header Vary: User-Agent doesn't get sent, you will send the wrong output to users behind a cache causing it to break for those users. In regards to browser side detection <a href=\"https://gist.github.com/padolsey/527683\" rel=\"nofollow noreferrer\">here is a long thread of examples</a> on how that might be done. Even client-side detection has it's pitfalls.</p>\n\n<hr>\n\n<p>At the end of the day, maybe the best answer is don't use any of these methods and forget about legacy browsers since <a href=\"https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support\" rel=\"nofollow noreferrer\">Microsoft has dropped support for them as of January 12</a>.</p>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86283/" ]
On the checkout page, on the Billing Details section, I added two custom fields: Alpha and Beta. During checkout these fields are edited by the user and then saved together with the rest of his address info. On the dashboard, on the "Edit User" page I also added these two custom fields: Alpha and Beta. On the dashboard when I create an order (Woocommerce > Orders > Add Order) I select a customer. His Billing Details are automatically loaded into the "Billing Details" area. Now I have to load also the values of the Alpha and Beta custom fields for that specific customer, into the "Custom Fields" area of the "Add New Order" page. 1 - How can I get the ID of that selected customer? 2 - Then, having the user ID how can I get the values of his Alpha and Beta fields and display them into the "Custom Fields" area of the "Add New Order" page? The Order is not saved yet! Thank you
To extend on **@gmazzap** suggestion on not using globals when you can use `wp_scripts()`, there is a shortcut for `wp_scripts()` for adding conditional comments called `wp_script_add_data` and likewise `wp_style_add_data` for conditional styles. So the correct way to use conditionals as of Wordpress 4.2 is like this: ------------------------------------------------------------------------ ``` /** * IE enqueue HTML5shiv with conditionals * @link http://tiny.cc/html5shiv */ function wpse_213701_enqueue_html5shiv() { wp_enqueue_script( 'html5shiv', 'https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js', array(), false, false ); wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' ); } add_action('wp_enqueue_scripts', 'wpse_213701_enqueue_html5shiv'); ``` However, the example above is using *HTML5shiv* which is a unique situation. Since it **has to** be loaded in the head you could do something like this next example if you're worried about a plugin like [Roots Soil](https://github.com/roots/soil) removing all the scripts from the head. --- Most likely you won't run into a situation like this though. It's a very unstable thing to do since a lot of scripts are required to load in the head. Putting scripts in the footer should be done by setting [`$in_footer`](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) variable to true when enqueuing scripts. So if you do use roots or any cache plugin for that matter don't plan on everything working exactly how you want right out of the box. *Here's an ugly example of what you can do:* ``` add_action( 'wp_head', 'wpse_213701_check_html5shiv', 1 ); function wpse_213701_check_html5shiv() { remove_action( 'wp_head', 'genesis_html5_ie_fix' ); if ( !has_filter( 'wp_head', 'wp_enqueue_scripts' ) && !wp_script_is( 'html5shiv', 'done' ) ) { add_action('wp_head', 'wpse_213701_echo_html5shiv'); wp_dequeue_script('html5shiv'); } } function wpse_213701_echo_html5shiv() { echo '<!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script><![endif]-->' . "\n"; } ``` --- This is overkill though and it still isn't a guarantee that it will work. Over the past 4 years *html5shiv* has taken on many names which has caused it to be registered / enqueued with several different handles (html5, html5shiv, html5shim, themename-html5shiv, html5-ie-fix, and html5-polyfill just to name a few). Additionally, it's often [bundled with modernizr](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills). With that in mind, if you think the above example is ridiculous, you're just as well off adding the script to `wp_head` in your child theme since a plugins *html5shiv* handle will most likely named something else. Update (Moving scripts to footer with this approach) : ------------------------------------------------------ This sparked some action on [Roots/Soil](https://github.com/roots/soil/issues/33) Github page. Here's probably the best way to do this ( as suggested by [@grappler](https://wordpress.stackexchange.com/users/17937/grappler) ) and still move scripts to the footer. A similar approach was posted on [**@kaiser's**](https://wordpress.stackexchange.com/users/385/kaiser) [blog](http://unserkaiser.com/blog/2013/10/08/how-to-move-wordpress-core-javascript-to-the-footer/) a few years back. ``` function grappler_move_js_to_footer() $scripts = wp_scripts(); foreach( $scripts->registered as $script ) { if ( 'html5' == $script->handle ) { wp_script_add_data( $script->handle, 'group', 0 ); } else { wp_script_add_data( $script->handle, 'group', 1 ); } } } add_action( 'wp_enqueue_scripts', 'grappler_move_js_to_footer', 99 ); ``` --- As for what Mark Kaplan suggested and what **[toscho mentioned here](https://wordpress.stackexchange.com/a/213822/43806)** , **you shouldn't be using option 2's $is\_IE method**. Apparently, if the HTTP header Vary: User-Agent doesn't get sent, you will send the wrong output to users behind a cache causing it to break for those users. In regards to browser side detection [here is a long thread of examples](https://gist.github.com/padolsey/527683) on how that might be done. Even client-side detection has it's pitfalls. --- At the end of the day, maybe the best answer is don't use any of these methods and forget about legacy browsers since [Microsoft has dropped support for them as of January 12](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support).
213,720
<p>I want to delete all posts of a specific post type (in this case "vfb_entry") that are older than 60 days. The cron job should run once a day.</p> <p>I have the following code but it's not working if I trigger the cron job. However, running only the query in phpMyAdmin returns the correct result. So there must be an issue with the fuction itself.</p> <p>Can anyone please help?</p> <pre><code>// Cron Job to Delete VFB Entries older than 60 days if(!wp_next_scheduled( 'remove_old_vfb_entries')){ wp_schedule_event(time(), 'daily', 'remove_old_vfb_entries'); } add_action('remove_old_vfb_entries', 'myd_remove_old_vfb_entries'); // Build the function function myd_remove_old_vfb_entries(){ global $wpdb; // Set max post date and post_type name $date = date("Y-m-d H:i:s", strtotime('-60 days')); $post_type = 'vfb_entry'; // Build the query // Only select VFB Entries from LFG or LFM Form $query = " SELECT $wpdb-&gt;posts.ID FROM $wpdb-&gt;posts WHERE post_type = '$post_type' AND post_status = 'publish' AND post_date &lt; '$date' AND ($wpdb-&gt;posts.ID IN (SELECT entry_id FROM wp_postmeta_lfg4 WHERE post_id IS NOT NULL) OR $wpdb-&gt;posts.ID IN (SELECT entry_id FROM wp_postmeta_lfm3 WHERE post_id IS NOT NULL)) ORDER BY post_modified DESC "; $results = $wpdb-&gt;get_results($query); foreach($results as $post){ // Let the WordPress API clean up the entire post trails wp_delete_post( $post-&gt;ID, true); } } </code></pre> <p><strong>Edit:</strong> Solution without querying my views, just using wp_posts and wp_postmeta and an INNER JOIN below.</p>
[ { "answer_id": 213886, "author": "jackennils", "author_id": 86289, "author_profile": "https://wordpress.stackexchange.com/users/86289", "pm_score": 1, "selected": false, "text": "<pre><code>// Cron Job to Delete VFB Entries older than 60 days\nif(!wp_next_scheduled( 'remove_old_vfb_entries')){\n wp_schedule_event(time(), 'daily', 'remove_old_vfb_entries');\n}\nadd_action('remove_old_vfb_entries', 'myd_remove_old_vfb_entries');\n\n// Build the function\nfunction myd_remove_old_vfb_entries(){\nglobal $wpdb;\n// Set max post date and post_type name\n$date = date(\"Y-m-d H:i:s\", strtotime('-60 days'));\n$post_type = 'vfb_entry';\n\n// Build the query \n// Only Delete Entries from Form 5 and 8\n$query = \"\n SELECT $wpdb-&gt;posts.ID FROM $wpdb-&gt;posts \n INNER JOIN $wpdb-&gt;postmeta \n ON $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id \n WHERE post_type = '$post_type' \n AND post_status = 'publish' \n AND $wpdb-&gt;postmeta.meta_key = '_vfb_form_id' \n AND ($wpdb-&gt;postmeta.meta_value = 5 OR $wpdb-&gt;postmeta.meta_value = 8) \n AND post_date &lt; '$date' \n\";\n$results = $wpdb-&gt;get_results($query);\n foreach($results as $post){\n // Let the WordPress API clean up the entire post trails\n wp_delete_post( $post-&gt;ID, true);\n }\n}\n</code></pre>\n" }, { "answer_id": 262471, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I want to delete all posts of a specific post type (in this case \"vfb_entry\") that are older than 60 days. The cron job should run once a day.</p>\n</blockquote>\n\n<p>The first step is setting up the cron job. The code in the question is correct for this part, so it's basically copied below.</p>\n\n<p>The second part requires querying the database for a specific post type where the entry is older than 60 days. We can do this with <code>get_posts()</code> and specifying the <code>post_type</code> argument and the <code>date_query</code> argument.</p>\n\n<pre><code>//* If the scheduled event got removed from the cron schedule, re-add it\nif( ! wp_next_scheduled( 'wpse_213720_remove_old_entries' ) ) {\n wp_schedule_event( time(), 'daily', 'wpse_213720_remove_old_entries' );\n}\n\n//* Add action to hook fired by cron event\nadd_action( 'wpse_213720_remove_old_entries', 'wpse_213720_remove_old_entries' );\nfunction wpse_213720_remove_old_entries() {\n //* Get all the custom post type entries older than 60 days...\n $posts = get_posts( [\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'wpse_262471_post_type',\n 'date_query' =&gt; [\n 'before' =&gt; date( \"Y-m-d H:i:s\", strtotime( '-60 days' ) ),\n ],\n ]);\n //* ...and delete them\n array_filter( function( $post ) {\n wp_delete_post( $post-&gt;ID );\n }, $posts );\n}\n</code></pre>\n\n<p>The answer above directly queries <code>$wpdb</code>. Using the <code>get_posts()</code> abstraction is better for a variety of reasons including ease-of-reading and future-proofing.</p>\n" }, { "answer_id": 262492, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 2, "selected": false, "text": "<pre><code>// add the schedule event if it has been removed \nif( ! wp_next_scheduled( 'mg_remove_old_entries' ) ) {\n wp_schedule_event( time(), 'daily', 'mg_remove_old_entries' ); //run the event daily\n}\n\n// action hooked to fired with wordpress cron job\nadd_action( 'mg_remove_old_entries', 'mg_remove_old_entries' );\nfunction mg_remove_old_entries() {\n $posts = get_posts( [\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'vfb_entry',\n 'date_query' =&gt; [\n // get all the posts from the database which are older than 60 days\n 'before' =&gt; date( \"Y-m-d H:i:s\", strtotime( '-60 days' ) ),\n ],\n ]);\n\n if( !empty($posts) ) {\n foreach( $posts as $post ) {\n wp_delete_post( $post-&gt;ID ); //remove the post from the database\n }\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> There is no need to run any custom sql query. It would make the query slow and also it is not good for wordpress. Wordpress has already in built functions for everything. </p>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213720", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86289/" ]
I want to delete all posts of a specific post type (in this case "vfb\_entry") that are older than 60 days. The cron job should run once a day. I have the following code but it's not working if I trigger the cron job. However, running only the query in phpMyAdmin returns the correct result. So there must be an issue with the fuction itself. Can anyone please help? ``` // Cron Job to Delete VFB Entries older than 60 days if(!wp_next_scheduled( 'remove_old_vfb_entries')){ wp_schedule_event(time(), 'daily', 'remove_old_vfb_entries'); } add_action('remove_old_vfb_entries', 'myd_remove_old_vfb_entries'); // Build the function function myd_remove_old_vfb_entries(){ global $wpdb; // Set max post date and post_type name $date = date("Y-m-d H:i:s", strtotime('-60 days')); $post_type = 'vfb_entry'; // Build the query // Only select VFB Entries from LFG or LFM Form $query = " SELECT $wpdb->posts.ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_status = 'publish' AND post_date < '$date' AND ($wpdb->posts.ID IN (SELECT entry_id FROM wp_postmeta_lfg4 WHERE post_id IS NOT NULL) OR $wpdb->posts.ID IN (SELECT entry_id FROM wp_postmeta_lfm3 WHERE post_id IS NOT NULL)) ORDER BY post_modified DESC "; $results = $wpdb->get_results($query); foreach($results as $post){ // Let the WordPress API clean up the entire post trails wp_delete_post( $post->ID, true); } } ``` **Edit:** Solution without querying my views, just using wp\_posts and wp\_postmeta and an INNER JOIN below.
``` // add the schedule event if it has been removed if( ! wp_next_scheduled( 'mg_remove_old_entries' ) ) { wp_schedule_event( time(), 'daily', 'mg_remove_old_entries' ); //run the event daily } // action hooked to fired with wordpress cron job add_action( 'mg_remove_old_entries', 'mg_remove_old_entries' ); function mg_remove_old_entries() { $posts = get_posts( [ 'numberposts' => -1, 'post_type' => 'vfb_entry', 'date_query' => [ // get all the posts from the database which are older than 60 days 'before' => date( "Y-m-d H:i:s", strtotime( '-60 days' ) ), ], ]); if( !empty($posts) ) { foreach( $posts as $post ) { wp_delete_post( $post->ID ); //remove the post from the database } } } ``` **Note:** There is no need to run any custom sql query. It would make the query slow and also it is not good for wordpress. Wordpress has already in built functions for everything.
213,739
<p>I am trying to get only <strong>one</strong> post and this needs to be <strong>the latest one</strong> so here is what I am doing:</p> <pre><code>$basic_args = $wp_query-&gt;query_vars; $basic_args['tax_query'] = $wp_query-&gt;tax_query; $aditional_args = array( 'post__in' =&gt; get_option('sticky_posts'), 'ignore_sticky_posts' =&gt; 1, 'order' =&gt; 'desc', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 1 ); $normal_args = array_merge($basic_args, $aditional_args); $normal_query = new WP_Query($normal_args); $prev_post_ids = array(); if (!$normal_query-&gt;have_posts()) { $normal_args = array_merge($basic_args, array('posts_per_page' =&gt; 1)); $normal_query = new WP_Query($normal_args); } echo $normal_query-&gt;post_count; // returns 25 if ($normal_query-&gt;have_posts()) { while ($normal_query-&gt;have_posts()) { .... // here I got 25 results instead of just one } } </code></pre> <p>I know that <code>posts_per_page</code> should be limit how many post I will get but is not working for me and don't know why. As you can read I am getting 25 post on the loop instead of one. Can any give me some advice around this topic? I have read <a href="https://wordpress.stackexchange.com/questions/181541/how-to-limit-the-number-of-posts-that-wp-query-gets">this</a> and <a href="https://codex.wordpress.org/Class_Reference/WP_Query" rel="nofollow noreferrer">this</a> but isn't helping at all.</p> <p><strong>Update1</strong></p> <p>I debug the <code>$normal_query-&gt;request</code> as suggested by <strong>@pieter-goosen</strong> and I am getting this <em>wrong</em> SQL query:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (6) ) AND wp_posts.post_type IN ('opinion', 'post', 'especiales') AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 25 </code></pre> <p>Where the <code>LIMIT</code> is modified?</p> <p><strong>Update2</strong></p> <p>I have debug also the <code>$basic_args</code> which have <code>$wp_query-&gt;query_vars</code> and also <code>$normal_args</code> and here is the result:</p> <pre><code>echo '&lt;pre&gt;'; print_r($basic_args); echo '&lt;/pre&gt;'; Array ( [category_name] =&gt; internacionales [error] =&gt; [m] =&gt; [p] =&gt; 0 [post_parent] =&gt; [subpost] =&gt; [subpost_id] =&gt; [attachment] =&gt; [attachment_id] =&gt; 0 [name] =&gt; [static] =&gt; [pagename] =&gt; [page_id] =&gt; 0 [second] =&gt; [minute] =&gt; [hour] =&gt; [day] =&gt; 0 [monthnum] =&gt; 0 [year] =&gt; 0 [w] =&gt; 0 [tag] =&gt; [cat] =&gt; 409 [tag_id] =&gt; [author] =&gt; [author_name] =&gt; [feed] =&gt; [tb] =&gt; [paged] =&gt; 0 [comments_popup] =&gt; [meta_key] =&gt; [meta_value] =&gt; [preview] =&gt; [s] =&gt; [sentence] =&gt; [title] =&gt; [fields] =&gt; [menu_order] =&gt; [category__in] =&gt; Array ( ) [category__not_in] =&gt; Array ( ) [category__and] =&gt; Array ( ) [post__in] =&gt; Array ( ) [post__not_in] =&gt; Array ( ) [post_name__in] =&gt; Array ( ) [tag__in] =&gt; Array ( ) [tag__not_in] =&gt; Array ( ) [tag__and] =&gt; Array ( ) [tag_slug__in] =&gt; Array ( ) [tag_slug__and] =&gt; Array ( ) [post_parent__in] =&gt; Array ( ) [post_parent__not_in] =&gt; Array ( ) [author__in] =&gt; Array ( ) [author__not_in] =&gt; Array ( ) [ignore_sticky_posts] =&gt; [suppress_filters] =&gt; [cache_results] =&gt; 1 [update_post_term_cache] =&gt; 1 [update_post_meta_cache] =&gt; 1 [post_type] =&gt; [posts_per_page] =&gt; 10 [nopaging] =&gt; [comments_per_page] =&gt; 50 [no_found_rows] =&gt; [order] =&gt; DESC [tax_query] =&gt; WP_Tax_Query Object ( [queries] =&gt; Array ( [0] =&gt; Array ( [taxonomy] =&gt; category [terms] =&gt; Array ( [0] =&gt; internacionales ) [field] =&gt; slug [operator] =&gt; IN [include_children] =&gt; 1 ) ) [relation] =&gt; AND [table_aliases:protected] =&gt; Array ( [0] =&gt; wp_term_relationships ) [queried_terms] =&gt; Array ( [category] =&gt; Array ( [terms] =&gt; Array ( [0] =&gt; internacionales ) [field] =&gt; slug ) ) [primary_table] =&gt; wp_posts [primary_id_column] =&gt; ID ) ) echo '&lt;pre&gt;'; print_r($normal_args); echo '&lt;/pre&gt;'; Array ( [category_name] =&gt; internacionales [error] =&gt; [m] =&gt; [p] =&gt; 0 [post_parent] =&gt; [subpost] =&gt; [subpost_id] =&gt; [attachment] =&gt; [attachment_id] =&gt; 0 [name] =&gt; [static] =&gt; [pagename] =&gt; [page_id] =&gt; 0 [second] =&gt; [minute] =&gt; [hour] =&gt; [day] =&gt; 0 [monthnum] =&gt; 0 [year] =&gt; 0 [w] =&gt; 0 [tag] =&gt; [cat] =&gt; 409 [tag_id] =&gt; [author] =&gt; [author_name] =&gt; [feed] =&gt; [tb] =&gt; [paged] =&gt; 0 [comments_popup] =&gt; [meta_key] =&gt; [meta_value] =&gt; [preview] =&gt; [s] =&gt; [sentence] =&gt; [title] =&gt; [fields] =&gt; [menu_order] =&gt; [category__in] =&gt; Array ( ) [category__not_in] =&gt; Array ( ) [category__and] =&gt; Array ( ) [post__in] =&gt; Array ( ) [post__not_in] =&gt; Array ( ) [post_name__in] =&gt; Array ( ) [tag__in] =&gt; Array ( ) [tag__not_in] =&gt; Array ( ) [tag__and] =&gt; Array ( ) [tag_slug__in] =&gt; Array ( ) [tag_slug__and] =&gt; Array ( ) [post_parent__in] =&gt; Array ( ) [post_parent__not_in] =&gt; Array ( ) [author__in] =&gt; Array ( ) [author__not_in] =&gt; Array ( ) [ignore_sticky_posts] =&gt; 1 [suppress_filters] =&gt; [cache_results] =&gt; 1 [update_post_term_cache] =&gt; 1 [update_post_meta_cache] =&gt; 1 [post_type] =&gt; [posts_per_page] =&gt; 1 [nopaging] =&gt; [comments_per_page] =&gt; 50 [no_found_rows] =&gt; [order] =&gt; desc [tax_query] =&gt; WP_Tax_Query Object ( [queries] =&gt; Array ( [0] =&gt; Array ( [taxonomy] =&gt; category [terms] =&gt; Array ( [0] =&gt; internacionales ) [field] =&gt; slug [operator] =&gt; IN [include_children] =&gt; 1 ) ) [relation] =&gt; AND [table_aliases:protected] =&gt; Array ( [0] =&gt; wp_term_relationships ) [queried_terms] =&gt; Array ( [category] =&gt; Array ( [terms] =&gt; Array ( [0] =&gt; internacionales ) [field] =&gt; slug ) ) [primary_table] =&gt; wp_posts [primary_id_column] =&gt; ID ) [post_status] =&gt; publish ) </code></pre> <p>As you can see <code>post_per_page</code> is set to <code>1</code> here so why it's taking those 25?</p> <p><strong>Update 3</strong></p> <p>Apparently this is the problematic code at <code>functions.php</code>:</p> <pre><code>function change_wp_search_size($query) { if ($query-&gt;is_search) { $query-&gt;query_vars['posts_per_page'] = 25; } // Change 25 to the number of posts you would like to show return $query; // Return our modified query variables } add_filter('pre_get_posts', 'change_wp_search_size'); </code></pre> <p>Shouldn't this works for search only? Why is acting over all query_vars all the time?</p>
[ { "answer_id": 213844, "author": "ReynierPM", "author_id": 16412, "author_profile": "https://wordpress.stackexchange.com/users/16412", "pm_score": 0, "selected": false, "text": "<p>Ok, after the suggestions from <strong>@pieter-goosen</strong> I have found a solution, just adding this <code>remove_all_filters( 'pre_get_posts' )</code> before run that <code>WP_Query</code> fix the issue, hope it helps to others</p>\n" }, { "answer_id": 213845, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p><code>pre_get_posts</code> alters all queries, back end and front end regardless. </p>\n\n<p>There are two very important checks that a large amount of people misses, that is the <code>!is_admin()</code> check which only targets the front end, and then the most important check, <code>is_main_query()</code> which will only alter the main query and not custom queries. </p>\n\n<p>You statement should look something like the follwoing </p>\n\n<pre><code>if ( !is_admin() \n &amp;&amp; $query-&gt;is_main_query() \n &amp;&amp; $query-&gt;is_search() \n) {\n // Your arguments to set\n}\n</code></pre>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213739", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16412/" ]
I am trying to get only **one** post and this needs to be **the latest one** so here is what I am doing: ``` $basic_args = $wp_query->query_vars; $basic_args['tax_query'] = $wp_query->tax_query; $aditional_args = array( 'post__in' => get_option('sticky_posts'), 'ignore_sticky_posts' => 1, 'order' => 'desc', 'post_status' => 'publish', 'posts_per_page' => 1 ); $normal_args = array_merge($basic_args, $aditional_args); $normal_query = new WP_Query($normal_args); $prev_post_ids = array(); if (!$normal_query->have_posts()) { $normal_args = array_merge($basic_args, array('posts_per_page' => 1)); $normal_query = new WP_Query($normal_args); } echo $normal_query->post_count; // returns 25 if ($normal_query->have_posts()) { while ($normal_query->have_posts()) { .... // here I got 25 results instead of just one } } ``` I know that `posts_per_page` should be limit how many post I will get but is not working for me and don't know why. As you can read I am getting 25 post on the loop instead of one. Can any give me some advice around this topic? I have read [this](https://wordpress.stackexchange.com/questions/181541/how-to-limit-the-number-of-posts-that-wp-query-gets) and [this](https://codex.wordpress.org/Class_Reference/WP_Query) but isn't helping at all. **Update1** I debug the `$normal_query->request` as suggested by **@pieter-goosen** and I am getting this *wrong* SQL query: ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (6) ) AND wp_posts.post_type IN ('opinion', 'post', 'especiales') AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 25 ``` Where the `LIMIT` is modified? **Update2** I have debug also the `$basic_args` which have `$wp_query->query_vars` and also `$normal_args` and here is the result: ``` echo '<pre>'; print_r($basic_args); echo '</pre>'; Array ( [category_name] => internacionales [error] => [m] => [p] => 0 [post_parent] => [subpost] => [subpost_id] => [attachment] => [attachment_id] => 0 [name] => [static] => [pagename] => [page_id] => 0 [second] => [minute] => [hour] => [day] => 0 [monthnum] => 0 [year] => 0 [w] => 0 [tag] => [cat] => 409 [tag_id] => [author] => [author_name] => [feed] => [tb] => [paged] => 0 [comments_popup] => [meta_key] => [meta_value] => [preview] => [s] => [sentence] => [title] => [fields] => [menu_order] => [category__in] => Array ( ) [category__not_in] => Array ( ) [category__and] => Array ( ) [post__in] => Array ( ) [post__not_in] => Array ( ) [post_name__in] => Array ( ) [tag__in] => Array ( ) [tag__not_in] => Array ( ) [tag__and] => Array ( ) [tag_slug__in] => Array ( ) [tag_slug__and] => Array ( ) [post_parent__in] => Array ( ) [post_parent__not_in] => Array ( ) [author__in] => Array ( ) [author__not_in] => Array ( ) [ignore_sticky_posts] => [suppress_filters] => [cache_results] => 1 [update_post_term_cache] => 1 [update_post_meta_cache] => 1 [post_type] => [posts_per_page] => 10 [nopaging] => [comments_per_page] => 50 [no_found_rows] => [order] => DESC [tax_query] => WP_Tax_Query Object ( [queries] => Array ( [0] => Array ( [taxonomy] => category [terms] => Array ( [0] => internacionales ) [field] => slug [operator] => IN [include_children] => 1 ) ) [relation] => AND [table_aliases:protected] => Array ( [0] => wp_term_relationships ) [queried_terms] => Array ( [category] => Array ( [terms] => Array ( [0] => internacionales ) [field] => slug ) ) [primary_table] => wp_posts [primary_id_column] => ID ) ) echo '<pre>'; print_r($normal_args); echo '</pre>'; Array ( [category_name] => internacionales [error] => [m] => [p] => 0 [post_parent] => [subpost] => [subpost_id] => [attachment] => [attachment_id] => 0 [name] => [static] => [pagename] => [page_id] => 0 [second] => [minute] => [hour] => [day] => 0 [monthnum] => 0 [year] => 0 [w] => 0 [tag] => [cat] => 409 [tag_id] => [author] => [author_name] => [feed] => [tb] => [paged] => 0 [comments_popup] => [meta_key] => [meta_value] => [preview] => [s] => [sentence] => [title] => [fields] => [menu_order] => [category__in] => Array ( ) [category__not_in] => Array ( ) [category__and] => Array ( ) [post__in] => Array ( ) [post__not_in] => Array ( ) [post_name__in] => Array ( ) [tag__in] => Array ( ) [tag__not_in] => Array ( ) [tag__and] => Array ( ) [tag_slug__in] => Array ( ) [tag_slug__and] => Array ( ) [post_parent__in] => Array ( ) [post_parent__not_in] => Array ( ) [author__in] => Array ( ) [author__not_in] => Array ( ) [ignore_sticky_posts] => 1 [suppress_filters] => [cache_results] => 1 [update_post_term_cache] => 1 [update_post_meta_cache] => 1 [post_type] => [posts_per_page] => 1 [nopaging] => [comments_per_page] => 50 [no_found_rows] => [order] => desc [tax_query] => WP_Tax_Query Object ( [queries] => Array ( [0] => Array ( [taxonomy] => category [terms] => Array ( [0] => internacionales ) [field] => slug [operator] => IN [include_children] => 1 ) ) [relation] => AND [table_aliases:protected] => Array ( [0] => wp_term_relationships ) [queried_terms] => Array ( [category] => Array ( [terms] => Array ( [0] => internacionales ) [field] => slug ) ) [primary_table] => wp_posts [primary_id_column] => ID ) [post_status] => publish ) ``` As you can see `post_per_page` is set to `1` here so why it's taking those 25? **Update 3** Apparently this is the problematic code at `functions.php`: ``` function change_wp_search_size($query) { if ($query->is_search) { $query->query_vars['posts_per_page'] = 25; } // Change 25 to the number of posts you would like to show return $query; // Return our modified query variables } add_filter('pre_get_posts', 'change_wp_search_size'); ``` Shouldn't this works for search only? Why is acting over all query\_vars all the time?
`pre_get_posts` alters all queries, back end and front end regardless. There are two very important checks that a large amount of people misses, that is the `!is_admin()` check which only targets the front end, and then the most important check, `is_main_query()` which will only alter the main query and not custom queries. You statement should look something like the follwoing ``` if ( !is_admin() && $query->is_main_query() && $query->is_search() ) { // Your arguments to set } ```
213,742
<p>I am building my first WP plugin, it should load some JS and CSS files only on specific pages selected through a form available in the plugin Admin area. Once selected in the form, Page Title gets stored in the DB wp_options table, then the data is pulled back out in a variable named $page_selected. To load JS and CSS files only in the pages selected in form, I wanted to use the is_page() function, passing the $page_selected variable as a parameter.</p> <pre><code> function my_custom_tooltip() { if ( is_page($page_selected) ) { wp_enqueue_style( 'custom_tooltip_frontend_css', plugins_url('custom-image-tooltip/custom-image-tooltip.css') ); wp_enqueue_script( 'custom_tooltip_frontend_js', plugins_url('custom-image-tooltip/custom-image-tooltip.js'), array('jquery'), '', true ); } } add_action('wp_enqueue_scripts', 'my_custom_tooltip'); </code></pre> <p>Unluckily In my case that conditional statement doesn't work correctly. Is there any way to achieve the same result, matching the page selected in the form by the user with the current Page being displayed?</p>
[ { "answer_id": 213743, "author": "Puneet Sahalot", "author_id": 19739, "author_profile": "https://wordpress.stackexchange.com/users/19739", "pm_score": 3, "selected": false, "text": "<p>If <code>$page_selected</code> returns a string containing the page title, it should work fine. I have tested it and <code>is_page()</code> accepts page title, page ID and the slug. </p>\n\n<p>If you are facing issues, it will be better to store page ID in the database and use it with <code>is_page()</code> </p>\n\n<p>Please refer to <a href=\"https://codex.wordpress.org/Function_Reference/is_page\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/is_page</a> for more details on the possible arguments that can be passed to this conditional statement. </p>\n" }, { "answer_id": 213744, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 0, "selected": false, "text": "<p>Untested...but something like this should work to get the name (i.e. slug) of the page currently displayed:</p>\n\n<pre><code>function my_custom_tooltip() {\n global $post;\n if ( is_object( $post ) &amp;&amp; $post-&gt;post_type=='page' ) {\n if ( $post-&gt;post_name == $page_selected ) {\n wp_enqueue_style( 'custom_tooltip_frontend_css', plugins_url('custom-image-tooltip/custom-image-tooltip.css') );\n wp_enqueue_script( 'custom_tooltip_frontend_js', plugins_url('custom-image-tooltip/custom-image-tooltip.js'), array('jquery'), '', true );\n }\n }\n}\n</code></pre>\n\n<p>The compare to <code>$page_selected</code> is of course expecting it to be in \"slug\" format as well...or if comparing to page title you could use <code>$post-&gt;post_title</code> instead of <code>$post-&gt;post_name</code>.</p>\n\n<p>Note, this is an example where using PHP classes is helpful, to avoid having to use a global variable (<code>$page_selected</code>) inside that function...</p>\n" }, { "answer_id": 214141, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": false, "text": "<p>I make some pretty change and I hope this help you well. Try below code:</p>\n\n<pre><code>function my_custom_tooltip() {\n wp_enqueue_style( 'custom_tooltip_frontend_css', plugins_url('custom-image-tooltip/custom-image-tooltip.css') );\n wp_enqueue_script( 'custom_tooltip_frontend_js', plugins_url('custom-image-tooltip/custom-image-tooltip.js'), array('jquery'), '', true );\n} \n\nif(is_page($page_selected)){\n add_action('wp_enqueue_scripts', 'my_custom_tooltip');\n}\n</code></pre>\n\n<p>Here, make sure about <code>$page_selected</code>.</p>\n\n<p><strong>NOTE:</strong> You should always <em>enqueue</em> your scripts in a theme's <em>functions.php</em> file - not a template file. Template files are just Not The Right Place <em>99.9%</em> of the time. </p>\n\n<p>You can use <code>is_page()</code> in multiple form like:</p>\n\n<pre><code>// When any single Page is being displayed.\nis_page();\n\n// When Page 42 (ID) is being displayed.\nis_page( 42 );\n\n// When the Page with a post_title of \"Contact\" is being displayed.\nis_page( 'Contact' );\n\n// When the Page with a post_name (slug) of \"about-me\" is being displayed.\nis_page( 'about-me' );\n\n// Returns true when the Pages displayed is either post ID 42, or post_name \"about-me\", or post_title \"Contact\". \nis_page( array( 42, 'about-me', 'Contact' ) );\n</code></pre>\n\n<p><strong>Note:</strong> The array ability was added at Version 2.5.</p>\n" }, { "answer_id": 280291, "author": "Lucas Miranda", "author_id": 127219, "author_profile": "https://wordpress.stackexchange.com/users/127219", "pm_score": 1, "selected": false, "text": "<p>If you're running this code inside a template file, it will work just fine, but if this code is in functions.php or in a plugin file, it will throw this error in <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\"><code>debug.log</code></a>:</p>\n\n<blockquote>\n <p>PHP Notice: is_page was called <strong>incorrectly</strong>. Conditional query tags do not work before the query is run. Before then, they always return false.</p>\n</blockquote>\n\n<p>In this case, you could use the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a> action hook, as explained <a href=\"https://stackoverflow.com/a/22070503/7090367\">here</a>.</p>\n" } ]
2016/01/05
[ "https://wordpress.stackexchange.com/questions/213742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86296/" ]
I am building my first WP plugin, it should load some JS and CSS files only on specific pages selected through a form available in the plugin Admin area. Once selected in the form, Page Title gets stored in the DB wp\_options table, then the data is pulled back out in a variable named $page\_selected. To load JS and CSS files only in the pages selected in form, I wanted to use the is\_page() function, passing the $page\_selected variable as a parameter. ``` function my_custom_tooltip() { if ( is_page($page_selected) ) { wp_enqueue_style( 'custom_tooltip_frontend_css', plugins_url('custom-image-tooltip/custom-image-tooltip.css') ); wp_enqueue_script( 'custom_tooltip_frontend_js', plugins_url('custom-image-tooltip/custom-image-tooltip.js'), array('jquery'), '', true ); } } add_action('wp_enqueue_scripts', 'my_custom_tooltip'); ``` Unluckily In my case that conditional statement doesn't work correctly. Is there any way to achieve the same result, matching the page selected in the form by the user with the current Page being displayed?
If `$page_selected` returns a string containing the page title, it should work fine. I have tested it and `is_page()` accepts page title, page ID and the slug. If you are facing issues, it will be better to store page ID in the database and use it with `is_page()` Please refer to <https://codex.wordpress.org/Function_Reference/is_page> for more details on the possible arguments that can be passed to this conditional statement.
213,805
<p>I tried adding placeholder similar to the given for <strong>ContactNumber</strong> for my drop down <strong>Outlet</strong> but it doesn't appear.</p> <p>Code-</p> <pre><code>&lt;div class="form-group form-icon-group"&gt; &lt;i class="fa fa-phone" &gt; &lt;/i&gt; [tel* ContactNumber /8 class:form-control placeholder "Contact Number *"] &lt;/div&gt; &lt;div class="form-group form-icon-group"&gt; &lt;i class="fa fa-food" &gt; &lt;/i&gt; [select Outlet id:outlet class:form-control "-- Select Outlet--" "Pasir Ris" "Thomson"] &lt;/div&gt; </code></pre> <p>Tried adding <code>first_as_label "Preferred outlet?"</code> so this displays as ordinary drop down values.</p> <p>Rest all of the fields do show the placeholder,any other way to give placeholder for drop down?</p>
[ { "answer_id": 213809, "author": "Reigel Gallarde", "author_id": 974, "author_profile": "https://wordpress.stackexchange.com/users/974", "pm_score": -1, "selected": true, "text": "<p>to answer the question: this is not possible. </p>\n\n<p>AFAIK, (HTMLwise) there's no way to add a placeholder to select tags. </p>\n\n<p>A lot of devs I know however tend to use <code>disabled selected</code> combination for the option...</p>\n\n\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;select&gt;\n &lt;option value=\"\" disabled selected&gt;Select your option&lt;/option&gt;\n &lt;option value=\"ydasdas\"&gt;ydasdas&lt;/option&gt;\n &lt;option value=\"dasda\"&gt;dasda&lt;/option&gt;\n &lt;option value=\"ydagfdsdas\"&gt;ydagfdsdas&lt;/option&gt;\n &lt;option value=\"ewefsdf\"&gt;ewefsdf&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n\n\n<p><a href=\"https://jsfiddle.net/9amo84jd/\" rel=\"nofollow noreferrer\">demo</a></p>\n\n<p>I have checked CF7's source code (version 4.3.1), and there's no easy way we can achieve this html format.</p>\n\n<p>You can go the hard way by removing <code>wpcf7_add_shortcode_select</code> action on <code>wpcf7_init</code> and add yours instead. </p>\n" }, { "answer_id": 213864, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 7, "selected": false, "text": "<p>Contrary to what the accepted answer suggests, it actually is possible and built into Contact Form 7. Here's the actual <a href=\"http://contactform7.com/checkboxes-radio-buttons-and-menus/#select\">list of options <code>[select]</code> holds</a>. Pretty much you would define the first option to be the placeholder using <code>first_as_label</code>:</p>\n\n<pre><code>[select* Test first_as_label \"Placeholder\" \"Option 1\" \"Option 2\"]\n</code></pre>\n\n<p>While it won't traditionally look like a placeholder, if it's required the user won't be able to select the placeholder and send the form - this forces the user to select any of the other options.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213805", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86319/" ]
I tried adding placeholder similar to the given for **ContactNumber** for my drop down **Outlet** but it doesn't appear. Code- ``` <div class="form-group form-icon-group"> <i class="fa fa-phone" > </i> [tel* ContactNumber /8 class:form-control placeholder "Contact Number *"] </div> <div class="form-group form-icon-group"> <i class="fa fa-food" > </i> [select Outlet id:outlet class:form-control "-- Select Outlet--" "Pasir Ris" "Thomson"] </div> ``` Tried adding `first_as_label "Preferred outlet?"` so this displays as ordinary drop down values. Rest all of the fields do show the placeholder,any other way to give placeholder for drop down?
to answer the question: this is not possible. AFAIK, (HTMLwise) there's no way to add a placeholder to select tags. A lot of devs I know however tend to use `disabled selected` combination for the option... ```html <select> <option value="" disabled selected>Select your option</option> <option value="ydasdas">ydasdas</option> <option value="dasda">dasda</option> <option value="ydagfdsdas">ydagfdsdas</option> <option value="ewefsdf">ewefsdf</option> </select> ``` [demo](https://jsfiddle.net/9amo84jd/) I have checked CF7's source code (version 4.3.1), and there's no easy way we can achieve this html format. You can go the hard way by removing `wpcf7_add_shortcode_select` action on `wpcf7_init` and add yours instead.
213,808
<p>I just bought the Visual Composer plugin from wpbakery, my problem is that I'm making ajax calls to get the content of posts that have been edited with Visual Composer when I get the data it only show me the shortcodes of the plugin</p> <p>As I see from the information that I have found on how to fix this problem is that ajax calls can't show shortcodes because of the admin ajax url that they dont have full access to wordpress enviornment but I want to know if someone has done it please it would help me a lot</p> <p>basically this is how I print it, the ajax call is working fine it shows me what I saved but the elements doesnt show correctly it only shows shortcodes</p> <p>this code is in a plugin I made</p> <pre><code>function prefix_load_proyect () { $post_id = $_POST[ 'proyect' ]; $the_query = new WP_Query(array('p'=&gt;$post_id, 'post_type' =&gt; 'home_portfolio')); while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $content = apply_filters('the_content', $post-&gt;post_content); $content = do_shortcode(get_post_field('post_content', $postid)); $html=$content; endwhile; wp_reset_postdata(); echo $html; die(); } </code></pre> <p>then in the js file I just make the ajax call and put the html response with jquery into a container</p> <pre><code> jQuery.ajax({ type: 'POST', url: ajaxurl, data: {"action": "load-filter-proyect", proyect: proyectID }, success: function(response) { jQuery('#agregarProyectContainer').html(response); }); </code></pre>
[ { "answer_id": 213833, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>...ajax calls can't show shortcodes because of the admin ajax url that they dont have full access to wordpress enviorment</p>\n</blockquote>\n\n<p>Not true. AJAX calls have exactly the same resources at their disposal as regular WordPress requests. Just make sure to parse the content in the same way <code>the_content()</code> does:</p>\n\n<pre><code>$parsed_content = apply_filters( 'the_content', $post-&gt;post_content );\n</code></pre>\n\n<p><strong>Update:</strong> Your code is a mess, try this instead:</p>\n\n<pre><code>function prefix_load_proyect() {\n if ( ! isset( $_POST['proyect'] ) || ! $post_id = absint( $_POST['proyect'] ) )\n return;\n\n if ( ! $post = get_post( $post_id ) )\n return;\n\n echo apply_filters( 'the_content', $post-&gt;post_content );\n exit;\n}\n</code></pre>\n" }, { "answer_id": 239221, "author": "Martin from WP-Stars.com", "author_id": 85008, "author_profile": "https://wordpress.stackexchange.com/users/85008", "pm_score": 2, "selected": false, "text": "<p>Since Visual Composer Version 4.9 you have to use WPBMap::addAllMappedShortcodes() before the apply_filters('the_content', ...) or do_shortcode(). You don't need both by the way, because apply_filters('the_content', ...) executes do_shortcode() anyway.</p>\n\n<p>Your function would then be:</p>\n\n<pre><code>function prefix_load_proyect () {\n\n $post_id = $_POST[ 'proyect' ];\n $the_query = new WP_Query(array('p'=&gt;$post_id, 'post_type' =&gt; 'home_portfolio'));\n\n\n /* --- Necessary since Visual Compoer V 4.9 --- */\n WPBMap::addAllMappedShortcodes();\n\n\n while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n\n $content .= apply_filters('the_content', $post-&gt;post_content);\n endwhile;\n\n echo $content;\n wp_die(); // wp_die() instead of die() provides better integration with WordPress\n}\n</code></pre>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86321/" ]
I just bought the Visual Composer plugin from wpbakery, my problem is that I'm making ajax calls to get the content of posts that have been edited with Visual Composer when I get the data it only show me the shortcodes of the plugin As I see from the information that I have found on how to fix this problem is that ajax calls can't show shortcodes because of the admin ajax url that they dont have full access to wordpress enviornment but I want to know if someone has done it please it would help me a lot basically this is how I print it, the ajax call is working fine it shows me what I saved but the elements doesnt show correctly it only shows shortcodes this code is in a plugin I made ``` function prefix_load_proyect () { $post_id = $_POST[ 'proyect' ]; $the_query = new WP_Query(array('p'=>$post_id, 'post_type' => 'home_portfolio')); while ( $the_query->have_posts() ) : $the_query->the_post(); $content = apply_filters('the_content', $post->post_content); $content = do_shortcode(get_post_field('post_content', $postid)); $html=$content; endwhile; wp_reset_postdata(); echo $html; die(); } ``` then in the js file I just make the ajax call and put the html response with jquery into a container ``` jQuery.ajax({ type: 'POST', url: ajaxurl, data: {"action": "load-filter-proyect", proyect: proyectID }, success: function(response) { jQuery('#agregarProyectContainer').html(response); }); ```
Since Visual Composer Version 4.9 you have to use WPBMap::addAllMappedShortcodes() before the apply\_filters('the\_content', ...) or do\_shortcode(). You don't need both by the way, because apply\_filters('the\_content', ...) executes do\_shortcode() anyway. Your function would then be: ``` function prefix_load_proyect () { $post_id = $_POST[ 'proyect' ]; $the_query = new WP_Query(array('p'=>$post_id, 'post_type' => 'home_portfolio')); /* --- Necessary since Visual Compoer V 4.9 --- */ WPBMap::addAllMappedShortcodes(); while ( $the_query->have_posts() ) : $the_query->the_post(); $content .= apply_filters('the_content', $post->post_content); endwhile; echo $content; wp_die(); // wp_die() instead of die() provides better integration with WordPress } ```
213,812
<p>How can I get a post's content by post id? I tried <code>get_page('ID');</code> to show content but it does not work. </p>
[ { "answer_id": 213815, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 4, "selected": false, "text": "<p>You can do it multiple ways. Following are best two ways.</p>\n\n<pre><code>$post_id = 5// example post id\n$post_content = get_post($post_id);\n$content = $post_content-&gt;post_content;\necho do_shortcode( $content );//executing shortcodes\n</code></pre>\n\n<p>Another method</p>\n\n<pre><code>$content = get_post_field('post_content', $post_id);\necho do_shortcode( $content );//executing shortcodes\n</code></pre>\n\n<p>After Pieter Goosen suggestion on <code>apply_filters</code>.</p>\n\n<p>You can use <code>apply_filters</code> if you wanted the content to be filtered by other plugins. So this eliminates the need to use <code>do_shortcode</code></p>\n\n<p>Example</p>\n\n<pre><code>$post_id = 5// example post id\n$post_content = get_post($post_id);\n$content = $post_content-&gt;post_content;\necho apply_filters('the_content',$content);\n //no need to use do_shortcode, but content might be filtered by other plugins.\n</code></pre>\n\n<p>If you don't want to allow other plugins to filter this content and need shortcode function then go with <code>do_shortcode</code>.</p>\n\n<p>If you don't want shortcode too then just play with the <code>post_content</code>.</p>\n" }, { "answer_id": 213820, "author": "etest", "author_id": 86325, "author_profile": "https://wordpress.stackexchange.com/users/86325", "pm_score": -1, "selected": false, "text": "<p>By using <code>get_page('ID')</code>.</p>\n\n<pre><code>$page_id = 123; //Page ID\n$page_data = get_page($page_id); \n$title = $page_data-&gt;post_title; \n$content = $page_data-&gt;post_content;\n</code></pre>\n" }, { "answer_id": 246724, "author": "DrLightman", "author_id": 4053, "author_profile": "https://wordpress.stackexchange.com/users/4053", "pm_score": 0, "selected": false, "text": "<p>I'll just leave here another hacky ugly way that you may find useful sometimes. Of course methods which use API calls are always preferred (get_post(), get_the_content(), ...).</p>\n\n<pre><code>global $wpdb;\n$post_id = 123; // fill in your desired post ID\n$post_content_raw = $wpdb-&gt;get_var(\n $wpdb-&gt;prepare(\n \"select post_content from $wpdb-&gt;posts where ID = %d\",\n $post_id\n )\n);\n</code></pre>\n" }, { "answer_id": 291495, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>$id = 23; // add the ID of the page where the zero is\n$p = get_page($id);\n$t = $p-&gt;post_title;\necho '&lt;h3&gt;'.apply_filters('post_title', $t).'&lt;/h3&gt;'; // the title is here wrapped with h3\necho apply_filters('the_content', $p-&gt;post_content);\n</code></pre>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76513/" ]
How can I get a post's content by post id? I tried `get_page('ID');` to show content but it does not work.
You can do it multiple ways. Following are best two ways. ``` $post_id = 5// example post id $post_content = get_post($post_id); $content = $post_content->post_content; echo do_shortcode( $content );//executing shortcodes ``` Another method ``` $content = get_post_field('post_content', $post_id); echo do_shortcode( $content );//executing shortcodes ``` After Pieter Goosen suggestion on `apply_filters`. You can use `apply_filters` if you wanted the content to be filtered by other plugins. So this eliminates the need to use `do_shortcode` Example ``` $post_id = 5// example post id $post_content = get_post($post_id); $content = $post_content->post_content; echo apply_filters('the_content',$content); //no need to use do_shortcode, but content might be filtered by other plugins. ``` If you don't want to allow other plugins to filter this content and need shortcode function then go with `do_shortcode`. If you don't want shortcode too then just play with the `post_content`.
213,817
<p>How can I execute DB queries when theme installs and delete those tables on theme uninstall?</p>
[ { "answer_id": 213819, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 0, "selected": false, "text": "<p>Theme activation use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow\">after_switch_theme</a></p>\n\n<pre><code>add_action(\"after_switch_theme\", \"setup_db\"); \n\nfunction setup_db(){\n //run your create table statements\n}\n</code></pre>\n\n<p>Theme deactivation use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/switch_theme\" rel=\"nofollow\">switch_theme</a></p>\n\n<pre><code>add_action('switch_theme', 'delete_db_things');\n\nfunction delete_db_things(){\n //run deletion statements\n}\n</code></pre>\n" }, { "answer_id": 213838, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p>Yes, you can accomplish it by WP default functionality. Let me explain it. </p>\n\n<p><strong>1. While switch theme:</strong></p>\n\n<p>There is a <code>switch_theme</code> action that runs right after the theme is switched. switch_theme is triggered when the blog's theme is changed. Specifically, it fires after the theme has been switched but before the next request. Theme developers should use this hook to do things when their theme is deactivated. </p>\n\n<pre><code>&lt;?php add_action('switch_theme', 'theme_deactivation_function'); ?&gt; \n</code></pre>\n\n<p>Theme functions attached to this hook are only triggered in the theme being deactivated. To do things when your theme is activated, use <code>after_switch_theme</code>. </p>\n\n<p>Delete a theme's options after deactivation:</p>\n\n<pre><code>add_action('switch_theme', 'mytheme_setup_options');\n\nfunction mytheme_setup_options () {\n delete_option('mytheme_enable_features');\n delete_option('mytheme_enable_catalog');\n}\n</code></pre>\n\n<p><code>switch_theme</code> will only be called when your theme is <em>de-activated</em>.</p>\n\n<p><strong>2. After switch theme:</strong></p>\n\n<p>Theme functions attached to this hook are only triggered in the theme (and/or child theme) being activated. To do things when your theme is deactivated, use <code>switch_theme</code>. </p>\n\n<p>In other words, the after_setup_theme represents the point at which <em>WordPress</em> sets up the current Theme, not the point at which the administrator activates and/or configures the current Theme.</p>\n\n<pre><code>&lt;?php add_action(\"after_switch_theme\", \"mytheme_do_something\"); ?&gt;\n</code></pre>\n\n<p>Add options for your theme and set them to their default values:</p>\n\n<pre><code>add_action('after_switch_theme', 'mytheme_setup_options');\n\nfunction mytheme_setup_options () {\n add_option('mytheme_enable_catalog', 0);\n add_option('mytheme_enable_features', 0);\n}\n</code></pre>\n\n<p><code>after_switch_theme</code> only fire when your theme is being activated.</p>\n\n<p><strong>Referance:</strong> <code>switch_theme</code> and <code>after_switch_theme</code> actions hook are located in <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L0\" rel=\"nofollow\">wp-includes/theme.php</a></p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86324/" ]
How can I execute DB queries when theme installs and delete those tables on theme uninstall?
Yes, you can accomplish it by WP default functionality. Let me explain it. **1. While switch theme:** There is a `switch_theme` action that runs right after the theme is switched. switch\_theme is triggered when the blog's theme is changed. Specifically, it fires after the theme has been switched but before the next request. Theme developers should use this hook to do things when their theme is deactivated. ``` <?php add_action('switch_theme', 'theme_deactivation_function'); ?> ``` Theme functions attached to this hook are only triggered in the theme being deactivated. To do things when your theme is activated, use `after_switch_theme`. Delete a theme's options after deactivation: ``` add_action('switch_theme', 'mytheme_setup_options'); function mytheme_setup_options () { delete_option('mytheme_enable_features'); delete_option('mytheme_enable_catalog'); } ``` `switch_theme` will only be called when your theme is *de-activated*. **2. After switch theme:** Theme functions attached to this hook are only triggered in the theme (and/or child theme) being activated. To do things when your theme is deactivated, use `switch_theme`. In other words, the after\_setup\_theme represents the point at which *WordPress* sets up the current Theme, not the point at which the administrator activates and/or configures the current Theme. ``` <?php add_action("after_switch_theme", "mytheme_do_something"); ?> ``` Add options for your theme and set them to their default values: ``` add_action('after_switch_theme', 'mytheme_setup_options'); function mytheme_setup_options () { add_option('mytheme_enable_catalog', 0); add_option('mytheme_enable_features', 0); } ``` `after_switch_theme` only fire when your theme is being activated. **Referance:** `switch_theme` and `after_switch_theme` actions hook are located in [wp-includes/theme.php](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/theme.php#L0)
213,825
<p>I want to check if the title of the post has changed and do some stuff if it did.</p> <p>I thought of using the post_updated hook, the codex says "Use this hook whenever you need to compare values <strong>before</strong> and <strong>after</strong> the post update.", but i can't figure out how to use the before and after arguments.</p> <pre><code>function check_values($post_ID, $post_after, $post_before){ echo 'Post ID:'; var_dump($post_ID); echo '&lt;br&gt;Post Object AFTER update:'; echo '&lt;pre&gt;'; print_r($post_after); echo '&lt;/pre&gt;'; echo '&lt;br&gt;Post Object BEFORE update:'; echo '&lt;pre&gt;'; print_r($post_before); echo '&lt;/pre&gt;'; } add_action( 'post_updated', 'check_values', 10, 3 ); </code></pre> <p>and i'm echoing it <code>echo check_values($post-&gt;ID, get_post(),get_post());</code> inside a metabox.</p> <p>Currently I'm getting the same values.</p> <p>If i <code>echo check_values();</code> I get missing argument error and on <code>echo check_values($post_ID, $post_after, $post_before)</code> i get NULL.</p> <p><strong>How can i get the values before and after the update?</strong></p> <p><strong>Update</strong></p> <pre><code>function check_values($post_ID, $post_after, $post_before){ if ($post_before-&gt;post_title != $post_after-&gt;post_title) { // do stuff } } add_action( 'post_updated', 'check_values', 10, 3 ); </code></pre>
[ { "answer_id": 213827, "author": "JoeMoe1984", "author_id": 32601, "author_profile": "https://wordpress.stackexchange.com/users/32601", "pm_score": 4, "selected": true, "text": "<p>First off you are using the function wrong. The function is tied to an action within wordpress whenever you use the <code>add_action</code> function. In this case you have added it to the <code>post_updated</code> action.</p>\n\n<p>Basically your check_values function gets added to a queue which will then get called by the action when its time to do the action.</p>\n\n<p>You can see where the action gets called here: <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359</a></p>\n\n<p>See line 3359 of this file. There is a function called <code>do_action</code> and its going to call all the functions tied to the post_updated action. This would include your check_values function. This is where your function is getting called and as you can see it passes in the necessary parameters for your function to interact with.</p>\n\n<p>Try updating or adding a post. You should see some output there because this is when wordpress is calling your function.</p>\n\n<p>Then in order to check to see if there was a change compare the two titles from the two before and after post objects</p>\n\n<pre><code>&lt;?php \n\nfunction check_values($post_ID, $post_after, $post_before){\n if( $post_after-&gt;post_title !== $post_before-&gt;post_title ) {\n // do something\n }\n}\n\nadd_action( 'post_updated', 'check_values', 10, 3 );\n?&gt;\n</code></pre>\n" }, { "answer_id": 333218, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When I used this action \"post_updated\" and update the post from latest updated gutenburg editor that time I get same post name in before post and after post details array. </p>\n\n<p>It means suppose post name is \"abc-test\" and I changed this to a new post name as \"abc-test-2\" then I get \"abc-test-2\" name in both post after and before details.</p>\n\n<p>Why its showing same data?</p>\n\n<p>Thanks in advance.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47701/" ]
I want to check if the title of the post has changed and do some stuff if it did. I thought of using the post\_updated hook, the codex says "Use this hook whenever you need to compare values **before** and **after** the post update.", but i can't figure out how to use the before and after arguments. ``` function check_values($post_ID, $post_after, $post_before){ echo 'Post ID:'; var_dump($post_ID); echo '<br>Post Object AFTER update:'; echo '<pre>'; print_r($post_after); echo '</pre>'; echo '<br>Post Object BEFORE update:'; echo '<pre>'; print_r($post_before); echo '</pre>'; } add_action( 'post_updated', 'check_values', 10, 3 ); ``` and i'm echoing it `echo check_values($post->ID, get_post(),get_post());` inside a metabox. Currently I'm getting the same values. If i `echo check_values();` I get missing argument error and on `echo check_values($post_ID, $post_after, $post_before)` i get NULL. **How can i get the values before and after the update?** **Update** ``` function check_values($post_ID, $post_after, $post_before){ if ($post_before->post_title != $post_after->post_title) { // do stuff } } add_action( 'post_updated', 'check_values', 10, 3 ); ```
First off you are using the function wrong. The function is tied to an action within wordpress whenever you use the `add_action` function. In this case you have added it to the `post_updated` action. Basically your check\_values function gets added to a queue which will then get called by the action when its time to do the action. You can see where the action gets called here: <https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359> See line 3359 of this file. There is a function called `do_action` and its going to call all the functions tied to the post\_updated action. This would include your check\_values function. This is where your function is getting called and as you can see it passes in the necessary parameters for your function to interact with. Try updating or adding a post. You should see some output there because this is when wordpress is calling your function. Then in order to check to see if there was a change compare the two titles from the two before and after post objects ``` <?php function check_values($post_ID, $post_after, $post_before){ if( $post_after->post_title !== $post_before->post_title ) { // do something } } add_action( 'post_updated', 'check_values', 10, 3 ); ?> ```
213,843
<p>I've a dropdown control that lists all pages of the website.</p> <p>When I select a page in the dropdown I would update the preview iframe to that page. </p> <p>There is the following method to change the customizer <code>previewUrl</code></p> <p><code>wp.customize.previewer.previewUrl( url )</code></p> <p>But I can't realize how and where exactly I should do this. The dropdown control has transport set to <code>refresh</code> and the preview will refresh automatically everytime the control value changes.</p> <p>Maybe a solution could be to change the <code>previewUrl</code> before the customizer automatically refresh the preview.</p> <p>Do you have any suggestions to do this? Thanks in advance.</p>
[ { "answer_id": 213827, "author": "JoeMoe1984", "author_id": 32601, "author_profile": "https://wordpress.stackexchange.com/users/32601", "pm_score": 4, "selected": true, "text": "<p>First off you are using the function wrong. The function is tied to an action within wordpress whenever you use the <code>add_action</code> function. In this case you have added it to the <code>post_updated</code> action.</p>\n\n<p>Basically your check_values function gets added to a queue which will then get called by the action when its time to do the action.</p>\n\n<p>You can see where the action gets called here: <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359</a></p>\n\n<p>See line 3359 of this file. There is a function called <code>do_action</code> and its going to call all the functions tied to the post_updated action. This would include your check_values function. This is where your function is getting called and as you can see it passes in the necessary parameters for your function to interact with.</p>\n\n<p>Try updating or adding a post. You should see some output there because this is when wordpress is calling your function.</p>\n\n<p>Then in order to check to see if there was a change compare the two titles from the two before and after post objects</p>\n\n<pre><code>&lt;?php \n\nfunction check_values($post_ID, $post_after, $post_before){\n if( $post_after-&gt;post_title !== $post_before-&gt;post_title ) {\n // do something\n }\n}\n\nadd_action( 'post_updated', 'check_values', 10, 3 );\n?&gt;\n</code></pre>\n" }, { "answer_id": 333218, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When I used this action \"post_updated\" and update the post from latest updated gutenburg editor that time I get same post name in before post and after post details array. </p>\n\n<p>It means suppose post name is \"abc-test\" and I changed this to a new post name as \"abc-test-2\" then I get \"abc-test-2\" name in both post after and before details.</p>\n\n<p>Why its showing same data?</p>\n\n<p>Thanks in advance.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20032/" ]
I've a dropdown control that lists all pages of the website. When I select a page in the dropdown I would update the preview iframe to that page. There is the following method to change the customizer `previewUrl` `wp.customize.previewer.previewUrl( url )` But I can't realize how and where exactly I should do this. The dropdown control has transport set to `refresh` and the preview will refresh automatically everytime the control value changes. Maybe a solution could be to change the `previewUrl` before the customizer automatically refresh the preview. Do you have any suggestions to do this? Thanks in advance.
First off you are using the function wrong. The function is tied to an action within wordpress whenever you use the `add_action` function. In this case you have added it to the `post_updated` action. Basically your check\_values function gets added to a queue which will then get called by the action when its time to do the action. You can see where the action gets called here: <https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359> See line 3359 of this file. There is a function called `do_action` and its going to call all the functions tied to the post\_updated action. This would include your check\_values function. This is where your function is getting called and as you can see it passes in the necessary parameters for your function to interact with. Try updating or adding a post. You should see some output there because this is when wordpress is calling your function. Then in order to check to see if there was a change compare the two titles from the two before and after post objects ``` <?php function check_values($post_ID, $post_after, $post_before){ if( $post_after->post_title !== $post_before->post_title ) { // do something } } add_action( 'post_updated', 'check_values', 10, 3 ); ?> ```
213,857
<p>I'd like to wrap my post thumbnail with <code>&lt;figure&gt;</code> tags. </p> <p>I have tried the following and the image appears, but the <code>&lt;figure&gt;</code> tags come up empty.</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) { echo '&lt;figure&gt;'.the_post_thumbnail('gallery').'&lt;/figure&gt;'; } ?&gt; </code></pre> <p>I've also tried the following, but the image is missing and only the empty <code>&lt;figure&gt;</code> tags appear.</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) { echo '&lt;figure&gt;'.get_the_post_thumbnail('gallery').'&lt;/figure&gt;'; } ?&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>For anyone wanting the full code from the answer, here it is: </p> <pre><code>&lt;?php if ( has_post_thumbnail() ) { echo '&lt;figure&gt;'.get_the_post_thumbnail( $page-&gt;ID, 'gallery').'&lt;/figure&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 213858, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\">get_the_post_thumbnail( $id, $size )</a>\nif you're going to echo the result. </p>\n\n<p>And make sure you have post thumbs enabled. </p>\n\n<pre><code>add_theme_support( 'post-thumbnails' );\n</code></pre>\n" }, { "answer_id": 214267, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 0, "selected": false, "text": "<p>The feature became available with Version 2.9. Note that you can optionally pass a second argument with an array of the Post Types for which you want to enable this feature. </p>\n\n<pre><code>add_theme_support( 'post-thumbnails' );\nadd_theme_support( 'post-thumbnails', array( 'post' ) ); // Posts only\nadd_theme_support( 'post-thumbnails', array( 'page' ) ); // Pages only\nadd_theme_support( 'post-thumbnails', array( 'post', 'movie' ) ); // Posts and Movies\n</code></pre>\n\n<p>This feature must be called before the init hook is fired. That means it needs to be placed directly into <em>functions.php</em> or within a function attached to the '<code>after_setup_theme</code>' hook. </p>\n\n<p><strong>NOTE</strong>: For custom post types, you can also add post thumbnails using the <code>register_post_type</code> function as well.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213857", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37548/" ]
I'd like to wrap my post thumbnail with `<figure>` tags. I have tried the following and the image appears, but the `<figure>` tags come up empty. ``` <?php if ( has_post_thumbnail() ) { echo '<figure>'.the_post_thumbnail('gallery').'</figure>'; } ?> ``` I've also tried the following, but the image is missing and only the empty `<figure>` tags appear. ``` <?php if ( has_post_thumbnail() ) { echo '<figure>'.get_the_post_thumbnail('gallery').'</figure>'; } ?> ``` **UPDATE** For anyone wanting the full code from the answer, here it is: ``` <?php if ( has_post_thumbnail() ) { echo '<figure>'.get_the_post_thumbnail( $page->ID, 'gallery').'</figure>'; } ?> ```
Use [get\_the\_post\_thumbnail( $id, $size )](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) if you're going to echo the result. And make sure you have post thumbs enabled. ``` add_theme_support( 'post-thumbnails' ); ```
213,861
<p>I developed the theme. Redux Framework configuration file located in the theme directory. Himself ReduX Framework I installed from the repository Wordpress using the TGM. But when I install a theme, then this message appears</p> <blockquote> <p>Redux Framework has an embedded demo. Click here to activate the sample config file.</p> </blockquote> <p>and I need to click on the link for load my options!</p> <p>How can I make so that my settings are automatically loaded?</p> <p>functions.php in my theme</p> <pre><code>/** * Redux */ if ( class_exists( 'ReduxFramework' ) ) { require_once( dirname( __FILE__ ) . '/inc/options-init.php' ); } </code></pre>
[ { "answer_id": 214019, "author": "EndyVelvet", "author_id": 60574, "author_profile": "https://wordpress.stackexchange.com/users/60574", "pm_score": 2, "selected": true, "text": "<p>Problem solved! Helped official support. It was necessary to add the following code.</p>\n\n<pre><code>add_action( 'redux/loaded', 'remove_demo' );\n/**\n * Removes the demo link and the notice of integrated demo from the redux-framework plugin\n */\nif ( ! function_exists( 'remove_demo' ) ) {\n function remove_demo() {\n // Used to hide the demo mode link from the plugin page. Only used when Redux is a plugin.\n if ( class_exists( 'ReduxFrameworkPlugin' ) ) {\n remove_filter( 'plugin_row_meta', array(\n ReduxFrameworkPlugin::instance(),\n 'plugin_metalinks'\n ), null, 2 );\n\n // Used to hide the activation notice informing users of the demo panel. Only used when Redux is a plugin.\n remove_action( 'admin_notices', array( ReduxFrameworkPlugin::instance(), 'admin_notices' ) );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 239271, "author": "SirBennyLavaThe3rd", "author_id": 102814, "author_profile": "https://wordpress.stackexchange.com/users/102814", "pm_score": 0, "selected": false, "text": "<p>I want to add something to this answer. This won't work if you use TGMPA. But if you want to suppress the this message:</p>\n\n<blockquote>\n <p>Redux Framework has an embedded demo. Click here to activate the sample config file.</p>\n</blockquote>\n\n<p>You can add the following to your <strong>functions.php</strong> file.</p>\n\n<pre><code>add_action('admin_init', 'override_redux_message', 30);\n\nfunction override_redux_message() {\n update_option( 'ReduxFrameworkPlugin_ACTIVATED_NOTICES', []);\n}\n</code></pre>\n\n<p>This will prevent the message from showing.\nHope it helps.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60574/" ]
I developed the theme. Redux Framework configuration file located in the theme directory. Himself ReduX Framework I installed from the repository Wordpress using the TGM. But when I install a theme, then this message appears > > Redux Framework has an embedded demo. Click here to activate the > sample config file. > > > and I need to click on the link for load my options! How can I make so that my settings are automatically loaded? functions.php in my theme ``` /** * Redux */ if ( class_exists( 'ReduxFramework' ) ) { require_once( dirname( __FILE__ ) . '/inc/options-init.php' ); } ```
Problem solved! Helped official support. It was necessary to add the following code. ``` add_action( 'redux/loaded', 'remove_demo' ); /** * Removes the demo link and the notice of integrated demo from the redux-framework plugin */ if ( ! function_exists( 'remove_demo' ) ) { function remove_demo() { // Used to hide the demo mode link from the plugin page. Only used when Redux is a plugin. if ( class_exists( 'ReduxFrameworkPlugin' ) ) { remove_filter( 'plugin_row_meta', array( ReduxFrameworkPlugin::instance(), 'plugin_metalinks' ), null, 2 ); // Used to hide the activation notice informing users of the demo panel. Only used when Redux is a plugin. remove_action( 'admin_notices', array( ReduxFrameworkPlugin::instance(), 'admin_notices' ) ); } } } ```
213,866
<p>I'm coding a theme where I want to display information in the footer that's only available on a template page. I have been using <code>get_page_by_title()</code> which works well if you know what the page will be called, but in my opinion it's not very dynamic, it's impossible to predict what a user will name a page in your theme.</p> <p>In my research I found a function called <code>get_all_page_ids()</code> which returns a numerically indexed array of ids from the site. This function would be a lot cooler if it was an associative (or even a post object), but I digress.</p> <p>I have considered using something like this:</p> <pre><code>$all_page_ids = get_all_page_ids(); foreach ($all_page_ids as $id) { // get_post() {@link https://developer.wordpress.org/reference/functions/get_post/} $post_object = get_post($id); // preg_match() {@link http://php.net/manual/en/function.preg-match.php} if(preg_match("/\b(contact)\b/i", $post_object-&gt;post_title)) { // do something here } else { // for readability continue; } } </code></pre> <p>However, this still creates the problem of having to know that the user chose to have the word contact in their title. What if they created a page called "Get in Touch" that is their contact page? This would break.</p> <p>So, in short, my question revolves around best practice for theme designers. Is <code>get_page_by_title()</code> the <em>best</em> way to get another page's ID, or is there a way to combine a few functions/variables to get another page's ID without knowing the title?</p> <p>Or are there WordPress functions that do this kind of heavy lifting or is <code>get_page_by_title()</code> the only close one? My suspicion is there's a hackier, but better way to do this, I just don't have any ideas. Thanks for any help you're able to give on this.</p>
[ { "answer_id": 213867, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>If you don't force a title, and obviously do not know the id, the only way you can do it is by letting the user select which page to use, usually done in the theme's options page, but can be done in the costumizer, or even as part of page editing</p>\n" }, { "answer_id": 213878, "author": "Laxmana", "author_id": 40948, "author_profile": "https://wordpress.stackexchange.com/users/40948", "pm_score": 2, "selected": false, "text": "<p>If your page is a template page then you can use <code>is_page_template($template_name)</code> </p>\n\n<p>Otherwise as Mark mentioned you have to create a theme option and let the user decide. </p>\n\n<p>More: <a href=\"https://codex.wordpress.org/Function_Reference/is_page_template\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/is_page_template</a></p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I misread your question. You can get all pages using a certain template name but again a user could made more than one such pages with the same template so you are not sure which one to choose.</p>\n\n<pre><code> $args = array(\n 'meta_key' =&gt; '_wp_page_template',\n 'meta_value' =&gt; 'page-about.php',\n 'post_type' =&gt; 'page'\n );\n $posts_array = get_posts( $args );\n</code></pre>\n\n<p>Another idea is to create yourself your page with code at the activation of the theme/plugin and then save the id as an option but also provide a theme option to the user to change the page if he/she wants. That's how WooCommerce works with the Shop Page.</p>\n\n<p>Again I believe Mark's approach is better and safer.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213866", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76066/" ]
I'm coding a theme where I want to display information in the footer that's only available on a template page. I have been using `get_page_by_title()` which works well if you know what the page will be called, but in my opinion it's not very dynamic, it's impossible to predict what a user will name a page in your theme. In my research I found a function called `get_all_page_ids()` which returns a numerically indexed array of ids from the site. This function would be a lot cooler if it was an associative (or even a post object), but I digress. I have considered using something like this: ``` $all_page_ids = get_all_page_ids(); foreach ($all_page_ids as $id) { // get_post() {@link https://developer.wordpress.org/reference/functions/get_post/} $post_object = get_post($id); // preg_match() {@link http://php.net/manual/en/function.preg-match.php} if(preg_match("/\b(contact)\b/i", $post_object->post_title)) { // do something here } else { // for readability continue; } } ``` However, this still creates the problem of having to know that the user chose to have the word contact in their title. What if they created a page called "Get in Touch" that is their contact page? This would break. So, in short, my question revolves around best practice for theme designers. Is `get_page_by_title()` the *best* way to get another page's ID, or is there a way to combine a few functions/variables to get another page's ID without knowing the title? Or are there WordPress functions that do this kind of heavy lifting or is `get_page_by_title()` the only close one? My suspicion is there's a hackier, but better way to do this, I just don't have any ideas. Thanks for any help you're able to give on this.
If you don't force a title, and obviously do not know the id, the only way you can do it is by letting the user select which page to use, usually done in the theme's options page, but can be done in the costumizer, or even as part of page editing
213,894
<p>I am having some issue removing the width and height from my attachment images when using wp_get_attachment_image. This is what I am using to display the image </p> <pre><code> &lt;?php echo $image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full'); ?&gt; </code></pre> <p>How it looks the the source code</p> <pre><code> &lt;img width="150" height="108" src="http://website:8888/wp-content/uploads/2015/12/cupcakes-and-cosmetics-logo.png" class="attachment-1 size-1" alt="cupcakes-and-cosmetics-logo" /&gt; </code></pre> <p>I would like it to display like this</p> <pre><code> &lt;img src="http://website:8888/wp-content/uploads/2015/12/cupcakes-and-cosmetics-logo.png" class="attachment-1 size-1" alt="cupcakes-and-cosmetics-logo" /&gt; </code></pre> <p>The image is getting pulled from an repeatable file field with an entry with an id of slide_image_id. I am have been looking around and have notice to use wp_get_attachment_image_url but when I use it with my above code the image does not display. Is there something I am doing wrong?</p> <pre><code> &lt;?php echo $image = wp_get_attachment_image_url( $entry['slide_image_id'], true, 'full'); ?&gt; </code></pre> <p>Side note: $entry['slide_image_id'] is what is being used to call my repeatable file field. </p>
[ { "answer_id": 213897, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p>Your arguments for both <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/\"><code>wp_get_attachment_image_url()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image\"><code>wp_get_attachment_image()</code></a> are in the wrong order - check the linked documentation for details. Additionally, <code>wp_get_attachment_image_url()</code> returns a URL - not an actual image element.</p>\n\n<blockquote>\n <p>Removing the <code>width</code> and <code>height</code> attributes from <code>&lt;img&gt;</code> elements is\n inadvisable: if the layout of the page is in any way influenced by the\n size of the image, the layout will \"glitch\" as soon as the CSS which\n specifies the image's dimensions, or the image itself loads.</p>\n</blockquote>\n\n<p>Unfortunately, the <code>wp_get_attachment_image()</code> function is currently (as of WordPress 4.4.1) hard-coded to output the <code>width</code> and <code>height</code> <code>&lt;img&gt;</code> attributes (see <a href=\"https://core.trac.wordpress.org/ticket/14110\">ticket #14110</a>), so you'll need to build the image markup yourself. This can be done by taking cues from <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800\"><code>wp_get_attachment_image()</code>'s source</a>:</p>\n\n<pre><code>&lt;?php\n $attachment = get_post( $entry['slide_image_id'] );\n\n if( $attachment ) {\n $img_size_class = 'full';\n $img_atts = array(\n 'src' =&gt; wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ),\n 'class' =&gt; 'attachment-' . $img_size_class . ' size-' . $img_size_class,\n 'alt' =&gt; trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) )\n );\n\n //If an 'alt' attribute was not specified, try to create one from attachment post data\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_excerpt ));\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_title ));\n\n $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class );\n\n echo( '&lt;img ' );\n foreach( $img_atts as $name =&gt; $value ) {\n echo( $name . '=\"' . $value . '\" ';\n }\n echo( '/&gt;' );\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 213906, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<h2>Workaround</h2>\n\n<p>I did some core digging/testing and found a workaround through the <code>wp_constrain_dimensions</code> filter:</p>\n\n<pre><code>// Add filter to empty the height/width array\nadd_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n// Display image html\necho wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n// Remove filter again\nremove_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n</code></pre>\n\n<p>This seems to allow us to remove the <em>height</em> and <em>width</em> attributes from the generated image html of <code>wp_get_attachment_image()</code>, without getting out the reg-ex canons. We could also use the <code>wp_get_attachment_image_src</code> filter in a similar way to remove the <em>width</em>/<em>height</em> but keep the <em>url</em>. </p>\n\n<h2>Notes</h2>\n\n<p>This workaround will remove the <code>srcset</code> and <code>sizes</code> attributes as well. But it's also possible to set the <em>srcset</em> and <em>sizes</em> attributes through the fourth <code>$attr</code> input argument.</p>\n\n<p>As mentioned by @bosco, you've switched the <em>icon</em> and <em>size</em> input arguments in:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], true, 'full' );\n</code></pre>\n\n<p>Use this instead:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n</code></pre>\n" }, { "answer_id": 318736, "author": "JMRC", "author_id": 153770, "author_profile": "https://wordpress.stackexchange.com/users/153770", "pm_score": 1, "selected": false, "text": "<p>I simply used CSS for this one. It doesn't work in all scenario's, but often enough it will. Let's take a 300px x 300px image:</p>\n\n<pre><code>max-height: 300px;\nmax-width: 300px;\nwidth: auto;\n</code></pre>\n\n<p>This constrains the dimensions of the image without losing its width to height ratio. Otherwise you can also use REGEX:</p>\n\n<pre><code>$html = preg_replace(array('/width=\"[^\"]*\"/', '/height=\"[^\"]*\"/'), '', $html);\n</code></pre>\n\n<p>These were some alternatives. Good luck.</p>\n" }, { "answer_id": 366425, "author": "Jahmic", "author_id": 35802, "author_profile": "https://wordpress.stackexchange.com/users/35802", "pm_score": 1, "selected": false, "text": "<p><strong>Regex approach</strong></p>\n\n<p>After retrieving the raw image output that will include the width and height attributes, simply remove them with a regex replace of an empty string:</p>\n\n<pre><code>&lt;?php\n$raw_image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full');\n$final_image = preg_replace('/(height|width)=\"\\d*\"\\s/', \"\", $raw_image);\necho $final_image;\n?&gt;\n</code></pre>\n\n<p>In the future, it would be great if WordPress supplied a filter to get suppress these attributes.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54798/" ]
I am having some issue removing the width and height from my attachment images when using wp\_get\_attachment\_image. This is what I am using to display the image ``` <?php echo $image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full'); ?> ``` How it looks the the source code ``` <img width="150" height="108" src="http://website:8888/wp-content/uploads/2015/12/cupcakes-and-cosmetics-logo.png" class="attachment-1 size-1" alt="cupcakes-and-cosmetics-logo" /> ``` I would like it to display like this ``` <img src="http://website:8888/wp-content/uploads/2015/12/cupcakes-and-cosmetics-logo.png" class="attachment-1 size-1" alt="cupcakes-and-cosmetics-logo" /> ``` The image is getting pulled from an repeatable file field with an entry with an id of slide\_image\_id. I am have been looking around and have notice to use wp\_get\_attachment\_image\_url but when I use it with my above code the image does not display. Is there something I am doing wrong? ``` <?php echo $image = wp_get_attachment_image_url( $entry['slide_image_id'], true, 'full'); ?> ``` Side note: $entry['slide\_image\_id'] is what is being used to call my repeatable file field.
Your arguments for both [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) and [`wp_get_attachment_image()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image) are in the wrong order - check the linked documentation for details. Additionally, `wp_get_attachment_image_url()` returns a URL - not an actual image element. > > Removing the `width` and `height` attributes from `<img>` elements is > inadvisable: if the layout of the page is in any way influenced by the > size of the image, the layout will "glitch" as soon as the CSS which > specifies the image's dimensions, or the image itself loads. > > > Unfortunately, the `wp_get_attachment_image()` function is currently (as of WordPress 4.4.1) hard-coded to output the `width` and `height` `<img>` attributes (see [ticket #14110](https://core.trac.wordpress.org/ticket/14110)), so you'll need to build the image markup yourself. This can be done by taking cues from [`wp_get_attachment_image()`'s source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800): ``` <?php $attachment = get_post( $entry['slide_image_id'] ); if( $attachment ) { $img_size_class = 'full'; $img_atts = array( 'src' => wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ), 'class' => 'attachment-' . $img_size_class . ' size-' . $img_size_class, 'alt' => trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) ) ); //If an 'alt' attribute was not specified, try to create one from attachment post data if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_excerpt )); if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_title )); $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class ); echo( '<img ' ); foreach( $img_atts as $name => $value ) { echo( $name . '="' . $value . '" '; } echo( '/>' ); } ?> ```
213,896
<p>i understand with the wp rest API i will be able to build Wordpress themes with other languages but will i be able to do the same in customizer api or would i need to use php to give customization options to users?</p>
[ { "answer_id": 213897, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p>Your arguments for both <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/\"><code>wp_get_attachment_image_url()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image\"><code>wp_get_attachment_image()</code></a> are in the wrong order - check the linked documentation for details. Additionally, <code>wp_get_attachment_image_url()</code> returns a URL - not an actual image element.</p>\n\n<blockquote>\n <p>Removing the <code>width</code> and <code>height</code> attributes from <code>&lt;img&gt;</code> elements is\n inadvisable: if the layout of the page is in any way influenced by the\n size of the image, the layout will \"glitch\" as soon as the CSS which\n specifies the image's dimensions, or the image itself loads.</p>\n</blockquote>\n\n<p>Unfortunately, the <code>wp_get_attachment_image()</code> function is currently (as of WordPress 4.4.1) hard-coded to output the <code>width</code> and <code>height</code> <code>&lt;img&gt;</code> attributes (see <a href=\"https://core.trac.wordpress.org/ticket/14110\">ticket #14110</a>), so you'll need to build the image markup yourself. This can be done by taking cues from <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800\"><code>wp_get_attachment_image()</code>'s source</a>:</p>\n\n<pre><code>&lt;?php\n $attachment = get_post( $entry['slide_image_id'] );\n\n if( $attachment ) {\n $img_size_class = 'full';\n $img_atts = array(\n 'src' =&gt; wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ),\n 'class' =&gt; 'attachment-' . $img_size_class . ' size-' . $img_size_class,\n 'alt' =&gt; trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) )\n );\n\n //If an 'alt' attribute was not specified, try to create one from attachment post data\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_excerpt ));\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_title ));\n\n $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class );\n\n echo( '&lt;img ' );\n foreach( $img_atts as $name =&gt; $value ) {\n echo( $name . '=\"' . $value . '\" ';\n }\n echo( '/&gt;' );\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 213906, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<h2>Workaround</h2>\n\n<p>I did some core digging/testing and found a workaround through the <code>wp_constrain_dimensions</code> filter:</p>\n\n<pre><code>// Add filter to empty the height/width array\nadd_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n// Display image html\necho wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n// Remove filter again\nremove_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n</code></pre>\n\n<p>This seems to allow us to remove the <em>height</em> and <em>width</em> attributes from the generated image html of <code>wp_get_attachment_image()</code>, without getting out the reg-ex canons. We could also use the <code>wp_get_attachment_image_src</code> filter in a similar way to remove the <em>width</em>/<em>height</em> but keep the <em>url</em>. </p>\n\n<h2>Notes</h2>\n\n<p>This workaround will remove the <code>srcset</code> and <code>sizes</code> attributes as well. But it's also possible to set the <em>srcset</em> and <em>sizes</em> attributes through the fourth <code>$attr</code> input argument.</p>\n\n<p>As mentioned by @bosco, you've switched the <em>icon</em> and <em>size</em> input arguments in:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], true, 'full' );\n</code></pre>\n\n<p>Use this instead:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n</code></pre>\n" }, { "answer_id": 318736, "author": "JMRC", "author_id": 153770, "author_profile": "https://wordpress.stackexchange.com/users/153770", "pm_score": 1, "selected": false, "text": "<p>I simply used CSS for this one. It doesn't work in all scenario's, but often enough it will. Let's take a 300px x 300px image:</p>\n\n<pre><code>max-height: 300px;\nmax-width: 300px;\nwidth: auto;\n</code></pre>\n\n<p>This constrains the dimensions of the image without losing its width to height ratio. Otherwise you can also use REGEX:</p>\n\n<pre><code>$html = preg_replace(array('/width=\"[^\"]*\"/', '/height=\"[^\"]*\"/'), '', $html);\n</code></pre>\n\n<p>These were some alternatives. Good luck.</p>\n" }, { "answer_id": 366425, "author": "Jahmic", "author_id": 35802, "author_profile": "https://wordpress.stackexchange.com/users/35802", "pm_score": 1, "selected": false, "text": "<p><strong>Regex approach</strong></p>\n\n<p>After retrieving the raw image output that will include the width and height attributes, simply remove them with a regex replace of an empty string:</p>\n\n<pre><code>&lt;?php\n$raw_image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full');\n$final_image = preg_replace('/(height|width)=\"\\d*\"\\s/', \"\", $raw_image);\necho $final_image;\n?&gt;\n</code></pre>\n\n<p>In the future, it would be great if WordPress supplied a filter to get suppress these attributes.</p>\n" } ]
2016/01/06
[ "https://wordpress.stackexchange.com/questions/213896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86364/" ]
i understand with the wp rest API i will be able to build Wordpress themes with other languages but will i be able to do the same in customizer api or would i need to use php to give customization options to users?
Your arguments for both [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) and [`wp_get_attachment_image()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image) are in the wrong order - check the linked documentation for details. Additionally, `wp_get_attachment_image_url()` returns a URL - not an actual image element. > > Removing the `width` and `height` attributes from `<img>` elements is > inadvisable: if the layout of the page is in any way influenced by the > size of the image, the layout will "glitch" as soon as the CSS which > specifies the image's dimensions, or the image itself loads. > > > Unfortunately, the `wp_get_attachment_image()` function is currently (as of WordPress 4.4.1) hard-coded to output the `width` and `height` `<img>` attributes (see [ticket #14110](https://core.trac.wordpress.org/ticket/14110)), so you'll need to build the image markup yourself. This can be done by taking cues from [`wp_get_attachment_image()`'s source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800): ``` <?php $attachment = get_post( $entry['slide_image_id'] ); if( $attachment ) { $img_size_class = 'full'; $img_atts = array( 'src' => wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ), 'class' => 'attachment-' . $img_size_class . ' size-' . $img_size_class, 'alt' => trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) ) ); //If an 'alt' attribute was not specified, try to create one from attachment post data if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_excerpt )); if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_title )); $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class ); echo( '<img ' ); foreach( $img_atts as $name => $value ) { echo( $name . '="' . $value . '" '; } echo( '/>' ); } ?> ```
213,910
<p>I have posts in two languages, managed by WPML.</p> <p>In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language).</p> <p>Which is the best way to define links text and URL only once, and reuse them in both languages?</p> <p>I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).</p>
[ { "answer_id": 213897, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<p>Your arguments for both <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/\"><code>wp_get_attachment_image_url()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image\"><code>wp_get_attachment_image()</code></a> are in the wrong order - check the linked documentation for details. Additionally, <code>wp_get_attachment_image_url()</code> returns a URL - not an actual image element.</p>\n\n<blockquote>\n <p>Removing the <code>width</code> and <code>height</code> attributes from <code>&lt;img&gt;</code> elements is\n inadvisable: if the layout of the page is in any way influenced by the\n size of the image, the layout will \"glitch\" as soon as the CSS which\n specifies the image's dimensions, or the image itself loads.</p>\n</blockquote>\n\n<p>Unfortunately, the <code>wp_get_attachment_image()</code> function is currently (as of WordPress 4.4.1) hard-coded to output the <code>width</code> and <code>height</code> <code>&lt;img&gt;</code> attributes (see <a href=\"https://core.trac.wordpress.org/ticket/14110\">ticket #14110</a>), so you'll need to build the image markup yourself. This can be done by taking cues from <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800\"><code>wp_get_attachment_image()</code>'s source</a>:</p>\n\n<pre><code>&lt;?php\n $attachment = get_post( $entry['slide_image_id'] );\n\n if( $attachment ) {\n $img_size_class = 'full';\n $img_atts = array(\n 'src' =&gt; wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ),\n 'class' =&gt; 'attachment-' . $img_size_class . ' size-' . $img_size_class,\n 'alt' =&gt; trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) )\n );\n\n //If an 'alt' attribute was not specified, try to create one from attachment post data\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_excerpt ));\n if( empty( $img_atts[ 'alt' ] ) )\n $img_atts[ 'alt' ] = trim(strip_tags( $attachment-&gt;post_title ));\n\n $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class );\n\n echo( '&lt;img ' );\n foreach( $img_atts as $name =&gt; $value ) {\n echo( $name . '=\"' . $value . '\" ';\n }\n echo( '/&gt;' );\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 213906, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<h2>Workaround</h2>\n\n<p>I did some core digging/testing and found a workaround through the <code>wp_constrain_dimensions</code> filter:</p>\n\n<pre><code>// Add filter to empty the height/width array\nadd_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n// Display image html\necho wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n// Remove filter again\nremove_filter( 'wp_constrain_dimensions', '__return_empty_array' );\n</code></pre>\n\n<p>This seems to allow us to remove the <em>height</em> and <em>width</em> attributes from the generated image html of <code>wp_get_attachment_image()</code>, without getting out the reg-ex canons. We could also use the <code>wp_get_attachment_image_src</code> filter in a similar way to remove the <em>width</em>/<em>height</em> but keep the <em>url</em>. </p>\n\n<h2>Notes</h2>\n\n<p>This workaround will remove the <code>srcset</code> and <code>sizes</code> attributes as well. But it's also possible to set the <em>srcset</em> and <em>sizes</em> attributes through the fourth <code>$attr</code> input argument.</p>\n\n<p>As mentioned by @bosco, you've switched the <em>icon</em> and <em>size</em> input arguments in:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], true, 'full' );\n</code></pre>\n\n<p>Use this instead:</p>\n\n<pre><code>echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true );\n</code></pre>\n" }, { "answer_id": 318736, "author": "JMRC", "author_id": 153770, "author_profile": "https://wordpress.stackexchange.com/users/153770", "pm_score": 1, "selected": false, "text": "<p>I simply used CSS for this one. It doesn't work in all scenario's, but often enough it will. Let's take a 300px x 300px image:</p>\n\n<pre><code>max-height: 300px;\nmax-width: 300px;\nwidth: auto;\n</code></pre>\n\n<p>This constrains the dimensions of the image without losing its width to height ratio. Otherwise you can also use REGEX:</p>\n\n<pre><code>$html = preg_replace(array('/width=\"[^\"]*\"/', '/height=\"[^\"]*\"/'), '', $html);\n</code></pre>\n\n<p>These were some alternatives. Good luck.</p>\n" }, { "answer_id": 366425, "author": "Jahmic", "author_id": 35802, "author_profile": "https://wordpress.stackexchange.com/users/35802", "pm_score": 1, "selected": false, "text": "<p><strong>Regex approach</strong></p>\n\n<p>After retrieving the raw image output that will include the width and height attributes, simply remove them with a regex replace of an empty string:</p>\n\n<pre><code>&lt;?php\n$raw_image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full');\n$final_image = preg_replace('/(height|width)=\"\\d*\"\\s/', \"\", $raw_image);\necho $final_image;\n?&gt;\n</code></pre>\n\n<p>In the future, it would be great if WordPress supplied a filter to get suppress these attributes.</p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59235/" ]
I have posts in two languages, managed by WPML. In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language). Which is the best way to define links text and URL only once, and reuse them in both languages? I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).
Your arguments for both [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) and [`wp_get_attachment_image()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image) are in the wrong order - check the linked documentation for details. Additionally, `wp_get_attachment_image_url()` returns a URL - not an actual image element. > > Removing the `width` and `height` attributes from `<img>` elements is > inadvisable: if the layout of the page is in any way influenced by the > size of the image, the layout will "glitch" as soon as the CSS which > specifies the image's dimensions, or the image itself loads. > > > Unfortunately, the `wp_get_attachment_image()` function is currently (as of WordPress 4.4.1) hard-coded to output the `width` and `height` `<img>` attributes (see [ticket #14110](https://core.trac.wordpress.org/ticket/14110)), so you'll need to build the image markup yourself. This can be done by taking cues from [`wp_get_attachment_image()`'s source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800): ``` <?php $attachment = get_post( $entry['slide_image_id'] ); if( $attachment ) { $img_size_class = 'full'; $img_atts = array( 'src' => wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ), 'class' => 'attachment-' . $img_size_class . ' size-' . $img_size_class, 'alt' => trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) ) ); //If an 'alt' attribute was not specified, try to create one from attachment post data if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_excerpt )); if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_title )); $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class ); echo( '<img ' ); foreach( $img_atts as $name => $value ) { echo( $name . '="' . $value . '" '; } echo( '/>' ); } ?> ```
213,920
<p>I am newbee to web development,since last few days i am struggling to login through php code. My PHP code is as follow</p> <pre><code>//my php code @include_once '../wp-includes/user.php'; $creds = array( 'user_login' =&gt; 'abc', 'user_password' =&gt; 'abc', 'rememember' =&gt; false ); $user = wp_signon( $creds, 0 ); if ( is_wp_error($user) ) echo $user-&gt;get_error_message(); </code></pre> <p>when the PHP code is executed on server i get the below error. </p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function do_action_ref_array() in /Users/meenalgupta/Sites/wordpress/mysite/wp-includes/user.php:57 Stack trace: #0 /Users/meenalgupta/Sites/wordPress/mysite/wp-admin/mypage.php(38): wp_signon(Array, 0) #1 {main} thrown in /Users/meenalgupta/Sites/wordpress/mysite/wp-includes/user.php on line 57</p> </blockquote> <p>My wordpress version is 4.4.1.</p> <p>Please let me know what to do?</p>
[ { "answer_id": 213924, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>You probably call <code>wp_signon</code> too early. You first need to let all of the wordpress core to load before calling it</p>\n" }, { "answer_id": 243601, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<p>You should BIND the codes into action (you can use <code>plugins_loaded</code> for earliest stage):</p>\n\n<pre><code>add_action('plugins_loaded', 'my_func');\nfunction my_func(){\n\n // ======== HERE YOUR CODES =========//\n\n}\n</code></pre>\n\n<p>p.s. you have to include the file correctly!</p>\n\n<pre><code>include_once(ABSPATH.'wp-includes/user.php');\n</code></pre>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86390/" ]
I am newbee to web development,since last few days i am struggling to login through php code. My PHP code is as follow ``` //my php code @include_once '../wp-includes/user.php'; $creds = array( 'user_login' => 'abc', 'user_password' => 'abc', 'rememember' => false ); $user = wp_signon( $creds, 0 ); if ( is_wp_error($user) ) echo $user->get_error_message(); ``` when the PHP code is executed on server i get the below error. > > Fatal error: Uncaught Error: Call to undefined function > do\_action\_ref\_array() in > /Users/meenalgupta/Sites/wordpress/mysite/wp-includes/user.php:57 > Stack trace: #0 > /Users/meenalgupta/Sites/wordPress/mysite/wp-admin/mypage.php(38): > wp\_signon(Array, 0) #1 {main} thrown in > /Users/meenalgupta/Sites/wordpress/mysite/wp-includes/user.php on line > 57 > > > My wordpress version is 4.4.1. Please let me know what to do?
You should BIND the codes into action (you can use `plugins_loaded` for earliest stage): ``` add_action('plugins_loaded', 'my_func'); function my_func(){ // ======== HERE YOUR CODES =========// } ``` p.s. you have to include the file correctly! ``` include_once(ABSPATH.'wp-includes/user.php'); ```
213,932
<p>I have a problem with get_pages. It displays the wrong ID for the blog page. I have tried this code.</p> <pre><code>$pages = get_pages(array("echo" =&gt; 0)); foreach($pages as $page){ echo $page-&gt;ID; } </code></pre> <p>But for the blog page it returns the wrong ID. It should be 1 (the blog page is automatically 1 if I understand it correctly) but instead it returns the ID of the actual page. </p> <p>I've also tried the is_page() function, but that doesn't seem to work on objects.</p> <p>Is there any way arround this issue?</p>
[ { "answer_id": 213924, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>You probably call <code>wp_signon</code> too early. You first need to let all of the wordpress core to load before calling it</p>\n" }, { "answer_id": 243601, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<p>You should BIND the codes into action (you can use <code>plugins_loaded</code> for earliest stage):</p>\n\n<pre><code>add_action('plugins_loaded', 'my_func');\nfunction my_func(){\n\n // ======== HERE YOUR CODES =========//\n\n}\n</code></pre>\n\n<p>p.s. you have to include the file correctly!</p>\n\n<pre><code>include_once(ABSPATH.'wp-includes/user.php');\n</code></pre>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83390/" ]
I have a problem with get\_pages. It displays the wrong ID for the blog page. I have tried this code. ``` $pages = get_pages(array("echo" => 0)); foreach($pages as $page){ echo $page->ID; } ``` But for the blog page it returns the wrong ID. It should be 1 (the blog page is automatically 1 if I understand it correctly) but instead it returns the ID of the actual page. I've also tried the is\_page() function, but that doesn't seem to work on objects. Is there any way arround this issue?
You should BIND the codes into action (you can use `plugins_loaded` for earliest stage): ``` add_action('plugins_loaded', 'my_func'); function my_func(){ // ======== HERE YOUR CODES =========// } ``` p.s. you have to include the file correctly! ``` include_once(ABSPATH.'wp-includes/user.php'); ```
213,939
<p>When I open the newly created page in WordPress I get <code>page not found</code> but when I reset the permalinks to none <code>http://localhost/?page_id=6</code> opens normally .</p> <p>Even with this permalink it works : <code>/index.php/%postname%/</code> But when I change it to only <code>/%postname%/</code> I get <code>page not found error</code> .</p> <p>Here is my <code>htaccess</code> file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 214029, "author": "Bharat", "author_id": 83408, "author_profile": "https://wordpress.stackexchange.com/users/83408", "pm_score": 0, "selected": false, "text": "<p>This problem is .htaccess file's. Before doing anything first take backup your files and database.</p>\n\n<p>Then rename the .htaccess file in your root of WordPress installation. and then change the permalink setting you want in WordPress Dashboard. </p>\n\n<p>I hope this will work for you.</p>\n" }, { "answer_id": 214062, "author": "Cheffheid", "author_id": 64470, "author_profile": "https://wordpress.stackexchange.com/users/64470", "pm_score": 3, "selected": true, "text": "<p>Do you have mod_rewrite enabled?</p>\n\n<p>This sort of thing tends to happen when it's not. At which point, you only have access to ugly permalinks (?p=N) or \"almost pretty\" permalinks (/index.php/slug). The latter uses pathinfo to get you the page you're requesting instead.</p>\n\n<p>So I'd suggest double checking whether mod_rewrite is installed and enabled. If it turns out it isn't, enable it and restart Apache.</p>\n\n<p>Here's more on <a href=\"http://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow\">using permalinks from the WP codex</a>.</p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82746/" ]
When I open the newly created page in WordPress I get `page not found` but when I reset the permalinks to none `http://localhost/?page_id=6` opens normally . Even with this permalink it works : `/index.php/%postname%/` But when I change it to only `/%postname%/` I get `page not found error` . Here is my `htaccess` file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
Do you have mod\_rewrite enabled? This sort of thing tends to happen when it's not. At which point, you only have access to ugly permalinks (?p=N) or "almost pretty" permalinks (/index.php/slug). The latter uses pathinfo to get you the page you're requesting instead. So I'd suggest double checking whether mod\_rewrite is installed and enabled. If it turns out it isn't, enable it and restart Apache. Here's more on [using permalinks from the WP codex](http://codex.wordpress.org/Using_Permalinks).
213,972
<p>Im currently using a theme that has template pages, and they notified me that I cannot use any page restriction plugins, as for that would only work on the default template page. Id like to restrict a certain page, for non logged in users, and they said I must try and use the "is user logged in" function on that specific page. Id like to redirect non logged in users to the login page, and once logged in, they will be able to view that pages content...</p> <p>Would something like this work?</p> <p>Any help would be gladly appreciated!</p>
[ { "answer_id": 213984, "author": "Syed Alam Abbas", "author_id": 86425, "author_profile": "https://wordpress.stackexchange.com/users/86425", "pm_score": -1, "selected": false, "text": "<p>You need a plugin that will conditionally show a menu item. There a few out there. <a href=\"https://wordpress.org/plugins/nav-menu-roles/\" rel=\"nofollow\">Here</a> is one of them</p>\n" }, { "answer_id": 213991, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 1, "selected": false, "text": "<p>You can check for if a user is logged in or not by <code>is_user_logged_in()</code> if logged in then show the page if not then redirect them. Perfect hook to use for this <code>template_redirect</code>.</p>\n\n<p>Example</p>\n\n<pre><code>function check_and_redirect(){\n\n if( is_page( 45 ) &amp;&amp; !is_user_logged_in() ) {\n wp_redirect( wp_login_url() );\n exit();\n }\n\n}\nadd_action('template_redirect', 'check_and_redirect');\n</code></pre>\n\n<p><code>is_page()</code> is used to check for specific pages, you can use page title, slug.</p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86412/" ]
Im currently using a theme that has template pages, and they notified me that I cannot use any page restriction plugins, as for that would only work on the default template page. Id like to restrict a certain page, for non logged in users, and they said I must try and use the "is user logged in" function on that specific page. Id like to redirect non logged in users to the login page, and once logged in, they will be able to view that pages content... Would something like this work? Any help would be gladly appreciated!
You can check for if a user is logged in or not by `is_user_logged_in()` if logged in then show the page if not then redirect them. Perfect hook to use for this `template_redirect`. Example ``` function check_and_redirect(){ if( is_page( 45 ) && !is_user_logged_in() ) { wp_redirect( wp_login_url() ); exit(); } } add_action('template_redirect', 'check_and_redirect'); ``` `is_page()` is used to check for specific pages, you can use page title, slug.
213,977
<p>I'm trying to create a metabox in a custom post type. When I attempt to insert information into the Listing Price box and update the post, the information is not saved and disappears once the page reloads. Please take a look at my code below and let me know if you see anything that could be causing this issue. Thanks!</p> <p>EDIT: I figured it out. I'm still not sure why my previous method wouldn't work. I changed the input field value to ID, 'listing_price', true ); ?> and now the box updates!</p> <pre><code>&lt;?php function cns_add_custom_metabox(){ add_meta_box( 'cns_meta', __('ForesTree Listing'), 'cns_meta_callback', 'listing', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'cns_add_custom_metabox' ); function cns_meta_callback( $post ){ wp_nonce_field( basename(__FILE__), 'cns_listing_nonce' ); $cns_stored_meta = get_post_meta( $post-&gt;ID ); ?&gt; &lt;div&gt; &lt;div class="meta-row"&gt; &lt;div class="meta-th"&gt; &lt;label for="listing-price" class="cns-row-title"&gt;Listing Price&lt;/label&gt; &lt;/div&gt; &lt;div class="meta-td"&gt; &lt;input type="number" name="listing_price" id="listing-price" value="&lt;?php if ( ! empty ( $cns_stored_meta['listing_price'] ) ) { echo esc_attr( $cns_store_meta['listing_price'][0] ); } ?&gt;"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="meta-row"&gt; &lt;div class="meta-th"&gt; &lt;span&gt;Listing Description&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="meta-editor"&gt;&lt;/div&gt; &lt;?php $content = get_post_meta( $post-&gt;ID, 'listing_description', true ); $editor_id = 'listing_description'; $settings = array( 'textarea_rows' =&gt; 8, 'media_buttons' =&gt; false ); wp_editor( $content, $editor_id, $settings ); ?&gt; &lt;/div&gt; &lt;?php } function cns_meta_save( $post_id ) { // Checks save status $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = ( isset( $_POST[ 'cns_listing_nonce' ] ) &amp;&amp; wp_verify_nonce( $_POST[ 'cns_listing_nonce' ], basename(__FILE__) ) ) ? 'true' : 'false'; // Exits script depending on save status if( $is_autosave || $is_revision || !$is_valid_nonce ){ return; } if( isset( $_POST['listing_price'] ) ) { update_post_meta( $post_id, 'listing_price', sanitize_text_field( $_POST[ 'listing_price' ] ) ); } } add_action( 'save_post', 'cns_meta_save' ); </code></pre>
[ { "answer_id": 213984, "author": "Syed Alam Abbas", "author_id": 86425, "author_profile": "https://wordpress.stackexchange.com/users/86425", "pm_score": -1, "selected": false, "text": "<p>You need a plugin that will conditionally show a menu item. There a few out there. <a href=\"https://wordpress.org/plugins/nav-menu-roles/\" rel=\"nofollow\">Here</a> is one of them</p>\n" }, { "answer_id": 213991, "author": "WPTC-Troop", "author_id": 82793, "author_profile": "https://wordpress.stackexchange.com/users/82793", "pm_score": 1, "selected": false, "text": "<p>You can check for if a user is logged in or not by <code>is_user_logged_in()</code> if logged in then show the page if not then redirect them. Perfect hook to use for this <code>template_redirect</code>.</p>\n\n<p>Example</p>\n\n<pre><code>function check_and_redirect(){\n\n if( is_page( 45 ) &amp;&amp; !is_user_logged_in() ) {\n wp_redirect( wp_login_url() );\n exit();\n }\n\n}\nadd_action('template_redirect', 'check_and_redirect');\n</code></pre>\n\n<p><code>is_page()</code> is used to check for specific pages, you can use page title, slug.</p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38938/" ]
I'm trying to create a metabox in a custom post type. When I attempt to insert information into the Listing Price box and update the post, the information is not saved and disappears once the page reloads. Please take a look at my code below and let me know if you see anything that could be causing this issue. Thanks! EDIT: I figured it out. I'm still not sure why my previous method wouldn't work. I changed the input field value to ID, 'listing\_price', true ); ?> and now the box updates! ``` <?php function cns_add_custom_metabox(){ add_meta_box( 'cns_meta', __('ForesTree Listing'), 'cns_meta_callback', 'listing', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'cns_add_custom_metabox' ); function cns_meta_callback( $post ){ wp_nonce_field( basename(__FILE__), 'cns_listing_nonce' ); $cns_stored_meta = get_post_meta( $post->ID ); ?> <div> <div class="meta-row"> <div class="meta-th"> <label for="listing-price" class="cns-row-title">Listing Price</label> </div> <div class="meta-td"> <input type="number" name="listing_price" id="listing-price" value="<?php if ( ! empty ( $cns_stored_meta['listing_price'] ) ) { echo esc_attr( $cns_store_meta['listing_price'][0] ); } ?>"/> </div> </div> <div class="meta-row"> <div class="meta-th"> <span>Listing Description</span> </div> </div> <div class="meta-editor"></div> <?php $content = get_post_meta( $post->ID, 'listing_description', true ); $editor_id = 'listing_description'; $settings = array( 'textarea_rows' => 8, 'media_buttons' => false ); wp_editor( $content, $editor_id, $settings ); ?> </div> <?php } function cns_meta_save( $post_id ) { // Checks save status $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = ( isset( $_POST[ 'cns_listing_nonce' ] ) && wp_verify_nonce( $_POST[ 'cns_listing_nonce' ], basename(__FILE__) ) ) ? 'true' : 'false'; // Exits script depending on save status if( $is_autosave || $is_revision || !$is_valid_nonce ){ return; } if( isset( $_POST['listing_price'] ) ) { update_post_meta( $post_id, 'listing_price', sanitize_text_field( $_POST[ 'listing_price' ] ) ); } } add_action( 'save_post', 'cns_meta_save' ); ```
You can check for if a user is logged in or not by `is_user_logged_in()` if logged in then show the page if not then redirect them. Perfect hook to use for this `template_redirect`. Example ``` function check_and_redirect(){ if( is_page( 45 ) && !is_user_logged_in() ) { wp_redirect( wp_login_url() ); exit(); } } add_action('template_redirect', 'check_and_redirect'); ``` `is_page()` is used to check for specific pages, you can use page title, slug.
213,981
<pre><code>get_terms($taxonomy, array('parent' =&gt; $parent)); </code></pre> <p>This works for some parents and returns an empty array for others. I checked if a term with the parent ID exists and if the same ID is in the 'parent' field of the child term's taxonomy. Even copy-pasted directly from the database. Is there anything else? I don't see a difference between the parents that work and the ones that don't.</p> <p>edit: All invisible terms appear the moment I add a new term via the dashboard. Turns out the problem was that there is a function <code>wp_insert_term()</code> for adding terms and I was using <code>$wpdb-&gt;insert</code> and manually inserting the term and the taxonomy, which makes a difference, somehow.</p>
[ { "answer_id": 213993, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>The only variable which can really have an effect on the result as you described, is taxonomy. If you have verified that there are terms with a parent of <code>1</code> and a parent of <code>5</code>, and <code>get_terms()</code> only returns terms for terms with a parent of <code>1</code>, it can only mean that term <code>1</code> and term <code>5</code> belongs to different taxonomies. <code>get_terms()</code> will only return results if the term data passed is associated with the passed taxonomy. </p>\n\n<p>You need to remember, <strong>all</strong> terms, regardless of taxonomy, are stored in the <code>wp_terms</code> table. Relationships are stored in the <code>wp_term_taxonomy</code> table. This is where the term's taxonomy and parent is saved. </p>\n\n<p>Here is a small script which you can run on any page. This will print all the taxonomies and all terms associated with that taxonomy and also print the parent ID if the terms aren't top level terms. You can use this to \"debug\" your issue</p>\n\n<pre><code>$taxonomies = get_taxonomies(); \nif ( $taxonomies ) {\n foreach ( $taxonomies as $taxonomy ) {\n $terms = get_terms( $taxonomy );\n if ( $terms ) {\n echo '&lt;strong&gt;' . strtoupper( $taxonomy ) . '&lt;/strong&gt;&lt;/br&gt;';\n foreach ( $terms as $term ) {\n $parent_id = ( 0 != $term-&gt;parent ) ? ' and has a parent ID of ' . $term-&gt;parent : '';\n echo 'Term '. $term-&gt;name . ' ID ' . $term-&gt;term_id . ' belongs to the taxonomy '. $taxonomy . $parent_id . '&lt;/br&gt;';\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 214047, "author": "Nadroev", "author_id": 71594, "author_profile": "https://wordpress.stackexchange.com/users/71594", "pm_score": 1, "selected": true, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_term\" rel=\"nofollow\"><code>wp_insert_term()</code></a> instead of <code>$wpdb-&gt;insert</code> for adding new terms.</p>\n" } ]
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71594/" ]
``` get_terms($taxonomy, array('parent' => $parent)); ``` This works for some parents and returns an empty array for others. I checked if a term with the parent ID exists and if the same ID is in the 'parent' field of the child term's taxonomy. Even copy-pasted directly from the database. Is there anything else? I don't see a difference between the parents that work and the ones that don't. edit: All invisible terms appear the moment I add a new term via the dashboard. Turns out the problem was that there is a function `wp_insert_term()` for adding terms and I was using `$wpdb->insert` and manually inserting the term and the taxonomy, which makes a difference, somehow.
Use [`wp_insert_term()`](https://codex.wordpress.org/Function_Reference/wp_insert_term) instead of `$wpdb->insert` for adding new terms.